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