feat(assessment): add the review band of attempt signals and the disclosed collector

This commit is contained in:
shira committed 2026-10-08 23:04:57 +03:00
1 parent 68286af8b7
commit b3c6dc870b
124 files changed
+13522 -633

No files matched your search

+8
View File
@@ -41,6 +41,14 @@ mail-retry-build: ## Build the local mail retry operator command
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/mail-retry ./cmd/mail-retry
.PHONY: assessment-review assessment-review-build
assessment-review: ## Print the audited manual-review band of an attempt (set ARGS)
$(GO) run ./cmd/assessment-review $(ARGS)
assessment-review-build: ## Build the local assessment review operator command
@mkdir -p bin
$(GO) build -buildvcs=false -trimpath -o bin/assessment-review ./cmd/assessment-review
.PHONY: deps install install-tools
deps: ## Download pinned Go module dependencies
$(GO) mod download
+4 -2
View File
@@ -92,9 +92,11 @@ Answer submission evaluates the frozen server key and stores each answer once. N
## Assessment signals
The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` accepts batches of focus-loss durations, clipboard event byte counts, and fullscreen exits. It stores no clipboard or answer content and supports no camera, microphone, screenshot, or screen recording. Events are bound to the owned real attempt and one of its frozen items; training attempts do not accept them. New batches require current C3 and an active attempt.
The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` accepts batches of focus-loss durations, clipboard event byte counts, and fullscreen exits. It stores no clipboard or answer content (`size_bytes` is the UTF-8 byte count of the pasted text plus file sizes, computed on the device, for a paste, and an approximate selection length in UTF-16 code units, with the text unread, for copy and cut) and supports no camera, microphone, screenshot, or screen recording. Events are bound to the owned real attempt and one of its frozen items; training attempts do not accept them. New batches require current C3 and an active attempt.
The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Browser collection and interpretation of these signals are separate work.
The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata: a timestamp outside five minutes before the attempt's creation to five minutes after database time rejects the whole batch with 400, so the client moves its timestamps to server time using the `Date` header; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Interpretation of these signals is separate work.
The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version; a `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user.
## Anonymous profile projection
+4 -2
View File
@@ -92,9 +92,11 @@
## Сигналы прохождения оценки
Доступный только кандидату `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` принимает пакеты длительностей потери фокуса, размеров событий буфера обмена и выходов из полноэкранного режима. Содержимое буфера и ответов не сохраняется; камера, микрофон, скриншоты и запись экрана не поддерживаются. События привязаны к собственной реальной попытке и одному из ее закрепленных вопросов; учебные попытки их не принимают. Новый пакет требует действующего C3 и активной попытки.
Доступный только кандидату `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` принимает пакеты длительностей потери фокуса, размеров событий буфера обмена и выходов из полноэкранного режима. Содержимое буфера и ответов не сохраняется; `size_bytes` для вставки - байты UTF-8 вставленного текста плюс размер файлов, посчитанные на устройстве, а для копирования и вырезания - приблизительная длина выделения в единицах UTF-16 (текст не читается); камера, микрофон, скриншоты и запись экрана не поддерживаются. События привязаны к собственной реальной попытке и одному из ее закрепленных вопросов; учебные попытки их не принимают. Новый пакет требует действующего C3 и активной попытки.
Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Сбор событий браузером и их интерпретация относятся к отдельной работе.
Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными: метка вне окна от создания попытки минус пять минут до времени БД плюс пять минут отклоняет весь пакет с 400, поэтому клиент приводит метки к серверному времени по заголовку `Date`; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Интерпретация сигналов относится к отдельной работе.
Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер; `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем.
## Анонимная проекция профиля
+28
View File
@@ -0,0 +1,28 @@
// Command assessment-review prints the stored manual-review band of one
// assessment attempt for an operator and records the read in an audit table.
// It changes nothing else.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"lincodex/backend/internal/adapter/primary/cli/assessmentreview"
)
func main() {
os.Exit(run())
}
func run() int {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := assessmentreview.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout); err != nil {
_, _ = fmt.Fprintf(os.Stderr, "assessment-review: %v\n", err)
return 2
}
return 0
}
+4 -3
View File
@@ -314,8 +314,9 @@ func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) (
return occupied, err
}
// The isolated browser fixture opts into the extended demo policy explicitly.
// Normal startup still seeds V1, and an operator's policy must never be replaced.
// The isolated browser fixture opts into the extended demo policy explicitly,
// including the manual-review band thresholds. Normal startup still seeds V1,
// and an operator's policy must never be replaced.
func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) {
initial, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
@@ -344,7 +345,7 @@ func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (
}
version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return databaseTime }).Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV2(),
Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV3(),
})
return err
})
@@ -0,0 +1,271 @@
-- +goose Up
-- Server-side signals of a real assessment attempt and the review band built
-- from them. The band is a hint for a manual check by an operator. Nothing here
-- is read by a result, a category, a quota, or any candidate or employer
-- operation, and nothing stores an answer, an address, or a session token:
-- answers become keyed fingerprints, sessions and networks become keyed
-- digests that are bound to one attempt.
-- One row per accepted answer. The fingerprint is an HMAC of the normalized
-- answer under a server secret, scoped to the family version, so answers of
-- different candidates to different seed variants of one family can be compared
-- without the answer text.
CREATE TABLE assessment_answer_observations (
attempt_id uuid NOT NULL,
item_instance_id uuid NOT NULL,
user_id uuid NOT NULL,
family_id uuid NOT NULL REFERENCES assessment_families (id),
variant_seed bigint NOT NULL,
answer_format text NOT NULL,
answer_fingerprint bytea NOT NULL,
-- Key generation of the fingerprint. Only fingerprints of one generation
-- are compared, so a future key rotation is an explicit step.
key_version smallint NOT NULL,
-- Server time from the previous answer or session start to this answer.
elapsed_ms integer NOT NULL,
-- True when the time starts at the previous answer, which is when the item
-- was shown. The first item of a work session starts at the session start
-- and is not used for the speed signals.
measured_from_answer boolean NOT NULL,
observed_at timestamptz NOT NULL,
CONSTRAINT assessment_answer_observations_pkey PRIMARY KEY (attempt_id, item_instance_id),
CONSTRAINT assessment_answer_observations_item_fk FOREIGN KEY (attempt_id, item_instance_id)
REFERENCES assessment_attempt_items (attempt_id, id) ON DELETE CASCADE,
CONSTRAINT assessment_answer_observations_owner_fk FOREIGN KEY (attempt_id, user_id)
REFERENCES assessment_attempts (id, user_id) ON DELETE CASCADE,
CONSTRAINT assessment_answer_observations_format CHECK (answer_format IN ('integer', 'integer_sequence')),
CONSTRAINT assessment_answer_observations_fingerprint CHECK (octet_length(answer_fingerprint) = 32),
CONSTRAINT assessment_answer_observations_key_version CHECK (key_version > 0),
CONSTRAINT assessment_answer_observations_elapsed CHECK (elapsed_ms >= 0)
);
-- Serves the comparison with other candidates' answers of the same family.
CREATE INDEX assessment_answer_observations_match_idx
ON assessment_answer_observations (family_id, key_version, answer_fingerprint);
-- Maintained counters of the observations: how many answers hold each
-- fingerprint of a family version, and how many answers the family version has,
-- both per key generation. The share of a value is read from them instead of
-- being counted over the population at every comparison. They are derived
-- caches without foreign keys and are only increased: an answer removed with an
-- account stays counted, which keeps the population estimate and avoids lock
-- contention on the deletion path.
CREATE TABLE assessment_answer_fingerprint_holders (
family_id uuid NOT NULL,
key_version smallint NOT NULL,
answer_fingerprint bytea NOT NULL,
holders integer NOT NULL,
CONSTRAINT assessment_answer_fingerprint_holders_pkey PRIMARY KEY (family_id, key_version, answer_fingerprint),
CONSTRAINT assessment_answer_fingerprint_holders_fingerprint CHECK (octet_length(answer_fingerprint) = 32),
CONSTRAINT assessment_answer_fingerprint_holders_count CHECK (holders > 0)
);
CREATE TABLE assessment_answer_family_totals (
family_id uuid NOT NULL,
key_version smallint NOT NULL,
answer_count integer NOT NULL,
CONSTRAINT assessment_answer_family_totals_pkey PRIMARY KEY (family_id, key_version),
CONSTRAINT assessment_answer_family_totals_count CHECK (answer_count > 0)
);
-- The counters change in the transaction of the insert. A transaction touches
-- one holders row and one totals row, always in this order, so two answers
-- cannot deadlock on them.
-- +goose StatementBegin
CREATE FUNCTION assessment_answer_observation_count() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO assessment_answer_fingerprint_holders (family_id, key_version, answer_fingerprint, holders)
VALUES (NEW.family_id, NEW.key_version, NEW.answer_fingerprint, 1)
ON CONFLICT (family_id, key_version, answer_fingerprint)
DO UPDATE SET holders = assessment_answer_fingerprint_holders.holders + 1;
INSERT INTO assessment_answer_family_totals (family_id, key_version, answer_count)
VALUES (NEW.family_id, NEW.key_version, 1)
ON CONFLICT (family_id, key_version)
DO UPDATE SET answer_count = assessment_answer_family_totals.answer_count + 1;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_answer_observation_count
AFTER INSERT ON assessment_answer_observations
FOR EACH ROW EXECUTE FUNCTION assessment_answer_observation_count();
-- Written when the session or the network of an attempt changes between two
-- accepted answers or signal batches: which session and which network sent
-- the request, as digests.
CREATE TABLE assessment_attempt_origin_marks (
id uuid NOT NULL,
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
source text NOT NULL,
observed_at timestamptz NOT NULL,
session_digest bytea NOT NULL,
network_digest bytea,
key_version smallint NOT NULL,
CONSTRAINT assessment_attempt_origin_marks_pkey PRIMARY KEY (id),
CONSTRAINT assessment_attempt_origin_marks_key_version CHECK (key_version > 0),
CONSTRAINT assessment_attempt_origin_marks_source CHECK (source IN ('answer', 'signals')),
CONSTRAINT assessment_attempt_origin_marks_session CHECK (octet_length(session_digest) = 32),
CONSTRAINT assessment_attempt_origin_marks_network CHECK (
network_digest IS NULL OR octet_length(network_digest) = 32
)
);
CREATE INDEX assessment_attempt_origin_marks_attempt_idx
ON assessment_attempt_origin_marks (attempt_id, observed_at, id);
-- Observations and marks are facts: only the attempt cascade may remove them.
-- +goose StatementBegin
CREATE FUNCTION assessment_signal_fact_immutable() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN
RETURN OLD;
END IF;
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_signal_fact_immutable',
MESSAGE = 'assessment signal facts are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_answer_observations_immutable
BEFORE UPDATE OR DELETE ON assessment_answer_observations
FOR EACH ROW EXECUTE FUNCTION assessment_signal_fact_immutable();
CREATE TRIGGER assessment_attempt_origin_marks_immutable
BEFORE UPDATE OR DELETE ON assessment_attempt_origin_marks
FOR EACH ROW EXECUTE FUNCTION assessment_signal_fact_immutable();
-- The review of an attempt. It is recomputed in place when a later attempt
-- matches an answer, but it stays pinned to the product policy version of the
-- attempt that produced it.
CREATE TABLE assessment_attempt_reviews (
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
policy_version_id uuid NOT NULL REFERENCES policy_versions (id),
band text NOT NULL,
reasons text[] NOT NULL,
answered_items integer NOT NULL,
fast_answers integer NOT NULL,
deviating_answers integer NOT NULL,
parallel_alternations integer NOT NULL,
extra_networks integer NOT NULL,
matched_integer_items integer NOT NULL,
matched_sequence_items integer NOT NULL,
duplicate_evidence_bits integer NOT NULL,
client_focus_loss_ms bigint NOT NULL,
client_clipboard_events integer NOT NULL,
client_fullscreen_exits integer NOT NULL,
evaluated_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT assessment_attempt_reviews_pkey PRIMARY KEY (attempt_id),
CONSTRAINT assessment_attempt_reviews_band CHECK (band IN ('normal', 'attention', 'review')),
CONSTRAINT assessment_attempt_reviews_reasons CHECK (
reasons <@ ARRAY['fast_answers', 'deviating_answers', 'parallel_sessions', 'extra_networks',
'duplicate_answers', 'client_signals']::text[]
),
CONSTRAINT assessment_attempt_reviews_counts CHECK (
answered_items >= 0 AND fast_answers >= 0 AND deviating_answers >= 0 AND parallel_alternations >= 0
AND extra_networks >= 0 AND matched_integer_items >= 0 AND matched_sequence_items >= 0
AND duplicate_evidence_bits >= 0 AND client_focus_loss_ms >= 0 AND client_clipboard_events >= 0
AND client_fullscreen_exits >= 0
),
CONSTRAINT assessment_attempt_reviews_update_order CHECK (updated_at >= evaluated_at)
);
-- +goose StatementBegin
CREATE FUNCTION assessment_attempt_review_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
IF pg_trigger_depth() > 1 THEN
RETURN OLD;
END IF;
ELSIF NEW.attempt_id = OLD.attempt_id AND NEW.policy_version_id = OLD.policy_version_id
AND NEW.evaluated_at = OLD.evaluated_at THEN
RETURN NEW;
END IF;
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_reviews_pinned',
MESSAGE = 'assessment attempt review keeps its attempt, policy version, and first evaluation';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_attempt_review_guard
BEFORE UPDATE OR DELETE ON assessment_attempt_reviews
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_review_guard();
-- Every operator read of a review is recorded, whether or not a review exists.
-- The attempt is not a foreign key, so the record outlives an account deletion.
CREATE TABLE assessment_review_reads (
id uuid NOT NULL,
attempt_id uuid NOT NULL,
actor text NOT NULL,
found boolean NOT NULL,
read_at timestamptz NOT NULL,
CONSTRAINT assessment_review_reads_pkey PRIMARY KEY (id),
CONSTRAINT assessment_review_reads_actor CHECK (
char_length(actor) <= 128 AND actor ~ '^operator:[a-z0-9][a-z0-9._-]*$'
)
);
CREATE INDEX assessment_review_reads_attempt_idx
ON assessment_review_reads (attempt_id, read_at);
-- +goose StatementBegin
CREATE FUNCTION assessment_review_reads_immutable() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_review_reads_immutable',
MESSAGE = 'assessment review read records are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_review_reads_immutable
BEFORE UPDATE OR DELETE ON assessment_review_reads
FOR EACH ROW EXECUTE FUNCTION assessment_review_reads_immutable();
CREATE TRIGGER assessment_review_reads_no_truncate
BEFORE TRUNCATE ON assessment_review_reads
FOR EACH STATEMENT EXECUTE FUNCTION assessment_review_reads_immutable();
-- +goose Down
-- The audit of operator reads is durable evidence. Rolling the schema back must
-- not remove it as a side effect: an operator exports or resolves it first.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM assessment_review_reads) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'assessment_review_reads_retained',
TABLE = 'assessment_review_reads',
MESSAGE = 'assessment review read audit must be retained before rollback';
END IF;
END;
$$;
-- +goose StatementEnd
DROP TRIGGER assessment_review_reads_no_truncate ON assessment_review_reads;
DROP TRIGGER assessment_review_reads_immutable ON assessment_review_reads;
DROP FUNCTION assessment_review_reads_immutable();
DROP INDEX assessment_review_reads_attempt_idx;
DROP TABLE assessment_review_reads;
DROP TRIGGER assessment_attempt_review_guard ON assessment_attempt_reviews;
DROP FUNCTION assessment_attempt_review_guard();
DROP TABLE assessment_attempt_reviews;
DROP TRIGGER assessment_answer_observation_count ON assessment_answer_observations;
DROP FUNCTION assessment_answer_observation_count();
DROP TABLE assessment_answer_family_totals;
DROP TABLE assessment_answer_fingerprint_holders;
DROP TRIGGER assessment_attempt_origin_marks_immutable ON assessment_attempt_origin_marks;
DROP TRIGGER assessment_answer_observations_immutable ON assessment_answer_observations;
DROP FUNCTION assessment_signal_fact_immutable();
DROP INDEX assessment_attempt_origin_marks_attempt_idx;
DROP TABLE assessment_attempt_origin_marks;
DROP INDEX assessment_answer_observations_match_idx;
DROP TABLE assessment_answer_observations;
@@ -0,0 +1,15 @@
-- +goose Up
-- A record that a candidate was shown the notice about the collected
-- assessment signals. It is not a consent: no operation reads it to allow or
-- refuse signal storage. One row per account and notice version keeps the time
-- of the first acknowledgement; a changed notice text uses a new version.
CREATE TABLE assessment_signal_notice_acknowledgements (
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
notice_version integer NOT NULL,
acknowledged_at timestamptz NOT NULL,
CONSTRAINT assessment_signal_notice_acknowledgements_pkey PRIMARY KEY (user_id, notice_version),
CONSTRAINT assessment_signal_notice_acknowledgements_version CHECK (notice_version >= 1)
);
-- +goose Down
DROP TABLE assessment_signal_notice_acknowledgements;
@@ -0,0 +1,15 @@
-- The caller has already checked that the user is a candidate. A missing row
-- means the notice version was not acknowledged.
-- name: GetAssessmentSignalNoticeAcknowledgement :one
SELECT acknowledged_at
FROM assessment_signal_notice_acknowledgements
WHERE
user_id = sqlc.arg(user_id)
AND notice_version = sqlc.arg(notice_version);
-- The first acknowledgement wins; a repeat keeps the stored time and inserts
-- nothing. The caller reads the stored row afterwards in the same transaction.
-- name: InsertAssessmentSignalNoticeAcknowledgement :exec
INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at)
VALUES (sqlc.arg(user_id), sqlc.arg(notice_version), sqlc.arg(acknowledged_at))
ON CONFLICT (user_id, notice_version) DO NOTHING;
@@ -0,0 +1,247 @@
-- name: InsertAssessmentAnswerObservation :exec
INSERT INTO assessment_answer_observations (
attempt_id,
item_instance_id,
user_id,
family_id,
variant_seed,
answer_format,
answer_fingerprint,
key_version,
elapsed_ms,
measured_from_answer,
observed_at
) VALUES (
sqlc.arg(attempt_id),
sqlc.arg(item_instance_id),
sqlc.arg(user_id),
sqlc.arg(family_id),
sqlc.arg(variant_seed),
sqlc.arg(answer_format),
sqlc.arg(answer_fingerprint),
sqlc.arg(key_version),
sqlc.arg(elapsed_ms),
sqlc.arg(measured_from_answer),
sqlc.arg(observed_at)
);
-- name: InsertAssessmentOriginMark :exec
INSERT INTO assessment_attempt_origin_marks (
id,
attempt_id,
source,
observed_at,
session_digest,
network_digest,
key_version
) VALUES (
sqlc.arg(id),
sqlc.arg(attempt_id),
sqlc.arg(source),
sqlc.arg(observed_at),
sqlc.arg(session_digest),
sqlc.narg(network_digest),
sqlc.arg(key_version)
);
-- An attempt holds at most 220 items, so the list is bounded by the attempt.
-- name: ListAssessmentAnswerTimes :many
SELECT answer_format, elapsed_ms, measured_from_answer
FROM assessment_answer_observations
WHERE attempt_id = sqlc.arg(attempt_id)
ORDER BY observed_at, item_instance_id
LIMIT 220;
-- Marks exist only where the session or the network changed. The bound keeps a
-- request that flaps between networks from growing the list without limit.
-- name: ListAssessmentOriginMarks :many
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version
FROM assessment_attempt_origin_marks
WHERE attempt_id = sqlc.arg(attempt_id)
ORDER BY observed_at, id
LIMIT 5000;
-- The caller holds the attempt row lock, so the last mark is stable.
-- name: GetLastAssessmentOriginMark :one
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version
FROM assessment_attempt_origin_marks
WHERE attempt_id = sqlc.arg(attempt_id)
ORDER BY observed_at DESC, id DESC
LIMIT 1;
-- Compares this attempt with every other attempt separately. A matched answer
-- is an equal fingerprint of the same family version under the same key
-- generation, given by another candidate to a different seed variant. It
-- carries -log2 of the share of answers that hold that fingerprint, read from
-- the maintained counters, between
-- zero and the cap of its format, and the bits of one pair add up. Pairs under
-- min_bits are dropped, the strongest come first, and the list is bounded.
-- An attempt has ended when its state is terminal or its deadline has passed.
-- name: ListAssessmentDuplicatePairs :many
WITH mine AS (
SELECT
own.family_id,
own.key_version,
own.answer_fingerprint,
own.answer_format,
own.variant_seed,
own.user_id
FROM assessment_answer_observations AS own
WHERE own.attempt_id = sqlc.arg(attempt_id)
),
pair_items AS (
SELECT
other.attempt_id AS other_attempt_id,
mine.answer_format,
least(
CASE
WHEN mine.answer_format = 'integer' THEN sqlc.arg(integer_cap_bits)::float8
ELSE sqlc.arg(sequence_cap_bits)::float8
END,
greatest(0::float8, -ln(holders.holders::float8 / totals.answer_count::float8) / ln(2::float8))
) AS bits
FROM mine
INNER JOIN assessment_answer_observations AS other
ON mine.family_id = other.family_id
AND mine.key_version = other.key_version
AND mine.answer_fingerprint = other.answer_fingerprint
AND mine.user_id <> other.user_id
AND mine.variant_seed <> other.variant_seed
INNER JOIN assessment_answer_fingerprint_holders AS holders
ON mine.family_id = holders.family_id
AND mine.key_version = holders.key_version
AND mine.answer_fingerprint = holders.answer_fingerprint
INNER JOIN assessment_answer_family_totals AS totals
ON mine.family_id = totals.family_id
AND mine.key_version = totals.key_version
)
SELECT
pair_items.other_attempt_id,
other_attempt.product_policy_version_id,
floor(sum(pair_items.bits))::integer AS evidence_bits,
(count(*) FILTER (WHERE pair_items.answer_format = 'integer'))::integer AS integer_items,
(count(*) FILTER (WHERE pair_items.answer_format = 'integer_sequence'))::integer AS sequence_items
FROM pair_items
INNER JOIN assessment_attempts AS other_attempt ON pair_items.other_attempt_id = other_attempt.id
WHERE
NOT sqlc.arg(ended_only)::boolean
OR other_attempt.state IN ('completed', 'expired', 'insufficient_bank')
OR other_attempt.expires_at <= sqlc.arg(now)::timestamptz
GROUP BY pair_items.other_attempt_id, other_attempt.product_policy_version_id
HAVING floor(sum(pair_items.bits)) >= sqlc.arg(min_bits)::float8
ORDER BY evidence_bits DESC, pair_items.other_attempt_id
LIMIT sqlc.arg(row_limit);
-- The attempt a review job works on: real attempts only.
-- name: GetAssessmentReviewSubject :one
SELECT product_policy_version_id
FROM assessment_attempts
WHERE id = sqlc.arg(attempt_id) AND kind IN ('root', 'corrective');
-- name: GetAssessmentClientSignalTotals :one
SELECT
COALESCE(sum(duration_ms) FILTER (WHERE kind = 'focus_loss'), 0)::bigint AS focus_loss_ms,
(count(*) FILTER (WHERE kind IN ('copy', 'paste', 'cut')))::integer AS clipboard_events,
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits
FROM assessment_signal_events
WHERE attempt_id = sqlc.arg(attempt_id);
-- The times come from the database clock, never from a caller, and the update
-- time cannot fall behind the stored times, so two jobs writing one review in
-- either order keep the order check. The first evaluation time and the policy
-- version stay; the guard trigger refuses a change of either.
-- name: UpsertAssessmentAttemptReview :exec
INSERT INTO assessment_attempt_reviews (
attempt_id,
policy_version_id,
band,
reasons,
answered_items,
fast_answers,
deviating_answers,
parallel_alternations,
extra_networks,
matched_integer_items,
matched_sequence_items,
duplicate_evidence_bits,
client_focus_loss_ms,
client_clipboard_events,
client_fullscreen_exits,
evaluated_at,
updated_at
) VALUES (
sqlc.arg(attempt_id),
sqlc.arg(policy_version_id),
sqlc.arg(band),
sqlc.arg(reasons)::text[],
sqlc.arg(answered_items),
sqlc.arg(fast_answers),
sqlc.arg(deviating_answers),
sqlc.arg(parallel_alternations),
sqlc.arg(extra_networks),
sqlc.arg(matched_integer_items),
sqlc.arg(matched_sequence_items),
sqlc.arg(duplicate_evidence_bits),
sqlc.arg(client_focus_loss_ms),
sqlc.arg(client_clipboard_events),
sqlc.arg(client_fullscreen_exits),
clock_timestamp(),
clock_timestamp()
)
ON CONFLICT (attempt_id) DO UPDATE SET
policy_version_id = EXCLUDED.policy_version_id,
band = EXCLUDED.band,
reasons = EXCLUDED.reasons,
answered_items = EXCLUDED.answered_items,
fast_answers = EXCLUDED.fast_answers,
deviating_answers = EXCLUDED.deviating_answers,
parallel_alternations = EXCLUDED.parallel_alternations,
extra_networks = EXCLUDED.extra_networks,
matched_integer_items = EXCLUDED.matched_integer_items,
matched_sequence_items = EXCLUDED.matched_sequence_items,
duplicate_evidence_bits = EXCLUDED.duplicate_evidence_bits,
client_focus_loss_ms = EXCLUDED.client_focus_loss_ms,
client_clipboard_events = EXCLUDED.client_clipboard_events,
client_fullscreen_exits = EXCLUDED.client_fullscreen_exits,
updated_at = greatest(
clock_timestamp(), assessment_attempt_reviews.evaluated_at, assessment_attempt_reviews.updated_at
);
-- Serializes the evaluations of one review. A job takes these locks for every
-- attempt it will write, in ascending attempt order, before it reads any fact,
-- so what it reads is what the previous writer committed.
-- name: LockAssessmentReview :exec
SELECT pg_advisory_xact_lock(hashtextextended(
'lincodex.assessment.signal_review:' || sqlc.arg(attempt_id)::text,
0
));
-- name: GetAssessmentAttemptReview :one
SELECT
review.attempt_id,
review.policy_version_id,
policy.version AS policy_version,
review.band,
review.reasons,
review.answered_items,
review.fast_answers,
review.deviating_answers,
review.parallel_alternations,
review.extra_networks,
review.matched_integer_items,
review.matched_sequence_items,
review.duplicate_evidence_bits,
review.client_focus_loss_ms,
review.client_clipboard_events,
review.client_fullscreen_exits,
review.evaluated_at,
review.updated_at
FROM assessment_attempt_reviews AS review
JOIN policy_versions AS policy ON policy.id = review.policy_version_id
WHERE review.attempt_id = sqlc.arg(attempt_id);
-- name: InsertAssessmentReviewRead :exec
INSERT INTO assessment_review_reads (id, attempt_id, actor, found, read_at)
VALUES (sqlc.arg(id), sqlc.arg(attempt_id), sqlc.arg(actor), sqlc.arg(found), sqlc.arg(read_at));
@@ -525,12 +525,18 @@ func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *tes
if err != nil {
t.Fatalf("NewAttemptService() error = %v", err)
}
signalObserver, err := assessment.NewSignalObserver(keyring)
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
attemptService.WithSignalObserver(signalObserver)
attemptHandler := v1.NewAssessmentHandler(attemptService)
signalService, err := assessment.NewSignalService(transactor, keyring, clock.Now)
if err != nil {
t.Fatalf("NewSignalService() error = %v", err)
}
signalHandler := v1.NewAssessmentSignalHandler(signalService)
signalService.WithSignalObserver(signalObserver)
signalHandler := v1.NewAssessmentSignalHandler(signalService).WithNotice(signalService)
logs := &strings.Builder{}
logger := slog.New(slog.NewJSONHandler(logs, nil))
responder := problem.NewResponder(logger)
@@ -550,6 +556,13 @@ func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *tes
}
func seedAssessmentAttemptHTTPBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool) {
t.Helper()
seedAssessmentAttemptHTTPBankWithSignals(ctx, t, pool, nil)
}
// seedAssessmentAttemptHTTPBankWithSignals seeds the attempt fixture bank under
// a product policy that carries the given signal thresholds, or none.
func seedAssessmentAttemptHTTPBankWithSignals(ctx context.Context, t *testing.T, pool *pgxpool.Pool, signals *domain.AssessmentSignalPolicy) {
t.Helper()
transactor := postgresadapter.NewTransactor(pool)
bank := assessment.NewBank(transactor)
@@ -566,6 +579,7 @@ func seedAssessmentAttemptHTTPBank(ctx context.Context, t *testing.T, pool *pgxp
productPolicy.Assessment.Training = demoAttemptPolicy.Training
productPolicy.Assessment.Attempt.MaxSessions = 1
productPolicy.Assessment.Attempt.IdleTimeoutSeconds = 60
productPolicy.Assessment.Signals = signals
policyVersion, err := publisher.Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated,
Author: policyTestAuthor, Policy: productPolicy,
@@ -122,7 +122,7 @@ func TestAssessmentBank(t *testing.T) {
"edit the version": `UPDATE assessment_families SET version = version + 10`,
"edit the hash scheme": `UPDATE assessment_families SET hash_scheme = 2`,
"delete": `DELETE FROM assessment_families`,
"truncate": `TRUNCATE assessment_families, assessment_training_bank_binding_families, assessment_attempt_items, assessment_signal_events`,
"truncate": `TRUNCATE assessment_families, assessment_training_bank_binding_families, assessment_attempt_items, assessment_signal_events, assessment_answer_observations`,
} {
_, err := fixture.pool.Exec(ctx, statement)
assertPgError(t, name, err, assessmentIntegritySQLState, "assessment_families_immutable")
@@ -0,0 +1,117 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
)
const assessmentSignalNoticePath = "/api/v1/me/assessment-signal-notice"
type signalNoticeProjection struct {
NoticeVersion int `json:"notice_version"`
Acknowledged bool `json:"acknowledged"`
AcknowledgedAt *string `json:"acknowledged_at"`
}
func decodeSignalNotice(t *testing.T, response *httptest.ResponseRecorder) signalNoticeProjection {
t.Helper()
if response.Code != http.StatusOK {
t.Fatalf("signal notice response = %d %s, want 200", response.Code, response.Body.String())
}
if response.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("signal notice Cache-Control = %q, want no-store", response.Header().Get("Cache-Control"))
}
var notice signalNoticeProjection
if err := json.Unmarshal(response.Body.Bytes(), &notice); err != nil {
t.Fatalf("decode signal notice: %v", err)
}
return notice
}
func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
t.Cleanup(harness.pool.Close)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "notice-owner@example.test", passwordHash, true)
other := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "notice-other@example.test", passwordHash, true)
employer := createAssessmentAvailabilityEmployer(ctx, t, harness.sessionHTTPHarness, "notice-employer@example.test", passwordHash)
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.231:1234")
otherCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, other.Email.Address(), "192.0.2.232:1234")
employerCookie, employerCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.233:1234")
request := func(method, body, origin, sessionCookie, token string) *httptest.ResponseRecorder {
return assessmentAttemptHTTPRequest(t, harness, method, assessmentSignalNoticePath, body, origin, sessionCookie, token, "", "192.0.2.234:1234")
}
anonymous := request(http.MethodGet, "", "", "", "")
requireSessionProblem(t, anonymous, http.StatusUnauthorized, "unauthenticated")
before := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, ""))
if before.NoticeVersion != 1 || before.Acknowledged || before.AcknowledgedAt != nil {
t.Fatalf("notice before acknowledgement = %+v", before)
}
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, ""),
http.StatusForbidden, "csrf_check_failed")
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, "https://evil.example", cookie.Value, csrf),
http.StatusForbidden, "csrf_check_failed")
if rejected := request(http.MethodPut, `{"notice_version":0}`, sessionHTTPTestOrigin, cookie.Value, csrf); rejected.Code != http.StatusBadRequest {
t.Fatalf("version 0 = %d %s, want 400", rejected.Code, rejected.Body.String())
}
if rejected := request(http.MethodPut, `{"notice_version":1,"accepted":true}`, sessionHTTPTestOrigin, cookie.Value, csrf); rejected.Code != http.StatusBadRequest {
t.Fatalf("unknown field = %d %s, want 400", rejected.Code, rejected.Body.String())
}
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf),
http.StatusConflict, "state_conflict")
if untouched := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")); untouched.Acknowledged {
t.Fatalf("a refused request stored an acknowledgement: %+v", untouched)
}
first := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf))
if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != 1 {
t.Fatalf("first acknowledgement = %+v", first)
}
time.Sleep(5 * time.Millisecond)
repeat := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf))
if repeat.AcknowledgedAt == nil || *repeat.AcknowledgedAt != *first.AcknowledgedAt {
t.Fatalf("a repeat changed the first acknowledgement time: first %+v, repeat %+v", first, repeat)
}
read := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, ""))
if !read.Acknowledged || read.AcknowledgedAt == nil || *read.AcknowledgedAt != *first.AcknowledgedAt {
t.Fatalf("read after acknowledgement = %+v, want %+v", read, first)
}
var rows int
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_notice_acknowledgements WHERE user_id = $1", candidate.ID).Scan(&rows); err != nil || rows != 1 {
t.Fatalf("stored acknowledgement rows = %d, error %v, want exactly one", rows, err)
}
if foreign := decodeSignalNotice(t, request(http.MethodGet, "", "", otherCookie.Value, "")); foreign.Acknowledged {
t.Fatalf("another account inherited the acknowledgement: %+v", foreign)
}
requireSessionProblem(t, request(http.MethodGet, "", "", employerCookie.Value, ""), http.StatusForbidden, "forbidden")
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, employerCookie.Value, employerCSRF),
http.StatusForbidden, "forbidden")
// The acknowledgement is a record, not a consent: it creates no ledger row.
var consentRows int
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1 AND purpose = 'c3'", candidate.ID).Scan(&consentRows); err != nil || consentRows != 0 {
t.Fatalf("C3 rows after acknowledgement = %d, error %v, want none", consentRows, err)
}
}
@@ -0,0 +1,770 @@
//go:build integration
package integration_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"math/rand/v2"
"net/http"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/cli/assessmentreview"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/policy"
"lincodex/backend/internal/worker/jobrunner"
)
const (
reviewDuplicateIntegerAnswer = 123456
reviewAddressOne = "192.0.2.77"
reviewAddressTwo = "198.51.100.88"
reviewAddressThree = "203.0.113.99"
)
// reviewTestSignalPolicy returns thresholds that make the band deterministic
// for requests that arrive within milliseconds: the median deviation is off
// (it needs more answers than an attempt has), the review level is out of reach
// for the server signals that every fast test run produces, and the duplicate
// levels are low enough for a copied pair to reach them in a population of a
// handful of attempts, where a matched answer carries only a bit or two.
func reviewTestSignalPolicy() domain.AssessmentSignalPolicy {
signals := domain.DemoAssessmentSignalPolicy()
signals.FastAnswersAttention, signals.FastAnswersReview = 3, 1000
signals.DeviationMinAnswers = 220
signals.DeviatingAnswersAttention, signals.DeviatingAnswersReview = 1000, 1000
signals.ParallelAlternationsAttention, signals.ParallelAlternationsReview = 2, 1000
signals.ExtraNetworksAttention, signals.ExtraNetworksReview = 2, 1000
signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 4, 6
return signals
}
// reviewUnreachableSignalPolicy is a later policy version under which the same
// behavior stays normal.
func reviewUnreachableSignalPolicy() domain.AssessmentSignalPolicy {
signals := reviewTestSignalPolicy()
signals.FastAnswersAttention, signals.FastAnswersReview = 1000, 1000
signals.ParallelAlternationsAttention, signals.ParallelAlternationsReview = 1000, 1000
signals.ExtraNetworksAttention, signals.ExtraNetworksReview = 1000, 1000
signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 4096, 4096
signals.ClientFocusLossAttentionMS = 24 * 60 * 60 * 1000
signals.ClientClipboardEventsAttention, signals.ClientFullscreenExitsAttention = 1000, 1000
return signals
}
type reviewCandidate struct {
user domain.User
cookies [2]*http.Cookie
csrf [2]string
}
// newReviewCandidate creates a verified candidate with a questionnaire and the
// C3 consent and logs in once per requested session.
func newReviewCandidate(ctx context.Context, t *testing.T, harness *assessmentAttemptHTTPHarness, email, addressBase string, sessions int) reviewCandidate {
t.Helper()
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
user := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, true)
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", user.ID); err != nil {
t.Fatalf("set candidate onboarding step: %v", err)
}
candidate := reviewCandidate{user: user}
for session := range sessions {
candidate.cookies[session], candidate.csrf[session] = loginConsentHTTP(t, harness.sessionHTTPHarness, email, fmt.Sprintf("%s.%d:1234", addressBase, 10+session))
}
if response := assessmentAttemptQuestionnaireRequest(t, harness, candidate.cookies[0].Value, candidate.csrf[0], addressBase+".20:1234"); response.Code != http.StatusOK {
t.Fatalf("save questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness, candidate.cookies[0], candidate.csrf[0], addressBase+".21:1234")
return candidate
}
func (candidate reviewCandidate) createAttempt(t *testing.T, harness *assessmentAttemptHTTPHarness, key, remoteAddr string) assessmentAnswerHTTPAttempt {
t.Helper()
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr)
var attempt assessmentAnswerHTTPAttempt
if response.Code != http.StatusCreated || json.Unmarshal(response.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil {
t.Fatalf("create real attempt = %d %s", response.Code, response.Body.String())
}
return attempt
}
// answerAll submits every item of the attempt in order. Request i is sent by
// session i modulo the number of sessions and from the matching address.
func (candidate reviewCandidate) answerAll(
ctx context.Context,
t *testing.T,
harness *assessmentAttemptHTTPHarness,
attempt assessmentAnswerHTTPAttempt,
sessions int,
addresses []string,
answerFor func(item assessmentAnswerHTTPItem) json.RawMessage,
keyPrefix string,
) assessmentAnswerHTTPAttempt {
t.Helper()
return candidate.answerFirst(ctx, t, harness, attempt, 0, sessions, addresses, answerFor, keyPrefix)
}
// answerFirst answers the first count items, or all of them when count is zero.
func (candidate reviewCandidate) answerFirst(
ctx context.Context,
t *testing.T,
harness *assessmentAttemptHTTPHarness,
attempt assessmentAnswerHTTPAttempt,
count, sessions int,
addresses []string,
answerFor func(item assessmentAnswerHTTPItem) json.RawMessage,
keyPrefix string,
) assessmentAnswerHTTPAttempt {
t.Helper()
items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID)
if count > 0 {
items = items[:count]
}
version := attempt.Version
last := attempt
for index, item := range items {
body, err := json.Marshal(struct {
ExpectedVersion int64 `json:"expected_version"`
ItemID uuid.UUID `json:"item_id"`
Answer json.RawMessage `json:"answer"`
}{ExpectedVersion: version, ItemID: item.ID, Answer: answerFor(item)})
if err != nil {
t.Fatalf("marshal answer: %v", err)
}
session := index % sessions
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body), sessionHTTPTestOrigin,
candidate.cookies[session].Value, candidate.csrf[session], fmt.Sprintf("%s-%d", keyPrefix, item.Ordinal),
addresses[index%len(addresses)]+":4321")
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &last) != nil {
t.Fatalf("answer item %d = %d %s", item.Ordinal, response.Code, response.Body.String())
}
version = last.Version
}
return last
}
func (candidate reviewCandidate) finalize(t *testing.T, harness *assessmentAttemptHTTPHarness, attempt assessmentAnswerHTTPAttempt, key, remoteAddr string) {
t.Helper()
body, err := json.Marshal(map[string]int64{"expected_version": attempt.Version})
if err != nil {
t.Fatalf("marshal finalization: %v", err)
}
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", string(body), sessionHTTPTestOrigin,
candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr)
if response.Code != http.StatusOK {
t.Fatalf("finalize attempt = %d %s", response.Code, response.Body.String())
}
}
func answerFromBody(t *testing.T, version int64, item assessmentAnswerHTTPItem, correct bool) json.RawMessage {
t.Helper()
var envelope struct {
Answer json.RawMessage `json:"answer"`
}
if err := json.Unmarshal(assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct), &envelope); err != nil {
t.Fatalf("decode fixture answer: %v", err)
}
return envelope.Answer
}
func correctReviewAnswer(t *testing.T) func(assessmentAnswerHTTPItem) json.RawMessage {
return func(item assessmentAnswerHTTPItem) json.RawMessage { return answerFromBody(t, 1, item, true) }
}
// copiedReviewAnswer gives every candidate the same wrong answer for the same
// family, whatever the seed: a constant number, and for an order the reverse of
// the identity order.
func copiedReviewAnswer(t *testing.T) func(assessmentAnswerHTTPItem) json.RawMessage {
return func(item assessmentAnswerHTTPItem) json.RawMessage {
if item.Variant.AnswerFormat == domain.AnswerFormatInteger {
return json.RawMessage(fmt.Sprintf(`{"format":"number","number":%d}`, reviewDuplicateIntegerAnswer))
}
tasks := item.Variant.Parameters["tasks"]
elements := make([]string, 0, tasks)
for task := tasks; task >= 1; task-- {
elements = append(elements, fmt.Sprintf("job_%d", task))
}
answer, err := json.Marshal(map[string]any{"format": "order", "element_ids": elements})
if err != nil {
t.Fatalf("marshal copied order answer: %v", err)
}
return answer
}
}
// reviewJobWorker builds a scheduled job worker for the review kind. now is the
// clock of the worker: a clock far ahead also runs the jobs due at the
// deadlines of the attempts.
func reviewJobWorker(t *testing.T, harness *assessmentAttemptHTTPHarness, now func() time.Time, batch int) *jobrunner.Worker {
t.Helper()
settings := jobTestSettings(time.Second)
settings.BatchSize = batch
worker, err := jobrunner.New([]inbound.JobHandler{assessment.NewSignalReviewJob(nil)},
postgresadapter.NewScheduledJobStore(harness.pool, settings.Lease), prometheus.New(), slog.New(slog.DiscardHandler), settings, now)
if err != nil {
t.Fatalf("jobrunner.New() error = %v", err)
}
return worker
}
// runReviewJobs runs passes until none claims a job and fails on any retry or
// dead job: a review must succeed at once.
func runReviewJobs(ctx context.Context, t *testing.T, worker *jobrunner.Worker) int {
t.Helper()
done := 0
for range 50 {
result, err := worker.RunDue(ctx)
if err != nil {
t.Fatalf("RunDue() error = %v", err)
}
if result.Retried != 0 || result.Dead != 0 || result.LeaseLost != 0 {
t.Fatalf("review job pass = %+v, want only finished jobs", result)
}
if result.Claimed == 0 {
return done
}
done += result.Done
}
t.Fatal("review jobs did not become idle")
return done
}
func reviewNow() time.Time { return time.Now().UTC() }
func reviewFarFuture() time.Time { return time.Now().UTC().Add(200 * time.Hour) }
type storedReview struct {
Band string
Reasons []string
PolicyVersion int32
PolicyID uuid.UUID
Fast int32
Alternations int32
ExtraNetworks int32
MatchedInt int32
Evidence int32
ClipboardN int32
}
func readStoredReview(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness, attemptID uuid.UUID) (storedReview, bool) {
t.Helper()
var review storedReview
rows, err := harness.pool.Query(ctx, `
SELECT r.band, r.reasons, p.version, r.policy_version_id, r.fast_answers, r.parallel_alternations, r.extra_networks,
r.matched_integer_items, r.duplicate_evidence_bits, r.client_clipboard_events
FROM assessment_attempt_reviews r JOIN policy_versions p ON p.id = r.policy_version_id WHERE r.attempt_id = $1`, attemptID)
if err != nil {
t.Fatalf("read stored review: %v", err)
}
defer rows.Close()
if !rows.Next() {
return storedReview{}, false
}
if err := rows.Scan(&review.Band, &review.Reasons, &review.PolicyVersion, &review.PolicyID, &review.Fast, &review.Alternations,
&review.ExtraNetworks, &review.MatchedInt, &review.Evidence, &review.ClipboardN); err != nil {
t.Fatalf("scan stored review: %v", err)
}
return review, true
}
func newReviewHarness(ctx context.Context, t *testing.T, signals domain.AssessmentSignalPolicy) *assessmentAttemptHTTPHarness {
t.Helper()
env := bootstrap(t, postgresService, redisService)
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
t.Cleanup(harness.pool.Close)
seedAssessmentAttemptHTTPBankWithSignals(ctx, t, harness.pool, &signals)
return harness
}
func TestAssessmentSignalReviewOverHTTP(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
defer cancel()
oldSignals := reviewTestSignalPolicy()
harness := newReviewHarness(ctx, t, oldSignals)
fast := newReviewCandidate(ctx, t, harness, "review-fast@example.test", "192.0.2", 2)
control := newReviewCandidate(ctx, t, harness, "review-control@example.test", "192.0.3", 2)
copyOne := newReviewCandidate(ctx, t, harness, "review-copy-one@example.test", "192.0.4", 1)
copyTwo := newReviewCandidate(ctx, t, harness, "review-copy-two@example.test", "192.0.5", 1)
abandoned := newReviewCandidate(ctx, t, harness, "review-abandoned@example.test", "192.0.6", 1)
// Four attempts start under the first policy version.
fastAttempt := fast.createAttempt(t, harness, "review-fast-create", "192.0.2.30:1234")
copyOneAttempt := copyOne.createAttempt(t, harness, "review-copy-one-create", "192.0.4.30:1234")
copyTwoAttempt := copyTwo.createAttempt(t, harness, "review-copy-two-create", "192.0.5.30:1234")
abandonedAttempt := abandoned.createAttempt(t, harness, "review-abandoned-create", "192.0.6.30:1234")
// A new policy version is published while they are in progress; an attempt
// that starts afterwards pins the new version.
newSignals := reviewUnreachableSignalPolicy()
newPolicy := integrationPolicy(11)
newPolicy.Assessment.MaxAttemptsPerWindow = 1
demoAttemptPolicy := domain.DemoProductPolicyV2().Assessment
newPolicy.Assessment.Attempt, newPolicy.Assessment.Training = demoAttemptPolicy.Attempt, demoAttemptPolicy.Training
newPolicy.Assessment.Attempt.MaxSessions, newPolicy.Assessment.Attempt.IdleTimeoutSeconds = 1, 60
newPolicy.Assessment.Signals = &newSignals
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
newVersion, err := publisher.Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: newPolicy,
})
if err != nil {
t.Fatalf("Publish(new signal policy) error = %v", err)
}
// A category opening is bound to one product policy version, so the
// category is opened again under the new version.
openAssessmentAttemptFixtureCategory(ctx, t, assessment.NewBank(postgresadapter.NewTransactor(harness.pool)),
newVersion.ID(), domain.AssessmentCategory("backend"), domain.SpecializationBackend, domain.GradeJunior)
controlAttempt := control.createAttempt(t, harness, "review-control-create", "192.0.3.30:1234")
// Very fast answers, two logged-in sessions that take turns, three networks,
// and client paste events: the attempt gets attention.
addresses := []string{reviewAddressOne, reviewAddressTwo, reviewAddressThree}
fastItems := readAssessmentAnswerHTTPItems(t, ctx, harness, fastAttempt.ID)
for index := range 3 {
response := submitAssessmentSignal(t, harness, fastAttempt.ID, fast.cookies[1], fast.csrf[1], fmt.Sprintf("review-paste-%d", index),
assessmentSignalBody(t, fastItems[0].ID, time.Now().UTC().Truncate(time.Microsecond), "paste", int32Pointer(40)), reviewAddressTwo+":4321")
assertSignalReceipt(t, response, http.StatusOK, "accepted", 1)
}
fastDone := fast.answerAll(ctx, t, harness, fastAttempt, 2, addresses, correctReviewAnswer(t), "review-fast-answer")
fast.finalize(t, harness, fastDone, "review-fast-finalize", "192.0.2.31:1234")
// The same behavior under the later version, from a candidate who started
// after the policy changed.
controlDone := control.answerAll(ctx, t, harness, controlAttempt, 2, addresses, correctReviewAnswer(t), "review-control-answer")
control.finalize(t, harness, controlDone, "review-control-finalize", "192.0.3.31:1234")
// The reviews are computed by scheduled jobs after the attempts ended, not
// in the transactions of the candidates: nothing exists before the worker
// runs, and the results are already readable.
if _, found := readStoredReview(t, ctx, harness, fastAttempt.ID); found {
t.Fatal("a review exists before the review job ran: it was computed in the candidate's transaction")
}
var pendingJobs int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status = 'pending'`).Scan(&pendingJobs); err != nil || pendingJobs < 4 {
t.Fatalf("pending review jobs = %d (error %v), want a deadline job per answered attempt and an ended job per finalized one", pendingJobs, err)
}
immediate := reviewJobWorker(t, harness, reviewNow, 5)
runReviewJobs(ctx, t, immediate)
fastReview, found := readStoredReview(t, ctx, harness, fastAttempt.ID)
if !found || fastReview.Band != "attention" {
t.Fatalf("fast attempt review = %+v (found %v), want band attention", fastReview, found)
}
for _, reason := range []string{"fast_answers", "parallel_sessions", "extra_networks", "client_signals"} {
if !slices.Contains(fastReview.Reasons, reason) {
t.Errorf("fast attempt reasons = %v, want %s", fastReview.Reasons, reason)
}
}
if slices.Contains(fastReview.Reasons, "duplicate_answers") || fastReview.ClipboardN != 3 || fastReview.ExtraNetworks != 2 {
t.Errorf("fast attempt reasons = %v, clipboard events = %d, extra networks = %d; want no duplicate flag, three paste events, and two extra networks",
fastReview.Reasons, fastReview.ClipboardN, fastReview.ExtraNetworks)
}
controlReview, found := readStoredReview(t, ctx, harness, controlAttempt.ID)
if !found || controlReview.Band != "normal" || len(controlReview.Reasons) != 0 {
t.Fatalf("attempt under the later policy version review = %+v (found %v), want band normal", controlReview, found)
}
if fastReview.PolicyVersion == newVersion.Version() || controlReview.PolicyVersion != newVersion.Version() || domain.PolicyVersionID(controlReview.PolicyID) != newVersion.ID() {
t.Fatalf("pinned policy versions = %d (old attempt) and %d (new attempt), want the old and then %d", fastReview.PolicyVersion, controlReview.PolicyVersion, newVersion.Version())
}
if controlReview.Fast == 0 || controlReview.Alternations == 0 || controlReview.ExtraNetworks == 0 {
t.Fatalf("later-version review counted fast=%d alternations=%d extra networks=%d, want the facts kept even when the band is normal", controlReview.Fast, controlReview.Alternations, controlReview.ExtraNetworks)
}
// The band changes neither the result nor the category data: the same
// correct answers give the same result whatever the band.
fastResult := readReviewCandidateResult(t, harness, fast, fastAttempt.ID)
controlResult := readReviewCandidateResult(t, harness, control, controlAttempt.ID)
for _, field := range []string{"outcome", "basic_score", "limitations", "mode"} {
if stringMustJSON(t, fastResult[field]) != stringMustJSON(t, controlResult[field]) {
t.Errorf("result field %s differs between the attention and the normal attempt: %v vs %v", field, fastResult[field], controlResult[field])
}
}
if fastResult["outcome"] != "confirmed" {
t.Fatalf("attention attempt outcome = %v, want confirmed", fastResult["outcome"])
}
var bandColumns int64
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns
WHERE table_schema = 'public' AND table_name LIKE 'assessment\_%' AND table_name <> 'assessment_attempt_reviews'
AND (column_name LIKE '%band%' OR column_name LIKE '%attention%')`).Scan(&bandColumns); err != nil || bandColumns != 0 {
t.Fatalf("assessment tables other than the review table carry %d band columns (error %v), want none", bandColumns, err)
}
// Different seeds, identical answers: the first attempt has no duplicate
// flag until the other candidate has answered; then, when the second one
// ends, both are flagged.
oneItems := readAssessmentAnswerHTTPItems(t, ctx, harness, copyOneAttempt.ID)
twoItems := readAssessmentAnswerHTTPItems(t, ctx, harness, copyTwoAttempt.ID)
sameSeeds := 0
for index := range oneItems {
if oneItems[index].Variant.Seed == twoItems[index].Variant.Seed {
sameSeeds++
}
}
if sameSeeds == len(oneItems) {
t.Fatal("both copy attempts drew the same seeds; the test needs different seed variants")
}
oneDone := copyOne.answerAll(ctx, t, harness, copyOneAttempt, 1, []string{"192.0.4.40"}, copiedReviewAnswer(t), "review-copy-one-answer")
copyOne.finalize(t, harness, oneDone, "review-copy-one-finalize", "192.0.4.41:1234")
runReviewJobs(ctx, t, immediate)
firstAlone, found := readStoredReview(t, ctx, harness, copyOneAttempt.ID)
if !found || slices.Contains(firstAlone.Reasons, "duplicate_answers") {
t.Fatalf("first copied attempt review before the other answered = %+v (found %v), want no duplicate flag yet", firstAlone, found)
}
// A third attempt copies the same answers and is abandoned: it never
// finalizes. While it runs, a match with it does not flag it.
abandonedItems := readAssessmentAnswerHTTPItems(t, ctx, harness, abandonedAttempt.ID)
abandoned.answerFirst(ctx, t, harness, abandonedAttempt, len(abandonedItems)-1, 1, []string{"192.0.6.40"}, copiedReviewAnswer(t), "review-abandoned-answer")
twoDone := copyTwo.answerAll(ctx, t, harness, copyTwoAttempt, 1, []string{"192.0.5.40"}, copiedReviewAnswer(t), "review-copy-two-answer")
copyTwo.finalize(t, harness, twoDone, "review-copy-two-finalize", "192.0.5.41:1234")
runReviewJobs(ctx, t, immediate)
for name, attemptID := range map[string]uuid.UUID{"first": copyOneAttempt.ID, "second": copyTwoAttempt.ID} {
review, found := readStoredReview(t, ctx, harness, attemptID)
if !found || review.Band != "review" || !slices.Contains(review.Reasons, "duplicate_answers") || review.MatchedInt == 0 || review.Evidence < 6 {
t.Errorf("%s copied attempt review = %+v (found %v), want band review with a duplicate flag and at least 6 evidence bits", name, review, found)
}
}
if _, found := readStoredReview(t, ctx, harness, abandonedAttempt.ID); found {
t.Fatal("the running attempt was flagged before it ended; it is flagged by its own job when it ends")
}
// The abandoned attempt ends without being finalized (its state becomes
// terminal) and its job at the deadline reviews it. The clock of the worker
// is moved past the deadline.
terminalizeAttempt(t, ctx, harness.pool, abandonedAttempt.ID)
runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewFarFuture, 5))
abandonedReview, found := readStoredReview(t, ctx, harness, abandonedAttempt.ID)
if !found || abandonedReview.Band != "review" || !slices.Contains(abandonedReview.Reasons, "duplicate_answers") {
t.Fatalf("abandoned attempt review = %+v (found %v), want it flagged when it ended", abandonedReview, found)
}
var unfinished int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status <> 'done'`).Scan(&unfinished); err != nil || unfinished != 0 {
t.Fatalf("unfinished review jobs = %d (error %v), want none", unfinished, err)
}
for name, attemptID := range map[string]uuid.UUID{"fast": fastAttempt.ID, "later-version": controlAttempt.ID} {
// Two honest attempts can coincide on a low-entropy answer by chance;
// the evidence stays below the attention level and raises no flag.
if review, _ := readStoredReview(t, ctx, harness, attemptID); slices.Contains(review.Reasons, "duplicate_answers") || review.Evidence >= oldSignals.DuplicateAttentionBits {
t.Errorf("%s attempt was flagged as a duplicate: %+v", name, review)
}
}
// No candidate read carries the band, its reasons, or the facts behind it.
candidates := map[string]struct {
candidate reviewCandidate
attemptID uuid.UUID
}{
"fast": {fast, fastAttempt.ID}, "later-version": {control, controlAttempt.ID},
"copy-one": {copyOne, copyOneAttempt.ID}, "copy-two": {copyTwo, copyTwoAttempt.ID},
}
for name, entry := range candidates {
for _, path := range []string{
"/api/v1/me/assessment-attempts/" + entry.attemptID.String(),
"/api/v1/me/assessment-attempts/" + entry.attemptID.String() + "/result",
"/api/v1/me/assessment-availability",
} {
response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", entry.candidate.cookies[0].Value, "", "", "203.0.113.200:1234")
if response.Code != http.StatusOK {
t.Fatalf("%s candidate read %s = %d %s", name, path, response.Code, response.Body.String())
}
lowered := strings.ToLower(response.Body.String())
for _, forbidden := range []string{`"band"`, "attention", `"reasons"`, "fingerprint", "parallel_sessions", "fast_answers", "duplicate_answers", "client_signals", "review_band", "extra_networks"} {
if strings.Contains(lowered, forbidden) {
t.Errorf("%s candidate read %s contains %q: %s", name, path, forbidden, response.Body.String())
}
}
}
}
// The operator command is the only reader, and every read is recorded.
operator, err := assessment.NewReviewOperator(postgresadapter.NewTransactor(harness.pool))
if err != nil {
t.Fatalf("NewReviewOperator() error = %v", err)
}
var output bytes.Buffer
command := assessmentreview.Command{AttemptID: domain.AssessmentAttemptID(fastAttempt.ID), Actor: "operator:integration"}
if err := assessmentreview.Execute(ctx, command, operator, &output); err != nil {
t.Fatalf("Execute(fast attempt) error = %v", err)
}
for _, want := range []string{"band: attention", fmt.Sprintf("policy_version: %d", fastReview.PolicyVersion), "fast_answers", "parallel_sessions", "extra_networks: 2"} {
if !strings.Contains(output.String(), want) {
t.Errorf("operator output lacks %q:\n%s", want, output.String())
}
}
missing := assessmentreview.Command{AttemptID: domain.AssessmentAttemptID(uuid.New()), Actor: "operator:integration"}
if err := assessmentreview.Execute(ctx, missing, operator, &output); err == nil {
t.Fatal("Execute(unknown attempt) succeeded")
}
if err := assessmentreview.Execute(ctx, assessmentreview.Command{AttemptID: command.AttemptID, Actor: "alice"}, operator, &output); err == nil {
t.Fatal("Execute(actor without the operator prefix) succeeded")
}
var reads, foundReads, missingReads int64
if err := harness.pool.QueryRow(ctx, `SELECT count(*), count(*) FILTER (WHERE found), count(*) FILTER (WHERE NOT found) FROM assessment_review_reads WHERE actor = 'operator:integration'`).
Scan(&reads, &foundReads, &missingReads); err != nil || reads != 2 || foundReads != 1 || missingReads != 1 {
t.Fatalf("audit records = %d (found %d, missing %d), error %v; want one found read and one miss", reads, foundReads, missingReads, err)
}
// Facts, reviews, and the audit refuse edits, deletes, and truncation.
for _, statement := range []string{
"UPDATE assessment_answer_observations SET elapsed_ms = 0",
"DELETE FROM assessment_attempt_origin_marks",
"UPDATE assessment_attempt_reviews SET policy_version_id = '" + newVersion.ID().String() + "' WHERE attempt_id = '" + fastAttempt.ID.String() + "'",
"DELETE FROM assessment_attempt_reviews",
"UPDATE assessment_review_reads SET actor = 'operator:other'",
"DELETE FROM assessment_review_reads",
"TRUNCATE assessment_review_reads",
} {
if _, err := harness.pool.Exec(ctx, statement); err == nil {
t.Errorf("statement %q succeeded", statement)
}
}
// Origin marks are written when the session or the network changes, not for
// every request: the fast attempt alternates on every answer, the copied
// attempts keep one session and one network.
var oneMarks int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempt_origin_marks WHERE attempt_id = $1`, copyOneAttempt.ID).Scan(&oneMarks); err != nil || oneMarks != 1 {
t.Fatalf("origin marks of an attempt with one session and one network = %d (error %v), want 1", oneMarks, err)
}
// Logs and stored rows carry no answer text, address, or session token.
privateValues := []string{
reviewAddressOne, reviewAddressTwo, reviewAddressThree, "192.0.2.", "192.0.3.", "192.0.4.", "192.0.5.", "192.0.6.",
fmt.Sprint(reviewDuplicateIntegerAnswer), fast.cookies[0].Value, fast.cookies[1].Value, fast.csrf[0],
}
logs := harness.logs.String()
for _, private := range privateValues {
if strings.Contains(logs, private) {
t.Errorf("logs contain %q", private)
}
}
for _, table := range []string{"assessment_answer_observations", "assessment_attempt_origin_marks", "assessment_attempt_reviews", "assessment_review_reads", "scheduled_jobs"} {
var document string
if err := harness.pool.QueryRow(ctx, fmt.Sprintf("SELECT COALESCE(string_agg(row_to_json(t)::text, ' '), '') FROM %s t", table)).Scan(&document); err != nil {
t.Fatalf("read %s as text: %v", table, err)
}
for _, private := range privateValues[:8] {
if strings.Contains(document, private) {
t.Errorf("table %s contains %q", table, private)
}
}
if table != "scheduled_jobs" && strings.Contains(document, fmt.Sprint(reviewDuplicateIntegerAnswer)) {
t.Errorf("table %s contains answer text", table)
}
}
}
// Honest candidates with different seeds, answering correctly or not at random,
// are not flagged as duplicates, while a pair that copies the same answers is.
// A population of a few dozen carries little evidence per matched answer, so
// the thresholds are scaled down for the test; the demo thresholds are
// evaluated against ten thousand rivals by a unit test instead.
func TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag(t *testing.T) {
const honestCandidates = 30
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
defer cancel()
signals := domain.DemoAssessmentSignalPolicy()
signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 32, 44
harness := newReviewHarness(ctx, t, signals)
random := rand.New(rand.NewPCG(7, 11))
honest := make([]assessmentAnswerHTTPAttempt, 0, honestCandidates)
for index := range honestCandidates {
candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-honest-%02d@example.test", index), fmt.Sprintf("10.%d.0", index), 1)
attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-honest-create-%d", index), fmt.Sprintf("10.%d.0.30:1234", index))
done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("10.%d.0.40", index)}, func(item assessmentAnswerHTTPItem) json.RawMessage {
return answerFromBody(t, 1, item, random.IntN(2) == 0)
}, fmt.Sprintf("review-honest-answer-%d", index))
candidate.finalize(t, harness, done, fmt.Sprintf("review-honest-finalize-%d", index), fmt.Sprintf("10.%d.0.41:1234", index))
honest = append(honest, attempt)
}
copies := make([]assessmentAnswerHTTPAttempt, 0, 2)
for index := range 2 {
candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-population-copy-%d@example.test", index), fmt.Sprintf("11.%d.0", index), 1)
attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-population-copy-create-%d", index), fmt.Sprintf("11.%d.0.30:1234", index))
done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("11.%d.0.40", index)}, copiedReviewAnswer(t), fmt.Sprintf("review-population-copy-answer-%d", index))
candidate.finalize(t, harness, done, fmt.Sprintf("review-population-copy-finalize-%d", index), fmt.Sprintf("11.%d.0.41:1234", index))
copies = append(copies, attempt)
}
runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewNow, 10))
strongest := int32(0)
for index, attempt := range honest {
review, found := readStoredReview(t, ctx, harness, attempt.ID)
if !found {
t.Fatalf("honest attempt %d has no review", index)
}
strongest = max(strongest, review.Evidence)
if slices.Contains(review.Reasons, "duplicate_answers") {
t.Errorf("honest attempt %d is flagged as a duplicate: %+v", index, review)
}
}
t.Logf("strongest chance evidence among %d honest attempts: %d bits (attention level %d)", honestCandidates, strongest, signals.DuplicateAttentionBits)
for index, attempt := range copies {
review, found := readStoredReview(t, ctx, harness, attempt.ID)
if !found || !slices.Contains(review.Reasons, "duplicate_answers") || review.Evidence < signals.DuplicateAttentionBits {
t.Errorf("copied attempt %d review = %+v (found %v), want a duplicate flag in a population of %d", index, review, found, honestCandidates)
}
}
}
// Several copied attempts end at the same moment and their jobs run on
// separate workers at once: no job deadlocks or retries, and every attempt is
// flagged.
func TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt(t *testing.T) {
const (
copiers = 4
honest = 8
)
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
defer cancel()
harness := newReviewHarness(ctx, t, reviewTestSignalPolicy())
// Honest attempts give the population its denominator: a value that every
// attempt of a tiny population shares carries no evidence at all.
for index := range honest {
candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-concurrent-honest-%d@example.test", index), fmt.Sprintf("13.%d.0", index), 1)
attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-concurrent-honest-create-%d", index), fmt.Sprintf("13.%d.0.30:1234", index))
done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("13.%d.0.40", index)}, correctReviewAnswer(t), fmt.Sprintf("review-concurrent-honest-answer-%d", index))
candidate.finalize(t, harness, done, fmt.Sprintf("review-concurrent-honest-finalize-%d", index), fmt.Sprintf("13.%d.0.41:1234", index))
}
candidates := make([]reviewCandidate, copiers)
attempts := make([]assessmentAnswerHTTPAttempt, copiers)
done := make([]assessmentAnswerHTTPAttempt, copiers)
for index := range copiers {
candidates[index] = newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-concurrent-%d@example.test", index), fmt.Sprintf("12.%d.0", index), 1)
attempts[index] = candidates[index].createAttempt(t, harness, fmt.Sprintf("review-concurrent-create-%d", index), fmt.Sprintf("12.%d.0.30:1234", index))
}
for index := range copiers {
done[index] = candidates[index].answerAll(ctx, t, harness, attempts[index], 1, []string{fmt.Sprintf("12.%d.0.40", index)}, copiedReviewAnswer(t), fmt.Sprintf("review-concurrent-answer-%d", index))
}
var finalizing sync.WaitGroup
for index := range copiers {
finalizing.Add(1)
go func() {
defer finalizing.Done()
candidates[index].finalize(t, harness, done[index], fmt.Sprintf("review-concurrent-finalize-%d", index), fmt.Sprintf("12.%d.0.41:1234", index))
}()
}
finalizing.Wait()
var running sync.WaitGroup
start := make(chan struct{})
for range copiers {
running.Add(1)
worker := reviewJobWorker(t, harness, reviewNow, 1)
go func() {
defer running.Done()
<-start
runReviewJobs(ctx, t, worker)
}()
}
close(start)
running.Wait()
for index, attempt := range attempts {
review, found := readStoredReview(t, ctx, harness, attempt.ID)
if !found || review.Band != "review" || !slices.Contains(review.Reasons, "duplicate_answers") {
t.Errorf("copied attempt %d review = %+v (found %v), want it flagged", index, review, found)
}
}
var dead int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND (status = 'dead' OR attempts > 1)`).Scan(&dead); err != nil || dead != 0 {
t.Fatalf("review jobs that failed or were retried = %d (error %v), want none", dead, err)
}
}
func readReviewCandidateResult(t *testing.T, harness *assessmentAttemptHTTPHarness, candidate reviewCandidate, attemptID uuid.UUID) map[string]any {
t.Helper()
response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+attemptID.String()+"/result", "", "",
candidate.cookies[0].Value, "", "", "203.0.113.201:1234")
var result map[string]any
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &result) != nil {
t.Fatalf("read result = %d %s", response.Code, response.Body.String())
}
return result
}
// A review job takes the review lock of every attempt it writes before it reads
// any fact. While another writer holds the lock of an attempt, the job waits
// and does not read or write; after the writer commits, the job reads what was
// committed. This is what keeps a slow job from overwriting a newer review with
// an older evaluation.
func TestAssessmentSignalReviewJobWaitsForTheReviewLock(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
defer cancel()
harness := newReviewHarness(ctx, t, reviewTestSignalPolicy())
candidate := newReviewCandidate(ctx, t, harness, "review-lock@example.test", "14.0.0", 1)
attempt := candidate.createAttempt(t, harness, "review-lock-create", "14.0.0.30:1234")
done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{"14.0.0.40"}, correctReviewAnswer(t), "review-lock-answer")
candidate.finalize(t, harness, done, "review-lock-finalize", "14.0.0.41:1234")
transactor := postgresadapter.NewTransactor(harness.pool)
locked, release, finished := make(chan struct{}), make(chan struct{}), make(chan error, 1)
go func() {
finished <- transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := unit.AssessmentSignals().LockReview(ctx, domain.AssessmentAttemptID(attempt.ID)); err != nil {
return err
}
close(locked)
<-release
return nil
})
}()
<-locked
jobFinished := make(chan struct{})
go func() {
defer close(jobFinished)
runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewNow, 1))
}()
select {
case <-jobFinished:
t.Fatal("the review job finished while another writer held the review lock")
case <-time.After(1500 * time.Millisecond):
}
if _, found := readStoredReview(t, ctx, harness, attempt.ID); found {
t.Fatal("a review was written while the review lock was held elsewhere")
}
var running int
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status = 'running'`).Scan(&running); err != nil || running != 1 {
t.Fatalf("running review jobs = %d (error %v), want the one waiting for the lock", running, err)
}
close(release)
if err := <-finished; err != nil {
t.Fatalf("lock holder transaction error = %v", err)
}
select {
case <-jobFinished:
case <-time.After(30 * time.Second):
t.Fatal("the review job did not finish after the lock was released")
}
if review, found := readStoredReview(t, ctx, harness, attempt.ID); !found || review.Fast == 0 {
t.Fatalf("review after the lock was released = %+v (found %v), want it computed from the committed facts", review, found)
}
}
@@ -0,0 +1,102 @@
//go:build integration
package integration_test
import (
"context"
"testing"
"time"
"github.com/google/uuid"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
)
const assessmentSignalReviewMigrationVersion = 33
// The audit of operator reads is durable evidence: rolling the schema back
// must not remove it as a side effect. An empty audit does not block the
// rollback, and the derived facts and reviews go with it.
func TestAssessmentSignalReviewMigrationDownRetainsAudit(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
t.Run("a retained audit row blocks the rollback", func(t *testing.T) {
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackAboveMigration(ctx, t, migrator, assessmentSignalReviewMigrationVersion)
if _, err := pool.Exec(ctx, `INSERT INTO assessment_review_reads (id, attempt_id, actor, found, read_at)
VALUES ($1, $2, 'operator:retained', false, $3)`, uuid.New(), uuid.New(), time.Now().UTC()); err != nil {
t.Fatalf("insert retained audit row: %v", err)
}
_, err := migrator.DownOne(ctx)
assertPgError(t, "DownOne() with a retained audit", err, privacyIntegrityViolation, "assessment_review_reads_retained")
var tableExists bool
var rows int
if err := pool.QueryRow(ctx, `SELECT to_regclass('public.assessment_review_reads') IS NOT NULL`).Scan(&tableExists); err != nil || !tableExists {
t.Fatalf("audit table exists = %v (error %v) after a refused rollback", tableExists, err)
}
if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_review_reads`).Scan(&rows); err != nil || rows != 1 {
t.Fatalf("retained audit rows = %d (error %v), want 1", rows, err)
}
if _, err := pool.Exec(ctx, `TRUNCATE assessment_review_reads`); err == nil {
t.Fatal("TRUNCATE of the audit table succeeded")
}
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("Status() error = %v", err)
}
for _, status := range statuses {
if status.Version == assessmentSignalReviewMigrationVersion && !status.Applied {
t.Fatal("the migration is not applied after its guarded Down() failed")
}
}
})
t.Run("an empty audit lets the rollback remove the tables", func(t *testing.T) {
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackAboveMigration(ctx, t, migrator, assessmentSignalReviewMigrationVersion)
if _, err := migrator.DownOne(ctx); err != nil {
t.Fatalf("DownOne() with an empty audit error = %v", err)
}
var remaining int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN (
'assessment_answer_observations', 'assessment_attempt_origin_marks', 'assessment_attempt_reviews', 'assessment_review_reads')`).Scan(&remaining); err != nil || remaining != 0 {
t.Fatalf("tables left after the rollback = %d (error %v), want none", remaining, err)
}
})
}
// rollBackAboveMigration rolls back every applied migration later than version.
func rollBackAboveMigration(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, version int64) {
t.Helper()
for {
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("Status() while preparing migration %d: %v", version, err)
}
later := false
for _, status := range statuses {
if status.Applied && status.Version > version {
later = true
}
}
if !later {
return
}
result, err := migrator.DownOne(ctx)
if err != nil || result.Version <= version {
t.Fatalf("DownOne() while preparing migration %d = version %d, error %v", version, result.Version, err)
}
}
}
@@ -51,6 +51,7 @@ var (
assessmentAttemptTables = []pgx.Identifier{
{"assessment_attempt_results"},
{"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"},
{"assessment_answer_observations"}, {"assessment_attempt_origin_marks"}, {"assessment_attempt_reviews"},
{"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"},
}
supportCaseTables = []pgx.Identifier{
+2 -1
View File
@@ -248,7 +248,8 @@ func TestPolicyVersions(t *testing.T) {
company_card_view_quota_usage, assessment_training_bank_bindings,
assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items,
support_cases, support_case_events, assessment_signal_idempotency_outcomes,
assessment_signal_events, assessment_signal_batches, assessment_attempt_results`},
assessment_signal_events, assessment_signal_batches, assessment_attempt_results,
assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks`},
}
for _, statement := range statements {
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
@@ -0,0 +1,133 @@
// Package assessmentreview implements the local operator command that prints
// the stored manual-review band of an assessment attempt. The band is never
// served over HTTP; this command is the only reader until staff roles exist.
package assessmentreview
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
)
const usage = "usage: assessment-review inspect --attempt <uuid> --actor operator:<handle>"
// Command is a parsed, validated review inspection.
type Command struct {
AttemptID domain.AssessmentAttemptID
Actor string
}
// Operator reads a review and records the read.
type Operator interface {
Inspect(ctx context.Context, attemptID domain.AssessmentAttemptID, actor string) (domain.AssessmentAttemptReview, error)
}
// Parse validates every argument before Run reads configuration or connects
// to PostgreSQL.
func Parse(args []string) (Command, error) {
if len(args) == 0 || args[0] != "inspect" {
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("assessment-review inspect", flag.ContinueOnError)
flags.SetOutput(io.Discard)
attempt := flags.String("attempt", "", "attempt UUID")
actor := flags.String("actor", "", "operator handle")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
return Command{}, errors.New(usage)
}
attemptID, err := uuid.Parse(strings.TrimSpace(*attempt))
if err != nil || attemptID == uuid.Nil {
return Command{}, errors.New("attempt must be a non-zero UUID")
}
if _, err := domain.ParseAssessmentReviewActor(strings.TrimSpace(*actor)); err != nil {
return Command{}, errors.New("actor must be operator:<handle>")
}
return Command{AttemptID: domain.AssessmentAttemptID(attemptID), Actor: strings.TrimSpace(*actor)}, nil
}
// Run parses the command, loads only DATABASE_URL from the supplied
// environment, and executes the operator usecase. It does not load dotenv
// files.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil {
return errors.New("assessment review command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
pool, err := postgres.NewPool(ctx, databaseURL)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
operator, err := assessment.NewReviewOperator(postgres.NewTransactor(pool))
if err != nil {
return errors.New("assessment review is unavailable")
}
return Execute(ctx, command, operator, output)
}
// Execute prints the review. The output holds counts, durations, the band, the
// reason codes, and the policy version; it holds no answer, address, session,
// candidate, or contact data.
func Execute(ctx context.Context, command Command, operator Operator, output io.Writer) error {
if operator == nil || output == nil {
return errors.New("assessment review command dependencies are required")
}
review, err := operator.Inspect(ctx, command.AttemptID, command.Actor)
if err != nil {
return safeOperationError(err)
}
reasons := make([]string, 0, len(review.Outcome.Reasons))
for _, reason := range review.Outcome.Reasons {
reasons = append(reasons, string(reason))
}
measures := review.Measures
if _, err := fmt.Fprintf(output,
"attempt: %s\nband: %s\nreasons: %s\npolicy_version: %d\nevaluated_at: %s\nupdated_at: %s\n"+
"answered_items: %d\nfast_answers: %d\ndeviating_answers: %d\nparallel_alternations: %d\nextra_networks: %d\n"+
"matched_integer_items: %d\nmatched_sequence_items: %d\nduplicate_evidence_bits: %d\n"+
"client_focus_loss_ms: %d\nclient_clipboard_events: %d\nclient_fullscreen_exits: %d\n"+
"note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged\n",
review.AttemptID, review.Outcome.Band, strings.Join(reasons, ","), review.PolicyVersion,
review.EvaluatedAt.UTC().Format(time.RFC3339), review.UpdatedAt.UTC().Format(time.RFC3339),
measures.AnsweredItems, measures.FastAnswers, measures.DeviatingAnswers, measures.ParallelAlternations,
measures.ExtraNetworks, measures.MatchedIntegerItems, measures.MatchedSequenceItems,
measures.DuplicateEvidenceBits, measures.ClientFocusLossMS, measures.ClientClipboardEvents,
measures.ClientFullscreenExits,
); err != nil {
return errors.New("could not write the review")
}
return nil
}
func safeOperationError(err error) error {
switch {
case errors.Is(err, outbound.ErrAssessmentReviewNotFound):
return errors.New("attempt has no review (the read was recorded)")
case errors.Is(err, domain.ErrInvalidAssessmentReview):
return errors.New("attempt or actor is invalid")
default:
return errors.New("assessment review operation failed")
}
}
@@ -0,0 +1,113 @@
package assessmentreview
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
type operatorFake struct {
review domain.AssessmentAttemptReview
err error
calls int
actor string
}
func (operator *operatorFake) Inspect(_ context.Context, _ domain.AssessmentAttemptID, actor string) (domain.AssessmentAttemptReview, error) {
operator.calls++
operator.actor = actor
return operator.review, operator.err
}
func TestParseRequiresAnAttemptAndAnOperatorHandle(t *testing.T) {
id := uuid.New().String()
command, err := Parse([]string{"inspect", "--attempt", id, "--actor", "operator:night"})
if err != nil || command.AttemptID.String() != id || command.Actor != "operator:night" {
t.Fatalf("Parse(valid) = %+v, %v", command, err)
}
for _, args := range [][]string{
nil,
{"list"},
{"inspect"},
{"inspect", "--attempt", id},
{"inspect", "--attempt", id, "--actor", "alice"},
{"inspect", "--attempt", "not-a-uuid", "--actor", "operator:night"},
{"inspect", "--attempt", uuid.Nil.String(), "--actor", "operator:night"},
{"inspect", "--attempt", id, "--actor", "operator:night", "extra"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) {
lookup := func(string) (string, bool) {
t.Fatal("environment read before arguments were validated")
return "", false
}
if err := Run(context.Background(), []string{"inspect"}, lookup, &bytes.Buffer{}); err == nil {
t.Fatal("Run(invalid arguments) succeeded")
}
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
err := Run(context.Background(), []string{"inspect", "--attempt", uuid.New().String(), "--actor", "operator:night"}, noDatabase, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
}
}
func TestExecutePrintsOnlyBandCountsAndReasons(t *testing.T) {
attemptID := domain.AssessmentAttemptID(uuid.New())
operator := &operatorFake{review: domain.AssessmentAttemptReview{
AttemptID: attemptID, PolicyVersion: 4,
Measures: domain.AssessmentReviewMeasures{AnsweredItems: 9, FastAnswers: 5, ParallelAlternations: 2, ExtraNetworks: 1, MatchedIntegerItems: 3, DuplicateEvidenceBits: 9},
Outcome: domain.AssessmentReviewOutcome{
Band: domain.AssessmentReviewBandAttention,
Reasons: []domain.AssessmentReviewReason{domain.AssessmentReviewReasonFastAnswers, domain.AssessmentReviewReasonParallelSessions},
},
EvaluatedAt: time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC), UpdatedAt: time.Date(2026, time.October, 2, 10, 0, 0, 0, time.UTC),
}}
var output bytes.Buffer
command := Command{AttemptID: attemptID, Actor: "operator:night"}
if err := Execute(context.Background(), command, operator, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
for _, want := range []string{"attempt: " + attemptID.String(), "band: attention", "reasons: fast_answers,parallel_sessions", "policy_version: 4", "fast_answers: 5", "matched_integer_items: 3", "extra_networks: 1", "duplicate_evidence_bits: 9", "a hint for a manual check"} {
if !strings.Contains(output.String(), want) {
t.Errorf("output lacks %q:\n%s", want, output.String())
}
}
for _, forbidden := range []string{"user", "email", "address", "session", "answer:", "fingerprint"} {
if strings.Contains(output.String(), forbidden+":") {
t.Errorf("output has a %q line:\n%s", forbidden, output.String())
}
}
if operator.calls != 1 || operator.actor != "operator:night" {
t.Fatalf("operator calls/actor = %d/%q, want one call with the handle", operator.calls, operator.actor)
}
}
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
for _, test := range []struct {
err error
want string
}{
{outbound.ErrAssessmentReviewNotFound, "no review"},
{domain.ErrInvalidAssessmentReview, "invalid"},
{errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "operation failed"},
} {
err := Execute(context.Background(), Command{}, &operatorFake{err: test.err}, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") {
t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want)
}
}
}
@@ -320,6 +320,239 @@ func (s *Server) handleAcceptMyInvitationRequest(args [1]string, argsEscaped boo
}
}
// handleAcknowledgeMyAssessmentSignalNoticeRequest handles AcknowledgeMyAssessmentSignalNotice operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The body carries the notice version the candidate
// was shown. The server stores the acknowledgement for the account and that version; the response
// carries the server time of the first acknowledgement.
//
// The operation needs no Idempotency-Key: it is idempotent. Repeating it for an acknowledged version
// changes nothing, keeps the first time, and answers 200, so a retry after a lost response succeeds. A
// version other than the one the server requires answers 409 state_conflict and stores nothing; the
// client reads the notice again.
//
// The acknowledgement is not a consent. It does not grant, replace, or hide C3, and it does not affect
// the signal operation or any score, category, or quota. The body carries no signal, answer, or
// clipboard data.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account (403 forbidden), then the version (409).
//
// PUT /api/v1/me/assessment-signal-notice
func (s *Server) handleAcknowledgeMyAssessmentSignalNoticeRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("AcknowledgeMyAssessmentSignalNotice"),
semconv.HTTPRequestMethodKey.String("PUT"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-signal-notice"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), AcknowledgeMyAssessmentSignalNoticeOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: AcknowledgeMyAssessmentSignalNoticeOperation,
ID: "AcknowledgeMyAssessmentSignalNotice",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, AcknowledgeMyAssessmentSignalNoticeOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, AcknowledgeMyAssessmentSignalNoticeOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
var rawBody []byte
request, rawBody, close, err := s.decodeAcknowledgeMyAssessmentSignalNoticeRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response AcknowledgeMyAssessmentSignalNoticeRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: AcknowledgeMyAssessmentSignalNoticeOperation,
OperationSummary: "Record that the current candidate read the signal notice.",
OperationID: "AcknowledgeMyAssessmentSignalNotice",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = *AssessmentSignalNoticeAcknowledgement
Params = struct{}
Response = AcknowledgeMyAssessmentSignalNoticeRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.AcknowledgeMyAssessmentSignalNotice(ctx, request)
return response, err
},
)
} else {
response, err = s.h.AcknowledgeMyAssessmentSignalNotice(ctx, request)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeAcknowledgeMyAssessmentSignalNoticeResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleCancelMyInvitationRequest handles CancelMyInvitation operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -4056,6 +4289,209 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped
}
}
// handleGetMyAssessmentSignalNoticeRequest handles GetMyAssessmentSignalNotice operation.
//
// Requires the session cookie of a candidate account with a confirmed email; the candidate comes from
// the session. Returns the notice version that the server requires now and whether this candidate
// acknowledged it. The notice lists the signals that are collected during a real assessment attempt
// and states that images, sound, and clipboard contents are not collected. Client signals are the time
// away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode.
// Server signals are the response time of each item measured by the server, a change of network
// address during the attempt, parallel sessions, and the comparison of answers to variants of the same
// task by candidates. The server stores for these only one-way keyed digests: it stores no network
// address, no session token, and no answer text. Client signals are stored only while the C3 consent
// is current. The client shows it before a real attempt starts and does not start the attempt until
// the notice is acknowledged.
//
// The acknowledgement is stored on the server per account and notice version, so it survives a reload
// and a new browser. It is not a consent and never changes C3: the signal operation still requires a
// current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express
// training mode collects no signals and needs no acknowledgement.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or
// an unconfirmed email answers 403 forbidden.
//
// GET /api/v1/me/assessment-signal-notice
func (s *Server) handleGetMyAssessmentSignalNoticeRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetMyAssessmentSignalNotice"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-signal-notice"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentSignalNoticeOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: GetMyAssessmentSignalNoticeOperation,
ID: "GetMyAssessmentSignalNotice",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentSignalNoticeOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
var rawBody []byte
var response GetMyAssessmentSignalNoticeRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetMyAssessmentSignalNoticeOperation,
OperationSummary: "Read whether the current candidate acknowledged the signal notice.",
OperationID: "GetMyAssessmentSignalNotice",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{},
Raw: r,
}
type (
Request = struct{}
Params = struct{}
Response = GetMyAssessmentSignalNoticeRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
nil,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetMyAssessmentSignalNotice(ctx)
return response, err
},
)
} else {
response, err = s.h.GetMyAssessmentSignalNotice(ctx)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetMyAssessmentSignalNoticeResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetMyCardPreviewRequest handles GetMyCardPreview operation.
//
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
@@ -7265,6 +7701,219 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool,
}
}
// handleListMyAssessmentResultsRequest handles ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
// candidate, newest first by decided_at and attempt_id. demo_express training results never appear.
// The cursor is opaque and bound to this candidate and listing; a malformed or foreign cursor returns
// 400 validation_failed.
//
// A v2 result includes the category decision captured when that attempt ended, including the confirmed
// grade then in force. Legacy v1 results omit category_decision because a later category must not be
// projected backward. Later policy, bank, review, or category changes do not alter either result.
// Employers cannot read this history; their separate projection contains only the current permitted
// category and no answers.
//
// GET /api/v1/me/assessment-results
func (s *Server) handleListMyAssessmentResultsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyAssessmentResults"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-results"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyAssessmentResultsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ListMyAssessmentResultsOperation,
ID: "ListMyAssessmentResults",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyAssessmentResultsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeListMyAssessmentResultsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ListMyAssessmentResultsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyAssessmentResultsOperation,
OperationSummary: "List immutable real assessment results of the current candidate.",
OperationID: "ListMyAssessmentResults",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListMyAssessmentResultsParams
Response = ListMyAssessmentResultsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyAssessmentResultsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyAssessmentResults(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyAssessmentResults(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeListMyAssessmentResultsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMyCardAccessHistoryRequest handles ListMyCardAccessHistory operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
@@ -5,6 +5,10 @@ type AcceptMyInvitationRes interface {
acceptMyInvitationRes()
}
type AcknowledgeMyAssessmentSignalNoticeRes interface {
acknowledgeMyAssessmentSignalNoticeRes()
}
type CancelMyInvitationRes interface {
cancelMyInvitationRes()
}
@@ -65,6 +69,10 @@ type GetMyAssessmentResultRes interface {
getMyAssessmentResultRes()
}
type GetMyAssessmentSignalNoticeRes interface {
getMyAssessmentSignalNoticeRes()
}
type GetMyCardPreviewRes interface {
getMyCardPreviewRes()
}
@@ -121,6 +129,10 @@ type HideOrganizationRes interface {
hideOrganizationRes()
}
type ListMyAssessmentResultsRes interface {
listMyAssessmentResultsRes()
}
type ListMyCardAccessHistoryRes interface {
listMyCardAccessHistoryRes()
}
File diff suppressed because it is too large. Load diff
@@ -6,68 +6,71 @@ package api
type OperationName = string
const (
AcceptMyInvitationOperation OperationName = "AcceptMyInvitation"
CancelMyInvitationOperation OperationName = "CancelMyInvitation"
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt"
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyCardPreviewOperation OperationName = "GetMyCardPreview"
GetMyConsentTextOperation OperationName = "GetMyConsentText"
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings"
GetMyProfileOperation OperationName = "GetMyProfile"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
GrantMyConsentOperation OperationName = "GrantMyConsent"
HideOrganizationOperation OperationName = "HideOrganization"
ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
RegisterAccountOperation OperationName = "RegisterAccount"
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
RevokeMyConsentOperation OperationName = "RevokeMyConsent"
RevokeMyOrganizationContactConsentOperation OperationName = "RevokeMyOrganizationContactConsent"
SaveMyProfileOperation OperationName = "SaveMyProfile"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SearchOrganizationMatchesOperation OperationName = "SearchOrganizationMatches"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SetMyPublicationOperation OperationName = "SetMyPublication"
SetMySearchStatusOperation OperationName = "SetMySearchStatus"
StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UnhideOrganizationOperation OperationName = "UnhideOrganization"
UpdateOrganizationOperation OperationName = "UpdateOrganization"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation"
AcceptMyInvitationOperation OperationName = "AcceptMyInvitation"
AcknowledgeMyAssessmentSignalNoticeOperation OperationName = "AcknowledgeMyAssessmentSignalNotice"
CancelMyInvitationOperation OperationName = "CancelMyInvitation"
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt"
GetConsentTextOperation OperationName = "GetConsentText"
GetCurrentAccountOperation OperationName = "GetCurrentAccount"
GetCurrentSessionOperation OperationName = "GetCurrentSession"
GetHealthzOperation OperationName = "GetHealthz"
GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt"
GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability"
GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult"
GetMyAssessmentSignalNoticeOperation OperationName = "GetMyAssessmentSignalNotice"
GetMyCardPreviewOperation OperationName = "GetMyCardPreview"
GetMyConsentTextOperation OperationName = "GetMyConsentText"
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings"
GetMyProfileOperation OperationName = "GetMyProfile"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
GrantMyConsentOperation OperationName = "GrantMyConsent"
HideOrganizationOperation OperationName = "HideOrganization"
ListMyAssessmentResultsOperation OperationName = "ListMyAssessmentResults"
ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
RegisterAccountOperation OperationName = "RegisterAccount"
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
RevokeMyConsentOperation OperationName = "RevokeMyConsent"
RevokeMyOrganizationContactConsentOperation OperationName = "RevokeMyOrganizationContactConsent"
SaveMyProfileOperation OperationName = "SaveMyProfile"
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SearchOrganizationMatchesOperation OperationName = "SearchOrganizationMatches"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SetMyPublicationOperation OperationName = "SetMyPublication"
SetMySearchStatusOperation OperationName = "SetMySearchStatus"
StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UnhideOrganizationOperation OperationName = "UnhideOrganization"
UpdateOrganizationOperation OperationName = "UpdateOrganization"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation"
)
@@ -2433,6 +2433,181 @@ func decodeHideOrganizationParams(args [1]string, argsEscaped bool, r *http.Requ
return params, nil
}
// ListMyAssessmentResultsParams is parameters of ListMyAssessmentResults operation.
type ListMyAssessmentResultsParams struct {
// Maximum number of results per page.
Limit OptInt32 `json:",omitempty,omitzero"`
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
Cursor OptString `json:",omitempty,omitzero"`
}
func unpackListMyAssessmentResultsParams(packed middleware.Parameters) (params ListMyAssessmentResultsParams) {
{
key := middleware.ParameterKey{
Name: "limit",
In: "query",
}
if v, ok := packed[key]; ok {
params.Limit = v.(OptInt32)
}
}
{
key := middleware.ParameterKey{
Name: "cursor",
In: "query",
}
if v, ok := packed[key]; ok {
params.Cursor = v.(OptString)
}
}
return params
}
func decodeListMyAssessmentResultsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyAssessmentResultsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// Set default value for query: limit.
{
val := int32(20)
params.Limit.SetTo(val)
}
// Decode query: limit.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "limit",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotLimitVal int32
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
paramsDotLimitVal = c
return nil
}(); err != nil {
return err
}
params.Limit.SetTo(paramsDotLimitVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Limit.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 50,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "limit",
In: "query",
Err: err,
}
}
// Decode query: cursor.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "cursor",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotCursorVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCursorVal = c
return nil
}(); err != nil {
return err
}
params.Cursor.SetTo(paramsDotCursorVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Cursor.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 512,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "cursor",
In: "query",
Err: err,
}
}
return params, nil
}
// ListMyCardAccessHistoryParams is parameters of ListMyCardAccessHistory operation.
type ListMyCardAccessHistoryParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
@@ -93,6 +93,85 @@ func (s *Server) decodeAcceptMyInvitationRequest(r *http.Request) (
}
}
func (s *Server) decodeAcknowledgeMyAssessmentSignalNoticeRequest(r *http.Request) (
req *AssessmentSignalNoticeAcknowledgement,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request AssessmentSignalNoticeAcknowledgement
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCancelMyInvitationRequest(r *http.Request) (
req *InvitationCommand,
rawBody []byte,
@@ -165,6 +165,89 @@ func encodeAcceptMyInvitationResponse(response AcceptMyInvitationRes, w http.Res
}
}
func encodeAcknowledgeMyAssessmentSignalNoticeResponse(response AcknowledgeMyAssessmentSignalNoticeRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentSignalNoticeHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *AcknowledgeMyAssessmentSignalNoticeBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *AcknowledgeMyAssessmentSignalNoticeUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *AcknowledgeMyAssessmentSignalNoticeForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *AcknowledgeMyAssessmentSignalNoticeConflict:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeCancelMyInvitationResponse(response CancelMyInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CandidateInvitationHeaders:
@@ -1683,6 +1766,65 @@ func encodeGetMyAssessmentResultResponse(response GetMyAssessmentResultRes, w ht
}
}
func encodeGetMyAssessmentSignalNoticeResponse(response GetMyAssessmentSignalNoticeRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentSignalNoticeHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyAssessmentSignalNoticeUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetMyAssessmentSignalNoticeForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetMyCardPreviewResponse(response GetMyCardPreviewRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CardPreviewHeaders:
@@ -2790,6 +2932,77 @@ func encodeHideOrganizationResponse(response HideOrganizationRes, w http.Respons
}
}
func encodeListMyAssessmentResultsResponse(response ListMyAssessmentResultsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentResultHistoryPageHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyAssessmentResultsBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyAssessmentResultsUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyAssessmentResultsForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeListMyCardAccessHistoryResponse(response ListMyCardAccessHistoryRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *CardAccessListHeaders:
File diff suppressed because it is too large. Load diff
@@ -191,6 +191,22 @@ func (s *AccountScenario) UnmarshalText(data []byte) error {
}
}
type AcknowledgeMyAssessmentSignalNoticeBadRequest Problem
func (*AcknowledgeMyAssessmentSignalNoticeBadRequest) acknowledgeMyAssessmentSignalNoticeRes() {}
type AcknowledgeMyAssessmentSignalNoticeConflict Problem
func (*AcknowledgeMyAssessmentSignalNoticeConflict) acknowledgeMyAssessmentSignalNoticeRes() {}
type AcknowledgeMyAssessmentSignalNoticeForbidden Problem
func (*AcknowledgeMyAssessmentSignalNoticeForbidden) acknowledgeMyAssessmentSignalNoticeRes() {}
type AcknowledgeMyAssessmentSignalNoticeUnauthorized Problem
func (*AcknowledgeMyAssessmentSignalNoticeUnauthorized) acknowledgeMyAssessmentSignalNoticeRes() {}
// The anonymous candidate card as an organization reads it. Only explicitly published values reach it;
// unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It
// carries no name, contact, resume text, employer, salary figure, account or profile identifier, and
@@ -1021,12 +1037,213 @@ func (s *AssessmentAvailabilityHeaders) SetResponse(val AssessmentAvailability)
func (*AssessmentAvailabilityHeaders) getMyAssessmentAvailabilityRes() {}
// Category decision captured when this result was stored. It is absent from legacy v1 results because
// their current grade cannot be inferred later. It never exposes review identifiers, private answers,
// or the candidate's current category after this decision.
// Ref: #/components/schemas/AssessmentCategoryDecisionView
type AssessmentCategoryDecisionView struct {
Status AssessmentCategoryDecisionViewStatus `json:"status"`
PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"`
CurrentConfirmedGrade NilGradeCode `json:"current_confirmed_grade"`
Method NilAssessmentCategoryDecisionViewMethod `json:"method"`
Source NilAssessmentCategoryDecisionViewSource `json:"source"`
CalibrationStatus NilCalibrationStatus `json:"calibration_status"`
}
// GetStatus returns the value of Status.
func (s *AssessmentCategoryDecisionView) GetStatus() AssessmentCategoryDecisionViewStatus {
return s.Status
}
// GetPreviousConfirmedGrade returns the value of PreviousConfirmedGrade.
func (s *AssessmentCategoryDecisionView) GetPreviousConfirmedGrade() NilGradeCode {
return s.PreviousConfirmedGrade
}
// GetCurrentConfirmedGrade returns the value of CurrentConfirmedGrade.
func (s *AssessmentCategoryDecisionView) GetCurrentConfirmedGrade() NilGradeCode {
return s.CurrentConfirmedGrade
}
// GetMethod returns the value of Method.
func (s *AssessmentCategoryDecisionView) GetMethod() NilAssessmentCategoryDecisionViewMethod {
return s.Method
}
// GetSource returns the value of Source.
func (s *AssessmentCategoryDecisionView) GetSource() NilAssessmentCategoryDecisionViewSource {
return s.Source
}
// GetCalibrationStatus returns the value of CalibrationStatus.
func (s *AssessmentCategoryDecisionView) GetCalibrationStatus() NilCalibrationStatus {
return s.CalibrationStatus
}
// SetStatus sets the value of Status.
func (s *AssessmentCategoryDecisionView) SetStatus(val AssessmentCategoryDecisionViewStatus) {
s.Status = val
}
// SetPreviousConfirmedGrade sets the value of PreviousConfirmedGrade.
func (s *AssessmentCategoryDecisionView) SetPreviousConfirmedGrade(val NilGradeCode) {
s.PreviousConfirmedGrade = val
}
// SetCurrentConfirmedGrade sets the value of CurrentConfirmedGrade.
func (s *AssessmentCategoryDecisionView) SetCurrentConfirmedGrade(val NilGradeCode) {
s.CurrentConfirmedGrade = val
}
// SetMethod sets the value of Method.
func (s *AssessmentCategoryDecisionView) SetMethod(val NilAssessmentCategoryDecisionViewMethod) {
s.Method = val
}
// SetSource sets the value of Source.
func (s *AssessmentCategoryDecisionView) SetSource(val NilAssessmentCategoryDecisionViewSource) {
s.Source = val
}
// SetCalibrationStatus sets the value of CalibrationStatus.
func (s *AssessmentCategoryDecisionView) SetCalibrationStatus(val NilCalibrationStatus) {
s.CalibrationStatus = val
}
type AssessmentCategoryDecisionViewMethod string
const (
AssessmentCategoryDecisionViewMethodDemoBasicPassMark AssessmentCategoryDecisionViewMethod = "demo_basic_pass_mark"
)
// AllValues returns all AssessmentCategoryDecisionViewMethod values.
func (AssessmentCategoryDecisionViewMethod) AllValues() []AssessmentCategoryDecisionViewMethod {
return []AssessmentCategoryDecisionViewMethod{
AssessmentCategoryDecisionViewMethodDemoBasicPassMark,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s AssessmentCategoryDecisionViewMethod) MarshalText() ([]byte, error) {
switch s {
case AssessmentCategoryDecisionViewMethodDemoBasicPassMark:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *AssessmentCategoryDecisionViewMethod) UnmarshalText(data []byte) error {
switch AssessmentCategoryDecisionViewMethod(data) {
case AssessmentCategoryDecisionViewMethodDemoBasicPassMark:
*s = AssessmentCategoryDecisionViewMethodDemoBasicPassMark
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
type AssessmentCategoryDecisionViewSource string
const (
AssessmentCategoryDecisionViewSourceSyntheticDemo AssessmentCategoryDecisionViewSource = "synthetic_demo"
)
// AllValues returns all AssessmentCategoryDecisionViewSource values.
func (AssessmentCategoryDecisionViewSource) AllValues() []AssessmentCategoryDecisionViewSource {
return []AssessmentCategoryDecisionViewSource{
AssessmentCategoryDecisionViewSourceSyntheticDemo,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s AssessmentCategoryDecisionViewSource) MarshalText() ([]byte, error) {
switch s {
case AssessmentCategoryDecisionViewSourceSyntheticDemo:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *AssessmentCategoryDecisionViewSource) UnmarshalText(data []byte) error {
switch AssessmentCategoryDecisionViewSource(data) {
case AssessmentCategoryDecisionViewSourceSyntheticDemo:
*s = AssessmentCategoryDecisionViewSourceSyntheticDemo
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
type AssessmentCategoryDecisionViewStatus string
const (
AssessmentCategoryDecisionViewStatusNotEligible AssessmentCategoryDecisionViewStatus = "not_eligible"
AssessmentCategoryDecisionViewStatusNotConfirmed AssessmentCategoryDecisionViewStatus = "not_confirmed"
AssessmentCategoryDecisionViewStatusAssigned AssessmentCategoryDecisionViewStatus = "assigned"
AssessmentCategoryDecisionViewStatusUnchanged AssessmentCategoryDecisionViewStatus = "unchanged"
)
// AllValues returns all AssessmentCategoryDecisionViewStatus values.
func (AssessmentCategoryDecisionViewStatus) AllValues() []AssessmentCategoryDecisionViewStatus {
return []AssessmentCategoryDecisionViewStatus{
AssessmentCategoryDecisionViewStatusNotEligible,
AssessmentCategoryDecisionViewStatusNotConfirmed,
AssessmentCategoryDecisionViewStatusAssigned,
AssessmentCategoryDecisionViewStatusUnchanged,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s AssessmentCategoryDecisionViewStatus) MarshalText() ([]byte, error) {
switch s {
case AssessmentCategoryDecisionViewStatusNotEligible:
return []byte(s), nil
case AssessmentCategoryDecisionViewStatusNotConfirmed:
return []byte(s), nil
case AssessmentCategoryDecisionViewStatusAssigned:
return []byte(s), nil
case AssessmentCategoryDecisionViewStatusUnchanged:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *AssessmentCategoryDecisionViewStatus) UnmarshalText(data []byte) error {
switch AssessmentCategoryDecisionViewStatus(data) {
case AssessmentCategoryDecisionViewStatusNotEligible:
*s = AssessmentCategoryDecisionViewStatusNotEligible
return nil
case AssessmentCategoryDecisionViewStatusNotConfirmed:
*s = AssessmentCategoryDecisionViewStatusNotConfirmed
return nil
case AssessmentCategoryDecisionViewStatusAssigned:
*s = AssessmentCategoryDecisionViewStatusAssigned
return nil
case AssessmentCategoryDecisionViewStatusUnchanged:
*s = AssessmentCategoryDecisionViewStatusUnchanged
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// Ref: #/components/schemas/AssessmentClipboardSignal
type AssessmentClipboardSignal struct {
Kind AssessmentClipboardSignalKind `json:"kind"`
ItemInstanceID AssessmentItemId `json:"item_instance_id"`
OccurredAt Timestamp `json:"occurred_at"`
// Byte count only. Clipboard or selection contents are not transmitted or retained.
// Size only; clipboard and selection contents are never transmitted or retained. For `paste` it is the
// UTF-8 byte count of the pasted plain text plus the byte size of pasted files, counted on the device
// from the paste event. For `copy` and `cut` it is the selection length in UTF-16 code units taken
// from the selection offsets of a form field, or zero when the field offsets are unavailable; it is an
// approximate size and the selected text is not read. The server applies no conversion and treats the
// value as an order-of-magnitude indicator.
SizeBytes int32 `json:"size_bytes"`
}
@@ -1538,7 +1755,8 @@ type AssessmentCorrectiveResult struct {
ConfirmedGrade NilGradeCode `json:"confirmed_grade"`
// Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed
// nothing, this grade stays in force.
PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"`
PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"`
CategoryDecision OptAssessmentCategoryDecisionView `json:"category_decision"`
// Strength of an adaptive confirmation, otherwise null.
Strength NilAssessmentStrength `json:"strength"`
CalibrationStatus CalibrationStatus `json:"calibration_status"`
@@ -1622,6 +1840,11 @@ func (s *AssessmentCorrectiveResult) GetPreviousConfirmedGrade() NilGradeCode {
return s.PreviousConfirmedGrade
}
// GetCategoryDecision returns the value of CategoryDecision.
func (s *AssessmentCorrectiveResult) GetCategoryDecision() OptAssessmentCategoryDecisionView {
return s.CategoryDecision
}
// GetStrength returns the value of Strength.
func (s *AssessmentCorrectiveResult) GetStrength() NilAssessmentStrength {
return s.Strength
@@ -1737,6 +1960,11 @@ func (s *AssessmentCorrectiveResult) SetPreviousConfirmedGrade(val NilGradeCode)
s.PreviousConfirmedGrade = val
}
// SetCategoryDecision sets the value of CategoryDecision.
func (s *AssessmentCorrectiveResult) SetCategoryDecision(val OptAssessmentCategoryDecisionView) {
s.CategoryDecision = val
}
// SetStrength sets the value of Strength.
func (s *AssessmentCorrectiveResult) SetStrength(val NilAssessmentStrength) {
s.Strength = val
@@ -4131,7 +4359,8 @@ type AssessmentQualifiedResult struct {
ConfirmedGrade NilGradeCode `json:"confirmed_grade"`
// Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed
// nothing, this grade stays in force.
PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"`
PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"`
CategoryDecision OptAssessmentCategoryDecisionView `json:"category_decision"`
// Strength of an adaptive confirmation, otherwise null.
Strength NilAssessmentStrength `json:"strength"`
CalibrationStatus CalibrationStatus `json:"calibration_status"`
@@ -4215,6 +4444,11 @@ func (s *AssessmentQualifiedResult) GetPreviousConfirmedGrade() NilGradeCode {
return s.PreviousConfirmedGrade
}
// GetCategoryDecision returns the value of CategoryDecision.
func (s *AssessmentQualifiedResult) GetCategoryDecision() OptAssessmentCategoryDecisionView {
return s.CategoryDecision
}
// GetStrength returns the value of Strength.
func (s *AssessmentQualifiedResult) GetStrength() NilAssessmentStrength {
return s.Strength
@@ -4330,6 +4564,11 @@ func (s *AssessmentQualifiedResult) SetPreviousConfirmedGrade(val NilGradeCode)
s.PreviousConfirmedGrade = val
}
// SetCategoryDecision sets the value of CategoryDecision.
func (s *AssessmentQualifiedResult) SetCategoryDecision(val OptAssessmentCategoryDecisionView) {
s.CategoryDecision = val
}
// SetStrength sets the value of Strength.
func (s *AssessmentQualifiedResult) SetStrength(val NilAssessmentStrength) {
s.Strength = val
@@ -4499,6 +4738,78 @@ func (s *AssessmentRealMode) UnmarshalText(data []byte) error {
}
}
// A completed root or corrective result. Training-only demo_express results are excluded from
// qualification history.
// Ref: #/components/schemas/AssessmentRealResult
// AssessmentRealResult represents sum type.
type AssessmentRealResult struct {
// Type selects the active sum variant, switch on this field.
Type AssessmentRealResultType
AssessmentQualifiedResult AssessmentQualifiedResult
AssessmentCorrectiveResult AssessmentCorrectiveResult
}
// AssessmentRealResultType is oneOf type of AssessmentRealResult.
type AssessmentRealResultType string
// Possible values for AssessmentRealResultType.
const (
AssessmentQualifiedResultAssessmentRealResult AssessmentRealResultType = "root"
AssessmentCorrectiveResultAssessmentRealResult AssessmentRealResultType = "corrective"
)
// IsAssessmentQualifiedResult reports whether AssessmentRealResult is AssessmentQualifiedResult.
func (s AssessmentRealResult) IsAssessmentQualifiedResult() bool {
return s.Type == AssessmentQualifiedResultAssessmentRealResult
}
// IsAssessmentCorrectiveResult reports whether AssessmentRealResult is AssessmentCorrectiveResult.
func (s AssessmentRealResult) IsAssessmentCorrectiveResult() bool {
return s.Type == AssessmentCorrectiveResultAssessmentRealResult
}
// SetAssessmentQualifiedResult sets AssessmentRealResult to AssessmentQualifiedResult.
func (s *AssessmentRealResult) SetAssessmentQualifiedResult(v AssessmentQualifiedResult) {
s.Type = AssessmentQualifiedResultAssessmentRealResult
s.AssessmentQualifiedResult = v
}
// GetAssessmentQualifiedResult returns AssessmentQualifiedResult and true boolean if AssessmentRealResult is AssessmentQualifiedResult.
func (s AssessmentRealResult) GetAssessmentQualifiedResult() (v AssessmentQualifiedResult, ok bool) {
if !s.IsAssessmentQualifiedResult() {
return v, false
}
return s.AssessmentQualifiedResult, true
}
// NewAssessmentQualifiedResultAssessmentRealResult returns new AssessmentRealResult from AssessmentQualifiedResult.
func NewAssessmentQualifiedResultAssessmentRealResult(v AssessmentQualifiedResult) AssessmentRealResult {
var s AssessmentRealResult
s.SetAssessmentQualifiedResult(v)
return s
}
// SetAssessmentCorrectiveResult sets AssessmentRealResult to AssessmentCorrectiveResult.
func (s *AssessmentRealResult) SetAssessmentCorrectiveResult(v AssessmentCorrectiveResult) {
s.Type = AssessmentCorrectiveResultAssessmentRealResult
s.AssessmentCorrectiveResult = v
}
// GetAssessmentCorrectiveResult returns AssessmentCorrectiveResult and true boolean if AssessmentRealResult is AssessmentCorrectiveResult.
func (s AssessmentRealResult) GetAssessmentCorrectiveResult() (v AssessmentCorrectiveResult, ok bool) {
if !s.IsAssessmentCorrectiveResult() {
return v, false
}
return s.AssessmentCorrectiveResult, true
}
// NewAssessmentCorrectiveResultAssessmentRealResult returns new AssessmentRealResult from AssessmentCorrectiveResult.
func NewAssessmentCorrectiveResultAssessmentRealResult(v AssessmentCorrectiveResult) AssessmentRealResult {
var s AssessmentRealResult
s.SetAssessmentCorrectiveResult(v)
return s
}
// Immutable result of a terminal assessment attempt. The result shape distinguishes real grade
// decisions from demo_express training output.
// Ref: #/components/schemas/AssessmentResult
@@ -4627,6 +4938,62 @@ func (s *AssessmentResultHeaders) SetResponse(val AssessmentResult) {
func (*AssessmentResultHeaders) getMyAssessmentResultRes() {}
// Owner-only immutable root and corrective results ordered by decided_at and attempt_id descending.
// Legacy v1 results omit category_decision.
// Ref: #/components/schemas/AssessmentResultHistoryPage
type AssessmentResultHistoryPage struct {
Items []AssessmentRealResult `json:"items"`
Page PageInfo `json:"page"`
}
// GetItems returns the value of Items.
func (s *AssessmentResultHistoryPage) GetItems() []AssessmentRealResult {
return s.Items
}
// GetPage returns the value of Page.
func (s *AssessmentResultHistoryPage) GetPage() PageInfo {
return s.Page
}
// SetItems sets the value of Items.
func (s *AssessmentResultHistoryPage) SetItems(val []AssessmentRealResult) {
s.Items = val
}
// SetPage sets the value of Page.
func (s *AssessmentResultHistoryPage) SetPage(val PageInfo) {
s.Page = val
}
// AssessmentResultHistoryPageHeaders wraps AssessmentResultHistoryPage with response headers.
type AssessmentResultHistoryPageHeaders struct {
CacheControl CacheControlNoStore
Response AssessmentResultHistoryPage
}
// GetCacheControl returns the value of CacheControl.
func (s *AssessmentResultHistoryPageHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *AssessmentResultHistoryPageHeaders) GetResponse() AssessmentResultHistoryPage {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *AssessmentResultHistoryPageHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *AssessmentResultHistoryPageHeaders) SetResponse(val AssessmentResultHistoryPage) {
s.Response = val
}
func (*AssessmentResultHistoryPageHeaders) listMyAssessmentResultsRes() {}
// Work sessions of the attempt, as the policy version limits them, for example two sessions within the
// time limit.
//
@@ -4817,6 +5184,97 @@ func NewAssessmentFullscreenExitSignalAssessmentSignalEvent(v AssessmentFullscre
return s
}
// State of the notice about the signals that are collected during a real assessment attempt. The
// acknowledgement is a record that the candidate was informed. It is not a consent, grants no purpose,
// and neither enables nor blocks signal storage; C3 remains the only consent that the signal operation
// checks.
// Ref: #/components/schemas/AssessmentSignalNotice
type AssessmentSignalNotice struct {
// The version the server currently requires the candidate to acknowledge.
NoticeVersion AssessmentSignalNoticeVersion `json:"notice_version"`
// True when the candidate acknowledged `notice_version`.
Acknowledged bool `json:"acknowledged"`
// Server time of the first acknowledgement of this version, or null.
AcknowledgedAt NilTimestamp `json:"acknowledged_at"`
}
// GetNoticeVersion returns the value of NoticeVersion.
func (s *AssessmentSignalNotice) GetNoticeVersion() AssessmentSignalNoticeVersion {
return s.NoticeVersion
}
// GetAcknowledged returns the value of Acknowledged.
func (s *AssessmentSignalNotice) GetAcknowledged() bool {
return s.Acknowledged
}
// GetAcknowledgedAt returns the value of AcknowledgedAt.
func (s *AssessmentSignalNotice) GetAcknowledgedAt() NilTimestamp {
return s.AcknowledgedAt
}
// SetNoticeVersion sets the value of NoticeVersion.
func (s *AssessmentSignalNotice) SetNoticeVersion(val AssessmentSignalNoticeVersion) {
s.NoticeVersion = val
}
// SetAcknowledged sets the value of Acknowledged.
func (s *AssessmentSignalNotice) SetAcknowledged(val bool) {
s.Acknowledged = val
}
// SetAcknowledgedAt sets the value of AcknowledgedAt.
func (s *AssessmentSignalNotice) SetAcknowledgedAt(val NilTimestamp) {
s.AcknowledgedAt = val
}
// The notice version the candidate was shown and acknowledged.
// Ref: #/components/schemas/AssessmentSignalNoticeAcknowledgement
type AssessmentSignalNoticeAcknowledgement struct {
NoticeVersion AssessmentSignalNoticeVersion `json:"notice_version"`
}
// GetNoticeVersion returns the value of NoticeVersion.
func (s *AssessmentSignalNoticeAcknowledgement) GetNoticeVersion() AssessmentSignalNoticeVersion {
return s.NoticeVersion
}
// SetNoticeVersion sets the value of NoticeVersion.
func (s *AssessmentSignalNoticeAcknowledgement) SetNoticeVersion(val AssessmentSignalNoticeVersion) {
s.NoticeVersion = val
}
// AssessmentSignalNoticeHeaders wraps AssessmentSignalNotice with response headers.
type AssessmentSignalNoticeHeaders struct {
CacheControl CacheControlNoStore
Response AssessmentSignalNotice
}
// GetCacheControl returns the value of CacheControl.
func (s *AssessmentSignalNoticeHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *AssessmentSignalNoticeHeaders) GetResponse() AssessmentSignalNotice {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *AssessmentSignalNoticeHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *AssessmentSignalNoticeHeaders) SetResponse(val AssessmentSignalNotice) {
s.Response = val
}
func (*AssessmentSignalNoticeHeaders) acknowledgeMyAssessmentSignalNoticeRes() {}
func (*AssessmentSignalNoticeHeaders) getMyAssessmentSignalNoticeRes() {}
type AssessmentSignalNoticeVersion int32
// Receipt for the submitted batch. It contains no signal details, score, review decision, threshold,
// or result band.
// Ref: #/components/schemas/AssessmentSignalReceipt
@@ -9452,6 +9910,14 @@ type GetMyAssessmentResultUnauthorized Problem
func (*GetMyAssessmentResultUnauthorized) getMyAssessmentResultRes() {}
type GetMyAssessmentSignalNoticeForbidden Problem
func (*GetMyAssessmentSignalNoticeForbidden) getMyAssessmentSignalNoticeRes() {}
type GetMyAssessmentSignalNoticeUnauthorized Problem
func (*GetMyAssessmentSignalNoticeUnauthorized) getMyAssessmentSignalNoticeRes() {}
type GetMyCardPreviewForbidden Problem
func (*GetMyCardPreviewForbidden) getMyCardPreviewRes() {}
@@ -11413,6 +11879,18 @@ func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent {
return s
}
type ListMyAssessmentResultsBadRequest Problem
func (*ListMyAssessmentResultsBadRequest) listMyAssessmentResultsRes() {}
type ListMyAssessmentResultsForbidden Problem
func (*ListMyAssessmentResultsForbidden) listMyAssessmentResultsRes() {}
type ListMyAssessmentResultsUnauthorized Problem
func (*ListMyAssessmentResultsUnauthorized) listMyAssessmentResultsRes() {}
type ListMyCardAccessHistoryBadRequest Problem
func (*ListMyCardAccessHistoryBadRequest) listMyCardAccessHistoryRes() {}
@@ -15727,6 +16205,96 @@ func (o NilAnonymousCardContent) Or(d AnonymousCardContent) AnonymousCardContent
return d
}
// NewNilAssessmentCategoryDecisionViewMethod returns new NilAssessmentCategoryDecisionViewMethod with value set to v.
func NewNilAssessmentCategoryDecisionViewMethod(v AssessmentCategoryDecisionViewMethod) NilAssessmentCategoryDecisionViewMethod {
return NilAssessmentCategoryDecisionViewMethod{
Value: v,
}
}
// NilAssessmentCategoryDecisionViewMethod is nullable AssessmentCategoryDecisionViewMethod.
type NilAssessmentCategoryDecisionViewMethod struct {
Value AssessmentCategoryDecisionViewMethod
Null bool
}
// SetTo sets value to v.
func (o *NilAssessmentCategoryDecisionViewMethod) SetTo(v AssessmentCategoryDecisionViewMethod) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilAssessmentCategoryDecisionViewMethod) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilAssessmentCategoryDecisionViewMethod) SetToNull() {
o.Null = true
var v AssessmentCategoryDecisionViewMethod
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilAssessmentCategoryDecisionViewMethod) Get() (v AssessmentCategoryDecisionViewMethod, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilAssessmentCategoryDecisionViewMethod) Or(d AssessmentCategoryDecisionViewMethod) AssessmentCategoryDecisionViewMethod {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilAssessmentCategoryDecisionViewSource returns new NilAssessmentCategoryDecisionViewSource with value set to v.
func NewNilAssessmentCategoryDecisionViewSource(v AssessmentCategoryDecisionViewSource) NilAssessmentCategoryDecisionViewSource {
return NilAssessmentCategoryDecisionViewSource{
Value: v,
}
}
// NilAssessmentCategoryDecisionViewSource is nullable AssessmentCategoryDecisionViewSource.
type NilAssessmentCategoryDecisionViewSource struct {
Value AssessmentCategoryDecisionViewSource
Null bool
}
// SetTo sets value to v.
func (o *NilAssessmentCategoryDecisionViewSource) SetTo(v AssessmentCategoryDecisionViewSource) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilAssessmentCategoryDecisionViewSource) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilAssessmentCategoryDecisionViewSource) SetToNull() {
o.Null = true
var v AssessmentCategoryDecisionViewSource
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilAssessmentCategoryDecisionViewSource) Get() (v AssessmentCategoryDecisionViewSource, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilAssessmentCategoryDecisionViewSource) Or(d AssessmentCategoryDecisionViewSource) AssessmentCategoryDecisionViewSource {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilAssessmentItem returns new NilAssessmentItem with value set to v.
func NewNilAssessmentItem(v AssessmentItem) NilAssessmentItem {
return NilAssessmentItem{
@@ -16087,6 +16655,51 @@ func (o NilBool) Or(d bool) bool {
return d
}
// NewNilCalibrationStatus returns new NilCalibrationStatus with value set to v.
func NewNilCalibrationStatus(v CalibrationStatus) NilCalibrationStatus {
return NilCalibrationStatus{
Value: v,
}
}
// NilCalibrationStatus is nullable CalibrationStatus.
type NilCalibrationStatus struct {
Value CalibrationStatus
Null bool
}
// SetTo sets value to v.
func (o *NilCalibrationStatus) SetTo(v CalibrationStatus) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilCalibrationStatus) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilCalibrationStatus) SetToNull() {
o.Null = true
var v CalibrationStatus
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilCalibrationStatus) Get() (v CalibrationStatus, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilCalibrationStatus) Or(d CalibrationStatus) CalibrationStatus {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilCandidateExperience returns new NilCandidateExperience with value set to v.
func NewNilCandidateExperience(v CandidateExperience) NilCandidateExperience {
return NilCandidateExperience{
@@ -19356,6 +19969,52 @@ func (s *OnboardingStep) UnmarshalText(data []byte) error {
}
}
// NewOptAssessmentCategoryDecisionView returns new OptAssessmentCategoryDecisionView with value set to v.
func NewOptAssessmentCategoryDecisionView(v AssessmentCategoryDecisionView) OptAssessmentCategoryDecisionView {
return OptAssessmentCategoryDecisionView{
Value: v,
Set: true,
}
}
// OptAssessmentCategoryDecisionView is optional AssessmentCategoryDecisionView.
type OptAssessmentCategoryDecisionView struct {
Value AssessmentCategoryDecisionView
Set bool
}
// IsSet returns true if OptAssessmentCategoryDecisionView was set.
func (o OptAssessmentCategoryDecisionView) IsSet() bool { return o.Set }
// Reset unsets value.
func (o *OptAssessmentCategoryDecisionView) Reset() {
var v AssessmentCategoryDecisionView
o.Value = v
o.Set = false
}
// SetTo sets value to v.
func (o *OptAssessmentCategoryDecisionView) SetTo(v AssessmentCategoryDecisionView) {
o.Set = true
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o OptAssessmentCategoryDecisionView) Get() (v AssessmentCategoryDecisionView, ok bool) {
if !o.Set {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o OptAssessmentCategoryDecisionView) Or(d AssessmentCategoryDecisionView) AssessmentCategoryDecisionView {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewOptCandidateSalaryCompatibility returns new OptCandidateSalaryCompatibility with value set to v.
func NewOptCandidateSalaryCompatibility(v CandidateSalaryCompatibility) OptCandidateSalaryCompatibility {
return OptCandidateSalaryCompatibility{
@@ -56,63 +56,66 @@ func findAuthorization(h http.Header, prefix string) (string, bool) {
// operationRolesSessionCookie is a private map storing roles per operation.
var operationRolesSessionCookie = map[string][]string{
AcceptMyInvitationOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyAssessmentAttemptOperation: []string{},
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyCardPreviewOperation: []string{},
GetMyConsentTextOperation: []string{},
GetMyInvitationOperation: []string{},
GetMyPrivacySettingsOperation: []string{},
GetMyProfileOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationCandidateCardOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
ListMyCardAccessHistoryOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyHiddenOrganizationsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMyPrivacyHistoryOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SearchOrganizationMatchesOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SetMyPublicationOperation: []string{},
SetMySearchStatusOperation: []string{},
StartMyAssessmentAttemptSessionOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UnhideOrganizationOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
AcceptMyInvitationOperation: []string{},
AcknowledgeMyAssessmentSignalNoticeOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GetCurrentAccountOperation: []string{},
GetCurrentSessionOperation: []string{},
GetMyAssessmentAttemptOperation: []string{},
GetMyAssessmentAvailabilityOperation: []string{},
GetMyAssessmentResultOperation: []string{},
GetMyAssessmentSignalNoticeOperation: []string{},
GetMyCardPreviewOperation: []string{},
GetMyConsentTextOperation: []string{},
GetMyInvitationOperation: []string{},
GetMyPrivacySettingsOperation: []string{},
GetMyProfileOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationCandidateCardOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
ListMyAssessmentResultsOperation: []string{},
ListMyCardAccessHistoryOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyHiddenOrganizationsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMyPrivacyHistoryOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SearchOrganizationMatchesOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SetMyPublicationOperation: []string{},
SetMySearchStatusOperation: []string{},
StartMyAssessmentAttemptSessionOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UnhideOrganizationOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
}
// GetRolesForSessionCookie returns the required roles for the given operation.
@@ -138,37 +141,38 @@ func GetRolesForSessionCookie(operation string) []string {
// operationRolesSessionCsrf is a private map storing roles per operation.
var operationRolesSessionCsrf = map[string][]string{
AcceptMyInvitationOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SearchOrganizationMatchesOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SetMyPublicationOperation: []string{},
SetMySearchStatusOperation: []string{},
StartMyAssessmentAttemptSessionOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UnhideOrganizationOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
AcceptMyInvitationOperation: []string{},
AcknowledgeMyAssessmentSignalNoticeOperation: []string{},
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
FinalizeMyAssessmentAttemptOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
LogoutOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RevokeMyConsentOperation: []string{},
RevokeMyOrganizationContactConsentOperation: []string{},
SaveMyProfileOperation: []string{},
SaveMyQuestionnaireOperation: []string{},
SearchOrganizationMatchesOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SetMyPublicationOperation: []string{},
SetMySearchStatusOperation: []string{},
StartMyAssessmentAttemptSessionOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UnhideOrganizationOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
WithdrawOrganizationInvitationOperation: []string{},
}
// GetRolesForSessionCsrf returns the required roles for the given operation.
@@ -64,6 +64,27 @@ type Handler interface {
//
// POST /api/v1/me/invitations/{invitation_id}/accept
AcceptMyInvitation(ctx context.Context, req *InvitationAcceptance, params AcceptMyInvitationParams) (AcceptMyInvitationRes, error)
// AcknowledgeMyAssessmentSignalNotice implements AcknowledgeMyAssessmentSignalNotice operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The body carries the notice version the candidate
// was shown. The server stores the acknowledgement for the account and that version; the response
// carries the server time of the first acknowledgement.
//
// The operation needs no Idempotency-Key: it is idempotent. Repeating it for an acknowledged version
// changes nothing, keeps the first time, and answers 200, so a retry after a lost response succeeds. A
// version other than the one the server requires answers 409 state_conflict and stores nothing; the
// client reads the notice again.
//
// The acknowledgement is not a consent. It does not grant, replace, or hide C3, and it does not affect
// the signal operation or any score, category, or quota. The body carries no signal, answer, or
// clipboard data.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account (403 forbidden), then the version (409).
//
// PUT /api/v1/me/assessment-signal-notice
AcknowledgeMyAssessmentSignalNotice(ctx context.Context, req *AssessmentSignalNoticeAcknowledgement) (AcknowledgeMyAssessmentSignalNoticeRes, error)
// CancelMyInvitation implements CancelMyInvitation operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -599,6 +620,30 @@ type Handler interface {
//
// GET /api/v1/me/assessment-attempts/{attempt_id}/result
GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error)
// GetMyAssessmentSignalNotice implements GetMyAssessmentSignalNotice operation.
//
// Requires the session cookie of a candidate account with a confirmed email; the candidate comes from
// the session. Returns the notice version that the server requires now and whether this candidate
// acknowledged it. The notice lists the signals that are collected during a real assessment attempt
// and states that images, sound, and clipboard contents are not collected. Client signals are the time
// away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode.
// Server signals are the response time of each item measured by the server, a change of network
// address during the attempt, parallel sessions, and the comparison of answers to variants of the same
// task by candidates. The server stores for these only one-way keyed digests: it stores no network
// address, no session token, and no answer text. Client signals are stored only while the C3 consent
// is current. The client shows it before a real attempt starts and does not start the attempt until
// the notice is acknowledged.
//
// The acknowledgement is stored on the server per account and notice version, so it survives a reload
// and a new browser. It is not a consent and never changes C3: the signal operation still requires a
// current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express
// training mode collects no signals and needs no acknowledgement.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or
// an unconfirmed email answers 403 forbidden.
//
// GET /api/v1/me/assessment-signal-notice
GetMyAssessmentSignalNotice(ctx context.Context) (GetMyAssessmentSignalNoticeRes, error)
// GetMyCardPreview implements GetMyCardPreview operation.
//
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
@@ -956,6 +1001,21 @@ type Handler interface {
//
// PUT /api/v1/me/privacy/hidden-organizations/{org_id}
HideOrganization(ctx context.Context, params HideOrganizationParams) (HideOrganizationRes, error)
// ListMyAssessmentResults implements ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
// candidate, newest first by decided_at and attempt_id. demo_express training results never appear.
// The cursor is opaque and bound to this candidate and listing; a malformed or foreign cursor returns
// 400 validation_failed.
//
// A v2 result includes the category decision captured when that attempt ended, including the confirmed
// grade then in force. Legacy v1 results omit category_decision because a later category must not be
// projected backward. Later policy, bank, review, or category changes do not alter either result.
// Employers cannot read this history; their separate projection contains only the current permitted
// category and no answers.
//
// GET /api/v1/me/assessment-results
ListMyAssessmentResults(ctx context.Context, params ListMyAssessmentResultsParams) (ListMyAssessmentResultsRes, error)
// ListMyCardAccessHistory implements ListMyCardAccessHistory operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
@@ -72,6 +72,30 @@ func (UnimplementedHandler) AcceptMyInvitation(ctx context.Context, req *Invitat
return r, ht.ErrNotImplemented
}
// AcknowledgeMyAssessmentSignalNotice implements AcknowledgeMyAssessmentSignalNotice operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The body carries the notice version the candidate
// was shown. The server stores the acknowledgement for the account and that version; the response
// carries the server time of the first acknowledgement.
//
// The operation needs no Idempotency-Key: it is idempotent. Repeating it for an acknowledged version
// changes nothing, keeps the first time, and answers 200, so a retry after a lost response succeeds. A
// version other than the one the server requires answers 409 state_conflict and stores nothing; the
// client reads the notice again.
//
// The acknowledgement is not a consent. It does not grant, replace, or hide C3, and it does not affect
// the signal operation or any score, category, or quota. The body carries no signal, answer, or
// clipboard data.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account (403 forbidden), then the version (409).
//
// PUT /api/v1/me/assessment-signal-notice
func (UnimplementedHandler) AcknowledgeMyAssessmentSignalNotice(ctx context.Context, req *AssessmentSignalNoticeAcknowledgement) (r AcknowledgeMyAssessmentSignalNoticeRes, _ error) {
return r, ht.ErrNotImplemented
}
// CancelMyInvitation implements CancelMyInvitation operation.
//
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
@@ -655,6 +679,33 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge
return r, ht.ErrNotImplemented
}
// GetMyAssessmentSignalNotice implements GetMyAssessmentSignalNotice operation.
//
// Requires the session cookie of a candidate account with a confirmed email; the candidate comes from
// the session. Returns the notice version that the server requires now and whether this candidate
// acknowledged it. The notice lists the signals that are collected during a real assessment attempt
// and states that images, sound, and clipboard contents are not collected. Client signals are the time
// away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode.
// Server signals are the response time of each item measured by the server, a change of network
// address during the attempt, parallel sessions, and the comparison of answers to variants of the same
// task by candidates. The server stores for these only one-way keyed digests: it stores no network
// address, no session token, and no answer text. Client signals are stored only while the C3 consent
// is current. The client shows it before a real attempt starts and does not start the attempt until
// the notice is acknowledged.
//
// The acknowledgement is stored on the server per account and notice version, so it survives a reload
// and a new browser. It is not a consent and never changes C3: the signal operation still requires a
// current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express
// training mode collects no signals and needs no acknowledgement.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or
// an unconfirmed email answers 403 forbidden.
//
// GET /api/v1/me/assessment-signal-notice
func (UnimplementedHandler) GetMyAssessmentSignalNotice(ctx context.Context) (r GetMyAssessmentSignalNoticeRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetMyCardPreview implements GetMyCardPreview operation.
//
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
@@ -1057,6 +1108,24 @@ func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrg
return r, ht.ErrNotImplemented
}
// ListMyAssessmentResults implements ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
// candidate, newest first by decided_at and attempt_id. demo_express training results never appear.
// The cursor is opaque and bound to this candidate and listing; a malformed or foreign cursor returns
// 400 validation_failed.
//
// A v2 result includes the category decision captured when that attempt ended, including the confirmed
// grade then in force. Legacy v1 results omit category_decision because a later category must not be
// projected backward. Later policy, bank, review, or category changes do not alter either result.
// Employers cannot read this history; their separate projection contains only the current permitted
// category and no answers.
//
// GET /api/v1/me/assessment-results
func (UnimplementedHandler) ListMyAssessmentResults(ctx context.Context, params ListMyAssessmentResultsParams) (r ListMyAssessmentResultsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMyCardAccessHistory implements ListMyCardAccessHistory operation.
//
// Requires the session cookie of a candidate account. The candidate comes from the session, so the
@@ -155,6 +155,38 @@ func (s AccountScenario) Validate() error {
}
}
func (s *AcknowledgeMyAssessmentSignalNoticeBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *AcknowledgeMyAssessmentSignalNoticeConflict) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *AcknowledgeMyAssessmentSignalNoticeForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *AcknowledgeMyAssessmentSignalNoticeUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *AnonymousCardContent) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -717,6 +749,152 @@ func (s *AssessmentAvailabilityHeaders) Validate() error {
return nil
}
func (s *AssessmentCategoryDecisionView) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Status.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "status",
Error: err,
})
}
if err := func() error {
if value, ok := s.PreviousConfirmedGrade.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "previous_confirmed_grade",
Error: err,
})
}
if err := func() error {
if value, ok := s.CurrentConfirmedGrade.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "current_confirmed_grade",
Error: err,
})
}
if err := func() error {
if value, ok := s.Method.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "method",
Error: err,
})
}
if err := func() error {
if value, ok := s.Source.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "source",
Error: err,
})
}
if err := func() error {
if value, ok := s.CalibrationStatus.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "calibration_status",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s AssessmentCategoryDecisionViewMethod) Validate() error {
switch s {
case "demo_basic_pass_mark":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s AssessmentCategoryDecisionViewSource) Validate() error {
switch s {
case "synthetic_demo":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s AssessmentCategoryDecisionViewStatus) Validate() error {
switch s {
case "not_eligible":
return nil
case "not_confirmed":
return nil
case "assigned":
return nil
case "unchanged":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *AssessmentClipboardSignal) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -1214,6 +1392,24 @@ func (s *AssessmentCorrectiveResult) Validate() error {
Error: err,
})
}
if err := func() error {
if value, ok := s.CategoryDecision.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "category_decision",
Error: err,
})
}
if err := func() error {
if value, ok := s.Strength.Get(); ok {
if err := func() error {
@@ -3470,6 +3666,24 @@ func (s *AssessmentQualifiedResult) Validate() error {
Error: err,
})
}
if err := func() error {
if value, ok := s.CategoryDecision.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "category_decision",
Error: err,
})
}
if err := func() error {
if value, ok := s.Strength.Get(); ok {
if err := func() error {
@@ -3730,6 +3944,23 @@ func (s AssessmentRealMode) Validate() error {
}
}
func (s AssessmentRealResult) Validate() error {
switch s.Type {
case AssessmentQualifiedResultAssessmentRealResult:
if err := s.AssessmentQualifiedResult.Validate(); err != nil {
return err
}
return nil
case AssessmentCorrectiveResultAssessmentRealResult:
if err := s.AssessmentCorrectiveResult.Validate(); err != nil {
return err
}
return nil
default:
return errors.Errorf("invalid type %q", s.Type)
}
}
func (s AssessmentResult) Validate() error {
switch s.Type {
case AssessmentQualifiedResultAssessmentResult:
@@ -3786,6 +4017,99 @@ func (s *AssessmentResultHeaders) Validate() error {
return nil
}
func (s *AssessmentResultHistoryPage) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if s.Items == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 50,
MaxLengthSet: true,
}).ValidateLength(len(s.Items)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Items {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "items",
Error: err,
})
}
if err := func() error {
if err := s.Page.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "page",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *AssessmentResultHistoryPageHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *AssessmentSessions) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -3931,6 +4255,104 @@ func (s AssessmentSignalEvent) Validate() error {
}
}
func (s *AssessmentSignalNotice) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.NoticeVersion.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "notice_version",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *AssessmentSignalNoticeAcknowledgement) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.NoticeVersion.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "notice_version",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *AssessmentSignalNoticeHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s AssessmentSignalNoticeVersion) Validate() error {
alias := (int32)(s)
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 2147483647,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(alias)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}
func (s *AssessmentSignalReceipt) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -8765,6 +9187,22 @@ func (s *GetMyAssessmentResultUnauthorized) Validate() error {
return nil
}
func (s *GetMyAssessmentSignalNoticeForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GetMyAssessmentSignalNoticeUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *GetMyCardPreviewForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -10412,6 +10850,30 @@ func (s ItemContent) Validate() error {
}
}
func (s *ListMyAssessmentResultsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyAssessmentResultsForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyAssessmentResultsUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyCardAccessHistoryBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -0,0 +1,127 @@
package httpadapter
import (
"slices"
"strings"
"testing"
"lincodex/backend/internal/adapter/primary/http/api"
)
// reviewBandTerms are fragments of the names that would carry the manual-review
// band, its reasons, or the facts behind it. The band is read by an operator
// command only; no HTTP operation, whoever calls it, may declare any of them.
var reviewBandTerms = []string{
"review_band", "integrity", "signal_review", "attempt_review", "reviewband", "answer_fingerprint",
"fingerprint", "duplicate_answer", "duplicate_evidence", "matched_integer", "matched_sequence",
"parallel_session", "parallel_alternation", "address_change", "fast_answers", "deviating_answers",
"origin_mark", "network_digest", "session_digest", "evidence_bits",
}
// declaredPropertyNames collects the names under every "properties" key of a
// decoded contract value.
func declaredPropertyNames(value any, found map[string]bool) {
switch typed := value.(type) {
case map[string]any:
for key, child := range typed {
if properties, ok := child.(map[string]any); ok && key == "properties" {
for name := range properties {
found[name] = true
}
}
declaredPropertyNames(child, found)
}
case []any:
for _, child := range typed {
declaredPropertyNames(child, found)
}
}
}
// declaredEnumValues collects every string in an "enum" array.
func declaredEnumValues(value any, found map[string]bool) {
switch typed := value.(type) {
case map[string]any:
for key, child := range typed {
if values, ok := child.([]any); ok && key == "enum" {
for _, entry := range values {
if text, ok := entry.(string); ok {
found[text] = true
}
}
}
declaredEnumValues(child, found)
}
case []any:
for _, child := range typed {
declaredEnumValues(child, found)
}
}
}
// No operation reaches the review band. Candidate reads, employer reads, and
// every other operation are walked through all references: request bodies,
// responses, parameters, and headers. The band stays server-side until staff
// roles exist; the operator command is the only reader.
func TestNoOperationReachesTheAssessmentReviewBand(t *testing.T) {
spec := parsePublicContract(t)
index := componentsIndex(t, spec)
if len(spec.Paths) == 0 {
t.Fatal("the contract declares no path")
}
operations := 0
for path, item := range spec.Paths {
operations++
value := mustJSONValue(t, item)
properties, enums := map[string]bool{}, map[string]bool{}
declaredPropertyNames(value, properties)
declaredEnumValues(value, enums)
for name := range reachableSchemas(index, value) {
lowered := strings.ToLower(name)
for _, term := range []string{"reviewband", "signalreview", "attemptreview", "assessmentreview", "fingerprint", "originmark"} {
if strings.Contains(lowered, term) {
t.Errorf("%s reaches the schema %s", path, name)
}
}
component := mustJSONValue(t, index["#/components/schemas/"+name])
declaredPropertyNames(component, properties)
declaredEnumValues(component, enums)
}
for name := range properties {
for _, term := range reviewBandTerms {
if strings.Contains(strings.ToLower(name), term) {
t.Errorf("%s declares the property %q", path, name)
}
}
if name == "band" || name == "reasons" {
t.Errorf("%s declares the property %q", path, name)
}
}
if enums["attention"] && enums["review"] {
t.Errorf("%s declares the band values attention and review", path)
}
}
if operations < 10 {
t.Fatalf("walked only %d paths, want the whole contract", operations)
}
}
// The walk is not vacuous: it reaches the signal receipt, which carries
// counts and a status and nothing of the band.
func TestSignalReceiptDeclaresNoBandAndIsReachable(t *testing.T) {
spec := parsePublicContract(t)
index := componentsIndex(t, spec)
operation := operationByID(t, spec, "RecordMyAssessmentAttemptSignals")
reached := reachableSchemas(index, mustJSONValue(t, operation))
if !reached["AssessmentSignalReceipt"] {
t.Fatalf("the signal operation reaches %v, want AssessmentSignalReceipt", reached)
}
receipt := spec.Components.Schemas["AssessmentSignalReceipt"]
if got, want := propertyNames(receipt), []string{"accepted_events", "received_at", "status"}; !slices.Equal(got, want) {
t.Errorf("AssessmentSignalReceipt properties = %v, want %v", got, want)
}
if receipt.AdditionalProperties.Bool == nil || *receipt.AdditionalProperties.Bool {
t.Error("AssessmentSignalReceipt accepts unknown properties")
}
assertNoJSONFields(t, api.AssessmentSignalReceipt{}, []string{"band", "review", "reasons", "attention"})
}
@@ -208,7 +208,7 @@ func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
result, err := operations.SubmitAnswer(ctx, assessmentusecase.SubmitAttemptAnswerCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
ItemID: uuid.UUID(request.ItemID), ExpectedVersion: int64(request.ExpectedVersion),
IdempotencyKey: params.IdempotencyKey, Answer: answer,
IdempotencyKey: params.IdempotencyKey, Answer: answer, Origin: assessmentRequestOrigin(ctx),
})
if err != nil {
return assessmentAnswerFailure(ctx, err)
@@ -0,0 +1,18 @@
package v1
import (
"context"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
// assessmentRequestOrigin hands the authenticated session and the limiter key
// of the client address to the server signals. The usecase turns them into
// keyed digests; neither value is stored or logged.
func assessmentRequestOrigin(ctx context.Context) assessmentusecase.RequestOrigin {
session, ok := sessionFromContext(ctx)
if !ok {
return assessmentusecase.RequestOrigin{}
}
return assessmentusecase.RequestOrigin{SessionID: session.SessionID, ClientKey: clientKey(ctx)}
}
@@ -23,6 +23,7 @@ type AssessmentSignalOperations interface {
// It never logs or returns event details.
type AssessmentSignalHandler struct {
operations AssessmentSignalOperations
notice AssessmentSignalNoticeOperations
}
func NewAssessmentSignalHandler(operations AssessmentSignalOperations) *AssessmentSignalHandler {
@@ -61,7 +62,7 @@ func (handler *AssessmentSignalHandler) RecordMyAssessmentAttemptSignals(
}
receipt, err := handler.operations.RecordSignals(ctx, assessmentusecase.RecordSignalsCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
IdempotencyKey: params.IdempotencyKey, Events: events,
IdempotencyKey: params.IdempotencyKey, Events: events, Origin: assessmentRequestOrigin(ctx),
})
if err != nil {
return signalFailure(ctx, err)
@@ -0,0 +1,103 @@
package v1
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
// AssessmentSignalNoticeOperations reads and records the acknowledgement of the
// notice about collected assessment signals.
type AssessmentSignalNoticeOperations interface {
GetSignalNotice(ctx context.Context, actorID uuid.UUID) (assessmentusecase.SignalNoticeState, error)
AcknowledgeSignalNotice(ctx context.Context, actorID uuid.UUID, version int32) (assessmentusecase.SignalNoticeState, error)
}
// WithNotice serves the signal notice operations next to the signal batches.
// Without it those operations answer as not implemented.
func (handler *AssessmentSignalHandler) WithNotice(operations AssessmentSignalNoticeOperations) *AssessmentSignalHandler {
if operations == nil {
panic("v1.AssessmentSignalHandler.WithNotice - notice operations must not be nil")
}
handler.notice = operations
return handler
}
func (handler *Handler) GetMyAssessmentSignalNotice(ctx context.Context) (api.GetMyAssessmentSignalNoticeRes, error) {
if handler.assessmentSignals == nil || handler.assessmentSignals.notice == nil {
return handler.UnimplementedHandler.GetMyAssessmentSignalNotice(ctx)
}
return handler.assessmentSignals.GetMyAssessmentSignalNotice(ctx)
}
func (handler *Handler) AcknowledgeMyAssessmentSignalNotice(
ctx context.Context,
request *api.AssessmentSignalNoticeAcknowledgement,
) (api.AcknowledgeMyAssessmentSignalNoticeRes, error) {
if handler.assessmentSignals == nil || handler.assessmentSignals.notice == nil {
return handler.UnimplementedHandler.AcknowledgeMyAssessmentSignalNotice(ctx, request)
}
return handler.assessmentSignals.AcknowledgeMyAssessmentSignalNotice(ctx, request)
}
func (handler *AssessmentSignalHandler) GetMyAssessmentSignalNotice(ctx context.Context) (api.GetMyAssessmentSignalNoticeRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetMyAssessmentSignalNoticeUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
state, err := handler.notice.GetSignalNotice(ctx, principal.UserID)
if err != nil {
if isSignalNoticeForbidden(err) {
return (*api.GetMyAssessmentSignalNoticeForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
return nil, err
}
return signalNoticeResponse(state), nil
}
func (handler *AssessmentSignalHandler) AcknowledgeMyAssessmentSignalNotice(
ctx context.Context,
request *api.AssessmentSignalNoticeAcknowledgement,
) (api.AcknowledgeMyAssessmentSignalNoticeRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.AcknowledgeMyAssessmentSignalNoticeUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if request == nil {
return (*api.AcknowledgeMyAssessmentSignalNoticeBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response,
), nil
}
state, err := handler.notice.AcknowledgeSignalNotice(ctx, principal.UserID, int32(request.NoticeVersion))
switch {
case err == nil:
return signalNoticeResponse(state), nil
case isSignalNoticeForbidden(err):
return (*api.AcknowledgeMyAssessmentSignalNoticeForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrSignalNoticeVersionMismatch):
return (*api.AcknowledgeMyAssessmentSignalNoticeConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
default:
return nil, err
}
}
func isSignalNoticeForbidden(err error) bool {
return errors.Is(err, assessmentusecase.ErrAttemptForbidden) || errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified)
}
func signalNoticeResponse(state assessmentusecase.SignalNoticeState) *api.AssessmentSignalNoticeHeaders {
notice := api.AssessmentSignalNotice{
NoticeVersion: api.AssessmentSignalNoticeVersion(state.Version), Acknowledged: state.Acknowledged,
}
notice.AcknowledgedAt.SetToNull()
if state.Acknowledged {
notice.AcknowledgedAt.SetTo(api.Timestamp(state.AcknowledgedAt.UTC().Truncate(time.Microsecond)))
}
return &api.AssessmentSignalNoticeHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: notice}
}
@@ -0,0 +1,102 @@
package v1
import (
"context"
"fmt"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
assessmentusecase "lincodex/backend/internal/usecase/assessment"
)
type signalNoticeStub struct {
state assessmentusecase.SignalNoticeState
err error
version int32
calls int
}
func (stub *signalNoticeStub) GetSignalNotice(context.Context, uuid.UUID) (assessmentusecase.SignalNoticeState, error) {
stub.calls++
return stub.state, stub.err
}
func (stub *signalNoticeStub) AcknowledgeSignalNotice(
_ context.Context,
_ uuid.UUID,
version int32,
) (assessmentusecase.SignalNoticeState, error) {
stub.calls++
stub.version = version
return stub.state, stub.err
}
func TestSignalNoticeHandlerReturnsNullTimeUntilAcknowledged(t *testing.T) {
stub := &signalNoticeStub{state: assessmentusecase.SignalNoticeState{Version: 1}}
handler := NewAssessmentSignalHandler(&assessmentSignalOperationsStub{}).WithNotice(stub)
result, err := handler.GetMyAssessmentSignalNotice(principalForTest(uuid.New()))
if err != nil {
t.Fatalf("GetMyAssessmentSignalNotice() error = %v", err)
}
response, ok := result.(*api.AssessmentSignalNoticeHeaders)
if !ok {
t.Fatalf("result = %T, want notice headers", result)
}
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.Acknowledged ||
!response.Response.AcknowledgedAt.Null || response.Response.NoticeVersion != 1 {
t.Fatalf("notice response = %+v", response)
}
}
func TestSignalNoticeHandlerAcknowledgesTheSentVersion(t *testing.T) {
at := time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC)
stub := &signalNoticeStub{state: assessmentusecase.SignalNoticeState{Version: 1, Acknowledged: true, AcknowledgedAt: at}}
handler := NewAssessmentSignalHandler(&assessmentSignalOperationsStub{}).WithNotice(stub)
result, err := handler.AcknowledgeMyAssessmentSignalNotice(
principalForTest(uuid.New()), &api.AssessmentSignalNoticeAcknowledgement{NoticeVersion: 1},
)
if err != nil {
t.Fatalf("AcknowledgeMyAssessmentSignalNotice() error = %v", err)
}
response, ok := result.(*api.AssessmentSignalNoticeHeaders)
if !ok || !response.Response.Acknowledged || response.Response.AcknowledgedAt.Null ||
!time.Time(response.Response.AcknowledgedAt.Value).Equal(at) || stub.version != 1 {
t.Fatalf("result = %#v, sent version %d", result, stub.version)
}
}
func TestSignalNoticeHandlerMapsFailuresWithoutLeakingDetails(t *testing.T) {
cases := []struct {
name string
err error
want any
}{
{"version", assessmentusecase.ErrSignalNoticeVersionMismatch, &api.AcknowledgeMyAssessmentSignalNoticeConflict{}},
{"employer", assessmentusecase.ErrAttemptForbidden, &api.AcknowledgeMyAssessmentSignalNoticeForbidden{}},
{"unverified", assessmentusecase.ErrAttemptEmailNotVerified, &api.AcknowledgeMyAssessmentSignalNoticeForbidden{}},
}
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
handler := NewAssessmentSignalHandler(&assessmentSignalOperationsStub{}).WithNotice(&signalNoticeStub{err: testCase.err})
result, err := handler.AcknowledgeMyAssessmentSignalNotice(
principalForTest(uuid.New()), &api.AssessmentSignalNoticeAcknowledgement{NoticeVersion: 1},
)
if err != nil {
t.Fatalf("error = %v, want a typed problem response", err)
}
if gotType, wantType := fmt.Sprintf("%T", result), fmt.Sprintf("%T", testCase.want); gotType != wantType {
t.Fatalf("result type = %s, want %s", gotType, wantType)
}
})
}
}
func TestSignalNoticeIsNotImplementedWithoutOperations(t *testing.T) {
handler := &Handler{assessmentSignals: NewAssessmentSignalHandler(&assessmentSignalOperationsStub{})}
if _, err := handler.GetMyAssessmentSignalNotice(principalForTest(uuid.New())); err == nil {
t.Fatal("GetMyAssessmentSignalNotice() without notice operations must not answer as implemented")
}
}
@@ -0,0 +1,74 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/port/outbound"
)
var (
_ outbound.AssessmentSignalNoticeRepositories = (*UnitOfWork)(nil)
_ outbound.AssessmentSignalNoticeRepository = assessmentSignalNoticeRepository{}
)
func (unit *UnitOfWork) AssessmentSignalNotices() outbound.AssessmentSignalNoticeRepository {
return assessmentSignalNoticeRepository{queries: unit.queries}
}
type assessmentSignalNoticeRepository struct {
queries *sqlc.Queries
}
func (repository assessmentSignalNoticeRepository) Get(
ctx context.Context,
userID uuid.UUID,
version int32,
) (time.Time, error) {
const location = "assessmentSignalNoticeRepository.Get"
if userID == uuid.Nil || version < 1 {
return time.Time{}, fmt.Errorf("%s - user and notice version are required", location)
}
stored, err := repository.queries.GetAssessmentSignalNoticeAcknowledgement(ctx, sqlc.GetAssessmentSignalNoticeAcknowledgementParams{
UserID: pgUUID(userID), NoticeVersion: version,
})
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, fmt.Errorf("%s - read acknowledgement: %w", location, outbound.ErrAssessmentSignalNoticeNotAcknowledged)
}
if err != nil {
return time.Time{}, fmt.Errorf("%s - read acknowledgement: %w", location, mapAssessmentError(err))
}
return acknowledgementTime(location, stored)
}
func (repository assessmentSignalNoticeRepository) Acknowledge(
ctx context.Context,
userID uuid.UUID,
version int32,
at time.Time,
) (time.Time, error) {
const location = "assessmentSignalNoticeRepository.Acknowledge"
if userID == uuid.Nil || version < 1 || at.IsZero() {
return time.Time{}, fmt.Errorf("%s - user, notice version, and time are required", location)
}
if err := repository.queries.InsertAssessmentSignalNoticeAcknowledgement(ctx, sqlc.InsertAssessmentSignalNoticeAcknowledgementParams{
UserID: pgUUID(userID), NoticeVersion: version, AcknowledgedAt: pgTime(at),
}); err != nil {
return time.Time{}, fmt.Errorf("%s - insert acknowledgement: %w", location, mapAssessmentError(err))
}
return repository.Get(ctx, userID, version)
}
func acknowledgementTime(location string, stored pgtype.Timestamptz) (time.Time, error) {
if !stored.Valid || stored.Time.IsZero() {
return time.Time{}, fmt.Errorf("%s - stored acknowledgement time is missing", location)
}
return stored.Time.UTC(), nil
}
@@ -0,0 +1,299 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func (repository assessmentSignalRepository) SaveAnswerObservation(
ctx context.Context,
observation domain.AssessmentAnswerObservation,
) error {
const location = "assessmentSignalRepository.SaveAnswerObservation"
if err := observation.Validate(); err != nil {
return fmt.Errorf("%s - observation is invalid: %w", location, err)
}
if err := repository.queries.InsertAssessmentAnswerObservation(ctx, sqlc.InsertAssessmentAnswerObservationParams{
AttemptID: pgUUID(observation.AttemptID.UUID()), ItemInstanceID: pgUUID(observation.ItemInstanceID),
UserID: pgUUID(observation.UserID), FamilyID: pgUUID(uuid.UUID(observation.FamilyID)),
// The seed is stored as the two's-complement image of the uint64, which
// keeps equality and inequality exact.
VariantSeed: int64(observation.Seed), //nolint:gosec // The two's-complement image of the seed keeps equality exact.
AnswerFormat: observation.AnswerFormat,
AnswerFingerprint: observation.Fingerprint[:], KeyVersion: observation.KeyVersion,
ElapsedMs: observation.ElapsedMS, MeasuredFromAnswer: observation.MeasuredFromAnswer,
ObservedAt: pgTime(observation.ObservedAt),
}); err != nil {
return fmt.Errorf("%s - insert observation: %w", location, mapAssessmentError(err))
}
return nil
}
func (repository assessmentSignalRepository) SaveOriginMark(ctx context.Context, mark domain.AssessmentOriginMark) error {
const location = "assessmentSignalRepository.SaveOriginMark"
if err := mark.Validate(); err != nil {
return fmt.Errorf("%s - mark is invalid: %w", location, err)
}
var network []byte
if !mark.NetworkDigest.IsZero() {
network = mark.NetworkDigest[:]
}
if err := repository.queries.InsertAssessmentOriginMark(ctx, sqlc.InsertAssessmentOriginMarkParams{
ID: pgUUID(mark.ID), AttemptID: pgUUID(mark.AttemptID.UUID()), Source: string(mark.Source),
ObservedAt: pgTime(mark.ObservedAt), SessionDigest: mark.SessionDigest[:], NetworkDigest: network,
KeyVersion: mark.KeyVersion,
}); err != nil {
return fmt.Errorf("%s - insert origin mark: %w", location, mapAssessmentError(err))
}
return nil
}
func (repository assessmentSignalRepository) LastOriginMark(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
) (domain.AssessmentOriginMark, bool, error) {
const location = "assessmentSignalRepository.LastOriginMark"
if attemptID.IsZero() {
return domain.AssessmentOriginMark{}, false, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview)
}
row, err := repository.queries.GetLastAssessmentOriginMark(ctx, pgUUID(attemptID.UUID()))
if errors.Is(err, pgx.ErrNoRows) {
return domain.AssessmentOriginMark{}, false, nil
}
if err != nil {
return domain.AssessmentOriginMark{}, false, fmt.Errorf("%s - read last mark: %w", location, mapAssessmentError(err))
}
mark, err := restoreAssessmentOriginMark(row)
if err != nil {
return domain.AssessmentOriginMark{}, false, fmt.Errorf("%s - restore mark: %w", location, err)
}
return mark, true, nil
}
func (repository assessmentSignalRepository) ReviewInputs(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
) (outbound.AssessmentReviewInputs, error) {
const location = "assessmentSignalRepository.ReviewInputs"
if attemptID.IsZero() {
return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview)
}
id := pgUUID(attemptID.UUID())
times, err := repository.queries.ListAssessmentAnswerTimes(ctx, id)
if err != nil {
return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - list answer times: %w", location, mapAssessmentError(err))
}
marks, err := repository.queries.ListAssessmentOriginMarks(ctx, id)
if err != nil {
return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - list origin marks: %w", location, mapAssessmentError(err))
}
totals, err := repository.queries.GetAssessmentClientSignalTotals(ctx, id)
if err != nil {
return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - total client signals: %w", location, mapAssessmentError(err))
}
inputs := outbound.AssessmentReviewInputs{
ClientFocusLossMS: totals.FocusLossMs, ClientClipboardCount: totals.ClipboardEvents,
ClientFullscreenExit: totals.FullscreenExits,
}
for _, row := range times {
inputs.Answers = append(inputs.Answers, domain.AssessmentResponseSample{
AnswerFormat: row.AnswerFormat, ElapsedMS: row.ElapsedMs, MeasuredFromAnswer: row.MeasuredFromAnswer,
})
}
for _, row := range marks {
mark, err := restoreAssessmentOriginMark(row)
if err != nil {
return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - restore origin mark: %w", location, err)
}
inputs.Marks = append(inputs.Marks, mark)
}
return inputs, nil
}
func restoreAssessmentOriginMark(row sqlc.AssessmentAttemptOriginMark) (domain.AssessmentOriginMark, error) {
if !row.ID.Valid || !row.AttemptID.Valid || !row.ObservedAt.Valid || len(row.SessionDigest) != len(domain.AssessmentDigest{}) ||
len(row.NetworkDigest) != 0 && len(row.NetworkDigest) != len(domain.AssessmentDigest{}) {
return domain.AssessmentOriginMark{}, domain.ErrInvalidAssessmentReview
}
mark := domain.AssessmentOriginMark{
ID: uuid.UUID(row.ID.Bytes), AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes),
Source: domain.AssessmentOriginSource(row.Source), ObservedAt: row.ObservedAt.Time.UTC(),
KeyVersion: row.KeyVersion,
}
copy(mark.SessionDigest[:], row.SessionDigest)
copy(mark.NetworkDigest[:], row.NetworkDigest)
if err := mark.Validate(); err != nil {
return domain.AssessmentOriginMark{}, err
}
return mark, nil
}
func (repository assessmentSignalRepository) DuplicatePairs(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
query outbound.AssessmentDuplicateQuery,
) ([]outbound.AssessmentDuplicatePair, error) {
const location = "assessmentSignalRepository.DuplicatePairs"
if attemptID.IsZero() || query.Limit < 1 || query.IntegerCapBits < 1 || query.SequenceCapBits < 1 || query.MinBits < 0 ||
query.EndedOnly && query.Now.IsZero() {
return nil, fmt.Errorf("%s - attempt, caps, and bounds are required: %w", location, domain.ErrInvalidAssessmentReview)
}
rows, err := repository.queries.ListAssessmentDuplicatePairs(ctx, sqlc.ListAssessmentDuplicatePairsParams{
AttemptID: pgUUID(attemptID.UUID()), IntegerCapBits: float64(query.IntegerCapBits),
SequenceCapBits: float64(query.SequenceCapBits), MinBits: float64(query.MinBits),
EndedOnly: query.EndedOnly, Now: pgTime(query.Now), RowLimit: query.Limit,
})
if err != nil {
return nil, fmt.Errorf("%s - list pairs: %w", location, mapAssessmentError(err))
}
pairs := make([]outbound.AssessmentDuplicatePair, 0, len(rows))
for _, row := range rows {
if !row.OtherAttemptID.Valid || !row.ProductPolicyVersionID.Valid || row.EvidenceBits < 0 {
return nil, fmt.Errorf("%s - stored pair is incomplete: %w", location, domain.ErrInvalidAssessmentReview)
}
pairs = append(pairs, outbound.AssessmentDuplicatePair{
AttemptID: domain.AssessmentAttemptID(row.OtherAttemptID.Bytes),
PolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
EvidenceBits: row.EvidenceBits, IntegerItems: row.IntegerItems, SequenceItems: row.SequenceItems,
})
}
return pairs, nil
}
func (repository assessmentSignalRepository) ReviewSubject(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
) (domain.PolicyVersionID, bool, error) {
const location = "assessmentSignalRepository.ReviewSubject"
if attemptID.IsZero() {
return domain.PolicyVersionID{}, false, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview)
}
policyID, err := repository.queries.GetAssessmentReviewSubject(ctx, pgUUID(attemptID.UUID()))
if errors.Is(err, pgx.ErrNoRows) {
return domain.PolicyVersionID{}, false, nil
}
if err != nil {
return domain.PolicyVersionID{}, false, fmt.Errorf("%s - read attempt: %w", location, mapAssessmentError(err))
}
if !policyID.Valid {
return domain.PolicyVersionID{}, false, fmt.Errorf("%s - stored policy is missing: %w", location, domain.ErrInvalidAssessmentReview)
}
return domain.PolicyVersionID(policyID.Bytes), true, nil
}
func (repository assessmentSignalRepository) LockReview(ctx context.Context, attemptID domain.AssessmentAttemptID) error {
const location = "assessmentSignalRepository.LockReview"
if attemptID.IsZero() {
return fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview)
}
if err := repository.queries.LockAssessmentReview(ctx, attemptID.String()); err != nil {
return fmt.Errorf("%s - take advisory lock: %w", location, mapAssessmentError(err))
}
return nil
}
func (repository assessmentSignalRepository) SaveReview(ctx context.Context, review domain.AssessmentAttemptReview) error {
const location = "assessmentSignalRepository.SaveReview"
if err := review.Validate(); err != nil {
return fmt.Errorf("%s - review is invalid: %w", location, err)
}
measures := review.Measures
reasons := make([]string, 0, len(review.Outcome.Reasons))
for _, reason := range review.Outcome.Reasons {
reasons = append(reasons, string(reason))
}
if err := repository.queries.UpsertAssessmentAttemptReview(ctx, sqlc.UpsertAssessmentAttemptReviewParams{
AttemptID: pgUUID(review.AttemptID.UUID()), PolicyVersionID: pgUUID(uuid.UUID(review.PolicyVersionID)),
Band: string(review.Outcome.Band), Reasons: reasons, AnsweredItems: measures.AnsweredItems,
FastAnswers: measures.FastAnswers, DeviatingAnswers: measures.DeviatingAnswers,
ParallelAlternations: measures.ParallelAlternations, ExtraNetworks: measures.ExtraNetworks,
MatchedIntegerItems: measures.MatchedIntegerItems, MatchedSequenceItems: measures.MatchedSequenceItems,
DuplicateEvidenceBits: measures.DuplicateEvidenceBits, ClientFocusLossMs: measures.ClientFocusLossMS,
ClientClipboardEvents: measures.ClientClipboardEvents, ClientFullscreenExits: measures.ClientFullscreenExits,
}); err != nil {
return fmt.Errorf("%s - upsert review: %w", location, mapAssessmentError(err))
}
return nil
}
func (repository assessmentSignalRepository) GetReview(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
) (domain.AssessmentAttemptReview, error) {
const location = "assessmentSignalRepository.GetReview"
if attemptID.IsZero() {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview)
}
row, err := repository.queries.GetAssessmentAttemptReview(ctx, pgUUID(attemptID.UUID()))
if errors.Is(err, pgx.ErrNoRows) {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - review does not exist: %w", location, outbound.ErrAssessmentReviewNotFound)
}
if err != nil {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - read review: %w", location, mapAssessmentError(err))
}
review, err := restoreAssessmentAttemptReview(row)
if err != nil {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - restore review: %w", location, err)
}
return review, nil
}
func restoreAssessmentAttemptReview(row sqlc.GetAssessmentAttemptReviewRow) (domain.AssessmentAttemptReview, error) {
if !row.AttemptID.Valid || !row.PolicyVersionID.Valid || !row.EvaluatedAt.Valid || !row.UpdatedAt.Valid {
return domain.AssessmentAttemptReview{}, domain.ErrInvalidAssessmentReview
}
reasons := make([]domain.AssessmentReviewReason, 0, len(row.Reasons))
for _, reason := range row.Reasons {
reasons = append(reasons, domain.AssessmentReviewReason(reason))
}
review := domain.AssessmentAttemptReview{
AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes),
PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes),
PolicyVersion: row.PolicyVersion,
Measures: domain.AssessmentReviewMeasures{
AnsweredItems: row.AnsweredItems, FastAnswers: row.FastAnswers, DeviatingAnswers: row.DeviatingAnswers,
ParallelAlternations: row.ParallelAlternations, ExtraNetworks: row.ExtraNetworks,
MatchedIntegerItems: row.MatchedIntegerItems, MatchedSequenceItems: row.MatchedSequenceItems,
DuplicateEvidenceBits: row.DuplicateEvidenceBits,
ClientFocusLossMS: row.ClientFocusLossMs, ClientClipboardEvents: row.ClientClipboardEvents,
ClientFullscreenExits: row.ClientFullscreenExits,
},
Outcome: domain.AssessmentReviewOutcome{
Band: domain.AssessmentReviewBand(row.Band), Reasons: reasons,
},
EvaluatedAt: row.EvaluatedAt.Time.UTC(), UpdatedAt: row.UpdatedAt.Time.UTC(),
}
if err := review.Validate(); err != nil {
return domain.AssessmentAttemptReview{}, err
}
return review, nil
}
func (repository assessmentSignalRepository) RecordReviewRead(
ctx context.Context,
id uuid.UUID,
attemptID domain.AssessmentAttemptID,
actor domain.AssessmentReviewActor,
found bool,
at time.Time,
) error {
const location = "assessmentSignalRepository.RecordReviewRead"
if id == uuid.Nil || attemptID.IsZero() || actor == "" || at.IsZero() {
return fmt.Errorf("%s - record identifiers, attempt, actor, and time are required: %w", location, domain.ErrInvalidAssessmentReview)
}
if err := repository.queries.InsertAssessmentReviewRead(ctx, sqlc.InsertAssessmentReviewReadParams{
ID: pgUUID(id), AttemptID: pgUUID(attemptID.UUID()), Actor: string(actor), Found: found, ReadAt: pgTime(at),
}); err != nil {
return fmt.Errorf("%s - insert read record: %w", location, mapAssessmentError(err))
}
return nil
}
@@ -0,0 +1,53 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_signal_notice.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getAssessmentSignalNoticeAcknowledgement = `-- name: GetAssessmentSignalNoticeAcknowledgement :one
SELECT acknowledged_at
FROM assessment_signal_notice_acknowledgements
WHERE
user_id = $1
AND notice_version = $2
`
type GetAssessmentSignalNoticeAcknowledgementParams struct {
UserID pgtype.UUID
NoticeVersion int32
}
// The caller has already checked that the user is a candidate. A missing row
// means the notice version was not acknowledged.
func (q *Queries) GetAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg GetAssessmentSignalNoticeAcknowledgementParams) (pgtype.Timestamptz, error) {
row := q.db.QueryRow(ctx, getAssessmentSignalNoticeAcknowledgement, arg.UserID, arg.NoticeVersion)
var acknowledged_at pgtype.Timestamptz
err := row.Scan(&acknowledged_at)
return acknowledged_at, err
}
const insertAssessmentSignalNoticeAcknowledgement = `-- name: InsertAssessmentSignalNoticeAcknowledgement :exec
INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at)
VALUES ($1, $2, $3)
ON CONFLICT (user_id, notice_version) DO NOTHING
`
type InsertAssessmentSignalNoticeAcknowledgementParams struct {
UserID pgtype.UUID
NoticeVersion int32
AcknowledgedAt pgtype.Timestamptz
}
// The first acknowledgement wins; a repeat keeps the stored time and inserts
// nothing. The caller reads the stored row afterwards in the same transaction.
func (q *Queries) InsertAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg InsertAssessmentSignalNoticeAcknowledgementParams) error {
_, err := q.db.Exec(ctx, insertAssessmentSignalNoticeAcknowledgement, arg.UserID, arg.NoticeVersion, arg.AcknowledgedAt)
return err
}
@@ -0,0 +1,577 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_signal_review.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getAssessmentAttemptReview = `-- name: GetAssessmentAttemptReview :one
SELECT
review.attempt_id,
review.policy_version_id,
policy.version AS policy_version,
review.band,
review.reasons,
review.answered_items,
review.fast_answers,
review.deviating_answers,
review.parallel_alternations,
review.extra_networks,
review.matched_integer_items,
review.matched_sequence_items,
review.duplicate_evidence_bits,
review.client_focus_loss_ms,
review.client_clipboard_events,
review.client_fullscreen_exits,
review.evaluated_at,
review.updated_at
FROM assessment_attempt_reviews AS review
JOIN policy_versions AS policy ON policy.id = review.policy_version_id
WHERE review.attempt_id = $1
`
type GetAssessmentAttemptReviewRow struct {
AttemptID pgtype.UUID
PolicyVersionID pgtype.UUID
PolicyVersion int32
Band string
Reasons []string
AnsweredItems int32
FastAnswers int32
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
EvaluatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) GetAssessmentAttemptReview(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentAttemptReviewRow, error) {
row := q.db.QueryRow(ctx, getAssessmentAttemptReview, attemptID)
var i GetAssessmentAttemptReviewRow
err := row.Scan(
&i.AttemptID,
&i.PolicyVersionID,
&i.PolicyVersion,
&i.Band,
&i.Reasons,
&i.AnsweredItems,
&i.FastAnswers,
&i.DeviatingAnswers,
&i.ParallelAlternations,
&i.ExtraNetworks,
&i.MatchedIntegerItems,
&i.MatchedSequenceItems,
&i.DuplicateEvidenceBits,
&i.ClientFocusLossMs,
&i.ClientClipboardEvents,
&i.ClientFullscreenExits,
&i.EvaluatedAt,
&i.UpdatedAt,
)
return i, err
}
const getAssessmentClientSignalTotals = `-- name: GetAssessmentClientSignalTotals :one
SELECT
COALESCE(sum(duration_ms) FILTER (WHERE kind = 'focus_loss'), 0)::bigint AS focus_loss_ms,
(count(*) FILTER (WHERE kind IN ('copy', 'paste', 'cut')))::integer AS clipboard_events,
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits
FROM assessment_signal_events
WHERE attempt_id = $1
`
type GetAssessmentClientSignalTotalsRow struct {
FocusLossMs int64
ClipboardEvents int32
FullscreenExits int32
}
func (q *Queries) GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error) {
row := q.db.QueryRow(ctx, getAssessmentClientSignalTotals, attemptID)
var i GetAssessmentClientSignalTotalsRow
err := row.Scan(&i.FocusLossMs, &i.ClipboardEvents, &i.FullscreenExits)
return i, err
}
const getAssessmentReviewSubject = `-- name: GetAssessmentReviewSubject :one
SELECT product_policy_version_id
FROM assessment_attempts
WHERE id = $1 AND kind IN ('root', 'corrective')
`
// The attempt a review job works on: real attempts only.
func (q *Queries) GetAssessmentReviewSubject(ctx context.Context, attemptID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, getAssessmentReviewSubject, attemptID)
var product_policy_version_id pgtype.UUID
err := row.Scan(&product_policy_version_id)
return product_policy_version_id, err
}
const getLastAssessmentOriginMark = `-- name: GetLastAssessmentOriginMark :one
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version
FROM assessment_attempt_origin_marks
WHERE attempt_id = $1
ORDER BY observed_at DESC, id DESC
LIMIT 1
`
// The caller holds the attempt row lock, so the last mark is stable.
func (q *Queries) GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error) {
row := q.db.QueryRow(ctx, getLastAssessmentOriginMark, attemptID)
var i AssessmentAttemptOriginMark
err := row.Scan(
&i.ID,
&i.AttemptID,
&i.Source,
&i.ObservedAt,
&i.SessionDigest,
&i.NetworkDigest,
&i.KeyVersion,
)
return i, err
}
const insertAssessmentAnswerObservation = `-- name: InsertAssessmentAnswerObservation :exec
INSERT INTO assessment_answer_observations (
attempt_id,
item_instance_id,
user_id,
family_id,
variant_seed,
answer_format,
answer_fingerprint,
key_version,
elapsed_ms,
measured_from_answer,
observed_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11
)
`
type InsertAssessmentAnswerObservationParams struct {
AttemptID pgtype.UUID
ItemInstanceID pgtype.UUID
UserID pgtype.UUID
FamilyID pgtype.UUID
VariantSeed int64
AnswerFormat string
AnswerFingerprint []byte
KeyVersion int16
ElapsedMs int32
MeasuredFromAnswer bool
ObservedAt pgtype.Timestamptz
}
func (q *Queries) InsertAssessmentAnswerObservation(ctx context.Context, arg InsertAssessmentAnswerObservationParams) error {
_, err := q.db.Exec(ctx, insertAssessmentAnswerObservation,
arg.AttemptID,
arg.ItemInstanceID,
arg.UserID,
arg.FamilyID,
arg.VariantSeed,
arg.AnswerFormat,
arg.AnswerFingerprint,
arg.KeyVersion,
arg.ElapsedMs,
arg.MeasuredFromAnswer,
arg.ObservedAt,
)
return err
}
const insertAssessmentOriginMark = `-- name: InsertAssessmentOriginMark :exec
INSERT INTO assessment_attempt_origin_marks (
id,
attempt_id,
source,
observed_at,
session_digest,
network_digest,
key_version
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertAssessmentOriginMarkParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Source string
ObservedAt pgtype.Timestamptz
SessionDigest []byte
NetworkDigest []byte
KeyVersion int16
}
func (q *Queries) InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error {
_, err := q.db.Exec(ctx, insertAssessmentOriginMark,
arg.ID,
arg.AttemptID,
arg.Source,
arg.ObservedAt,
arg.SessionDigest,
arg.NetworkDigest,
arg.KeyVersion,
)
return err
}
const insertAssessmentReviewRead = `-- name: InsertAssessmentReviewRead :exec
INSERT INTO assessment_review_reads (id, attempt_id, actor, found, read_at)
VALUES ($1, $2, $3, $4, $5)
`
type InsertAssessmentReviewReadParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Actor string
Found bool
ReadAt pgtype.Timestamptz
}
func (q *Queries) InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error {
_, err := q.db.Exec(ctx, insertAssessmentReviewRead,
arg.ID,
arg.AttemptID,
arg.Actor,
arg.Found,
arg.ReadAt,
)
return err
}
const listAssessmentAnswerTimes = `-- name: ListAssessmentAnswerTimes :many
SELECT answer_format, elapsed_ms, measured_from_answer
FROM assessment_answer_observations
WHERE attempt_id = $1
ORDER BY observed_at, item_instance_id
LIMIT 220
`
type ListAssessmentAnswerTimesRow struct {
AnswerFormat string
ElapsedMs int32
MeasuredFromAnswer bool
}
// An attempt holds at most 220 items, so the list is bounded by the attempt.
func (q *Queries) ListAssessmentAnswerTimes(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAnswerTimesRow, error) {
rows, err := q.db.Query(ctx, listAssessmentAnswerTimes, attemptID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAssessmentAnswerTimesRow
for rows.Next() {
var i ListAssessmentAnswerTimesRow
if err := rows.Scan(&i.AnswerFormat, &i.ElapsedMs, &i.MeasuredFromAnswer); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAssessmentDuplicatePairs = `-- name: ListAssessmentDuplicatePairs :many
WITH mine AS (
SELECT
own.family_id,
own.key_version,
own.answer_fingerprint,
own.answer_format,
own.variant_seed,
own.user_id
FROM assessment_answer_observations AS own
WHERE own.attempt_id = $5
),
pair_items AS (
SELECT
other.attempt_id AS other_attempt_id,
mine.answer_format,
least(
CASE
WHEN mine.answer_format = 'integer' THEN $6::float8
ELSE $7::float8
END,
greatest(0::float8, -ln(holders.holders::float8 / totals.answer_count::float8) / ln(2::float8))
) AS bits
FROM mine
INNER JOIN assessment_answer_observations AS other
ON mine.family_id = other.family_id
AND mine.key_version = other.key_version
AND mine.answer_fingerprint = other.answer_fingerprint
AND mine.user_id <> other.user_id
AND mine.variant_seed <> other.variant_seed
INNER JOIN assessment_answer_fingerprint_holders AS holders
ON mine.family_id = holders.family_id
AND mine.key_version = holders.key_version
AND mine.answer_fingerprint = holders.answer_fingerprint
INNER JOIN assessment_answer_family_totals AS totals
ON mine.family_id = totals.family_id
AND mine.key_version = totals.key_version
)
SELECT
pair_items.other_attempt_id,
other_attempt.product_policy_version_id,
floor(sum(pair_items.bits))::integer AS evidence_bits,
(count(*) FILTER (WHERE pair_items.answer_format = 'integer'))::integer AS integer_items,
(count(*) FILTER (WHERE pair_items.answer_format = 'integer_sequence'))::integer AS sequence_items
FROM pair_items
INNER JOIN assessment_attempts AS other_attempt ON pair_items.other_attempt_id = other_attempt.id
WHERE
NOT $1::boolean
OR other_attempt.state IN ('completed', 'expired', 'insufficient_bank')
OR other_attempt.expires_at <= $2::timestamptz
GROUP BY pair_items.other_attempt_id, other_attempt.product_policy_version_id
HAVING floor(sum(pair_items.bits)) >= $3::float8
ORDER BY evidence_bits DESC, pair_items.other_attempt_id
LIMIT $4
`
type ListAssessmentDuplicatePairsParams struct {
EndedOnly bool
Now pgtype.Timestamptz
MinBits float64
RowLimit int32
AttemptID pgtype.UUID
IntegerCapBits float64
SequenceCapBits float64
}
type ListAssessmentDuplicatePairsRow struct {
OtherAttemptID pgtype.UUID
ProductPolicyVersionID pgtype.UUID
EvidenceBits int32
IntegerItems int32
SequenceItems int32
}
// Compares this attempt with every other attempt separately. A matched answer
// is an equal fingerprint of the same family version under the same key
// generation, given by another candidate to a different seed variant. It
// carries -log2 of the share of answers that hold that fingerprint, read from
// the maintained counters, between
// zero and the cap of its format, and the bits of one pair add up. Pairs under
// min_bits are dropped, the strongest come first, and the list is bounded.
// An attempt has ended when its state is terminal or its deadline has passed.
func (q *Queries) ListAssessmentDuplicatePairs(ctx context.Context, arg ListAssessmentDuplicatePairsParams) ([]ListAssessmentDuplicatePairsRow, error) {
rows, err := q.db.Query(ctx, listAssessmentDuplicatePairs,
arg.EndedOnly,
arg.Now,
arg.MinBits,
arg.RowLimit,
arg.AttemptID,
arg.IntegerCapBits,
arg.SequenceCapBits,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAssessmentDuplicatePairsRow
for rows.Next() {
var i ListAssessmentDuplicatePairsRow
if err := rows.Scan(
&i.OtherAttemptID,
&i.ProductPolicyVersionID,
&i.EvidenceBits,
&i.IntegerItems,
&i.SequenceItems,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAssessmentOriginMarks = `-- name: ListAssessmentOriginMarks :many
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version
FROM assessment_attempt_origin_marks
WHERE attempt_id = $1
ORDER BY observed_at, id
LIMIT 5000
`
// Marks exist only where the session or the network changed. The bound keeps a
// request that flaps between networks from growing the list without limit.
func (q *Queries) ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error) {
rows, err := q.db.Query(ctx, listAssessmentOriginMarks, attemptID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AssessmentAttemptOriginMark
for rows.Next() {
var i AssessmentAttemptOriginMark
if err := rows.Scan(
&i.ID,
&i.AttemptID,
&i.Source,
&i.ObservedAt,
&i.SessionDigest,
&i.NetworkDigest,
&i.KeyVersion,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockAssessmentReview = `-- name: LockAssessmentReview :exec
SELECT pg_advisory_xact_lock(hashtextextended(
'lincodex.assessment.signal_review:' || $1::text,
0
))
`
// Serializes the evaluations of one review. A job takes these locks for every
// attempt it will write, in ascending attempt order, before it reads any fact,
// so what it reads is what the previous writer committed.
func (q *Queries) LockAssessmentReview(ctx context.Context, attemptID string) error {
_, err := q.db.Exec(ctx, lockAssessmentReview, attemptID)
return err
}
const upsertAssessmentAttemptReview = `-- name: UpsertAssessmentAttemptReview :exec
INSERT INTO assessment_attempt_reviews (
attempt_id,
policy_version_id,
band,
reasons,
answered_items,
fast_answers,
deviating_answers,
parallel_alternations,
extra_networks,
matched_integer_items,
matched_sequence_items,
duplicate_evidence_bits,
client_focus_loss_ms,
client_clipboard_events,
client_fullscreen_exits,
evaluated_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4::text[],
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
clock_timestamp(),
clock_timestamp()
)
ON CONFLICT (attempt_id) DO UPDATE SET
policy_version_id = EXCLUDED.policy_version_id,
band = EXCLUDED.band,
reasons = EXCLUDED.reasons,
answered_items = EXCLUDED.answered_items,
fast_answers = EXCLUDED.fast_answers,
deviating_answers = EXCLUDED.deviating_answers,
parallel_alternations = EXCLUDED.parallel_alternations,
extra_networks = EXCLUDED.extra_networks,
matched_integer_items = EXCLUDED.matched_integer_items,
matched_sequence_items = EXCLUDED.matched_sequence_items,
duplicate_evidence_bits = EXCLUDED.duplicate_evidence_bits,
client_focus_loss_ms = EXCLUDED.client_focus_loss_ms,
client_clipboard_events = EXCLUDED.client_clipboard_events,
client_fullscreen_exits = EXCLUDED.client_fullscreen_exits,
updated_at = greatest(
clock_timestamp(), assessment_attempt_reviews.evaluated_at, assessment_attempt_reviews.updated_at
)
`
type UpsertAssessmentAttemptReviewParams struct {
AttemptID pgtype.UUID
PolicyVersionID pgtype.UUID
Band string
Reasons []string
AnsweredItems int32
FastAnswers int32
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
}
// The times come from the database clock, never from a caller, and the update
// time cannot fall behind the stored times, so two jobs writing one review in
// either order keep the order check. The first evaluation time and the policy
// version stay; the guard trigger refuses a change of either.
func (q *Queries) UpsertAssessmentAttemptReview(ctx context.Context, arg UpsertAssessmentAttemptReviewParams) error {
_, err := q.db.Exec(ctx, upsertAssessmentAttemptReview,
arg.AttemptID,
arg.PolicyVersionID,
arg.Band,
arg.Reasons,
arg.AnsweredItems,
arg.FastAnswers,
arg.DeviatingAnswers,
arg.ParallelAlternations,
arg.ExtraNetworks,
arg.MatchedIntegerItems,
arg.MatchedSequenceItems,
arg.DuplicateEvidenceBits,
arg.ClientFocusLossMs,
arg.ClientClipboardEvents,
arg.ClientFullscreenExits,
)
return err
}
@@ -16,6 +16,33 @@ type AccountDeletionRequest struct {
CompletedAt pgtype.Timestamptz
}
type AssessmentAnswerFamilyTotal struct {
FamilyID pgtype.UUID
KeyVersion int16
AnswerCount int32
}
type AssessmentAnswerFingerprintHolder struct {
FamilyID pgtype.UUID
KeyVersion int16
AnswerFingerprint []byte
Holders int32
}
type AssessmentAnswerObservation struct {
AttemptID pgtype.UUID
ItemInstanceID pgtype.UUID
UserID pgtype.UUID
FamilyID pgtype.UUID
VariantSeed int64
AnswerFormat string
AnswerFingerprint []byte
KeyVersion int16
ElapsedMs int32
MeasuredFromAnswer bool
ObservedAt pgtype.Timestamptz
}
type AssessmentAttempt struct {
ID pgtype.UUID
UserID pgtype.UUID
@@ -74,6 +101,16 @@ type AssessmentAttemptItem struct {
AnsweredAt pgtype.Timestamptz
}
type AssessmentAttemptOriginMark struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Source string
ObservedAt pgtype.Timestamptz
SessionDigest []byte
NetworkDigest []byte
KeyVersion int16
}
type AssessmentAttemptResult struct {
AttemptID pgtype.UUID
UserID pgtype.UUID
@@ -99,6 +136,26 @@ type AssessmentAttemptResult struct {
DecidedAt pgtype.Timestamptz
}
type AssessmentAttemptReview struct {
AttemptID pgtype.UUID
PolicyVersionID pgtype.UUID
Band string
Reasons []string
AnsweredItems int32
FastAnswers int32
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
EvaluatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
OpeningID pgtype.UUID
Specialization string
@@ -143,6 +200,14 @@ type AssessmentFamily struct {
RetiredBy pgtype.Text
}
type AssessmentReviewRead struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Actor string
Found bool
ReadAt pgtype.Timestamptz
}
type AssessmentSignalBatch struct {
ID pgtype.UUID
AttemptID pgtype.UUID
@@ -169,6 +234,12 @@ type AssessmentSignalIdempotencyOutcome struct {
ReceivedAt pgtype.Timestamptz
}
type AssessmentSignalNoticeAcknowledgement struct {
UserID pgtype.UUID
NoticeVersion int32
AcknowledgedAt pgtype.Timestamptz
}
type AssessmentTrainingBankBinding struct {
ID pgtype.UUID
Category string
@@ -227,15 +227,22 @@ type Querier interface {
GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error)
// Reads a result only for the owning candidate.
GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error)
GetAssessmentAttemptReview(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentAttemptReviewRow, error)
// Reads an active real attempt without taking the write lock used by create.
// The availability GET never expires or otherwise mutates this row.
GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error)
GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error)
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
// The attempt a review job works on: real attempts only.
GetAssessmentReviewSubject(ctx context.Context, attemptID pgtype.UUID) (pgtype.UUID, error)
// Counts eligible root attempts in a policy window and computes the instant
// at which one additional root slot opens. The microsecond adjustment matches
// the creation predicate created_at >= since at PostgreSQL timestamp precision.
GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error)
// The caller has already checked that the user is a candidate. A missing row
// means the notice version was not acknowledged.
GetAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg GetAssessmentSignalNoticeAcknowledgementParams) (pgtype.Timestamptz, error)
// Read only the receipt associated with the reserved idempotency scope.
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
// Reads one hiding of the candidate with the current name of the
@@ -272,6 +279,8 @@ type Querier interface {
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
// Explains why ConsumeEmailToken matched no row.
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
// The caller holds the attempt row lock, so the last mark is stable.
GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error)
GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
// Reads the status of the newest delivery of a kind addressed to an account,
// for the account's own view of its mail. It selects no address and no
@@ -328,6 +337,7 @@ type Querier interface {
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
InsertAssessmentAnswerObservation(ctx context.Context, arg InsertAssessmentAnswerObservationParams) error
// Inserts the attempt header. The database guard rechecks the current policy,
// opening or disjoint training binding, and immutable pins.
InsertAssessmentAttempt(ctx context.Context, arg InsertAssessmentAttemptParams) error
@@ -351,12 +361,17 @@ type Querier interface {
// returns no row instead of an error, so a conflict does not abort the
// surrounding transaction.
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error
InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error
// The attempt row is already locked by the caller. Store a parent before its
// bounded child events, in the same transaction as the immutable receipt.
InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error
// Each inserted event is checked by the database guard against attempt state
// and the aggregate capacity as a second line of defense.
InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error
// The first acknowledgement wins; a repeat keeps the stored time and inserts
// nothing. The caller reads the stored row afterwards in the same transaction.
InsertAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg InsertAssessmentSignalNoticeAcknowledgementParams) error
// Save exactly one immutable response receipt for each live idempotency scope.
InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error
// Records a successfully authorized view after visibility and quota checks.
@@ -473,6 +488,8 @@ type Querier interface {
// Read the latest serialized event so a temporarily regressing application
// clock cannot make the next request fall before an event already counted.
LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error)
// An attempt holds at most 220 items, so the list is bounded by the attempt.
ListAssessmentAnswerTimes(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAnswerTimesRow, error)
// Reads chain headers in creation order. The use case verifies root eligibility
// and descending target grades in the domain before it creates a correction.
ListAssessmentAttemptChain(ctx context.Context, arg ListAssessmentAttemptChainParams) ([]AssessmentAttempt, error)
@@ -488,10 +505,22 @@ type Querier interface {
// Counting the first unanswered item after expiry is conservative when the
// final response was lost, while frozen future items remain excluded.
ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error)
// Compares this attempt with every other attempt separately. A matched answer
// is an equal fingerprint of the same family version under the same key
// generation, given by another candidate to a different seed variant. It
// carries -log2 of the share of answers that hold that fingerprint, read from
// the maintained counters, between
// zero and the cap of its format, and the bits of one pair add up. Pairs under
// min_bits are dropped, the strongest come first, and the list is bounded.
// An attempt has ended when its state is terminal or its deadline has passed.
ListAssessmentDuplicatePairs(ctx context.Context, arg ListAssessmentDuplicatePairsParams) ([]ListAssessmentDuplicatePairsRow, error)
// One page of the versions of a category in key and version order, after the
// given position; an empty key and version 0 start at the beginning. The
// (family_key, version) unique index serves the scan.
ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, error)
// Marks exist only where the session or the network changed. The bound keeps a
// request that flaps between networks from growing the list without limit.
ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error)
// Reads the exact family membership pinned by a training binding.
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
// Lists only the current candidate's own access history. It deliberately
@@ -566,6 +595,10 @@ type Querier interface {
// published or open the category, until the transaction ends. The key is
// namespaced, so it cannot collide with another use of advisory locks.
LockAssessmentCategory(ctx context.Context, category string) error
// Serializes the evaluations of one review. A job takes these locks for every
// attempt it will write, in ascending attempt order, before it reads any fact,
// so what it reads is what the previous writer committed.
LockAssessmentReview(ctx context.Context, attemptID string) error
// Lock the account before an organization checks candidate visibility. The
// hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
// a hide either commits before the later visibility recheck or waits for the
@@ -895,6 +928,11 @@ type Querier interface {
// registrant never stands for the new one; the new registration records its
// own C1 in the same transaction. A version conflict deletes nothing.
UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error)
// The times come from the database clock, never from a caller, and the update
// time cannot fall behind the stored times, so two jobs writing one review in
// either order keep the order check. The first evaluation time and the policy
// version stay; the guard trigger refuses a change of either.
UpsertAssessmentAttemptReview(ctx context.Context, arg UpsertAssessmentAttemptReviewParams) error
}
var _ Querier = (*Queries)(nil)
+6
View File
@@ -46,5 +46,11 @@ func newAssessmentHandler(
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create service: %w", err)
}
observer, err := newSignalObserver(keyring)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create signal observer: %w", err)
}
service.WithSignalObserver(observer)
return v1.NewAssessmentHandler(service), pool.Close, nil
}
@@ -35,5 +35,11 @@ func newAssessmentSignalHandler(
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentSignalHandler - create service: %w", err)
}
return v1.NewAssessmentSignalHandler(service), pool.Close, nil
observer, err := newSignalObserver(keyring)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentSignalHandler - create signal observer: %w", err)
}
service.WithSignalObserver(observer)
return v1.NewAssessmentSignalHandler(service).WithNotice(service), pool.Close, nil
}
@@ -0,0 +1,19 @@
package bootstrap
import (
"fmt"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/identity"
)
// newSignalObserver derives the answer, session, and network digests of the
// server signals from the identity keyring, so no separate secret is needed and
// the digests change with IDENTITY_KEY_SECRET.
func newSignalObserver(keyring *identity.Keyring) (*assessment.SignalObserver, error) {
observer, err := assessment.NewSignalObserver(keyring)
if err != nil {
return nil, fmt.Errorf("bootstrap.newSignalObserver - create observer: %w", err)
}
return observer, nil
}
+8 -6
View File
@@ -10,6 +10,7 @@ import (
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/retry"
)
@@ -29,11 +30,12 @@ const (
var _ jobrunner.Metrics = (*prometheus.Metrics)(nil)
// jobHandlers lists the scheduled job handlers, one per kind. A product
// module adds its handler here, for example the invitation response
// deadline, and the worker then claims jobs of that kind with the next
// deployment. Jobs of a kind without a handler wait in the database.
func jobHandlers() []inbound.JobHandler {
return []inbound.JobHandler{}
// module adds its handler here, and the worker then claims jobs of that kind
// with the next deployment. Jobs of a kind without a handler wait in the
// database. The only kind now is the computation of the assessment review
// band, which can never block or change a result.
func jobHandlers(logger *slog.Logger) []inbound.JobHandler {
return []inbound.JobHandler{assessment.NewSignalReviewJob(logger)}
}
func newJobWorker(
@@ -42,7 +44,7 @@ func newJobWorker(
logger *slog.Logger,
metrics *prometheus.Metrics,
) (*jobrunner.Worker, func(), error) {
return buildJobWorker(ctx, settings, logger, metrics, jobHandlers())
return buildJobWorker(ctx, settings, logger, metrics, jobHandlers(logger.With(slog.String("component", "assessment_review"))))
}
// buildJobWorker builds the scheduled job worker and the PostgreSQL pool it
+3 -2
View File
@@ -55,8 +55,9 @@ func TestBuildJobWorkerSkipsWithoutWork(t *testing.T) {
}
}
func TestBootstrapRegistersNoJobKindYet(t *testing.T) {
if handlers := jobHandlers(); len(handlers) != 0 {
func TestBootstrapRegistersTheReviewJobKind(t *testing.T) {
handlers := jobHandlers(slog.New(slog.DiscardHandler))
if len(handlers) != 1 || handlers[0].JobKind() != "assessment.signal_review" {
t.Fatalf("jobHandlers() = %v; update the documentation when the registered job kinds change", handlers)
}
}
@@ -0,0 +1,137 @@
package domain
// AssessmentSignalPolicy holds the versioned thresholds that turn the server
// observations of an attempt into a review band. The band is a hint for a
// manual check: it never changes a result, a category, or a quota. The section
// is optional; a policy version without it makes no band, and an absent
// section never acquires defaults.
//
// Counts are numbers of items or events, durations carry their unit in the
// field name, and the duplicate thresholds are evidence bits: a matched answer
// adds the number of bits that the policy assumes for its format, and a pair of
// candidates that coincides by chance reaches N bits with a probability of
// about 2^-N when every matched answer is independent.
type AssessmentSignalPolicy struct {
// FastFloorIntegerMS and FastFloorSequenceMS are the shortest server time
// from the previous answer or session start to the answer that is still
// plausible for the answer format. A shorter time is a fast answer.
FastFloorIntegerMS int32
FastFloorSequenceMS int32
// FastAnswersAttention and FastAnswersReview are the numbers of fast
// answers that raise the band.
FastAnswersAttention int32
FastAnswersReview int32
// DeviationRatio is the factor by which an answer time may differ from the
// median answer time of the same attempt, in both directions, before it is
// an anomalous deviation. 50000 means five times. It applies only to an
// attempt with at least DeviationMinAnswers answers.
DeviationRatio BasisPoints
DeviationMinAnswers int32
DeviatingAnswersAttention int32
DeviatingAnswersReview int32
ParallelAlternationsAttention int32
ParallelAlternationsReview int32
// ExtraNetworks counts the distinct client networks of the attempt beyond
// the first. Going from one network to another and back adds one, however
// often it happens.
ExtraNetworksAttention int32
ExtraNetworksReview int32
// A matched answer carries -log2 of the share of attempts that hold the
// same fingerprint for the family version, so a popular value, such as the
// correct answer of a variant, carries little. DuplicateIntegerCapBits and
// DuplicateSequenceCapBits cap what one answer of the format can carry; an
// integer answer has a small answer space and is capped lower. The bits of
// the matched answers of one pair of attempts add up, and the highest pair
// decides: an attempt is compared with every other one, not with the whole
// population at once.
DuplicateIntegerCapBits int32
DuplicateSequenceCapBits int32
DuplicateAttentionBits int32
DuplicateReviewBits int32
// The client thresholds can raise a normal band to attention only, because
// a browser reports them and anyone can forge or suppress them.
ClientFocusLossAttentionMS int32
ClientClipboardEventsAttention int32
ClientFullscreenExitsAttention int32
}
// Sanity bounds of the signal section. They reject a value in the wrong unit;
// the demo values themselves are recorded in DemoAssessmentSignalPolicy.
const (
minSignalFloorMS = 1000
maxSignalFloorMS = 10 * 60 * 1000
maxSignalCount = 1000
minSignalDeviationRatio = BasisPoints(20000)
maxSignalDeviationRatio = BasisPoints(1000000)
minSignalDeviationAnswers = 3
maxSignalDeviationAnswers = maxAssessmentAttemptItems
maxSignalEvidenceBits = 64
maxSignalThresholdBits = 4096
minSignalClientFocusLossMS = 1000
maxSignalClientFocusLossMS = 24 * 60 * 60 * 1000
)
// DemoAssessmentSignalPolicy returns the initial thresholds. They are agreed
// starting values for verifying the flow, not measured results: no study of
// real candidates supports them, and a calibrated policy must replace them.
func DemoAssessmentSignalPolicy() AssessmentSignalPolicy {
return AssessmentSignalPolicy{
FastFloorIntegerMS: 5000,
FastFloorSequenceMS: 8000,
FastAnswersAttention: 3,
FastAnswersReview: 6,
DeviationRatio: 50000,
DeviationMinAnswers: 5,
DeviatingAnswersAttention: 3,
DeviatingAnswersReview: 6,
ParallelAlternationsAttention: 2,
ParallelAlternationsReview: 6,
ExtraNetworksAttention: 2, ExtraNetworksReview: 5,
DuplicateIntegerCapBits: 8, DuplicateSequenceCapBits: 12,
DuplicateAttentionBits: 48,
DuplicateReviewBits: 64,
ClientFocusLossAttentionMS: 120000,
ClientClipboardEventsAttention: 3,
ClientFullscreenExitsAttention: 3,
}
}
// Validate rejects a zero, out-of-range, or inconsistent section.
func (policy AssessmentSignalPolicy) Validate() error {
const location = "AssessmentSignalPolicy.Validate"
if err := firstError(
checkRange(location, "assessment.signals.fast_floor_integer_ms", policy.FastFloorIntegerMS, minSignalFloorMS, maxSignalFloorMS),
checkRange(location, "assessment.signals.fast_floor_sequence_ms", policy.FastFloorSequenceMS, minSignalFloorMS, maxSignalFloorMS),
checkRange(location, "assessment.signals.deviation_ratio_bp", policy.DeviationRatio, minSignalDeviationRatio, maxSignalDeviationRatio),
checkRange(location, "assessment.signals.deviation_min_answers", policy.DeviationMinAnswers, minSignalDeviationAnswers, maxSignalDeviationAnswers),
checkRange(location, "assessment.signals.duplicate_integer_cap_bits", policy.DuplicateIntegerCapBits, 1, maxSignalEvidenceBits),
checkRange(location, "assessment.signals.duplicate_sequence_cap_bits", policy.DuplicateSequenceCapBits, 1, maxSignalEvidenceBits),
checkRange(location, "assessment.signals.client_focus_loss_attention_ms", policy.ClientFocusLossAttentionMS, minSignalClientFocusLossMS, maxSignalClientFocusLossMS),
checkRange(location, "assessment.signals.client_clipboard_events_attention", policy.ClientClipboardEventsAttention, 1, maxSignalCount),
checkRange(location, "assessment.signals.client_fullscreen_exits_attention", policy.ClientFullscreenExitsAttention, 1, maxSignalCount),
); err != nil {
return err
}
for _, pair := range []struct {
field string
attention, review int32
maximum int32
}{
{"fast_answers", policy.FastAnswersAttention, policy.FastAnswersReview, maxSignalCount},
{"deviating_answers", policy.DeviatingAnswersAttention, policy.DeviatingAnswersReview, maxSignalCount},
{"parallel_alternations", policy.ParallelAlternationsAttention, policy.ParallelAlternationsReview, maxSignalCount},
{"extra_networks", policy.ExtraNetworksAttention, policy.ExtraNetworksReview, maxSignalCount},
{"duplicate_bits", policy.DuplicateAttentionBits, policy.DuplicateReviewBits, maxSignalThresholdBits},
} {
if err := checkRange(location, "assessment.signals."+pair.field+"_attention", pair.attention, 1, pair.maximum); err != nil {
return err
}
if err := checkRange(location, "assessment.signals."+pair.field+"_review", pair.review, pair.attention, pair.maximum); err != nil {
return err
}
}
return nil
}
@@ -0,0 +1,80 @@
package domain
import (
"errors"
"testing"
)
func TestDemoSignalPolicyIsValidAndRoundTripsThroughTheDocument(t *testing.T) {
policy := DemoProductPolicyV3()
if err := policy.Validate(); err != nil {
t.Fatalf("DemoProductPolicyV3().Validate() error = %v", err)
}
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
if decoded.Assessment.Signals == nil || *decoded.Assessment.Signals != DemoAssessmentSignalPolicy() {
t.Fatalf("decoded signals = %+v, want the demo values", decoded.Assessment.Signals)
}
if DemoProductPolicyV2().Assessment.Signals != nil {
t.Fatal("DemoProductPolicyV2 gained a signal section; a stored version must not change")
}
}
func TestSignalSectionAloneIsASchemaTwoExtensionAndNeverAcquiresDefaults(t *testing.T) {
signals := DemoAssessmentSignalPolicy()
policy := DemoProductPolicyV1()
policy.Assessment.Signals = &signals
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil || decoded.Assessment.Signals == nil || decoded.Assessment.Attempt != nil || decoded.Support != nil {
t.Fatalf("decode signals-only schema 2 = %+v, error %v", decoded.Assessment, err)
}
legacy := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) {
policySection(t, document, "assessment")["signals"] = nil
})
if _, err := decodeProductPolicy(legacy); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(schema 1 with a signals key) error = %v, want ErrInvalidPolicy", err)
}
missingField := editPolicySchemaDocument(t, encoded, func(document map[string]any) {
delete(policySection(t, policySection(t, document, "assessment"), "signals"), "fast_floor_integer_ms")
})
if _, err := decodeProductPolicy(missingField); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(missing signal field) error = %v, want ErrInvalidPolicy", err)
}
}
func TestSignalPolicyRejectsOutOfRangeAndInconsistentValues(t *testing.T) {
tests := []struct {
name string
change func(*AssessmentSignalPolicy)
}{
{"zero section", func(policy *AssessmentSignalPolicy) { *policy = AssessmentSignalPolicy{} }},
{"floor in seconds instead of milliseconds", func(policy *AssessmentSignalPolicy) { policy.FastFloorIntegerMS = 5 }},
{"review below attention", func(policy *AssessmentSignalPolicy) { policy.FastAnswersReview = policy.FastAnswersAttention - 1 }},
{"duplicate review below attention", func(policy *AssessmentSignalPolicy) { policy.DuplicateReviewBits = policy.DuplicateAttentionBits - 1 }},
{"deviation ratio below two", func(policy *AssessmentSignalPolicy) { policy.DeviationRatio = 15000 }},
{"deviation needs several answers", func(policy *AssessmentSignalPolicy) { policy.DeviationMinAnswers = 2 }},
{"evidence bits beyond a hash", func(policy *AssessmentSignalPolicy) { policy.DuplicateSequenceCapBits = 65 }},
{"client threshold zero", func(policy *AssessmentSignalPolicy) { policy.ClientClipboardEventsAttention = 0 }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
test.change(&policy)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
@@ -0,0 +1,387 @@
package domain
import (
"crypto/sha256"
"errors"
"fmt"
"slices"
"time"
"github.com/google/uuid"
)
// ErrInvalidAssessmentReview reports a malformed server observation or review.
// Its text never includes an answer, an address, or a session identifier.
var ErrInvalidAssessmentReview = errors.New("invalid assessment review")
// AssessmentReviewBand is the manual-check hint of one attempt. It is stored
// for an operator only. It has no effect on the result, the category, or a
// quota, and no candidate or employer read carries it.
type AssessmentReviewBand string
const (
AssessmentReviewBandNormal AssessmentReviewBand = "normal"
AssessmentReviewBandAttention AssessmentReviewBand = "attention"
AssessmentReviewBandReview AssessmentReviewBand = "review"
)
func (band AssessmentReviewBand) rank() int {
switch band {
case AssessmentReviewBandNormal:
return 0
case AssessmentReviewBandAttention:
return 1
case AssessmentReviewBandReview:
return 2
default:
return -1
}
}
// IsKnown reports whether the band is one of the three stored values.
func (band AssessmentReviewBand) IsKnown() bool { return band.rank() >= 0 }
// AssessmentReviewReason names a signal group that raised the band.
type AssessmentReviewReason string
const (
AssessmentReviewReasonFastAnswers AssessmentReviewReason = "fast_answers"
AssessmentReviewReasonDeviatingAnswers AssessmentReviewReason = "deviating_answers"
AssessmentReviewReasonParallelSessions AssessmentReviewReason = "parallel_sessions"
AssessmentReviewReasonExtraNetworks AssessmentReviewReason = "extra_networks"
AssessmentReviewReasonDuplicateAnswers AssessmentReviewReason = "duplicate_answers"
AssessmentReviewReasonClientSignals AssessmentReviewReason = "client_signals"
)
// IsKnown reports whether the reason is a stored value.
func (reason AssessmentReviewReason) IsKnown() bool {
switch reason {
case AssessmentReviewReasonFastAnswers, AssessmentReviewReasonDeviatingAnswers,
AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks,
AssessmentReviewReasonDuplicateAnswers, AssessmentReviewReasonClientSignals:
return true
default:
return false
}
}
// AssessmentDigest is a keyed 32-byte digest. It stands for an answer, a
// session, or a network address without carrying any of them.
type AssessmentDigest [sha256.Size]byte
// IsZero reports an unset digest.
func (digest AssessmentDigest) IsZero() bool { return digest == AssessmentDigest{} }
// AssessmentAnswerObservation is the server-side record of one accepted
// answer: how long it took, and a keyed fingerprint of the normalized answer
// that allows comparing answers of different candidates without storing them.
type AssessmentAnswerObservation struct {
AttemptID AssessmentAttemptID
UserID uuid.UUID
ItemInstanceID uuid.UUID
FamilyID AssessmentFamilyID
FamilyVersion int32
Seed VariantSeed
AnswerFormat string
Fingerprint AssessmentDigest
// KeyVersion names the key generation of Fingerprint, so a rotation is
// explicit and fingerprints of different generations are never compared.
KeyVersion int16
ElapsedMS int32
// MeasuredFromAnswer is true when ElapsedMS starts at the previous answer,
// which is when this item was shown. The first item of a work session starts
// at the session start, which is only an upper bound of the time the item
// was on screen, so such a time is not used for the speed signals.
MeasuredFromAnswer bool
ObservedAt time.Time
}
// Validate checks that the observation can be stored.
func (observation AssessmentAnswerObservation) Validate() error {
const location = "AssessmentAnswerObservation.Validate"
switch {
case observation.AttemptID.IsZero(), observation.UserID == uuid.Nil, observation.ItemInstanceID == uuid.Nil,
uuid.UUID(observation.FamilyID) == uuid.Nil, observation.FamilyVersion < 1:
return fmt.Errorf("%s - identifiers are required: %w", location, ErrInvalidAssessmentReview)
case observation.AnswerFormat != AnswerFormatInteger && observation.AnswerFormat != AnswerFormatIntegerSequence:
return fmt.Errorf("%s - answer format is unsupported: %w", location, ErrInvalidAssessmentReview)
case observation.Fingerprint.IsZero(), observation.KeyVersion < 1:
return fmt.Errorf("%s - fingerprint and its key version are required: %w", location, ErrInvalidAssessmentReview)
case observation.ElapsedMS < 0, observation.ObservedAt.IsZero():
return fmt.Errorf("%s - elapsed time and observation time are required: %w", location, ErrInvalidAssessmentReview)
}
return nil
}
// AssessmentOriginSource says which request produced an origin mark.
type AssessmentOriginSource string
const (
AssessmentOriginAnswer AssessmentOriginSource = "answer"
AssessmentOriginSignals AssessmentOriginSource = "signals"
)
// AssessmentOriginMark records, for one accepted request, keyed digests of the
// authenticated session and of the client network. The digests are bound to
// the attempt, so they cannot be correlated between attempts, and they are
// useless without the server secret. NetworkDigest is absent when the client
// address could not be resolved.
type AssessmentOriginMark struct {
ID uuid.UUID
AttemptID AssessmentAttemptID
Source AssessmentOriginSource
ObservedAt time.Time
SessionDigest AssessmentDigest
NetworkDigest AssessmentDigest
KeyVersion int16
}
// Validate checks that the mark can be stored.
func (mark AssessmentOriginMark) Validate() error {
const location = "AssessmentOriginMark.Validate"
if mark.ID == uuid.Nil || mark.AttemptID.IsZero() || mark.ObservedAt.IsZero() || mark.SessionDigest.IsZero() || mark.KeyVersion < 1 {
return fmt.Errorf("%s - identifiers, time, session digest, and key version are required: %w", location, ErrInvalidAssessmentReview)
}
if mark.Source != AssessmentOriginAnswer && mark.Source != AssessmentOriginSignals {
return fmt.Errorf("%s - source is unknown: %w", location, ErrInvalidAssessmentReview)
}
return nil
}
// AssessmentResponseSample is the server time of one answer.
type AssessmentResponseSample struct {
AnswerFormat string
ElapsedMS int32
MeasuredFromAnswer bool
}
// AssessmentResponseTimes counts the answers and the answers that the policy
// calls fast or anomalously fast. Only server time is used: the client may
// report durations of its own, but they never replace it.
type AssessmentResponseTimes struct {
Answered int32
Fast int32
Deviating int32
}
// ClassifyResponseTimes applies the fast floors and the median deviation of
// the policy. Only answers measured from the previous answer count. The
// deviation is computed within one answer format, so a slow format does not
// make a quick one look anomalous, and only on the fast side: a slow answer is
// not suspicious by itself. One answer contributes to at most one counter: an
// answer under its floor is fast and is not counted again as a deviation.
func (policy AssessmentSignalPolicy) ClassifyResponseTimes(samples []AssessmentResponseSample) AssessmentResponseTimes {
result := AssessmentResponseTimes{Answered: int32(min(len(samples), maxAssessmentAttemptItems))}
byFormat := map[string][]int64{}
for _, sample := range samples {
if !sample.MeasuredFromAnswer {
continue
}
floor := policy.fastFloor(sample.AnswerFormat)
if sample.ElapsedMS < floor {
result.Fast++
// Kept for the median, but marked so it is not a deviation too.
byFormat[sample.AnswerFormat] = append(byFormat[sample.AnswerFormat], -int64(sample.ElapsedMS)-1)
continue
}
byFormat[sample.AnswerFormat] = append(byFormat[sample.AnswerFormat], int64(sample.ElapsedMS))
}
ratio := int64(policy.DeviationRatio)
for _, marked := range byFormat {
if len(marked) < int(policy.DeviationMinAnswers) {
continue
}
elapsed := make([]int64, len(marked))
for index, value := range marked {
elapsed[index] = value
if value < 0 {
elapsed[index] = -value - 1
}
}
slices.Sort(elapsed)
median := elapsed[len(elapsed)/2]
if len(elapsed)%2 == 0 {
median = (elapsed[len(elapsed)/2-1] + elapsed[len(elapsed)/2]) / 2
}
median = max(median, 1)
for _, value := range marked {
// value is more than ratio times below the median, in basis points.
if value >= 0 && max(value, 1)*ratio < median*int64(basisPointsPerUnit) {
result.Deviating++
}
}
}
return result
}
func (policy AssessmentSignalPolicy) fastFloor(format string) int32 {
if format == AnswerFormatIntegerSequence {
return policy.FastFloorSequenceMS
}
return policy.FastFloorIntegerMS
}
// AssessmentOriginAnomalies counts the origin changes of an attempt.
type AssessmentOriginAnomalies struct {
// ParallelAlternations counts requests that came back to an earlier
// session after another session had been used, as when two logged-in
// sessions work on one attempt in turn. A single move from one session to
// another is not counted.
ParallelAlternations int32
// ExtraNetworks counts the distinct network digests beyond the first. A
// move to another network and back is one extra network.
ExtraNetworks int32
}
// CountOriginAnomalies orders the marks by time and then by ID and counts
// alternations between sessions and distinct client networks.
func CountOriginAnomalies(marks []AssessmentOriginMark) AssessmentOriginAnomalies {
ordered := slices.Clone(marks)
slices.SortStableFunc(ordered, func(left, right AssessmentOriginMark) int {
if byTime := left.ObservedAt.Compare(right.ObservedAt); byTime != 0 {
return byTime
}
return slices.Compare(left.ID[:], right.ID[:])
})
var anomalies AssessmentOriginAnomalies
seenSessions := map[AssessmentDigest]struct{}{}
networks := map[AssessmentDigest]struct{}{}
var previousSession AssessmentDigest
for _, mark := range ordered {
_, seen := seenSessions[mark.SessionDigest]
if seen && mark.SessionDigest != previousSession {
anomalies.ParallelAlternations++
}
seenSessions[mark.SessionDigest] = struct{}{}
previousSession = mark.SessionDigest
if !mark.NetworkDigest.IsZero() {
networks[mark.NetworkDigest] = struct{}{}
}
}
anomalies.ExtraNetworks = int32(max(len(networks)-1, 0)) //nolint:gosec // The number of marks of an attempt is bounded by its stored list.
return anomalies
}
// AssessmentReviewMeasures is everything the band is computed from. Every
// field is a count or a duration; none of them holds an answer or an address.
// The duplicate fields describe the pair of attempts with the most evidence.
type AssessmentReviewMeasures struct {
AnsweredItems int32
FastAnswers int32
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMS int64
ClientClipboardEvents int32
ClientFullscreenExits int32
}
// AssessmentReviewOutcome is the computed band with the groups behind it.
type AssessmentReviewOutcome struct {
Band AssessmentReviewBand
Reasons []AssessmentReviewReason
}
// Evaluate computes the band. Server signals decide it. Parallel sessions and
// extra networks are weak and correlated (a phone and a laptop produce both), so
// they are one group: alone it reaches attention at most, and review only
// together with a strong signal (fast answers, deviating answers, or duplicate
// answers) at attention or above. Client signals can only raise a normal band
// to attention, because a browser reports them.
func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures) AssessmentReviewOutcome {
type signal struct {
reason AssessmentReviewReason
band AssessmentReviewBand
weak bool
}
signals := []signal{
{AssessmentReviewReasonFastAnswers, signalLevel(measures.FastAnswers, policy.FastAnswersAttention, policy.FastAnswersReview), false},
{AssessmentReviewReasonDeviatingAnswers, signalLevel(measures.DeviatingAnswers, policy.DeviatingAnswersAttention, policy.DeviatingAnswersReview), false},
{AssessmentReviewReasonParallelSessions, signalLevel(measures.ParallelAlternations, policy.ParallelAlternationsAttention, policy.ParallelAlternationsReview), true},
{AssessmentReviewReasonExtraNetworks, signalLevel(measures.ExtraNetworks, policy.ExtraNetworksAttention, policy.ExtraNetworksReview), true},
{AssessmentReviewReasonDuplicateAnswers, signalLevel(measures.DuplicateEvidenceBits, policy.DuplicateAttentionBits, policy.DuplicateReviewBits), false},
}
strongRaised := false
for _, entry := range signals {
if !entry.weak && entry.band.rank() > 0 {
strongRaised = true
}
}
outcome := AssessmentReviewOutcome{Band: AssessmentReviewBandNormal}
for _, entry := range signals {
band := entry.band
if entry.weak && band == AssessmentReviewBandReview && !strongRaised {
band = AssessmentReviewBandAttention
}
if band.rank() == 0 {
continue
}
outcome.Reasons = append(outcome.Reasons, entry.reason)
if band.rank() > outcome.Band.rank() {
outcome.Band = band
}
}
if measures.ClientFocusLossMS >= int64(policy.ClientFocusLossAttentionMS) ||
measures.ClientClipboardEvents >= policy.ClientClipboardEventsAttention ||
measures.ClientFullscreenExits >= policy.ClientFullscreenExitsAttention {
outcome.Reasons = append(outcome.Reasons, AssessmentReviewReasonClientSignals)
if outcome.Band == AssessmentReviewBandNormal {
outcome.Band = AssessmentReviewBandAttention
}
}
return outcome
}
func signalLevel(value, attention, review int32) AssessmentReviewBand {
switch {
case value >= review:
return AssessmentReviewBandReview
case value >= attention:
return AssessmentReviewBandAttention
default:
return AssessmentReviewBandNormal
}
}
// AssessmentAttemptReview is the stored review of an attempt. PolicyVersionID
// pins the policy version that computed it, which is the version the attempt
// itself is pinned to.
type AssessmentAttemptReview struct {
AttemptID AssessmentAttemptID
PolicyVersionID PolicyVersionID
PolicyVersion int32
Measures AssessmentReviewMeasures
Outcome AssessmentReviewOutcome
EvaluatedAt time.Time
UpdatedAt time.Time
}
// Validate checks that the review can be stored.
func (review AssessmentAttemptReview) Validate() error {
const location = "AssessmentAttemptReview.Validate"
if review.AttemptID.IsZero() || review.PolicyVersionID.IsZero() || !review.Outcome.Band.IsKnown() ||
review.EvaluatedAt.IsZero() || review.UpdatedAt.IsZero() {
return fmt.Errorf("%s - attempt, policy, band, and times are required: %w", location, ErrInvalidAssessmentReview)
}
for _, reason := range review.Outcome.Reasons {
if !reason.IsKnown() {
return fmt.Errorf("%s - reason is unknown: %w", location, ErrInvalidAssessmentReview)
}
}
return nil
}
// AssessmentReviewActor is the audit handle of an operator who reads a
// review, written as operator:<handle>. It is not authentication.
type AssessmentReviewActor string
// ParseAssessmentReviewActor accepts operator:<handle>.
func ParseAssessmentReviewActor(value string) (AssessmentReviewActor, error) {
if len(value) > 128 || !assessmentOperatorPattern.MatchString(value) {
return "", fmt.Errorf("domain.ParseAssessmentReviewActor - actor must be operator:<handle> of at most 128 bytes in lowercase letters, digits, '.', '_', or '-': %w", ErrInvalidAssessmentReview)
}
return AssessmentReviewActor(value), nil
}
@@ -0,0 +1,167 @@
package domain
import (
"slices"
"testing"
"time"
"github.com/google/uuid"
)
func answerSample(format string, elapsedMS int32, fromAnswer bool) AssessmentResponseSample {
return AssessmentResponseSample{AnswerFormat: format, ElapsedMS: elapsedMS, MeasuredFromAnswer: fromAnswer}
}
func TestClassifyResponseTimesUsesFloorsPerFormat(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
samples := []AssessmentResponseSample{
answerSample(AnswerFormatInteger, 4999, true),
answerSample(AnswerFormatInteger, 5000, true),
answerSample(AnswerFormatIntegerSequence, 7999, true),
answerSample(AnswerFormatIntegerSequence, 8000, true),
// The first item of a work session is measured from the session start,
// when the item was not necessarily on screen, so it is not counted.
answerSample(AnswerFormatInteger, 10, false),
}
got := policy.ClassifyResponseTimes(samples)
if got.Answered != 5 || got.Fast != 2 || got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes(floors) = %+v, want 5 answers, 2 fast, and no deviation below the minimum count", got)
}
}
func TestClassifyResponseTimesDeviatesOnTheFastSideWithinOneFormat(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
steady := func(count int, elapsed int32) []AssessmentResponseSample {
samples := make([]AssessmentResponseSample, 0, count+1)
for range count {
samples = append(samples, answerSample(AnswerFormatInteger, elapsed, true))
}
return samples
}
if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 11999, true))); got.Deviating != 1 || got.Fast != 0 {
t.Fatalf("ClassifyResponseTimes(fast outlier) = %+v, want one deviation below a fifth of the median", got)
}
if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 12001, true))); got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes(inside the ratio) = %+v, want no deviation", got)
}
if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 900000, true))); got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes(slow outlier) = %+v, want no deviation: a slow answer is not suspicious", got)
}
// Another format has its own median and its own minimum count: five slow
// orders do not make a quick integer answer deviate, and the integer
// answers alone are too few.
mixed := append(steady(3, 60000), answerSample(AnswerFormatIntegerSequence, 70000, true), answerSample(AnswerFormatIntegerSequence, 70000, true))
mixed = append(mixed, answerSample(AnswerFormatInteger, 9000, true))
if got := policy.ClassifyResponseTimes(mixed); got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes(mixed formats) = %+v, want no deviation: each format has fewer than %d answers", got, policy.DeviationMinAnswers)
}
// Answers measured from a session start are left out of the median too.
withStart := append(steady(5, 60000), answerSample(AnswerFormatInteger, 60000, false), answerSample(AnswerFormatInteger, 1, false))
if got := policy.ClassifyResponseTimes(withStart); got.Deviating != 0 || got.Fast != 0 {
t.Fatalf("ClassifyResponseTimes(session start items) = %+v, want them excluded", got)
}
}
func TestClassifyResponseTimesCountsAnAnswerOnce(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
samples := make([]AssessmentResponseSample, 0, 7)
for range 6 {
samples = append(samples, answerSample(AnswerFormatInteger, 60000, true))
}
// Under the floor and far below the median: fast, and not a deviation too.
samples = append(samples, answerSample(AnswerFormatInteger, 1000, true))
got := policy.ClassifyResponseTimes(samples)
if got.Fast != 1 || got.Deviating != 0 {
t.Fatalf("ClassifyResponseTimes() = %+v, want the answer counted as fast only", got)
}
}
func originMark(second int, session, network byte) AssessmentOriginMark {
mark := AssessmentOriginMark{
ID: uuid.New(), AttemptID: AssessmentAttemptID(uuid.New()), Source: AssessmentOriginAnswer,
ObservedAt: time.Date(2026, time.October, 1, 12, 0, second, 0, time.UTC),
SessionDigest: AssessmentDigest{session}, KeyVersion: 1,
}
if network != 0 {
mark.NetworkDigest = AssessmentDigest{network}
}
return mark
}
func TestCountOriginAnomalies(t *testing.T) {
tests := []struct {
name string
marks []AssessmentOriginMark
want AssessmentOriginAnomalies
}{
{"one session and one network", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 1), originMark(3, 1, 1)}, AssessmentOriginAnomalies{}},
{"moving once to another session is not parallel", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 2, 1), originMark(3, 2, 1)}, AssessmentOriginAnomalies{}},
{"turns between two sessions", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 2, 1), originMark(3, 1, 1), originMark(4, 2, 1)}, AssessmentOriginAnomalies{ParallelAlternations: 2}},
{"unknown addresses are skipped and a return is not a new network", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 0), originMark(3, 1, 2), originMark(4, 1, 2), originMark(5, 1, 1)}, AssessmentOriginAnomalies{ExtraNetworks: 1}},
{"three networks", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 2), originMark(3, 1, 3), originMark(4, 1, 1)}, AssessmentOriginAnomalies{ExtraNetworks: 2}},
{"order follows time and not the slice", []AssessmentOriginMark{originMark(4, 2, 1), originMark(1, 1, 1), originMark(3, 1, 1), originMark(2, 2, 1)}, AssessmentOriginAnomalies{ParallelAlternations: 2}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := CountOriginAnomalies(test.marks); got != test.want {
t.Fatalf("CountOriginAnomalies() = %+v, want %+v", got, test.want)
}
})
}
}
func TestEvaluateBandFollowsThePolicyAndClientSignalsOnlyRaiseToAttention(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
tests := []struct {
name string
measures AssessmentReviewMeasures
wantBand AssessmentReviewBand
wantReasons []AssessmentReviewReason
}{
{"nothing observed", AssessmentReviewMeasures{AnsweredItems: 8}, AssessmentReviewBandNormal, nil},
{"fast answers reach attention", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers}},
{"fast answers reach review", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersReview}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers}},
{"a weak signal alone stops at attention", AssessmentReviewMeasures{ExtraNetworks: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonExtraNetworks}},
{"parallel sessions alone stop at attention", AssessmentReviewMeasures{ParallelAlternations: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonParallelSessions}},
{"two weak signals do not lift each other", AssessmentReviewMeasures{ParallelAlternations: 50, ExtraNetworks: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks}},
{"a weak signal reaches review beside a server signal", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ExtraNetworks: 50}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonExtraNetworks}},
{"less duplicate evidence than the attention level is no flag", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateAttentionBits - 1}, AssessmentReviewBandNormal, nil},
{"duplicate evidence at the attention level", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateAttentionBits}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonDuplicateAnswers}},
{"duplicate evidence at the review level", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateReviewBits}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonDuplicateAnswers}},
{"client signals alone raise a normal band to attention", AssessmentReviewMeasures{ClientFocusLossMS: int64(policy.ClientFocusLossAttentionMS)}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}},
{"client signals never raise attention to review", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ClientClipboardEvents: 1000, ClientFullscreenExits: 1000, ClientFocusLossMS: 1 << 40}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonClientSignals}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := policy.Evaluate(test.measures)
if got.Band != test.wantBand || !slices.Equal(got.Reasons, test.wantReasons) {
t.Fatalf("Evaluate() = %+v, want band %s reasons %v", got, test.wantBand, test.wantReasons)
}
})
}
}
func TestEvaluateUsesTheThresholdsOfTheGivenPolicy(t *testing.T) {
measures := AssessmentReviewMeasures{FastAnswers: 4}
strict := DemoAssessmentSignalPolicy()
strict.FastAnswersAttention, strict.FastAnswersReview = 2, 4
relaxed := DemoAssessmentSignalPolicy()
relaxed.FastAnswersAttention, relaxed.FastAnswersReview = 100, 200
if got := strict.Evaluate(measures).Band; got != AssessmentReviewBandReview {
t.Fatalf("strict policy band = %s, want review", got)
}
if got := relaxed.Evaluate(measures).Band; got != AssessmentReviewBandNormal {
t.Fatalf("relaxed policy band = %s, want normal", got)
}
}
func TestParseAssessmentReviewActorRequiresAnOperatorHandle(t *testing.T) {
if _, err := ParseAssessmentReviewActor("operator:night.shift-1"); err != nil {
t.Fatalf("ParseAssessmentReviewActor(valid) error = %v", err)
}
for _, invalid := range []string{"", "alice", "operator:", "operator:Alice", "operator:a@b.example", "system:cron"} {
if _, err := ParseAssessmentReviewActor(invalid); err == nil {
t.Errorf("ParseAssessmentReviewActor(%q) accepted an invalid actor", invalid)
}
}
}
+13
View File
@@ -130,6 +130,10 @@ func (policy ProductPolicy) clone() ProductPolicy {
trainingCopy := *training
copied.Assessment.Training = &trainingCopy
}
if signals := policy.Assessment.Signals; signals != nil {
signalsCopy := *signals
copied.Assessment.Signals = &signalsCopy
}
if support := policy.Support; support != nil {
supportCopy := *support
copied.Support = &supportCopy
@@ -324,6 +328,10 @@ type AssessmentPolicy struct {
// Training is an explicit non-qualification policy section. It is nil in
// immutable legacy policies and never inherits real assessment settings.
Training *AssessmentTrainingPolicy
// Signals holds the thresholds of the manual-review band. It is nil in
// policy versions that predate it; such a version computes no band and
// never inherits another version's thresholds.
Signals *AssessmentSignalPolicy
}
// AssessmentAttemptPolicy holds the versioned execution limits for a newly
@@ -452,6 +460,11 @@ func (policy AssessmentPolicy) Validate() error {
return err
}
}
if policy.Signals != nil {
if err := policy.Signals.Validate(); err != nil {
return err
}
}
return nil
}
+10
View File
@@ -86,3 +86,13 @@ func DemoProductPolicyV2() ProductPolicy {
policy.Support = &support
return policy
}
// DemoProductPolicyV3 returns the demo policy with the manual-review band
// thresholds on top of DemoProductPolicyV2. It is published explicitly; a
// stored version is never rewritten, and startup seeding publishes V1 only.
func DemoProductPolicyV3() ProductPolicy {
policy := DemoProductPolicyV2()
signals := DemoAssessmentSignalPolicy()
policy.Assessment.Signals = &signals
return policy
}
+79 -2
View File
@@ -88,6 +88,7 @@ type assessmentPolicyDocument struct {
StopRule *assessmentStopDocument `json:"stop_rule"`
Attempt *assessmentAttemptDocument `json:"attempt,omitempty"`
Training *assessmentTrainingDocument `json:"training,omitempty"`
Signals *assessmentSignalsDocument `json:"signals,omitempty"`
}
type assessmentPolicyV1Document struct {
@@ -111,6 +112,28 @@ type assessmentAttemptDocument struct {
BasicPassMarkBP *BasisPoints `json:"basic_pass_mark_bp"`
}
type assessmentSignalsDocument struct {
FastFloorIntegerMS *int32 `json:"fast_floor_integer_ms"`
FastFloorSequenceMS *int32 `json:"fast_floor_sequence_ms"`
FastAnswersAttention *int32 `json:"fast_answers_attention"`
FastAnswersReview *int32 `json:"fast_answers_review"`
DeviationRatioBP *BasisPoints `json:"deviation_ratio_bp"`
DeviationMinAnswers *int32 `json:"deviation_min_answers"`
DeviatingAnswersAttention *int32 `json:"deviating_answers_attention"`
DeviatingAnswersReview *int32 `json:"deviating_answers_review"`
ParallelAlternationsAttention *int32 `json:"parallel_alternations_attention"`
ParallelAlternationsReview *int32 `json:"parallel_alternations_review"`
ExtraNetworksAttention *int32 `json:"extra_networks_attention"`
ExtraNetworksReview *int32 `json:"extra_networks_review"`
DuplicateIntegerCapBits *int32 `json:"duplicate_integer_cap_bits"`
DuplicateSequenceCapBits *int32 `json:"duplicate_sequence_cap_bits"`
DuplicateBitsAttention *int32 `json:"duplicate_bits_attention"`
DuplicateBitsReview *int32 `json:"duplicate_bits_review"`
ClientFocusLossAttentionMS *int32 `json:"client_focus_loss_attention_ms"`
ClientClipboardEventsAttention *int32 `json:"client_clipboard_events_attention"`
ClientFullscreenExitsAttention *int32 `json:"client_fullscreen_exits_attention"`
}
type assessmentTrainingDocument struct {
DemoExpressDurationSeconds *int32 `json:"demo_express_duration_seconds"`
DemoExpressItemCount *int32 `json:"demo_express_item_count"`
@@ -155,7 +178,7 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
}
}
schemaVersion := int32(productPolicySchemaVersionV1)
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Support != nil {
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil || policy.Support != nil {
schemaVersion = productPolicySchemaVersionV2
}
document := productPolicyDocument{
@@ -196,6 +219,7 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
},
Attempt: encodeAssessmentAttemptPolicy(assessment.Attempt),
Training: encodeAssessmentTrainingPolicy(assessment.Training),
Signals: encodeAssessmentSignalPolicy(assessment.Signals),
},
Identity: &identityPolicyDocument{
VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime),
@@ -241,6 +265,33 @@ func encodeAssessmentTrainingPolicy(policy *AssessmentTrainingPolicy) *assessmen
}
}
func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSignalsDocument {
if policy == nil {
return nil
}
return &assessmentSignalsDocument{
FastFloorIntegerMS: pointer(policy.FastFloorIntegerMS),
FastFloorSequenceMS: pointer(policy.FastFloorSequenceMS),
FastAnswersAttention: pointer(policy.FastAnswersAttention),
FastAnswersReview: pointer(policy.FastAnswersReview),
DeviationRatioBP: pointer(policy.DeviationRatio),
DeviationMinAnswers: pointer(policy.DeviationMinAnswers),
DeviatingAnswersAttention: pointer(policy.DeviatingAnswersAttention),
DeviatingAnswersReview: pointer(policy.DeviatingAnswersReview),
ParallelAlternationsAttention: pointer(policy.ParallelAlternationsAttention),
ParallelAlternationsReview: pointer(policy.ParallelAlternationsReview),
ExtraNetworksAttention: pointer(policy.ExtraNetworksAttention),
ExtraNetworksReview: pointer(policy.ExtraNetworksReview),
DuplicateIntegerCapBits: pointer(policy.DuplicateIntegerCapBits),
DuplicateSequenceCapBits: pointer(policy.DuplicateSequenceCapBits),
DuplicateBitsAttention: pointer(policy.DuplicateAttentionBits),
DuplicateBitsReview: pointer(policy.DuplicateReviewBits),
ClientFocusLossAttentionMS: pointer(policy.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: pointer(policy.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: pointer(policy.ClientFullscreenExitsAttention),
}
}
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
return &organizationTierQuotaDocument{
Active: pointer(quota.Active),
@@ -295,7 +346,7 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
return ProductPolicy{}, err
}
assessment := parsed.Assessment
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil)
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil || assessment.Signals != nil)
if !hasAssessmentExtension && parsed.Support == nil {
return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension")
}
@@ -371,6 +422,31 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
IdleTimeoutSeconds: require(&reader, "assessment.training.idle_timeout_seconds", training.IdleTimeoutSeconds),
}
}
var signalPolicy *AssessmentSignalPolicy
if assessment.Signals != nil {
signals := assessment.Signals
signalPolicy = &AssessmentSignalPolicy{
FastFloorIntegerMS: require(&reader, "assessment.signals.fast_floor_integer_ms", signals.FastFloorIntegerMS),
FastFloorSequenceMS: require(&reader, "assessment.signals.fast_floor_sequence_ms", signals.FastFloorSequenceMS),
FastAnswersAttention: require(&reader, "assessment.signals.fast_answers_attention", signals.FastAnswersAttention),
FastAnswersReview: require(&reader, "assessment.signals.fast_answers_review", signals.FastAnswersReview),
DeviationRatio: require(&reader, "assessment.signals.deviation_ratio_bp", signals.DeviationRatioBP),
DeviationMinAnswers: require(&reader, "assessment.signals.deviation_min_answers", signals.DeviationMinAnswers),
DeviatingAnswersAttention: require(&reader, "assessment.signals.deviating_answers_attention", signals.DeviatingAnswersAttention),
DeviatingAnswersReview: require(&reader, "assessment.signals.deviating_answers_review", signals.DeviatingAnswersReview),
ParallelAlternationsAttention: require(&reader, "assessment.signals.parallel_alternations_attention", signals.ParallelAlternationsAttention),
ParallelAlternationsReview: require(&reader, "assessment.signals.parallel_alternations_review", signals.ParallelAlternationsReview),
ExtraNetworksAttention: require(&reader, "assessment.signals.extra_networks_attention", signals.ExtraNetworksAttention),
ExtraNetworksReview: require(&reader, "assessment.signals.extra_networks_review", signals.ExtraNetworksReview),
DuplicateIntegerCapBits: require(&reader, "assessment.signals.duplicate_integer_cap_bits", signals.DuplicateIntegerCapBits),
DuplicateSequenceCapBits: require(&reader, "assessment.signals.duplicate_sequence_cap_bits", signals.DuplicateSequenceCapBits),
DuplicateAttentionBits: require(&reader, "assessment.signals.duplicate_bits_attention", signals.DuplicateBitsAttention),
DuplicateReviewBits: require(&reader, "assessment.signals.duplicate_bits_review", signals.DuplicateBitsReview),
ClientFocusLossAttentionMS: require(&reader, "assessment.signals.client_focus_loss_attention_ms", signals.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: require(&reader, "assessment.signals.client_clipboard_events_attention", signals.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: require(&reader, "assessment.signals.client_fullscreen_exits_attention", signals.ClientFullscreenExitsAttention),
}
}
policy := ProductPolicy{
Invitations: InvitationPolicy{
ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays),
@@ -406,6 +482,7 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
},
Attempt: attemptPolicy,
Training: trainingPolicy,
Signals: signalPolicy,
},
Identity: IdentityPolicy{
VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours),
@@ -5,10 +5,51 @@ import (
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var ErrAssessmentSignalOutcomeNotFound = errors.New("assessment signal outcome not found")
var (
ErrAssessmentSignalOutcomeNotFound = errors.New("assessment signal outcome not found")
ErrAssessmentReviewNotFound = errors.New("assessment attempt review not found")
)
// AssessmentReviewInputs are the stored facts a review is computed from, apart
// from the comparison with other attempts. They hold no answer, address, or
// session identifier.
type AssessmentReviewInputs struct {
Answers []domain.AssessmentResponseSample
Marks []domain.AssessmentOriginMark
ClientFocusLossMS int64
ClientClipboardCount int32
ClientFullscreenExit int32
}
// AssessmentDuplicateQuery selects the pairs of attempts that share answers.
// The caps come from the policy of the attempt being evaluated.
type AssessmentDuplicateQuery struct {
IntegerCapBits int32
SequenceCapBits int32
// MinBits drops pairs with less evidence.
MinBits int32
// EndedOnly keeps only attempts that are over at Now: terminal, or past
// their deadline.
EndedOnly bool
Now time.Time
Limit int32
}
// AssessmentDuplicatePair is one other attempt that shares answers with the
// evaluated one. It is used inside the usecase only: nothing that identifies
// the other attempt or its candidate leaves it.
type AssessmentDuplicatePair struct {
AttemptID domain.AssessmentAttemptID
PolicyVersionID domain.PolicyVersionID
EvidenceBits int32
IntegerItems int32
SequenceItems int32
}
type AssessmentSignalRepositories interface {
AssessmentSignals() AssessmentSignalRepository
@@ -23,4 +64,28 @@ type AssessmentSignalRepository interface {
SaveOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, attemptID domain.AssessmentAttemptID, receipt domain.AssessmentSignalReceipt) error
DeleteExpiredOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) error
GetOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (domain.AssessmentSignalReceipt, error)
// SaveAnswerObservation and SaveOriginMark store server-side facts of an
// accepted request in the current unit of work. The caller holds the row
// lock of the attempt; no other lock is taken.
SaveAnswerObservation(ctx context.Context, observation domain.AssessmentAnswerObservation) error
SaveOriginMark(ctx context.Context, mark domain.AssessmentOriginMark) error
LastOriginMark(ctx context.Context, attemptID domain.AssessmentAttemptID) (domain.AssessmentOriginMark, bool, error)
ReviewInputs(ctx context.Context, attemptID domain.AssessmentAttemptID) (AssessmentReviewInputs, error)
// DuplicatePairs lists the other attempts that share answers with the given
// one, strongest first and bounded by the query.
DuplicatePairs(ctx context.Context, attemptID domain.AssessmentAttemptID, query AssessmentDuplicateQuery) ([]AssessmentDuplicatePair, error)
// ReviewSubject returns the product policy version a real attempt is pinned
// to; found is false for an unknown or training attempt.
ReviewSubject(ctx context.Context, attemptID domain.AssessmentAttemptID) (domain.PolicyVersionID, bool, error)
// LockReview takes the transaction-scoped lock of one attempt's review. A
// job locks every review it will write, in ascending attempt order, before
// it reads any fact, so concurrent evaluations of one attempt run one after
// another and the later one reads what the earlier one committed.
LockReview(ctx context.Context, attemptID domain.AssessmentAttemptID) error
// SaveReview stores the review; the times come from the database clock.
SaveReview(ctx context.Context, review domain.AssessmentAttemptReview) error
GetReview(ctx context.Context, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptReview, error)
RecordReviewRead(ctx context.Context, id uuid.UUID, attemptID domain.AssessmentAttemptID, actor domain.AssessmentReviewActor, found bool, at time.Time) error
}
@@ -0,0 +1,29 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
)
// ErrAssessmentSignalNoticeNotAcknowledged reports that the account has no
// acknowledgement for the requested notice version.
var ErrAssessmentSignalNoticeNotAcknowledged = errors.New("assessment signal notice is not acknowledged")
type AssessmentSignalNoticeRepositories interface {
AssessmentSignalNotices() AssessmentSignalNoticeRepository
}
// AssessmentSignalNoticeRepository stores the record that a candidate was shown
// the notice about collected assessment signals. The record is not a consent
// and no storage rule reads it.
type AssessmentSignalNoticeRepository interface {
// Get returns the time of the first acknowledgement of the version, or
// ErrAssessmentSignalNoticeNotAcknowledged.
Get(ctx context.Context, userID uuid.UUID, version int32) (time.Time, error)
// Acknowledge stores the acknowledgement when none exists for the version
// and keeps the earlier time otherwise. It returns the stored time.
Acknowledge(ctx context.Context, userID uuid.UUID, version int32, at time.Time) (time.Time, error)
}
@@ -70,6 +70,7 @@ type UnitOfWork interface {
AssessmentBankRepositories
AssessmentAttemptRepositories
AssessmentSignalRepositories
AssessmentSignalNoticeRepositories
SupportCaseRepositories
Policies() PolicyRepository
Deliveries() DeliveryRepository
+10 -1
View File
@@ -24,6 +24,9 @@ type SubmitAttemptAnswerCommand struct {
ExpectedVersion int64
IdempotencyKey string
Answer json.RawMessage
// Origin is the sender of the request. It feeds the server signals only and
// is not part of the idempotency fingerprint.
Origin RequestOrigin
}
type canonicalAttemptAnswerBody struct {
@@ -132,7 +135,7 @@ func (service *AttemptService) submitNewAnswer(
return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err)
}
databaseTime = databaseTime.UTC().Truncate(time.Microsecond)
return service.persistSubmittedAnswer(ctx, repository, scope, command, current, databaseTime, result)
return service.persistSubmittedAnswer(ctx, unit, repository, scope, command, current, databaseTime, result)
}
func lockAttemptForAnswer(
@@ -168,6 +171,7 @@ func lockAttemptForAnswer(
func (service *AttemptService) persistSubmittedAnswer(
ctx context.Context,
unit outbound.UnitOfWork,
repository outbound.AssessmentAttemptRepository,
scope outbound.AssessmentAttemptIdempotencyScope,
command SubmitAttemptAnswerCommand,
@@ -199,6 +203,11 @@ func (service *AttemptService) persistSubmittedAnswer(
if err := repository.SaveAnswer(ctx, current, updated, command.ItemID); err != nil {
return fmt.Errorf("%s - persist answer and attempt transition: %w", location, err)
}
if err := service.signalObserver.observeAnswer(
ctx, unit, current, updated, command.ItemID, command.Origin,
); err != nil {
return fmt.Errorf("%s - observe accepted answer: %w", location, err)
}
}
outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()}
if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil {
@@ -64,6 +64,7 @@ type AttemptService struct {
keyring Keyring
clock func() time.Time
categoryDecisions AssessmentCategoryDecisionService
signalObserver *SignalObserver
}
// NewAttemptService fails at startup when a required dependency is missing.
@@ -244,7 +244,16 @@ func (service *AttemptService) finalizeActiveAttempt(
}
return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr)
}
return service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result)
if err := service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result); err != nil {
return err
}
if !changed {
return nil
}
if err := service.signalObserver.scheduleEndedReview(ctx, unit, updated, databaseTime); err != nil {
return fmt.Errorf("%s - schedule review: %w", location, err)
}
return nil
}
func (service *AttemptService) persistFinalizedAttempt(
@@ -51,6 +51,7 @@ type SignalService struct {
transactor outbound.Transactor
keyring Keyring
clock func() time.Time
observer *SignalObserver
}
func NewSignalService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time) (*SignalService, error) {
@@ -65,6 +66,9 @@ type RecordSignalsCommand struct {
AttemptID domain.AssessmentAttemptID
IdempotencyKey string
Events []domain.AssessmentSignalEvent
// Origin is the sender of the batch. It feeds the server signals only and
// is not part of the idempotency fingerprint.
Origin RequestOrigin
}
type canonicalSignalRequest struct {
@@ -191,6 +195,11 @@ func (service *SignalService) recordNewSignals(
if err != nil {
return fmt.Errorf("%s - persist bounded event batch: %w", location, err)
}
if status == domain.AssessmentSignalReceiptAccepted {
if err := service.observer.recordOrigin(ctx, repository, attempt.ID(), domain.AssessmentOriginSignals, databaseTime, command.Origin); err != nil {
return fmt.Errorf("%s - record request origin: %w", location, err)
}
}
newReceipt, err := domain.NewAssessmentSignalReceipt(status, acceptedCount, databaseTime)
if err != nil {
return fmt.Errorf("%s - build receipt: %w", location, err)
@@ -0,0 +1,88 @@
package assessment
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
)
// CurrentSignalNoticeVersion is the version of the notice text that lists the
// collected assessment signals. Change it together with the client text so that
// every candidate acknowledges the new wording.
const CurrentSignalNoticeVersion int32 = 1
// ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice
// version other than the one the server requires.
var ErrSignalNoticeVersionMismatch = errors.New("assessment signal notice version is not current")
// SignalNoticeState is the acknowledgement state of the current notice version.
type SignalNoticeState struct {
Version int32
Acknowledged bool
AcknowledgedAt time.Time
}
// GetSignalNotice reads whether the candidate acknowledged the current notice.
// The record is not a consent and does not influence signal storage.
func (service *SignalService) GetSignalNotice(ctx context.Context, actorID uuid.UUID) (SignalNoticeState, error) {
const location = "SignalService.GetSignalNotice"
state := SignalNoticeState{Version: CurrentSignalNoticeVersion}
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, actorID, location); err != nil {
return err
}
acknowledgedAt, err := unit.AssessmentSignalNotices().Get(ctx, actorID, CurrentSignalNoticeVersion)
if errors.Is(err, outbound.ErrAssessmentSignalNoticeNotAcknowledged) {
return nil
}
if err != nil {
return fmt.Errorf("%s - read acknowledgement: %w", location, err)
}
state.Acknowledged, state.AcknowledgedAt = true, acknowledgedAt
return nil
})
if err != nil {
return SignalNoticeState{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return state, nil
}
// AcknowledgeSignalNotice records the first acknowledgement of the current
// notice version. A repeat keeps the stored time, so a retry after a lost
// response succeeds. Another version is refused without storing anything.
func (service *SignalService) AcknowledgeSignalNotice(
ctx context.Context,
actorID uuid.UUID,
version int32,
) (SignalNoticeState, error) {
const location = "SignalService.AcknowledgeSignalNotice"
if version != CurrentSignalNoticeVersion {
return SignalNoticeState{}, fmt.Errorf("%s - compare version: %w", location, ErrSignalNoticeVersionMismatch)
}
state := SignalNoticeState{Version: CurrentSignalNoticeVersion, Acknowledged: true}
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, actorID, location); err != nil {
return err
}
now, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time: %w", location, err)
}
state.AcknowledgedAt, err = unit.AssessmentSignalNotices().Acknowledge(
ctx, actorID, CurrentSignalNoticeVersion, now.UTC().Truncate(time.Microsecond),
)
if err != nil {
return fmt.Errorf("%s - store acknowledgement: %w", location, err)
}
return nil
})
if err != nil {
return SignalNoticeState{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return state, nil
}
@@ -0,0 +1,491 @@
package assessment
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"slices"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
// SignalDigester derives the keyed digests that stand for an answer, a login
// session, and a client network in the stored server signals. No digest can be
// turned back into what it stands for without the server secret.
type SignalDigester interface {
AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, canonicalAnswer []byte) domain.AssessmentDigest
AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest
AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest
// AssessmentDigestKeyVersion is the key generation of the digests above.
AssessmentDigestKeyVersion() int16
}
// SignalReviewJobKind is the scheduled job kind that computes reviews.
const SignalReviewJobKind = "assessment.signal_review"
const (
// signalReviewPairLimit bounds the other attempts one job refreshes.
signalReviewPairLimit = 50
// signalReviewDeadlineGrace moves the deadline job past the deadline, so an
// answer committed right at the deadline is in its facts.
signalReviewDeadlineGrace = time.Minute
signalReviewDeadlineKey = "deadline"
signalReviewEndedKey = "ended"
)
// RequestOrigin is what the HTTP adapter knows about the sender of an answer or
// a signal batch: the authenticated session and the limiter key of the client
// address. It is used only to make digests and is never stored or logged. An
// empty ClientKey means the address could not be resolved.
type RequestOrigin struct {
SessionID uuid.UUID
ClientKey string
}
// SignalObserver records server-side facts of real attempts and schedules the
// computation of the manual-review band. The band has no effect on the result,
// the category, or the quotas: it is written to its own tables by a scheduled
// job and read by no candidate or employer operation.
type SignalObserver struct {
digester SignalDigester
}
// NewSignalObserver fails at startup when the digester is missing.
func NewSignalObserver(digester SignalDigester) (*SignalObserver, error) {
if digester == nil {
return nil, errors.New("assessment.NewSignalObserver - digester must be set")
}
return &SignalObserver{digester: digester}, nil
}
// WithSignalObserver turns on the server signals of answers and the scheduling
// of reviews. Without it the service records nothing.
func (service *AttemptService) WithSignalObserver(observer *SignalObserver) *AttemptService {
service.signalObserver = observer
return service
}
// WithSignalObserver turns on the origin marks of accepted signal batches.
func (service *SignalService) WithSignalObserver(observer *SignalObserver) *SignalService {
service.observer = observer
return service
}
func isRealAttemptKind(kind domain.AssessmentAttemptKind) bool {
return kind == domain.AssessmentAttemptKindRoot || kind == domain.AssessmentAttemptKindCorrective
}
// observeAnswer stores the server time and the keyed answer fingerprint of an
// answer that was just accepted and the origin of its request, and makes sure
// a review job is due when the attempt reaches its deadline. It takes no lock
// besides the attempt row the caller already holds. The time runs from the last
// activity of the attempt, which is the previous answer or the start of the
// current work session, to the answer. It is server time only.
func (observer *SignalObserver) observeAnswer(
ctx context.Context,
unit outbound.UnitOfWork,
before, after domain.AssessmentAttempt,
itemID uuid.UUID,
origin RequestOrigin,
) error {
const location = "SignalObserver.observeAnswer"
if observer == nil || !isRealAttemptKind(after.Kind()) {
return nil
}
snapshot := after.Snapshot()
previous := before.Snapshot()
for _, item := range snapshot.Items {
if item.ID != itemID {
continue
}
answeredAt := item.AnsweredAt
elapsed := answeredAt.Sub(previous.LastActivityAt).Milliseconds()
elapsed = max(0, min(elapsed, int64(1<<31-1)))
observation := domain.AssessmentAnswerObservation{
AttemptID: snapshot.ID, UserID: snapshot.UserID, ItemInstanceID: item.ID,
FamilyID: item.Variant.FamilyID, FamilyVersion: item.Variant.FamilyVersion, Seed: item.Variant.Seed,
AnswerFormat: item.Variant.AnswerFormat,
Fingerprint: observer.digester.AssessmentAnswerFingerprint(
uuid.UUID(item.Variant.FamilyID), item.Variant.FamilyVersion, item.Answer,
),
KeyVersion: observer.digester.AssessmentDigestKeyVersion(),
ElapsedMS: int32(elapsed),
// The last activity is the previous answer when an item was answered
// since the session started; then that answer is when this item was
// shown. Otherwise the item is the first of the session.
MeasuredFromAnswer: answeredSince(previous),
ObservedAt: answeredAt,
}
repository := unit.AssessmentSignals()
if err := repository.SaveAnswerObservation(ctx, observation); err != nil {
return fmt.Errorf("%s - store answer observation: %w", location, err)
}
if err := observer.recordOrigin(ctx, repository, snapshot.ID, domain.AssessmentOriginAnswer, answeredAt, origin); err != nil {
return fmt.Errorf("%s - record request origin: %w", location, err)
}
if err := scheduleSignalReview(ctx, unit, snapshot.ID, signalReviewDeadlineKey, snapshot.ExpiresAt.Add(signalReviewDeadlineGrace)); err != nil {
return fmt.Errorf("%s - schedule the review at the deadline: %w", location, err)
}
return nil
}
return fmt.Errorf("%s - item is not part of the attempt: %w", location, domain.ErrInvalidAssessmentReview)
}
// answeredSince reports whether an item was answered at the last activity of
// the attempt.
func answeredSince(snapshot domain.AssessmentAttemptSnapshot) bool {
for _, item := range snapshot.Items {
if !item.AnsweredAt.IsZero() && item.AnsweredAt.Equal(snapshot.LastActivityAt) {
return true
}
}
return false
}
// recordOrigin stores the session and network digests of an accepted request
// when they differ from the last stored mark, which is enough to count session
// alternations and distinct networks. A request without a session is not
// marked. The caller holds the attempt row lock, so the last mark is stable.
func (observer *SignalObserver) recordOrigin(
ctx context.Context,
repository outbound.AssessmentSignalRepository,
attemptID domain.AssessmentAttemptID,
source domain.AssessmentOriginSource,
at time.Time,
origin RequestOrigin,
) error {
const location = "SignalObserver.recordOrigin"
if observer == nil || origin.SessionID == uuid.Nil {
return nil
}
id, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("%s - generate mark ID: %w", location, err)
}
mark := domain.AssessmentOriginMark{
ID: id, AttemptID: attemptID, Source: source, ObservedAt: at,
SessionDigest: observer.digester.AssessmentSessionDigest(attemptID.UUID(), origin.SessionID),
KeyVersion: observer.digester.AssessmentDigestKeyVersion(),
}
if origin.ClientKey != "" {
mark.NetworkDigest = observer.digester.AssessmentNetworkDigest(attemptID.UUID(), origin.ClientKey)
}
last, found, err := repository.LastOriginMark(ctx, attemptID)
if err != nil {
return fmt.Errorf("%s - read last mark: %w", location, err)
}
if found && last.SessionDigest == mark.SessionDigest && last.NetworkDigest == mark.NetworkDigest && last.KeyVersion == mark.KeyVersion {
return nil
}
if err := repository.SaveOriginMark(ctx, mark); err != nil {
return fmt.Errorf("%s - store origin mark: %w", location, err)
}
return nil
}
// scheduleEndedReview makes a review due now for an attempt that just ended.
// It runs in the transaction of the ending, so the job exists exactly when the
// attempt ended; the review itself is computed later by the job and can never
// block or change the result.
func (observer *SignalObserver) scheduleEndedReview(
ctx context.Context,
unit outbound.UnitOfWork,
attempt domain.AssessmentAttempt,
at time.Time,
) error {
if observer == nil || !isRealAttemptKind(attempt.Kind()) {
return nil
}
return scheduleSignalReview(ctx, unit, attempt.ID(), signalReviewEndedKey, at)
}
func scheduleSignalReview(
ctx context.Context,
unit outbound.UnitOfWork,
attemptID domain.AssessmentAttemptID,
suffix string,
dueAt time.Time,
) error {
const location = "assessment.scheduleSignalReview"
payload, err := json.Marshal(map[string]string{"attempt_id": attemptID.String()})
if err != nil {
return fmt.Errorf("%s - encode payload: %w", location, err)
}
job, err := domain.NewScheduledJob(domain.ScheduledJobInput{
Kind: SignalReviewJobKind, Key: attemptID.String() + ":" + suffix, DueAt: dueAt, Payload: payload,
})
if err != nil {
return fmt.Errorf("%s - build job: %w", location, err)
}
if _, err := unit.ScheduledJobs().Schedule(ctx, job); err != nil {
return fmt.Errorf("%s - schedule job: %w", location, err)
}
return nil
}
// SignalReviewJob computes the review of one attempt and refreshes the review
// of every other ended attempt that shares answers with it, so that a match
// flags both. It reads only committed facts and takes no lock apart from the
// rows it writes, which it writes in ascending attempt order, so concurrent
// jobs over shared attempts cannot deadlock. A job for an attempt that is still
// running when the match is found is not needed: the running attempt has its
// own job for its end and its deadline, and that job sees the other facts.
type SignalReviewJob struct {
logger *slog.Logger
}
// NewSignalReviewJob returns the handler of SignalReviewJobKind. The logger
// receives one line per job with counts and the duration, never an answer, an
// address, or a candidate.
func NewSignalReviewJob(logger *slog.Logger) *SignalReviewJob {
if logger == nil {
logger = slog.New(slog.DiscardHandler)
}
return &SignalReviewJob{logger: logger}
}
// JobKind is the stable kind name.
func (*SignalReviewJob) JobKind() string { return SignalReviewJobKind }
// Handle computes the reviews. A malformed payload is final; any storage error
// is retried by the runner with backoff.
func (handler *SignalReviewJob) Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
const location = "SignalReviewJob.Handle"
started := time.Now()
attemptID, err := signalReviewJobAttempt(job)
if err != nil {
return fmt.Errorf("%s - read payload: %w", location, err)
}
repository := unit.AssessmentSignals()
policyID, found, err := repository.ReviewSubject(ctx, attemptID)
if err != nil {
return fmt.Errorf("%s - read attempt: %w", location, err)
}
if !found {
// The attempt is gone (its account was deleted) or is not a real attempt.
return nil
}
policy, err := unit.Policies().GetByID(ctx, policyID)
if err != nil {
return fmt.Errorf("%s - read pinned policy: %w", location, err)
}
signals := policy.Policy().Assessment.Signals
if signals == nil {
return nil
}
now, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time: %w", location, err)
}
now = now.UTC().Truncate(time.Microsecond)
targets, err := reviewTargets(ctx, repository, attemptID, policyID, signals, now)
if err != nil {
return fmt.Errorf("%s - list matched attempts: %w", location, err)
}
if err := writeReviews(ctx, unit, targets, policy, now); err != nil {
return fmt.Errorf("%s - write reviews: %w", location, err)
}
handler.logger.InfoContext(ctx, "assessment review job finished",
slog.Int("reviews", len(targets)), slog.Int("matched_attempts", len(targets)-1),
slog.Int64("duration_ms", time.Since(started).Milliseconds()))
return nil
}
func signalReviewJobAttempt(job outbound.ClaimedJob) (domain.AssessmentAttemptID, error) {
var payload struct {
AttemptID string `json:"attempt_id"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil {
return domain.AssessmentAttemptID{}, fmt.Errorf("decode payload: %w", inbound.ErrJobRejected)
}
parsed, err := uuid.Parse(payload.AttemptID)
if err != nil || parsed == uuid.Nil {
return domain.AssessmentAttemptID{}, fmt.Errorf("payload names no attempt: %w", inbound.ErrJobRejected)
}
return domain.AssessmentAttemptID(parsed), nil
}
// writeReviews locks every review it will write, in ascending attempt order,
// before any fact is read. The later of two jobs over one attempt then waits
// here and reads what the earlier one committed, so no job overwrites a newer
// review with an older evaluation, and no lock order can form a cycle.
func writeReviews(
ctx context.Context,
unit outbound.UnitOfWork,
targets []reviewTarget,
own domain.PolicyVersion,
now time.Time,
) error {
repository := unit.AssessmentSignals()
for _, entry := range targets {
if err := repository.LockReview(ctx, entry.id); err != nil {
return fmt.Errorf("lock review: %w", err)
}
}
for _, entry := range targets {
pinned := own
if entry.policy != own.ID() {
var err error
if pinned, err = unit.Policies().GetByID(ctx, entry.policy); err != nil {
return fmt.Errorf("read pinned policy of a matched attempt: %w", err)
}
}
if err := evaluateReview(ctx, repository, entry.id, pinned, now); err != nil {
return fmt.Errorf("evaluate attempt: %w", err)
}
}
return nil
}
type reviewTarget struct {
id domain.AssessmentAttemptID
policy domain.PolicyVersionID
}
// reviewTargets lists the attempt itself and the ended attempts whose pair with
// it reaches the attention level, in ascending attempt order. Two jobs over the
// same pair therefore lock the review rows in the same order.
func reviewTargets(
ctx context.Context,
repository outbound.AssessmentSignalRepository,
attemptID domain.AssessmentAttemptID,
policyID domain.PolicyVersionID,
signals *domain.AssessmentSignalPolicy,
now time.Time,
) ([]reviewTarget, error) {
pairs, err := repository.DuplicatePairs(ctx, attemptID, outbound.AssessmentDuplicateQuery{
IntegerCapBits: signals.DuplicateIntegerCapBits, SequenceCapBits: signals.DuplicateSequenceCapBits,
MinBits: signals.DuplicateAttentionBits, EndedOnly: true, Now: now, Limit: signalReviewPairLimit,
})
if err != nil {
return nil, err
}
targets := []reviewTarget{{id: attemptID, policy: policyID}}
for _, pair := range pairs {
if pair.AttemptID != attemptID {
targets = append(targets, reviewTarget{id: pair.AttemptID, policy: pair.PolicyVersionID})
}
}
slices.SortFunc(targets, func(left, right reviewTarget) int { return bytes.Compare(left.id[:], right.id[:]) })
return targets, nil
}
// evaluateReview computes and stores the review of one attempt under the
// signal thresholds of the policy version that attempt is pinned to. A version
// without a signal section produces no review.
func evaluateReview(
ctx context.Context,
repository outbound.AssessmentSignalRepository,
attemptID domain.AssessmentAttemptID,
policy domain.PolicyVersion,
now time.Time,
) error {
const location = "assessment.evaluateReview"
signals := policy.Policy().Assessment.Signals
if signals == nil {
return nil
}
inputs, err := repository.ReviewInputs(ctx, attemptID)
if err != nil {
return fmt.Errorf("%s - read stored facts: %w", location, err)
}
best, err := repository.DuplicatePairs(ctx, attemptID, outbound.AssessmentDuplicateQuery{
IntegerCapBits: signals.DuplicateIntegerCapBits, SequenceCapBits: signals.DuplicateSequenceCapBits,
Limit: 1,
})
if err != nil {
return fmt.Errorf("%s - find the strongest pair: %w", location, err)
}
times := signals.ClassifyResponseTimes(inputs.Answers)
anomalies := domain.CountOriginAnomalies(inputs.Marks)
measures := domain.AssessmentReviewMeasures{
AnsweredItems: times.Answered, FastAnswers: times.Fast, DeviatingAnswers: times.Deviating,
ParallelAlternations: anomalies.ParallelAlternations, ExtraNetworks: anomalies.ExtraNetworks,
ClientFocusLossMS: inputs.ClientFocusLossMS, ClientClipboardEvents: inputs.ClientClipboardCount,
ClientFullscreenExits: inputs.ClientFullscreenExit,
}
if len(best) > 0 {
measures.DuplicateEvidenceBits = best[0].EvidenceBits
measures.MatchedIntegerItems, measures.MatchedSequenceItems = best[0].IntegerItems, best[0].SequenceItems
}
review := domain.AssessmentAttemptReview{
AttemptID: attemptID, PolicyVersionID: policy.ID(), PolicyVersion: policy.Version(),
Measures: measures, Outcome: signals.Evaluate(measures), EvaluatedAt: now, UpdatedAt: now,
}
if err := repository.SaveReview(ctx, review); err != nil {
return fmt.Errorf("%s - store review: %w", location, err)
}
return nil
}
// ReviewOperator lets an operator read the stored review of one attempt. Every
// read is recorded with the operator handle. Until staff roles exist this is
// the only way to read a band.
type ReviewOperator struct {
transactor outbound.Transactor
}
func NewReviewOperator(transactor outbound.Transactor) (*ReviewOperator, error) {
if transactor == nil {
return nil, errors.New("assessment.NewReviewOperator - transactor must be set")
}
return &ReviewOperator{transactor: transactor}, nil
}
// Inspect returns the review of an attempt and records the read, also when the
// attempt has no review. The actor is an audit handle, not authentication.
func (operator *ReviewOperator) Inspect(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
actor string,
) (domain.AssessmentAttemptReview, error) {
const location = "ReviewOperator.Inspect"
parsed, err := domain.ParseAssessmentReviewActor(actor)
if err != nil {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - parse actor: %w", location, err)
}
if attemptID.IsZero() {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview)
}
readID, err := uuid.NewV7()
if err != nil {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - generate read ID: %w", location, err)
}
var review domain.AssessmentAttemptReview
missing := false
err = operator.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
repository := unit.AssessmentSignals()
stored, err := repository.GetReview(ctx, attemptID)
switch {
case errors.Is(err, outbound.ErrAssessmentReviewNotFound):
missing = true
case err != nil:
return fmt.Errorf("%s - read review: %w", location, err)
default:
review = stored
}
at, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time: %w", location, err)
}
if err := repository.RecordReviewRead(ctx, readID, attemptID, parsed, !missing, at.UTC().Truncate(time.Microsecond)); err != nil {
return fmt.Errorf("%s - record read: %w", location, err)
}
return nil
})
if err != nil {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - transaction: %w", location, err)
}
if missing {
return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - attempt has no review: %w", location, outbound.ErrAssessmentReviewNotFound)
}
return review, nil
}
@@ -0,0 +1,700 @@
package assessment
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
var signalReviewTestTime = time.Date(2026, time.October, 5, 9, 0, 0, 0, time.UTC)
// signalDigesterFake derives plain SHA-256 values so a test can compare them;
// the production keyring uses HMAC under a server secret.
type signalDigesterFake struct{}
func (signalDigesterFake) AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, answer []byte) domain.AssessmentDigest {
return domain.AssessmentDigest(sha256.Sum256(append(append(familyID[:], binary.BigEndian.AppendUint32(nil, uint32(familyVersion))...), answer...)))
}
func (signalDigesterFake) AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest {
return domain.AssessmentDigest(sha256.Sum256(append(attemptID[:], sessionID[:]...)))
}
func (signalDigesterFake) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest {
return domain.AssessmentDigest(sha256.Sum256(append(attemptID[:], clientKey...)))
}
func (signalDigesterFake) AssessmentDigestKeyVersion() int16 { return 7 }
// signalRepositoryFake records the writes of the observer and the job. The
// embedded interface is nil, so a call the test does not expect panics.
type signalRepositoryFake struct {
outbound.AssessmentSignalRepository
observations []domain.AssessmentAnswerObservation
marks []domain.AssessmentOriginMark
reviews []domain.AssessmentAttemptReview
inputs outbound.AssessmentReviewInputs
pairs map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair
subjects map[domain.AssessmentAttemptID]domain.PolicyVersionID
queries []outbound.AssessmentDuplicateQuery
// events records the order of locks and reads of a job.
events []string
}
func (repository *signalRepositoryFake) SaveAnswerObservation(_ context.Context, observation domain.AssessmentAnswerObservation) error {
repository.observations = append(repository.observations, observation)
return nil
}
func (repository *signalRepositoryFake) SaveOriginMark(_ context.Context, mark domain.AssessmentOriginMark) error {
repository.marks = append(repository.marks, mark)
return nil
}
func (repository *signalRepositoryFake) LastOriginMark(context.Context, domain.AssessmentAttemptID) (domain.AssessmentOriginMark, bool, error) {
if len(repository.marks) == 0 {
return domain.AssessmentOriginMark{}, false, nil
}
return repository.marks[len(repository.marks)-1], true, nil
}
func (repository *signalRepositoryFake) ReviewInputs(context.Context, domain.AssessmentAttemptID) (outbound.AssessmentReviewInputs, error) {
repository.events = append(repository.events, "read")
return repository.inputs, nil
}
func (repository *signalRepositoryFake) LockReview(_ context.Context, attemptID domain.AssessmentAttemptID) error {
repository.events = append(repository.events, "lock:"+attemptID.String())
return nil
}
func (repository *signalRepositoryFake) DuplicatePairs(
_ context.Context,
attemptID domain.AssessmentAttemptID,
query outbound.AssessmentDuplicateQuery,
) ([]outbound.AssessmentDuplicatePair, error) {
repository.queries = append(repository.queries, query)
pairs := repository.pairs[attemptID]
if query.MinBits > 0 {
pairs = slices.DeleteFunc(slices.Clone(pairs), func(pair outbound.AssessmentDuplicatePair) bool { return pair.EvidenceBits < query.MinBits })
}
return pairs, nil
}
func (repository *signalRepositoryFake) ReviewSubject(_ context.Context, attemptID domain.AssessmentAttemptID) (domain.PolicyVersionID, bool, error) {
id, found := repository.subjects[attemptID]
return id, found, nil
}
func (repository *signalRepositoryFake) SaveReview(_ context.Context, review domain.AssessmentAttemptReview) error {
repository.reviews = append(repository.reviews, review)
return nil
}
type jobSchedulerFake struct {
jobs []domain.ScheduledJob
}
func (scheduler *jobSchedulerFake) Schedule(_ context.Context, job domain.ScheduledJob) (bool, error) {
scheduler.jobs = append(scheduler.jobs, job)
return true, nil
}
func (*jobSchedulerFake) Cancel(context.Context, string, string) (bool, error) { return false, nil }
type policiesFake struct {
outbound.PolicyRepository
versions map[domain.PolicyVersionID]domain.PolicyVersion
}
func (policies policiesFake) GetByID(_ context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) {
return policies.versions[id], nil
}
type bankClockFake struct {
outbound.AssessmentBankRepository
}
func (bankClockFake) DatabaseTime(context.Context) (time.Time, error) {
return signalReviewTestTime, nil
}
type signalUnitFake struct {
outbound.UnitOfWork
repository *signalRepositoryFake
scheduler *jobSchedulerFake
policies policiesFake
}
func newSignalUnitFake() *signalUnitFake {
return &signalUnitFake{repository: &signalRepositoryFake{}, scheduler: &jobSchedulerFake{}}
}
func (unit *signalUnitFake) AssessmentSignals() outbound.AssessmentSignalRepository {
return unit.repository
}
func (unit *signalUnitFake) ScheduledJobs() outbound.JobScheduler { return unit.scheduler }
func (unit *signalUnitFake) Policies() outbound.PolicyRepository { return unit.policies }
func (unit *signalUnitFake) AssessmentBank() outbound.AssessmentBankRepository {
return bankClockFake{}
}
func signalReviewFamily(t *testing.T, draft domain.AssessmentFamilyDraft) domain.AssessmentFamily {
t.Helper()
core, hash := draft.Core(), draft.ContentHash()
generator, err := draft.SeedGeneratorJSON()
if err != nil {
t.Fatalf("SeedGeneratorJSON() error = %v", err)
}
answerKey, err := draft.AnswerKeyJSON()
if err != nil {
t.Fatalf("AnswerKeyJSON() error = %v", err)
}
rubric, err := draft.RubricJSON()
if err != nil {
t.Fatalf("RubricJSON() error = %v", err)
}
family, err := domain.RestoreAssessmentFamily(domain.StoredAssessmentFamily{
ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category),
Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName),
Author: string(core.Author), Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus),
SeedGenerator: generator, AnswerKey: answerKey, Rubric: rubric, ContentHash: hash[:],
HashScheme: draft.HashScheme(), Lifecycle: string(domain.AssessmentLifecycleDraft), CreatedAt: signalReviewTestTime,
})
if err != nil {
t.Fatalf("RestoreAssessmentFamily() error = %v", err)
}
return family
}
func signalReviewDemoFamilies(t *testing.T) []domain.AssessmentFamily {
t.Helper()
drafts, err := loadDemoBundle(t).Drafts()
if err != nil {
t.Fatalf("Drafts() error = %v", err)
}
families := make([]domain.AssessmentFamily, 0, len(drafts))
for _, draft := range drafts {
families = append(families, signalReviewFamily(t, draft))
}
return families
}
func signalReviewPolicyVersion(t *testing.T, number int32, policy domain.ProductPolicy) domain.PolicyVersion {
t.Helper()
draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor,
EffectiveAt: signalReviewTestTime, Policy: policy,
})
if err != nil {
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
}
numbered, err := draft.WithVersion(number)
if err != nil {
t.Fatalf("WithVersion() error = %v", err)
}
hash := numbered.DocumentHash()
version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{
ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()),
Author: string(numbered.Author()), EffectiveAt: signalReviewTestTime, CreatedAt: signalReviewTestTime,
Document: numbered.Document(), DocumentHash: hash[:],
})
if err != nil {
t.Fatalf("RestorePolicyVersion() error = %v", err)
}
return version
}
func signalReviewAttempt(t *testing.T, policy domain.PolicyVersion, kind domain.AssessmentAttemptKind) domain.AssessmentAttempt {
t.Helper()
families := signalReviewDemoFamilies(t)
items := make([]domain.AssessmentAttemptItemInput, len(families))
for index, family := range families {
variant, err := family.NewVariant(domain.VariantSeed(1000 + index))
if err != nil {
t.Fatalf("NewVariant() error = %v", err)
}
items[index] = domain.AssessmentAttemptItemInput{Variant: variant}
}
versions := domain.AssessmentAttemptVersions{
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
BankVersion: "backend-demo.v1", AlgorithmVersion: "assessment.v1",
}
input := domain.NewAssessmentAttemptInput{
UserID: uuid.New(), Kind: kind, BankCategory: "backend", Versions: versions, Policy: policy,
CreatedAt: signalReviewTestTime, Items: items,
}
if kind == domain.AssessmentAttemptKindDemoExpress {
input.BankCategory = "training-demo"
input.Items = items[:policy.Policy().Assessment.Training.DemoExpressItemCount]
input.Versions.TrainingBindingID, input.Versions.TrainingManifestHash = uuid.New(), [32]byte{2}
} else {
specialization, grade := domain.SpecializationBackend, domain.GradeJunior
input.Specialization, input.TargetGrade = &specialization, &grade
input.Versions.GradingPolicyVersionID, input.Versions.OpeningID = policy.ID(), uuid.New()
input.Versions.OpeningManifestHash = [32]byte{1}
}
attempt, err := domain.NewAssessmentAttempt(input)
if err != nil {
t.Fatalf("NewAssessmentAttempt() error = %v", err)
}
return attempt
}
func signalReviewFirstAnswer(t *testing.T, attempt domain.AssessmentAttempt, at time.Time) (domain.AssessmentAttempt, domain.AssessmentAttemptItemSnapshot) {
t.Helper()
item := attempt.Snapshot().Items[0]
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, json.RawMessage(`{"format":"number","number":424242}`), at)
if err != nil || !changed {
t.Fatalf("SubmitAnswer() = changed %v, error %v", changed, err)
}
return updated, updated.Snapshot().Items[0]
}
func signalReviewSecondAnswer(t *testing.T, attempt domain.AssessmentAttempt, at time.Time) (domain.AssessmentAttempt, domain.AssessmentAttemptItemSnapshot) {
t.Helper()
item := attempt.Snapshot().Items[1]
tasks := item.Variant.Parameters["tasks"]
elements := make([]string, 0, tasks)
for task := int32(1); task <= tasks; task++ {
elements = append(elements, fmt.Sprintf("job_%d", task))
}
answer, err := json.Marshal(map[string]any{"format": "order", "element_ids": elements})
if err != nil {
t.Fatalf("marshal order answer: %v", err)
}
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, at)
if err != nil || !changed {
t.Fatalf("SubmitAnswer(second) = changed %v, error %v", changed, err)
}
return updated, updated.Snapshot().Items[1]
}
func TestObserveAnswerStoresServerTimeAndKeyedFingerprintOnly(t *testing.T) {
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
answeredAt := signalReviewTestTime.Add(12*time.Second + 340*time.Millisecond)
updated, item := signalReviewFirstAnswer(t, attempt, answeredAt)
observer, err := NewSignalObserver(signalDigesterFake{})
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
unit := newSignalUnitFake()
origin := RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.77"}
if err := observer.observeAnswer(context.Background(), unit, attempt, updated, item.ID, origin); err != nil {
t.Fatalf("observeAnswer() error = %v", err)
}
if len(unit.repository.observations) != 1 || len(unit.repository.marks) != 1 {
t.Fatalf("stored %d observations and %d marks, want one of each", len(unit.repository.observations), len(unit.repository.marks))
}
observation := unit.repository.observations[0]
if observation.ElapsedMS != 12340 || observation.ItemInstanceID != item.ID || observation.FamilyID != item.Variant.FamilyID ||
observation.Seed != item.Variant.Seed || observation.AnswerFormat != item.Variant.AnswerFormat {
t.Fatalf("observation = %+v, want 12340 ms from the attempt start for the answered item", observation)
}
if observation.MeasuredFromAnswer {
t.Fatal("the first item of a session was measured from an answer; it is measured from the session start")
}
if observation.KeyVersion != 7 || unit.repository.marks[0].KeyVersion != 7 {
t.Fatalf("key versions = %d and %d, want the digester generation 7", observation.KeyVersion, unit.repository.marks[0].KeyVersion)
}
if want := (signalDigesterFake{}).AssessmentAnswerFingerprint(uuid.UUID(item.Variant.FamilyID), item.Variant.FamilyVersion, item.Answer); observation.Fingerprint != want {
t.Fatal("fingerprint is not the keyed digest of the canonical answer")
}
mark := unit.repository.marks[0]
if mark.Source != domain.AssessmentOriginAnswer || mark.NetworkDigest.IsZero() || mark.SessionDigest.IsZero() {
t.Fatalf("origin mark = %+v, want an answer mark with session and network digests", mark)
}
stored := fmt.Sprintf("%+v %+v", observation, mark)
for _, secret := range []string{"424242", "198.51.100.77", origin.SessionID.String()} {
if strings.Contains(stored, secret) {
t.Fatalf("stored facts contain %q", secret)
}
}
// A review is due when the attempt reaches its deadline, however it ends.
if len(unit.scheduler.jobs) != 1 {
t.Fatalf("scheduled %d jobs, want the review at the deadline", len(unit.scheduler.jobs))
}
job := unit.scheduler.jobs[0]
if job.Kind() != SignalReviewJobKind || job.Key() != attempt.ID().String()+":deadline" || !job.DueAt().Equal(attempt.ExpiresAt().Add(time.Minute)) {
t.Fatalf("job = %s %s due %s, want the deadline job of the attempt due a minute after its expiry", job.Kind(), job.Key(), job.DueAt())
}
if strings.Contains(string(job.Payload()), "424242") || !strings.Contains(string(job.Payload()), attempt.ID().String()) {
t.Fatalf("job payload = %s, want the attempt ID only", job.Payload())
}
}
func TestObserveAnswerMeasuresLaterItemsFromThePreviousAnswerAndMarksOnlyChanges(t *testing.T) {
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
first := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
firstUpdated, firstItem := signalReviewFirstAnswer(t, first, signalReviewTestTime.Add(20*time.Second))
secondUpdated, secondItem := signalReviewSecondAnswer(t, firstUpdated, signalReviewTestTime.Add(24*time.Second))
observer, err := NewSignalObserver(signalDigesterFake{})
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
unit := newSignalUnitFake()
origin := RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.77"}
if err := observer.observeAnswer(context.Background(), unit, first, firstUpdated, firstItem.ID, origin); err != nil {
t.Fatalf("observeAnswer(first) error = %v", err)
}
if err := observer.observeAnswer(context.Background(), unit, firstUpdated, secondUpdated, secondItem.ID, origin); err != nil {
t.Fatalf("observeAnswer(second) error = %v", err)
}
second := unit.repository.observations[1]
if second.ElapsedMS != 4000 || !second.MeasuredFromAnswer {
t.Fatalf("second observation = %+v, want 4000 ms measured from the previous answer", second)
}
if len(unit.repository.marks) != 1 {
t.Fatalf("stored %d marks for two requests from one session and network, want 1", len(unit.repository.marks))
}
// Writing a mark for every request would grow without bound; a change of the
// session or the network writes one.
thirdOrigin := RequestOrigin{SessionID: origin.SessionID, ClientKey: "203.0.113.5"}
if err := observer.recordOrigin(context.Background(), unit.repository, first.ID(), domain.AssessmentOriginSignals, signalReviewTestTime, thirdOrigin); err != nil {
t.Fatalf("recordOrigin(new network) error = %v", err)
}
if err := observer.recordOrigin(context.Background(), unit.repository, first.ID(), domain.AssessmentOriginSignals, signalReviewTestTime, thirdOrigin); err != nil {
t.Fatalf("recordOrigin(repeat) error = %v", err)
}
if len(unit.repository.marks) != 2 {
t.Fatalf("stored %d marks after a network change and a repeat, want 2", len(unit.repository.marks))
}
}
func TestObserveAnswerSkipsTrainingAttemptsAndMarksNothingWithoutASession(t *testing.T) {
observer, err := NewSignalObserver(signalDigesterFake{})
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
training := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindDemoExpress)
trainingUpdated, trainingItem := signalReviewFirstAnswer(t, training, signalReviewTestTime.Add(time.Second))
unit := newSignalUnitFake()
if err := observer.observeAnswer(context.Background(), unit, training, trainingUpdated, trainingItem.ID, RequestOrigin{SessionID: uuid.New()}); err != nil {
t.Fatalf("observeAnswer(training) error = %v", err)
}
if err := observer.scheduleEndedReview(context.Background(), unit, trainingUpdated, signalReviewTestTime); err != nil {
t.Fatalf("scheduleEndedReview(training) error = %v", err)
}
if len(unit.repository.observations)+len(unit.repository.marks)+len(unit.scheduler.jobs) != 0 {
t.Fatal("a training attempt produced server signals or a review job")
}
root := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
rootUpdated, rootItem := signalReviewFirstAnswer(t, root, signalReviewTestTime.Add(time.Second))
if err := observer.observeAnswer(context.Background(), unit, root, rootUpdated, rootItem.ID, RequestOrigin{}); err != nil {
t.Fatalf("observeAnswer(no session) error = %v", err)
}
if len(unit.repository.observations) != 1 || len(unit.repository.marks) != 0 {
t.Fatalf("no-session request stored %d observations and %d marks, want 1 and 0", len(unit.repository.observations), len(unit.repository.marks))
}
var disabled *SignalObserver
if err := disabled.observeAnswer(context.Background(), unit, root, rootUpdated, rootItem.ID, RequestOrigin{SessionID: uuid.New()}); err != nil {
t.Fatalf("observeAnswer(disabled observer) error = %v", err)
}
if err := disabled.scheduleEndedReview(context.Background(), unit, rootUpdated, signalReviewTestTime); err != nil {
t.Fatalf("scheduleEndedReview(disabled observer) error = %v", err)
}
if len(unit.repository.observations) != 1 {
t.Fatal("a disabled observer stored an observation")
}
if _, err := NewSignalObserver(nil); err == nil {
t.Fatal("NewSignalObserver(nil) accepted a missing digester")
}
}
func TestScheduleEndedReviewIsKeyedByTheAttemptEnding(t *testing.T) {
observer, err := NewSignalObserver(signalDigesterFake{})
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
attempt := signalReviewAttempt(t, signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3()), domain.AssessmentAttemptKindRoot)
unit := newSignalUnitFake()
if err := observer.scheduleEndedReview(context.Background(), unit, attempt, signalReviewTestTime); err != nil {
t.Fatalf("scheduleEndedReview() error = %v", err)
}
job := unit.scheduler.jobs[0]
if job.Key() != attempt.ID().String()+":ended" || !job.DueAt().Equal(signalReviewTestTime) {
t.Fatalf("job = %s due %s, want the ended job due at the ending", job.Key(), job.DueAt())
}
}
func signalJob(attemptID domain.AssessmentAttemptID) outbound.ClaimedJob {
return outbound.ClaimedJob{
Kind: SignalReviewJobKind, Key: attemptID.String() + ":ended",
Payload: json.RawMessage(`{"attempt_id":"` + attemptID.String() + `"}`),
}
}
func TestSignalReviewJobRefusesBrokenPayloadsAndIgnoresMissingAttempts(t *testing.T) {
job := NewSignalReviewJob(nil)
if job.JobKind() != "assessment.signal_review" {
t.Fatalf("JobKind() = %q", job.JobKind())
}
unit := newSignalUnitFake()
for _, payload := range []string{``, `{}`, `{"attempt_id":"not-a-uuid"}`, `{"attempt_id":"00000000-0000-0000-0000-000000000000"}`} {
err := job.Handle(context.Background(), unit, outbound.ClaimedJob{Payload: json.RawMessage(payload)})
if !errors.Is(err, inbound.ErrJobRejected) {
t.Errorf("Handle(%q) error = %v, want a rejected job", payload, err)
}
}
if err := job.Handle(context.Background(), unit, signalJob(domain.AssessmentAttemptID(uuid.New()))); err != nil {
t.Fatalf("Handle(unknown attempt) error = %v, want a finished job", err)
}
if len(unit.repository.reviews) != 0 {
t.Fatal("a review was stored for an unknown attempt")
}
}
// A job writes the reviews of its attempt and of the matched ended attempts in
// ascending attempt order, each under the policy version that attempt is pinned
// to, so two concurrent jobs over the same pair take row locks in one order.
func TestSignalReviewJobWritesPairsInAscendingOrderUnderTheirOwnPolicies(t *testing.T) {
strictSignals := domain.DemoAssessmentSignalPolicy()
strictSignals.FastAnswersAttention, strictSignals.FastAnswersReview = 1, 2
strict := domain.DemoProductPolicyV3()
strict.Assessment.Signals = &strictSignals
relaxedSignals := domain.DemoAssessmentSignalPolicy()
relaxedSignals.FastAnswersAttention, relaxedSignals.FastAnswersReview = 100, 200
relaxed := domain.DemoProductPolicyV3()
relaxed.Assessment.Signals = &relaxedSignals
strictVersion := signalReviewPolicyVersion(t, 4, strict)
relaxedVersion := signalReviewPolicyVersion(t, 5, relaxed)
legacyVersion := signalReviewPolicyVersion(t, 2, domain.DemoProductPolicyV2())
low := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000001"))
middle := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000002"))
high := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000003"))
legacy := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000004"))
unit := newSignalUnitFake()
unit.policies = policiesFake{versions: map[domain.PolicyVersionID]domain.PolicyVersion{
strictVersion.ID(): strictVersion, relaxedVersion.ID(): relaxedVersion, legacyVersion.ID(): legacyVersion,
}}
unit.repository.subjects = map[domain.AssessmentAttemptID]domain.PolicyVersionID{high: strictVersion.ID()}
unit.repository.inputs = outbound.AssessmentReviewInputs{Answers: []domain.AssessmentResponseSample{
answerSampleForJob(100), answerSampleForJob(100),
}}
unit.repository.pairs = map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair{high: {
{AttemptID: middle, PolicyVersionID: relaxedVersion.ID(), EvidenceBits: 90},
{AttemptID: low, PolicyVersionID: strictVersion.ID(), EvidenceBits: 80},
{AttemptID: legacy, PolicyVersionID: legacyVersion.ID(), EvidenceBits: 70},
// Below the attention level of the evaluated policy: not refreshed.
{AttemptID: domain.AssessmentAttemptID(uuid.New()), PolicyVersionID: strictVersion.ID(), EvidenceBits: 1},
}}
if err := NewSignalReviewJob(nil).Handle(context.Background(), unit, signalJob(high)); err != nil {
t.Fatalf("Handle() error = %v", err)
}
reviews := unit.repository.reviews
if len(reviews) != 3 {
t.Fatalf("stored %d reviews, want the attempt, its two matched attempts, and none for a version without a signal section", len(reviews))
}
if reviews[0].AttemptID != low || reviews[1].AttemptID != middle || reviews[2].AttemptID != high {
t.Fatalf("review order = %s %s %s, want ascending attempt IDs", reviews[0].AttemptID, reviews[1].AttemptID, reviews[2].AttemptID)
}
if reviews[0].Outcome.Band != domain.AssessmentReviewBandReview || reviews[1].Outcome.Band != domain.AssessmentReviewBandNormal ||
reviews[1].PolicyVersionID != relaxedVersion.ID() {
t.Fatalf("bands = %s/%s, want each attempt judged by its own pinned policy", reviews[0].Outcome.Band, reviews[1].Outcome.Band)
}
// All locks come first, in ascending order, before any fact is read.
wantEvents := []string{"lock:" + low.String(), "lock:" + middle.String(), "lock:" + high.String(), "lock:" + legacy.String()}
if len(unit.repository.events) < 5 || !slices.Equal(unit.repository.events[:4], wantEvents) || unit.repository.events[4] != "read" {
t.Fatalf("job events = %v, want the four review locks in ascending order before the first read", unit.repository.events)
}
queried := unit.repository.queries[0]
if !queried.EndedOnly || queried.Limit != signalReviewPairLimit || queried.MinBits != strictSignals.DuplicateAttentionBits {
t.Fatalf("pair query = %+v, want ended attempts only, bounded, from the attention level", queried)
}
}
func answerSampleForJob(elapsed int32) domain.AssessmentResponseSample {
return domain.AssessmentResponseSample{AnswerFormat: domain.AnswerFormatInteger, ElapsedMS: elapsed, MeasuredFromAnswer: true}
}
func TestEvaluateReviewTakesTheStrongestPair(t *testing.T) {
version := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
repository := &signalRepositoryFake{pairs: map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair{}}
attemptID := domain.AssessmentAttemptID(uuid.New())
repository.pairs[attemptID] = []outbound.AssessmentDuplicatePair{
{AttemptID: domain.AssessmentAttemptID(uuid.New()), EvidenceBits: 66, IntegerItems: 8, SequenceItems: 1},
{AttemptID: domain.AssessmentAttemptID(uuid.New()), EvidenceBits: 20, IntegerItems: 3},
}
if err := evaluateReview(context.Background(), repository, attemptID, version, signalReviewTestTime); err != nil {
t.Fatalf("evaluateReview() error = %v", err)
}
review := repository.reviews[0]
if review.Measures.DuplicateEvidenceBits != 66 || review.Measures.MatchedIntegerItems != 8 || review.Measures.MatchedSequenceItems != 1 ||
review.Outcome.Band != domain.AssessmentReviewBandReview {
t.Fatalf("review = %+v, want the strongest pair and the review band", review)
}
if query := repository.queries[0]; query.Limit != 1 || query.MinBits != 0 || query.EndedOnly {
t.Fatalf("pair query = %+v, want the single strongest pair among all attempts", query)
}
}
// The duplicate thresholds are sums of bits over one pair of attempts, and a
// matched answer carries -log2 of the share of attempts that hold its value. The
// test measures, for the four demo families, how likely two independent
// candidates are to give the same correct answer and which values they share,
// and from that computes the probability that one pair of honest candidates
// reaches each threshold on a 23-item attempt. Since an attempt is compared with
// every other one, the per-attempt rate is that probability times the number of
// rivals. The measurement covers four AI-drafted families; it is not a
// calibration, and a real bank needs its own run.
func TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow(t *testing.T) {
const (
seedsPerFamily = 4000
rivals = 1e4
items = 23
// Targets for one honest attempt facing all rivals.
attentionTarget = 1e-3
reviewTarget = 1e-8
)
policy := domain.DemoAssessmentSignalPolicy()
type outcome struct {
probability float64
bits int
}
families := signalReviewDemoFamilies(t)
perFamily := make([][]outcome, 0, len(families))
for _, family := range families {
counts := map[string]int{}
var format string
for seed := 1; seed <= seedsPerFamily; seed++ {
variant, err := family.NewVariant(domain.VariantSeed(seed))
if err != nil {
t.Fatalf("NewVariant(%d) error = %v", seed, err)
}
counts[variant.ReferenceAnswer]++
format = variant.AnswerFormat
}
capBits := float64(policy.DuplicateIntegerCapBits)
if format == domain.AnswerFormatIntegerSequence {
capBits = float64(policy.DuplicateSequenceCapBits)
}
matched := 0.0
outcomes := make([]outcome, 0, len(counts)+1)
for _, count := range counts {
share := float64(count) / seedsPerFamily
// Rounded up, so the computed probability is not understated.
bits := int(math.Ceil(math.Min(capBits, -math.Log2(share))))
outcomes = append(outcomes, outcome{probability: share * share, bits: bits})
matched += share * share
}
perFamily = append(perFamily, append(outcomes, outcome{probability: 1 - matched}))
}
tail := func(threshold int) float64 {
distribution := make([]float64, threshold+1)
distribution[0] = 1
for item := range items {
next := make([]float64, threshold+1)
for sum, mass := range distribution {
if mass == 0 {
continue
}
for _, entry := range perFamily[item%len(perFamily)] {
next[min(sum+entry.bits, threshold)] += mass * entry.probability
}
}
distribution = next
}
return distribution[threshold]
}
attention := tail(int(policy.DuplicateAttentionBits)) * rivals
review := tail(int(policy.DuplicateReviewBits)) * rivals
t.Logf("per-attempt false flag rate against %.0f rivals: attention %.3g, review %.3g", rivals, attention, review)
if attention > attentionTarget || review > reviewTarget {
t.Fatalf("per-attempt false flag rate attention %.3g (target %.0e), review %.3g (target %.0e)", attention, attentionTarget, review, reviewTarget)
}
}
func TestSignalLogsAndErrorsCarryNoAnswerOrAddress(t *testing.T) {
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
updated, item := signalReviewFirstAnswer(t, attempt, signalReviewTestTime.Add(time.Second))
observer, err := NewSignalObserver(signalDigesterFake{})
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
// An observation for an item the attempt does not hold is refused with an
// error that names neither the answer nor the origin.
err = observer.observeAnswer(context.Background(), newSignalUnitFake(), attempt, updated, uuid.New(), RequestOrigin{SessionID: uuid.New(), ClientKey: "203.0.113.9"})
if err == nil {
t.Fatal("observeAnswer(foreign item) succeeded")
}
for _, secret := range []string{"424242", "203.0.113.9", string(item.Answer)} {
if strings.Contains(err.Error(), secret) {
t.Fatalf("error text contains %q: %v", secret, err)
}
}
}
// copiedPairEvidence is the evidence of a pair that copies every answer of an
// attempt of the given length in a population of the given number of answers
// per family: each shared value is held by the two copiers only, so a matched
// answer carries log2(population / 2) bits up to the cap of its format. The
// items follow the demo bank: three integer families for one order family.
func copiedPairEvidence(policy domain.AssessmentSignalPolicy, items, population int) float64 {
bits := math.Log2(float64(population) / 2)
total := 0.0
for item := range items {
capBits := float64(policy.DuplicateIntegerCapBits)
if item%4 == 1 {
capBits = float64(policy.DuplicateSequenceCapBits)
}
total += math.Min(capBits, bits)
}
return math.Floor(total)
}
// The demo thresholds are tuned against ten thousand rivals, so a copied pair
// is only flagged once enough attempts exist for its shared values to be rare.
// This test calculates how many answers per family that takes, so the figure in
// the documentation is not an estimate; to try the feature on a small stand,
// publish a policy with lower thresholds instead of changing the demo values.
func TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged(t *testing.T) {
policy := domain.DemoAssessmentSignalPolicy()
needed := func(items int, threshold int32) int {
for population := 2; population <= 1<<20; population++ {
if copiedPairEvidence(policy, items, population) >= float64(threshold) {
return population
}
}
return -1
}
for _, test := range []struct {
items int
wantAttention, wantReview int
}{
{items: 13, wantAttention: 26, wantReview: 61},
{items: 23, wantAttention: 9, wantReview: 14},
} {
attention := needed(test.items, policy.DuplicateAttentionBits)
review := needed(test.items, policy.DuplicateReviewBits)
t.Logf("%d items: a copied pair reaches attention from %d answers per family and review from %d", test.items, attention, review)
if attention != test.wantAttention || review != test.wantReview {
t.Errorf("%d items: attention at %d and review at %d answers per family, want %d and %d", test.items, attention, review, test.wantAttention, test.wantReview)
}
}
}
@@ -4,9 +4,12 @@ import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
@@ -24,6 +27,10 @@ const (
labelTokenBucket = "lincodex/identity/verification-token-bucket/v1"
labelSessionCSRF = "lincodex/identity/session-csrf/v1"
labelCandidateView = "lincodex/identity/candidate-view/v1"
labelAnswerFingerprint = "lincodex/assessment/answer-fingerprint/v1"
labelSignalSession = "lincodex/assessment/signal-session/v1"
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
)
// Keyring computes the keyed digests of the anonymous identity operations:
@@ -39,6 +46,9 @@ type Keyring struct {
tokenKey []byte
sessionCSRFKey []byte
candidateViewKey []byte
answerKey []byte
signalSessionKey []byte
signalNetworkKey []byte
}
// NewKeyring derives the purpose keys from secret.
@@ -54,6 +64,9 @@ func NewKeyring(secret []byte) (*Keyring, error) {
tokenKey: derive(secret, labelTokenBucket),
sessionCSRFKey: derive(secret, labelSessionCSRF),
candidateViewKey: derive(secret, labelCandidateView),
answerKey: derive(secret, labelAnswerFingerprint),
signalSessionKey: derive(secret, labelSignalSession),
signalNetworkKey: derive(secret, labelSignalNetwork),
}, nil
}
@@ -143,3 +156,39 @@ func (keyring *Keyring) VerifySessionCSRF(token domain.SecretToken, supplied str
}
return hmac.Equal([]byte(keyring.SessionCSRF(token)), []byte(supplied))
}
// AssessmentDigestKeyVersion is the key generation of the assessment
// fingerprints and digests. It is stored next to each of them; a rotation adds
// a new generation instead of silently changing the old values.
func (keyring *Keyring) AssessmentDigestKeyVersion() int16 { return 1 }
// AssessmentAnswerFingerprint is the keyed digest of a normalized answer to a
// family version. It is the same for every candidate and every seed, which
// lets stored fingerprints be compared without the answer text.
func (keyring *Keyring) AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, canonicalAnswer []byte) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.answerKey)
mac.Write(familyID[:])
mac.Write(binary.BigEndian.AppendUint32(nil, uint32(familyVersion))) //nolint:gosec // A family version is a positive int32.
mac.Write(canonicalAnswer)
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentSessionDigest identifies a login session inside one attempt. The
// digest changes with the attempt, so it cannot link attempts or reveal the
// session identifier.
func (keyring *Keyring) AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.signalSessionKey)
mac.Write(attemptID[:])
mac.Write(sessionID[:])
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentNetworkDigest identifies a client network inside one attempt from
// its limiter key. The address itself is never stored, and the digest cannot
// link attempts.
func (keyring *Keyring) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.signalNetworkKey)
mac.Write(attemptID[:])
mac.Write([]byte(clientKey))
return domain.AssessmentDigest(mac.Sum(nil))
}
@@ -2,9 +2,12 @@ package identity
import (
"bytes"
"crypto/sha256"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
func TestCandidateViewPseudonymKeyIsPurposeDerived(t *testing.T) {
@@ -54,3 +57,69 @@ func TestCandidateViewPseudonymKeyRequiresValidKeyring(t *testing.T) {
t.Fatal("CandidateViewPseudonymKey() accepted a nil keyring")
}
}
func TestAssessmentAnswerFingerprintIsKeyedDeterministicAndScoped(t *testing.T) {
keyring, err := NewKeyring(bytes.Repeat([]byte{1}, MinKeySecretBytes))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
other, err := NewKeyring(bytes.Repeat([]byte{2}, MinKeySecretBytes))
if err != nil {
t.Fatalf("NewKeyring(other) error = %v", err)
}
family, otherFamily := uuid.New(), uuid.New()
answer := []byte(`{"format":"number","number":42}`)
first := keyring.AssessmentAnswerFingerprint(family, 1, answer)
if first.IsZero() || first != keyring.AssessmentAnswerFingerprint(family, 1, answer) {
t.Fatal("the same family version and answer must give the same non-zero fingerprint")
}
for name, different := range map[string]domain.AssessmentDigest{
"another answer": keyring.AssessmentAnswerFingerprint(family, 1, []byte(`{"format":"number","number":43}`)),
"another family": keyring.AssessmentAnswerFingerprint(otherFamily, 1, answer),
"another family version": keyring.AssessmentAnswerFingerprint(family, 2, answer),
"another secret": other.AssessmentAnswerFingerprint(family, 1, answer),
} {
if different == first {
t.Errorf("%s gave the same fingerprint", name)
}
}
plain := sha256.Sum256(append(append(family[:], 0, 0, 0, 1), answer...))
if first == domain.AssessmentDigest(plain) {
t.Fatal("the fingerprint is a plain hash and can be checked without the server secret")
}
if keyring.AssessmentDigestKeyVersion() < 1 {
t.Fatal("the digest key version must be positive")
}
}
func TestAssessmentSessionAndNetworkDigestsAreBoundToTheAttempt(t *testing.T) {
keyring, err := NewKeyring(bytes.Repeat([]byte{1}, MinKeySecretBytes))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
attempt, otherAttempt, session, otherSession := uuid.New(), uuid.New(), uuid.New(), uuid.New()
sessionDigest := keyring.AssessmentSessionDigest(attempt, session)
if sessionDigest != keyring.AssessmentSessionDigest(attempt, session) {
t.Fatal("the session digest is not deterministic")
}
if sessionDigest == keyring.AssessmentSessionDigest(otherAttempt, session) {
t.Fatal("one session has the same digest in two attempts, so attempts could be linked")
}
if sessionDigest == keyring.AssessmentSessionDigest(attempt, otherSession) {
t.Fatal("two sessions of one attempt have the same digest")
}
networkDigest := keyring.AssessmentNetworkDigest(attempt, "198.51.100.0")
if networkDigest != keyring.AssessmentNetworkDigest(attempt, "198.51.100.0") {
t.Fatal("the network digest is not deterministic")
}
if networkDigest == keyring.AssessmentNetworkDigest(otherAttempt, "198.51.100.0") {
t.Fatal("one network has the same digest in two attempts, so attempts could be linked")
}
if networkDigest == keyring.AssessmentNetworkDigest(attempt, "198.51.100.1") {
t.Fatal("two client networks have the same digest")
}
// Each purpose has its own key: the same bytes under another purpose differ.
if sessionDigest == keyring.AssessmentNetworkDigest(attempt, string(session[:])) {
t.Fatal("session and network digests share a key")
}
}