feat(assessment): find the attempt behind a leaked task text
This commit is contained in:
1 parent
bb917bf62e
commit
5a731c25b7
26 files changed
+2500
No files matched your search
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user