feat(assessment): find the attempt behind a leaked task text
This commit is contained in:
1 parent
bb917bf62e
commit
5a731c25b7
26 files changed
+2500
No files matched your search
@@ -49,6 +49,14 @@ 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: assessment-leak-trace assessment-leak-trace-build
|
||||
assessment-leak-trace: ## Find the attempt behind a leaked task text; the search is audited (set ARGS)
|
||||
$(GO) run ./cmd/assessment-leak-trace $(ARGS)
|
||||
|
||||
assessment-leak-trace-build: ## Build the local leak trace operator command
|
||||
@mkdir -p bin
|
||||
$(GO) build -buildvcs=false -trimpath -o bin/assessment-leak-trace ./cmd/assessment-leak-trace
|
||||
|
||||
.PHONY: assessment-category-attest assessment-category-attest-build
|
||||
assessment-category-attest: ## Attest a category opening for synthetic demonstration categories (set ARGS)
|
||||
$(GO) run ./cmd/assessment-category-attest $(ARGS)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// Command assessment-leak-trace searches for the assessment attempt behind a
|
||||
// leaked task text. It reads text, never an image: a screenshot must be read
|
||||
// by an OCR tool first. It records every search in an audit table and changes
|
||||
// nothing else.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/cli/leaktrace"
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(run())
|
||||
}
|
||||
|
||||
func run() int {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := leaktrace.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdin, os.Stdout); err != nil {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "assessment-leak-trace: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -86,6 +86,24 @@ func (config *Config) loadIdentity(lookup LookupEnv) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// IdentityKeySecretFromEnv reads IDENTITY_KEY_SECRET for an operator command
|
||||
// that recomputes keyed values of the server, such as the codes of the leak
|
||||
// trace. It never draws an ephemeral secret: a random one would make every
|
||||
// value unreadable, and a command that silently searched with it would report
|
||||
// nothing found. The error never contains the secret.
|
||||
func IdentityKeySecretFromEnv(lookup LookupEnv) ([]byte, error) {
|
||||
secret := strings.TrimSpace(valueOrDefault(lookup, "IDENTITY_KEY_SECRET", ""))
|
||||
switch {
|
||||
case secret == "":
|
||||
return nil, errors.New("config.IdentityKeySecretFromEnv - IDENTITY_KEY_SECRET is not set")
|
||||
case strings.HasPrefix(secret, examplePlaceholderPrefix):
|
||||
return nil, errors.New("config.IdentityKeySecretFromEnv - IDENTITY_KEY_SECRET is an example placeholder")
|
||||
case len(secret) < MinIdentityKeySecretBytes:
|
||||
return nil, fmt.Errorf("config.IdentityKeySecretFromEnv - IDENTITY_KEY_SECRET must have at least %d bytes", MinIdentityKeySecretBytes)
|
||||
}
|
||||
return []byte(secret), nil
|
||||
}
|
||||
|
||||
// ValidateIdentity checks the registration settings. Errors never include
|
||||
// the secret.
|
||||
func (config Config) ValidateIdentity() error {
|
||||
|
||||
@@ -135,3 +135,26 @@ func TestLoadFromEnvRejectsThePlaceholderSecret(t *testing.T) {
|
||||
t.Fatalf("LoadFromEnv() error = %v, want a refusal that does not quote the value", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentityKeySecretFromEnvRefusesWhatTheServerCouldNotUseAndNeverEchoesIt(t *testing.T) {
|
||||
secret := strings.Repeat("s", MinIdentityKeySecretBytes)
|
||||
got, err := IdentityKeySecretFromEnv(func(key string) (string, bool) { return " " + secret + " ", key == "IDENTITY_KEY_SECRET" })
|
||||
if err != nil || string(got) != secret {
|
||||
t.Fatalf("IdentityKeySecretFromEnv(valid) = %q, %v, want the trimmed secret", got, err)
|
||||
}
|
||||
for name, value := range map[string]string{
|
||||
"unset": "",
|
||||
"placeholder": "replace-this-with-a-generated-secret-of-enough-length",
|
||||
"too short": "short-secret",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, err := IdentityKeySecretFromEnv(func(key string) (string, bool) { return value, key == "IDENTITY_KEY_SECRET" && value != "" })
|
||||
if err == nil {
|
||||
t.Fatal("IdentityKeySecretFromEnv() succeeded, want an error")
|
||||
}
|
||||
if value != "" && strings.Contains(err.Error(), value) {
|
||||
t.Fatalf("the error contains the secret: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
-- +goose Up
|
||||
-- The audit of the operator search for the attempt behind a leaked task text.
|
||||
-- Every search writes one row, whatever it finds, before a result is shown.
|
||||
-- A row holds no leaked text: only a keyed digest of the normalized text and its
|
||||
-- length, the outcome, and, for a found search, the attempt. The attempt is not
|
||||
-- a foreign key, so the row outlives an account deletion. Nothing reads these
|
||||
-- rows for a candidate, an employer, a result, a category, or a quota.
|
||||
CREATE TABLE assessment_leak_traces (
|
||||
id uuid NOT NULL,
|
||||
actor text NOT NULL,
|
||||
searched_at timestamptz NOT NULL,
|
||||
text_digest bytea NOT NULL,
|
||||
key_version smallint NOT NULL,
|
||||
text_runes integer NOT NULL,
|
||||
status text NOT NULL,
|
||||
method text,
|
||||
attempt_id uuid,
|
||||
candidates integer NOT NULL,
|
||||
evidence_bits integer NOT NULL,
|
||||
CONSTRAINT assessment_leak_traces_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT assessment_leak_traces_actor CHECK (
|
||||
char_length(actor) <= 128 AND actor ~ '^operator:[a-z0-9][a-z0-9._-]*$'
|
||||
),
|
||||
CONSTRAINT assessment_leak_traces_digest CHECK (octet_length(text_digest) = 32),
|
||||
CONSTRAINT assessment_leak_traces_key_version CHECK (key_version > 0),
|
||||
CONSTRAINT assessment_leak_traces_counts CHECK (text_runes >= 0 AND candidates >= 0 AND evidence_bits >= 0),
|
||||
CONSTRAINT assessment_leak_traces_status CHECK (status IN ('found', 'ambiguous', 'not_found')),
|
||||
CONSTRAINT assessment_leak_traces_method CHECK (
|
||||
method IS NULL OR method IN ('invisible_mark', 'visible_code', 'wording', 'variant')
|
||||
),
|
||||
CONSTRAINT assessment_leak_traces_found CHECK (
|
||||
(status = 'found' AND attempt_id IS NOT NULL AND method IS NOT NULL)
|
||||
OR (status <> 'found' AND attempt_id IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX assessment_leak_traces_attempt_idx
|
||||
ON assessment_leak_traces (attempt_id, searched_at)
|
||||
WHERE attempt_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX assessment_leak_traces_searched_idx
|
||||
ON assessment_leak_traces (searched_at, id);
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION assessment_leak_traces_immutable() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23000', CONSTRAINT = 'assessment_leak_traces_immutable',
|
||||
MESSAGE = 'assessment leak trace audit records are immutable';
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER assessment_leak_traces_immutable
|
||||
BEFORE UPDATE OR DELETE ON assessment_leak_traces
|
||||
FOR EACH ROW EXECUTE FUNCTION assessment_leak_traces_immutable();
|
||||
|
||||
CREATE TRIGGER assessment_leak_traces_no_truncate
|
||||
BEFORE TRUNCATE ON assessment_leak_traces
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION assessment_leak_traces_immutable();
|
||||
|
||||
-- +goose Down
|
||||
-- The audit of operator searches is durable evidence. Rolling the schema back
|
||||
-- must not remove it as a side effect: an operator exports or resolves it first.
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM assessment_leak_traces) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'assessment_leak_traces_retained',
|
||||
TABLE = 'assessment_leak_traces',
|
||||
MESSAGE = 'assessment leak trace audit must be retained before rollback';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
DROP TRIGGER assessment_leak_traces_no_truncate ON assessment_leak_traces;
|
||||
DROP TRIGGER assessment_leak_traces_immutable ON assessment_leak_traces;
|
||||
DROP FUNCTION assessment_leak_traces_immutable();
|
||||
DROP INDEX assessment_leak_traces_searched_idx;
|
||||
DROP INDEX assessment_leak_traces_attempt_idx;
|
||||
DROP TABLE assessment_leak_traces;
|
||||
@@ -0,0 +1,51 @@
|
||||
-- Real attempts in ascending identifier order, so that a caller can walk all of
|
||||
-- them in pages. Only the identifier and the time span are read.
|
||||
-- name: ListAssessmentTraceAttempts :many
|
||||
SELECT id, created_at, expires_at
|
||||
FROM assessment_attempts
|
||||
WHERE kind IN ('root', 'corrective') AND id > sqlc.arg(after_id)
|
||||
ORDER BY id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- The unmarked statements of real attempts whose text, with runs of white space
|
||||
-- collapsed, contains the fragment. The fragment is matched literally: position
|
||||
-- is not a pattern. The scan reads the stored variant of every item, which is
|
||||
-- fine for an operator command and not for a request path.
|
||||
-- name: FindAssessmentTraceStatements :many
|
||||
SELECT
|
||||
item.attempt_id,
|
||||
(item.variant ->> 'Statement')::text AS statement
|
||||
FROM assessment_attempt_items AS item
|
||||
INNER JOIN assessment_attempts AS attempt ON item.attempt_id = attempt.id
|
||||
WHERE
|
||||
attempt.kind IN ('root', 'corrective')
|
||||
AND position(sqlc.arg(fragment)::text IN regexp_replace((item.variant ->> 'Statement')::text, '\s+', ' ', 'g')) > 0
|
||||
ORDER BY item.attempt_id, item.ordinal
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- name: InsertAssessmentLeakTrace :exec
|
||||
INSERT INTO assessment_leak_traces (
|
||||
id,
|
||||
actor,
|
||||
searched_at,
|
||||
text_digest,
|
||||
key_version,
|
||||
text_runes,
|
||||
status,
|
||||
method,
|
||||
attempt_id,
|
||||
candidates,
|
||||
evidence_bits
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(actor),
|
||||
sqlc.arg(searched_at),
|
||||
sqlc.arg(text_digest),
|
||||
sqlc.arg(key_version),
|
||||
sqlc.arg(text_runes),
|
||||
sqlc.arg(status),
|
||||
sqlc.narg(method),
|
||||
sqlc.narg(attempt_id),
|
||||
sqlc.arg(candidates),
|
||||
sqlc.arg(evidence_bits)
|
||||
);
|
||||
@@ -0,0 +1,215 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/cli/leaktrace"
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// TestAssessmentLeakTraceOverHTTP checks, with PostgreSQL, that the operator
|
||||
// search finds the real attempt behind the text that the page presented: by the
|
||||
// invisible mark, then by the statement and its wording once the mark is gone,
|
||||
// then by the visible code of a screenshot's text. It checks that unrelated text
|
||||
// is not found, that every search is audited without the text and the audit is
|
||||
// immutable and outlives the attempt, that a search changes no attempt, review,
|
||||
// or result, and that the command wiring reads the same secret as the server.
|
||||
func TestAssessmentLeakTraceOverHTTP(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
|
||||
defer cancel()
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
t.Cleanup(harness.pool.Close)
|
||||
signals := reviewTestSignalPolicy()
|
||||
seedAssessmentAttemptHTTPBankWithSignals(ctx, t, harness.pool, &signals)
|
||||
|
||||
first := newReviewCandidate(ctx, t, harness, "leak-first@example.test", "192.0.2", 1)
|
||||
second := newReviewCandidate(ctx, t, harness, "leak-second@example.test", "192.0.3", 1)
|
||||
firstAttempt := leakTraceCreate(t, harness, first, "leak-first-create", "192.0.2.30:1234")
|
||||
secondAttempt := leakTraceCreate(t, harness, second, "leak-second-create", "192.0.3.30:1234")
|
||||
if firstAttempt.code == secondAttempt.code || firstAttempt.prompt == secondAttempt.prompt {
|
||||
t.Fatal("two attempts were presented the same code or the same marked prompt")
|
||||
}
|
||||
|
||||
tracer, err := assessment.NewLeakTracer(postgresadapter.NewTransactor(harness.pool), harness.keyring, harness.keyring)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLeakTracer() error = %v", err)
|
||||
}
|
||||
trace := func(text, code string) assessment.LeakTraceResult {
|
||||
t.Helper()
|
||||
result, err := tracer.Trace(ctx, assessment.LeakTraceCommand{Actor: "operator:integration", Text: text, Code: code})
|
||||
if err != nil {
|
||||
t.Fatalf("Trace() error = %v", err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
before := leakTraceFacts(t, ctx, harness)
|
||||
|
||||
// The text as presented, inside a message: the invisible mark names the attempt.
|
||||
marked := trace("Look what I got at the test: "+firstAttempt.prompt+" any ideas?", "")
|
||||
if marked.Status != domain.AssessmentLeakTraceFound || marked.Method != domain.AssessmentLeakTraceInvisibleMark ||
|
||||
marked.AttemptID != domain.AssessmentAttemptID(firstAttempt.id) || marked.EvidenceBits != 50 {
|
||||
t.Fatalf("marked text result = %+v, want the first attempt by its invisible mark", marked)
|
||||
}
|
||||
|
||||
// The invisible characters stripped (a chat tool, retyping): the statement and
|
||||
// its wording still point at the attempt that was served it, and not at the other.
|
||||
stripped := trace(domain.VisibleAssessmentText(secondAttempt.prompt), "")
|
||||
if stripped.Status != domain.AssessmentLeakTraceFound || stripped.AttemptID != domain.AssessmentAttemptID(secondAttempt.id) ||
|
||||
(stripped.Method != domain.AssessmentLeakTraceWording && stripped.Method != domain.AssessmentLeakTraceVariant) {
|
||||
t.Fatalf("stripped text result = %+v, want the second attempt by its statement", stripped)
|
||||
}
|
||||
|
||||
// The text of a screenshot: the statement without the mark and the tile with the code and the time.
|
||||
tile := fmt.Sprintf("%s\n%s %s", domain.VisibleAssessmentText(firstAttempt.prompt), firstAttempt.code, time.Now().UTC().Format("2006-01-02 15:04")+"Z")
|
||||
screenshot := trace(tile, "")
|
||||
if screenshot.Status != domain.AssessmentLeakTraceFound || screenshot.Method != domain.AssessmentLeakTraceVisibleCode ||
|
||||
screenshot.AttemptID != domain.AssessmentAttemptID(firstAttempt.id) {
|
||||
t.Fatalf("screenshot text result = %+v, want the first attempt by its visible code", screenshot)
|
||||
}
|
||||
if !strings.Contains(strings.Join(screenshot.Notes, " "), "falls within the life of the attempt") {
|
||||
t.Fatalf("screenshot notes = %v, want the tile time within the attempt", screenshot.Notes)
|
||||
}
|
||||
|
||||
// Insufficient data is reported as not found.
|
||||
unrelated := trace("The committee will meet on Thursday to discuss the budget for the coming year and the new office.", "")
|
||||
if unrelated.Status != domain.AssessmentLeakTraceNotFound || !unrelated.AttemptID.IsZero() {
|
||||
t.Fatalf("unrelated text result = %+v, want not found", unrelated)
|
||||
}
|
||||
short := trace("How many requests?", "")
|
||||
if short.Status != domain.AssessmentLeakTraceNotFound {
|
||||
t.Fatalf("short text result = %+v, want not found", short)
|
||||
}
|
||||
|
||||
// A search changes no attempt, review, or result.
|
||||
if after := leakTraceFacts(t, ctx, harness); after != before {
|
||||
t.Fatalf("a search changed the attempts: %q before, %q after", before, after)
|
||||
}
|
||||
|
||||
// Every search was audited, without the text.
|
||||
var rows int64
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_leak_traces`).Scan(&rows); err != nil || rows != 5 {
|
||||
t.Fatalf("audit rows = %d, error %v, want one per search", rows, err)
|
||||
}
|
||||
var dump string
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT string_agg(t::text, ' ') FROM assessment_leak_traces AS t`).Scan(&dump); err != nil {
|
||||
t.Fatalf("dump the audit: %v", err)
|
||||
}
|
||||
for _, leaked := range []string{"gateway", "limiter", "committee", "Thursday", firstAttempt.code} {
|
||||
if strings.Contains(strings.ToLower(dump), strings.ToLower(leaked)) {
|
||||
t.Fatalf("the audit holds %q, want a keyed digest of the text only", leaked)
|
||||
}
|
||||
}
|
||||
if found := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE status = 'found' AND attempt_id IS NOT NULL AND actor = 'operator:integration'`); found != 3 {
|
||||
t.Fatalf("found audit rows = %d, want 3", found)
|
||||
}
|
||||
if notFound := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE status = 'not_found' AND attempt_id IS NULL AND method IS NULL`); notFound != 2 {
|
||||
t.Fatalf("not found audit rows = %d, want 2", notFound)
|
||||
}
|
||||
|
||||
// The audit is immutable and survives the attempt it names.
|
||||
_, updateErr := harness.pool.Exec(ctx, `UPDATE assessment_leak_traces SET actor = 'operator:other'`)
|
||||
assertSQLError(t, "update an audit record", updateErr, "23000", "assessment_leak_traces_immutable")
|
||||
_, deleteErr := harness.pool.Exec(ctx, `DELETE FROM assessment_leak_traces`)
|
||||
assertSQLError(t, "delete an audit record", deleteErr, "23000", "assessment_leak_traces_immutable")
|
||||
_, truncateErr := harness.pool.Exec(ctx, `TRUNCATE assessment_leak_traces`)
|
||||
assertSQLError(t, "truncate the audit", truncateErr, "23000", "assessment_leak_traces_immutable")
|
||||
_, foundWithoutAttempt := harness.pool.Exec(ctx, `INSERT INTO assessment_leak_traces
|
||||
(id, actor, searched_at, text_digest, key_version, text_runes, status, method, attempt_id, candidates, evidence_bits)
|
||||
VALUES ($1, 'operator:integration', now(), $2, 1, 10, 'found', 'wording', NULL, 1, 1)`, uuid.New(), bytes.Repeat([]byte{1}, 32))
|
||||
assertSQLError(t, "found search without an attempt", foundWithoutAttempt, assessmentCheckSQLState, "assessment_leak_traces_found")
|
||||
if _, err := harness.pool.Exec(ctx, `DELETE FROM assessment_attempts WHERE id = $1`, firstAttempt.id); err != nil {
|
||||
t.Fatalf("delete the attempt: %v", err)
|
||||
}
|
||||
if rows := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE attempt_id = $1`, firstAttempt.id); rows != 2 {
|
||||
t.Fatalf("audit rows of the deleted attempt = %d, want them kept", rows)
|
||||
}
|
||||
gone := trace(firstAttempt.prompt, "")
|
||||
if gone.Status != domain.AssessmentLeakTraceNotFound {
|
||||
t.Fatalf("search for a deleted attempt = %+v, want not found: the mark names no attempt any more", gone)
|
||||
}
|
||||
|
||||
// The command reads the secret of the server and the audit is written by it too.
|
||||
var output bytes.Buffer
|
||||
lookup := func(key string) (string, bool) {
|
||||
switch key {
|
||||
case "DATABASE_URL":
|
||||
return databaseURL, true
|
||||
case "IDENTITY_KEY_SECRET":
|
||||
return isolatedEnv.Config.IdentityKeySecret, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
err = leaktrace.Run(ctx, []string{"search", "--actor", "operator:command", "--stdin"}, lookup,
|
||||
strings.NewReader("Question: "+secondAttempt.prompt), &output)
|
||||
if err != nil || !strings.Contains(output.String(), "result: found") || !strings.Contains(output.String(), "method: invisible_mark") ||
|
||||
!strings.Contains(output.String(), "attempt: "+secondAttempt.id.String()) {
|
||||
t.Fatalf("command output = %q, error %v, want the second attempt by its mark", output.String(), err)
|
||||
}
|
||||
if rows := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE actor = 'operator:command' AND status = 'found'`); rows != 1 {
|
||||
t.Fatalf("command audit rows = %d, want 1", rows)
|
||||
}
|
||||
otherSecret := func(key string) (string, bool) {
|
||||
if key == "IDENTITY_KEY_SECRET" {
|
||||
return strings.Repeat("x", 48), true
|
||||
}
|
||||
return lookup(key)
|
||||
}
|
||||
output.Reset()
|
||||
if err := leaktrace.Run(ctx, []string{"search", "--actor", "operator:command", "--stdin"}, otherSecret,
|
||||
strings.NewReader("Question: "+secondAttempt.prompt), &output); err != nil || strings.Contains(output.String(), "method: invisible_mark") {
|
||||
t.Fatalf("a command with another secret = %q, %v, want it not to read the mark of the server", output.String(), err)
|
||||
}
|
||||
}
|
||||
|
||||
type leakTraceAttempt struct {
|
||||
id uuid.UUID
|
||||
code string
|
||||
prompt string
|
||||
}
|
||||
|
||||
func leakTraceCreate(t *testing.T, harness *assessmentAttemptHTTPHarness, candidate reviewCandidate, key, remoteAddr string) leakTraceAttempt {
|
||||
t.Helper()
|
||||
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("create real attempt = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
id, _ := assessmentSignalAttemptItem(t, response.Body.Bytes())
|
||||
code, prompt := decodeWatermarkedAttempt(t, response.Body.Bytes())
|
||||
if code == "" || !hasZeroWidth(prompt) {
|
||||
t.Fatalf("the presented attempt has code %q and a prompt without a mark", code)
|
||||
}
|
||||
return leakTraceAttempt{id: id, code: code, prompt: prompt}
|
||||
}
|
||||
|
||||
// leakTraceFacts summarizes what a search must not change: the versions and
|
||||
// states of the attempts and the number of reviews and results.
|
||||
func leakTraceFacts(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness) string {
|
||||
t.Helper()
|
||||
var facts string
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT
|
||||
coalesce((SELECT string_agg(id::text || ':' || version || ':' || state, ',' ORDER BY id) FROM assessment_attempts), '') || '|' ||
|
||||
(SELECT count(*) FROM assessment_attempt_reviews) || '|' ||
|
||||
(SELECT count(*) FROM assessment_attempt_results)`).Scan(&facts); err != nil {
|
||||
t.Fatalf("read the attempt facts: %v", err)
|
||||
}
|
||||
return facts
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// Package leaktrace implements the local operator command that finds the
|
||||
// assessment attempt behind a leaked task text. It takes text: a screenshot has
|
||||
// to be read by an OCR tool first, which is outside this command. Every search
|
||||
// is recorded in an audit table before a result is printed. The result is a hint
|
||||
// for a manual review and an appeal: it is never shown to an employer and never
|
||||
// changes a score, a category, or a quota.
|
||||
package leaktrace
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const usage = "usage: assessment-leak-trace search --actor operator:<handle> (--file <path> | --stdin) [--code XXXXX-XXXXX]"
|
||||
|
||||
// maxInputBytes is the largest text the command reads. It is one byte above the
|
||||
// limit of the usecase, so an oversize text is refused instead of cut.
|
||||
const maxInputBytes = 64<<10 + 1
|
||||
|
||||
// Command is a parsed, validated search.
|
||||
type Command struct {
|
||||
Actor string
|
||||
// File is the path of the leaked text; empty when the text comes from stdin.
|
||||
File string
|
||||
Stdin bool
|
||||
// Code is a visible code that the operator read from a screenshot by eye.
|
||||
Code string
|
||||
}
|
||||
|
||||
// Tracer finds the attempt behind a text and records the search.
|
||||
type Tracer interface {
|
||||
Trace(ctx context.Context, command assessment.LeakTraceCommand) (assessment.LeakTraceResult, error)
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects to
|
||||
// PostgreSQL.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 || args[0] != "search" {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("assessment-leak-trace search", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
actor := flags.String("actor", "", "operator handle")
|
||||
file := flags.String("file", "", "file with the leaked text")
|
||||
stdin := flags.Bool("stdin", false, "read the leaked text from standard input")
|
||||
code := flags.String("code", "", "visible code read from a screenshot")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
if _, err := domain.ParseAssessmentReviewActor(strings.TrimSpace(*actor)); err != nil {
|
||||
return Command{}, errors.New("actor must be operator:<handle>")
|
||||
}
|
||||
if *file != "" && *stdin {
|
||||
return Command{}, errors.New("give the text with --file or --stdin, not both")
|
||||
}
|
||||
if *file == "" && !*stdin && strings.TrimSpace(*code) == "" {
|
||||
return Command{}, errors.New("give the leaked text with --file or --stdin, or a visible code with --code")
|
||||
}
|
||||
if strings.TrimSpace(*code) != "" {
|
||||
if _, err := domain.ParseAssessmentWatermarkCode(*code); err != nil {
|
||||
return Command{}, errors.New("code must be a watermark code of two groups of five characters, such as 7K3QD-9XM2T")
|
||||
}
|
||||
}
|
||||
return Command{Actor: strings.TrimSpace(*actor), File: *file, Stdin: *stdin, Code: strings.TrimSpace(*code)}, nil
|
||||
}
|
||||
|
||||
// Run parses the command, loads only DATABASE_URL and IDENTITY_KEY_SECRET from
|
||||
// the supplied environment, and executes the search. It does not load dotenv
|
||||
// files.
|
||||
func Run(ctx context.Context, args []string, lookup config.LookupEnv, stdin io.Reader, output io.Writer) error {
|
||||
command, err := Parse(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lookup == nil || stdin == nil || output == nil {
|
||||
return errors.New("leak trace command dependencies are required")
|
||||
}
|
||||
text, err := readText(command, stdin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
databaseURL := config.DatabaseURLFromEnv(lookup)
|
||||
if databaseURL == "" {
|
||||
return errors.New("DATABASE_URL is not set")
|
||||
}
|
||||
secret, err := config.IdentityKeySecretFromEnv(lookup)
|
||||
if err != nil {
|
||||
return errors.New("IDENTITY_KEY_SECRET must be the secret of the server that served the attempts")
|
||||
}
|
||||
keyring, err := identity.NewKeyring(secret)
|
||||
if err != nil {
|
||||
return errors.New("IDENTITY_KEY_SECRET is invalid")
|
||||
}
|
||||
pool, err := postgres.NewPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return errors.New("database configuration is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("database is unavailable")
|
||||
}
|
||||
tracer, err := assessment.NewLeakTracer(postgres.NewTransactor(pool), keyring, keyring)
|
||||
if err != nil {
|
||||
return errors.New("leak trace is unavailable")
|
||||
}
|
||||
return Execute(ctx, command, text, tracer, output)
|
||||
}
|
||||
|
||||
func readText(command Command, stdin io.Reader) (string, error) {
|
||||
var reader io.Reader
|
||||
switch {
|
||||
case command.File != "":
|
||||
file, err := os.Open(command.File)
|
||||
if err != nil {
|
||||
return "", errors.New("the text file cannot be opened")
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
reader = file
|
||||
case command.Stdin:
|
||||
reader = stdin
|
||||
default:
|
||||
return "", nil
|
||||
}
|
||||
text, err := io.ReadAll(io.LimitReader(reader, maxInputBytes))
|
||||
if err != nil {
|
||||
return "", errors.New("the text cannot be read")
|
||||
}
|
||||
return string(text), nil
|
||||
}
|
||||
|
||||
// Execute runs the search and prints the outcome. The output names the outcome,
|
||||
// the method, the attempt, the strength of the evidence, and fixed notes about
|
||||
// it. It never prints the leaked text and no data of the candidate.
|
||||
func Execute(ctx context.Context, command Command, text string, tracer Tracer, output io.Writer) error {
|
||||
if tracer == nil || output == nil {
|
||||
return errors.New("leak trace command dependencies are required")
|
||||
}
|
||||
result, err := tracer.Trace(ctx, assessment.LeakTraceCommand{Actor: command.Actor, Text: text, Code: command.Code})
|
||||
if err != nil {
|
||||
return safeOperationError(err)
|
||||
}
|
||||
var builder strings.Builder
|
||||
fmt.Fprintf(&builder, "search: %s\nresult: %s\n", result.SearchID, result.Status)
|
||||
if result.Status == domain.AssessmentLeakTraceFound {
|
||||
fmt.Fprintf(&builder, "method: %s\nattempt: %s\nevidence_bits: %d\n", result.Method, result.AttemptID, result.EvidenceBits)
|
||||
}
|
||||
fmt.Fprintf(&builder, "candidates: %d\n", result.Candidates)
|
||||
for _, note := range result.Notes {
|
||||
fmt.Fprintf(&builder, "note: %s\n", note)
|
||||
}
|
||||
builder.WriteString("note: a hint for a manual review and an appeal; it changes no score, category, or quota, " +
|
||||
"and an employer never sees it. The search is recorded in the audit.\n")
|
||||
if result.Status == domain.AssessmentLeakTraceNotFound {
|
||||
builder.WriteString("note: not found is an honest answer: the data is not enough to name an attempt.\n")
|
||||
}
|
||||
if _, err := io.WriteString(output, builder.String()); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeOperationError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, assessment.ErrInvalidLeakTrace):
|
||||
return errors.New("the text or the code cannot be searched (empty, not valid UTF-8, or longer than 64 KiB)")
|
||||
case errors.Is(err, domain.ErrInvalidAssessmentReview):
|
||||
return errors.New("actor is invalid")
|
||||
default:
|
||||
return errors.New("assessment leak trace operation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package leaktrace
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type tracerFake struct {
|
||||
result assessment.LeakTraceResult
|
||||
err error
|
||||
command assessment.LeakTraceCommand
|
||||
calls int
|
||||
}
|
||||
|
||||
func (tracer *tracerFake) Trace(_ context.Context, command assessment.LeakTraceCommand) (assessment.LeakTraceResult, error) {
|
||||
tracer.calls++
|
||||
tracer.command = command
|
||||
return tracer.result, tracer.err
|
||||
}
|
||||
|
||||
func TestParseTakesTheTextFromAFileOrStandardInputAndAnOperatorHandle(t *testing.T) {
|
||||
command, err := Parse([]string{"search", "--actor", "operator:night", "--file", "leak.txt"})
|
||||
if err != nil || command.File != "leak.txt" || command.Actor != "operator:night" || command.Stdin {
|
||||
t.Fatalf("Parse(file) = %+v, %v", command, err)
|
||||
}
|
||||
command, err = Parse([]string{"search", "--actor", "operator:night", "--stdin", "--code", "7k3qd 9xm2t"})
|
||||
if err != nil || !command.Stdin || command.Code != "7k3qd 9xm2t" {
|
||||
t.Fatalf("Parse(stdin and code) = %+v, %v", command, err)
|
||||
}
|
||||
// A code read from a screenshot by eye is enough on its own.
|
||||
if _, err := Parse([]string{"search", "--actor", "operator:night", "--code", "7K3QD-9XM2T"}); err != nil {
|
||||
t.Fatalf("Parse(code only) error = %v", err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil,
|
||||
{"find"},
|
||||
{"search"},
|
||||
{"search", "--file", "leak.txt"},
|
||||
{"search", "--actor", "alice", "--file", "leak.txt"},
|
||||
{"search", "--actor", "operator:night"},
|
||||
{"search", "--actor", "operator:night", "--file", "leak.txt", "--stdin"},
|
||||
{"search", "--actor", "operator:night", "--code", "NOT A CODE"},
|
||||
{"search", "--actor", "operator:night", "--file", "leak.txt", "extra"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunValidatesArgumentsBeforeReadingTheEnvironmentAndNeverEchoesTheSecret(t *testing.T) {
|
||||
lookup := func(string) (string, bool) {
|
||||
t.Fatal("environment read before arguments were validated")
|
||||
return "", false
|
||||
}
|
||||
if err := Run(context.Background(), []string{"search"}, lookup, strings.NewReader(""), &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("Run(invalid arguments) succeeded")
|
||||
}
|
||||
args := []string{"search", "--actor", "operator:night", "--stdin"}
|
||||
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
|
||||
if err := Run(context.Background(), args, noDatabase, strings.NewReader("leaked text"), &bytes.Buffer{}); err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
|
||||
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
|
||||
}
|
||||
// A secret that the server could not have used makes every code unreadable, so the command refuses it.
|
||||
const shortSecret = "too-short-secret"
|
||||
var weakSecret config.LookupEnv = func(key string) (string, bool) {
|
||||
switch key {
|
||||
case "DATABASE_URL":
|
||||
return "postgres://operator@localhost/lincodex", true
|
||||
case "IDENTITY_KEY_SECRET":
|
||||
return shortSecret, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
err := Run(context.Background(), args, weakSecret, strings.NewReader("leaked text"), &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET") || strings.Contains(err.Error(), shortSecret) {
|
||||
t.Fatalf("Run(weak secret) error = %v, want a message that does not echo the secret", err)
|
||||
}
|
||||
var noSecret config.LookupEnv = func(key string) (string, bool) {
|
||||
if key == "DATABASE_URL" {
|
||||
return "postgres://operator@localhost/lincodex", true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
if err := Run(context.Background(), args, noSecret, strings.NewReader("leaked text"), &bytes.Buffer{}); err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET") {
|
||||
t.Fatalf("Run(no secret) error = %v, want an IDENTITY_KEY_SECRET message", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheTextIsReadFromAFileOrStandardInputWithinTheLimit(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "leak.txt")
|
||||
if err := os.WriteFile(path, []byte("text from a file"), 0o600); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
fromFile, err := readText(Command{File: path}, strings.NewReader("ignored"))
|
||||
if err != nil || fromFile != "text from a file" {
|
||||
t.Fatalf("readText(file) = %q, %v", fromFile, err)
|
||||
}
|
||||
fromStdin, err := readText(Command{Stdin: true}, strings.NewReader("text from stdin"))
|
||||
if err != nil || fromStdin != "text from stdin" {
|
||||
t.Fatalf("readText(stdin) = %q, %v", fromStdin, err)
|
||||
}
|
||||
// One byte above the limit of the usecase is read, so an oversize text is refused and not cut.
|
||||
oversize, err := readText(Command{Stdin: true}, strings.NewReader(strings.Repeat("a", 1<<20)))
|
||||
if err != nil || len(oversize) != maxInputBytes {
|
||||
t.Fatalf("readText(oversize) read %d bytes, %v, want %d", len(oversize), err, maxInputBytes)
|
||||
}
|
||||
if _, err := readText(Command{File: filepath.Join(t.TempDir(), "missing.txt")}, strings.NewReader("")); err == nil {
|
||||
t.Fatal("readText(missing file) succeeded")
|
||||
}
|
||||
if text, err := readText(Command{Code: "7K3QD-9XM2T"}, strings.NewReader("ignored")); err != nil || text != "" {
|
||||
t.Fatalf("readText(code only) = %q, %v, want no text", text, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePrintsTheOutcomeAndNeverTheLeakedText(t *testing.T) {
|
||||
const leaked = "SECRET-LEAKED-STATEMENT about a sliding-window limiter"
|
||||
attemptID := domain.AssessmentAttemptID(uuid.New())
|
||||
found := &tracerFake{result: assessment.LeakTraceResult{
|
||||
SearchID: uuid.New(), Status: domain.AssessmentLeakTraceFound, Method: domain.AssessmentLeakTraceInvisibleMark,
|
||||
AttemptID: attemptID, Candidates: 1, EvidenceBits: 50, Notes: []string{"the invisible mark of the statement carries one code"},
|
||||
}}
|
||||
var output bytes.Buffer
|
||||
if err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, found, &output); err != nil {
|
||||
t.Fatalf("Execute(found) error = %v", err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"result: found", "method: invisible_mark", "attempt: " + attemptID.String(), "evidence_bits: 50", "candidates: 1",
|
||||
"note: the invisible mark of the statement carries one code", "an employer never sees it", "changes no score, category, or quota",
|
||||
} {
|
||||
if !strings.Contains(output.String(), want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, output.String())
|
||||
}
|
||||
}
|
||||
if strings.Contains(output.String(), "SECRET-LEAKED") || strings.Contains(output.String(), "sliding-window") {
|
||||
t.Fatalf("the output quotes the leaked text:\n%s", output.String())
|
||||
}
|
||||
if found.command.Actor != "operator:night" || found.command.Text != leaked {
|
||||
t.Fatalf("command = %+v, want the actor and the text passed on", found.command)
|
||||
}
|
||||
|
||||
notFound := &tracerFake{result: assessment.LeakTraceResult{
|
||||
SearchID: uuid.New(), Status: domain.AssessmentLeakTraceNotFound, Notes: []string{"no statement of any real attempt contains this text"},
|
||||
}}
|
||||
output.Reset()
|
||||
if err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, notFound, &output); err != nil {
|
||||
t.Fatalf("Execute(not found) error = %v", err)
|
||||
}
|
||||
if !strings.Contains(output.String(), "result: not_found") || !strings.Contains(output.String(), "not found is an honest answer") ||
|
||||
strings.Contains(output.String(), "attempt:") || strings.Contains(output.String(), "method:") {
|
||||
t.Fatalf("not found output:\n%s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
|
||||
const leaked = "SECRET-LEAKED-STATEMENT"
|
||||
for name, test := range map[string]struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
"a request the usecase refuses": {err: assessment.ErrInvalidLeakTrace, want: "cannot be searched"},
|
||||
"an invalid actor": {err: domain.ErrInvalidAssessmentReview, want: "actor is invalid"},
|
||||
"a storage failure": {err: errors.New("pq: connection refused for " + leaked), want: "operation failed"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, &tracerFake{err: test.err}, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), leaked) {
|
||||
t.Fatalf("Execute() error = %v, want a safe message containing %q", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if err := Execute(context.Background(), Command{}, "", nil, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("Execute() without a tracer succeeded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.AssessmentLeakTraceRepository = assessmentLeakTraceRepository{}
|
||||
|
||||
func (unit *UnitOfWork) AssessmentLeakTraces() outbound.AssessmentLeakTraceRepository {
|
||||
return assessmentLeakTraceRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type assessmentLeakTraceRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository assessmentLeakTraceRepository) ListRealAttempts(
|
||||
ctx context.Context,
|
||||
after domain.AssessmentAttemptID,
|
||||
limit int32,
|
||||
) ([]outbound.AssessmentTraceAttempt, error) {
|
||||
const location = "assessmentLeakTraceRepository.ListRealAttempts"
|
||||
if limit < 1 {
|
||||
return nil, fmt.Errorf("%s - a positive limit is required: %w", location, domain.ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
rows, err := repository.queries.ListAssessmentTraceAttempts(ctx, sqlc.ListAssessmentTraceAttemptsParams{
|
||||
AfterID: pgUUID(after.UUID()), RowLimit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - list attempts: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
attempts := make([]outbound.AssessmentTraceAttempt, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !row.ID.Valid || !row.CreatedAt.Valid || !row.ExpiresAt.Valid {
|
||||
return nil, fmt.Errorf("%s - stored attempt is incomplete: %w", location, domain.ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
attempts = append(attempts, outbound.AssessmentTraceAttempt{
|
||||
ID: domain.AssessmentAttemptID(row.ID.Bytes), CreatedAt: row.CreatedAt.Time.UTC(), ExpiresAt: row.ExpiresAt.Time.UTC(),
|
||||
})
|
||||
}
|
||||
return attempts, nil
|
||||
}
|
||||
|
||||
func (repository assessmentLeakTraceRepository) FindStatementsContaining(
|
||||
ctx context.Context,
|
||||
fragment string,
|
||||
limit int32,
|
||||
) ([]outbound.AssessmentTraceStatement, error) {
|
||||
const location = "assessmentLeakTraceRepository.FindStatementsContaining"
|
||||
if fragment == "" || limit < 1 {
|
||||
return nil, fmt.Errorf("%s - a fragment and a positive limit are required: %w", location, domain.ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
rows, err := repository.queries.FindAssessmentTraceStatements(ctx, sqlc.FindAssessmentTraceStatementsParams{
|
||||
Fragment: fragment, RowLimit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - find statements: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
statements := make([]outbound.AssessmentTraceStatement, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !row.AttemptID.Valid {
|
||||
return nil, fmt.Errorf("%s - stored statement has no attempt: %w", location, domain.ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
statements = append(statements, outbound.AssessmentTraceStatement{
|
||||
AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes), Statement: row.Statement,
|
||||
})
|
||||
}
|
||||
return statements, nil
|
||||
}
|
||||
|
||||
func (repository assessmentLeakTraceRepository) RecordSearch(ctx context.Context, record domain.AssessmentLeakTraceRecord) error {
|
||||
const location = "assessmentLeakTraceRepository.RecordSearch"
|
||||
if err := record.Validate(); err != nil {
|
||||
return fmt.Errorf("%s - record is invalid: %w", location, err)
|
||||
}
|
||||
method := pgtype.Text{}
|
||||
if record.Method != "" {
|
||||
method = pgtype.Text{String: string(record.Method), Valid: true}
|
||||
}
|
||||
attempt := pgtype.UUID{}
|
||||
if !record.AttemptID.IsZero() {
|
||||
attempt = pgUUID(record.AttemptID.UUID())
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentLeakTrace(ctx, sqlc.InsertAssessmentLeakTraceParams{
|
||||
ID: pgUUID(record.ID), Actor: string(record.Actor), SearchedAt: pgTime(record.SearchedAt),
|
||||
TextDigest: record.TextDigest[:], KeyVersion: record.KeyVersion, TextRunes: record.TextRunes,
|
||||
Status: string(record.Status), Method: method, AttemptID: attempt,
|
||||
Candidates: record.Candidates, EvidenceBits: record.EvidenceBits,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert audit record: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_leak_traces.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const findAssessmentTraceStatements = `-- name: FindAssessmentTraceStatements :many
|
||||
SELECT
|
||||
item.attempt_id,
|
||||
(item.variant ->> 'Statement')::text AS statement
|
||||
FROM assessment_attempt_items AS item
|
||||
INNER JOIN assessment_attempts AS attempt ON item.attempt_id = attempt.id
|
||||
WHERE
|
||||
attempt.kind IN ('root', 'corrective')
|
||||
AND position($1::text IN regexp_replace((item.variant ->> 'Statement')::text, '\s+', ' ', 'g')) > 0
|
||||
ORDER BY item.attempt_id, item.ordinal
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type FindAssessmentTraceStatementsParams struct {
|
||||
Fragment string
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type FindAssessmentTraceStatementsRow struct {
|
||||
AttemptID pgtype.UUID
|
||||
Statement string
|
||||
}
|
||||
|
||||
// The unmarked statements of real attempts whose text, with runs of white space
|
||||
// collapsed, contains the fragment. The fragment is matched literally: position
|
||||
// is not a pattern. The scan reads the stored variant of every item, which is
|
||||
// fine for an operator command and not for a request path.
|
||||
func (q *Queries) FindAssessmentTraceStatements(ctx context.Context, arg FindAssessmentTraceStatementsParams) ([]FindAssessmentTraceStatementsRow, error) {
|
||||
rows, err := q.db.Query(ctx, findAssessmentTraceStatements, arg.Fragment, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []FindAssessmentTraceStatementsRow
|
||||
for rows.Next() {
|
||||
var i FindAssessmentTraceStatementsRow
|
||||
if err := rows.Scan(&i.AttemptID, &i.Statement); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const insertAssessmentLeakTrace = `-- name: InsertAssessmentLeakTrace :exec
|
||||
INSERT INTO assessment_leak_traces (
|
||||
id,
|
||||
actor,
|
||||
searched_at,
|
||||
text_digest,
|
||||
key_version,
|
||||
text_runes,
|
||||
status,
|
||||
method,
|
||||
attempt_id,
|
||||
candidates,
|
||||
evidence_bits
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8,
|
||||
$9,
|
||||
$10,
|
||||
$11
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentLeakTraceParams struct {
|
||||
ID pgtype.UUID
|
||||
Actor string
|
||||
SearchedAt pgtype.Timestamptz
|
||||
TextDigest []byte
|
||||
KeyVersion int16
|
||||
TextRunes int32
|
||||
Status string
|
||||
Method pgtype.Text
|
||||
AttemptID pgtype.UUID
|
||||
Candidates int32
|
||||
EvidenceBits int32
|
||||
}
|
||||
|
||||
func (q *Queries) InsertAssessmentLeakTrace(ctx context.Context, arg InsertAssessmentLeakTraceParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentLeakTrace,
|
||||
arg.ID,
|
||||
arg.Actor,
|
||||
arg.SearchedAt,
|
||||
arg.TextDigest,
|
||||
arg.KeyVersion,
|
||||
arg.TextRunes,
|
||||
arg.Status,
|
||||
arg.Method,
|
||||
arg.AttemptID,
|
||||
arg.Candidates,
|
||||
arg.EvidenceBits,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listAssessmentTraceAttempts = `-- name: ListAssessmentTraceAttempts :many
|
||||
SELECT id, created_at, expires_at
|
||||
FROM assessment_attempts
|
||||
WHERE kind IN ('root', 'corrective') AND id > $1
|
||||
ORDER BY id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListAssessmentTraceAttemptsParams struct {
|
||||
AfterID pgtype.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListAssessmentTraceAttemptsRow struct {
|
||||
ID pgtype.UUID
|
||||
CreatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Real attempts in ascending identifier order, so that a caller can walk all of
|
||||
// them in pages. Only the identifier and the time span are read.
|
||||
func (q *Queries) ListAssessmentTraceAttempts(ctx context.Context, arg ListAssessmentTraceAttemptsParams) ([]ListAssessmentTraceAttemptsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listAssessmentTraceAttempts, arg.AfterID, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListAssessmentTraceAttemptsRow
|
||||
for rows.Next() {
|
||||
var i ListAssessmentTraceAttemptsRow
|
||||
if err := rows.Scan(&i.ID, &i.CreatedAt, &i.ExpiresAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -215,6 +215,20 @@ type AssessmentFamily struct {
|
||||
RetiredBy pgtype.Text
|
||||
}
|
||||
|
||||
type AssessmentLeakTrace struct {
|
||||
ID pgtype.UUID
|
||||
Actor string
|
||||
SearchedAt pgtype.Timestamptz
|
||||
TextDigest []byte
|
||||
KeyVersion int16
|
||||
TextRunes int32
|
||||
Status string
|
||||
Method pgtype.Text
|
||||
AttemptID pgtype.UUID
|
||||
Candidates int32
|
||||
EvidenceBits int32
|
||||
}
|
||||
|
||||
type AssessmentReviewRead struct {
|
||||
ID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
|
||||
@@ -277,6 +277,11 @@ type Querier interface {
|
||||
// NULL retry_at. due_at keeps the deadline. The same guard as the
|
||||
// completion applies.
|
||||
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
|
||||
// The unmarked statements of real attempts whose text, with runs of white space
|
||||
// collapsed, contains the fragment. The fragment is matched literally: position
|
||||
// is not a pattern. The scan reads the stored variant of every item, which is
|
||||
// fine for an operator command and not for a request path.
|
||||
FindAssessmentTraceStatements(ctx context.Context, arg FindAssessmentTraceStatementsParams) ([]FindAssessmentTraceStatementsRow, error)
|
||||
FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error)
|
||||
FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error)
|
||||
// Returns the newest open reservation of a delivery under a provider account
|
||||
@@ -480,6 +485,7 @@ 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)
|
||||
InsertAssessmentLeakTrace(ctx context.Context, arg InsertAssessmentLeakTraceParams) 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
|
||||
@@ -677,6 +683,9 @@ type Querier interface {
|
||||
// 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)
|
||||
// Real attempts in ascending identifier order, so that a caller can walk all of
|
||||
// them in pages. Only the identifier and the time span are read.
|
||||
ListAssessmentTraceAttempts(ctx context.Context, arg ListAssessmentTraceAttemptsParams) ([]ListAssessmentTraceAttemptsRow, error)
|
||||
// Reads the exact family membership pinned by a training binding.
|
||||
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
|
||||
ListCandidateAssessmentCategories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateAssessmentCategory, error)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ErrInvalidAssessmentLeakTrace reports a malformed leak trace record.
|
||||
var ErrInvalidAssessmentLeakTrace = errors.New("invalid assessment leak trace")
|
||||
|
||||
// AssessmentLeakTraceStatus is how a search for the source of a leaked text
|
||||
// ended. Not found is a normal outcome, and ambiguous means that the data does
|
||||
// not tell several attempts apart; neither names an attempt.
|
||||
type AssessmentLeakTraceStatus string
|
||||
|
||||
const (
|
||||
AssessmentLeakTraceFound AssessmentLeakTraceStatus = "found"
|
||||
AssessmentLeakTraceAmbiguous AssessmentLeakTraceStatus = "ambiguous"
|
||||
AssessmentLeakTraceNotFound AssessmentLeakTraceStatus = "not_found"
|
||||
)
|
||||
|
||||
// IsKnown reports whether the status is one of the stored values.
|
||||
func (status AssessmentLeakTraceStatus) IsKnown() bool {
|
||||
switch status {
|
||||
case AssessmentLeakTraceFound, AssessmentLeakTraceAmbiguous, AssessmentLeakTraceNotFound:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// AssessmentLeakTraceMethod names the evidence that decided a search.
|
||||
type AssessmentLeakTraceMethod string
|
||||
|
||||
const (
|
||||
// AssessmentLeakTraceInvisibleMark is the code that the zero-width mark of the
|
||||
// statement carries. It is keyed, so it identifies the attempt on its own.
|
||||
AssessmentLeakTraceInvisibleMark AssessmentLeakTraceMethod = "invisible_mark"
|
||||
// AssessmentLeakTraceVisibleCode is the code of the faint tile, read from the
|
||||
// text of a screenshot. The code is keyed, so it identifies the attempt on
|
||||
// its own; a single wrong character of the recognized text is tolerated.
|
||||
AssessmentLeakTraceVisibleCode AssessmentLeakTraceMethod = "visible_code"
|
||||
// AssessmentLeakTraceWording is the choice of interchangeable phrases among
|
||||
// the attempts that were served the same statement text.
|
||||
AssessmentLeakTraceWording AssessmentLeakTraceMethod = "wording"
|
||||
// AssessmentLeakTraceVariant is a statement text that only one attempt was
|
||||
// ever served. It follows from the seed of the variant, not from a mark.
|
||||
AssessmentLeakTraceVariant AssessmentLeakTraceMethod = "variant"
|
||||
)
|
||||
|
||||
// IsKnown reports whether the method is one of the stored values.
|
||||
func (method AssessmentLeakTraceMethod) IsKnown() bool {
|
||||
switch method {
|
||||
case AssessmentLeakTraceInvisibleMark, AssessmentLeakTraceVisibleCode,
|
||||
AssessmentLeakTraceWording, AssessmentLeakTraceVariant:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// AssessmentLeakTraceRecord is the audit of one search. It holds no leaked
|
||||
// text, only a keyed digest of it and its length. Whatever the outcome, the
|
||||
// record exists before a result is shown, and it names an attempt only when the
|
||||
// search found one. It is not shown to an employer and changes no result,
|
||||
// category, or quota.
|
||||
type AssessmentLeakTraceRecord struct {
|
||||
ID uuid.UUID
|
||||
Actor AssessmentReviewActor
|
||||
SearchedAt time.Time
|
||||
// TextDigest is a keyed digest of the normalized text, so the same text
|
||||
// searched twice is visible in the audit without keeping it.
|
||||
TextDigest AssessmentDigest
|
||||
KeyVersion int16
|
||||
TextRunes int32
|
||||
Status AssessmentLeakTraceStatus
|
||||
Method AssessmentLeakTraceMethod
|
||||
AttemptID AssessmentAttemptID
|
||||
// Candidates is the number of attempts that the evidence left in play.
|
||||
Candidates int32
|
||||
// EvidenceBits is the strength of the deciding evidence, an upper bound on
|
||||
// how rarely another attempt would match it by chance (2^-bits).
|
||||
EvidenceBits int32
|
||||
}
|
||||
|
||||
// Validate checks that the record can be stored.
|
||||
func (record AssessmentLeakTraceRecord) Validate() error {
|
||||
const location = "AssessmentLeakTraceRecord.Validate"
|
||||
switch {
|
||||
case record.ID == uuid.Nil, record.Actor == "", record.SearchedAt.IsZero():
|
||||
return fmt.Errorf("%s - identifier, actor, and time are required: %w", location, ErrInvalidAssessmentLeakTrace)
|
||||
case record.TextDigest.IsZero(), record.KeyVersion < 1, record.TextRunes < 0:
|
||||
return fmt.Errorf("%s - the text digest, its key version, and a length are required: %w", location, ErrInvalidAssessmentLeakTrace)
|
||||
case !record.Status.IsKnown():
|
||||
return fmt.Errorf("%s - status is unknown: %w", location, ErrInvalidAssessmentLeakTrace)
|
||||
case record.Candidates < 0, record.EvidenceBits < 0:
|
||||
return fmt.Errorf("%s - counts cannot be negative: %w", location, ErrInvalidAssessmentLeakTrace)
|
||||
case record.Status == AssessmentLeakTraceFound && (record.AttemptID.IsZero() || !record.Method.IsKnown()):
|
||||
return fmt.Errorf("%s - a found search names its attempt and its method: %w", location, ErrInvalidAssessmentLeakTrace)
|
||||
case record.Status != AssessmentLeakTraceFound && !record.AttemptID.IsZero():
|
||||
return fmt.Errorf("%s - only a found search names an attempt: %w", location, ErrInvalidAssessmentLeakTrace)
|
||||
case record.Method != "" && !record.Method.IsKnown():
|
||||
return fmt.Errorf("%s - method is unknown: %w", location, ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func validLeakTraceRecord() AssessmentLeakTraceRecord {
|
||||
return AssessmentLeakTraceRecord{
|
||||
ID: uuid.New(), Actor: "operator:night", SearchedAt: time.Date(2026, time.October, 11, 9, 0, 0, 0, time.UTC),
|
||||
TextDigest: AssessmentDigest{1}, KeyVersion: 1, TextRunes: 120,
|
||||
Status: AssessmentLeakTraceNotFound, Candidates: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeakTraceRecordNamesAnAttemptOnlyWhenItFoundOne(t *testing.T) {
|
||||
record := validLeakTraceRecord()
|
||||
if err := record.Validate(); err != nil {
|
||||
t.Fatalf("Validate(not found) error = %v", err)
|
||||
}
|
||||
record.Status, record.Candidates = AssessmentLeakTraceAmbiguous, 3
|
||||
if err := record.Validate(); err != nil {
|
||||
t.Fatalf("Validate(ambiguous) error = %v", err)
|
||||
}
|
||||
found := validLeakTraceRecord()
|
||||
found.Status, found.Method, found.AttemptID, found.Candidates, found.EvidenceBits = AssessmentLeakTraceFound, AssessmentLeakTraceVisibleCode, AssessmentAttemptID(uuid.New()), 1, 50
|
||||
if err := found.Validate(); err != nil {
|
||||
t.Fatalf("Validate(found) error = %v", err)
|
||||
}
|
||||
for name, change := range map[string]func(*AssessmentLeakTraceRecord){
|
||||
"found without an attempt": func(record *AssessmentLeakTraceRecord) { record.AttemptID = AssessmentAttemptID{} },
|
||||
"found without a method": func(record *AssessmentLeakTraceRecord) { record.Method = "" },
|
||||
"found with an unknown method": func(record *AssessmentLeakTraceRecord) { record.Method = "psychic" },
|
||||
"unknown status": func(record *AssessmentLeakTraceRecord) { record.Status = "maybe" },
|
||||
"no actor": func(record *AssessmentLeakTraceRecord) { record.Actor = "" },
|
||||
"no digest": func(record *AssessmentLeakTraceRecord) { record.TextDigest = AssessmentDigest{} },
|
||||
"no key version": func(record *AssessmentLeakTraceRecord) { record.KeyVersion = 0 },
|
||||
"negative candidates": func(record *AssessmentLeakTraceRecord) { record.Candidates = -1 },
|
||||
"no time": func(record *AssessmentLeakTraceRecord) { record.SearchedAt = time.Time{} },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
record := found
|
||||
change(&record)
|
||||
if err := record.Validate(); !errors.Is(err, ErrInvalidAssessmentLeakTrace) {
|
||||
t.Fatalf("Validate() error = %v, want ErrInvalidAssessmentLeakTrace", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
notFoundWithAttempt := validLeakTraceRecord()
|
||||
notFoundWithAttempt.AttemptID = AssessmentAttemptID(uuid.New())
|
||||
if err := notFoundWithAttempt.Validate(); !errors.Is(err, ErrInvalidAssessmentLeakTrace) {
|
||||
t.Fatalf("Validate(not found with an attempt) error = %v, want ErrInvalidAssessmentLeakTrace: only a found search names an attempt", err)
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,36 @@ type AssessmentDuplicatePair struct {
|
||||
type AssessmentSignalRepositories interface {
|
||||
AssessmentSignals() AssessmentSignalRepository
|
||||
AssessmentWorkLeases() AssessmentWorkLeaseRepository
|
||||
AssessmentLeakTraces() AssessmentLeakTraceRepository
|
||||
}
|
||||
|
||||
// AssessmentTraceAttempt is a real attempt as the leak trace reads it: its
|
||||
// identifier and the time span in which a tile could have been on its screen.
|
||||
type AssessmentTraceAttempt struct {
|
||||
ID domain.AssessmentAttemptID
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// AssessmentTraceStatement is the stored, unmarked statement of one item of a
|
||||
// real attempt.
|
||||
type AssessmentTraceStatement struct {
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
Statement string
|
||||
}
|
||||
|
||||
// AssessmentLeakTraceRepository serves the operator command that finds the
|
||||
// attempt behind a leaked text. It reads statements and attempt identifiers
|
||||
// only, never an answer, and writes only the audit of the search.
|
||||
type AssessmentLeakTraceRepository interface {
|
||||
// ListRealAttempts returns up to limit real attempts with an identifier above
|
||||
// after, in ascending order, so that a caller can walk all of them.
|
||||
ListRealAttempts(ctx context.Context, after domain.AssessmentAttemptID, limit int32) ([]AssessmentTraceAttempt, error)
|
||||
// FindStatementsContaining returns up to limit statements of real attempts
|
||||
// whose text, with runs of white space collapsed, contains the fragment.
|
||||
FindStatementsContaining(ctx context.Context, fragment string, limit int32) ([]AssessmentTraceStatement, error)
|
||||
// RecordSearch stores the audit of a search; the record is immutable.
|
||||
RecordSearch(ctx context.Context, record domain.AssessmentLeakTraceRecord) error
|
||||
}
|
||||
|
||||
// AssessmentWorkLeaseRepository keeps the hold of the single active work
|
||||
|
||||
@@ -0,0 +1,638 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxLeakTextBytes bounds the text of one search. A statement is at most a
|
||||
// few kilobytes; a longer text is a document, and the operator can search it
|
||||
// in pieces.
|
||||
maxLeakTextBytes = 64 << 10
|
||||
// minLeakAnchorRunes is the shortest stretch of statement text, free of
|
||||
// interchangeable phrases, that the search accepts as an anchor. A shorter
|
||||
// one occurs in too many statements to say anything.
|
||||
minLeakAnchorRunes = 24
|
||||
// maxLeakCandidates bounds the attempts that one text may match. A text that
|
||||
// more attempts hold is generic: it names no attempt.
|
||||
maxLeakCandidates = 200
|
||||
// leakTracePageSize is how many attempts one page of the code scan reads.
|
||||
leakTracePageSize = 5000
|
||||
// maxLeakCodes bounds the visible codes that one text may offer, so a text
|
||||
// full of code-shaped tokens cannot make the scan expensive.
|
||||
maxLeakCodes = 16
|
||||
// leakTileTimeSlack is how far outside the life of an attempt the time on a
|
||||
// tile may fall and still count as consistent: the tile shows the clock of the
|
||||
// device, which is not the clock of the server.
|
||||
leakTileTimeSlack = time.Hour
|
||||
)
|
||||
|
||||
// ErrInvalidLeakTrace reports a malformed search request. Its text never
|
||||
// quotes the leaked text.
|
||||
var ErrInvalidLeakTrace = errors.New("invalid assessment leak trace request")
|
||||
|
||||
// LeakDigester derives the keyed digest that stands for a searched text in the
|
||||
// audit, so the same text can be recognized without keeping it.
|
||||
type LeakDigester interface {
|
||||
AssessmentLeakTextDigest(text []byte) domain.AssessmentDigest
|
||||
AssessmentDigestKeyVersion() int16
|
||||
}
|
||||
|
||||
// LeakTracer finds the attempt behind a leaked task text. It works from the
|
||||
// text of a leak, which an operator copies out of a message or, for a
|
||||
// screenshot, reads out of the image with a separate OCR step: the tracer
|
||||
// accepts text and reads no image. It reads attempt identifiers and unmarked
|
||||
// statements, writes only its own audit, shows nothing to an employer, and
|
||||
// changes no result, category, or quota. What it finds is a hint for a manual
|
||||
// review and an appeal, never an automatic decision.
|
||||
type LeakTracer struct {
|
||||
transactor outbound.Transactor
|
||||
seeds WatermarkSeeds
|
||||
digester LeakDigester
|
||||
}
|
||||
|
||||
// NewLeakTracer fails at startup when a dependency is missing.
|
||||
func NewLeakTracer(transactor outbound.Transactor, seeds WatermarkSeeds, digester LeakDigester) (*LeakTracer, error) {
|
||||
if transactor == nil || seeds == nil || digester == nil {
|
||||
return nil, errors.New("assessment.NewLeakTracer - every dependency must be set")
|
||||
}
|
||||
return &LeakTracer{transactor: transactor, seeds: seeds, digester: digester}, nil
|
||||
}
|
||||
|
||||
// LeakTraceCommand is one search. Text is the leaked text, with or without its
|
||||
// invisible characters. Code is a visible code that the operator read from a
|
||||
// screenshot by eye; it is searched like a code found in the text.
|
||||
type LeakTraceCommand struct {
|
||||
Actor string
|
||||
Text string
|
||||
Code string
|
||||
}
|
||||
|
||||
// LeakTraceResult is what a search found. Notes are fixed phrases about the
|
||||
// evidence; none of them quotes the text.
|
||||
type LeakTraceResult struct {
|
||||
SearchID uuid.UUID
|
||||
Status domain.AssessmentLeakTraceStatus
|
||||
Method domain.AssessmentLeakTraceMethod
|
||||
AttemptID domain.AssessmentAttemptID
|
||||
Candidates int32
|
||||
EvidenceBits int32
|
||||
Notes []string
|
||||
}
|
||||
|
||||
// leakEvidence is what the text offers before anything is looked up.
|
||||
type leakEvidence struct {
|
||||
normalized string
|
||||
canonical string
|
||||
// markCodes are the distinct codes of intact invisible runs, and markCopies
|
||||
// the number of intact runs; a code is exact.
|
||||
markCodes []domain.AssessmentWatermarkCode
|
||||
markCopies int
|
||||
// visibleCodes are codes read from a screenshot; a recognizer can miss one
|
||||
// character, so one differing character is tolerated.
|
||||
visibleCodes []domain.AssessmentWatermarkCode
|
||||
tileTimes []time.Time
|
||||
}
|
||||
|
||||
// attemptHit is an attempt whose code the text shows.
|
||||
type attemptHit struct {
|
||||
attempt outbound.AssessmentTraceAttempt
|
||||
distance int
|
||||
}
|
||||
|
||||
// Trace searches for the attempt and records the search. The search and its
|
||||
// audit are one transaction: no result exists without its record, and a failed
|
||||
// audit fails the search.
|
||||
func (tracer *LeakTracer) Trace(ctx context.Context, command LeakTraceCommand) (LeakTraceResult, error) {
|
||||
const location = "LeakTracer.Trace"
|
||||
actor, err := domain.ParseAssessmentReviewActor(command.Actor)
|
||||
if err != nil {
|
||||
return LeakTraceResult{}, fmt.Errorf("%s - parse actor: %w", location, err)
|
||||
}
|
||||
evidence, err := gatherLeakEvidence(command)
|
||||
if err != nil {
|
||||
return LeakTraceResult{}, fmt.Errorf("%s - read the text: %w", location, err)
|
||||
}
|
||||
searchID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return LeakTraceResult{}, fmt.Errorf("%s - generate search ID: %w", location, err)
|
||||
}
|
||||
var result LeakTraceResult
|
||||
err = tracer.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
repository := unit.AssessmentLeakTraces()
|
||||
found, err := tracer.search(ctx, repository, evidence)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - search: %w", location, err)
|
||||
}
|
||||
found.SearchID = searchID
|
||||
searchedAt, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read database time: %w", location, err)
|
||||
}
|
||||
record := domain.AssessmentLeakTraceRecord{
|
||||
ID: searchID, Actor: actor, SearchedAt: searchedAt.UTC().Truncate(time.Microsecond),
|
||||
TextDigest: tracer.digester.AssessmentLeakTextDigest([]byte(evidence.canonical)),
|
||||
KeyVersion: tracer.digester.AssessmentDigestKeyVersion(),
|
||||
TextRunes: int32(min(utf8.RuneCountInString(evidence.normalized), 1<<30)), //nolint:gosec // The text is at most maxLeakTextBytes.
|
||||
Status: found.Status, Method: found.Method, AttemptID: found.AttemptID,
|
||||
Candidates: found.Candidates, EvidenceBits: found.EvidenceBits,
|
||||
}
|
||||
if err := repository.RecordSearch(ctx, record); err != nil {
|
||||
return fmt.Errorf("%s - record the search: %w", location, err)
|
||||
}
|
||||
result = found
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return LeakTraceResult{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func gatherLeakEvidence(command LeakTraceCommand) (leakEvidence, error) {
|
||||
const location = "assessment.gatherLeakEvidence"
|
||||
if len(command.Text) > maxLeakTextBytes {
|
||||
return leakEvidence{}, fmt.Errorf("%s - the text is longer than %d bytes: %w", location, maxLeakTextBytes, ErrInvalidLeakTrace)
|
||||
}
|
||||
if !utf8.ValidString(command.Text) {
|
||||
return leakEvidence{}, fmt.Errorf("%s - the text is not valid UTF-8: %w", location, ErrInvalidLeakTrace)
|
||||
}
|
||||
runs := domain.ExtractAssessmentWatermarkCodes(command.Text)
|
||||
evidence := leakEvidence{
|
||||
normalized: domain.NormalizedAssessmentText(command.Text),
|
||||
canonical: domain.CanonicalAssessmentText(command.Text),
|
||||
markCodes: uniqueCodes(runs), markCopies: len(runs),
|
||||
}
|
||||
evidence.visibleCodes, evidence.tileTimes = visibleLeakCodes(evidence.normalized)
|
||||
if strings.TrimSpace(command.Code) != "" {
|
||||
code, err := domain.ParseAssessmentWatermarkCode(command.Code)
|
||||
if err != nil {
|
||||
return leakEvidence{}, fmt.Errorf("%s - the code is not a watermark code: %w", location, ErrInvalidLeakTrace)
|
||||
}
|
||||
evidence.visibleCodes = uniqueCodes(append(evidence.visibleCodes, code))
|
||||
}
|
||||
if evidence.normalized == "" && len(evidence.visibleCodes) == 0 {
|
||||
return leakEvidence{}, fmt.Errorf("%s - there is no text and no code: %w", location, ErrInvalidLeakTrace)
|
||||
}
|
||||
return evidence, nil
|
||||
}
|
||||
|
||||
var (
|
||||
// The tile shows the code in two groups of five. A recognizer may read the
|
||||
// hyphen as another dash or leave a space around it.
|
||||
hyphenatedCode = regexp.MustCompile(`(?i)\b([0-9a-z]{5})\s?[-\x{2010}-\x{2015}_]\s?([0-9a-z]{5})\b`)
|
||||
// Or it may drop the hyphen; then the time that follows on the tile anchors it.
|
||||
tileLine = regexp.MustCompile(`(?i)\b([0-9a-z]{5})[-\x{2010}-\x{2015}_ ]?([0-9a-z]{5})\s+(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2})Z?`)
|
||||
)
|
||||
|
||||
// visibleLeakCodes reads the codes that the text of a screenshot shows and the
|
||||
// times that stand beside them on the tile.
|
||||
func visibleLeakCodes(text string) ([]domain.AssessmentWatermarkCode, []time.Time) {
|
||||
var codes []domain.AssessmentWatermarkCode
|
||||
var times []time.Time
|
||||
add := func(first, second string) {
|
||||
if code, err := domain.ParseAssessmentWatermarkCode(first + second); err == nil {
|
||||
codes = append(codes, code)
|
||||
}
|
||||
}
|
||||
for _, match := range hyphenatedCode.FindAllStringSubmatch(text, -1) {
|
||||
add(match[1], match[2])
|
||||
}
|
||||
for _, match := range tileLine.FindAllStringSubmatch(text, -1) {
|
||||
add(match[1], match[2])
|
||||
if at, err := time.Parse("2006-01-02 15:04", match[3]+" "+match[4]); err == nil {
|
||||
times = append(times, at.UTC())
|
||||
}
|
||||
}
|
||||
codes = uniqueCodes(codes)
|
||||
if len(codes) > maxLeakCodes {
|
||||
codes = codes[:maxLeakCodes]
|
||||
}
|
||||
return codes, times
|
||||
}
|
||||
|
||||
func uniqueCodes(codes []domain.AssessmentWatermarkCode) []domain.AssessmentWatermarkCode {
|
||||
seen := make(map[domain.AssessmentWatermarkCode]struct{}, len(codes))
|
||||
unique := make([]domain.AssessmentWatermarkCode, 0, len(codes))
|
||||
for _, code := range codes {
|
||||
if _, duplicate := seen[code]; duplicate {
|
||||
continue
|
||||
}
|
||||
seen[code] = struct{}{}
|
||||
unique = append(unique, code)
|
||||
}
|
||||
return unique
|
||||
}
|
||||
|
||||
// search runs the methods in order of strength: the invisible mark, the visible
|
||||
// code, and the statement text with its wording. A strong method that finds an
|
||||
// attempt decides; the statement text then only corroborates it.
|
||||
func (tracer *LeakTracer) search(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentLeakTraceRepository,
|
||||
evidence leakEvidence,
|
||||
) (LeakTraceResult, error) {
|
||||
var notes []string
|
||||
if len(evidence.markCodes) > 0 || len(evidence.visibleCodes) > 0 {
|
||||
marked, visible, err := tracer.scanCodes(ctx, repository, evidence)
|
||||
if err != nil {
|
||||
return LeakTraceResult{}, err
|
||||
}
|
||||
if result, decided := decideByCodes(evidence, marked, visible); decided {
|
||||
return tracer.corroborate(ctx, repository, evidence, result)
|
||||
}
|
||||
notes = append(notes, codeNotes(evidence, marked, visible)...)
|
||||
} else {
|
||||
notes = append(notes, "the text holds no invisible mark and no visible code")
|
||||
}
|
||||
result, err := tracer.searchStatements(ctx, repository, evidence)
|
||||
if err != nil {
|
||||
return LeakTraceResult{}, err
|
||||
}
|
||||
result.Notes = append(notes, result.Notes...)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// scanCodes walks every real attempt once and compares its code with the codes
|
||||
// of the text. The code of an attempt is computed, never stored, so nothing
|
||||
// needs a lookup table.
|
||||
func (tracer *LeakTracer) scanCodes(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentLeakTraceRepository,
|
||||
evidence leakEvidence,
|
||||
) (marked, visible []attemptHit, err error) {
|
||||
const location = "LeakTracer.scanCodes"
|
||||
var after domain.AssessmentAttemptID
|
||||
for {
|
||||
page, err := repository.ListRealAttempts(ctx, after, leakTracePageSize)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("%s - list attempts: %w", location, err)
|
||||
}
|
||||
for _, attempt := range page {
|
||||
watermark, err := domain.NewAssessmentWatermark(tracer.seeds.AssessmentWatermarkSeed(attempt.ID.UUID()))
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("%s - build the watermark of an attempt: %w", location, err)
|
||||
}
|
||||
code := watermark.Code()
|
||||
for _, target := range evidence.markCodes {
|
||||
if code == target {
|
||||
marked = append(marked, attemptHit{attempt: attempt})
|
||||
}
|
||||
}
|
||||
for _, target := range evidence.visibleCodes {
|
||||
if distance := code.Distance(target); distance <= 1 {
|
||||
visible = append(visible, attemptHit{attempt: attempt, distance: distance})
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(page) < leakTracePageSize {
|
||||
return marked, visible, nil
|
||||
}
|
||||
after = page[len(page)-1].ID
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, fmt.Errorf("%s - search was cancelled: %w", location, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func distinctAttempts(hits []attemptHit) []domain.AssessmentAttemptID {
|
||||
var ids []domain.AssessmentAttemptID
|
||||
for _, hit := range hits {
|
||||
if !containsAttempt(ids, hit.attempt.ID) {
|
||||
ids = append(ids, hit.attempt.ID)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func containsAttempt(ids []domain.AssessmentAttemptID, id domain.AssessmentAttemptID) bool {
|
||||
for _, candidate := range ids {
|
||||
if candidate == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// decideByCodes turns the hits of the two code channels into a result. Both
|
||||
// codes are keyed, so one attempt behind one code is a finding on its own. Two
|
||||
// attempts behind the codes, or a mark and a code that name different attempts,
|
||||
// is ambiguous and never a guess.
|
||||
func decideByCodes(evidence leakEvidence, marked, visible []attemptHit) (LeakTraceResult, bool) {
|
||||
markedIDs, visibleIDs := distinctAttempts(marked), distinctAttempts(visible)
|
||||
switch {
|
||||
case len(markedIDs) == 0 && len(visibleIDs) == 0:
|
||||
return LeakTraceResult{}, false
|
||||
case len(markedIDs) > 1 || len(visibleIDs) > 1 || len(markedIDs) == 1 && len(visibleIDs) == 1 && markedIDs[0] != visibleIDs[0]:
|
||||
count := int32(max(len(markedIDs), len(visibleIDs))) //nolint:gosec // Bounded by the codes of one text.
|
||||
return LeakTraceResult{
|
||||
Status: domain.AssessmentLeakTraceAmbiguous, Candidates: count,
|
||||
Notes: []string{"the codes of the text name more than one attempt, or the mark and the visible code name different attempts"},
|
||||
}, true
|
||||
case len(markedIDs) == 1:
|
||||
return LeakTraceResult{
|
||||
Status: domain.AssessmentLeakTraceFound, Method: domain.AssessmentLeakTraceInvisibleMark,
|
||||
AttemptID: markedIDs[0], Candidates: 1, EvidenceBits: 50,
|
||||
Notes: markNotes(evidence, visible),
|
||||
}, true
|
||||
default:
|
||||
return LeakTraceResult{
|
||||
Status: domain.AssessmentLeakTraceFound, Method: domain.AssessmentLeakTraceVisibleCode,
|
||||
AttemptID: visibleIDs[0], Candidates: 1, EvidenceBits: visibleBits(visible, visibleIDs[0]),
|
||||
Notes: visibleNotes(evidence, visible),
|
||||
}, true
|
||||
}
|
||||
}
|
||||
|
||||
// visibleBits is the strength of a visible code: all 50 bits when it matches
|
||||
// exactly, and about 45 when one recognized character differs, because that
|
||||
// character could have been any of 31 others.
|
||||
func visibleBits(hits []attemptHit, id domain.AssessmentAttemptID) int32 {
|
||||
for _, hit := range hits {
|
||||
if hit.attempt.ID == id && hit.distance == 0 {
|
||||
return 50
|
||||
}
|
||||
}
|
||||
return 45
|
||||
}
|
||||
|
||||
func markNotes(evidence leakEvidence, visible []attemptHit) []string {
|
||||
notes := []string{fmt.Sprintf("the invisible mark of the statement carries one code (%d intact copies of it)", evidence.markCopies)}
|
||||
if len(visible) > 0 {
|
||||
notes = append(notes, "a visible code in the text names the same attempt")
|
||||
}
|
||||
return notes
|
||||
}
|
||||
|
||||
func visibleNotes(evidence leakEvidence, visible []attemptHit) []string {
|
||||
notes := []string{"the visible code of the tile matches one attempt"}
|
||||
exact := false
|
||||
var attempt outbound.AssessmentTraceAttempt
|
||||
for _, hit := range visible {
|
||||
attempt = hit.attempt
|
||||
exact = exact || hit.distance == 0
|
||||
}
|
||||
if !exact {
|
||||
notes = append(notes, "one character of the recognized code differs from the code of the attempt, as a text recognizer may misread it")
|
||||
}
|
||||
if note := tileTimeNote(evidence.tileTimes, attempt); note != "" {
|
||||
notes = append(notes, note)
|
||||
}
|
||||
return notes
|
||||
}
|
||||
|
||||
// tileTimeNote compares the time on the tile with the life of the attempt. The
|
||||
// time is the clock of a device, so a difference is a note and never a verdict.
|
||||
func tileTimeNote(times []time.Time, attempt outbound.AssessmentTraceAttempt) string {
|
||||
if len(times) == 0 || attempt.ID.IsZero() {
|
||||
return ""
|
||||
}
|
||||
for _, at := range times {
|
||||
if !at.Before(attempt.CreatedAt.Add(-leakTileTimeSlack)) && !at.After(attempt.ExpiresAt.Add(leakTileTimeSlack)) {
|
||||
return "the time on the tile falls within the life of the attempt"
|
||||
}
|
||||
}
|
||||
return "the time on the tile falls outside the life of the attempt, which a wrong device clock can also cause"
|
||||
}
|
||||
|
||||
func codeNotes(evidence leakEvidence, marked, visible []attemptHit) []string {
|
||||
var notes []string
|
||||
if len(evidence.markCodes) > 0 && len(marked) == 0 {
|
||||
notes = append(notes, "the invisible mark of the text matches no attempt (a key from before a secret rotation, a deleted attempt, or a forged mark)")
|
||||
}
|
||||
if len(evidence.visibleCodes) > 0 && len(visible) == 0 {
|
||||
notes = append(notes, "no visible code of the text matches an attempt")
|
||||
}
|
||||
return notes
|
||||
}
|
||||
|
||||
// corroborate adds what the statement text says about a result that the codes
|
||||
// decided: whether the attempt really holds that statement. A mark copied onto
|
||||
// another text, or a code that a text recognizer made up, is then visible.
|
||||
func (tracer *LeakTracer) corroborate(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentLeakTraceRepository,
|
||||
evidence leakEvidence,
|
||||
result LeakTraceResult,
|
||||
) (LeakTraceResult, error) {
|
||||
if result.Status != domain.AssessmentLeakTraceFound {
|
||||
return result, nil
|
||||
}
|
||||
lookup, err := lookupHolders(ctx, repository, evidence)
|
||||
if err != nil {
|
||||
return LeakTraceResult{}, err
|
||||
}
|
||||
switch {
|
||||
case !lookup.anchored:
|
||||
result.Notes = append(result.Notes, "the text is too short to compare with the statements of the attempt")
|
||||
case lookup.generic:
|
||||
result.Notes = append(result.Notes, "the text is too generic to compare with the statements of the attempt")
|
||||
case followsFurthest(lookup, evidence, result.AttemptID):
|
||||
result.Notes = append(result.Notes, "the statement text of the leak matches an item of that attempt")
|
||||
default:
|
||||
result.Notes = append(result.Notes, "the statement text of the leak matches no item of that attempt: the code may have been attached to another text")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// followsFurthest reports whether the text is a copy of a statement of the
|
||||
// attempt, as far as it is a copy of any statement that the lookup found: the
|
||||
// attempt then holds the statement that the text repeats, and not only the text
|
||||
// of its family.
|
||||
func followsFurthest(lookup holderLookup, evidence leakEvidence, id domain.AssessmentAttemptID) bool {
|
||||
furthest, own := 0, 0
|
||||
for _, stored := range lookup.statements {
|
||||
alignment := domain.AssessmentLeakAlignment(stored.Statement, evidence.normalized)
|
||||
if !alignment.Follows() {
|
||||
continue
|
||||
}
|
||||
furthest = max(furthest, alignment.Runes)
|
||||
if stored.AttemptID == id {
|
||||
own = max(own, alignment.Runes)
|
||||
}
|
||||
}
|
||||
return furthest >= minLeakAnchorRunes && own == furthest
|
||||
}
|
||||
|
||||
// holderLookup is what the statements say about a text: the statements of real
|
||||
// attempts that contain its anchor, whether the text was long enough to look
|
||||
// up, and whether so many statements contain it that it is generic.
|
||||
type holderLookup struct {
|
||||
statements []outbound.AssessmentTraceStatement
|
||||
anchored bool
|
||||
generic bool
|
||||
}
|
||||
|
||||
func lookupHolders(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentLeakTraceRepository,
|
||||
evidence leakEvidence,
|
||||
) (holderLookup, error) {
|
||||
const location = "assessment.lookupHolders"
|
||||
anchors := leakAnchors(evidence.normalized)
|
||||
if len(anchors) == 0 {
|
||||
return holderLookup{}, nil
|
||||
}
|
||||
// A piece of the text that the family of tasks shares with many attempts is
|
||||
// generic, and a piece at the end of the text may carry words from around the
|
||||
// statement and match nothing. The attempts that were served the statement are
|
||||
// in every set that does match, so the smallest set holds them.
|
||||
var smallest []outbound.AssessmentTraceStatement
|
||||
sawGeneric := false
|
||||
for _, anchor := range anchors {
|
||||
statements, err := repository.FindStatementsContaining(ctx, anchor, maxLeakCandidates+1)
|
||||
if err != nil {
|
||||
return holderLookup{}, fmt.Errorf("%s - find statements: %w", location, err)
|
||||
}
|
||||
switch {
|
||||
case len(statements) > maxLeakCandidates:
|
||||
sawGeneric = true
|
||||
case len(statements) > 0 && (smallest == nil || len(statements) < len(smallest)):
|
||||
smallest = statements
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case smallest != nil:
|
||||
return holderLookup{statements: smallest, anchored: true}, nil
|
||||
case sawGeneric:
|
||||
return holderLookup{anchored: true, generic: true}, nil
|
||||
default:
|
||||
return holderLookup{anchored: true}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// searchStatements decides by the statement text alone: the attempts that were
|
||||
// served this text, told apart by the interchangeable phrases their keys chose.
|
||||
func (tracer *LeakTracer) searchStatements(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentLeakTraceRepository,
|
||||
evidence leakEvidence,
|
||||
) (LeakTraceResult, error) {
|
||||
lookup, err := lookupHolders(ctx, repository, evidence)
|
||||
switch {
|
||||
case err != nil:
|
||||
return LeakTraceResult{}, err
|
||||
case !lookup.anchored:
|
||||
return notFound(fmt.Sprintf("the text is too short to identify a statement: it needs a stretch of at least %d characters without the interchangeable phrases", minLeakAnchorRunes)), nil
|
||||
case lookup.generic:
|
||||
return notFound(fmt.Sprintf("the text is generic: more than %d statements contain it", maxLeakCandidates)), nil
|
||||
case len(lookup.statements) == 0:
|
||||
return notFound("no statement of any real attempt contains this text"), nil
|
||||
}
|
||||
return tracer.narrowByWording(evidence, lookup)
|
||||
}
|
||||
|
||||
// narrowByWording decides among the attempts that hold a statement containing a
|
||||
// piece of the text. It first keeps the attempts whose statement the text
|
||||
// follows furthest, because the statement of another variant of the same family
|
||||
// shares the text of the family and differs in its numbers. Of those it keeps
|
||||
// the attempts whose chosen phrases the text does not contradict: the key of an
|
||||
// attempt chose one form for every interchangeable phrase, and the text shows
|
||||
// the forms that its source wrote. When the text shows no phrase group, or
|
||||
// several attempts chose alike, the wording cannot decide: one holder is then
|
||||
// named by the variant alone, and several are ambiguous, never a guess. A single
|
||||
// holder whose phrases the text contradicts is excluded, because the leak may
|
||||
// come from an attempt that was deleted.
|
||||
func (tracer *LeakTracer) narrowByWording(evidence leakEvidence, lookup holderLookup) (LeakTraceResult, error) {
|
||||
const location = "LeakTracer.narrowByWording"
|
||||
type aligned struct {
|
||||
attempt domain.AssessmentAttemptID
|
||||
alignment domain.LeakAlignment
|
||||
}
|
||||
var candidates []aligned
|
||||
furthest := 0
|
||||
for _, stored := range lookup.statements {
|
||||
alignment := domain.AssessmentLeakAlignment(stored.Statement, evidence.normalized)
|
||||
// The statement of another variant of the same family shares the text of
|
||||
// the family and then diverges: it is not a copy of the text.
|
||||
if !alignment.Follows() {
|
||||
continue
|
||||
}
|
||||
furthest = max(furthest, alignment.Runes)
|
||||
candidates = append(candidates, aligned{attempt: stored.AttemptID, alignment: alignment})
|
||||
}
|
||||
if furthest < minLeakAnchorRunes {
|
||||
return notFound("no statement of any real attempt is followed by this text to its end or to where the text stops"), nil
|
||||
}
|
||||
var holders, consistent []domain.AssessmentAttemptID
|
||||
slots := 0
|
||||
for _, candidate := range candidates {
|
||||
if candidate.alignment.Runes != furthest {
|
||||
continue
|
||||
}
|
||||
watermark, err := domain.NewAssessmentWatermark(tracer.seeds.AssessmentWatermarkSeed(candidate.attempt.UUID()))
|
||||
if err != nil {
|
||||
return LeakTraceResult{}, fmt.Errorf("%s - build the watermark of an attempt: %w", location, err)
|
||||
}
|
||||
agreeing, groups := watermark.WordingAgreement(candidate.alignment)
|
||||
slots = max(slots, groups)
|
||||
if !containsAttempt(holders, candidate.attempt) {
|
||||
holders = append(holders, candidate.attempt)
|
||||
}
|
||||
if agreeing == groups && !containsAttempt(consistent, candidate.attempt) {
|
||||
consistent = append(consistent, candidate.attempt)
|
||||
}
|
||||
}
|
||||
notes := []string{fmt.Sprintf("%d attempt(s) were served the statement that the text follows; the text shows %d interchangeable phrase group(s) of it", len(holders), slots)}
|
||||
switch {
|
||||
case len(consistent) == 0:
|
||||
result := notFound("the wording of the text disagrees with every attempt that was served this statement, so none of them is its source")
|
||||
result.Candidates = int32(len(holders)) //nolint:gosec // Bounded by maxLeakCandidates.
|
||||
result.Notes = append(notes, result.Notes...)
|
||||
return result, nil
|
||||
case len(consistent) > 1:
|
||||
return LeakTraceResult{
|
||||
Status: domain.AssessmentLeakTraceAmbiguous, Candidates: int32(len(consistent)), //nolint:gosec // Bounded by maxLeakCandidates.
|
||||
Notes: append(notes, "the wording of the text does not tell these attempts apart: they chose the same phrases, or the text shows none"),
|
||||
}, nil
|
||||
case len(holders) == 1 && slots == 0:
|
||||
return LeakTraceResult{
|
||||
Status: domain.AssessmentLeakTraceFound, Method: domain.AssessmentLeakTraceVariant,
|
||||
AttemptID: consistent[0], Candidates: 1,
|
||||
Notes: append(notes, "only one attempt was served this statement text, and the text carries no phrase group: this follows from the variant, not from a mark"),
|
||||
}, nil
|
||||
default:
|
||||
return LeakTraceResult{
|
||||
Status: domain.AssessmentLeakTraceFound, Method: domain.AssessmentLeakTraceWording,
|
||||
AttemptID: consistent[0], Candidates: 1, EvidenceBits: int32(slots),
|
||||
Notes: append(notes, "the wording of the text repeats the phrases that the key of this attempt chose, and no other attempt that was served the statement"),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func notFound(reason string) LeakTraceResult {
|
||||
return LeakTraceResult{Status: domain.AssessmentLeakTraceNotFound, Notes: []string{reason}}
|
||||
}
|
||||
|
||||
// maxLeakAnchors bounds how many pieces of a text are looked up.
|
||||
const maxLeakAnchors = 5
|
||||
|
||||
// leakAnchors lists the stretches of the normalized text that the database can
|
||||
// look for literally, longest first: the pieces between the interchangeable
|
||||
// phrases, because a stored statement may write a phrase in another form than
|
||||
// the text. A piece shorter than minLeakAnchorRunes is left out, and the list
|
||||
// is empty when no piece is long enough.
|
||||
func leakAnchors(normalized string) []string {
|
||||
var anchors []string
|
||||
for _, piece := range domain.AssessmentTextPiecesBetweenPhrases(normalized) {
|
||||
if piece = strings.TrimSpace(piece); utf8.RuneCountInString(piece) >= minLeakAnchorRunes {
|
||||
anchors = append(anchors, piece)
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(anchors, func(left, right string) int {
|
||||
return utf8.RuneCountInString(right) - utf8.RuneCountInString(left)
|
||||
})
|
||||
return anchors[:min(len(anchors), maxLeakAnchors)]
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const leakStatement = "A gateway protects an endpoint with a sliding-window limiter. A request arriving at second t is accepted only when fewer than 3 previously accepted requests have an arrival time in the half-open interval (t - 5, t]. A rejected request is not remembered and does not count against later requests. The gateway receives 8 requests at these arrival times, in seconds and in non-decreasing order: 0 0 1 2 2 3 4 6. How many requests does the gateway reject?"
|
||||
|
||||
var leakNow = time.Date(2026, time.October, 11, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
type leakDigesterFake struct{}
|
||||
|
||||
func (leakDigesterFake) AssessmentLeakTextDigest(text []byte) domain.AssessmentDigest {
|
||||
return domain.AssessmentDigest(sha256.Sum256(append([]byte("leak:"), text...)))
|
||||
}
|
||||
|
||||
func (leakDigesterFake) AssessmentDigestKeyVersion() int16 { return 7 }
|
||||
|
||||
// leakRepositoryFake holds attempts with their statements and records the audit.
|
||||
type leakRepositoryFake struct {
|
||||
attempts []outbound.AssessmentTraceAttempt
|
||||
statements []outbound.AssessmentTraceStatement
|
||||
records []domain.AssessmentLeakTraceRecord
|
||||
recordErr error
|
||||
}
|
||||
|
||||
func (repository *leakRepositoryFake) ListRealAttempts(_ context.Context, after domain.AssessmentAttemptID, limit int32) ([]outbound.AssessmentTraceAttempt, error) {
|
||||
var page []outbound.AssessmentTraceAttempt
|
||||
for _, attempt := range repository.attempts {
|
||||
if attempt.ID.UUID().String() > after.UUID().String() || after.IsZero() {
|
||||
page = append(page, attempt)
|
||||
}
|
||||
if int32(len(page)) == limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (repository *leakRepositoryFake) FindStatementsContaining(_ context.Context, fragment string, limit int32) ([]outbound.AssessmentTraceStatement, error) {
|
||||
var found []outbound.AssessmentTraceStatement
|
||||
for _, stored := range repository.statements {
|
||||
if strings.Contains(strings.Join(strings.Fields(stored.Statement), " "), fragment) {
|
||||
found = append(found, stored)
|
||||
}
|
||||
if int32(len(found)) == limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func (repository *leakRepositoryFake) RecordSearch(_ context.Context, record domain.AssessmentLeakTraceRecord) error {
|
||||
if repository.recordErr != nil {
|
||||
return repository.recordErr
|
||||
}
|
||||
if err := record.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
repository.records = append(repository.records, record)
|
||||
return nil
|
||||
}
|
||||
|
||||
type leakUnitFake struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
repository *leakRepositoryFake
|
||||
}
|
||||
|
||||
func (unit *leakUnitFake) AssessmentLeakTraces() outbound.AssessmentLeakTraceRepository {
|
||||
return unit.repository
|
||||
}
|
||||
|
||||
func (unit *leakUnitFake) AssessmentBank() outbound.AssessmentBankRepository { return bankClockFake{} }
|
||||
|
||||
type runningTransactor struct{ unit outbound.UnitOfWork }
|
||||
|
||||
func (transactor runningTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error {
|
||||
return fn(ctx, transactor.unit)
|
||||
}
|
||||
|
||||
func newLeakTracer(t *testing.T, repository *leakRepositoryFake) *LeakTracer {
|
||||
t.Helper()
|
||||
tracer, err := NewLeakTracer(runningTransactor{unit: &leakUnitFake{repository: repository}}, hashedSeeds{}, leakDigesterFake{})
|
||||
if err != nil {
|
||||
t.Fatalf("NewLeakTracer() error = %v", err)
|
||||
}
|
||||
return tracer
|
||||
}
|
||||
|
||||
func (repository *leakRepositoryFake) serve(id domain.AssessmentAttemptID, statement string) {
|
||||
repository.attempts = append(repository.attempts, outbound.AssessmentTraceAttempt{
|
||||
ID: id, CreatedAt: leakNow.Add(-30 * time.Minute), ExpiresAt: leakNow.Add(30 * time.Minute),
|
||||
})
|
||||
repository.statements = append(repository.statements, outbound.AssessmentTraceStatement{AttemptID: id, Statement: statement})
|
||||
}
|
||||
|
||||
func leakWatermark(t *testing.T, id domain.AssessmentAttemptID) domain.AssessmentWatermark {
|
||||
t.Helper()
|
||||
watermark, err := domain.NewAssessmentWatermark(hashedSeeds{}.AssessmentWatermarkSeed(id.UUID()))
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentWatermark() error = %v", err)
|
||||
}
|
||||
return watermark
|
||||
}
|
||||
|
||||
// attemptsThatWriteTheStatementDifferently returns count attempts that were
|
||||
// served the same statement and chose different phrases for at least one group.
|
||||
func attemptsThatWriteTheStatementDifferently(t *testing.T, count int) []domain.AssessmentAttemptID {
|
||||
t.Helper()
|
||||
var ids []domain.AssessmentAttemptID
|
||||
seen := map[string]struct{}{}
|
||||
for range 400 {
|
||||
id := domain.AssessmentAttemptID(uuid.New())
|
||||
wording := domain.VisibleAssessmentText(leakWatermark(t, id).Mark(leakStatement))
|
||||
if _, duplicate := seen[wording]; duplicate {
|
||||
continue
|
||||
}
|
||||
seen[wording] = struct{}{}
|
||||
ids = append(ids, id)
|
||||
if len(ids) == count {
|
||||
return ids
|
||||
}
|
||||
}
|
||||
t.Fatalf("no %d attempts with different wording found", count)
|
||||
return nil
|
||||
}
|
||||
|
||||
func traceAs(t *testing.T, tracer *LeakTracer, text, code string) LeakTraceResult {
|
||||
t.Helper()
|
||||
result, err := tracer.Trace(context.Background(), LeakTraceCommand{Actor: "operator:night.shift", Text: text, Code: code})
|
||||
if err != nil {
|
||||
t.Fatalf("Trace() error = %v", err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TestLeakedTextOfAVariantFindsTheAttemptByItsInvisibleMark(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 3)
|
||||
for _, id := range ids {
|
||||
repository.serve(id, leakStatement)
|
||||
}
|
||||
tracer := newLeakTracer(t, repository)
|
||||
for index, id := range ids {
|
||||
leaked := leakWatermark(t, id).Mark(leakStatement)
|
||||
// A leak usually holds the statement among other text.
|
||||
result := traceAs(t, tracer, "Question from the exam: "+leaked+" Thanks!", "")
|
||||
if result.Status != domain.AssessmentLeakTraceFound || result.Method != domain.AssessmentLeakTraceInvisibleMark || result.AttemptID != id {
|
||||
t.Fatalf("attempt %d: result = %+v, want found by the invisible mark in %s", index, result, id)
|
||||
}
|
||||
if result.EvidenceBits != 50 || result.Candidates != 1 {
|
||||
t.Fatalf("attempt %d: evidence = %d bits, %d candidates, want 50 and 1", index, result.EvidenceBits, result.Candidates)
|
||||
}
|
||||
if !strings.Contains(strings.Join(result.Notes, " "), "matches an item of that attempt") {
|
||||
t.Fatalf("attempt %d: notes = %v, want the corroboration by the statement text", index, result.Notes)
|
||||
}
|
||||
}
|
||||
// Every search was audited, with the attempt it found.
|
||||
if len(repository.records) != len(ids) || repository.records[0].AttemptID != ids[0] || repository.records[0].Method != domain.AssessmentLeakTraceInvisibleMark {
|
||||
t.Fatalf("audit = %+v, want one record per search", repository.records)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithoutTheInvisibleCharactersTheSearchFallsBackToTheVisibleCodeAndTheWording(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 3)
|
||||
for _, id := range ids {
|
||||
repository.serve(id, leakStatement)
|
||||
}
|
||||
tracer := newLeakTracer(t, repository)
|
||||
target := ids[1]
|
||||
watermark := leakWatermark(t, target)
|
||||
retyped := domain.VisibleAssessmentText(watermark.Mark(leakStatement))
|
||||
if retyped == leakStatement {
|
||||
t.Fatal("the fixture attempt wrote the statement as the bank did, so the wording cannot show it")
|
||||
}
|
||||
|
||||
// The OCR text of a screenshot: the statement, and the tile with its code and time.
|
||||
tile := fmt.Sprintf("%s %s", watermark.Code().String(), leakNow.Format("2006-01-02 15:04")+"Z")
|
||||
screenshot := traceAs(t, tracer, retyped+"\n"+tile, "")
|
||||
if screenshot.Status != domain.AssessmentLeakTraceFound || screenshot.Method != domain.AssessmentLeakTraceVisibleCode || screenshot.AttemptID != target {
|
||||
t.Fatalf("screenshot text result = %+v, want found by the visible code", screenshot)
|
||||
}
|
||||
if !strings.Contains(strings.Join(screenshot.Notes, " "), "falls within the life of the attempt") {
|
||||
t.Fatalf("notes = %v, want the tile time within the life of the attempt", screenshot.Notes)
|
||||
}
|
||||
|
||||
// The statement alone, with the invisible characters gone and no tile: only
|
||||
// the wording separates the three attempts that were served it.
|
||||
wordingOnly := traceAs(t, tracer, retyped, "")
|
||||
if wordingOnly.Status != domain.AssessmentLeakTraceFound {
|
||||
t.Fatalf("wording result = %+v, want the three differently worded attempts to be told apart", wordingOnly)
|
||||
}
|
||||
if wordingOnly.Method != domain.AssessmentLeakTraceWording || wordingOnly.AttemptID != target || wordingOnly.EvidenceBits < 1 {
|
||||
t.Fatalf("wording result = %+v, want the wording to find %s", wordingOnly, target)
|
||||
}
|
||||
|
||||
// An operator who read the code by eye gives it with --code and searches the statement text too.
|
||||
byEye := traceAs(t, tracer, "", watermark.Code().String())
|
||||
if byEye.Status != domain.AssessmentLeakTraceFound || byEye.Method != domain.AssessmentLeakTraceVisibleCode || byEye.AttemptID != target {
|
||||
t.Fatalf("code only result = %+v, want found by the code", byEye)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheVisibleCodeToleratesOneMisreadCharacterAndNoMore(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 2)
|
||||
for _, id := range ids {
|
||||
repository.serve(id, leakStatement)
|
||||
}
|
||||
tracer := newLeakTracer(t, repository)
|
||||
code := leakWatermark(t, ids[0]).Code().String()
|
||||
|
||||
misread := []rune(code)
|
||||
misread[2] = otherSymbol(misread[2])
|
||||
one := traceAs(t, tracer, "", string(misread))
|
||||
if one.Status != domain.AssessmentLeakTraceFound || one.AttemptID != ids[0] || one.EvidenceBits != 45 ||
|
||||
!strings.Contains(strings.Join(one.Notes, " "), "one character of the recognized code differs") {
|
||||
t.Fatalf("one misread character: %+v, want found with 45 bits and a note", one)
|
||||
}
|
||||
misread[6] = otherSymbol(misread[6])
|
||||
two := traceAs(t, tracer, "", string(misread))
|
||||
if two.Status != domain.AssessmentLeakTraceNotFound {
|
||||
t.Fatalf("two misread characters: %+v, want not found", two)
|
||||
}
|
||||
}
|
||||
|
||||
func otherSymbol(symbol rune) rune {
|
||||
if symbol == '2' {
|
||||
return '3'
|
||||
}
|
||||
return '2'
|
||||
}
|
||||
|
||||
func TestTextThatMatchesNothingIsNotFoundAndSaysSo(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
id := attemptsThatWriteTheStatementDifferently(t, 1)[0]
|
||||
repository.serve(id, leakStatement)
|
||||
tracer := newLeakTracer(t, repository)
|
||||
|
||||
for name, text := range map[string]string{
|
||||
"an unrelated paragraph": "The committee will meet on Thursday to discuss the budget for the coming year and the new office.",
|
||||
"a text that is too short": "How many requests?",
|
||||
"a statement of another family": "An in-memory cache holds at most 3 entries and evicts the least recently used entry when it is full.",
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
result := traceAs(t, tracer, text, "")
|
||||
if result.Status != domain.AssessmentLeakTraceNotFound || !result.AttemptID.IsZero() || len(result.Notes) == 0 {
|
||||
t.Fatalf("result = %+v, want not found with a reason and no attempt", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
if len(repository.records) != 3 {
|
||||
t.Fatalf("audit holds %d records, want one for every search, found or not", len(repository.records))
|
||||
}
|
||||
for _, record := range repository.records {
|
||||
if record.Status != domain.AssessmentLeakTraceNotFound || !record.AttemptID.IsZero() {
|
||||
t.Fatalf("audit record = %+v, want not found without an attempt", record)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStatementThatOnlyOneAttemptHoldsIsFoundByTheVariantAndExcludedByItsWording(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 2)
|
||||
repository.serve(ids[0], leakStatement)
|
||||
tracer := newLeakTracer(t, repository)
|
||||
|
||||
// The leak was written by the attempt that holds the statement.
|
||||
own := traceAs(t, tracer, domain.VisibleAssessmentText(leakWatermark(t, ids[0]).Mark(leakStatement)), "")
|
||||
if own.Status != domain.AssessmentLeakTraceFound || own.AttemptID != ids[0] || own.Candidates != 1 {
|
||||
t.Fatalf("own text result = %+v, want found", own)
|
||||
}
|
||||
// The same statement with the phrases of another attempt: that attempt may have
|
||||
// been deleted, so the only holder left is excluded by its own wording.
|
||||
foreign := traceAs(t, tracer, domain.VisibleAssessmentText(leakWatermark(t, ids[1]).Mark(leakStatement)), "")
|
||||
if foreign.Status != domain.AssessmentLeakTraceNotFound || !strings.Contains(strings.Join(foreign.Notes, " "), "disagrees with every attempt") {
|
||||
t.Fatalf("foreign wording result = %+v, want not found: the wording excludes the only holder", foreign)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnotherVariantOfTheSameFamilyDoesNotCompeteWithTheLeakedOne(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 2)
|
||||
// The other variant shares all the text of the family and differs in its numbers.
|
||||
otherVariant := strings.NewReplacer("fewer than 3", "fewer than 4", "(t - 5, t]", "(t - 6, t]", "8 requests", "9 requests", "0 0 1 2 2 3 4 6.", "0 1 1 3 3 4 5 8 9.").Replace(leakStatement)
|
||||
if otherVariant == leakStatement {
|
||||
t.Fatal("the fixture variants are the same")
|
||||
}
|
||||
repository.serve(ids[0], leakStatement)
|
||||
repository.serve(ids[1], otherVariant)
|
||||
tracer := newLeakTracer(t, repository)
|
||||
|
||||
// The leak has no mark and no code, and the family text alone matches both attempts.
|
||||
leak := "Posted in the group chat: " + domain.VisibleAssessmentText(leakWatermark(t, ids[0]).Mark(leakStatement)) + " please help"
|
||||
result := traceAs(t, tracer, leak, "")
|
||||
if result.Status != domain.AssessmentLeakTraceFound || result.AttemptID != ids[0] ||
|
||||
(result.Method != domain.AssessmentLeakTraceWording && result.Method != domain.AssessmentLeakTraceVariant) {
|
||||
t.Fatalf("result = %+v, want the attempt that was served the leaked variant, not the other one of its family", result)
|
||||
}
|
||||
if result.Candidates != 1 {
|
||||
t.Fatalf("candidates = %d, want only the attempt whose statement the text follows", result.Candidates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheLeakOfADeletedAttemptIsNotAttributedToAnotherVariantOfItsFamily(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 2)
|
||||
// Only another variant of the family is left: the attempt of the leak was deleted.
|
||||
otherVariant := strings.NewReplacer("fewer than 3", "fewer than 4", "(t - 5, t]", "(t - 6, t]", "8 requests", "9 requests", "0 0 1 2 2 3 4 6.", "0 1 1 3 3 4 5 8 9.").Replace(leakStatement)
|
||||
repository.serve(ids[1], otherVariant)
|
||||
tracer := newLeakTracer(t, repository)
|
||||
|
||||
whole := domain.VisibleAssessmentText(leakWatermark(t, ids[0]).Mark(leakStatement))
|
||||
result := traceAs(t, tracer, whole, "")
|
||||
if result.Status != domain.AssessmentLeakTraceNotFound || !result.AttemptID.IsZero() {
|
||||
t.Fatalf("result = %+v, want not found: the text shares only the text of the family with the attempt that is left", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestACutLeakIsFoundButOtherWordsInsideTheStatementAreNot(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 1)
|
||||
repository.serve(ids[0], leakStatement)
|
||||
tracer := newLeakTracer(t, repository)
|
||||
whole := domain.VisibleAssessmentText(leakWatermark(t, ids[0]).Mark(leakStatement))
|
||||
|
||||
// The leak stops inside the statement, as a cut or a screenshot of the top of the screen does.
|
||||
cut := whole[:len(whole)*2/3]
|
||||
if result := traceAs(t, tracer, cut, ""); result.Status != domain.AssessmentLeakTraceFound || result.AttemptID != ids[0] {
|
||||
t.Fatalf("cut leak result = %+v, want the attempt that was served the statement", result)
|
||||
}
|
||||
// Other words where the statement continues are not a copy of it.
|
||||
if result := traceAs(t, tracer, cut+" and then somebody wrote something else entirely here", ""); result.Status != domain.AssessmentLeakTraceNotFound {
|
||||
t.Fatalf("diverging leak result = %+v, want not found", result)
|
||||
}
|
||||
// Words around the whole statement are fine.
|
||||
if result := traceAs(t, tracer, "Look: "+whole+" What now?", ""); result.Status != domain.AssessmentLeakTraceFound || result.AttemptID != ids[0] {
|
||||
t.Fatalf("leak with words around = %+v, want found", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextHeldByAttemptsThatTheWordingCannotSeparateIsAmbiguous(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
// A statement without any interchangeable phrase: the wording tells nothing.
|
||||
plain := "The queue holds 12 jobs numbered from 1 to 12 and the worker takes the smallest number first every time."
|
||||
ids := []domain.AssessmentAttemptID{domain.AssessmentAttemptID(uuid.New()), domain.AssessmentAttemptID(uuid.New())}
|
||||
for _, id := range ids {
|
||||
repository.serve(id, plain)
|
||||
}
|
||||
tracer := newLeakTracer(t, repository)
|
||||
result := traceAs(t, tracer, plain, "")
|
||||
if result.Status != domain.AssessmentLeakTraceAmbiguous || result.Candidates != 2 || !result.AttemptID.IsZero() {
|
||||
t.Fatalf("result = %+v, want ambiguous between the two attempts without naming one", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMarkCopiedOntoAnotherTextIsFoundButFlagged(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 2)
|
||||
const other = "A scheduler runs 5 jobs one by one and needs 40 seconds to finish all of them in total."
|
||||
repository.serve(ids[0], leakStatement)
|
||||
repository.serve(ids[1], other)
|
||||
tracer := newLeakTracer(t, repository)
|
||||
|
||||
// The invisible run of attempt 0 sits in the text of the other statement.
|
||||
var run strings.Builder
|
||||
for _, r := range leakWatermark(t, ids[0]).Mark(leakStatement) {
|
||||
if unicode.Is(unicode.Cf, r) {
|
||||
run.WriteRune(r)
|
||||
} else if run.Len() > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
result := traceAs(t, tracer, other[:20]+run.String()+other[20:], "")
|
||||
if result.Status != domain.AssessmentLeakTraceFound || result.Method != domain.AssessmentLeakTraceInvisibleMark || result.AttemptID != ids[0] {
|
||||
t.Fatalf("result = %+v, want the mark to name attempt 0", result)
|
||||
}
|
||||
if !strings.Contains(strings.Join(result.Notes, " "), "attached to another text") {
|
||||
t.Fatalf("notes = %v, want the warning that the text does not match the attempt", result.Notes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMarkOfNoAttemptIsNotFound(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
repository.serve(domain.AssessmentAttemptID(uuid.New()), leakStatement)
|
||||
tracer := newLeakTracer(t, repository)
|
||||
// The attempt of this mark is not in the table: deleted, or issued under another secret.
|
||||
unknown := leakWatermark(t, domain.AssessmentAttemptID(uuid.New()))
|
||||
result := traceAs(t, tracer, unknown.Mark("An entirely different paragraph that no statement of the bank contains at all."), "")
|
||||
if result.Status != domain.AssessmentLeakTraceNotFound || !strings.Contains(strings.Join(result.Notes, " "), "matches no attempt") {
|
||||
t.Fatalf("result = %+v, want not found with a note about the mark", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkAndVisibleCodeOfDifferentAttemptsAreAmbiguous(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
ids := attemptsThatWriteTheStatementDifferently(t, 2)
|
||||
for _, id := range ids {
|
||||
repository.serve(id, leakStatement)
|
||||
}
|
||||
tracer := newLeakTracer(t, repository)
|
||||
marked := leakWatermark(t, ids[0]).Mark(leakStatement)
|
||||
result := traceAs(t, tracer, marked+" "+leakWatermark(t, ids[1]).Code().String()+" "+leakNow.Format("2006-01-02 15:04"), "")
|
||||
if result.Status != domain.AssessmentLeakTraceAmbiguous || !result.AttemptID.IsZero() {
|
||||
t.Fatalf("result = %+v, want ambiguous: the mark and the code name different attempts", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEverySearchIsAuditedWithoutTheTextAndAFailedAuditFailsTheSearch(t *testing.T) {
|
||||
repository := &leakRepositoryFake{}
|
||||
id := attemptsThatWriteTheStatementDifferently(t, 1)[0]
|
||||
repository.serve(id, leakStatement)
|
||||
tracer := newLeakTracer(t, repository)
|
||||
leaked := leakWatermark(t, id).Mark(leakStatement)
|
||||
|
||||
traceAs(t, tracer, leaked, "")
|
||||
traceAs(t, tracer, leaked, "")
|
||||
traceAs(t, tracer, "A paragraph that matches no statement of any attempt in the whole bank at all.", "")
|
||||
if len(repository.records) != 3 {
|
||||
t.Fatalf("audit holds %d records, want 3", len(repository.records))
|
||||
}
|
||||
first, second, third := repository.records[0], repository.records[1], repository.records[2]
|
||||
if first.ID == second.ID || first.TextDigest != second.TextDigest || first.TextDigest == third.TextDigest {
|
||||
t.Fatal("the digest must tie the same text together and tell another text apart, and every search has its own ID")
|
||||
}
|
||||
if first.Actor != "operator:night.shift" || first.KeyVersion != 7 || first.TextRunes < 100 {
|
||||
t.Fatalf("record = %+v, want the actor, the key version, and the length of the text", first)
|
||||
}
|
||||
stored := fmt.Sprintf("%+v", repository.records)
|
||||
for _, secret := range []string{"gateway", "sliding-window", "arrival times"} {
|
||||
if strings.Contains(stored, secret) {
|
||||
t.Fatalf("the audit holds %q, want no part of the leaked text", secret)
|
||||
}
|
||||
}
|
||||
|
||||
repository.recordErr = errors.New("audit storage is down")
|
||||
if result, err := tracer.Trace(context.Background(), LeakTraceCommand{Actor: "operator:night.shift", Text: leaked}); err == nil || !result.AttemptID.IsZero() {
|
||||
t.Fatalf("Trace() = %+v, %v, want no result when the audit cannot be written", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeakTraceRefusesBadRequestsWithoutQuotingTheText(t *testing.T) {
|
||||
tracer := newLeakTracer(t, &leakRepositoryFake{})
|
||||
secret := "SECRET-LEAKED-TEXT"
|
||||
tests := map[string]LeakTraceCommand{
|
||||
"no actor": {Text: secret},
|
||||
"a foreign actor": {Actor: "alice", Text: secret},
|
||||
"no text, no code": {Actor: "operator:night.shift"},
|
||||
"white space only": {Actor: "operator:night.shift", Text: " \n\t "},
|
||||
"a bad code": {Actor: "operator:night.shift", Code: "NOT A CODE"},
|
||||
"an oversized text": {Actor: "operator:night.shift", Text: strings.Repeat("a", maxLeakTextBytes+1)},
|
||||
"invalid UTF-8": {Actor: "operator:night.shift", Text: secret + "\xff\xfe"},
|
||||
}
|
||||
for name, command := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, err := tracer.Trace(context.Background(), command)
|
||||
if err == nil {
|
||||
t.Fatal("Trace() succeeded, want an error")
|
||||
}
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("the error quotes the text: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := NewLeakTracer(nil, hashedSeeds{}, leakDigesterFake{}); err == nil {
|
||||
t.Fatal("NewLeakTracer(nil transactor) succeeded")
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ const (
|
||||
labelWatermark = "lincodex/assessment/watermark/v1"
|
||||
labelSignalAgent = "lincodex/assessment/signal-agent/v1"
|
||||
labelWorkClient = "lincodex/assessment/work-client/v1"
|
||||
labelLeakText = "lincodex/assessment/leak-text/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -59,6 +60,7 @@ type Keyring struct {
|
||||
watermarkKey []byte
|
||||
signalAgentKey []byte
|
||||
workClientKey []byte
|
||||
leakTextKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -82,6 +84,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
watermarkKey: derive(secret, labelWatermark),
|
||||
signalAgentKey: derive(secret, labelSignalAgent),
|
||||
workClientKey: derive(secret, labelWorkClient),
|
||||
leakTextKey: derive(secret, labelLeakText),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -268,3 +271,13 @@ func (keyring *Keyring) AssessmentWorkClientDigest(attemptID uuid.UUID, clientID
|
||||
mac.Write([]byte(clientID))
|
||||
return domain.AssessmentDigest(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// AssessmentLeakTextDigest stands for the text of one operator search in the
|
||||
// audit. It is keyed, so the audit can show that a text was searched twice
|
||||
// without keeping it, and nobody can confirm a guess about a text from the
|
||||
// audit alone.
|
||||
func (keyring *Keyring) AssessmentLeakTextDigest(text []byte) domain.AssessmentDigest {
|
||||
mac := hmac.New(sha256.New, keyring.leakTextKey)
|
||||
mac.Write(text)
|
||||
return domain.AssessmentDigest(mac.Sum(nil))
|
||||
}
|
||||
@@ -188,6 +188,35 @@ func TestAssessmentAgentAndWorkClientDigestsAreKeyedBoundToTheAttemptAndSeparate
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentLeakTextDigestIsKeyedAndSeparateFromTheOtherDigests(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 secret) error = %v", err)
|
||||
}
|
||||
text := []byte("A gateway protects an endpoint with a sliding-window limiter.")
|
||||
digest := keyring.AssessmentLeakTextDigest(text)
|
||||
if digest.IsZero() || digest != keyring.AssessmentLeakTextDigest(text) {
|
||||
t.Fatal("the leak text digest is empty or not deterministic")
|
||||
}
|
||||
if digest == keyring.AssessmentLeakTextDigest(append(bytes.Clone(text), '.')) {
|
||||
t.Fatal("two texts have the same digest")
|
||||
}
|
||||
if digest == other.AssessmentLeakTextDigest(text) {
|
||||
t.Fatal("the digest does not depend on the server secret, so a guess about a text could be confirmed from the audit")
|
||||
}
|
||||
// The digest does not reuse the key of another purpose.
|
||||
attempt := uuid.New()
|
||||
if digest == domain.AssessmentDigest(keyring.AssessmentWatermarkSeed(attempt)) ||
|
||||
digest == keyring.AssessmentAgentDigest(attempt, string(text)) ||
|
||||
digest == domain.AssessmentDigest(keyring.Fingerprint(text)) {
|
||||
t.Fatal("the leak text digest shares a key with another purpose")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t *testing.T) {
|
||||
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
|
||||
if err != nil {
|
||||
|
||||
@@ -725,6 +725,16 @@ Implemented for real attempts (root and corrective). A training run (`demo_expre
|
||||
- Limits of the rule. It is a one-page-at-a-time rule, not a security boundary: a client that never holds the session is refused only while another page holds it, a candidate can always continue after the hold is released or has expired, and two windows of one candidate are not told from two people. The hold is renewed by a page timer, so a browser that throttles a background tab to one tick a minute still renews within the two minutes.
|
||||
- Operator reading. `make -C backend assessment-review ARGS='inspect ...'` prints the new counts `extra_agents`, `client_screenshot_keys`, and `client_devtools_opens` next to the old ones; the note at its end repeats that browser signals can be forged and that a screenshot or a phone photo cannot be prevented or seen by the page.
|
||||
|
||||
### Leak trace
|
||||
|
||||
Implemented as a local operator command, `assessment-leak-trace`, that finds the real attempt behind a leaked task text. It reads text and nothing else: a screenshot or a photo must be read by an OCR tool first, and OCR itself is outside this project (the command accepts any UTF-8 text of at most 64 KiB from a file or standard input, and a visible code that the operator read by eye). The result is a hint for a manual review and an appeal. It is never shown to an employer (no HTTP operation serves it), it changes no score, category, or quota (the command writes nothing but its own audit), and it never names an attempt on a guess. Code: `backend/cmd/assessment-leak-trace/`, `backend/internal/adapter/primary/cli/leaktrace/command.go`, `LeakTracer` in `backend/internal/usecase/assessment/leak_trace.go`, `AssessmentLeakAlignment` and `AssessmentTextPiecesBetweenPhrases` in `domain/assessment_wording.go`, `domain/assessment_leak_trace.go`, migration `backend/db/migrations/00051_create_assessment_leak_traces.sql`, and the queries `backend/db/queries/assessment_leak_traces.sql`.
|
||||
|
||||
- Methods, strongest first. (1) The invisible mark: intact runs of zero-width characters decode to the code of an attempt (50 keyed bits), so one attempt behind one code is a finding on its own. (2) The visible code: the code of the tile, found in the text of a screenshot as two groups of five characters (or ten characters followed by the date and time of the tile) or given with `--code`; one character that the recognizer misread is tolerated (45 bits), two are not. The time on the tile is compared with the life of the attempt (an hour of slack) and reported as a note, never as a verdict, because it is the clock of a device. (3) The statement and its wording: the stored, unmarked statements of real attempts are searched for pieces of the text, the attempts that were served that statement are told apart from other variants of the same family by how far the text follows their statement, and among those by the phrase forms the text shows (about one bit per phrase group; only the phrases aligned with the stored statement are read, so words around the statement in a message are ignored). A statement counts only when the text is a copy of it, whole or cut where the text stops: other words where the statement continues mean that another variant of the same family, which shares only its fixed text, is not the source. A statement text that only one attempt was served names that attempt by the variant alone when the text shows no phrase group, and is excluded when the text shows phrases that contradict the attempt, because the leak may come from an attempt that was deleted.
|
||||
- The code of an attempt is computed, never stored, so no lookup table exists: the command walks every real attempt (5000 per page), computes its code from `IDENTITY_KEY_SECRET`, and compares. The work is linear in the number of attempts and fine for an operator command. The command therefore needs the secret of the server that served the attempts; a rotated secret makes older codes and marks unreadable, and then the search can still use the statement text.
|
||||
- Outcomes. `found` names one attempt, the method, and the strength in bits, with notes such as whether the statement text matches the attempt (a mark attached to another text is flagged). `ambiguous` means that the evidence leaves several attempts in play (two attempts behind the codes, a mark and a visible code that name different attempts, or attempts that were served the same statement and chose the same phrases) and names none. `not_found` is an honest answer when the data is not enough: no mark, no code, no stretch of at least 24 characters free of interchangeable phrases, no statement that contains the text, a text that more than 200 statements contain (generic), or a wording that contradicts every holder.
|
||||
- Audit. Every search writes one row to `assessment_leak_traces` in the same transaction as the search, before a result is printed: the operator handle (`operator:<handle>`, not authentication), the database time, a keyed digest of the normalized text (HMAC-SHA-256 under a key derived from `IDENTITY_KEY_SECRET`, label `lincodex/assessment/leak-text/v1`), its length, the outcome, the method, the attempt for a found search, and the counts. The text is never stored or printed, the table refuses UPDATE, DELETE, and TRUNCATE, and the attempt is not a foreign key, so the audit outlives an account deletion. Rolling migration 51 back is refused while the audit holds a row.
|
||||
- What it cannot do. A leak with the mark and the tile gone, retyped in own words, or photographed so that no tile is legible leaves only the wording and the variant, which name one attempt only when few attempts were served the same statement. The text of a screenshot depends on the OCR tool. A text that was edited breaks the alignment. A watermark cannot prevent a leak, and the result is evidence for a person, not a decision. The command and its audit are described in [Operating the leak trace](DEPLOY.md#leak-trace).
|
||||
|
||||
### Skill evidence
|
||||
|
||||
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see [Matching and explanations](#matching-and-explanations)); no percentile reads it yet.
|
||||
|
||||
@@ -445,6 +445,23 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
|
||||
- To use thresholds other than the demo values, publish a policy version with an `assessment.signals` section through the policy publisher. `DemoProductPolicyV3` is the demo example and is published only explicitly (the isolated browser fixture does so); the startup seed publishes version 1 only. Attempts that already started keep the version they started with. The demo duplicate thresholds assume a population: a copied pair is flagged only from about 26 answers per family (attention) and 61 (review) at 13 items, or 9 and 14 at 23 items. To try the feature on a smaller stand, publish a policy version with lower `duplicate_bits_attention` and `duplicate_bits_review` (the integration tests use 4 and 6); do not edit the demo policy. A review is a point-in-time evaluation, run again by the job at the deadline. The job logs one line per run with the number of reviews and its duration (`assessment review job finished`).
|
||||
- The rows hold counts, durations, and keyed digests (HMAC-SHA-256 under keys derived from `IDENTITY_KEY_SECRET`, each with a key version) and no answer text. Rotating the secret keeps the stored rows but makes new fingerprints incomparable with old ones. Deleting an account deletes its attempts and, by cascade, their facts and reviews; the audit rows keep only the attempt ID and the handle. The digests are kept for the lifetime of the attempt; no retention period is defined yet.
|
||||
|
||||
## Leak trace
|
||||
|
||||
An operator finds the attempt behind a leaked task text with a local command (see [ARCHITECTURE.md](ARCHITECTURE.md#leak-trace) for how it decides). It takes text; a screenshot has to be read by an OCR tool first, which is not part of this project:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --file leaked.txt'
|
||||
pbpaste | make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --stdin'
|
||||
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --code 7K3QD-9XM2T'
|
||||
```
|
||||
|
||||
- The command needs `DATABASE_URL` and `IDENTITY_KEY_SECRET`, and reads nothing else from the environment or a dotenv file. The secret must be the one of the server that served the attempts: the codes and marks are computed from it, so a different secret finds nothing, and the command refuses an unset, placeholder, or short secret and never prints it. `make -C backend assessment-leak-trace-build` builds `backend/bin/assessment-leak-trace`.
|
||||
- Put the text in a file or on standard input, not in a command-line argument, so that it stays out of the shell history and the process list. The text is at most 64 KiB of UTF-8; a longer one is refused, and a document can be searched in pieces. `--code` takes a visible code that was read from a screenshot by eye, with or without the hyphen and in either case.
|
||||
- It prints the search ID, `found`, `ambiguous`, or `not_found`, and for a found search the method (`invisible_mark`, `visible_code`, `wording`, or `variant`), the attempt ID, and the strength in bits, with notes that never quote the text. `not_found` is a normal outcome, not an error: the data was not enough to name an attempt.
|
||||
- Every search is recorded in `assessment_leak_traces` (operator handle, database time, a keyed digest and the length of the text, the outcome, the method, the attempt of a found search, and counts) before a result is printed, whatever it finds. The table refuses UPDATE, DELETE, and TRUNCATE, keeps no text, and outlives the attempt it names. The handle is an audit label, not authentication: any holder of the database credential can type any handle. Rolling migration 51 back is refused while the audit holds a row.
|
||||
- The result goes to the operator only. No HTTP operation serves it, an employer never sees it, and it changes no score, category, or quota. It is a hint for a manual review and an appeal, not a decision.
|
||||
- The command reads every real attempt to compute its code and searches the stored statements, so it is meant for an operator and not for a request path; its cost grows linearly with the number of attempts.
|
||||
|
||||
## Demonstration categories on a stand
|
||||
|
||||
A category from a `demo_basic` result is assigned only on an isolated synthetic stand. It is not calibrated and must not appear in an environment with real candidates. Two independent steps enable it on a stand:
|
||||
|
||||
@@ -558,6 +558,10 @@ Over HTTP with PostgreSQL. `TestAssessmentWorkSessionOverHTTP` creates a real at
|
||||
|
||||
Frontend. Vitest covers the key rules (`capture-keys.test.ts`), the heuristic and its watcher with fake windows and timers (`devtools-heuristic.test.ts`), the collector (one event for a press and its release, no cancelling, no event without an item), the session wiring of the watcher, the work session controller (held, busy, lost at a renewal, a network gap, a release during a renewal, the renewal bounds, `work-session.test.ts`), the page identifier header of the answer command, and the notice version 4 text. `e2e/assessment-capture.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen and Cmd+Shift+4 are recorded as `screenshot_key` events with no key or image, the key event is not cancelled and the test goes on to an answer; a faked docked panel is recorded as `devtools_open`; a second tab opened on the attempt is refused with the explanation and shows no task, nothing is started in it, the first tab is undisturbed, and after the first tab leaves the second continues; `pagehide` releases the session; a tab that loses the session at a renewal stops and says so. These tests do not show behavior in other browsers or on a phone, whether the operating system hands a shortcut to the page, what a real screenshot looks like, or how often the heuristic is wrong on real windows; the mock server stands for the rules of the real one, which the HTTP test covers.
|
||||
|
||||
## Assessment leak trace tests
|
||||
|
||||
`backend/internal/usecase/assessment/leak_trace_test.go` runs the tracer against in-memory repositories with real watermarks: the leaked text of a variant, among other words, finds the right one of three attempts that were served the same statement (by the invisible mark); with the invisible characters removed, the visible code of the tile text finds the attempt, and the wording alone separates the attempts that were served the same statement and chose different phrases; the visible code tolerates one misread character and not two; unrelated text, a text that is too short, and a mark of no attempt are not found and say why; a statement that only one attempt holds is found by the variant and excluded when its wording contradicts the text; attempts that chose the same phrases, or a text with no phrase group, are ambiguous without naming one; a mark attached to another text is found and flagged; a mark and a visible code that name different attempts are ambiguous; another variant of the same family does not compete with the leaked one, and the leak of a deleted attempt is not attributed to the variant of its family that is left; a leak cut inside the statement is found, while other words where the statement continues are not; every search is audited with a keyed digest and no part of the text, the same text gives the same digest, and a failed audit fails the search; bad requests are refused without quoting the text. `domain/assessment_watermark_test.go` covers the alignment and the wording agreement (only the phrases aligned with the stored statement are read, a fragment, unrelated text, another variant aligning for fewer characters), `domain/assessment_leak_trace_test.go` the audit record, `usecase/identity/keyring_test.go` the keyed text digest, `config/identity_test.go` the secret reader, and `adapter/primary/cli/leaktrace/command_test.go` the argument rules, the file and standard input reading with its limit, the output (the outcome and fixed notes, never the text, an honest not found), safe error messages, and that the environment is not read before the arguments are valid. `TestAssessmentLeakTraceOverHTTP` (PostgreSQL) creates two real attempts over HTTP and checks that the marked prompt finds the first by its mark, the prompt without invisible characters finds the second by its statement, the text of a screenshot with the tile finds the first by its visible code and the tile time, unrelated and short text are not found, a search changes no attempt version or state and no review or result, every search is audited without the text, the audit refuses UPDATE, DELETE, and TRUNCATE and a found row without an attempt, the audit outlives a deleted attempt (which is then not found), and the command with the secret of the server finds the attempt while one with another secret does not read the mark. They do not run an OCR tool, so what the command does with the real recognition errors of a screenshot, and how well the wording separates attempts on a real bank, are not measured here.
|
||||
|
||||
## Internal notification tests
|
||||
|
||||
Unit tests (`make -C backend test`, `make -C frontend test`):
|
||||
|
||||
@@ -725,6 +725,16 @@ contact_grant относится к паре кандидат-компания
|
||||
- Пределы правила. Это правило "одна страница за раз", а не граница безопасности: клиент, который никогда не занимает сеанс, получает отказ только пока его занимает другая страница, кандидат всегда может продолжить после освобождения или истечения, а два окна одного кандидата не отличаются от двух людей. Занятие продлевает таймер страницы, поэтому браузер, который замедляет фоновую вкладку до одного такта в минуту, все равно продлевает его в пределах двух минут.
|
||||
- Чтение оператором. `make -C backend assessment-review ARGS='inspect ...'` печатает новые счетчики `extra_agents`, `client_screenshot_keys` и `client_devtools_opens` рядом со старыми; примечание в конце вывода повторяет, что браузерные сигналы можно подделать и что снимок экрана или фото телефоном предотвратить нельзя и страница их не видит.
|
||||
|
||||
### Поиск источника утечки
|
||||
|
||||
Реализован как локальная операторская команда `assessment-leak-trace`, которая находит реальную попытку, из которой утек текст задания. Она читает текст и больше ничего: снимок или фото сначала должен прочитать инструмент распознавания текста, а само распознавание в проект не входит (команда принимает любой текст UTF-8 до 64 КиБ из файла или стандартного ввода и видимый код, который оператор прочитал глазами). Результат - подсказка для ручной проверки и апелляции. Его никогда не видит работодатель (ни одна HTTP-операция его не отдает), он не меняет балл, категорию и квоты (команда ничего не пишет, кроме собственного журнала) и никогда не называет попытку наугад. Код: `backend/cmd/assessment-leak-trace/`, `backend/internal/adapter/primary/cli/leaktrace/command.go`, `LeakTracer` в `backend/internal/usecase/assessment/leak_trace.go`, `AssessmentLeakAlignment` и `AssessmentTextPiecesBetweenPhrases` в `domain/assessment_wording.go`, `domain/assessment_leak_trace.go`, миграция `backend/db/migrations/00051_create_assessment_leak_traces.sql` и запросы `backend/db/queries/assessment_leak_traces.sql`.
|
||||
|
||||
- Способы, от сильного к слабому. (1) Невидимая метка: целые запуски символов нулевой ширины декодируются в код попытки (50 ключевых бит), поэтому одна попытка за одним кодом - находка сама по себе. (2) Видимый код: код плитки, найденный в тексте снимка как две группы по пять символов (или десять символов, за которыми идут дата и время плитки), либо переданный через `--code`; один символ, который распознавание прочитало неверно, допускается (45 бит), два - нет. Время на плитке сравнивается с временем жизни попытки (с запасом в час) и сообщается как примечание, но не как вердикт, потому что это часы устройства. (3) Условие и формулировки: в сохраненных условиях реальных попыток без метки ищутся куски текста, попытки, которым выдано это условие, отделяются от других вариантов того же семейства по тому, насколько далеко текст следует их условию, а среди них - по формам оборотов, которые показывает текст (около одного бита на группу оборотов; читаются только обороты, выровненные с сохраненным условием, поэтому слова вокруг условия в сообщении игнорируются). Условие учитывается, только если текст - его копия, целая или обрезанная там, где текст кончается: другие слова там, где условие продолжается, означают, что другой вариант того же семейства, у которого совпадает лишь неизменный текст, не является источником. Текст условия, выданный только одной попытке, называет эту попытку одним лишь вариантом, если в тексте нет групп оборотов, и исключает ее, если обороты текста противоречат попытке, потому что утечка могла прийти из удаленной попытки.
|
||||
- Код попытки вычисляется и нигде не хранится, поэтому таблицы поиска нет: команда обходит все реальные попытки (по 5000 на страницу), вычисляет их коды из `IDENTITY_KEY_SECRET` и сравнивает. Работа линейна по числу попыток и приемлема для команды оператора. Поэтому команде нужен секрет сервера, который выдавал попытки; после смены секрета старые коды и метки нечитаемы, и поиск остается возможным только по тексту условия.
|
||||
- Исходы. `found` называет одну попытку, способ и силу в битах с примечаниями, например совпадает ли текст условия с попыткой (метка, приклеенная к другому тексту, помечается). `ambiguous` означает, что доказательства оставляют в игре несколько попыток (две попытки за кодами, метка и видимый код, называющие разные попытки, или попытки, которым выдано одно условие и которые выбрали одинаковые обороты), и не называет ни одной. `not_found` - честный ответ, когда данных мало: нет метки, нет кода, нет куска минимум из 24 символов без взаимозаменяемых оборотов, нет условия, которое содержит текст, текст содержат больше 200 условий (общий) или формулировки противоречат каждой подходящей попытке.
|
||||
- Журнал. Каждый поиск пишет одну строку в `assessment_leak_traces` в той же транзакции, что и поиск, до вывода результата: обозначение оператора (`operator:<handle>`, не аутентификация), время базы данных, ключевой отпечаток нормализованного текста (HMAC-SHA-256 под ключом, выведенным из `IDENTITY_KEY_SECRET`, метка `lincodex/assessment/leak-text/v1`), его длину, исход, способ, попытку для найденного поиска и счетчики. Текст никогда не хранится и не печатается, таблица отклоняет UPDATE, DELETE и TRUNCATE, а попытка не является внешним ключом, поэтому журнал переживает удаление аккаунта. Откат миграции 51 отклоняется, пока в журнале есть строка.
|
||||
- Чего команда не умеет. Утечка без метки и плитки, пересказанная своими словами или сфотографированная так, что плитка не читается, оставляет только формулировки и вариант, которые называют одну попытку лишь тогда, когда одно условие выдано немногим попыткам. Текст снимка зависит от инструмента распознавания. Отредактированный текст ломает выравнивание. Водяной знак не может предотвратить утечку, а результат - доказательство для человека, а не решение. Команда и ее журнал описаны в [Работе с поиском источника утечки](DEPLOY.md#поиск-источника-утечки).
|
||||
|
||||
### Доказательства навыков
|
||||
|
||||
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию для организации читает поиск (см. [Подбор и объяснение](#подбор-и-объяснение)); перцентиль ее пока не читает.
|
||||
|
||||
@@ -447,6 +447,23 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
|
||||
- Чтобы использовать пороги, отличные от демо, опубликуйте версию политики с разделом `assessment.signals` через публикатор политик. `DemoProductPolicyV3` - демо-пример, он публикуется только явно (так делает изолированная браузерная фикстура); стартовый seed публикует только версию 1. Попытки, которые уже начались, сохраняют версию, с которой начались. Демо-пороги дубликатов рассчитаны на совокупность: скопированная пара помечается лишь примерно от 26 ответов на семейство («внимание») и 61 («проверить») при 13 заданиях или от 9 и 14 при 23. Чтобы попробовать функцию на меньшем стенде, опубликуйте версию политики с меньшими `duplicate_bits_attention` и `duplicate_bits_review` (интеграционные тесты используют 4 и 6); демо-политику не редактируйте. Проверка - оценка на момент, задание на дедлайне запускает ее снова. Задание пишет в журнал одну строку на запуск с числом проверок и длительностью (`assessment review job finished`).
|
||||
- Строки хранят числа, длительности и ключевые дайджесты (HMAC-SHA-256 под ключами, выведенными из `IDENTITY_KEY_SECRET`, у каждого есть версия ключа) и не хранят текст ответа. Смена секрета сохраняет строки, но делает новые отпечатки несравнимыми со старыми. Удаление аккаунта удаляет его попытки и каскадом их факты и проверки; строки аудита хранят только идентификатор попытки и имя. Дайджесты хранятся столько же, сколько попытка; срок хранения пока не определен.
|
||||
|
||||
## Поиск источника утечки
|
||||
|
||||
Оператор находит попытку, из которой утек текст задания, локальной командой (как она решает, см. в [ARCHITECTURE.md](ARCHITECTURE.md#поиск-источника-утечки)). Команда принимает текст; снимок экрана сначала должен прочитать инструмент распознавания текста, который в этот проект не входит:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --file leaked.txt'
|
||||
pbpaste | make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --stdin'
|
||||
make -C backend assessment-leak-trace ARGS='search --actor operator:<handle> --code 7K3QD-9XM2T'
|
||||
```
|
||||
|
||||
- Команде нужны `DATABASE_URL` и `IDENTITY_KEY_SECRET`, больше она ничего не читает из окружения и dotenv-файла. Секрет должен быть тем, которым пользовался сервер, выдавший попытки: коды и метки вычисляются из него, поэтому другой секрет ничего не найдет, а команда отклоняет незаданный, шаблонный или короткий секрет и никогда его не печатает. `make -C backend assessment-leak-trace-build` собирает `backend/bin/assessment-leak-trace`.
|
||||
- Текст передавайте файлом или через стандартный ввод, а не аргументом командной строки, чтобы он не попал в историю оболочки и список процессов. Текст - до 64 КиБ UTF-8; более длинный отклоняется, документ можно искать частями. `--code` принимает видимый код, прочитанный со снимка глазами, с дефисом или без и в любом регистре.
|
||||
- Команда печатает ID поиска, `found`, `ambiguous` или `not_found`, а для найденного поиска способ (`invisible_mark`, `visible_code`, `wording` или `variant`), ID попытки и силу в битах, с примечаниями, которые никогда не цитируют текст. `not_found` - обычный исход, а не ошибка: данных не хватило, чтобы назвать попытку.
|
||||
- Каждый поиск записывается в `assessment_leak_traces` (обозначение оператора, время базы данных, ключевой отпечаток и длина текста, исход, способ, попытка найденного поиска и счетчики) до вывода результата, что бы он ни нашел. Таблица отклоняет UPDATE, DELETE и TRUNCATE, не хранит текст и переживает попытку, которую называет. Обозначение - метка журнала, а не аутентификация: любой владелец доступа к базе может ввести любое обозначение. Откат миграции 51 отклоняется, пока в журнале есть строка.
|
||||
- Результат получает только оператор. Ни одна HTTP-операция его не отдает, работодатель его не видит, он не меняет балл, категорию и квоты. Это подсказка для ручной проверки и апелляции, а не решение.
|
||||
- Команда читает все реальные попытки, чтобы вычислить их коды, и ищет по сохраненным условиям, поэтому она предназначена для оператора, а не для пути запроса; ее стоимость растет линейно с числом попыток.
|
||||
|
||||
## Демонстрационные категории на стенде
|
||||
|
||||
Категория по результату `demo_basic` присваивается только на изолированном синтетическом стенде. Она не калибрована и не должна появляться в рабочей среде с реальными кандидатами. Чтобы включить ее на стенде, нужны два независимых шага:
|
||||
|
||||
@@ -558,6 +558,10 @@ Vitest работает в Node без DOM, поэтому ограничени
|
||||
|
||||
Фронтенд. Vitest покрывает правила клавиш (`capture-keys.test.ts`), эвристику и ее наблюдателя с поддельными окнами и таймерами (`devtools-heuristic.test.ts`), сборщик (одно событие на нажатие и отпускание, без отмены, без события без задания), подключение наблюдателя к сеансу, контроллер рабочего сеанса (занято, свободно, потеряно при продлении, обрыв сети, освобождение во время продления, границы продления, `work-session.test.ts`), заголовок идентификатора страницы в команде ответа и текст версии 4 уведомления. `e2e/assessment-capture.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen и Cmd+Shift+4 записываются как события `screenshot_key` без клавиши и изображения, событие клавиши не отменяется, и тест доходит до ответа; подставная пристыкованная панель записывается как `devtools_open`; вторая вкладка с той же попыткой получает отказ с объяснением и не показывает задание, в ней ничего не начинается, первая вкладка не нарушена, а после ухода первой вкладки вторая продолжает; `pagehide` освобождает сеанс; вкладка, потерявшая сеанс при продлении, останавливается и говорит об этом. Эти тесты не показывают поведение в других браузерах и на телефоне, отдает ли операционная система сочетание странице, как выглядит настоящий снимок и как часто эвристика ошибается на настоящих окнах; подставной сервер изображает правила настоящего, которые покрывает тест HTTP.
|
||||
|
||||
## Тесты поиска источника утечки
|
||||
|
||||
`backend/internal/usecase/assessment/leak_trace_test.go` запускает поиск на репозиториях в памяти с настоящими водяными знаками: утекший текст варианта среди других слов находит правильную из трех попыток, которым выдано одно условие (по невидимой метке); без невидимых символов видимый код из текста плитки находит попытку, а одни формулировки различают попытки, которым выдано одно условие и которые выбрали разные обороты; видимый код допускает один неверно прочитанный символ, но не два; посторонний текст, слишком короткий текст и метка несуществующей попытки не находятся и объясняют причину; условие, выданное одной попытке, находится по варианту и исключается, если ее формулировки противоречат тексту; попытки с одинаковыми оборотами или текст без групп оборотов дают ambiguous без названия попытки; метка, приклеенная к другому тексту, находится с пометкой; метка и видимый код, называющие разные попытки, дают ambiguous; другой вариант того же семейства не конкурирует с утекшим, а утечка удаленной попытки не приписывается оставшемуся варианту ее семейства; утечка, оборванная внутри условия, находится, а другие слова там, где условие продолжается, - нет; каждый поиск попадает в журнал с ключевым отпечатком и без какой-либо части текста, один и тот же текст дает один отпечаток, а неудача записи в журнал проваливает поиск; неверные запросы отклоняются без цитирования текста. `domain/assessment_watermark_test.go` покрывает выравнивание и согласование формулировок (читаются только обороты, выровненные с сохраненным условием, фрагмент, посторонний текст, другой вариант, выравнивающийся на меньшее число символов), `domain/assessment_leak_trace_test.go` - запись журнала, `usecase/identity/keyring_test.go` - ключевой отпечаток текста, `config/identity_test.go` - чтение секрета, а `adapter/primary/cli/leaktrace/command_test.go` - правила аргументов, чтение из файла и стандартного ввода с ограничением, вывод (исход и фиксированные примечания, никогда не текст, честный not found), безопасные сообщения об ошибках и то, что окружение не читается, пока аргументы неверны. `TestAssessmentLeakTraceOverHTTP` (PostgreSQL) создает по HTTP две реальные попытки и проверяет, что текст задания с меткой находит первую по метке, текст без невидимых символов находит вторую по условию, текст снимка с плиткой находит первую по видимому коду и времени плитки, посторонний и короткий текст не находятся, поиск не меняет ни версию и состояние попыток, ни проверки и результаты, каждый поиск попадает в журнал без текста, журнал отклоняет UPDATE, DELETE, TRUNCATE и найденную строку без попытки, журнал переживает удаленную попытку (которая после этого не находится), а команда с секретом сервера находит попытку, тогда как с другим секретом метку не читает. Они не запускают инструмент распознавания, поэтому здесь не измерено, как команда справляется с настоящими ошибками распознаванияLine truncated
|
||||
|
||||
## Тесты внутренних уведомлений
|
||||
|
||||
Модульные тесты (`make -C backend test`, `make -C frontend test`):
|
||||
|
||||
Reference in new issue
Block a user