feat(assessment): find the attempt behind a leaked task text

This commit is contained in:
shira committed 2026-10-11 13:19:38 +03:00
1 parent bb917bf62e
commit 5a731c25b7
26 files changed
+2500

No files matched your search

@@ -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 {