183 lines
6.8 KiB
Go
183 lines
6.8 KiB
Go
// 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")
|
|
}
|
|
}
|