feat(assessment): watermark the task text of real attempts
This commit is contained in:
1 parent
24b64d698a
commit
c975a0d506
57 files changed
+2429
-92
No files matched your search
@@ -580,7 +580,11 @@ func newAssessmentAttemptHTTPHarnessWithMiddleware(
|
||||
t.Fatalf("NewSignalObserver() error = %v", err)
|
||||
}
|
||||
attemptService.WithSignalObserver(signalObserver)
|
||||
attemptHandler := v1.NewAssessmentHandler(attemptService)
|
||||
watermarker, err := assessment.NewWatermarker(keyring)
|
||||
if err != nil {
|
||||
t.Fatalf("NewWatermarker() error = %v", err)
|
||||
}
|
||||
attemptHandler := v1.NewAssessmentHandler(attemptService).WithPresenter(watermarker)
|
||||
signalService, err := assessment.NewSignalService(transactor, keyring, clock.Now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewSignalService() error = %v", err)
|
||||
|
||||
@@ -5,10 +5,13 @@ package integration_test
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
const assessmentSignalNoticePath = "/api/v1/me/assessment-signal-notice"
|
||||
@@ -19,6 +22,11 @@ type signalNoticeProjection struct {
|
||||
AcknowledgedAt *string `json:"acknowledged_at"`
|
||||
}
|
||||
|
||||
// noticeBody is the request body that acknowledges the given notice version.
|
||||
func noticeBody(version int) string {
|
||||
return fmt.Sprintf(`{"notice_version":%d}`, version)
|
||||
}
|
||||
|
||||
func decodeSignalNotice(t *testing.T, response *httptest.ResponseRecorder) signalNoticeProjection {
|
||||
t.Helper()
|
||||
if response.Code != http.StatusOK {
|
||||
@@ -45,6 +53,9 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
t.Cleanup(harness.pool.Close)
|
||||
|
||||
// The tests follow the version the server requires, so a new text version
|
||||
// needs no edit here.
|
||||
current := int(assessment.CurrentSignalNoticeVersion)
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
@@ -63,7 +74,7 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
|
||||
requireSessionProblem(t, anonymous, http.StatusUnauthorized, "unauthenticated")
|
||||
|
||||
before := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, ""))
|
||||
if before.NoticeVersion != 2 || before.Acknowledged || before.AcknowledgedAt != nil {
|
||||
if before.NoticeVersion != current || before.Acknowledged || before.AcknowledgedAt != nil {
|
||||
t.Fatalf("notice before acknowledgement = %+v", before)
|
||||
}
|
||||
|
||||
@@ -77,21 +88,21 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
|
||||
if rejected := request(http.MethodPut, `{"notice_version":1,"accepted":true}`, sessionHTTPTestOrigin, cookie.Value, csrf); rejected.Code != http.StatusBadRequest {
|
||||
t.Fatalf("unknown field = %d %s, want 400", rejected.Code, rejected.Body.String())
|
||||
}
|
||||
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":3}`, sessionHTTPTestOrigin, cookie.Value, csrf),
|
||||
requireSessionProblem(t, request(http.MethodPut, noticeBody(current+1), sessionHTTPTestOrigin, cookie.Value, csrf),
|
||||
http.StatusConflict, "state_conflict")
|
||||
// The previous version is no longer the one the server requires.
|
||||
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf),
|
||||
requireSessionProblem(t, request(http.MethodPut, noticeBody(current-1), sessionHTTPTestOrigin, cookie.Value, csrf),
|
||||
http.StatusConflict, "state_conflict")
|
||||
if untouched := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")); untouched.Acknowledged {
|
||||
t.Fatalf("a refused request stored an acknowledgement: %+v", untouched)
|
||||
}
|
||||
|
||||
first := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf))
|
||||
if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != 2 {
|
||||
first := decodeSignalNotice(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, cookie.Value, csrf))
|
||||
if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != current {
|
||||
t.Fatalf("first acknowledgement = %+v", first)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
repeat := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, cookie.Value, csrf))
|
||||
repeat := decodeSignalNotice(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, cookie.Value, csrf))
|
||||
if repeat.AcknowledgedAt == nil || *repeat.AcknowledgedAt != *first.AcknowledgedAt {
|
||||
t.Fatalf("a repeat changed the first acknowledgement time: first %+v, repeat %+v", first, repeat)
|
||||
}
|
||||
@@ -104,7 +115,7 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_notice_acknowledgements WHERE user_id = $1", candidate.ID).Scan(&rows); err != nil || rows != 1 {
|
||||
t.Fatalf("stored acknowledgement rows = %d, error %v, want exactly one", rows, err)
|
||||
}
|
||||
// An acknowledgement of version 1 stays stored but does not count for version 2.
|
||||
// An acknowledgement of version 1 stays stored but does not count for the current version.
|
||||
if _, err := harness.pool.Exec(ctx, "INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at) VALUES ($1, 1, now())", other.ID); err != nil {
|
||||
t.Fatalf("store a version 1 acknowledgement: %v", err)
|
||||
}
|
||||
@@ -113,7 +124,7 @@ func TestAssessmentSignalNoticeOverHTTP(t *testing.T) {
|
||||
}
|
||||
|
||||
requireSessionProblem(t, request(http.MethodGet, "", "", employerCookie.Value, ""), http.StatusForbidden, "forbidden")
|
||||
requireSessionProblem(t, request(http.MethodPut, `{"notice_version":2}`, sessionHTTPTestOrigin, employerCookie.Value, employerCSRF),
|
||||
requireSessionProblem(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, employerCookie.Value, employerCSRF),
|
||||
http.StatusForbidden, "forbidden")
|
||||
|
||||
// The acknowledgement is a record, not a consent: it creates no ledger row.
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//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
|
||||
}
|
||||
Reference in new issue
Block a user