//go:build integration package integration_test import ( "context" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" ) const ( workPageOne = "page-one-AAAAAAAAAAAAAAAA" workPageTwo = "page-two-BBBBBBBBBBBBBBBB" workAgentOne = "TestBrowser/1.0 (Desktop; Workstation)" workAgentTwo = "TestBrowser/2.0 (Phone; Handheld)" workAgentThree = "TestBrowser/3.0 (Tablet; Slate)" ) func workSessionRequest( t *testing.T, harness *assessmentAttemptHTTPHarness, method string, attemptID uuid.UUID, candidate reviewCandidate, client, agent string, ) *httptest.ResponseRecorder { t.Helper() headers := map[string]string{"User-Agent": agent} if client != "" { headers["X-Attempt-Client"] = client } return assessmentAttemptHTTPRequestWithHeaders(t, harness, method, "/api/v1/me/assessment-attempts/"+attemptID.String()+"/work-session", "", sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], "", "192.0.2.40:4321", 20*time.Second, headers) } func startSessionRequest( t *testing.T, harness *assessmentAttemptHTTPHarness, attempt assessmentAnswerHTTPAttempt, candidate reviewCandidate, key, client string, ) *httptest.ResponseRecorder { t.Helper() headers := map[string]string{"User-Agent": workAgentOne} if client != "" { headers["X-Attempt-Client"] = client } return assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/sessions", `{"expected_version":1}`, sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], key, "192.0.2.41:4321", 20*time.Second, headers) } func answerRequest( t *testing.T, harness *assessmentAttemptHTTPHarness, attempt assessmentAnswerHTTPAttempt, body []byte, candidate reviewCandidate, key, client string, ) *httptest.ResponseRecorder { t.Helper() headers := map[string]string{"User-Agent": workAgentOne} if client != "" { headers["X-Attempt-Client"] = client } return assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body), sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], key, "192.0.2.42:4321", 20*time.Second, headers) } // TestAssessmentWorkSessionOverHTTP checks, with PostgreSQL, that one open page // holds the work session of a real attempt: a second page is refused for the // session and the answer until the first one releases it or stops renewing, the // refusal is not stored under an idempotency key, the page and the User-Agent // are kept only as keyed digests, and the weak capture signals and extra // User-Agents reach the review band at attention at most. func TestAssessmentWorkSessionOverHTTP(t *testing.T) { ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) defer cancel() signals := reviewTestSignalPolicy() signals.ClientScreenshotKeysAttention, signals.ClientDevtoolsAttention = 2, 1 signals.ExtraAgentsAttention, signals.ExtraAgentsReview = 2, 3 harness := newReviewHarness(ctx, t, signals) candidate := newReviewCandidate(ctx, t, harness, "work-session@example.test", "192.0.2", 1) attempt := candidate.createAttempt(t, harness, "work-session-create", "192.0.2.30:1234") items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) answer := assessmentAnswerHTTPBody(t, 1, items[0]) // The first page holds the session; the answer carries no page identifier. held := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentOne) var lease struct { HeldUntil time.Time `json:"held_until"` RenewAfterSeconds int `json:"renew_after_seconds"` } if held.Code != http.StatusOK || json.Unmarshal(held.Body.Bytes(), &lease) != nil || lease.RenewAfterSeconds != 15 || !lease.HeldUntil.After(time.Now()) || held.Header().Get("Cache-Control") != "no-store" { t.Fatalf("hold = %d %s, want a no-store lease that renews every 15 seconds", held.Code, held.Body.String()) } if strings.Contains(held.Body.String(), workPageOne) { t.Fatalf("the lease %s repeats the page identifier", held.Body.String()) } if renewed := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentOne); renewed.Code != http.StatusOK { t.Fatalf("renewal by the holder = %d %s", renewed.Code, renewed.Body.String()) } // A second page is refused with an explanation-free 409 that changes nothing. requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo), http.StatusConflict, "state_conflict") requireSessionProblem(t, startSessionRequest(t, harness, attempt, candidate, "work-start", workPageTwo), http.StatusConflict, "state_conflict") requireSessionProblem(t, startSessionRequest(t, harness, attempt, candidate, "work-start-anonymous", ""), http.StatusConflict, "state_conflict") requireSessionProblem(t, answerRequest(t, harness, attempt, answer, candidate, "work-answer", workPageTwo), http.StatusConflict, "state_conflict") requireSessionProblem(t, answerRequest(t, harness, attempt, answer, candidate, "work-answer-anonymous", ""), http.StatusConflict, "state_conflict") if stored := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_items WHERE attempt_id = $1 AND answer IS NOT NULL", attempt.ID); stored != 0 { t.Fatalf("a refused answer was stored: %d answered items", stored) } // The refusal was not stored under the key: the holder reuses both keys. if resumed := startSessionRequest(t, harness, attempt, candidate, "work-start", workPageOne); resumed.Code != http.StatusOK { t.Fatalf("session of the holder under the refused key = %d %s", resumed.Code, resumed.Body.String()) } var answered assessmentAnswerHTTPAttempt first := answerRequest(t, harness, attempt, answer, candidate, "work-answer", workPageOne) if first.Code != http.StatusOK || json.Unmarshal(first.Body.Bytes(), &answered) != nil || answered.Version != 2 { t.Fatalf("answer of the holder under the refused key = %d %s", first.Code, first.Body.String()) } // Another page cannot release the session of the holder, and a release // never says whether it did anything. if released := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageTwo, workAgentTwo); released.Code != http.StatusNoContent { t.Fatalf("release by another page = %d %s, want 204", released.Code, released.Body.String()) } requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo), http.StatusConflict, "state_conflict") // The first page closes: the second takes over at once, with another browser. if released := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageOne, workAgentOne); released.Code != http.StatusNoContent { t.Fatalf("release by the holder = %d %s", released.Code, released.Body.String()) } if repeat := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageOne, workAgentOne); repeat.Code != http.StatusNoContent { t.Fatalf("repeated release = %d %s, want 204", repeat.Code, repeat.Body.String()) } if taken := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo); taken.Code != http.StatusOK { t.Fatalf("hold by the second page after the release = %d %s", taken.Code, taken.Body.String()) } second := answerRequest(t, harness, answered, answer, candidate, "work-answer-after", workPageOne) requireSessionProblem(t, second, http.StatusConflict, "state_conflict") // A page that is killed stops renewing: its hold ends by itself. if _, err := harness.pool.Exec(ctx, `UPDATE assessment_attempt_work_leases SET acquired_at = acquired_at - INTERVAL '10 minutes', renewed_at = renewed_at - INTERVAL '10 minutes' WHERE attempt_id = $1`, attempt.ID); err != nil { t.Fatalf("age the lease: %v", err) } if retaken := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentThree); retaken.Code != http.StatusOK { t.Fatalf("hold after the other page stopped renewing = %d %s", retaken.Code, retaken.Body.String()) } // Malformed identifiers, a foreign attempt, and a training run. for _, bad := range []string{"short", strings.Repeat("a", 65), "has space has space"} { response := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, bad, workAgentOne) if response.Code != http.StatusBadRequest { t.Fatalf("hold with page identifier %q = %d %s, want 400", bad, response.Code, response.Body.String()) } } requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, uuid.New(), candidate, workPageOne, workAgentOne), http.StatusNotFound, "not_found") missing := assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPut, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/work-session", "", sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], "", "192.0.2.43:4321", 20*time.Second, nil) if missing.Code != http.StatusBadRequest { t.Fatalf("hold without a page identifier = %d %s, want 400", missing.Code, missing.Body.String()) } noCSRF := assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPut, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/work-session", "", sessionHTTPTestOrigin, candidate.cookies[0].Value, "", "", "192.0.2.43:4321", 20*time.Second, map[string]string{"X-Attempt-Client": workPageOne}) requireSessionProblem(t, noCSRF, http.StatusForbidden, "csrf_check_failed") // Only digests are stored: no column holds a page identifier or a User-Agent. if rows := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_work_leases WHERE attempt_id = $1", attempt.ID); rows != 1 { t.Fatalf("lease rows = %d, want one per attempt", rows) } for _, table := range []string{"assessment_attempt_work_leases", "assessment_attempt_origin_marks"} { var dump string if err := harness.pool.QueryRow(ctx, "SELECT coalesce(string_agg(t::text, ' '), '') FROM "+table+" AS t WHERE attempt_id = $1", attempt.ID).Scan(&dump); err != nil { t.Fatalf("dump %s: %v", table, err) } for _, secret := range []string{workPageOne, workPageTwo, "TestBrowser", "Desktop", "Handheld"} { if strings.Contains(dump, secret) { t.Fatalf("%s holds %q, want only keyed digests", table, secret) } } } for _, agent := range []string{workAgentOne, workAgentTwo, workAgentThree} { digest := harness.keyring.AssessmentAgentDigest(attempt.ID, agent) if rows := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_origin_marks WHERE attempt_id = $1 AND agent_digest = $2 AND source = 'work_session'", attempt.ID, digest[:]); rows == 0 { t.Fatalf("no work session mark carries the digest of %q", agent) } } // The weak capture signals are stored without a measurement and refused with one. itemID := items[0].ID at := time.Now().UTC().Truncate(time.Microsecond) batch := func(events ...map[string]any) string { encoded, err := json.Marshal(map[string]any{"events": events}) if err != nil { t.Fatalf("marshal capture batch: %v", err) } return string(encoded) } event := func(kind string, offset time.Duration) map[string]any { return map[string]any{"kind": kind, "item_instance_id": itemID, "occurred_at": at.Add(offset).Format(time.RFC3339Nano)} } accepted := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-batch", batch(event("screenshot_key", 0), event("screenshot_key", time.Second), event("devtools_open", 2*time.Second)), "192.0.2.44:4321") assertSignalReceipt(t, accepted, http.StatusOK, "accepted", 3) withSize := event("screenshot_key", 3*time.Second) withSize["size_bytes"] = 10 if rejected := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-size", batch(withSize), "192.0.2.45:4321"); rejected.Code != http.StatusBadRequest { t.Fatalf("screenshot key with a size = %d %s, want 400", rejected.Code, rejected.Body.String()) } if unknown := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-kind", batch(event("screen_recording", 0)), "192.0.2.46:4321"); unknown.Code != http.StatusBadRequest { t.Fatalf("unknown signal kind = %d %s, want 400", unknown.Code, unknown.Body.String()) } if kinds := countRows(t, ctx, harness, "SELECT count(DISTINCT kind) FROM assessment_signal_events WHERE attempt_id = $1 AND kind IN ('screenshot_key', 'devtools_open')", attempt.ID); kinds != 2 { t.Fatalf("stored capture kinds = %d, want both", kinds) } // The band: three User-Agents, two screenshot keys, and open developer tools // are only weak signals, so the band is attention and never review. worker := reviewJobWorker(t, harness, reviewFarFuture, 10) runReviewJobs(ctx, t, worker) var band string var reasons []string var extraAgents, screenshotKeys, devtoolsOpens int32 if err := harness.pool.QueryRow(ctx, `SELECT band, reasons, extra_agents, client_screenshot_keys, client_devtools_opens FROM assessment_attempt_reviews WHERE attempt_id = $1`, attempt.ID).Scan(&band, &reasons, &extraAgents, &screenshotKeys, &devtoolsOpens); err != nil { t.Fatalf("read the review: %v", err) } if band != string(domain.AssessmentReviewBandAttention) || extraAgents != 2 || screenshotKeys != 2 || devtoolsOpens != 1 { t.Fatalf("review = band %s, %d extra agents, %d screenshot keys, %d detections; want attention, 2, 2, 1", band, extraAgents, screenshotKeys, devtoolsOpens) } for _, reason := range []string{string(domain.AssessmentReviewReasonExtraAgents), string(domain.AssessmentReviewReasonClientSignals)} { found := false for _, got := range reasons { found = found || got == reason } if !found { t.Fatalf("review reasons = %v, want %s among them", reasons, reason) } } } func countRows(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness, query string, args ...any) int64 { t.Helper() var count int64 if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { t.Fatalf("count rows (%s): %v", query, err) } return count }