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,182 @@
|
||||
// Package leaktrace implements the local operator command that finds the
|
||||
// assessment attempt behind a leaked task text. It takes text: a screenshot has
|
||||
// to be read by an OCR tool first, which is outside this command. Every search
|
||||
// is recorded in an audit table before a result is printed. The result is a hint
|
||||
// for a manual review and an appeal: it is never shown to an employer and never
|
||||
// changes a score, a category, or a quota.
|
||||
package leaktrace
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const usage = "usage: assessment-leak-trace search --actor operator:<handle> (--file <path> | --stdin) [--code XXXXX-XXXXX]"
|
||||
|
||||
// maxInputBytes is the largest text the command reads. It is one byte above the
|
||||
// limit of the usecase, so an oversize text is refused instead of cut.
|
||||
const maxInputBytes = 64<<10 + 1
|
||||
|
||||
// Command is a parsed, validated search.
|
||||
type Command struct {
|
||||
Actor string
|
||||
// File is the path of the leaked text; empty when the text comes from stdin.
|
||||
File string
|
||||
Stdin bool
|
||||
// Code is a visible code that the operator read from a screenshot by eye.
|
||||
Code string
|
||||
}
|
||||
|
||||
// Tracer finds the attempt behind a text and records the search.
|
||||
type Tracer interface {
|
||||
Trace(ctx context.Context, command assessment.LeakTraceCommand) (assessment.LeakTraceResult, error)
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects to
|
||||
// PostgreSQL.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 || args[0] != "search" {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("assessment-leak-trace search", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
actor := flags.String("actor", "", "operator handle")
|
||||
file := flags.String("file", "", "file with the leaked text")
|
||||
stdin := flags.Bool("stdin", false, "read the leaked text from standard input")
|
||||
code := flags.String("code", "", "visible code read from a screenshot")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
if _, err := domain.ParseAssessmentReviewActor(strings.TrimSpace(*actor)); err != nil {
|
||||
return Command{}, errors.New("actor must be operator:<handle>")
|
||||
}
|
||||
if *file != "" && *stdin {
|
||||
return Command{}, errors.New("give the text with --file or --stdin, not both")
|
||||
}
|
||||
if *file == "" && !*stdin && strings.TrimSpace(*code) == "" {
|
||||
return Command{}, errors.New("give the leaked text with --file or --stdin, or a visible code with --code")
|
||||
}
|
||||
if strings.TrimSpace(*code) != "" {
|
||||
if _, err := domain.ParseAssessmentWatermarkCode(*code); err != nil {
|
||||
return Command{}, errors.New("code must be a watermark code of two groups of five characters, such as 7K3QD-9XM2T")
|
||||
}
|
||||
}
|
||||
return Command{Actor: strings.TrimSpace(*actor), File: *file, Stdin: *stdin, Code: strings.TrimSpace(*code)}, nil
|
||||
}
|
||||
|
||||
// Run parses the command, loads only DATABASE_URL and IDENTITY_KEY_SECRET from
|
||||
// the supplied environment, and executes the search. It does not load dotenv
|
||||
// files.
|
||||
func Run(ctx context.Context, args []string, lookup config.LookupEnv, stdin io.Reader, output io.Writer) error {
|
||||
command, err := Parse(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lookup == nil || stdin == nil || output == nil {
|
||||
return errors.New("leak trace command dependencies are required")
|
||||
}
|
||||
text, err := readText(command, stdin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
databaseURL := config.DatabaseURLFromEnv(lookup)
|
||||
if databaseURL == "" {
|
||||
return errors.New("DATABASE_URL is not set")
|
||||
}
|
||||
secret, err := config.IdentityKeySecretFromEnv(lookup)
|
||||
if err != nil {
|
||||
return errors.New("IDENTITY_KEY_SECRET must be the secret of the server that served the attempts")
|
||||
}
|
||||
keyring, err := identity.NewKeyring(secret)
|
||||
if err != nil {
|
||||
return errors.New("IDENTITY_KEY_SECRET is invalid")
|
||||
}
|
||||
pool, err := postgres.NewPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return errors.New("database configuration is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("database is unavailable")
|
||||
}
|
||||
tracer, err := assessment.NewLeakTracer(postgres.NewTransactor(pool), keyring, keyring)
|
||||
if err != nil {
|
||||
return errors.New("leak trace is unavailable")
|
||||
}
|
||||
return Execute(ctx, command, text, tracer, output)
|
||||
}
|
||||
|
||||
func readText(command Command, stdin io.Reader) (string, error) {
|
||||
var reader io.Reader
|
||||
switch {
|
||||
case command.File != "":
|
||||
file, err := os.Open(command.File)
|
||||
if err != nil {
|
||||
return "", errors.New("the text file cannot be opened")
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
reader = file
|
||||
case command.Stdin:
|
||||
reader = stdin
|
||||
default:
|
||||
return "", nil
|
||||
}
|
||||
text, err := io.ReadAll(io.LimitReader(reader, maxInputBytes))
|
||||
if err != nil {
|
||||
return "", errors.New("the text cannot be read")
|
||||
}
|
||||
return string(text), nil
|
||||
}
|
||||
|
||||
// Execute runs the search and prints the outcome. The output names the outcome,
|
||||
// the method, the attempt, the strength of the evidence, and fixed notes about
|
||||
// it. It never prints the leaked text and no data of the candidate.
|
||||
func Execute(ctx context.Context, command Command, text string, tracer Tracer, output io.Writer) error {
|
||||
if tracer == nil || output == nil {
|
||||
return errors.New("leak trace command dependencies are required")
|
||||
}
|
||||
result, err := tracer.Trace(ctx, assessment.LeakTraceCommand{Actor: command.Actor, Text: text, Code: command.Code})
|
||||
if err != nil {
|
||||
return safeOperationError(err)
|
||||
}
|
||||
var builder strings.Builder
|
||||
fmt.Fprintf(&builder, "search: %s\nresult: %s\n", result.SearchID, result.Status)
|
||||
if result.Status == domain.AssessmentLeakTraceFound {
|
||||
fmt.Fprintf(&builder, "method: %s\nattempt: %s\nevidence_bits: %d\n", result.Method, result.AttemptID, result.EvidenceBits)
|
||||
}
|
||||
fmt.Fprintf(&builder, "candidates: %d\n", result.Candidates)
|
||||
for _, note := range result.Notes {
|
||||
fmt.Fprintf(&builder, "note: %s\n", note)
|
||||
}
|
||||
builder.WriteString("note: a hint for a manual review and an appeal; it changes no score, category, or quota, " +
|
||||
"and an employer never sees it. The search is recorded in the audit.\n")
|
||||
if result.Status == domain.AssessmentLeakTraceNotFound {
|
||||
builder.WriteString("note: not found is an honest answer: the data is not enough to name an attempt.\n")
|
||||
}
|
||||
if _, err := io.WriteString(output, builder.String()); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeOperationError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, assessment.ErrInvalidLeakTrace):
|
||||
return errors.New("the text or the code cannot be searched (empty, not valid UTF-8, or longer than 64 KiB)")
|
||||
case errors.Is(err, domain.ErrInvalidAssessmentReview):
|
||||
return errors.New("actor is invalid")
|
||||
default:
|
||||
return errors.New("assessment leak trace operation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package leaktrace
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type tracerFake struct {
|
||||
result assessment.LeakTraceResult
|
||||
err error
|
||||
command assessment.LeakTraceCommand
|
||||
calls int
|
||||
}
|
||||
|
||||
func (tracer *tracerFake) Trace(_ context.Context, command assessment.LeakTraceCommand) (assessment.LeakTraceResult, error) {
|
||||
tracer.calls++
|
||||
tracer.command = command
|
||||
return tracer.result, tracer.err
|
||||
}
|
||||
|
||||
func TestParseTakesTheTextFromAFileOrStandardInputAndAnOperatorHandle(t *testing.T) {
|
||||
command, err := Parse([]string{"search", "--actor", "operator:night", "--file", "leak.txt"})
|
||||
if err != nil || command.File != "leak.txt" || command.Actor != "operator:night" || command.Stdin {
|
||||
t.Fatalf("Parse(file) = %+v, %v", command, err)
|
||||
}
|
||||
command, err = Parse([]string{"search", "--actor", "operator:night", "--stdin", "--code", "7k3qd 9xm2t"})
|
||||
if err != nil || !command.Stdin || command.Code != "7k3qd 9xm2t" {
|
||||
t.Fatalf("Parse(stdin and code) = %+v, %v", command, err)
|
||||
}
|
||||
// A code read from a screenshot by eye is enough on its own.
|
||||
if _, err := Parse([]string{"search", "--actor", "operator:night", "--code", "7K3QD-9XM2T"}); err != nil {
|
||||
t.Fatalf("Parse(code only) error = %v", err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil,
|
||||
{"find"},
|
||||
{"search"},
|
||||
{"search", "--file", "leak.txt"},
|
||||
{"search", "--actor", "alice", "--file", "leak.txt"},
|
||||
{"search", "--actor", "operator:night"},
|
||||
{"search", "--actor", "operator:night", "--file", "leak.txt", "--stdin"},
|
||||
{"search", "--actor", "operator:night", "--code", "NOT A CODE"},
|
||||
{"search", "--actor", "operator:night", "--file", "leak.txt", "extra"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunValidatesArgumentsBeforeReadingTheEnvironmentAndNeverEchoesTheSecret(t *testing.T) {
|
||||
lookup := func(string) (string, bool) {
|
||||
t.Fatal("environment read before arguments were validated")
|
||||
return "", false
|
||||
}
|
||||
if err := Run(context.Background(), []string{"search"}, lookup, strings.NewReader(""), &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("Run(invalid arguments) succeeded")
|
||||
}
|
||||
args := []string{"search", "--actor", "operator:night", "--stdin"}
|
||||
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
|
||||
if err := Run(context.Background(), args, noDatabase, strings.NewReader("leaked text"), &bytes.Buffer{}); err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
|
||||
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
|
||||
}
|
||||
// A secret that the server could not have used makes every code unreadable, so the command refuses it.
|
||||
const shortSecret = "too-short-secret"
|
||||
var weakSecret config.LookupEnv = func(key string) (string, bool) {
|
||||
switch key {
|
||||
case "DATABASE_URL":
|
||||
return "postgres://operator@localhost/lincodex", true
|
||||
case "IDENTITY_KEY_SECRET":
|
||||
return shortSecret, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
err := Run(context.Background(), args, weakSecret, strings.NewReader("leaked text"), &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET") || strings.Contains(err.Error(), shortSecret) {
|
||||
t.Fatalf("Run(weak secret) error = %v, want a message that does not echo the secret", err)
|
||||
}
|
||||
var noSecret config.LookupEnv = func(key string) (string, bool) {
|
||||
if key == "DATABASE_URL" {
|
||||
return "postgres://operator@localhost/lincodex", true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
if err := Run(context.Background(), args, noSecret, strings.NewReader("leaked text"), &bytes.Buffer{}); err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET") {
|
||||
t.Fatalf("Run(no secret) error = %v, want an IDENTITY_KEY_SECRET message", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheTextIsReadFromAFileOrStandardInputWithinTheLimit(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "leak.txt")
|
||||
if err := os.WriteFile(path, []byte("text from a file"), 0o600); err != nil {
|
||||
t.Fatalf("write fixture: %v", err)
|
||||
}
|
||||
fromFile, err := readText(Command{File: path}, strings.NewReader("ignored"))
|
||||
if err != nil || fromFile != "text from a file" {
|
||||
t.Fatalf("readText(file) = %q, %v", fromFile, err)
|
||||
}
|
||||
fromStdin, err := readText(Command{Stdin: true}, strings.NewReader("text from stdin"))
|
||||
if err != nil || fromStdin != "text from stdin" {
|
||||
t.Fatalf("readText(stdin) = %q, %v", fromStdin, err)
|
||||
}
|
||||
// One byte above the limit of the usecase is read, so an oversize text is refused and not cut.
|
||||
oversize, err := readText(Command{Stdin: true}, strings.NewReader(strings.Repeat("a", 1<<20)))
|
||||
if err != nil || len(oversize) != maxInputBytes {
|
||||
t.Fatalf("readText(oversize) read %d bytes, %v, want %d", len(oversize), err, maxInputBytes)
|
||||
}
|
||||
if _, err := readText(Command{File: filepath.Join(t.TempDir(), "missing.txt")}, strings.NewReader("")); err == nil {
|
||||
t.Fatal("readText(missing file) succeeded")
|
||||
}
|
||||
if text, err := readText(Command{Code: "7K3QD-9XM2T"}, strings.NewReader("ignored")); err != nil || text != "" {
|
||||
t.Fatalf("readText(code only) = %q, %v, want no text", text, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePrintsTheOutcomeAndNeverTheLeakedText(t *testing.T) {
|
||||
const leaked = "SECRET-LEAKED-STATEMENT about a sliding-window limiter"
|
||||
attemptID := domain.AssessmentAttemptID(uuid.New())
|
||||
found := &tracerFake{result: assessment.LeakTraceResult{
|
||||
SearchID: uuid.New(), Status: domain.AssessmentLeakTraceFound, Method: domain.AssessmentLeakTraceInvisibleMark,
|
||||
AttemptID: attemptID, Candidates: 1, EvidenceBits: 50, Notes: []string{"the invisible mark of the statement carries one code"},
|
||||
}}
|
||||
var output bytes.Buffer
|
||||
if err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, found, &output); err != nil {
|
||||
t.Fatalf("Execute(found) error = %v", err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"result: found", "method: invisible_mark", "attempt: " + attemptID.String(), "evidence_bits: 50", "candidates: 1",
|
||||
"note: the invisible mark of the statement carries one code", "an employer never sees it", "changes no score, category, or quota",
|
||||
} {
|
||||
if !strings.Contains(output.String(), want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, output.String())
|
||||
}
|
||||
}
|
||||
if strings.Contains(output.String(), "SECRET-LEAKED") || strings.Contains(output.String(), "sliding-window") {
|
||||
t.Fatalf("the output quotes the leaked text:\n%s", output.String())
|
||||
}
|
||||
if found.command.Actor != "operator:night" || found.command.Text != leaked {
|
||||
t.Fatalf("command = %+v, want the actor and the text passed on", found.command)
|
||||
}
|
||||
|
||||
notFound := &tracerFake{result: assessment.LeakTraceResult{
|
||||
SearchID: uuid.New(), Status: domain.AssessmentLeakTraceNotFound, Notes: []string{"no statement of any real attempt contains this text"},
|
||||
}}
|
||||
output.Reset()
|
||||
if err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, notFound, &output); err != nil {
|
||||
t.Fatalf("Execute(not found) error = %v", err)
|
||||
}
|
||||
if !strings.Contains(output.String(), "result: not_found") || !strings.Contains(output.String(), "not found is an honest answer") ||
|
||||
strings.Contains(output.String(), "attempt:") || strings.Contains(output.String(), "method:") {
|
||||
t.Fatalf("not found output:\n%s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
|
||||
const leaked = "SECRET-LEAKED-STATEMENT"
|
||||
for name, test := range map[string]struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
"a request the usecase refuses": {err: assessment.ErrInvalidLeakTrace, want: "cannot be searched"},
|
||||
"an invalid actor": {err: domain.ErrInvalidAssessmentReview, want: "actor is invalid"},
|
||||
"a storage failure": {err: errors.New("pq: connection refused for " + leaked), want: "operation failed"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, &tracerFake{err: test.err}, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), leaked) {
|
||||
t.Fatalf("Execute() error = %v, want a safe message containing %q", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
if err := Execute(context.Background(), Command{}, "", nil, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("Execute() without a tracer succeeded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.AssessmentLeakTraceRepository = assessmentLeakTraceRepository{}
|
||||
|
||||
func (unit *UnitOfWork) AssessmentLeakTraces() outbound.AssessmentLeakTraceRepository {
|
||||
return assessmentLeakTraceRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type assessmentLeakTraceRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository assessmentLeakTraceRepository) ListRealAttempts(
|
||||
ctx context.Context,
|
||||
after domain.AssessmentAttemptID,
|
||||
limit int32,
|
||||
) ([]outbound.AssessmentTraceAttempt, error) {
|
||||
const location = "assessmentLeakTraceRepository.ListRealAttempts"
|
||||
if limit < 1 {
|
||||
return nil, fmt.Errorf("%s - a positive limit is required: %w", location, domain.ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
rows, err := repository.queries.ListAssessmentTraceAttempts(ctx, sqlc.ListAssessmentTraceAttemptsParams{
|
||||
AfterID: pgUUID(after.UUID()), RowLimit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - list attempts: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
attempts := make([]outbound.AssessmentTraceAttempt, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !row.ID.Valid || !row.CreatedAt.Valid || !row.ExpiresAt.Valid {
|
||||
return nil, fmt.Errorf("%s - stored attempt is incomplete: %w", location, domain.ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
attempts = append(attempts, outbound.AssessmentTraceAttempt{
|
||||
ID: domain.AssessmentAttemptID(row.ID.Bytes), CreatedAt: row.CreatedAt.Time.UTC(), ExpiresAt: row.ExpiresAt.Time.UTC(),
|
||||
})
|
||||
}
|
||||
return attempts, nil
|
||||
}
|
||||
|
||||
func (repository assessmentLeakTraceRepository) FindStatementsContaining(
|
||||
ctx context.Context,
|
||||
fragment string,
|
||||
limit int32,
|
||||
) ([]outbound.AssessmentTraceStatement, error) {
|
||||
const location = "assessmentLeakTraceRepository.FindStatementsContaining"
|
||||
if fragment == "" || limit < 1 {
|
||||
return nil, fmt.Errorf("%s - a fragment and a positive limit are required: %w", location, domain.ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
rows, err := repository.queries.FindAssessmentTraceStatements(ctx, sqlc.FindAssessmentTraceStatementsParams{
|
||||
Fragment: fragment, RowLimit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - find statements: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
statements := make([]outbound.AssessmentTraceStatement, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !row.AttemptID.Valid {
|
||||
return nil, fmt.Errorf("%s - stored statement has no attempt: %w", location, domain.ErrInvalidAssessmentLeakTrace)
|
||||
}
|
||||
statements = append(statements, outbound.AssessmentTraceStatement{
|
||||
AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes), Statement: row.Statement,
|
||||
})
|
||||
}
|
||||
return statements, nil
|
||||
}
|
||||
|
||||
func (repository assessmentLeakTraceRepository) RecordSearch(ctx context.Context, record domain.AssessmentLeakTraceRecord) error {
|
||||
const location = "assessmentLeakTraceRepository.RecordSearch"
|
||||
if err := record.Validate(); err != nil {
|
||||
return fmt.Errorf("%s - record is invalid: %w", location, err)
|
||||
}
|
||||
method := pgtype.Text{}
|
||||
if record.Method != "" {
|
||||
method = pgtype.Text{String: string(record.Method), Valid: true}
|
||||
}
|
||||
attempt := pgtype.UUID{}
|
||||
if !record.AttemptID.IsZero() {
|
||||
attempt = pgUUID(record.AttemptID.UUID())
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentLeakTrace(ctx, sqlc.InsertAssessmentLeakTraceParams{
|
||||
ID: pgUUID(record.ID), Actor: string(record.Actor), SearchedAt: pgTime(record.SearchedAt),
|
||||
TextDigest: record.TextDigest[:], KeyVersion: record.KeyVersion, TextRunes: record.TextRunes,
|
||||
Status: string(record.Status), Method: method, AttemptID: attempt,
|
||||
Candidates: record.Candidates, EvidenceBits: record.EvidenceBits,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert audit record: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_leak_traces.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const findAssessmentTraceStatements = `-- name: FindAssessmentTraceStatements :many
|
||||
SELECT
|
||||
item.attempt_id,
|
||||
(item.variant ->> 'Statement')::text AS statement
|
||||
FROM assessment_attempt_items AS item
|
||||
INNER JOIN assessment_attempts AS attempt ON item.attempt_id = attempt.id
|
||||
WHERE
|
||||
attempt.kind IN ('root', 'corrective')
|
||||
AND position($1::text IN regexp_replace((item.variant ->> 'Statement')::text, '\s+', ' ', 'g')) > 0
|
||||
ORDER BY item.attempt_id, item.ordinal
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type FindAssessmentTraceStatementsParams struct {
|
||||
Fragment string
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type FindAssessmentTraceStatementsRow struct {
|
||||
AttemptID pgtype.UUID
|
||||
Statement string
|
||||
}
|
||||
|
||||
// The unmarked statements of real attempts whose text, with runs of white space
|
||||
// collapsed, contains the fragment. The fragment is matched literally: position
|
||||
// is not a pattern. The scan reads the stored variant of every item, which is
|
||||
// fine for an operator command and not for a request path.
|
||||
func (q *Queries) FindAssessmentTraceStatements(ctx context.Context, arg FindAssessmentTraceStatementsParams) ([]FindAssessmentTraceStatementsRow, error) {
|
||||
rows, err := q.db.Query(ctx, findAssessmentTraceStatements, arg.Fragment, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []FindAssessmentTraceStatementsRow
|
||||
for rows.Next() {
|
||||
var i FindAssessmentTraceStatementsRow
|
||||
if err := rows.Scan(&i.AttemptID, &i.Statement); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const insertAssessmentLeakTrace = `-- name: InsertAssessmentLeakTrace :exec
|
||||
INSERT INTO assessment_leak_traces (
|
||||
id,
|
||||
actor,
|
||||
searched_at,
|
||||
text_digest,
|
||||
key_version,
|
||||
text_runes,
|
||||
status,
|
||||
method,
|
||||
attempt_id,
|
||||
candidates,
|
||||
evidence_bits
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8,
|
||||
$9,
|
||||
$10,
|
||||
$11
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentLeakTraceParams struct {
|
||||
ID pgtype.UUID
|
||||
Actor string
|
||||
SearchedAt pgtype.Timestamptz
|
||||
TextDigest []byte
|
||||
KeyVersion int16
|
||||
TextRunes int32
|
||||
Status string
|
||||
Method pgtype.Text
|
||||
AttemptID pgtype.UUID
|
||||
Candidates int32
|
||||
EvidenceBits int32
|
||||
}
|
||||
|
||||
func (q *Queries) InsertAssessmentLeakTrace(ctx context.Context, arg InsertAssessmentLeakTraceParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentLeakTrace,
|
||||
arg.ID,
|
||||
arg.Actor,
|
||||
arg.SearchedAt,
|
||||
arg.TextDigest,
|
||||
arg.KeyVersion,
|
||||
arg.TextRunes,
|
||||
arg.Status,
|
||||
arg.Method,
|
||||
arg.AttemptID,
|
||||
arg.Candidates,
|
||||
arg.EvidenceBits,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listAssessmentTraceAttempts = `-- name: ListAssessmentTraceAttempts :many
|
||||
SELECT id, created_at, expires_at
|
||||
FROM assessment_attempts
|
||||
WHERE kind IN ('root', 'corrective') AND id > $1
|
||||
ORDER BY id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListAssessmentTraceAttemptsParams struct {
|
||||
AfterID pgtype.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListAssessmentTraceAttemptsRow struct {
|
||||
ID pgtype.UUID
|
||||
CreatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Real attempts in ascending identifier order, so that a caller can walk all of
|
||||
// them in pages. Only the identifier and the time span are read.
|
||||
func (q *Queries) ListAssessmentTraceAttempts(ctx context.Context, arg ListAssessmentTraceAttemptsParams) ([]ListAssessmentTraceAttemptsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listAssessmentTraceAttempts, arg.AfterID, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListAssessmentTraceAttemptsRow
|
||||
for rows.Next() {
|
||||
var i ListAssessmentTraceAttemptsRow
|
||||
if err := rows.Scan(&i.ID, &i.CreatedAt, &i.ExpiresAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -215,6 +215,20 @@ type AssessmentFamily struct {
|
||||
RetiredBy pgtype.Text
|
||||
}
|
||||
|
||||
type AssessmentLeakTrace struct {
|
||||
ID pgtype.UUID
|
||||
Actor string
|
||||
SearchedAt pgtype.Timestamptz
|
||||
TextDigest []byte
|
||||
KeyVersion int16
|
||||
TextRunes int32
|
||||
Status string
|
||||
Method pgtype.Text
|
||||
AttemptID pgtype.UUID
|
||||
Candidates int32
|
||||
EvidenceBits int32
|
||||
}
|
||||
|
||||
type AssessmentReviewRead struct {
|
||||
ID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
|
||||
@@ -277,6 +277,11 @@ type Querier interface {
|
||||
// NULL retry_at. due_at keeps the deadline. The same guard as the
|
||||
// completion applies.
|
||||
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
|
||||
// The unmarked statements of real attempts whose text, with runs of white space
|
||||
// collapsed, contains the fragment. The fragment is matched literally: position
|
||||
// is not a pattern. The scan reads the stored variant of every item, which is
|
||||
// fine for an operator command and not for a request path.
|
||||
FindAssessmentTraceStatements(ctx context.Context, arg FindAssessmentTraceStatementsParams) ([]FindAssessmentTraceStatementsRow, error)
|
||||
FindCompanyCardViewQuotaUsage(ctx context.Context, arg FindCompanyCardViewQuotaUsageParams) (pgtype.Timestamptz, error)
|
||||
FindCompanyInvitationQuotaUsage(ctx context.Context, arg FindCompanyInvitationQuotaUsageParams) (pgtype.UUID, error)
|
||||
// Returns the newest open reservation of a delivery under a provider account
|
||||
@@ -480,6 +485,7 @@ type Querier interface {
|
||||
// returns no row instead of an error, so a conflict does not abort the
|
||||
// surrounding transaction.
|
||||
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
|
||||
InsertAssessmentLeakTrace(ctx context.Context, arg InsertAssessmentLeakTraceParams) error
|
||||
InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error
|
||||
InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error
|
||||
// The attempt row is already locked by the caller. Store a parent before its
|
||||
@@ -677,6 +683,9 @@ type Querier interface {
|
||||
// Marks exist only where the session or the network changed. The bound keeps a
|
||||
// request that flaps between networks from growing the list without limit.
|
||||
ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error)
|
||||
// Real attempts in ascending identifier order, so that a caller can walk all of
|
||||
// them in pages. Only the identifier and the time span are read.
|
||||
ListAssessmentTraceAttempts(ctx context.Context, arg ListAssessmentTraceAttemptsParams) ([]ListAssessmentTraceAttemptsRow, error)
|
||||
// Reads the exact family membership pinned by a training binding.
|
||||
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
|
||||
ListCandidateAssessmentCategories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateAssessmentCategory, error)
|
||||
|
||||
Reference in new issue
Block a user