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")
}
}