Files
lincodex/backend/integration_test/assessment_leak_trace_http_test.go

216 lines
11 KiB
Go

//go:build integration
package integration_test
import (
"bytes"
"context"
"fmt"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/cli/leaktrace"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/assessment"
)
// TestAssessmentLeakTraceOverHTTP checks, with PostgreSQL, that the operator
// search finds the real attempt behind the text that the page presented: by the
// invisible mark, then by the statement and its wording once the mark is gone,
// then by the visible code of a screenshot's text. It checks that unrelated text
// is not found, that every search is audited without the text and the audit is
// immutable and outlives the attempt, that a search changes no attempt, review,
// or result, and that the command wiring reads the same secret as the server.
func TestAssessmentLeakTraceOverHTTP(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
defer cancel()
env := bootstrap(t, postgresService, redisService)
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
t.Cleanup(harness.pool.Close)
signals := reviewTestSignalPolicy()
seedAssessmentAttemptHTTPBankWithSignals(ctx, t, harness.pool, &signals)
first := newReviewCandidate(ctx, t, harness, "leak-first@example.test", "192.0.2", 1)
second := newReviewCandidate(ctx, t, harness, "leak-second@example.test", "192.0.3", 1)
firstAttempt := leakTraceCreate(t, harness, first, "leak-first-create", "192.0.2.30:1234")
secondAttempt := leakTraceCreate(t, harness, second, "leak-second-create", "192.0.3.30:1234")
if firstAttempt.code == secondAttempt.code || firstAttempt.prompt == secondAttempt.prompt {
t.Fatal("two attempts were presented the same code or the same marked prompt")
}
tracer, err := assessment.NewLeakTracer(postgresadapter.NewTransactor(harness.pool), harness.keyring, harness.keyring)
if err != nil {
t.Fatalf("NewLeakTracer() error = %v", err)
}
trace := func(text, code string) assessment.LeakTraceResult {
t.Helper()
result, err := tracer.Trace(ctx, assessment.LeakTraceCommand{Actor: "operator:integration", Text: text, Code: code})
if err != nil {
t.Fatalf("Trace() error = %v", err)
}
return result
}
before := leakTraceFacts(t, ctx, harness)
// The text as presented, inside a message: the invisible mark names the attempt.
marked := trace("Look what I got at the test: "+firstAttempt.prompt+" any ideas?", "")
if marked.Status != domain.AssessmentLeakTraceFound || marked.Method != domain.AssessmentLeakTraceInvisibleMark ||
marked.AttemptID != domain.AssessmentAttemptID(firstAttempt.id) || marked.EvidenceBits != 50 {
t.Fatalf("marked text result = %+v, want the first attempt by its invisible mark", marked)
}
// The invisible characters stripped (a chat tool, retyping): the statement and
// its wording still point at the attempt that was served it, and not at the other.
stripped := trace(domain.VisibleAssessmentText(secondAttempt.prompt), "")
if stripped.Status != domain.AssessmentLeakTraceFound || stripped.AttemptID != domain.AssessmentAttemptID(secondAttempt.id) ||
(stripped.Method != domain.AssessmentLeakTraceWording && stripped.Method != domain.AssessmentLeakTraceVariant) {
t.Fatalf("stripped text result = %+v, want the second attempt by its statement", stripped)
}
// The text of a screenshot: the statement without the mark and the tile with the code and the time.
tile := fmt.Sprintf("%s\n%s %s", domain.VisibleAssessmentText(firstAttempt.prompt), firstAttempt.code, time.Now().UTC().Format("2006-01-02 15:04")+"Z")
screenshot := trace(tile, "")
if screenshot.Status != domain.AssessmentLeakTraceFound || screenshot.Method != domain.AssessmentLeakTraceVisibleCode ||
screenshot.AttemptID != domain.AssessmentAttemptID(firstAttempt.id) {
t.Fatalf("screenshot text result = %+v, want the first attempt by its visible code", screenshot)
}
if !strings.Contains(strings.Join(screenshot.Notes, " "), "falls within the life of the attempt") {
t.Fatalf("screenshot notes = %v, want the tile time within the attempt", screenshot.Notes)
}
// Insufficient data is reported as not found.
unrelated := trace("The committee will meet on Thursday to discuss the budget for the coming year and the new office.", "")
if unrelated.Status != domain.AssessmentLeakTraceNotFound || !unrelated.AttemptID.IsZero() {
t.Fatalf("unrelated text result = %+v, want not found", unrelated)
}
short := trace("How many requests?", "")
if short.Status != domain.AssessmentLeakTraceNotFound {
t.Fatalf("short text result = %+v, want not found", short)
}
// A search changes no attempt, review, or result.
if after := leakTraceFacts(t, ctx, harness); after != before {
t.Fatalf("a search changed the attempts: %q before, %q after", before, after)
}
// Every search was audited, without the text.
var rows int64
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_leak_traces`).Scan(&rows); err != nil || rows != 5 {
t.Fatalf("audit rows = %d, error %v, want one per search", rows, err)
}
var dump string
if err := harness.pool.QueryRow(ctx, `SELECT string_agg(t::text, ' ') FROM assessment_leak_traces AS t`).Scan(&dump); err != nil {
t.Fatalf("dump the audit: %v", err)
}
for _, leaked := range []string{"gateway", "limiter", "committee", "Thursday", firstAttempt.code} {
if strings.Contains(strings.ToLower(dump), strings.ToLower(leaked)) {
t.Fatalf("the audit holds %q, want a keyed digest of the text only", leaked)
}
}
if found := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE status = 'found' AND attempt_id IS NOT NULL AND actor = 'operator:integration'`); found != 3 {
t.Fatalf("found audit rows = %d, want 3", found)
}
if notFound := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE status = 'not_found' AND attempt_id IS NULL AND method IS NULL`); notFound != 2 {
t.Fatalf("not found audit rows = %d, want 2", notFound)
}
// The audit is immutable and survives the attempt it names.
_, updateErr := harness.pool.Exec(ctx, `UPDATE assessment_leak_traces SET actor = 'operator:other'`)
assertSQLError(t, "update an audit record", updateErr, "23000", "assessment_leak_traces_immutable")
_, deleteErr := harness.pool.Exec(ctx, `DELETE FROM assessment_leak_traces`)
assertSQLError(t, "delete an audit record", deleteErr, "23000", "assessment_leak_traces_immutable")
_, truncateErr := harness.pool.Exec(ctx, `TRUNCATE assessment_leak_traces`)
assertSQLError(t, "truncate the audit", truncateErr, "23000", "assessment_leak_traces_immutable")
_, foundWithoutAttempt := harness.pool.Exec(ctx, `INSERT INTO assessment_leak_traces
(id, actor, searched_at, text_digest, key_version, text_runes, status, method, attempt_id, candidates, evidence_bits)
VALUES ($1, 'operator:integration', now(), $2, 1, 10, 'found', 'wording', NULL, 1, 1)`, uuid.New(), bytes.Repeat([]byte{1}, 32))
assertSQLError(t, "found search without an attempt", foundWithoutAttempt, assessmentCheckSQLState, "assessment_leak_traces_found")
if _, err := harness.pool.Exec(ctx, `DELETE FROM assessment_attempts WHERE id = $1`, firstAttempt.id); err != nil {
t.Fatalf("delete the attempt: %v", err)
}
if rows := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE attempt_id = $1`, firstAttempt.id); rows != 2 {
t.Fatalf("audit rows of the deleted attempt = %d, want them kept", rows)
}
gone := trace(firstAttempt.prompt, "")
if gone.Status != domain.AssessmentLeakTraceNotFound {
t.Fatalf("search for a deleted attempt = %+v, want not found: the mark names no attempt any more", gone)
}
// The command reads the secret of the server and the audit is written by it too.
var output bytes.Buffer
lookup := func(key string) (string, bool) {
switch key {
case "DATABASE_URL":
return databaseURL, true
case "IDENTITY_KEY_SECRET":
return isolatedEnv.Config.IdentityKeySecret, true
default:
return "", false
}
}
err = leaktrace.Run(ctx, []string{"search", "--actor", "operator:command", "--stdin"}, lookup,
strings.NewReader("Question: "+secondAttempt.prompt), &output)
if err != nil || !strings.Contains(output.String(), "result: found") || !strings.Contains(output.String(), "method: invisible_mark") ||
!strings.Contains(output.String(), "attempt: "+secondAttempt.id.String()) {
t.Fatalf("command output = %q, error %v, want the second attempt by its mark", output.String(), err)
}
if rows := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE actor = 'operator:command' AND status = 'found'`); rows != 1 {
t.Fatalf("command audit rows = %d, want 1", rows)
}
otherSecret := func(key string) (string, bool) {
if key == "IDENTITY_KEY_SECRET" {
return strings.Repeat("x", 48), true
}
return lookup(key)
}
output.Reset()
if err := leaktrace.Run(ctx, []string{"search", "--actor", "operator:command", "--stdin"}, otherSecret,
strings.NewReader("Question: "+secondAttempt.prompt), &output); err != nil || strings.Contains(output.String(), "method: invisible_mark") {
t.Fatalf("a command with another secret = %q, %v, want it not to read the mark of the server", output.String(), err)
}
}
type leakTraceAttempt struct {
id uuid.UUID
code string
prompt string
}
func leakTraceCreate(t *testing.T, harness *assessmentAttemptHTTPHarness, candidate reviewCandidate, key, remoteAddr string) leakTraceAttempt {
t.Helper()
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr)
if response.Code != http.StatusCreated {
t.Fatalf("create real attempt = %d %s", response.Code, response.Body.String())
}
id, _ := assessmentSignalAttemptItem(t, response.Body.Bytes())
code, prompt := decodeWatermarkedAttempt(t, response.Body.Bytes())
if code == "" || !hasZeroWidth(prompt) {
t.Fatalf("the presented attempt has code %q and a prompt without a mark", code)
}
return leakTraceAttempt{id: id, code: code, prompt: prompt}
}
// leakTraceFacts summarizes what a search must not change: the versions and
// states of the attempts and the number of reviews and results.
func leakTraceFacts(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness) string {
t.Helper()
var facts string
if err := harness.pool.QueryRow(ctx, `SELECT
coalesce((SELECT string_agg(id::text || ':' || version || ':' || state, ',' ORDER BY id) FROM assessment_attempts), '') || '|' ||
(SELECT count(*) FROM assessment_attempt_reviews) || '|' ||
(SELECT count(*) FROM assessment_attempt_results)`).Scan(&facts); err != nil {
t.Fatalf("read the attempt facts: %v", err)
}
return facts
}