Files
lincodex/backend/integration_test/assessment_attempt_http_test.go
T

1098 lines
51 KiB
Go

//go:build integration
package integration_test
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
httpadapter "lincodex/backend/internal/adapter/primary/http"
apiadapter "lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/assessment"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/policy"
questionnaireusecase "lincodex/backend/internal/usecase/questionnaire"
)
const assessmentAttemptHTTPTimeout = 6 * time.Minute
func TestAssessmentAttemptOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
registeredAt := harness.clock.Now()
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-owner@example.test", passwordHash, true)
missingConsent := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-no-consent@example.test", passwordHash, true)
otherCandidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-other@example.test", passwordHash, true)
employer := createQuestionnaireHTTPEmployer(ctx, t, harness.sessionHTTPHarness, "attempt-employer@example.test", passwordHash, registeredAt)
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = ANY($1)",
[]uuid.UUID{candidate.ID, missingConsent.ID, otherCandidate.ID}); err != nil {
t.Fatalf("set candidate onboarding step: %v", err)
}
candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.241:1234")
missingCookie, missingCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, missingConsent.Email.Address(), "192.0.2.242:1234")
otherCookie, otherCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, otherCandidate.Email.Address(), "192.0.2.243:1234")
employerCookie, employerCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.244:1234")
backendBody := assessmentAttemptCreateBody(t, "backend")
guestCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody,
sessionHTTPTestOrigin, "", "", "guest-create", "192.0.2.245:1234")
requireSessionProblem(t, guestCreate, http.StatusUnauthorized, "unauthenticated")
employerCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody,
sessionHTTPTestOrigin, employerCookie.Value, employerCSRF, "employer-create", "192.0.2.246:1234")
requireSessionProblem(t, employerCreate, http.StatusForbidden, "forbidden")
missingC3Create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody,
sessionHTTPTestOrigin, missingCookie.Value, missingCSRF, "missing-c3-create", "192.0.2.247:1234")
requireSessionProblem(t, missingC3Create, http.StatusForbidden, "forbidden")
assertAttemptCount(t, ctx, harness.pool, 0)
if response := assessmentAttemptQuestionnaireRequest(t, harness, candidateCookie.Value, candidateCSRF, "192.0.2.248:1234"); response.Code != http.StatusOK {
t.Fatalf("save two-specialization questionnaire = %d %s", response.Code, response.Body.String())
}
trainingBody := `{"kind":"demo_express"}`
trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "192.0.2.248:1235")
if trainingCreate.Code != http.StatusCreated {
t.Fatalf("create reviewed express attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String())
}
var trainingSnapshot struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind"`
Mode string `json:"mode"`
State string `json:"state"`
}
if err := json.Unmarshal(trainingCreate.Body.Bytes(), &trainingSnapshot); err != nil || trainingSnapshot.ID == uuid.Nil ||
trainingSnapshot.Kind != "demo_express" || trainingSnapshot.Mode != "demo_express" || trainingSnapshot.State != "in_progress" {
t.Fatalf("express attempt = %+v, decode error %v", trainingSnapshot, err)
}
assertAttemptCount(t, ctx, harness.pool, 1)
grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "192.0.2.249:1234")
// Both requests pass the same candidate-wide root quota through different
// specialization locks. Exactly one can reserve the only root slot.
requests := []struct {
key string
body string
addr string
}{
{key: "attempt-backend-root", body: backendBody, addr: "192.0.2.250:1234"},
{key: "attempt-frontend-root", body: assessmentAttemptCreateBody(t, "frontend"), addr: "192.0.2.251:1234"},
}
responses := make([]*httptest.ResponseRecorder, len(requests))
start := make(chan struct{})
var wait sync.WaitGroup
for index := range requests {
wait.Add(1)
go func(index int) {
defer wait.Done()
<-start
request := requests[index]
responses[index] = assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", request.body,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, request.key, request.addr)
}(index)
}
close(start)
wait.Wait()
accepted := -1
conflicted := -1
for index, response := range responses {
switch response.Code {
case http.StatusCreated:
accepted = index
if response.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("created attempt Cache-Control = %q, want no-store", response.Header().Get("Cache-Control"))
}
case http.StatusConflict:
requireSessionProblem(t, response, http.StatusConflict, "state_conflict")
conflicted = index
default:
t.Fatalf("concurrent create %s = %d %s, want one 201 and one 409", requests[index].key, response.Code, response.Body.String())
}
}
if accepted < 0 || conflicted < 0 || accepted == conflicted {
t.Fatalf("concurrent root results accepted=%d conflicted=%d, want one of each", accepted, conflicted)
}
for index, response := range responses {
replay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", requests[index].body,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, requests[index].key, requests[index].addr)
assertAssessmentAttemptReplay(t, requests[index].key, response, replay)
}
var acceptedAttempt struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind"`
Version int64 `json:"version"`
State string `json:"state"`
Specialization string `json:"specialization"`
}
if err := json.Unmarshal(responses[accepted].Body.Bytes(), &acceptedAttempt); err != nil || acceptedAttempt.ID == uuid.Nil ||
acceptedAttempt.Kind != "root" || acceptedAttempt.Version != 1 || acceptedAttempt.State != "in_progress" {
t.Fatalf("created attempt = %+v, decode error %v", acceptedAttempt, err)
}
for _, privateField := range []string{`"answer_key"`, `"family_id"`, `"family_key"`, `"variant"`, `"variant_seed"`, `"solution"`} {
if strings.Contains(responses[accepted].Body.String(), privateField) {
t.Fatalf("public attempt response exposed %s", privateField)
}
}
assertAttemptCount(t, ctx, harness.pool, 2)
changedBody := assessmentAttemptCreateBody(t, "frontend")
if requests[accepted].body == changedBody {
changedBody = assessmentAttemptCreateBodyWithGrade(t, "backend", "middle")
}
keyReuse := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", changedBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, requests[accepted].key, "192.0.2.252:1234")
requireSessionProblem(t, keyReuse, http.StatusUnprocessableEntity, "idempotency_key_reused")
assertAttemptCount(t, ctx, harness.pool, 2)
getPath := "/api/v1/me/assessment-attempts/" + acceptedAttempt.ID.String()
before := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID)
for range 2 {
read := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", candidateCookie.Value, "", "", "192.0.2.253:1234")
if read.Code != http.StatusOK || read.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("own attempt read = %d Cache-Control=%q: %s", read.Code, read.Header().Get("Cache-Control"), read.Body.String())
}
if read.Body.String() != responses[accepted].Body.String() {
t.Fatalf("GET attempt projection differs from immutable create result: got %s want %s", read.Body.String(), responses[accepted].Body.String())
}
}
if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before {
t.Fatalf("read-only GET changed attempt state: before=%+v after=%+v", before, after)
}
var createdProjection struct {
CurrentItem *struct {
ID uuid.UUID `json:"id"`
Prompt string `json:"prompt"`
} `json:"current_item"`
}
if err := json.Unmarshal(responses[accepted].Body.Bytes(), &createdProjection); err != nil || createdProjection.CurrentItem == nil ||
createdProjection.CurrentItem.ID == uuid.Nil || createdProjection.CurrentItem.Prompt == "" {
t.Fatalf("decode created public item = %+v, error %v", createdProjection, err)
}
// A new pool, service graph, and router must read the same frozen item from
// PostgreSQL after reconstruction, not merely reuse an in-memory handler.
harness.pool.Close()
harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
restartedRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", candidateCookie.Value, "", "", "198.51.100.0:1234")
var restartedProjection struct {
CurrentItem *struct {
ID uuid.UUID `json:"id"`
Prompt string `json:"prompt"`
} `json:"current_item"`
}
if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restartedProjection) != nil ||
restartedProjection.CurrentItem == nil || restartedProjection.CurrentItem.ID != createdProjection.CurrentItem.ID ||
restartedProjection.CurrentItem.Prompt != createdProjection.CurrentItem.Prompt ||
restartedRead.Body.String() != responses[accepted].Body.String() {
t.Fatalf("GET after router reconstruction = %d %s, want item %s and original text", restartedRead.Code, restartedRead.Body.String(), createdProjection.CurrentItem.ID)
}
foreignRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", otherCookie.Value, "", "", "192.0.2.254:1234")
requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found")
unknownRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+uuid.NewString(), "", "", candidateCookie.Value, "", "", "192.0.2.255:1234")
requireSessionProblem(t, unknownRead, http.StatusNotFound, "not_found")
employerRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", employerCookie.Value, "", "", "198.51.100.1:1234")
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
guestRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", "", "", "", "198.51.100.2:1234")
requireSessionProblem(t, guestRead, http.StatusUnauthorized, "unauthenticated")
// Revocation wins before a session command and leaves both the attempt and
// its session budget unchanged. Restoring C3 permits the same key to run.
revokeC3 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c3", "", sessionHTTPTestOrigin,
candidateCookie.Value, candidateCSRF, "198.51.100.3:1234")
if revokeC3.Code != http.StatusNoContent {
t.Fatalf("revoke C3 before session = %d %s", revokeC3.Code, revokeC3.Body.String())
}
sessionPath := getPath + "/sessions"
sessionBody := `{"expected_version":1}`
blockedSession := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-session-key", "198.51.100.4:1234")
requireSessionProblem(t, blockedSession, http.StatusForbidden, "forbidden")
if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before {
t.Fatalf("C3-denied session command changed attempt: before=%+v after=%+v", before, after)
}
grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "192.0.2.260:1234")
startRequests := []struct {
key string
addr string
}{
{key: "attempt-session-key", addr: "198.51.100.5:1234"},
{key: "attempt-session-key-two", addr: "198.51.100.6:1234"},
}
startResponses := make([]*httptest.ResponseRecorder, len(startRequests))
startGate := make(chan struct{})
var startWait sync.WaitGroup
for index := range startRequests {
startWait.Add(1)
go func(index int) {
defer startWait.Done()
<-startGate
request := startRequests[index]
startResponses[index] = assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, request.key, request.addr)
}(index)
}
close(startGate)
startWait.Wait()
started := startResponses[0]
for index, response := range startResponses {
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("concurrent session start %s = %d Cache-Control=%q: %s", startRequests[index].key, response.Code, response.Header().Get("Cache-Control"), response.Body.String())
}
if response.Body.String() != started.Body.String() {
t.Fatalf("concurrent session starts returned different snapshots: %s != %s", response.Body.String(), started.Body.String())
}
}
startedReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, startRequests[0].key, startRequests[0].addr)
if startedReplay.Code != started.Code || startedReplay.Body.String() != started.Body.String() {
t.Fatalf("session replay = %d %s, want stored %d %s", startedReplay.Code, startedReplay.Body.String(), started.Code, started.Body.String())
}
var sessionSnapshot struct {
Version int64 `json:"version"`
Sessions struct {
Used int32 `json:"used"`
} `json:"sessions"`
}
if err := json.Unmarshal(started.Body.Bytes(), &sessionSnapshot); err != nil || sessionSnapshot.Version != 1 || sessionSnapshot.Sessions.Used != 1 {
t.Fatalf("same-active-session response = %+v, decode error %v; want version 1 and session 1", sessionSnapshot, err)
}
staleSession := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, `{"expected_version":2}`,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-stale-session", "198.51.100.7:1234")
requireSessionProblem(t, staleSession, http.StatusPreconditionFailed, "version_conflict")
if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before {
t.Fatalf("stale session command changed attempt: before=%+v after=%+v", before, after)
}
// The root owns a fixed 72-hour correction window. A terminal failed root
// can create one lower-grade correction without consuming another root
// quota slot, and the child keeps the root's exact deadline.
rootStartedAt, rootDeadline := readAttemptChainTiming(t, ctx, harness.pool, acceptedAttempt.ID)
if rootDeadline.Sub(rootStartedAt) != 72*time.Hour {
t.Fatalf("root chain deadline = %s, database started_at=%s; want 72 hours", rootDeadline, rootStartedAt)
}
terminalizeAttempt(t, ctx, harness.pool, acceptedAttempt.ID)
correctiveBody := assessmentAttemptCorrectiveBody(t, acceptedAttempt.Specialization, "intern", acceptedAttempt.ID)
corrective := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", correctiveBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-correction", "198.51.100.8:1234")
if corrective.Code != http.StatusCreated {
t.Fatalf("create lower-grade correction = %d %s", corrective.Code, corrective.Body.String())
}
var correctiveSnapshot struct {
ID uuid.UUID `json:"id"`
Kind string `json:"kind"`
RootAttemptID uuid.UUID `json:"root_attempt_id"`
}
if err := json.Unmarshal(corrective.Body.Bytes(), &correctiveSnapshot); err != nil || correctiveSnapshot.ID == uuid.Nil ||
correctiveSnapshot.Kind != "corrective" || correctiveSnapshot.RootAttemptID != acceptedAttempt.ID {
t.Fatalf("corrective snapshot = %+v, decode error %v; want root linkage", correctiveSnapshot, err)
}
if _, correctiveDeadline := readAttemptChainTiming(t, ctx, harness.pool, correctiveSnapshot.ID); !correctiveDeadline.Equal(rootDeadline) {
t.Fatalf("corrective database chain deadline = %s, want exact root deadline %s", correctiveDeadline, rootDeadline)
}
var rootCount int64
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'`, candidate.ID).Scan(&rootCount); err != nil || rootCount != 1 {
t.Fatalf("candidate root attempt count = %d, error %v; corrective must not consume root quota", rootCount, err)
}
terminalizeAttempt(t, ctx, harness.pool, correctiveSnapshot.ID)
repeatedGrade := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", correctiveBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-correction-repeat", "198.51.100.9:1234")
if repeatedGrade.Code != http.StatusBadRequest || !strings.Contains(repeatedGrade.Body.String(), "/target_grade") {
t.Fatalf("repeat corrective grade = %d %s, want field error at target_grade", repeatedGrade.Code, repeatedGrade.Body.String())
}
var correctionCount int64
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='corrective'`, candidate.ID).Scan(&correctionCount); err != nil || correctionCount != 1 {
t.Fatalf("candidate correction count = %d, error %v; repeated grade must not add a row", correctionCount, err)
}
// The typed 201 training outcome is replaced only after its generic
// idempotency window expires; the active training attempt yields a new 409.
trainingScope := harness.keyring.IdempotencyScope("assessment_attempt.create", "attempt-training", candidate.ID.String())
if _, err := harness.pool.Exec(ctx, `
WITH stamp AS (SELECT clock_timestamp() AS at)
UPDATE idempotency_records
SET created_at=stamp.at-interval '2 minutes', expires_at=stamp.at-interval '1 second'
FROM stamp WHERE scope_hash=$1`, trainingScope[:]); err != nil {
t.Fatalf("expire training idempotency fixture: %v", err)
}
expiredTrainingKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "198.51.100.10:1234")
requireSessionProblem(t, expiredTrainingKey, http.StatusConflict, "state_conflict")
reusedTrainingKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "198.51.100.10:1234")
assertAssessmentAttemptReplay(t, "attempt-training after expiry", expiredTrainingKey, reusedTrainingKey)
// Fail the item insert after the attempt header and idempotency reservation
// have been written. A same-key retry after removing the trigger must work,
// proving that the entire PostgreSQL transaction rolled back.
if response := assessmentAttemptQuestionnaireRequest(t, harness, otherCookie.Value, otherCSRF, "198.51.100.11:1234"); response.Code != http.StatusOK {
t.Fatalf("save rollback candidate questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness, otherCookie, otherCSRF, "198.51.100.12:1234")
if _, err := harness.pool.Exec(ctx, `CREATE FUNCTION reject_attempt_item_for_test() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION USING ERRCODE='23514', CONSTRAINT='test_attempt_item_rejected', MESSAGE='test failure'; END; $$`); err != nil {
t.Fatalf("create attempt-item rollback trigger function: %v", err)
}
if _, err := harness.pool.Exec(ctx, `CREATE TRIGGER reject_attempt_item_for_test BEFORE INSERT ON assessment_attempt_items FOR EACH ROW EXECUTE FUNCTION reject_attempt_item_for_test()`); err != nil {
t.Fatalf("create attempt-item rollback trigger: %v", err)
}
rollbackBody := assessmentAttemptCreateBody(t, "backend")
rollbackKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", rollbackBody,
sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "attempt-rollback-retry", "198.51.100.13:1234")
if rollbackKey.Code != http.StatusInternalServerError {
t.Fatalf("forced item insert failure = %d %s, want internal error", rollbackKey.Code, rollbackKey.Body.String())
}
if _, err := harness.pool.Exec(ctx, `DROP TRIGGER reject_attempt_item_for_test ON assessment_attempt_items`); err != nil {
t.Fatalf("drop attempt-item rollback trigger: %v", err)
}
if _, err := harness.pool.Exec(ctx, `DROP FUNCTION reject_attempt_item_for_test()`); err != nil {
t.Fatalf("drop attempt-item rollback trigger function: %v", err)
}
assertAttemptCount(t, ctx, harness.pool, 3)
retryAfterRollback := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", rollbackBody,
sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "attempt-rollback-retry", "198.51.100.13:1234")
if retryAfterRollback.Code != http.StatusCreated {
t.Fatalf("same-key create after rollback = %d %s, want 201", retryAfterRollback.Code, retryAfterRollback.Body.String())
}
assertAttemptCount(t, ctx, harness.pool, 4)
assertAttemptPinAndItemRowsAreImmutable(t, ctx, harness.pool, acceptedAttempt.ID)
}
func TestAssessmentAttemptSessionUsesDatabaseTimeAfterRowLockWait(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
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, "attempt-lock-wait@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 lock-wait candidate onboarding step: %v", err)
}
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.10:1234")
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.11:1234"); response.Code != http.StatusOK {
t.Fatalf("save lock-wait candidate questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.12:1234")
created := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", assessmentAttemptCreateBody(t, "backend"),
sessionHTTPTestOrigin, cookie.Value, csrf, "attempt-lock-wait-create", "203.0.113.13:1234")
if created.Code != http.StatusCreated {
t.Fatalf("create lock-wait attempt = %d %s", created.Code, created.Body.String())
}
var attempt struct {
ID uuid.UUID `json:"id"`
}
if err := json.Unmarshal(created.Body.Bytes(), &attempt); err != nil || attempt.ID == uuid.Nil {
t.Fatalf("decode lock-wait attempt ID = %s, error %v", attempt.ID, err)
}
lockConnection, err := harness.pool.Acquire(ctx)
if err != nil {
t.Fatalf("acquire row-lock connection: %v", err)
}
defer lockConnection.Release()
lockTx, err := lockConnection.Begin(ctx)
if err != nil {
t.Fatalf("begin row-lock transaction: %v", err)
}
defer func() {
if err := lockTx.Rollback(context.Background()); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
t.Errorf("rollback row-lock transaction: %v", err)
}
}()
var lockPID int32
if err := lockConnection.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&lockPID); err != nil {
t.Fatalf("read row-lock backend PID: %v", err)
}
var lockedID uuid.UUID
if err := lockTx.QueryRow(ctx, `SELECT id FROM assessment_attempts WHERE id=$1 FOR UPDATE`, attempt.ID).Scan(&lockedID); err != nil || lockedID != attempt.ID {
t.Fatalf("lock attempt row %s: got %s, error %v", attempt.ID, lockedID, err)
}
type requestResult struct {
response *httptest.ResponseRecorder
}
result := make(chan requestResult, 1)
go func() {
response := assessmentAttemptHTTPRequestWithTimeout(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/sessions", `{"expected_version":1}`,
sessionHTTPTestOrigin, cookie.Value, csrf, "attempt-lock-wait-session", "203.0.113.14:1234", 100*time.Second)
result <- requestResult{response: response}
}()
waitForAssessmentAttemptRowLock(t, ctx, harness.pool, lockPID)
waitForAttemptIdleDeadline(t, ctx, harness.pool, attempt.ID)
if err := lockTx.Commit(ctx); err != nil {
t.Fatalf("release row lock after idle timeout: %v", err)
}
select {
case completed := <-result:
if completed.response.Code != http.StatusOK {
t.Fatalf("session after lock-wait expiry = %d %s; server logs: %s",
completed.response.Code, completed.response.Body.String(), harness.logs.String())
}
var snapshot struct {
Version int64 `json:"version"`
State string `json:"state"`
Sessions struct {
Used int32 `json:"used"`
} `json:"sessions"`
}
if err := json.Unmarshal(completed.response.Body.Bytes(), &snapshot); err != nil || snapshot.Version != 2 ||
snapshot.State != "expired" || snapshot.Sessions.Used != 1 {
t.Fatalf("session response after deadline = %+v, error %v; want expired version 2 and one session", snapshot, err)
}
case <-time.After(30 * time.Second):
t.Fatal("session request did not finish after releasing attempt row lock")
}
}
type assessmentAttemptHTTPHarness struct {
*sessionHTTPHarness
keyring *identity.Keyring
}
func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *assessmentAttemptHTTPHarness {
t.Helper()
return newAssessmentAttemptHTTPHarnessWithCategories(ctx, t, env, assessment.AssessmentCategoryDecisionSettings{})
}
// newAssessmentAttemptHTTPHarnessWithCategories builds the attempt router with
// explicit category assignment settings. The zero settings deny assignment.
func newAssessmentAttemptHTTPHarnessWithCategories(
ctx context.Context,
t *testing.T,
env *testEnvironment,
categories assessment.AssessmentCategoryDecisionSettings,
) *assessmentAttemptHTTPHarness {
t.Helper()
return newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, env, categories, nil)
}
// assessmentHarnessParts are the shared dependencies of the attempt router, for
// a scenario that mounts further business areas on the same router.
type assessmentHarnessParts struct {
pool *pgxpool.Pool
transactor *postgresadapter.Transactor
keyring *identity.Keyring
clock *testClock
}
// newAssessmentAttemptHTTPHarnessWithOptions builds the attempt router and adds
// the handler options that extra returns, if any.
func newAssessmentAttemptHTTPHarnessWithOptions(
ctx context.Context,
t *testing.T,
env *testEnvironment,
categories assessment.AssessmentCategoryDecisionSettings,
extra func(assessmentHarnessParts) []v1.HandlerOption,
) *assessmentAttemptHTTPHarness {
t.Helper()
return newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env, categories, extra, nil)
}
// newAssessmentAttemptHTTPHarnessWithMiddleware also mounts the operation
// middleware that middleware returns, after extra has built its handlers, so a
// scenario can add the owner company context to the same router.
func newAssessmentAttemptHTTPHarnessWithMiddleware(
ctx context.Context,
t *testing.T,
env *testEnvironment,
categories assessment.AssessmentCategoryDecisionSettings,
extra func(assessmentHarnessParts) []v1.HandlerOption,
middleware func() []apiadapter.Middleware,
) *assessmentAttemptHTTPHarness {
t.Helper()
pool := env.newPool(ctx, t)
store := postgresadapter.NewIdentityStore(pool)
hasher, err := argon2id.NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
credentials := identity.NewCredentials(hasher)
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
transactor := postgresadapter.NewTransactor(pool)
sessions, err := identity.NewSessionService(identity.SessionDependencies{
Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(),
Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now,
}, identity.SessionSettings{
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
})
if err != nil {
t.Fatalf("NewSessionService() error = %v", err)
}
consentStore := postgresadapter.NewConsentStore(pool)
consentHandler := v1.NewConsentHandler(
consent.NewQueryService(consentStore, time.Now), consent.NewService(transactor, time.Now),
)
questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now))
catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor))
attemptService, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock.Now, categories)
if err != nil {
t.Fatalf("NewAttemptServiceWithCategorySettings() error = %v", err)
}
signalObserver, err := assessment.NewSignalObserver(keyring)
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
attemptService.WithSignalObserver(signalObserver)
attemptHandler := v1.NewAssessmentHandler(attemptService)
signalService, err := assessment.NewSignalService(transactor, keyring, clock.Now)
if err != nil {
t.Fatalf("NewSignalService() error = %v", err)
}
signalService.WithSignalObserver(signalObserver)
signalHandler := v1.NewAssessmentSignalHandler(signalService).WithNotice(signalService)
logs := &strings.Builder{}
logger := slog.New(slog.NewJSONHandler(logs, nil))
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL))
options := []v1.HandlerOption{
v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler),
v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler),
v1.WithAssessment(attemptHandler), v1.WithAssessmentSignals(signalHandler),
}
if extra != nil {
options = append(options, extra(assessmentHarnessParts{pool: pool, transactor: transactor, keyring: keyring, clock: clock})...)
}
handler := v1.NewHandler(healthHandler, responder, options...)
var operationMiddleware []apiadapter.Middleware
if middleware != nil {
operationMiddleware = middleware()
}
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil, operationMiddleware...)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
base := &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
return &assessmentAttemptHTTPHarness{sessionHTTPHarness: base, keyring: keyring}
}
func seedAssessmentAttemptHTTPBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool) {
t.Helper()
seedAssessmentAttemptHTTPBankWithSignals(ctx, t, pool, nil)
}
// seedAssessmentAttemptHTTPBankWithSignals seeds the attempt fixture bank under
// a product policy that carries the given signal thresholds, or none.
func seedAssessmentAttemptHTTPBankWithSignals(ctx context.Context, t *testing.T, pool *pgxpool.Pool, signals *domain.AssessmentSignalPolicy) {
t.Helper()
transactor := postgresadapter.NewTransactor(pool)
bank := assessment.NewBank(transactor)
store := postgresadapter.NewAssessmentBankStore(pool)
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now)
fixture := assessmentFixture{
ctx: ctx, pool: pool, store: store, transactor: transactor,
bank: bank, publisher: publisher, demoBundle: loadDemoBundleFile(t),
}
productPolicy := integrationPolicy(11)
productPolicy.Assessment.MaxAttemptsPerWindow = 1
demoAttemptPolicy := domain.DemoProductPolicyV2().Assessment
productPolicy.Assessment.Attempt = demoAttemptPolicy.Attempt
productPolicy.Assessment.Training = demoAttemptPolicy.Training
productPolicy.Assessment.Attempt.MaxSessions = 1
productPolicy.Assessment.Attempt.IdleTimeoutSeconds = 60
productPolicy.Assessment.Signals = signals
policyVersion, err := publisher.Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated,
Author: policyTestAuthor, Policy: productPolicy,
})
if err != nil {
t.Fatalf("Publish(attempt fixture policy) error = %v", err)
}
required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy())
if err != nil {
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
}
bundle := fixture.reviewedBundle(int(required))
bundle.Name = "assessment-attempt-backend-fixture"
if _, err := bank.ImportBundle(ctx, bundle); err != nil {
t.Fatalf("ImportBundle(backend attempt fixture) error = %v", err)
}
publishAssessmentAttemptFixtureFamilies(ctx, t, bank, bundle)
openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("backend"), domain.SpecializationBackend, domain.GradeJunior)
frontend := bundle
frontend.Name = "assessment-attempt-frontend-fixture"
frontend.Category = "frontend"
frontend.Families = append([]assessment.BundleFamily(nil), bundle.Families...)
for index := range frontend.Families {
frontend.Families[index].Key = fmt.Sprintf("attempt-frontend-%02d", index+1)
frontend.Families[index].Specialization = "frontend"
}
if _, err := bank.ImportBundle(ctx, frontend); err != nil {
t.Fatalf("ImportBundle(frontend attempt fixture) error = %v", err)
}
publishAssessmentAttemptFixtureFamilies(ctx, t, bank, frontend)
openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("frontend"), domain.SpecializationFrontend, domain.GradeJunior)
backendIntern := fixture.reviewedBundle(int(required))
backendIntern.Name = "assessment-attempt-backend-intern-fixture"
backendIntern.Category = "backend-intern"
for index := range backendIntern.Families {
backendIntern.Families[index].Key = fmt.Sprintf("attempt-backend-intern-%02d", index+1)
}
if _, err := bank.ImportBundle(ctx, backendIntern); err != nil {
t.Fatalf("ImportBundle(backend intern attempt fixture) error = %v", err)
}
publishAssessmentAttemptFixtureFamilies(ctx, t, bank, backendIntern)
openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("backend-intern"), domain.SpecializationBackend, domain.GradeIntern)
frontendIntern := fixture.reviewedBundle(int(required))
frontendIntern.Name = "assessment-attempt-frontend-intern-fixture"
frontendIntern.Category = "frontend-intern"
for index := range frontendIntern.Families {
frontendIntern.Families[index].Key = fmt.Sprintf("attempt-frontend-intern-%02d", index+1)
frontendIntern.Families[index].Specialization = "frontend"
}
if _, err := bank.ImportBundle(ctx, frontendIntern); err != nil {
t.Fatalf("ImportBundle(frontend intern attempt fixture) error = %v", err)
}
publishAssessmentAttemptFixtureFamilies(ctx, t, bank, frontendIntern)
openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("frontend-intern"), domain.SpecializationFrontend, domain.GradeIntern)
training := fixture.reviewedBundle(int(policyVersion.Policy().Assessment.Training.DemoExpressItemCount))
training.Name = "assessment-attempt-training-fixture"
training.Category = "training-attempts"
for index := range training.Families {
training.Families[index].Key = fmt.Sprintf("attempt-training-%02d", index+1)
}
if _, err := bank.ImportBundle(ctx, training); err != nil {
t.Fatalf("ImportBundle(training attempt fixture) error = %v", err)
}
publishAssessmentAttemptFixtureFamilies(ctx, t, bank, training)
seedAssessmentAttemptTrainingBinding(ctx, t, pool, policyVersion.ID().UUID(), training.Category, len(training.Families))
}
func publishAssessmentAttemptFixtureFamilies(ctx context.Context, t *testing.T, bank *assessment.Bank, bundle assessment.Bundle) {
t.Helper()
for _, family := range bundle.Families {
if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil {
t.Fatalf("PublishFamily(%s) error = %v", family.Key, err)
}
}
}
func openAssessmentAttemptFixtureCategory(
ctx context.Context,
t *testing.T,
bank *assessment.Bank,
policyID domain.PolicyVersionID,
category domain.AssessmentCategory,
specialization domain.SpecializationCode,
grade domain.GradeCode,
) {
t.Helper()
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(specialization, grade, []domain.TaskLanguageCode{domain.TaskLanguageGo})
if err != nil {
t.Fatalf("NewAssessmentCategoryCatalogMetadata(%s) error = %v", specialization, err)
}
if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
Category: category, GradingPolicyID: policyID, OpenedBy: fixtureOpener, CatalogMetadata: &metadata,
}); err != nil {
t.Fatalf("OpenCategory(%s) error = %v", category, err)
}
}
func seedAssessmentAttemptTrainingBinding(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
policyID uuid.UUID,
category string,
itemCount int,
) {
t.Helper()
type manifestEntry struct {
FamilyKey string `json:"family_key"`
Version int32 `json:"version"`
ContentSHA256 string `json:"content_sha256"`
}
type familyRecord struct {
ID uuid.UUID
Entry manifestEntry
Hash []byte
}
rows, err := pool.Query(ctx, `
SELECT id, family_key, version, content_sha256
FROM assessment_families
WHERE category=$1 AND lifecycle='published'
ORDER BY family_key, version`, category)
if err != nil {
t.Fatalf("read published training family fixture: %v", err)
}
var families []familyRecord
for rows.Next() {
var family familyRecord
if err := rows.Scan(&family.ID, &family.Entry.FamilyKey, &family.Entry.Version, &family.Hash); err != nil {
rows.Close()
t.Fatalf("scan training family fixture: %v", err)
}
family.Entry.ContentSHA256 = hex.EncodeToString(family.Hash)
families = append(families, family)
}
if err := rows.Err(); err != nil {
rows.Close()
t.Fatalf("iterate training family fixture: %v", err)
}
rows.Close()
if len(families) != itemCount {
t.Fatalf("published training family count = %d, want %d", len(families), itemCount)
}
manifest, err := json.Marshal(func() []manifestEntry {
entries := make([]manifestEntry, len(families))
for index := range families {
entries[index] = families[index].Entry
}
return entries
}())
if err != nil {
t.Fatalf("marshal training family manifest: %v", err)
}
canonical := []byte("lincodex.assessment.category-manifest.v1\x00")
for _, family := range families {
key := []byte(family.Entry.FamilyKey)
if len(key) > 64 || family.Entry.Version < 1 || len(family.Hash) != sha256.Size {
t.Fatalf("training family manifest entry is out of range")
}
canonical = binary.BigEndian.AppendUint32(canonical, uint32(len(key)))
canonical = append(canonical, key...)
canonical = binary.BigEndian.AppendUint32(canonical, uint32(family.Entry.Version))
canonical = append(canonical, family.Hash...)
}
manifestHash := sha256.Sum256(canonical)
bindingID := uuid.New()
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatalf("begin reviewed training binding fixture: %v", err)
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `
INSERT INTO assessment_training_bank_bindings (
id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at
) VALUES ($1,$2,$3,$4,$5,$6::jsonb,'operator:fixture-reviewer',clock_timestamp())`,
bindingID, category, policyID, itemCount, manifestHash[:], manifest); err != nil {
t.Fatalf("insert reviewed training binding fixture: %v", err)
}
for index, family := range families {
if _, err := tx.Exec(ctx, `
INSERT INTO assessment_training_bank_binding_families (
binding_id, ordinal, family_id, family_key, family_version, content_sha256
) VALUES ($1,$2,$3,$4,$5,$6)`, bindingID, index+1, family.ID, family.Entry.FamilyKey, family.Entry.Version, family.Hash); err != nil {
t.Fatalf("insert reviewed training family member %s: %v", family.Entry.FamilyKey, err)
}
}
if err := tx.Commit(ctx); err != nil {
t.Fatalf("commit reviewed training binding fixture: %v", err)
}
_, err = pool.Exec(ctx, `
INSERT INTO assessment_category_openings (
id, category, policy_version_id, opened_by, required_families, published_families, opened_at
) VALUES (gen_random_uuid(), $1, $2, 'operator:fixture-opener', 1, $3, clock_timestamp())`, category, policyID, itemCount)
assertPgError(t, "open a training-only category for real assessments", err, "23514", "assessment_training_category_is_disjoint")
}
func assessmentAttemptCreateBody(t *testing.T, specialization string) string {
t.Helper()
return assessmentAttemptCreateBodyWithGrade(t, specialization, "junior")
}
func assessmentAttemptCreateBodyWithGrade(t *testing.T, specialization, grade string) string {
t.Helper()
body, err := json.Marshal(map[string]string{
"kind": "root", "specialization": specialization, "target_grade": grade, "task_language": "go",
})
if err != nil {
t.Fatalf("marshal assessment create body: %v", err)
}
return string(body)
}
func assessmentAttemptCorrectiveBody(t *testing.T, specialization, grade string, rootID uuid.UUID) string {
t.Helper()
body, err := json.Marshal(map[string]string{
"kind": "corrective", "specialization": specialization, "target_grade": grade,
"task_language": "go", "root_attempt_id": rootID.String(),
})
if err != nil {
t.Fatalf("marshal corrective attempt body: %v", err)
}
return string(body)
}
func assessmentAttemptQuestionnaireRequest(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
cookie, csrf, remoteAddr string,
) *httptest.ResponseRecorder {
t.Helper()
body, err := json.Marshal(map[string]any{
"expected_version": 0,
"specializations": []any{
map[string]any{"specialization": "backend", "self_assessed_grade": "junior", "task_languages": []string{"go"}, "stack": []string{}, "experience": nil},
map[string]any{"specialization": "frontend", "self_assessed_grade": "junior", "task_languages": []string{"go"}, "stack": []string{}, "experience": nil},
},
"work_context": map[string]any{"work_formats": []string{"remote"}},
})
if err != nil {
t.Fatalf("marshal attempt questionnaire: %v", err)
}
return assessmentAttemptHTTPRequest(t, harness, http.MethodPut, "/api/v1/me/questionnaire", string(body),
sessionHTTPTestOrigin, cookie, csrf, "", remoteAddr)
}
func grantCurrentAttemptConsent(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
cookie *http.Cookie,
csrf, remoteAddr string,
) {
t.Helper()
textResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/consent-texts/c3", "",
"", cookie.Value, "", "", remoteAddr)
var current struct {
TextVersion string `json:"text_version"`
}
if textResponse.Code != http.StatusOK || json.Unmarshal(textResponse.Body.Bytes(), &current) != nil || current.TextVersion == "" {
t.Fatalf("read current C3 text = %d %s", textResponse.Code, textResponse.Body.String())
}
grant := consentGrantHTTP(t, harness.sessionHTTPHarness, cookie, csrf, "c3", current.TextVersion, sessionHTTPTestOrigin)
if grant.Code != http.StatusOK {
t.Fatalf("grant current C3 = %d %s", grant.Code, grant.Body.String())
}
}
func assessmentAttemptHTTPRequest(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string,
) *httptest.ResponseRecorder {
return assessmentAttemptHTTPRequestWithTimeout(t, harness, method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr, 20*time.Second)
}
func assessmentAttemptHTTPRequestWithTimeout(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string,
timeout time.Duration,
) *httptest.ResponseRecorder {
t.Helper()
requestContext, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
request := httptest.NewRequest(method, path, strings.NewReader(body)).WithContext(requestContext)
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
if origin != "" {
request.Header.Set("Origin", origin)
}
if cookie != "" {
request.Header.Set("Cookie", "__Host-lincodex_session="+cookie)
}
if csrf != "" {
request.Header.Set("X-CSRF-Token", csrf)
}
if idempotencyKey != "" {
request.Header.Set("Idempotency-Key", idempotencyKey)
}
request.RemoteAddr = remoteAddr
recorder := httptest.NewRecorder()
harness.router.ServeHTTP(recorder, request)
return recorder
}
func assertAttemptCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want int64) {
t.Helper()
var got int64
if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts").Scan(&got); err != nil {
t.Fatalf("count assessment attempts: %v", err)
}
if got != want {
t.Fatalf("assessment attempt rows = %d, want %d", got, want)
}
}
func readAttemptChainTiming(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) (time.Time, time.Time) {
t.Helper()
var createdAt, deadline time.Time
if err := pool.QueryRow(ctx, `SELECT created_at, chain_deadline FROM assessment_attempts WHERE id=$1`, attemptID).Scan(&createdAt, &deadline); err != nil {
t.Fatalf("read assessment root chain deadline: %v", err)
}
return createdAt.UTC(), deadline.UTC()
}
func terminalizeAttempt(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) {
t.Helper()
command, err := pool.Exec(ctx, `
WITH stamp AS (
SELECT GREATEST(clock_timestamp(), last_activity_at) AS at
FROM assessment_attempts WHERE id=$1
)
UPDATE assessment_attempts AS attempt
SET state='completed', outcome='not_confirmed', ended_at=stamp.at,
updated_at=stamp.at, version=attempt.version+1
FROM stamp
WHERE attempt.id=$1 AND attempt.state='in_progress'`, attemptID)
if err != nil || command.RowsAffected() != 1 {
t.Fatalf("terminalize assessment attempt = %d rows, error %v", command.RowsAffected(), err)
}
}
func assertAttemptPinAndItemRowsAreImmutable(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) {
t.Helper()
_, err := pool.Exec(ctx, `
UPDATE assessment_attempts
SET product_policy_version=product_policy_version+1, version=version+1, updated_at=clock_timestamp()
WHERE id=$1`, attemptID)
assertPgError(t, "change immutable attempt policy pin", err, "23000", "assessment_attempt_pins_immutable")
_, err = pool.Exec(ctx, `
UPDATE assessment_attempt_items
SET variant=variant || '{"changed":true}'::jsonb
WHERE attempt_id=$1 AND ordinal=1`, attemptID)
assertPgError(t, "change immutable attempt item variant", err, "23000", "assessment_attempt_item_immutable")
_, err = pool.Exec(ctx, `DELETE FROM assessment_attempt_items WHERE attempt_id=$1 AND ordinal=1`, attemptID)
assertPgError(t, "delete immutable attempt item", err, "23000", "assessment_attempt_item_delete_forbidden")
}
func assertAssessmentAttemptReplay(t *testing.T, key string, original, replay *httptest.ResponseRecorder) {
t.Helper()
if original.Code != replay.Code {
t.Fatalf("create replay %s status = %d, want stored status %d", key, replay.Code, original.Code)
}
if original.Code == http.StatusCreated {
if replay.Body.String() != original.Body.String() {
t.Fatalf("created attempt replay %s body differs from its immutable response", key)
}
return
}
type stableProblem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Code string `json:"code"`
Detail string `json:"detail"`
}
var originalProblem, replayProblem stableProblem
if err := json.Unmarshal(original.Body.Bytes(), &originalProblem); err != nil {
t.Fatalf("decode original conflict response: %v", err)
}
if err := json.Unmarshal(replay.Body.Bytes(), &replayProblem); err != nil {
t.Fatalf("decode replay conflict response: %v", err)
}
if originalProblem != replayProblem || replayProblem.Code != "state_conflict" {
t.Fatalf("create replay %s stable problem = %+v, want %+v", key, replayProblem, originalProblem)
}
}
type assessmentAttemptStoredState struct {
Version int64
Sessions int32
State string
}
func readAttemptStoredState(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) assessmentAttemptStoredState {
t.Helper()
var state assessmentAttemptStoredState
err := pool.QueryRow(ctx, `
SELECT version, sessions_used, state
FROM assessment_attempts WHERE id = $1`, attemptID).Scan(&state.Version, &state.Sessions, &state.State)
if err != nil {
t.Fatalf("read stored assessment attempt state: %v", err)
}
return state
}
func waitForAssessmentAttemptRowLock(t *testing.T, ctx context.Context, pool *pgxpool.Pool, blockingPID int32) {
t.Helper()
deadline := time.Now().Add(20 * time.Second)
for time.Now().Before(deadline) {
var waiting int64
err := pool.QueryRow(ctx, `
SELECT count(*)
FROM pg_stat_activity
WHERE wait_event_type='Lock'
AND $1 = ANY(pg_blocking_pids(pid))
AND query ILIKE '%assessment_attempts%'`, blockingPID).Scan(&waiting)
if err != nil {
t.Fatalf("inspect blocked attempt session request: %v", err)
}
if waiting > 0 {
return
}
select {
case <-ctx.Done():
t.Fatalf("wait for attempt row lock: %v", ctx.Err())
case <-time.After(50 * time.Millisecond):
}
}
t.Fatal("session command never waited on the locked assessment_attempts row")
}
func waitForAttemptIdleDeadline(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) {
t.Helper()
deadline := time.Now().Add(90 * time.Second)
for time.Now().Before(deadline) {
var expired bool
err := pool.QueryRow(ctx, `
SELECT last_activity_at + idle_timeout_seconds * interval '1 second' <= clock_timestamp()
FROM assessment_attempts WHERE id=$1`, attemptID).Scan(&expired)
if err != nil {
t.Fatalf("read attempt idle deadline: %v", err)
}
if expired {
return
}
select {
case <-ctx.Done():
t.Fatalf("wait for attempt idle deadline: %v", ctx.Err())
case <-time.After(100 * time.Millisecond):
}
}
t.Fatal("assessment attempt idle deadline did not pass during the row lock")
}