Files
lincodex/backend/integration_test/assessment_watermark_http_test.go

149 lines
6.5 KiB
Go

//go:build integration
package integration_test
import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
const assessmentWatermarkHTTPTimeout = 6 * time.Minute
// TestAssessmentWatermarkOverHTTP checks the mark on the path from the stored
// attempt to the response: a real attempt shows a code and a marked task text
// on every read, a training run shows neither, and the stored variant stays
// unmarked, so the reference answer and the grading never see the mark.
func TestAssessmentWatermarkOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), assessmentWatermarkHTTPTimeout)
defer cancel()
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)
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "watermark-owner@example.test", passwordHash, true)
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil {
t.Fatalf("set candidate onboarding step: %v", err)
}
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.231:1234")
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "192.0.2.232:1234"); response.Code != http.StatusOK {
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
}
training := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`,
sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-training", "192.0.2.233:1234")
if training.Code != http.StatusCreated {
t.Fatalf("create training attempt = %d %s", training.Code, training.Body.String())
}
if watermark, prompt := decodeWatermarkedAttempt(t, training.Body.Bytes()); watermark != "" || hasZeroWidth(prompt) {
t.Fatalf("training attempt carries watermark %q or a marked prompt, want neither", watermark)
}
grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.237:1234")
create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-root", "192.0.2.234:1234")
if create.Code != http.StatusCreated {
t.Fatalf("create real attempt = %d %s", create.Code, create.Body.String())
}
attemptID, _ := assessmentSignalAttemptItem(t, create.Body.Bytes())
code, prompt := decodeWatermarkedAttempt(t, create.Body.Bytes())
want := domainWatermark(t, harness, attemptID)
if code != want.Code().String() {
t.Fatalf("created attempt code = %q, want the code derived on the server %q", code, want.Code())
}
marks := domain.ExtractAssessmentWatermarkCodes(prompt)
if len(marks) == 0 || marks[0] != want.Code() {
t.Fatalf("invisible mark of the prompt = %v, want %s", marks, want.Code())
}
// A later read, and a replay of the creation, give the same code and text.
read := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+attemptID.String(), "",
"", cookie.Value, "", "", "192.0.2.235:1234")
if read.Code != http.StatusOK {
t.Fatalf("read attempt = %d %s", read.Code, read.Body.String())
}
if readCode, readPrompt := decodeWatermarkedAttempt(t, read.Body.Bytes()); readCode != code || readPrompt != prompt {
t.Fatalf("read attempt code/prompt = %q/%q, want the created ones %q/%q", readCode, readPrompt, code, prompt)
}
replay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-root", "192.0.2.236:1234")
if replayCode, replayPrompt := decodeWatermarkedAttempt(t, replay.Body.Bytes()); replay.Code != http.StatusCreated || replayCode != code || replayPrompt != prompt {
t.Fatalf("replayed creation = %d with code/prompt %q/%q, want the original ones", replay.Code, replayCode, replayPrompt)
}
// The response carries nothing of the key or the seed.
for _, secret := range []string{"seed", "key"} {
var document map[string]any
if err := json.Unmarshal(read.Body.Bytes(), &document); err != nil {
t.Fatalf("decode attempt: %v", err)
}
if watermark, ok := document["watermark"].(map[string]any); !ok || len(watermark) != 1 {
t.Fatalf("watermark object = %+v, want only a code", document["watermark"])
}
if _, exposed := document[secret]; exposed {
t.Fatalf("attempt response exposes %q", secret)
}
}
// The stored variant is the unmarked statement; grading reads it.
var stored string
if err := harness.pool.QueryRow(ctx, `SELECT variant->>'Statement' FROM assessment_attempt_items WHERE attempt_id = $1 ORDER BY ordinal LIMIT 1`, attemptID).Scan(&stored); err != nil {
t.Fatalf("read the stored statement: %v", err)
}
if hasZeroWidth(stored) {
t.Fatal("the stored statement carries an invisible mark, want the mark only on the presented text")
}
if domain.CanonicalAssessmentText(prompt) != domain.CanonicalAssessmentText(stored) {
t.Fatalf("the presented prompt differs in meaning from the stored statement:\n%q\n%q", prompt, stored)
}
}
func decodeWatermarkedAttempt(t *testing.T, body []byte) (code, prompt string) {
t.Helper()
var attempt struct {
Watermark *struct {
Code string `json:"code"`
} `json:"watermark"`
CurrentItem *struct {
Prompt string `json:"prompt"`
} `json:"current_item"`
}
if err := json.Unmarshal(body, &attempt); err != nil || attempt.CurrentItem == nil {
t.Fatalf("decode attempt: %+v, error %v", attempt, err)
}
if attempt.Watermark != nil {
code = attempt.Watermark.Code
}
return code, attempt.CurrentItem.Prompt
}
func hasZeroWidth(text string) bool {
return strings.ContainsAny(text, "\u200b\u200c\u200d\u2060")
}
func domainWatermark(t *testing.T, harness *assessmentAttemptHTTPHarness, attemptID uuid.UUID) domain.AssessmentWatermark {
t.Helper()
watermark, err := domain.NewAssessmentWatermark(harness.keyring.AssessmentWatermarkSeed(attemptID))
if err != nil {
t.Fatalf("NewAssessmentWatermark() error = %v", err)
}
return watermark
}