feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

@@ -0,0 +1,461 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/domain"
)
func TestAssessmentAnswerAndResultPersistAcrossRouterReconstruction(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)
}
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "answer-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(), "203.0.113.40:1234")
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK {
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234")
create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf,
"answer-flow-create", "203.0.113.43:1234")
if create.Code != http.StatusCreated {
t.Fatalf("create real attempt = %d %s; logs: %s", create.Code, create.Body.String(), harness.logs.String())
}
var publicAttempt assessmentAnswerHTTPAttempt
if err := json.Unmarshal(create.Body.Bytes(), &publicAttempt); err != nil || publicAttempt.ID == uuid.Nil || publicAttempt.CurrentItem == nil {
t.Fatalf("created attempt = %+v, decode error %v", publicAttempt, err)
}
items := readAssessmentAnswerHTTPItems(t, ctx, harness, publicAttempt.ID)
if len(items) < 2 || items[0].ID != publicAttempt.CurrentItem.ID {
t.Fatalf("frozen item count/current item = %d/%s, want ordered item list starting at current item", len(items), publicAttempt.CurrentItem.ID)
}
finalizePath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String() + "/finalize"
finalizeBody, err := json.Marshal(map[string]int64{"expected_version": publicAttempt.Version})
if err != nil {
t.Fatalf("marshal early finalize: %v", err)
}
earlyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234")
var pendingProblem struct {
Code string `json:"code"`
PendingItemIDs []uuid.UUID `json:"pending_item_ids"`
}
if earlyFinalize.Code != http.StatusConflict || json.Unmarshal(earlyFinalize.Body.Bytes(), &pendingProblem) != nil ||
pendingProblem.Code != "state_conflict" || len(pendingProblem.PendingItemIDs) != len(items) {
t.Fatalf("early finalize = %d %s, want state_conflict with %d pending item IDs", earlyFinalize.Code, earlyFinalize.Body.String(), len(items))
}
for index, item := range items {
if pendingProblem.PendingItemIDs[index] != item.ID {
t.Fatalf("pending item %d = %s, want frozen item %s", index, pendingProblem.PendingItemIDs[index], item.ID)
}
}
finalizeReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234")
if finalizeReplay.Code != earlyFinalize.Code ||
assessmentHTTPBodyWithoutTraceID(t, finalizeReplay.Body.String()) != assessmentHTTPBodyWithoutTraceID(t, earlyFinalize.Body.String()) {
t.Fatalf("early finalize replay = %d %s, want stored %d %s", finalizeReplay.Code, finalizeReplay.Body.String(), earlyFinalize.Code, earlyFinalize.Body.String())
}
firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, publicAttempt.Version, items[0], false)
withClientScore := strings.TrimSuffix(string(firstAnswer), "}") + `,"score":100}`
clientScore := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", withClientScore,
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
if clientScore.Code != http.StatusBadRequest {
t.Fatalf("answer with client score = %d %s, want rejected request", clientScore.Code, clientScore.Body.String())
}
answerScope := harness.keyring.IdempotencyScope("assessment_attempt.answer", "answer-flow-first", candidate.ID.String())
var badScoreOutcomeCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash=$1", answerScope[:]).Scan(&badScoreOutcomeCount); err != nil || badScoreOutcomeCount != 0 {
t.Fatalf("invalid client score reserved idempotency row count=%d error=%v, want zero", badScoreOutcomeCount, err)
}
firstAccepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
var firstSnapshot assessmentAnswerHTTPAttempt
if firstAccepted.Code != http.StatusOK || json.Unmarshal(firstAccepted.Body.Bytes(), &firstSnapshot) != nil ||
firstSnapshot.Version != publicAttempt.Version+1 || firstSnapshot.CurrentItem == nil || firstSnapshot.CurrentItem.ID != items[1].ID {
t.Fatalf("first answer = %d %s, want next frozen item and incremented version", firstAccepted.Code, firstAccepted.Body.String())
}
storedAnswer, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID)
if len(storedAnswer) == 0 || answeredAt.IsZero() {
t.Fatalf("first answer storage = bytes %d, answered_at %s; want canonical answer and server time", len(storedAnswer), answeredAt)
}
answerReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234")
if answerReplay.Code != firstAccepted.Code || answerReplay.Body.String() != firstAccepted.Body.String() {
t.Fatalf("answer replay = %d %s, want stored %d %s", answerReplay.Code, answerReplay.Body.String(), firstAccepted.Code, firstAccepted.Body.String())
}
// A reconstructed service graph and router read the committed answer and
// its server timestamp from PostgreSQL, not the old handler's memory.
harness.pool.Close()
harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
readPath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String()
reconstructedRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, readPath, "", "",
cookie.Value, "", "", "203.0.113.46:1234")
var reconstructedAttempt assessmentAnswerHTTPAttempt
if reconstructedRead.Code != http.StatusOK || json.Unmarshal(reconstructedRead.Body.Bytes(), &reconstructedAttempt) != nil ||
reconstructedAttempt.Version != firstSnapshot.Version || reconstructedAttempt.CurrentItem == nil ||
reconstructedAttempt.CurrentItem.ID != firstSnapshot.CurrentItem.ID {
t.Fatalf("GET after router reconstruction = %d %s, want version %d and item %s", reconstructedRead.Code, reconstructedRead.Body.String(), firstSnapshot.Version, firstSnapshot.CurrentItem.ID)
}
reconstructedAnswer, reconstructedAnsweredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID)
if string(reconstructedAnswer) != string(storedAnswer) || !reconstructedAnsweredAt.Equal(answeredAt) {
t.Fatalf("answer after router reconstruction differs: bytes equal=%v timestamp=%s want %s", string(reconstructedAnswer) == string(storedAnswer), reconstructedAnsweredAt, answeredAt)
}
currentVersion := reconstructedAttempt.Version
for _, item := range items[1:] {
body := assessmentAnswerHTTPBody(t, currentVersion, item)
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(body),
sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-item-%d", item.Ordinal),
fmt.Sprintf("203.0.113.%d:1234", 50+item.Ordinal))
var next assessmentAnswerHTTPAttempt
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != currentVersion+1 {
t.Fatalf("answer frozen item %d = %d %s, want version %d", item.Ordinal, response.Code, response.Body.String(), currentVersion+1)
}
if item.Ordinal < int32(len(items)) && (next.CurrentItem == nil || next.CurrentItem.ID != items[item.Ordinal].ID) {
t.Fatalf("answer item %d returned current item %+v, want %s", item.Ordinal, next.CurrentItem, items[item.Ordinal].ID)
}
if item.Ordinal == int32(len(items)) && (next.State != "ready_to_finalize" || next.CurrentItem != nil) {
t.Fatalf("final answer returned state=%s current_item=%+v, want ready_to_finalize", next.State, next.CurrentItem)
}
currentVersion = next.Version
}
finalizeBody, err = json.Marshal(map[string]int64{"expected_version": currentVersion})
if err != nil {
t.Fatalf("marshal finalization: %v", err)
}
finalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.90:1234")
var completed assessmentAnswerHTTPAttempt
if finalized.Code != http.StatusOK || json.Unmarshal(finalized.Body.Bytes(), &completed) != nil || completed.State != "completed" {
t.Fatalf("finalize complete attempt = %d %s, want completed", finalized.Code, finalized.Body.String())
}
resultPath := readPath + "/result"
resultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "",
cookie.Value, "", "", "203.0.113.91:1234")
var realResult map[string]any
if resultResponse.Code != http.StatusOK || json.Unmarshal(resultResponse.Body.Bytes(), &realResult) != nil ||
realResult["attempt_id"] != publicAttempt.ID.String() || realResult["outcome"] != "confirmed" {
t.Fatalf("read completed result = %d %s, want persisted confirmed result", resultResponse.Code, resultResponse.Body.String())
}
score, ok := realResult["basic_score"].(map[string]any)
points, pointsOK := score["points"].(float64)
maxPoints, maxPointsOK := score["max_points"].(float64)
if !ok || !pointsOK || !maxPointsOK || points != maxPoints-1 || score["pass_points"] == nil {
t.Fatalf("real result basic score = %#v, want one incorrect server-scored item", realResult["basic_score"])
}
sameKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.94:1234")
if sameKeyFinalize.Code != finalized.Code || sameKeyFinalize.Body.String() != finalized.Body.String() {
t.Fatalf("completed finalize replay = %d %s, want stored %d %s", sameKeyFinalize.Code, sameKeyFinalize.Body.String(), finalized.Code, finalized.Body.String())
}
newFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": completed.Version})
if err != nil {
t.Fatalf("marshal completed finalize retry: %v", err)
}
newKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(newFinalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize-again", "203.0.113.95:1234")
if newKeyFinalize.Code != finalized.Code || newKeyFinalize.Body.String() != finalized.Body.String() {
t.Fatalf("new-key completed finalize = %d %s, want existing terminal projection %d %s", newKeyFinalize.Code, newKeyFinalize.Body.String(), finalized.Code, finalized.Body.String())
}
var resultRowCount int64
var persistedVersion int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempt_results WHERE attempt_id=$1", publicAttempt.ID).Scan(&resultRowCount); err != nil {
t.Fatalf("count immutable result rows: %v", err)
}
if err := harness.pool.QueryRow(ctx, "SELECT version FROM assessment_attempts WHERE id=$1", publicAttempt.ID).Scan(&persistedVersion); err != nil {
t.Fatalf("read finalized attempt version: %v", err)
}
if resultRowCount != 1 || persistedVersion != completed.Version {
t.Fatalf("finalize retries left %d result rows and version %d, want one row and version %d", resultRowCount, persistedVersion, completed.Version)
}
resultSnapshot, productPolicyID, openingID, rawScore, passMark, rawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, publicAttempt.ID)
if resultSnapshot["outcome"] != "confirmed" || !rawScoreValid || rawScore != int16(score["points"].(float64)) {
t.Fatalf("stored result outcome/score = %v/%d (valid %v), API result = %v/%v", resultSnapshot["outcome"], rawScore, rawScoreValid, realResult["outcome"], score["points"])
}
pins, ok := resultSnapshot["pins"].(map[string]any)
if !ok || pins["product_policy_version_id"] != productPolicyID.String() || pins["opening_id"] != openingID.String() ||
!strings.Contains(stringMustJSON(t, resultSnapshot), `"product_policy_version_id":"`+productPolicyID.String()+`"`) {
t.Fatalf("stored result pin IDs are not UUID strings: %#v", resultSnapshot["pins"])
}
if passMark < 1 || strings.Contains(resultResponse.Body.String(), "ReferenceAnswer") || strings.Contains(resultResponse.Body.String(), "answer_key") {
t.Fatalf("result exposed private source or lost its stored pass mark: body=%s pass_mark=%d", resultResponse.Body.String(), passMark)
}
// The result projection is read from the immutable stored snapshot after a
// second router/pool reconstruction and stays byte-for-byte stable.
harness.pool.Close()
harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
restartedResult := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "",
cookie.Value, "", "", "203.0.113.92:1234")
if restartedResult.Code != http.StatusOK || restartedResult.Body.String() != resultResponse.Body.String() {
t.Fatalf("result after router reconstruction = %d %s, want stored projection %s", restartedResult.Code, restartedResult.Body.String(), resultResponse.Body.String())
}
var rootAttemptsBeforeExpress int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsBeforeExpress); err != nil {
t.Fatalf("count real attempts before express completion: %v", err)
}
trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`,
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-create", "203.0.113.93:1234")
var training assessmentAnswerHTTPAttempt
if trainingCreate.Code != http.StatusCreated || json.Unmarshal(trainingCreate.Body.Bytes(), &training) != nil || training.ID == uuid.Nil {
t.Fatalf("create express attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String())
}
trainingItems := readAssessmentAnswerHTTPItems(t, ctx, harness, training.ID)
trainingVersion := training.Version
for _, item := range trainingItems {
body := assessmentAnswerHTTPBody(t, trainingVersion, item)
response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/answers", string(body),
sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-express-%d", item.Ordinal),
fmt.Sprintf("203.0.113.%d:1234", 100+item.Ordinal))
var next assessmentAnswerHTTPAttempt
if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != trainingVersion+1 {
t.Fatalf("answer express item %d = %d %s", item.Ordinal, response.Code, response.Body.String())
}
trainingVersion = next.Version
}
trainingFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": trainingVersion})
if err != nil {
t.Fatalf("marshal express finalization: %v", err)
}
trainingFinalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/finalize", string(trainingFinalizeBody),
sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-finalize", "203.0.113.110:1234")
if trainingFinalized.Code != http.StatusOK {
t.Fatalf("finalize express attempt = %d %s", trainingFinalized.Code, trainingFinalized.Body.String())
}
trainingResultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet,
"/api/v1/me/assessment-attempts/"+training.ID.String()+"/result", "", "", cookie.Value, "", "", "203.0.113.111:1234")
var trainingResult map[string]any
if trainingResultResponse.Code != http.StatusOK || json.Unmarshal(trainingResultResponse.Body.Bytes(), &trainingResult) != nil ||
trainingResult["outcome"] != "demonstration" || trainingResult["mode"] != "demo_express" ||
trainingResult["basic_score"] != nil || trainingResult["confirmed_grade"] != nil || trainingResult["specialization"] != nil {
t.Fatalf("express result = %d %s, want demonstration without score or grade", trainingResultResponse.Code, trainingResultResponse.Body.String())
}
_, _, _, expressRawScore, _, expressRawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, training.ID)
if expressRawScoreValid {
t.Fatalf("express result stored raw score %d, want SQL NULL", expressRawScore)
}
var rootAttemptsAfterExpress int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsAfterExpress); err != nil {
t.Fatalf("count real attempts after express completion: %v", err)
}
if rootAttemptsAfterExpress != rootAttemptsBeforeExpress {
t.Fatalf("express completion changed real root quota count from %d to %d", rootAttemptsBeforeExpress, rootAttemptsAfterExpress)
}
}
type assessmentAnswerHTTPAttempt struct {
ID uuid.UUID `json:"id"`
Version int64 `json:"version"`
State string `json:"state"`
CurrentItem *struct {
ID uuid.UUID `json:"id"`
} `json:"current_item"`
}
type assessmentAnswerHTTPItem struct {
ID uuid.UUID
Ordinal int32
Variant domain.AssessmentVariant
}
func readAssessmentAnswerHTTPItems(
t *testing.T,
ctx context.Context,
harness *assessmentAttemptHTTPHarness,
attemptID uuid.UUID,
) []assessmentAnswerHTTPItem {
t.Helper()
rows, err := harness.pool.Query(ctx, `SELECT id, ordinal, variant FROM assessment_attempt_items WHERE attempt_id=$1 ORDER BY ordinal`, attemptID)
if err != nil {
t.Fatalf("read frozen assessment items: %v", err)
}
defer rows.Close()
items := make([]assessmentAnswerHTTPItem, 0)
for rows.Next() {
var item assessmentAnswerHTTPItem
var encoded []byte
if err := rows.Scan(&item.ID, &item.Ordinal, &encoded); err != nil {
t.Fatalf("scan frozen assessment item: %v", err)
}
item.Variant, err = domain.UnmarshalAssessmentAttemptVariant(encoded)
if err != nil {
t.Fatalf("restore frozen assessment variant: %v", err)
}
items = append(items, item)
}
if err := rows.Err(); err != nil {
t.Fatalf("iterate frozen assessment items: %v", err)
}
return items
}
func readAssessmentAnswerHTTPItem(
t *testing.T,
ctx context.Context,
harness *assessmentAttemptHTTPHarness,
attemptID, itemID uuid.UUID,
) ([]byte, time.Time) {
t.Helper()
var answer []byte
var answeredAt time.Time
if err := harness.pool.QueryRow(ctx, `SELECT answer, answered_at FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2`,
attemptID, itemID).Scan(&answer, &answeredAt); err != nil {
t.Fatalf("read stored answer and server time: %v", err)
}
return answer, answeredAt.UTC()
}
func assessmentAnswerHTTPBody(t *testing.T, version int64, item assessmentAnswerHTTPItem) []byte {
return assessmentAnswerHTTPBodyWithCorrectness(t, version, item, true)
}
func assessmentAnswerHTTPBodyWithCorrectness(
t *testing.T,
version int64,
item assessmentAnswerHTTPItem,
wantCorrect bool,
) []byte {
t.Helper()
var answer []byte
switch item.Variant.AnswerFormat {
case domain.AnswerFormatInteger:
reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64)
if err != nil {
t.Fatalf("parse frozen answer key %q: %v", item.Variant.ReferenceAnswer, err)
}
if !wantCorrect {
reference++
}
answer = []byte(fmt.Sprintf(`{"format":"number","number":%d}`, reference))
case domain.AnswerFormatIntegerSequence:
parts := strings.Fields(item.Variant.ReferenceAnswer)
if !wantCorrect && len(parts) < 2 {
t.Fatalf("frozen sequence answer %q has fewer than two tasks", item.Variant.ReferenceAnswer)
}
elements := make([]string, 0, len(parts))
for _, part := range parts {
elements = append(elements, "job_"+part)
}
if !wantCorrect {
elements[0], elements[1] = elements[1], elements[0]
}
var err error
answer, err = json.Marshal(struct {
Format string `json:"format"`
ElementIDs []string `json:"element_ids"`
}{Format: "order", ElementIDs: elements})
if err != nil {
t.Fatalf("marshal order answer: %v", err)
}
default:
t.Fatalf("unsupported fixture answer format %q", item.Variant.AnswerFormat)
}
_, correct, err := domain.CanonicalAssessmentAnswerForVariant(answer, item.Variant)
if err != nil || correct != wantCorrect {
t.Fatalf("fixture answer for item %s has correctness %v, want %v: error %v", item.ID, correct, wantCorrect, err)
}
body, err := json.Marshal(struct {
ExpectedVersion int64 `json:"expected_version"`
ItemID uuid.UUID `json:"item_id"`
Answer json.RawMessage `json:"answer"`
}{ExpectedVersion: version, ItemID: item.ID, Answer: answer})
if err != nil {
t.Fatalf("marshal answer command: %v", err)
}
return body
}
func readAssessmentAttemptHTTPResult(
t *testing.T,
ctx context.Context,
harness *assessmentAttemptHTTPHarness,
attemptID uuid.UUID,
) (map[string]any, uuid.UUID, uuid.UUID, int16, int32, bool) {
t.Helper()
var encoded []byte
var productPolicyID uuid.UUID
var storedOpeningID pgtype.UUID
var rawScore pgtype.Int2
var passMark pgtype.Int4
if err := harness.pool.QueryRow(ctx, `
SELECT result_snapshot, product_policy_version_id, opening_id, raw_score, pass_mark_basis_points
FROM assessment_attempt_results WHERE attempt_id=$1`, attemptID).
Scan(&encoded, &productPolicyID, &storedOpeningID, &rawScore, &passMark); err != nil {
t.Fatalf("read immutable assessment result row: %v", err)
}
var openingID uuid.UUID
if storedOpeningID.Valid {
openingID = uuid.UUID(storedOpeningID.Bytes)
}
var document map[string]any
if err := json.Unmarshal(encoded, &document); err != nil {
t.Fatalf("decode immutable assessment result document: %v", err)
}
if !rawScore.Valid || !passMark.Valid {
return document, productPolicyID, openingID, 0, 0, rawScore.Valid
}
return document, productPolicyID, openingID, rawScore.Int16, passMark.Int32, rawScore.Valid
}
func stringMustJSON(t *testing.T, value any) string {
t.Helper()
encoded, err := json.Marshal(value)
if err != nil {
t.Fatalf("marshal result snapshot for assertion: %v", err)
}
return string(encoded)
}
func assessmentHTTPBodyWithoutTraceID(t *testing.T, body string) string {
t.Helper()
var document map[string]json.RawMessage
if err := json.Unmarshal([]byte(body), &document); err != nil {
t.Fatalf("decode HTTP problem response: %v", err)
}
delete(document, "trace_id")
encoded, err := json.Marshal(document)
if err != nil {
t.Fatalf("marshal HTTP problem response: %v", err)
}
return string(encoded)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,509 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/assessment"
assessmentpolicy "lincodex/backend/internal/usecase/policy"
)
type assessmentAvailabilityHTTPGrade struct {
Grade string `json:"grade"`
Status string `json:"status"`
Mode *string `json:"mode"`
TimeLimitSeconds *int32 `json:"time_limit_seconds"`
MaxSessions *int32 `json:"max_sessions"`
MaxItems *int32 `json:"max_items"`
PracticeRequired *bool `json:"practice_required"`
}
type assessmentAvailabilityHTTPSpecialization struct {
Specialization string `json:"specialization"`
ActiveAttempt *uuid.UUID `json:"active_attempt_id"`
Grades []assessmentAvailabilityHTTPGrade `json:"grades"`
}
type assessmentAvailabilityHTTPProjection struct {
Specializations []assessmentAvailabilityHTTPSpecialization `json:"specializations"`
}
func TestAssessmentAvailabilityHTTPIsCandidateScopedAndReadOnly(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)
}
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-http-candidate@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)
}
candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.50:1234")
unauthenticated := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", "", "", "", "203.0.113.51:1234")
requireSessionProblem(t, unauthenticated, http.StatusUnauthorized, "unauthenticated")
employer := createAssessmentAvailabilityEmployer(ctx, t, harness.sessionHTTPHarness, "availability-http-employer@example.test", passwordHash)
employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "203.0.113.52:1234")
employerRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", employerCookie.Value, "", "", "203.0.113.53:1234")
requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden")
path := "/api/v1/me/assessment-availability"
emptyRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.54:1234")
var emptyProjection struct {
Specializations []json.RawMessage `json:"specializations"`
}
if emptyRead.Code != http.StatusOK || emptyRead.Header().Get("Cache-Control") != "no-store" ||
json.Unmarshal(emptyRead.Body.Bytes(), &emptyProjection) != nil || emptyProjection.Specializations == nil || len(emptyProjection.Specializations) != 0 {
t.Fatalf("availability before questionnaire = %d %s, Cache-Control=%q, want empty candidate projection",
emptyRead.Code, emptyRead.Body.String(), emptyRead.Header().Get("Cache-Control"))
}
if response := assessmentAttemptQuestionnaireRequest(t, harness, candidateCookie.Value, candidateCSRF, "203.0.113.55:1234"); response.Code != http.StatusOK {
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "203.0.113.56:1234")
available := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.57:1234")
var initial assessmentAvailabilityHTTPProjection
if available.Code != http.StatusOK || available.Header().Get("Cache-Control") != "no-store" ||
json.Unmarshal(available.Body.Bytes(), &initial) != nil || len(initial.Specializations) != 2 {
t.Fatalf("availability after questionnaire = %d %s, Cache-Control=%q, want both saved specializations",
available.Code, available.Body.String(), available.Header().Get("Cache-Control"))
}
backend := findAssessmentAvailabilitySpecialization(t, initial, "backend")
for _, target := range []string{"intern", "junior"} {
grade := findAssessmentAvailabilityGrade(t, backend, target)
if grade.Status != "available" || grade.Mode == nil || *grade.Mode != "demo_basic" ||
grade.TimeLimitSeconds == nil || *grade.TimeLimitSeconds != 72*60*60 ||
grade.MaxSessions == nil || *grade.MaxSessions != 1 || grade.MaxItems == nil || *grade.MaxItems != 13 ||
grade.PracticeRequired == nil || *grade.PracticeRequired {
t.Fatalf("backend %s availability = %+v, response=%s, want the published demo_basic start limits",
target, grade, available.Body.String())
}
}
// The questionnaire self-assesses junior, while this request selects the
// offered intern bank. The stored questionnaire grade is not a target gate.
created := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBodyWithGrade(t, "backend", "intern"), sessionHTTPTestOrigin,
candidateCookie.Value, candidateCSRF, "availability-create-different-grade", "203.0.113.58:1234")
var activeAttempt assessmentAnswerHTTPAttempt
if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &activeAttempt) != nil || activeAttempt.ID == uuid.Nil {
t.Fatalf("create attempt at offered grade different from self-assessment = %d %s", created.Code, created.Body.String())
}
// Re-login immediately before the read-only measurement so the session
// activity coalescing window cannot obscure a write caused by the GET.
candidateCookie, candidateCSRF = loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.59:1234")
token, err := domain.ParseSecretToken(candidateCookie.Value)
if err != nil {
t.Fatalf("parse synthetic session token for state comparison: %v", err)
}
tokenHash := token.Hash()
type availabilityReadState struct {
attemptVersion int64
sessionsUsed int32
updatedAt time.Time
sessionSeenAt time.Time
attemptRows int64
itemRows int64
answeredItems int64
idempotency int64
}
readAvailabilityState := func() availabilityReadState {
t.Helper()
var state availabilityReadState
if err := harness.pool.QueryRow(ctx, "SELECT version, sessions_used, updated_at FROM assessment_attempts WHERE id=$1", activeAttempt.ID).
Scan(&state.attemptVersion, &state.sessionsUsed, &state.updatedAt); err != nil {
t.Fatalf("read attempt state before/after availability: %v", err)
}
if err := harness.pool.QueryRow(ctx, "SELECT last_seen_at FROM sessions WHERE token_hash=$1", tokenHash[:]).Scan(&state.sessionSeenAt); err != nil {
t.Fatalf("read session activity before/after availability: %v", err)
}
if err := harness.pool.QueryRow(ctx, `
SELECT (SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'),
(SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2),
(SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2 AND answered_at IS NOT NULL),
(SELECT count(*) FROM idempotency_records)`, candidate.ID, activeAttempt.ID).
Scan(&state.attemptRows, &state.itemRows, &state.answeredItems, &state.idempotency); err != nil {
t.Fatalf("read attempt/quota state before/after availability: %v", err)
}
return state
}
before := readAvailabilityState()
for index := 0; index < 2; index++ {
response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.60:1234")
var current assessmentAvailabilityHTTPProjection
if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" ||
json.Unmarshal(response.Body.Bytes(), &current) != nil {
t.Fatalf("repeated availability GET %d = %d %s, Cache-Control=%q", index+1, response.Code,
response.Body.String(), response.Header().Get("Cache-Control"))
}
backend = findAssessmentAvailabilitySpecialization(t, current, "backend")
if backend.ActiveAttempt == nil || *backend.ActiveAttempt != activeAttempt.ID {
t.Fatalf("repeated availability GET %d active attempt = %v, want %s", index+1, backend.ActiveAttempt, activeAttempt.ID)
}
for _, grade := range backend.Grades {
if grade.Status != "active_attempt" {
t.Fatalf("backend grade %s status = %q while an attempt is active", grade.Grade, grade.Status)
}
}
}
after := readAvailabilityState()
if before.attemptVersion != after.attemptVersion || before.sessionsUsed != after.sessionsUsed ||
!before.updatedAt.Equal(after.updatedAt) || !before.sessionSeenAt.Equal(after.sessionSeenAt) ||
before.attemptRows != after.attemptRows || before.itemRows != after.itemRows ||
before.answeredItems != after.answeredItems || before.idempotency != after.idempotency {
t.Fatalf("availability GET wrote state: before=%+v after=%+v", before, after)
}
adaptive := domain.DemoProductPolicyV2()
adaptive.Assessment.Calibration = domain.AssessmentCalibrationCalibrated
adaptive.Assessment.Attempt.RealMode = domain.AssessmentRealModeAdaptive
adaptive.Assessment.Attempt.BasicPassMark = 0
publisher := assessmentpolicy.NewPublisher(postgres.NewPolicyStore(harness.pool).Policies(), time.Now)
adaptiveVersion, err := publisher.Publish(ctx, assessmentpolicy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: adaptive,
})
if err != nil {
t.Fatalf("publish explicit adaptive policy for unavailable-mode check: %v", err)
}
adaptiveBank := assessment.NewBank(postgres.NewTransactor(harness.pool))
adaptiveFixture := assessmentFixture{
ctx: ctx, pool: harness.pool, store: postgres.NewAssessmentBankStore(harness.pool),
transactor: postgres.NewTransactor(harness.pool), bank: adaptiveBank,
demoBundle: loadDemoBundleFile(t),
}
adaptiveRequired, err := domain.RequiredPublishedAssessmentFamilies(adaptiveVersion.Policy())
if err != nil {
t.Fatalf("read adaptive policy family requirement: %v", err)
}
var publishedBackendFamilies int32
if err := harness.pool.QueryRow(ctx, `
SELECT count(DISTINCT family_key)::integer
FROM assessment_families
WHERE category='backend' AND lifecycle='published' AND review_status='approved'`).Scan(&publishedBackendFamilies); err != nil {
t.Fatalf("count current backend families for adaptive opening: %v", err)
}
if publishedBackendFamilies < adaptiveRequired {
adaptiveBundle := adaptiveFixture.reviewedBundle(int(adaptiveRequired - publishedBackendFamilies))
adaptiveBundle.Name = "availability-adaptive-backend"
adaptiveBundle.Category = "backend"
for index := range adaptiveBundle.Families {
adaptiveBundle.Families[index].Key = fmt.Sprintf("availability-adaptive-backend-%02d", index+1)
adaptiveBundle.Families[index].Specialization = string(domain.SpecializationBackend)
}
if _, err := adaptiveBank.ImportBundle(ctx, adaptiveBundle); err != nil {
t.Fatalf("import additional reviewed backend families for adaptive opening: %v", err)
}
publishAssessmentAttemptFixtureFamilies(ctx, t, adaptiveBank, adaptiveBundle)
}
openAssessmentAttemptFixtureCategory(
ctx, t, adaptiveBank, adaptiveVersion.ID(), domain.AssessmentCategory("backend"),
domain.SpecializationBackend, domain.GradeJunior,
)
adaptiveCandidate := createSessionHTTPUser(
ctx, t, harness.sessionHTTPHarness, "availability-adaptive-candidate@example.test", passwordHash, true,
)
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", adaptiveCandidate.ID); err != nil {
t.Fatalf("set adaptive candidate onboarding step: %v", err)
}
adaptiveCookie, adaptiveCSRF := loginConsentHTTP(
t, harness.sessionHTTPHarness, adaptiveCandidate.Email.Address(), "203.0.113.63:1234",
)
if response := assessmentAvailabilityBackendQuestionnaireRequest(t, harness, adaptiveCookie.Value, adaptiveCSRF, "203.0.113.64:1234"); response.Code != http.StatusOK {
t.Fatalf("save adaptive candidate questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness, adaptiveCookie, adaptiveCSRF, "203.0.113.65:1234")
unsupported := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", adaptiveCookie.Value, "", "", "203.0.113.66:1234")
requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented")
var rootCountBefore, idempotencyBefore int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID).
Scan(&rootCountBefore); err != nil {
t.Fatalf("read adaptive candidate root attempt count before denied POST: %v", err)
}
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyBefore); err != nil {
t.Fatalf("read idempotency count before denied adaptive POST: %v", err)
}
adaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin,
adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.67:1234")
requireSessionProblem(t, adaptiveCreate, http.StatusConflict, "state_conflict")
var rootCountAfter int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID).
Scan(&rootCountAfter); err != nil {
t.Fatalf("read root attempts after unsupported adaptive create: %v", err)
}
var idempotencyAfter int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfter); err != nil {
t.Fatalf("read idempotency count after denied adaptive POST: %v", err)
}
if rootCountAfter != rootCountBefore {
t.Fatalf("unsupported adaptive create changed root attempt count from %d to %d", rootCountBefore, rootCountAfter)
}
if idempotencyAfter != idempotencyBefore+1 {
t.Fatalf("unsupported adaptive create idempotency row count = %d, want one immutable 409 outcome after %d", idempotencyAfter, idempotencyBefore)
}
replayedAdaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin,
adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.68:1234")
requireSessionProblem(t, replayedAdaptiveCreate, http.StatusConflict, "state_conflict")
var idempotencyAfterReplay int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfterReplay); err != nil {
t.Fatalf("read idempotency count after adaptive 409 replay: %v", err)
}
if idempotencyAfterReplay != idempotencyAfter {
t.Fatalf("adaptive 409 replay added idempotency rows: before replay=%d after=%d", idempotencyAfter, idempotencyAfterReplay)
}
}
func assessmentAvailabilityBackendQuestionnaireRequest(
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,
},
},
"work_context": map[string]any{"work_formats": []string{"remote"}},
})
if err != nil {
t.Fatalf("marshal backend-only adaptive questionnaire: %v", err)
}
return assessmentAttemptHTTPRequest(t, harness, http.MethodPut, "/api/v1/me/questionnaire", string(body),
sessionHTTPTestOrigin, cookie, csrf, "", remoteAddr)
}
func createAssessmentAvailabilityEmployer(
ctx context.Context,
t *testing.T,
harness *sessionHTTPHarness,
email string,
passwordHash domain.PasswordHash,
) domain.User {
t.Helper()
address, err := domain.NewEmailAddress(email)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
user, err := domain.NewUser(domain.Registration{
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer,
RegisteredAt: harness.clock.Now().Truncate(time.Microsecond),
})
if err != nil {
t.Fatalf("NewUser(employer) error = %v", err)
}
if err := harness.store.Users().Create(ctx, user); err != nil {
t.Fatalf("Create synthetic employer: %v", err)
}
verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion,
harness.clock.Now().Add(time.Microsecond))
if err != nil {
t.Fatalf("MarkEmailVerified(employer) error = %v", err)
}
return verified
}
func findAssessmentAvailabilitySpecialization(
t *testing.T,
availability assessmentAvailabilityHTTPProjection,
want string,
) assessmentAvailabilityHTTPSpecialization {
t.Helper()
for _, specialization := range availability.Specializations {
if specialization.Specialization == want {
return specialization
}
}
t.Fatalf("availability does not contain specialization %q", want)
return assessmentAvailabilityHTTPSpecialization{}
}
func findAssessmentAvailabilityGrade(
t *testing.T,
specialization assessmentAvailabilityHTTPSpecialization,
want string,
) assessmentAvailabilityHTTPGrade {
t.Helper()
for _, grade := range specialization.Grades {
if grade.Grade == want {
return grade
}
}
t.Fatalf("availability for %q does not contain grade %q", specialization.Specialization, want)
return assessmentAvailabilityHTTPGrade{}
}
func TestAssessmentDisclosedFamilyCutoffUsesItemDisclosureTime(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)
}
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-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(), "203.0.113.40:1234")
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK {
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234")
create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf,
"availability-disclosure-create", "203.0.113.43:1234")
var attempt assessmentAnswerHTTPAttempt
if create.Code != http.StatusCreated || json.Unmarshal(create.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil {
t.Fatalf("create real attempt = %d %s", create.Code, create.Body.String())
}
items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID)
if len(items) < 3 {
t.Fatalf("frozen item count = %d, want at least three items", len(items))
}
var createdAt time.Time
if err := harness.pool.QueryRow(ctx, "SELECT created_at FROM assessment_attempts WHERE id=$1", attempt.ID).Scan(&createdAt); err != nil {
t.Fatalf("read attempt creation time: %v", err)
}
since := createdAt.UTC().Add(time.Microsecond)
firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, attempt.Version, items[0], false)
accepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(firstAnswer),
sessionHTTPTestOrigin, cookie.Value, csrf, "availability-disclosure-answer", "203.0.113.44:1234")
if accepted.Code != http.StatusOK {
t.Fatalf("answer first item = %d %s", accepted.Code, accepted.Body.String())
}
_, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, attempt.ID, items[0].ID)
if !answeredAt.After(since) {
t.Fatalf("first answer timestamp %s must be after cutoff %s to establish distinct disclosure times", answeredAt, since)
}
familyKey := func(itemID uuid.UUID) domain.AssessmentFamilyKey {
t.Helper()
var stored string
if err := harness.pool.QueryRow(ctx, "SELECT family_key FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2", attempt.ID, itemID).Scan(&stored); err != nil {
t.Fatalf("read frozen item family key: %v", err)
}
key, err := domain.ParseAssessmentFamilyKey(stored)
if err != nil {
t.Fatalf("parse frozen item family key: %v", err)
}
return key
}
firstKey, secondKey, thirdKey := familyKey(items[0].ID), familyKey(items[1].ID), familyKey(items[2].ID)
var disclosed []domain.AssessmentFamilyKey
transactor := postgres.NewTransactor(harness.pool)
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
var readErr error
disclosed, readErr = unit.AssessmentAttempts().ListDisclosedFamilyKeys(txctx, candidate.ID, since)
return readErr
}); err != nil {
t.Fatalf("read disclosed family keys after the rolling cutoff: %v", err)
}
contains := func(want domain.AssessmentFamilyKey) bool {
for _, key := range disclosed {
if key == want {
return true
}
}
return false
}
if contains(firstKey) || !contains(secondKey) || contains(thirdKey) {
t.Fatalf("disclosed families = %v; want first excluded, second included, and future third excluded", disclosed)
}
var countBefore int32
var latestBefore bool
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
var readErr error
countBefore, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second))
if readErr != nil {
return readErr
}
_, latestBefore, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization(
txctx, candidate.ID, domain.SpecializationBackend, nil,
)
return readErr
}); err != nil {
t.Fatalf("read eligible root quota and retry history: %v", err)
}
if countBefore != 1 || !latestBefore {
t.Fatalf("eligible root before platform failure = count %d/latest %v, want 1/true", countBefore, latestBefore)
}
if _, err := harness.pool.Exec(ctx, `
WITH failure_time AS (SELECT clock_timestamp() AS at)
UPDATE assessment_attempts
SET state='insufficient_bank',
updated_at=failure_time.at,
ended_at=failure_time.at,
version=version+1
FROM failure_time
WHERE id=$1`, attempt.ID); err != nil {
t.Fatalf("mark isolated attempt as a system bank failure: %v", err)
}
var countAfter int32
var latestAfter bool
var quotaAfter outbound.AssessmentRootQuotaSnapshot
if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error {
var readErr error
countAfter, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second))
if readErr != nil {
return readErr
}
_, latestAfter, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization(
txctx, candidate.ID, domain.SpecializationBackend, nil,
)
if readErr != nil {
return readErr
}
asOf, timeErr := unit.AssessmentBank().DatabaseTime(txctx)
if timeErr != nil {
return timeErr
}
quotaAfter, readErr = unit.AssessmentAttempts().GetRootQuotaSnapshot(
txctx, candidate.ID, createdAt.Add(-time.Second), asOf, 24*time.Hour, 1,
)
return readErr
}); err != nil {
t.Fatalf("read quota and retry history after platform failure: %v", err)
}
if countAfter != 0 || latestAfter || quotaAfter.Count != 0 || quotaAfter.AvailableAt != nil {
t.Fatalf("platform failure remains in availability history: count=%d latest=%v quota=%+v, want excluded", countAfter, latestAfter, quotaAfter)
}
}
@@ -122,7 +122,7 @@ func TestAssessmentBank(t *testing.T) {
"edit the version": `UPDATE assessment_families SET version = version + 10`,
"edit the hash scheme": `UPDATE assessment_families SET hash_scheme = 2`,
"delete": `DELETE FROM assessment_families`,
"truncate": `TRUNCATE assessment_families`,
"truncate": `TRUNCATE assessment_families, assessment_training_bank_binding_families, assessment_attempt_items, assessment_signal_events`,
} {
_, err := fixture.pool.Exec(ctx, statement)
assertPgError(t, name, err, assessmentIntegritySQLState, "assessment_families_immutable")
@@ -0,0 +1,442 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
const assessmentSignalHTTPTimeout = 6 * time.Minute
func TestAssessmentSignalsOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), assessmentSignalHTTPTimeout)
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, "signal-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.201:1234")
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "192.0.2.202:1234"); response.Code != http.StatusOK {
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
}
trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`,
sessionHTTPTestOrigin, cookie.Value, csrf, "signal-training", "192.0.2.203:1234")
if trainingCreate.Code != http.StatusCreated {
t.Fatalf("create demo attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String())
}
trainingAttempt, trainingItem := assessmentSignalAttemptItem(t, trainingCreate.Body.Bytes())
grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.204:1234")
trainingBody := assessmentSignalBody(t, trainingItem, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil)
trainingSignal := submitAssessmentSignal(t, harness, trainingAttempt, cookie, csrf, "signal-demo", trainingBody, "192.0.2.205:1234")
requireSessionProblem(t, trainingSignal, http.StatusConflict, "state_conflict")
rootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "signal-root", "192.0.2.206:1234")
if rootCreate.Code != http.StatusCreated {
t.Fatalf("create real assessment attempt = %d %s", rootCreate.Code, rootCreate.Body.String())
}
attemptID, itemID := assessmentSignalAttemptItem(t, rootCreate.Body.Bytes())
occurredAt := time.Now().UTC().Truncate(time.Microsecond)
body := assessmentSignalBody(t, itemID, occurredAt, "fullscreen_exit", nil)
badItemBody := assessmentSignalBody(t, uuid.New(), occurredAt, "fullscreen_exit", nil)
badItem := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-bad-item", badItemBody, "192.0.2.207:1234")
if badItem.Code != http.StatusBadRequest {
t.Fatalf("foreign item signal = %d %s, want 400", badItem.Code, badItem.Body.String())
}
oldTimestampBody := assessmentSignalBody(t, itemID, occurredAt.Add(-10*time.Minute), "fullscreen_exit", nil)
oldTimestamp := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-old-time", oldTimestampBody, "192.0.2.208:1234")
if oldTimestamp.Code != http.StatusBadRequest {
t.Fatalf("out-of-window client timestamp = %d %s, want 400", oldTimestamp.Code, oldTimestamp.Body.String())
}
oversizedBody := `{"events":[]}` + strings.Repeat(" ", 32<<10)
oversized := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-oversized", oversizedBody, "192.0.2.209:1234")
requireSessionProblem(t, oversized, http.StatusRequestEntityTooLarge, "payload_too_large")
accepted := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.210:1234")
assertSignalReceipt(t, accepted, http.StatusOK, "accepted", 1)
if accepted.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("signal receipt Cache-Control = %q, want no-store", accepted.Header().Get("Cache-Control"))
}
var receipt map[string]any
if err := json.Unmarshal(accepted.Body.Bytes(), &receipt); err != nil || len(receipt) != 3 {
t.Fatalf("receipt fields = %+v, decode error %v", receipt, err)
}
for _, privateField := range []string{"events", "item_instance_id", "size_bytes", "answer", "score", "result"} {
if _, exposed := receipt[privateField]; exposed {
t.Fatalf("signal receipt exposed %q", privateField)
}
}
assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1)
assertAssessmentSignalImmutability(t, ctx, harness.pool, attemptID)
replay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.211:1234")
if replay.Code != accepted.Code || replay.Body.String() != accepted.Body.String() {
t.Fatalf("same-key signal replay = %d %s, want original %d %s", replay.Code, replay.Body.String(), accepted.Code, accepted.Body.String())
}
changedBody := assessmentSignalBody(t, itemID, occurredAt.Add(time.Second), "fullscreen_exit", nil)
changedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.212:1234")
requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused")
assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1)
expiredScope := harness.keyring.IdempotencyScope("assessment_attempt.signals", "signal-first", candidate.ID.String())
applicationNow := harness.clock.Now()
if _, err := harness.pool.Exec(ctx, `UPDATE idempotency_records
SET created_at = $2::timestamptz - INTERVAL '25 hours', expires_at = $2::timestamptz - INTERVAL '1 second'
WHERE scope_hash = $1`, expiredScope[:], applicationNow); err != nil {
t.Fatalf("expire signal idempotency scope fixture: %v", err)
}
expiredReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.224:1234")
assertSignalReceipt(t, expiredReplay, http.StatusOK, "accepted", 1)
assertSignalStoredCounts(t, ctx, harness, attemptID, 2, 2, 1)
assertAssessmentSignalMeasurementChecks(t, ctx, harness.pool, attemptID, itemID)
concurrentBodies := []string{
assessmentSignalBody(t, itemID, occurredAt.Add(2*time.Second), "copy", int32Pointer(12)),
assessmentSignalBody(t, itemID, occurredAt.Add(3*time.Second), "copy", int32Pointer(13)),
}
concurrentResponses := make([]*httptest.ResponseRecorder, len(concurrentBodies))
start := make(chan struct{})
var wait sync.WaitGroup
for index := range concurrentBodies {
wait.Add(1)
go func(index int) {
defer wait.Done()
<-start
concurrentResponses[index] = submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-concurrent", concurrentBodies[index], fmt.Sprintf("198.51.100.%d:1234", index+10))
}(index)
}
close(start)
wait.Wait()
acceptedIndex := -1
conflictIndex := -1
for index, response := range concurrentResponses {
switch response.Code {
case http.StatusOK:
acceptedIndex = index
case http.StatusUnprocessableEntity:
requireSessionProblem(t, response, http.StatusUnprocessableEntity, "idempotency_key_reused")
conflictIndex = index
default:
t.Fatalf("concurrent signal %d = %d %s", index, response.Code, response.Body.String())
}
}
if acceptedIndex < 0 || conflictIndex < 0 || acceptedIndex == conflictIndex {
t.Fatalf("concurrent same-key outcomes accepted=%d conflict=%d", acceptedIndex, conflictIndex)
}
assertSignalReceipt(t, concurrentResponses[acceptedIndex], http.StatusOK, "accepted", 1)
assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2)
otherCandidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-other@example.test", passwordHash, true)
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", otherCandidate.ID); err != nil {
t.Fatalf("set cascade candidate onboarding step: %v", err)
}
otherCookie, otherCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, otherCandidate.Email.Address(), "192.0.2.213:1234")
if response := assessmentAttemptQuestionnaireRequest(t, harness, otherCookie.Value, otherCSRF, "192.0.2.220:1234"); response.Code != http.StatusOK {
t.Fatalf("save cascade candidate questionnaire = %d %s", response.Code, response.Body.String())
}
grantCurrentAttemptConsent(t, harness, otherCookie, otherCSRF, "192.0.2.221:1234")
foreignAttempt := submitAssessmentSignal(t, harness, attemptID, otherCookie, otherCSRF, "signal-foreign", body, "192.0.2.214:1234")
requireSessionProblem(t, foreignAttempt, http.StatusNotFound, "not_found")
assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2)
otherRootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "signal-cascade", "192.0.2.222:1234")
if otherRootCreate.Code != http.StatusCreated {
t.Fatalf("create cascade candidate attempt = %d %s", otherRootCreate.Code, otherRootCreate.Body.String())
}
otherAttemptID, otherItemID := assessmentSignalAttemptItem(t, otherRootCreate.Body.Bytes())
otherSignalBody := assessmentSignalBody(t, otherItemID, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil)
otherAccepted := submitAssessmentSignal(t, harness, otherAttemptID, otherCookie, otherCSRF, "signal-cascade", otherSignalBody, "192.0.2.223:1234")
assertSignalReceipt(t, otherAccepted, http.StatusOK, "accepted", 1)
assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1)
revokeC3 := assessmentAttemptHTTPRequest(t, harness, http.MethodDelete, "/api/v1/me/consents/c3", "",
sessionHTTPTestOrigin, cookie.Value, csrf, "", "192.0.2.215:1234")
if revokeC3.Code != http.StatusNoContent {
t.Fatalf("revoke C3 = %d %s", revokeC3.Code, revokeC3.Body.String())
}
withoutC3 := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-no-c3", body, "192.0.2.216:1234")
requireSessionProblem(t, withoutC3, http.StatusForbidden, "forbidden")
grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.217:1234")
seedAssessmentSignalCapacity(ctx, t, harness.pool, attemptID, itemID, 10000)
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 2)
saturatedBody := assessmentSignalBody(t, itemID, occurredAt.Add(4*time.Second), "fullscreen_exit", nil)
saturated := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.218:1234")
assertSignalReceipt(t, saturated, http.StatusOK, "saturated", 0)
saturatedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.219:1234")
if saturatedReplay.Body.String() != saturated.Body.String() {
t.Fatalf("saturated replay = %s, want %s", saturatedReplay.Body.String(), saturated.Body.String())
}
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 3)
for next := signalOutcomeCount(t, ctx, harness.pool, attemptID); next < 30; next++ {
key := fmt.Sprintf("signal-rate-%02d", next)
response := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, key, saturatedBody, fmt.Sprintf("203.0.113.%d:1234", next+1))
assertSignalReceipt(t, response, http.StatusOK, "saturated", 0)
}
limitedKey := "signal-rate-retry"
limited := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, limitedKey, saturatedBody, "203.0.113.80:1234")
requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited")
if limited.Header().Get("Retry-After") == "" {
t.Fatal("rate-limited signal response omitted Retry-After")
}
scope := harness.keyring.IdempotencyScope("assessment_attempt.signals", limitedKey, candidate.ID.String())
var consumed int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash = $1", scope[:]).Scan(&consumed); err != nil {
t.Fatalf("check rejected idempotency scope: %v", err)
}
if consumed != 0 {
t.Fatalf("rate-limited idempotency scopes = %d, want 0", consumed)
}
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 30)
terminalizeAttempt(t, ctx, harness.pool, attemptID)
terminal := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-terminal", saturatedBody, "203.0.113.81:1234")
requireSessionProblem(t, terminal, http.StatusConflict, "state_conflict")
if _, err := harness.pool.Exec(ctx, "DELETE FROM assessment_attempts WHERE id = $1", attemptID); err != nil {
t.Fatalf("delete attempt for signal cascade test: %v", err)
}
deletedAttemptReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "203.0.113.82:1234")
requireSessionProblem(t, deletedAttemptReplay, http.StatusNotFound, "not_found")
assertSignalStoredCounts(t, ctx, harness, attemptID, 0, 0, 0)
_, accountDeleteErr := harness.pool.Exec(ctx, "DELETE FROM users WHERE id = $1", otherCandidate.ID)
assertSQLError(t, "delete account with retained consent history", accountDeleteErr, consentRestrictViolation, "consent_records_subject_id_fkey")
var retainedConsentRecords int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", otherCandidate.ID).Scan(&retainedConsentRecords); err != nil {
t.Fatalf("count retained consent records after rejected account deletion: %v", err)
}
if retainedConsentRecords == 0 {
t.Fatal("account deletion removed the candidate's retained consent records")
}
assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1)
}
func assessmentSignalAttemptItem(t *testing.T, body []byte) (uuid.UUID, uuid.UUID) {
t.Helper()
var attempt struct {
ID uuid.UUID `json:"id"`
CurrentItem *struct {
ID uuid.UUID `json:"id"`
} `json:"current_item"`
}
if err := json.Unmarshal(body, &attempt); err != nil || attempt.ID == uuid.Nil || attempt.CurrentItem == nil || attempt.CurrentItem.ID == uuid.Nil {
t.Fatalf("decode signal test attempt and item: %+v, error %v", attempt, err)
}
return attempt.ID, attempt.CurrentItem.ID
}
func assessmentSignalBody(t *testing.T, itemID uuid.UUID, occurredAt time.Time, kind string, size *int32) string {
t.Helper()
event := map[string]any{
"kind": kind, "item_instance_id": itemID, "occurred_at": occurredAt.UTC().Format(time.RFC3339Nano),
}
if size != nil {
event["size_bytes"] = *size
}
body, err := json.Marshal(map[string]any{"events": []any{event}})
if err != nil {
t.Fatalf("marshal signal test body: %v", err)
}
return string(body)
}
func int32Pointer(value int32) *int32 { return &value }
func submitAssessmentSignal(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
attemptID uuid.UUID,
cookie *http.Cookie,
csrf, key, body, remoteAddr string,
) *httptest.ResponseRecorder {
t.Helper()
path := "/api/v1/me/assessment-attempts/" + attemptID.String() + "/signals"
return assessmentAttemptHTTPRequest(t, harness, http.MethodPost, path, body,
sessionHTTPTestOrigin, cookie.Value, csrf, key, remoteAddr)
}
func assertSignalReceipt(t *testing.T, response *httptest.ResponseRecorder, status int, receiptStatus string, accepted int) {
t.Helper()
var receipt struct {
Status string `json:"status"`
AcceptedEvents int `json:"accepted_events"`
ReceivedAt time.Time `json:"received_at"`
}
if response.Code != status || json.Unmarshal(response.Body.Bytes(), &receipt) != nil ||
receipt.Status != receiptStatus || receipt.AcceptedEvents != accepted || receipt.ReceivedAt.IsZero() {
t.Fatalf("signal receipt = %d %s, want %d/%s/%d", response.Code, response.Body.String(), status, receiptStatus, accepted)
}
}
func assertSignalStoredCounts(
t *testing.T,
ctx context.Context,
harness *assessmentAttemptHTTPHarness,
attemptID uuid.UUID,
wantEvents, wantBatches, wantOutcomes int64,
) {
t.Helper()
for _, check := range []struct {
table string
want int64
}{
{table: "assessment_signal_events", want: wantEvents},
{table: "assessment_signal_batches", want: wantBatches},
{table: "assessment_signal_idempotency_outcomes", want: wantOutcomes},
} {
var got int64
query := "SELECT count(*) FROM " + check.table + " WHERE attempt_id = $1"
if err := harness.pool.QueryRow(ctx, query, attemptID).Scan(&got); err != nil {
t.Fatalf("count %s: %v", check.table, err)
}
if got != check.want {
t.Fatalf("%s rows = %d, want %d", check.table, got, check.want)
}
}
}
func assertAssessmentSignalMeasurementChecks(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID, itemID uuid.UUID) {
t.Helper()
for index, kind := range []string{"focus_loss", "copy"} {
batchID := uuid.New()
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatalf("begin measurement check %d: %v", index, err)
}
if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
VALUES ($1, $2, clock_timestamp(), 1)`, batchID, attemptID); err != nil {
t.Fatalf("insert measurement boundary batch: %v", err)
}
_, err = tx.Exec(ctx, `INSERT INTO assessment_signal_events (
batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes
) VALUES ($1, $2, 1, $3, $4, clock_timestamp(), NULL, NULL)`, batchID, attemptID, itemID, kind)
assertPgError(t, "reject null measurement for "+kind, err, "23514", "assessment_signal_events_measurement")
if err := tx.Rollback(ctx); err != nil {
t.Fatalf("rollback measurement check %d: %v", index, err)
}
}
}
func assertAssessmentSignalImmutability(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) {
t.Helper()
var batchID uuid.UUID
if err := pool.QueryRow(ctx, `SELECT id FROM assessment_signal_batches
WHERE attempt_id = $1 ORDER BY received_at, id LIMIT 1`, attemptID).Scan(&batchID); err != nil {
t.Fatalf("read signal batch for immutability checks: %v", err)
}
_, err := pool.Exec(ctx, "UPDATE assessment_signal_batches SET event_count = event_count WHERE id = $1", batchID)
assertPgError(t, "reject signal batch update", err, "23000", "assessment_signal_batches_immutable")
_, err = pool.Exec(ctx, "DELETE FROM assessment_signal_batches WHERE id = $1", batchID)
assertPgError(t, "reject direct signal batch deletion", err, "23000", "assessment_signal_batches_immutable")
var ordinal int32
if err := pool.QueryRow(ctx, `SELECT ordinal FROM assessment_signal_events
WHERE batch_id = $1 ORDER BY ordinal LIMIT 1`, batchID).Scan(&ordinal); err != nil {
t.Fatalf("read signal event for immutability checks: %v", err)
}
_, err = pool.Exec(ctx, "UPDATE assessment_signal_events SET occurred_at = occurred_at WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal)
assertPgError(t, "reject signal event update", err, "23000", "assessment_signal_events_immutable")
_, err = pool.Exec(ctx, "DELETE FROM assessment_signal_events WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal)
assertPgError(t, "reject direct signal event deletion", err, "23000", "assessment_signal_events_immutable")
var scopeHash []byte
if err := pool.QueryRow(ctx, `SELECT scope_hash FROM assessment_signal_idempotency_outcomes
WHERE attempt_id = $1 ORDER BY received_at LIMIT 1`, attemptID).Scan(&scopeHash); err != nil {
t.Fatalf("read signal outcome for immutability check: %v", err)
}
_, err = pool.Exec(ctx, "UPDATE assessment_signal_idempotency_outcomes SET status = status WHERE scope_hash = $1", scopeHash)
assertPgError(t, "reject signal outcome update", err, "23000", "assessment_signal_idempotency_outcomes_immutable")
}
func seedAssessmentSignalCapacity(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
attemptID, itemID uuid.UUID,
wantTotal int64,
) {
t.Helper()
var existing int64
if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_events WHERE attempt_id = $1", attemptID).Scan(&existing); err != nil {
t.Fatalf("read signal count before capacity fixture: %v", err)
}
remaining := wantTotal - existing
if remaining <= 0 {
t.Fatalf("capacity fixture has no remaining rows: existing=%d target=%d", existing, wantTotal)
}
batchCount := int((remaining + 49) / 50)
batchIDs := make([]uuid.UUID, batchCount)
for index := range batchIDs {
batchIDs[index] = uuid.New()
}
tx, err := pool.BeginTx(ctx, pgx.TxOptions{})
if err != nil {
t.Fatalf("begin bounded capacity fixture: %v", err)
}
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events DISABLE TRIGGER assessment_signal_event_guard"); err != nil {
t.Fatalf("disable only the capacity backstop for isolated fixture: %v", err)
}
if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
SELECT batch.batch_id, $1, clock_timestamp(), LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer
FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality)`, attemptID, batchIDs, remaining); err != nil {
t.Fatalf("insert bounded signal capacity batches: %v", err)
}
if _, err := tx.Exec(ctx, `WITH batches AS (
SELECT batch.batch_id, LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer AS event_count
FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality)
)
INSERT INTO assessment_signal_events (
batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes
)
SELECT batches.batch_id, $1, event.ordinality::integer, $4, 'fullscreen_exit', clock_timestamp(), NULL, NULL
FROM batches
CROSS JOIN LATERAL generate_series(1, batches.event_count) AS event(ordinality)`, attemptID, batchIDs, remaining, itemID); err != nil {
t.Fatalf("insert bounded signal capacity events: %v", err)
}
if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events ENABLE TRIGGER assessment_signal_event_guard"); err != nil {
t.Fatalf("restore signal capacity trigger: %v", err)
}
if err := tx.Commit(ctx); err != nil {
t.Fatalf("commit isolated signal capacity fixture: %v", err)
}
}
func signalOutcomeCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) int64 {
t.Helper()
var count int64
if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_idempotency_outcomes WHERE attempt_id = $1", attemptID).Scan(&count); err != nil {
t.Fatalf("count signal receipts: %v", err)
}
return count
}
@@ -0,0 +1,115 @@
//go:build integration
package integration_test
import (
"context"
"testing"
"time"
"github.com/google/uuid"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
)
const candidateCardAccessMigrationVersion = 30
func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("Up() error = %v", err)
}
rollBackToCandidateCardAccessVersion(ctx, t, migrator)
now := time.Now().UTC().Truncate(time.Microsecond)
identity := identityFixture{
ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now,
}
candidate := identity.createUser(t, "candidate@example.com", domain.ScenarioCandidate, now.Add(-time.Hour))
organizationFixture := organizationFixture{
ctx: ctx, pool: pool, identity: identity,
transactor: postgresadapter.NewTransactor(pool), now: now,
}
owner := organizationFixture.employer(t, "owner@example.com")
organization := organizationFixture.create(t, owner, organizationFixture.completeProfile(t, "Example Company"), now)
if _, err := pool.Exec(ctx, `INSERT INTO candidate_card_access_events (
id, candidate_id, organization_id, actor_id, kind, field_codes, occurred_at
) VALUES ($1, $2, $3, $4, 'card_viewed', ARRAY['stack']::text[], $5)`,
uuid.New(), candidate.ID, organization.ID(), owner.ID, now); err != nil {
t.Fatalf("insert retained card access event: %v", err)
}
_, err := migrator.DownOne(ctx)
assertPgError(t, "DownOne() with retained card access history", err, privacyIntegrityViolation, "candidate_card_access_events_retained")
var tableExists bool
if err := pool.QueryRow(ctx, `SELECT to_regclass('public.candidate_card_access_events') IS NOT NULL`).Scan(&tableExists); err != nil {
t.Fatalf("check access history table after refused rollback: %v", err)
}
if !tableExists {
t.Fatal("candidate_card_access_events was removed despite retained history")
}
var count int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1`, candidate.ID).Scan(&count); err != nil {
t.Fatalf("read retained access event after refused rollback: %v", err)
}
if count != 1 {
t.Fatalf("retained access event count = %d, want 1", count)
}
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("Status() after refused rollback: %v", err)
}
version30Applied := false
for _, status := range statuses {
if status.Version == candidateCardAccessMigrationVersion {
version30Applied = status.Applied
break
}
}
if !version30Applied {
t.Fatal("migration 30 is not applied after its guarded Down() failed")
}
}
func rollBackToCandidateCardAccessVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) {
t.Helper()
for {
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("Status() while preparing migration %d: %v", candidateCardAccessMigrationVersion, err)
}
version30Applied := false
laterMigrationApplied := false
for _, status := range statuses {
if !status.Applied {
continue
}
if status.Version == candidateCardAccessMigrationVersion {
version30Applied = true
}
if status.Version > candidateCardAccessMigrationVersion {
laterMigrationApplied = true
}
}
if !version30Applied {
t.Fatalf("migration %d is not applied", candidateCardAccessMigrationVersion)
}
if !laterMigrationApplied {
return
}
result, err := migrator.DownOne(ctx)
if err != nil {
t.Fatalf("DownOne() while preparing migration %d: %v", candidateCardAccessMigrationVersion, err)
}
if result.Version <= candidateCardAccessMigrationVersion {
t.Fatalf("DownOne() rolled back migration %d while preparing migration %d", result.Version, candidateCardAccessMigrationVersion)
}
}
}
@@ -0,0 +1,549 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
httpadapter "lincodex/backend/internal/adapter/primary/http"
"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/postgres/sqlc"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/anonymousprofile"
"lincodex/backend/internal/usecase/candidateprivacy"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/companyquota"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/policy"
)
const candidatePrivacyHTTPTestTimeout = 5 * time.Minute
type candidatePrivacyHTTPHarness struct {
*sessionHTTPHarness
key domain.CandidateViewPseudonymKey
settings *candidateprivacy.Service
}
func TestCandidatePrivacyHTTPReadsRecheckCurrentVisibility(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyHTTPTestTimeout)
defer cancel()
harness := newCandidatePrivacyHTTPHarness(ctx, t, env)
truncateTables(ctx, t, harness.pool, usersDependentTables...)
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), harness.clock.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
now := harness.clock.Now()
identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now}
organizations := organizationFixture{
ctx: ctx, pool: harness.pool, identity: identity,
transactor: postgresadapter.NewTransactor(harness.pool), now: now,
}
privacy := candidatePrivacyFixture{
ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity,
organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now,
}
profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, now: now}
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-target@example.test", passwordHash, true)
candidates := []domain.User{candidate}
for index := 1; index < 5; index++ {
other := privacy.candidate(t, fmt.Sprintf("privacy-cohort-%d@example.test", index))
verifyPrivacyCohortCandidate(t, privacy, other)
candidates = append(candidates, other)
}
for _, member := range candidates {
input := domain.CandidateProfileInput{Stack: privacyCohortConfirmedItems("go")}
if member.ID == candidate.ID {
input.FullName = confirmedDecision("Private Candidate Name")
input.Email = confirmedDecision("private-card-email@example.test")
}
profiles.save(t, member.ID, input, 0)
if member.ID == candidate.ID {
continue
}
c2 := privacy.grant(t, member.ID, domain.ConsentPurposePublication, privacyC2Version, now)
privacy.publish(t, member.ID, c2.ID(), 0, domain.CardFieldStack)
}
employer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
organizationA := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization A"), now)
organizationB := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization B"), now)
organizationC := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization C"), now)
inactiveOrganization := organizations.create(t, employer, organizations.completeProfile(t, "Privacy inactive organization"), now)
organizations.setMembershipState(t, inactiveOrganization.ID(), employer.ID, domain.MembershipStateLeft)
foreignEmployer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-foreign-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now)
foreignOrganization := organizations.create(t, foreignEmployer, organizations.completeProfile(t, "Privacy foreign organization"), now)
candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.170:1234")
employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.171:1234")
initialSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.172:1234")
if initialSettings.Code != http.StatusOK || initialSettings.Header().Get("Cache-Control") != "no-store" ||
!strings.Contains(initialSettings.Body.String(), `"state":"closed"`) || !strings.Contains(initialSettings.Body.String(), `"closed_reason":"never_published"`) {
t.Fatalf("initial privacy settings = %d Cache-Control=%q %s", initialSettings.Code, initialSettings.Header().Get("Cache-Control"), initialSettings.Body.String())
}
c2Grant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF,
"c2", privacyC2Version, sessionHTTPTestOrigin)
if c2Grant.Code != http.StatusOK {
t.Fatalf("C2 grant = %d %s", c2Grant.Code, c2Grant.Body.String())
}
publication := harness.request(t, http.MethodPut, "/api/v1/me/privacy/publication",
`{"expected_version":0,"state":"published","fields":["stack"]}`,
sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.173:1234")
if publication.Code != http.StatusOK || publication.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("publication = %d Cache-Control=%q %s", publication.Code, publication.Header().Get("Cache-Control"), publication.Body.String())
}
aliasA, err := harness.key.ForOrganization(organizationA.ID(), candidate.ID)
if err != nil {
t.Fatalf("ForOrganization(A) error = %v", err)
}
aliasB, err := harness.key.ForOrganization(organizationB.ID(), candidate.ID)
if err != nil {
t.Fatalf("ForOrganization(B) error = %v", err)
}
if aliasA == aliasB {
t.Fatalf("organization-scoped aliases unexpectedly match: %q", aliasA)
}
assertCandidatePrivacyContactPortFixture(t, ctx, harness, employer.ID, organizationA.ID(), candidate.ID, aliasA)
unknownOrganization := uuid.New()
for _, test := range []struct {
name string
organizationID uuid.UUID
wantStatus int
wantCode string
useCandidate bool
}{
{name: "active employer membership", organizationID: organizationA.ID(), wantStatus: http.StatusOK},
{name: "candidate account", organizationID: organizationA.ID(), wantStatus: http.StatusForbidden, wantCode: "forbidden", useCandidate: true},
{name: "inactive membership", organizationID: inactiveOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"},
{name: "foreign membership", organizationID: foreignOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"},
{name: "unknown organization", organizationID: unknownOrganization, wantStatus: http.StatusNotFound, wantCode: "not_found"},
} {
t.Run(test.name, func(t *testing.T) {
cookie := employerCookie.Value
if test.useCandidate {
cookie = candidateCookie.Value
}
response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, test.organizationID, aliasA, cookie)
if response.Code != test.wantStatus {
t.Fatalf("card response = %d %s, want %d", response.Code, response.Body.String(), test.wantStatus)
}
if test.wantCode != "" {
requireSessionProblem(t, response, test.wantStatus, test.wantCode)
}
if test.wantStatus == http.StatusOK {
if response.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("card Cache-Control = %q, want no-store", response.Header().Get("Cache-Control"))
}
var card struct {
Pseudonym string `json:"pseudonym"`
Stack []string `json:"stack"`
}
if err := json.Unmarshal(response.Body.Bytes(), &card); err != nil || card.Pseudonym != aliasA || len(card.Stack) != 1 || card.Stack[0] != "go" {
t.Fatalf("anonymous card = %+v, %v; body=%s", card, err, response.Body.String())
}
for _, privateValue := range []string{candidate.ID.String(), candidate.Email.Address(), "Private Candidate Name", "private-card-email@example.test"} {
if strings.Contains(response.Body.String(), privateValue) {
t.Errorf("anonymous card contains private value %q", privateValue)
}
}
}
})
}
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationA.ID(), []string{"stack"})
preview := harness.request(t, http.MethodGet, "/api/v1/me/privacy/preview", "", "", candidateCookie.Value, "", "192.0.2.174:1234")
if preview.Code != http.StatusOK || preview.Header().Get("Cache-Control") != "no-store" ||
strings.Contains(preview.Body.String(), aliasA) || strings.Contains(preview.Body.String(), candidate.ID.String()) {
t.Fatalf("private preview = %d Cache-Control=%q %s", preview.Code, preview.Header().Get("Cache-Control"), preview.Body.String())
}
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
hideA := harness.request(t, http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(),
"", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.175:1234")
if hideA.Code != http.StatusOK || hideA.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("hide organization A = %d Cache-Control=%q %s", hideA.Code, hideA.Header().Get("Cache-Control"), hideA.Body.String())
}
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusNotFound {
t.Fatalf("card after hiding A = %d %s, want generic 404", response.Code, response.Body.String())
}
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusOK {
t.Fatalf("card for B after hiding A = %d %s, want independent organization access", response.Code, response.Body.String())
}
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationB.ID(), []string{"stack"})
unhideA := harness.request(t, http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(),
"", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.176:1234")
if unhideA.Code != http.StatusNoContent {
t.Fatalf("unhide organization A = %d %s, want 204", unhideA.Code, unhideA.Body.String())
}
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusOK {
t.Fatalf("card after unhiding A = %d %s, want restored visibility while C2 is active", response.Code, response.Body.String())
}
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1)
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 2)
directHidden, err := harness.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: candidate.ID, Limit: 20})
if err != nil || len(directHidden.Items) != 0 || directHidden.HasMore {
t.Fatalf("direct hidden organization list = %+v, %v; want an empty page after unhide", directHidden, err)
}
hiddenList := harness.request(t, http.MethodGet, "/api/v1/me/privacy/hidden-organizations", "", "", candidateCookie.Value, "", "192.0.2.177:1234")
if hiddenList.Code != http.StatusOK || !strings.Contains(hiddenList.Body.String(), `"items":[]`) || hiddenList.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("hidden organizations after unhide = %d Cache-Control=%q %s", hiddenList.Code, hiddenList.Header().Get("Cache-Control"), hiddenList.Body.String())
}
privacyHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/history", "", "", candidateCookie.Value, "", "192.0.2.178:1234")
if privacyHistory.Code != http.StatusOK || !strings.Contains(privacyHistory.Body.String(), "publication_opened") ||
!strings.Contains(privacyHistory.Body.String(), "organization_hidden") || !strings.Contains(privacyHistory.Body.String(), "organization_unhidden") {
t.Fatalf("privacy history = %d %s", privacyHistory.Code, privacyHistory.Body.String())
}
accessHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/access-history", "", "", candidateCookie.Value, "", "192.0.2.179:1234")
if accessHistory.Code != http.StatusOK || accessHistory.Header().Get("Cache-Control") != "no-store" || !strings.Contains(accessHistory.Body.String(), "Privacy organization A") || !strings.Contains(accessHistory.Body.String(), "Privacy organization B") {
t.Fatalf("card access history = %d Cache-Control=%q %s", accessHistory.Code, accessHistory.Header().Get("Cache-Control"), accessHistory.Body.String())
}
// Hold the candidate account row so the employer read reaches and waits on
// its FOR SHARE visibility lock. Commit the competing hide only after the
// lock wait is observed; a visibility recheck must reject the stale cohort.
lockTx, err := harness.pool.Begin(ctx)
if err != nil {
t.Fatalf("begin visibility race transaction: %v", err)
}
defer func() { _ = lockTx.Rollback(context.Background()) }()
if _, err := lockTx.Exec(ctx, `SELECT id FROM users WHERE id = $1 FOR UPDATE`, candidate.ID); err != nil {
t.Fatalf("lock candidate row for visibility race: %v", err)
}
aliasC, err := harness.key.ForOrganization(organizationC.ID(), candidate.ID)
if err != nil {
t.Fatalf("ForOrganization(C) error = %v", err)
}
raceResult := make(chan *httptest.ResponseRecorder, 1)
go func() {
raceResult <- candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationC.ID(), aliasC, employerCookie.Value)
}()
monitor := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-monitor")
if waitEvent, waiting := waitForLockWait(ctx, monitor, "candidate-privacy-http"); !waiting || waitEvent == "" {
t.Fatalf("card read did not wait for candidate visibility lock, wait event %q", waitEvent)
}
if _, err := lockTx.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, candidate.ID, organizationC.ID(), now.Add(time.Second)); err != nil {
t.Fatalf("commit concurrent candidate hide fixture: %v", err)
}
if err := lockTx.Commit(ctx); err != nil {
t.Fatalf("commit visibility race transaction: %v", err)
}
raceResponse := <-raceResult
if raceResponse.Code != http.StatusNotFound {
t.Fatalf("card read that waited behind a hide = %d %s, want generic 404", raceResponse.Code, raceResponse.Body.String())
}
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0)
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0)
revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.180:1234")
if revoke.Code != http.StatusNoContent {
t.Fatalf("C2 revoke = %d %s, want 204", revoke.Code, revoke.Body.String())
}
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound {
t.Fatalf("card after C2 revoke = %d %s, want generic 404", response.Code, response.Body.String())
}
regrant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF,
"c2", privacyC2Version, sessionHTTPTestOrigin)
if regrant.Code != http.StatusOK {
t.Fatalf("C2 regrant = %d %s", regrant.Code, regrant.Body.String())
}
if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound {
t.Fatalf("card after C2 regrant without republication = %d %s, want generic 404", response.Code, response.Body.String())
}
closedSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.181:1234")
if closedSettings.Code != http.StatusOK || !strings.Contains(closedSettings.Body.String(), `"state":"closed"`) {
t.Fatalf("settings after C2 revoke and regrant = %d %s, want closed publication", closedSettings.Code, closedSettings.Body.String())
}
assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1)
}
func newCandidatePrivacyHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *candidatePrivacyHTTPHarness {
t.Helper()
pool := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-http")
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)
}
key, err := keyring.CandidateViewPseudonymKey()
if err != nil {
t.Fatalf("CandidateViewPseudonymKey() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Add(5 * time.Minute).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)
consentQueries := consent.NewQueryService(consentStore, clock.Now)
consentCommands := consent.NewService(transactor, clock.Now)
privacySettings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock.Now})
if err != nil {
t.Fatalf("candidateprivacy.NewService() error = %v", err)
}
quota := companyquota.NewService(clock.Now)
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(pool), key, clock.Now)
privacyViews, err := candidateview.NewService(candidateview.Dependencies{
Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: clock.Now,
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
return quota.ReserveCardView(ctx, unit, organization, candidateID)
},
})
if err != nil {
t.Fatalf("candidateview.NewService() error = %v", err)
}
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))
consentHandler := v1.NewConsentHandler(consentQueries, consentCommands)
privacyHandler := v1.NewPrivacyHandler(privacyViews, privacySettings, env.Config.AppPublicURL)
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler), v1.WithPrivacy(privacyHandler),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return &candidatePrivacyHTTPHarness{
sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs},
key: key, settings: privacySettings,
}
}
func candidatePrivacyCardRequest(t *testing.T, harness *sessionHTTPHarness, organizationID uuid.UUID, handle, cookie string) *httptest.ResponseRecorder {
t.Helper()
path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", organizationID, handle)
return harness.request(t, http.MethodGet, path, "", "", cookie, "", "192.0.2.190:1234")
}
func assertPrivacyCardAccessCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) {
t.Helper()
var count int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed'`, candidateID, organizationID).Scan(&count); err != nil {
t.Fatalf("count candidate card access events: %v", err)
}
if count != want {
t.Fatalf("card access event count = %d, want %d", count, want)
}
}
func assertPrivacyCardViewQuotaCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) {
t.Helper()
var count int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, candidateID, organizationID).Scan(&count); err != nil {
t.Fatalf("count card-view quota usage: %v", err)
}
if count != want {
t.Fatalf("card-view quota usage count = %d, want %d", count, want)
}
}
func assertPrivacyCardAccessFields(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want []string) {
t.Helper()
var fields []string
if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' ORDER BY occurred_at, id LIMIT 1`, candidateID, organizationID).Scan(&fields); err != nil {
t.Fatalf("read card-view audit fields: %v", err)
}
if len(fields) != len(want) {
t.Fatalf("card-view audit fields = %v, want %v", fields, want)
}
for index := range fields {
if fields[index] != want[index] {
t.Fatalf("card-view audit fields = %v, want %v", fields, want)
}
}
}
type candidatePrivacyContactGrantState uint8
const (
candidatePrivacyContactGrantAbsent candidatePrivacyContactGrantState = iota
candidatePrivacyContactGrantActive
candidatePrivacyContactGrantRevoked
)
type candidatePrivacyContactGrantFixture struct {
state candidatePrivacyContactGrantState
workflowAccepted bool
organizationID uuid.UUID
candidateID uuid.UUID
fields domain.ContactFieldSet
}
func (fixture *candidatePrivacyContactGrantFixture) currentFields(organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) {
if fixture == nil || fixture.state != candidatePrivacyContactGrantActive ||
fixture.organizationID != organizationID || fixture.candidateID != candidateID {
return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed
}
// Workflow acceptance is deliberately not used as authorization evidence.
return fixture.fields, nil
}
type candidatePrivacyContactTransactor struct {
inner outbound.Transactor
fixture *candidatePrivacyContactGrantFixture
}
func (transactor candidatePrivacyContactTransactor) WithinTransaction(
ctx context.Context,
fn func(context.Context, outbound.UnitOfWork) error,
) error {
return transactor.inner.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
view := candidatePrivacyContactView{
PrivacyViewRepository: unit.PrivacyView(),
fixture: transactor.fixture,
}
return fn(ctx, candidatePrivacyContactUnit{UnitOfWork: unit, view: view})
})
}
type candidatePrivacyContactUnit struct {
outbound.UnitOfWork
view outbound.PrivacyViewRepository
}
func (unit candidatePrivacyContactUnit) PrivacyView() outbound.PrivacyViewRepository {
return unit.view
}
type candidatePrivacyContactView struct {
outbound.PrivacyViewRepository
fixture *candidatePrivacyContactGrantFixture
}
func (view candidatePrivacyContactView) CurrentFields(_ context.Context, organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) {
return view.fixture.currentFields(organizationID, candidateID)
}
func assertCandidatePrivacyContactPortFixture(
t *testing.T,
ctx context.Context,
harness *candidatePrivacyHTTPHarness,
actorID, organizationID, candidateID uuid.UUID,
handle string,
) {
t.Helper()
fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail, domain.ContactFieldPhone)
if err != nil {
t.Fatalf("NewContactFieldSet() error = %v", err)
}
fixture := &candidatePrivacyContactGrantFixture{
organizationID: organizationID,
candidateID: candidateID,
fields: fields,
}
transactor := candidatePrivacyContactTransactor{
inner: postgresadapter.NewTransactor(harness.pool),
fixture: fixture,
}
projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(harness.pool), harness.key, harness.clock.Now)
quota := companyquota.NewService(harness.clock.Now)
service, err := candidateview.NewService(candidateview.Dependencies{
Transactor: transactor, Projector: projector, PseudonymKey: harness.key, Clock: harness.clock.Now,
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
return quota.ReserveCardView(ctx, unit, organization, candidateID)
},
})
if err != nil {
t.Fatalf("candidateview.NewService() error = %v", err)
}
for _, test := range []struct {
name string
state candidatePrivacyContactGrantState
want bool
}{
{name: "active grant returns selected fields", state: candidatePrivacyContactGrantActive, want: true},
{name: "workflow acceptance without a grant stays closed", state: candidatePrivacyContactGrantAbsent},
{name: "revoked grant stays closed", state: candidatePrivacyContactGrantRevoked},
} {
t.Run(test.name, func(t *testing.T) {
fixture.state = test.state
fixture.workflowAccepted = true
got, err := service.CurrentContactFields(ctx, actorID, organizationID, handle)
if test.want {
if err != nil {
t.Fatalf("CurrentContactFields() error = %v", err)
}
gotFields := got.Fields()
wantFields := fields.Fields()
if len(gotFields) != len(wantFields) {
t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields)
}
for index := range wantFields {
if gotFields[index] != wantFields[index] {
t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields)
}
}
} else if !errors.Is(err, outbound.ErrContactAccessClosed) {
t.Fatalf("CurrentContactFields() error = %v, want closed contact access", err)
}
assertPrivacyContactAudit(t, ctx, harness.pool, candidateID, organizationID, test.want)
})
}
}
func assertPrivacyContactAudit(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, checkFields bool) {
t.Helper()
var count int
if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&count); err != nil {
t.Fatalf("count contact-read audit events: %v", err)
}
if count != 1 {
t.Fatalf("contact-read audit count = %d, want one successful read and no records for denied reads", count)
}
if !checkFields {
return
}
var fields []string
if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&fields); err != nil {
t.Fatalf("read contact-read audit fields: %v", err)
}
if len(fields) != 2 || fields[0] != "email" || fields[1] != "phone" {
t.Fatalf("contact-read audit fields = %v, want [email phone]", fields)
}
}
@@ -36,11 +36,13 @@ var (
candidateSearchStatusesTable = pgx.Identifier{"candidate_search_statuses"}
candidateHiddenOrganizationsTable = pgx.Identifier{"candidate_hidden_organizations"}
candidatePrivacyEventsTable = pgx.Identifier{"candidate_privacy_events"}
candidateCardAccessEventsTable = pgx.Identifier{"candidate_card_access_events"}
// candidatePrivacyTables reference users, organizations, and the consent
// ledger, so every TRUNCATE of those names them through
// usersDependentTables.
candidatePrivacyTables = []pgx.Identifier{
candidatePrivacyEventsTable, candidateHiddenOrganizationsTable, candidateSearchStatusesTable, candidatePublicationsTable,
candidateCardAccessEventsTable, candidatePrivacyEventsTable, candidateHiddenOrganizationsTable,
candidateSearchStatusesTable, candidatePublicationsTable,
}
)
@@ -772,6 +774,66 @@ func TestCandidatePrivacyStorage(t *testing.T) {
})
}
func TestCandidateCardAccessEventRetentionAndActorAnonymization(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
now := time.Now().UTC().Truncate(time.Microsecond)
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
fixture := candidatePrivacyFixture{
ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity,
organizations: organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now},
ledger: postgresadapter.NewConsentStore(pool), now: now,
}
truncateTables(ctx, t, pool, usersDependentTables...)
candidate := fixture.candidate(t, "privacy-owner@example.test")
verifyPrivacyCohortCandidate(t, fixture, candidate)
organizationOwner := fixture.organizations.employer(t, "privacy-organization-owner@example.test")
organization := fixture.organizations.create(t, organizationOwner,
fixture.organizations.completeProfile(t, "Access history organization"), now)
actor := fixture.candidate(t, "privacy-viewer@example.test")
access, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{
CandidateID: candidate.ID, OrganizationID: organization.ID(), ActorID: actor.ID,
Kind: domain.CandidateCardAccessCardViewed, OccurredAt: now,
})
if err != nil {
t.Fatalf("NewCandidateCardAccess() error = %v", err)
}
queries := sqlc.New(pool)
if err := queries.InsertCandidateCardAccessEvent(ctx, sqlc.InsertCandidateCardAccessEventParams{
ID: uuidParam(access.ID()), CandidateID: uuidParam(candidate.ID), OrganizationID: uuidParam(organization.ID()),
ActorID: uuidParam(actor.ID), Kind: string(access.Kind()), FieldCodes: access.FieldCodes(), OccurredAt: timeParam(access.OccurredAt()),
}); err != nil {
t.Fatalf("InsertCandidateCardAccessEvent(pseudonym-only) error = %v", err)
}
_, err = pool.Exec(ctx, `UPDATE candidate_card_access_events SET field_codes = ARRAY['location'] WHERE id = $1`, access.ID())
assertPgError(t, "reject card access field update", err, privacyIntegrityViolation, "candidate_card_access_events_immutable")
_, err = pool.Exec(ctx, `UPDATE candidate_card_access_events SET actor_id = NULL WHERE id = $1`, access.ID())
assertPgError(t, "reject direct card access actor anonymization", err, privacyIntegrityViolation, "candidate_card_access_events_immutable")
_, err = pool.Exec(ctx, `DELETE FROM candidate_card_access_events WHERE id = $1`, access.ID())
assertPgError(t, "reject card access deletion", err, privacyIntegrityViolation, "candidate_card_access_events_retained")
if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, actor.ID); err != nil {
t.Fatalf("DELETE audit actor = %v", err)
}
var storedCandidate, storedOrganization uuid.UUID
var storedActor pgtype.UUID
var kind string
var fields []string
if err := pool.QueryRow(ctx, `SELECT candidate_id, organization_id, actor_id, kind, field_codes FROM candidate_card_access_events WHERE id = $1`, access.ID()).
Scan(&storedCandidate, &storedOrganization, &storedActor, &kind, &fields); err != nil {
t.Fatalf("read retained card access = %v", err)
}
if storedCandidate != candidate.ID || storedOrganization != organization.ID() || storedActor.Valid ||
kind != string(domain.CandidateCardAccessCardViewed) || len(fields) != 0 {
t.Fatalf("retained access = candidate %s org %s actor %+v kind %s fields %v", storedCandidate, storedOrganization, storedActor, kind, fields)
}
}
func containsWord(column, word string) bool {
for _, part := range splitIdentifier(column) {
if part == word {
+446
View File
@@ -0,0 +1,446 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
httpadapter "lincodex/backend/internal/adapter/primary/http"
"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/port/outbound"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
needusecase "lincodex/backend/internal/usecase/need"
"lincodex/backend/internal/usecase/organization"
)
func TestOrganizationNeedOwnerWorkflowOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout)
defer cancel()
harness := newNeedHTTPHarness(ctx, t, env)
resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"})
truncateTables(ctx, t, harness.pool, resetTables...)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
now := harness.clock.Now()
owner := createOrganizationHTTPUser(ctx, t, harness, "need-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now)
foreign := createOrganizationHTTPUser(ctx, t, harness, "need-foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now)
recruiter := createOrganizationHTTPUser(ctx, t, harness, "need-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now)
candidate := createOrganizationHTTPUser(ctx, t, harness, "need-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now)
unverified := createOrganizationHTTPUser(ctx, t, harness, "need-unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now)
ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address())
foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address())
recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address())
candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address())
unverifiedLogin := loginSessionHTTP(t, harness, unverified.Email.Address(), sessionHTTPTestPass,
env.Config.AppPublicURL, "", "192.0.2.44:1234")
requireSessionProblem(t, unverifiedLogin, http.StatusForbidden, "email_not_verified")
organizationID := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "need-http-company")
insertOrganizationHTTPMembership(ctx, t, harness, organizationID, recruiter.ID, "recruiter", "active", now)
basePath := "/api/v1/organizations/" + organizationID.String() + "/needs"
initialSource := `{"title":"Payments backend","source_text":"Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно."}`
createdResponses := parallelNeedRequests(t, harness, http.MethodPost, basePath, initialSource,
env.Config.AppPublicURL, ownerSession, "need-http-create-1", 2)
if createdResponses[0].Code != http.StatusCreated || createdResponses[1].Code != http.StatusCreated ||
createdResponses[0].Header().Get("Cache-Control") != "no-store" || string(createdResponses[0].Body.Bytes()) != string(createdResponses[1].Body.Bytes()) {
t.Fatalf("concurrent need create responses = %d %s and %d %s, want the same 201 response",
createdResponses[0].Code, createdResponses[0].Body.String(), createdResponses[1].Code, createdResponses[1].Body.String())
}
originalBody := append([]byte(nil), createdResponses[0].Body.Bytes()...)
created := decodeNeedHTTPResponse(t, originalBody)
if created.ID == uuid.Nil || created.Version != 1 || created.RequirementsVersion != 1 || created.Recommendations.Status != string(domain.NeedRecommendationsNotAvailable) {
t.Fatalf("created need identity or recommendation state = %+v", created)
}
if created.Requirements.Specialization.Status != string(domain.NeedValueExtracted) ||
created.Requirements.Specialization.Source == nil || created.Requirements.Specialization.Source.Origin != string(domain.NeedValueExtractedFromText) ||
created.Requirements.Grade.Status != string(domain.NeedValueUnknown) || created.Requirements.Grade.Value != nil {
t.Fatalf("source extraction invented or omitted a need value: %+v", created.Requirements)
}
gotSkills := make([]string, 0, len(created.Requirements.RequiredSkills))
for _, skill := range created.Requirements.RequiredSkills {
if skill.Status == string(domain.NeedItemExtracted) && skill.Source.Origin == string(domain.NeedValueExtractedFromText) {
gotSkills = append(gotSkills, skill.Name)
}
}
if !equalNeedStrings(gotSkills, []string{"Go", "PostgreSQL", "Temporal"}) {
t.Fatalf("extracted required skills = %v, want Go, PostgreSQL, Temporal", gotSkills)
}
if len(created.Readiness.MissingFields) == 0 {
t.Fatal("incomplete source text need has no readiness questions")
}
needPath := basePath + "/" + created.ID.String()
changedKeyBody := `{"title":"Different request"}`
changedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, changedKeyBody,
env.Config.AppPublicURL, ownerSession, "need-http-create-1")
requireSessionProblem(t, changedKey, http.StatusUnprocessableEntity, "idempotency_key_reused")
invalidNUL := organizationHTTPRequest(t, harness, http.MethodPost, basePath,
`{"title":"Bad\u0000title"}`, env.Config.AppPublicURL, ownerSession, "need-http-invalid-nul")
requireSessionProblem(t, invalidNUL, http.StatusBadRequest, "validation_failed")
var invalidProblem struct {
Errors []struct {
Pointer string `json:"pointer"`
} `json:"errors"`
}
if err := json.Unmarshal(invalidNUL.Body.Bytes(), &invalidProblem); err != nil || len(invalidProblem.Errors) == 0 {
t.Fatalf("NUL validation body = %s, decode error %v", invalidNUL.Body.String(), err)
}
updated := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
`{"expected_version":1,"required_skills":[{"name":"Go","status":"confirmed"}]}`,
env.Config.AppPublicURL, ownerSession, "")
if updated.Code != http.StatusOK {
t.Fatalf("confirm extracted skill = %d %s, want 200", updated.Code, updated.Body.String())
}
confirmed := decodeNeedHTTPResponse(t, updated.Body.Bytes())
if confirmed.Version != 2 || confirmed.RequirementsVersion != 2 || confirmed.Recommendations.Status != string(domain.NeedRecommendationsPending) ||
len(confirmed.Requirements.RequiredSkills) != 1 || confirmed.Requirements.RequiredSkills[0].Name != "Go" ||
confirmed.Requirements.RequiredSkills[0].Status != string(domain.NeedItemConfirmed) {
t.Fatalf("confirmed need state = %+v", confirmed)
}
currentRead := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", ownerSession, "")
if currentRead.Code != http.StatusOK || string(currentRead.Body.Bytes()) == string(originalBody) {
t.Fatalf("current need read = %d %s, want edited current version", currentRead.Code, currentRead.Body.String())
}
immutableReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, initialSource,
env.Config.AppPublicURL, ownerSession, "need-http-create-1")
if immutableReplay.Code != http.StatusCreated || string(immutableReplay.Body.Bytes()) != string(originalBody) {
t.Fatalf("live create replay = %d %s, want the original 201 body %s", immutableReplay.Code, immutableReplay.Body.String(), originalBody)
}
expiryKeyBody := `{"title":"Boundary need"}`
expiryKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
if expiryKey.Code != http.StatusCreated {
t.Fatalf("create need for expiry boundary = %d %s, want 201", expiryKey.Code, expiryKey.Body.String())
}
expiryOriginal := decodeNeedHTTPResponse(t, expiryKey.Body.Bytes())
boundary := harness.clock.Now()
expired, err := harness.pool.Exec(ctx,
`UPDATE idempotency_records AS record
SET created_at = $1, expires_at = $2
WHERE EXISTS (
SELECT 1 FROM organization_need_creation_results AS result
WHERE result.scope_hash = record.scope_hash
AND result.snapshot #>> '{need,title}' = 'Boundary need'
)`,
boundary.Add(-outbound.IdempotencyRetention), boundary)
if err != nil {
t.Fatalf("expire need create key at exact 24-hour boundary: %v", err)
}
if expired.RowsAffected() != 1 {
t.Fatalf("expired need create rows = %d, want 1", expired.RowsAffected())
}
reusedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
if reusedKey.Code != http.StatusCreated {
t.Fatalf("create after exact 24-hour replay boundary = %d %s, want a new 201", reusedKey.Code, reusedKey.Body.String())
}
replacement := decodeNeedHTTPResponse(t, reusedKey.Body.Bytes())
if replacement.ID == expiryOriginal.ID || replacement.Version != 1 {
t.Fatalf("expired key reused old need snapshot: %+v", replacement)
}
expiredReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody,
env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary")
if expiredReplay.Code != http.StatusCreated || string(expiredReplay.Body.Bytes()) != string(reusedKey.Body.Bytes()) {
t.Fatalf("replay after expired-key reuse = %d %s, want exact replacement response %s", expiredReplay.Code, expiredReplay.Body.String(), reusedKey.Body.String())
}
identicalUpdates := parallelNeedRequests(t, harness, http.MethodPatch, needPath,
`{"expected_version":2,"title":"Platform engineer"}`, env.Config.AppPublicURL, ownerSession, "", 2)
for index, response := range identicalUpdates {
if response.Code != http.StatusOK {
t.Fatalf("identical concurrent update %d = %d %s, want 200", index, response.Code, response.Body.String())
}
}
concurrentCurrent := decodeNeedHTTPResponse(t, identicalUpdates[0].Body.Bytes())
if concurrentCurrent.Version != 3 || concurrentCurrent.Title != "Platform engineer" {
t.Fatalf("identical concurrent update result = version %d title %q, want version 3", concurrentCurrent.Version, concurrentCurrent.Title)
}
differentUpdates := parallelNeedRequestsWithBodies(t, harness, http.MethodPatch, needPath,
[]string{`{"expected_version":3,"title":"Payments platform"}`, `{"expected_version":3,"title":"Cloud platform"}`},
env.Config.AppPublicURL, ownerSession)
var winner needHTTPResponse
successes := 0
conflicts := 0
for index, response := range differentUpdates {
switch response.Code {
case http.StatusOK:
successes++
winner = decodeNeedHTTPResponse(t, response.Body.Bytes())
case http.StatusPreconditionFailed:
conflicts++
default:
t.Fatalf("different concurrent update %d = %d %s, want 200 or 412", index, response.Code, response.Body.String())
}
}
if successes != 1 || conflicts != 1 || winner.Version != 4 {
t.Fatalf("different concurrent updates had %d successes and %d conflicts; winner = %+v, want one version 4 success", successes, conflicts, winner)
}
staleNoOp := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
fmt.Sprintf(`{"expected_version":3,"title":%q}`, winner.Title), env.Config.AppPublicURL, ownerSession, "")
if staleNoOp.Code != http.StatusOK || decodeNeedHTTPResponse(t, staleNoOp.Body.Bytes()).Version != 4 {
t.Fatalf("stale no-op update = %d %s, want current version 4", staleNoOp.Code, staleNoOp.Body.String())
}
staleInvalid := organizationHTTPRequest(t, harness, http.MethodPatch, needPath,
`{"expected_version":3,"required_skills":[{"name":"Go","status":"confirmed"},{"name":"go","status":"confirmed"}]}`,
env.Config.AppPublicURL, ownerSession, "")
requireSessionProblem(t, staleInvalid, http.StatusPreconditionFailed, "version_conflict")
secondNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Second need"}`,
env.Config.AppPublicURL, ownerSession, "need-http-create-2")
thirdNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Third need"}`,
env.Config.AppPublicURL, ownerSession, "need-http-create-3")
if secondNeed.Code != http.StatusCreated || thirdNeed.Code != http.StatusCreated {
t.Fatalf("create needs for pagination = %d %s and %d %s, want 201", secondNeed.Code, secondNeed.Body.String(), thirdNeed.Code, thirdNeed.Body.String())
}
firstPage := readNeedHTTPPage(t, harness, ownerSession, basePath+"?limit=1")
if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" {
t.Fatalf("first need page = %+v, want one item and cursor", firstPage)
}
secondPage := readNeedHTTPPage(t, harness, ownerSession,
basePath+"?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor))
if len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil ||
firstPage.Items[0].ID == secondPage.Items[0].ID {
t.Fatalf("second need page = %+v, want the next distinct item", secondPage)
}
for _, test := range []struct {
name string
session organizationHTTPSession
want int
}{
{name: "foreign owner", session: foreignSession, want: http.StatusNotFound},
{name: "active recruiter", session: recruiterSession, want: http.StatusForbidden},
{name: "candidate", session: candidateSession, want: http.StatusForbidden},
} {
t.Run(test.name, func(t *testing.T) {
response := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", test.session, "")
if response.Code != test.want {
t.Fatalf("need read = %d %s, want %d", response.Code, response.Body.String(), test.want)
}
if strings.Contains(response.Body.String(), "Payments backend") || strings.Contains(response.Body.String(), "PostgreSQL") {
t.Fatalf("denied response contains need data: %s", response.Body.String())
}
})
}
var versionCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM organization_need_versions WHERE organization_id = $1 AND need_id = $2", organizationID, created.ID).Scan(&versionCount); err != nil {
t.Fatalf("read immutable need history: %v", err)
}
if versionCount != 4 {
t.Fatalf("need history rows = %d, want 4", versionCount)
}
}
type needHTTPResponse struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
Version int64 `json:"version"`
RequirementsVersion int64 `json:"requirements_version"`
Requirements struct {
Specialization struct {
Status string `json:"status"`
Value *string `json:"value"`
Source *struct {
Origin string `json:"origin"`
} `json:"source"`
} `json:"specialization"`
Grade struct {
Status string `json:"status"`
Value *string `json:"value"`
} `json:"grade"`
RequiredSkills []struct {
Name string `json:"name"`
Status string `json:"status"`
Source struct {
Origin string `json:"origin"`
} `json:"source"`
} `json:"required_skills"`
} `json:"requirements"`
Readiness struct {
MissingFields []json.RawMessage `json:"missing_fields"`
} `json:"readiness"`
Recommendations struct {
Status string `json:"status"`
} `json:"recommendations"`
}
func decodeNeedHTTPResponse(t *testing.T, encoded []byte) needHTTPResponse {
t.Helper()
var response needHTTPResponse
if err := json.Unmarshal(encoded, &response); err != nil {
t.Fatalf("decode need response: %v", err)
}
return response
}
func equalNeedStrings(left, right []string) bool {
if len(left) != len(right) {
return false
}
for index := range left {
if left[index] != right[index] {
return false
}
}
return true
}
type needHTTPPage struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
NextCursor *string `json:"next_cursor"`
} `json:"page"`
}
func readNeedHTTPPage(t *testing.T, harness *sessionHTTPHarness, session organizationHTTPSession, path string) needHTTPPage {
t.Helper()
response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "")
if response.Code != http.StatusOK {
t.Fatalf("list organization needs = %d %s, want 200", response.Code, response.Body.String())
}
var page needHTTPPage
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
t.Fatalf("decode need list response: %v", err)
}
return page
}
func parallelNeedRequests(
t *testing.T,
harness *sessionHTTPHarness,
method, path, body, origin string,
session organizationHTTPSession,
idempotencyKey string,
count int,
) []*httptest.ResponseRecorder {
t.Helper()
responses := make([]*httptest.ResponseRecorder, count)
var group sync.WaitGroup
start := make(chan struct{})
for index := range count {
group.Go(func() {
<-start
responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, idempotencyKey)
})
}
close(start)
group.Wait()
return responses
}
func parallelNeedRequestsWithBodies(
t *testing.T,
harness *sessionHTTPHarness,
method, path string,
bodies []string,
origin string,
session organizationHTTPSession,
) []*httptest.ResponseRecorder {
t.Helper()
responses := make([]*httptest.ResponseRecorder, len(bodies))
var group sync.WaitGroup
start := make(chan struct{})
for index, body := range bodies {
group.Go(func() {
<-start
responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, "")
})
}
close(start)
group.Wait()
return responses
}
func newNeedHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
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)}
sessionService, err := identity.NewSessionService(identity.SessionDependencies{
Transactor: postgresadapter.NewTransactor(pool),
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)
}
organizationService, err := organization.NewService(organization.Dependencies{
Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now,
})
if err != nil {
t.Fatalf("organization.NewService() error = %v", err)
}
needService, err := needusecase.NewService(needusecase.Dependencies{
Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now,
})
if err != nil {
t.Fatalf("need.NewService() error = %v", err)
}
logs := &strings.Builder{}
logger := slog.New(slog.NewJSONHandler(io.Discard, nil))
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
identityHandler := v1.NewIdentityHandler(nil,
v1.WithSessionService(sessionService),
v1.WithPublicOrigin(env.Config.AppPublicURL),
)
organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL)
needHandler := v1.NewNeedHandler(needService)
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), v1.WithNeed(needHandler),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler))
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
}
func needHTTPPath(organizationID, needID uuid.UUID) string {
return fmt.Sprintf("/api/v1/organizations/%s/needs/%s", organizationID, needID)
}
+196 -1
View File
@@ -14,6 +14,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
@@ -310,13 +311,207 @@ func TestOrganizationNeedsStorage(t *testing.T) {
largeID := uuid.New()
body["id"] = largeID.String()
body["requirements_version"] = 1
body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotBytes+1)
body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotStorageBytes+1)
oversized, err := json.Marshal(body)
if err != nil {
t.Fatalf("encode oversized storage snapshot: %v", err)
}
insertRejectedSnapshot(largeID, oversized, "insert oversized snapshot")
})
t.Run("maximum bounded need shape stays within JSONB representation headroom", func(t *testing.T) {
reset(t)
owner := fixture.employer(t, "owner@example.com")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Большой профиль"), now)
maximum := maximumBoundedIntegrationNeed(t, organization.ID(), now.Add(time.Minute))
compact, err := json.Marshal(maximum.Snapshot())
if err != nil {
t.Fatalf("marshal maximum bounded need: %v", err)
}
if len(compact) > domain.MaxNeedSnapshotBytes {
t.Fatalf("maximum bounded need compact JSON = %d bytes, exceeds %d", len(compact), domain.MaxNeedSnapshotBytes)
}
if len(compact) < 64*1024 {
t.Fatalf("maximum bounded need compact JSON = %d bytes, want a substantial combined source and requirement payload", len(compact))
}
fixture.createNeed(t, maximum)
var storedBytes int
if err := pool.QueryRow(ctx, `
SELECT octet_length(snapshot::text)
FROM organization_need_versions
WHERE organization_id = $1 AND need_id = $2 AND version = 1
`, organization.ID(), maximum.ID()).Scan(&storedBytes); err != nil {
t.Fatalf("measure maximum need JSONB text size: %v", err)
}
if storedBytes < len(compact) || storedBytes-len(compact) > domain.MaxNeedJSONBTextHeadroom || storedBytes > domain.MaxNeedSnapshotStorageBytes {
t.Fatalf("maximum need storage = %d bytes, compact=%d headroom=%d; want storage within the explicit JSONB margin",
storedBytes, len(compact), domain.MaxNeedJSONBTextHeadroom)
}
if _, err := fixture.getNeed(organization.ID(), maximum.ID()); err != nil {
t.Fatalf("restore maximum bounded need: %v", err)
}
})
}
func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("apply migrations to rollback test database: %v", err)
}
pool := newPoolFor(ctx, t, databaseURL)
now := time.Now().UTC().Truncate(time.Microsecond)
fixture := organizationFixture{
ctx: ctx, pool: pool,
identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now},
transactor: postgresadapter.NewTransactor(pool), now: now,
}
scope := []byte(strings.Repeat("s", outbound.IdempotencyDigestSize))
fingerprint := []byte(strings.Repeat("f", outbound.IdempotencyDigestSize))
if _, err := pool.Exec(ctx, `
INSERT INTO idempotency_records (scope_hash, fingerprint, created_at, expires_at)
VALUES ($1, $2, $3, $4)
`, scope, fingerprint, now, now.Add(outbound.IdempotencyRetention)); err != nil {
t.Fatalf("insert live idempotency row: %v", err)
}
if _, err := pool.Exec(ctx, `
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
VALUES ($1, '{"need":{},"readiness":{},"recommendations":{}}'::jsonb)
`, scope); err != nil {
t.Fatalf("insert live creation result: %v", err)
}
if _, err := migrator.DownOne(ctx); err == nil {
t.Fatal("DownOne() succeeded while a need creation replay remained live")
}
assertNeedResultMigrationPresent(ctx, t, pool, 1)
if _, err := pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2 WHERE scope_hash = $3",
now.Add(-outbound.IdempotencyRetention-time.Second), now.Add(-time.Second), scope); err != nil {
t.Fatalf("expire idempotency replay before checking historical bounds: %v", err)
}
owner := fixture.employer(t, "need-migration-owner@example.test")
organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now)
need := newIntegrationNeed(t, organization.ID(), "Bounded rollback fixture", now.Add(time.Minute))
encoded, err := json.Marshal(need.Snapshot())
if err != nil {
t.Fatalf("marshal rollback snapshot: %v", err)
}
var body map[string]any
if err := json.Unmarshal(encoded, &body); err != nil {
t.Fatalf("decode rollback snapshot: %v", err)
}
body["rollback_bound_fixture"] = strings.Repeat("p", 265000)
encoded, err = json.Marshal(body)
if err != nil {
t.Fatalf("encode rollback-bound snapshot: %v", err)
}
var storageSize int
if err := pool.QueryRow(ctx, "SELECT octet_length($1::jsonb::text)", encoded).Scan(&storageSize); err != nil {
t.Fatalf("measure rollback-bound snapshot: %v", err)
}
if storageSize <= domain.MaxNeedSnapshotBytes || storageSize > domain.MaxNeedSnapshotStorageBytes {
t.Fatalf("rollback fixture JSONB size = %d, want (%d, %d]", storageSize, domain.MaxNeedSnapshotBytes, domain.MaxNeedSnapshotStorageBytes)
}
tx, err := pool.Begin(ctx)
if err != nil {
t.Fatalf("begin oversized-history fixture transaction: %v", err)
}
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
if _, err := tx.Exec(ctx, `
INSERT INTO organization_needs (id, organization_id, current_version, requirements_version, created_at, updated_at)
VALUES ($1, $2, 1, 1, $3, $3)
`, need.ID(), organization.ID(), now.Add(time.Minute)); err != nil {
t.Fatalf("insert oversized-history need parent: %v", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO organization_need_versions (organization_id, need_id, version, snapshot)
VALUES ($1, $2, 1, $3::jsonb)
`, organization.ID(), need.ID(), encoded); err != nil {
t.Fatalf("insert snapshot within current storage bound: %v", err)
}
if err := tx.Commit(ctx); err != nil {
t.Fatalf("commit oversized-history fixture: %v", err)
}
if _, err := migrator.DownOne(ctx); err == nil {
t.Fatal("DownOne() succeeded while retained need history exceeded the prior bound")
}
assertNeedResultMigrationPresent(ctx, t, pool, 1)
}
func assertNeedResultMigrationPresent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, resultRows int64) {
t.Helper()
var tableExists bool
var rows int64
if err := pool.QueryRow(ctx, `
SELECT to_regclass('organization_need_creation_results') IS NOT NULL,
(SELECT count(*) FROM organization_need_creation_results)
`).Scan(&tableExists, &rows); err != nil {
t.Fatalf("inspect migration preflight after rollback attempt: %v", err)
}
if !tableExists || rows != resultRows {
t.Fatalf("migration rollback changed state: result table exists=%t rows=%d, want true/%d", tableExists, rows, resultRows)
}
}
func maximumBoundedIntegrationNeed(t *testing.T, organizationID uuid.UUID, at time.Time) domain.Need {
t.Helper()
quote := strings.Repeat("q", 300)
extractedVersion := int64(1)
extractor := "need-rules.2026-10.1"
source := domain.NeedValueSource{
Origin: domain.NeedValueExtractedFromText, Quote: &quote,
ExtractedInVersion: &extractedVersion, ExtractionVersion: &extractor,
}
makeSkills := func(prefix string) []domain.NeedSkill {
skills := make([]domain.NeedSkill, 0, 30)
for index := range 30 {
name := fmt.Sprintf("%s-%02d-%s", prefix, index, strings.Repeat("s", 80))
skills = append(skills, domain.NeedSkill{Name: name, Status: domain.NeedItemExtracted, Source: source})
}
return skills
}
tasks := make([]domain.NeedTask, 0, 20)
for index := range 20 {
prefix := fmt.Sprintf("task-%02d-", index)
tasks = append(tasks, domain.NeedTask{
Text: prefix + strings.Repeat("t", 290-len(prefix)), Status: domain.NeedItemExtracted, Source: source,
})
}
rejected := make([]domain.NeedRejectedSuggestion, 0, domain.MaxNeedRejectedSuggestions)
for index := range domain.MaxNeedRejectedSuggestions {
rejected = append(rejected, domain.NeedRejectedSuggestion{
Field: domain.NeedRejectedSkills, Value: fmt.Sprintf("rejected-%02d-%s", index, strings.Repeat("r", 280)),
})
}
manual := &domain.NeedValueSource{Origin: domain.NeedValueManual}
formats := []domain.NeedWorkFormat{domain.NeedWorkFormatRemote, domain.NeedWorkFormatOffice, domain.NeedWorkFormatHybrid}
grade := domain.GradeSenior
specialization := domain.SpecializationBackend
domainName := strings.Repeat("d", 100)
location := strings.Repeat("l", 100)
formatValue := formats
salary := domain.NeedSalaryRange{SalaryFrom: 100000, SalaryTo: 120000, Currency: "RUB", Period: "month", TaxBasis: "gross"}
requirements := domain.NeedRequirements{
Specialization: domain.NeedValue[domain.SpecializationCode]{Status: domain.NeedValueConfirmed, Value: &specialization, Source: manual},
Grade: domain.NeedValue[domain.GradeCode]{Status: domain.NeedValueConfirmed, Value: &grade, Source: manual},
RequiredSkills: makeSkills("required"), DesiredSkills: makeSkills("desired"), Tasks: tasks,
Domain: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &domainName, Source: manual},
WorkFormats: domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueConfirmed, Value: &formatValue, Source: manual},
Location: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &location, Source: manual},
Salary: domain.NeedValue[domain.NeedSalaryRange]{Status: domain.NeedValueConfirmed, Value: &salary, Source: manual},
}
need, err := domain.NewNeed(domain.NeedSnapshot{
ID: uuid.New(), OrganizationID: organizationID, Title: strings.Repeat("n", 200), SourceText: needIntegrationPointer(strings.Repeat("s", 10000)),
Version: 1, RequirementsVersion: 1, Requirements: requirements, RejectedSuggestions: rejected,
CreatedAt: at, UpdatedAt: at,
})
if err != nil {
t.Fatalf("NewNeed(maximum bounded shape) error = %v", err)
}
return need
}
func (fixture organizationFixture) createNeed(t *testing.T, need domain.Need) {
+11 -1
View File
@@ -39,17 +39,27 @@ var (
// organizationTables are emptied together: memberships reference both
// users and organizations. Creation snapshots reference idempotency records.
organizationTables = []pgx.Identifier{
{"candidate_card_access_events"},
{"organization_need_versions"}, {"organization_needs"},
{"organization_need_creation_results"},
{"company_invitation_quota_usage"}, {"company_card_view_quota_usage"},
organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable,
}
candidateQuestionnaireTables = []pgx.Identifier{
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
}
assessmentAttemptTables = []pgx.Identifier{
{"assessment_attempt_results"},
{"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"},
{"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"},
}
supportCaseTables = []pgx.Identifier{
{"support_case_events"}, {"support_cases"}, {"support_case_create_outcomes"}, {"support_case_request_events"},
}
// usersDependentTables is every table that references users, directly or
// through another table of the list. A TRUNCATE of users must name all of
// them, so a migration that adds such a table adds it here.
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables)
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables, assessmentAttemptTables, supportCaseTables)
)
// organizationFixture works on the bootstrap database. The tables are
+6 -2
View File
@@ -242,9 +242,13 @@ func TestPolicyVersions(t *testing.T) {
SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '99') WHERE id = $1`, args: []any{id}},
{name: "delete", sql: `DELETE FROM policy_versions WHERE id = $1`, args: []any{id}},
{name: "delete of every row", sql: `DELETE FROM policy_versions`},
// Include referencing quota tables so PostgreSQL reaches the
// Include referencing tables so PostgreSQL reaches the
// immutable-policy trigger instead of its foreign-key precheck.
{name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage, company_card_view_quota_usage`},
{name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage,
company_card_view_quota_usage, assessment_training_bank_bindings,
assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items,
support_cases, support_case_events, assessment_signal_idempotency_outcomes,
assessment_signal_events, assessment_signal_batches, assessment_attempt_results`},
}
for _, statement := range statements {
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
@@ -0,0 +1,248 @@
//go:build integration
package integration_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/anonymousprofile"
"lincodex/backend/internal/usecase/policy"
"github.com/google/uuid"
)
func TestOrganizationAnonymousCandidateProjectionHonorsC2AndHiding(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
now := time.Now().UTC().Truncate(time.Microsecond)
identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}
policies := postgresadapter.NewPolicyStore(pool)
if _, err := policy.NewPublisher(policies.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
fixture := candidatePrivacyFixture{
ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity,
organizations: organizationFixture{
ctx: ctx, pool: pool, identity: identity,
transactor: postgresadapter.NewTransactor(pool), now: now,
},
ledger: postgresadapter.NewConsentStore(pool), now: now,
}
truncateTables(ctx, t, pool, usersDependentTables...)
owner := fixture.organizations.employer(t, "owner@example.test")
organization := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Projection test organization"), now)
organizationB := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Projection test organization B"), now)
profiles := candidateProfileFixture{ctx: ctx, pool: pool, queries: fixture.queries, identity: identity, now: now}
visible := make([]uuid.UUID, 0, 5)
for index := range 5 {
candidate := fixture.candidate(t, fmt.Sprintf("visible-%d@example.test", index))
verifyPrivacyCohortCandidate(t, fixture, candidate)
consent := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(time.Duration(index)*time.Second))
fixture.publish(t, candidate.ID, consent.ID(), 0,
domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience,
domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility,
)
profiles.save(t, candidate.ID, domain.CandidateProfileInput{
FullName: confirmedDecision("Private Name Marker"),
Email: confirmedDecision("private-contact-marker@example.test"),
Stack: privacyCohortConfirmedItems(
"go", "UniqueStackMarker",
),
Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}),
Experience: privacyCohortConfirmedItems(domain.ProfileExperience{
EmployerName: "Private Employer Marker", Specialization: domain.SpecializationBackend,
StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private Summary Marker",
}),
SoftSkills: privacyCohortConfirmedItems("Private Soft Skill Marker"),
Location: confirmedDecision("Private Location Marker"),
SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{
Amount: 180_000, TaxBasis: domain.ProfileTaxNet,
}),
}, 0)
if _, err := fixture.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{
UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now),
}); err != nil {
t.Fatalf("InsertCandidateQuestionnaire() error = %v", err)
}
visible = append(visible, candidate.ID)
}
hidden := fixture.candidate(t, "hidden@example.test")
verifyPrivacyCohortCandidate(t, fixture, hidden)
hiddenConsent := fixture.grant(t, hidden.ID, domain.ConsentPurposePublication, privacyC2Version, now)
fixture.publish(t, hidden.ID, hiddenConsent.ID(), 0, domain.CardFieldStack)
fixture.hide(t, hidden.ID, organization.ID(), now)
revoked := fixture.candidate(t, "revoked@example.test")
verifyPrivacyCohortCandidate(t, fixture, revoked)
revokedConsent := fixture.grant(t, revoked.ID, domain.ConsentPurposePublication, privacyC2Version, now)
fixture.publish(t, revoked.ID, revokedConsent.ID(), 0, domain.CardFieldStack)
fixture.revokeC2(t, revoked.ID, now.Add(time.Minute))
reader := postgresadapter.NewPrivacyCohortStore(pool)
sources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID())
if err != nil {
t.Fatalf("ListVisibleCandidateViewSources() error = %v", err)
}
if len(sources) != len(visible) {
t.Fatalf("visible sources = %d, want %d after excluding hidden and revoked candidates", len(sources), len(visible))
}
sourcesB, err := reader.ListVisibleCandidateViewSources(ctx, organizationB.ID())
if err != nil {
t.Fatalf("ListVisibleCandidateViewSources(B) error = %v", err)
}
sourcesAAgain, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID())
if err != nil {
t.Fatalf("ListVisibleCandidateViewSources(A again) error = %v", err)
}
if len(sourcesB) != len(visible)+1 || len(sourcesAAgain) != len(visible) {
t.Fatalf("visible sources A/B/A = %d/%d/%d, want %d/6/%d with B still seeing the organization-hidden candidate", len(sources), len(sourcesB), len(sourcesAAgain), len(visible), len(visible))
}
candidateID := sources[0].CandidateID()
if !privacyCohortHasSource(sourcesB, candidateID) || !privacyCohortHasSource(sourcesAAgain, candidateID) {
t.Fatal("the same candidate was not visible in repository reads A/B/A")
}
key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("dedicated-anonymous-view-key"), 2))
if err != nil {
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
}
aliasA, err := key.ForOrganization(organization.ID(), candidateID)
if err != nil {
t.Fatalf("ForOrganization(A) error = %v", err)
}
aliasB, err := key.ForOrganization(organizationB.ID(), candidateID)
if err != nil {
t.Fatalf("ForOrganization(B) error = %v", err)
}
aliasAAgain, err := key.ForOrganization(organization.ID(), candidateID)
if err != nil {
t.Fatalf("ForOrganization(A again) error = %v", err)
}
if aliasA != aliasAAgain || aliasA == aliasB {
t.Fatalf("repository-backed A/B/A aliases = %q/%q/%q, want stable A and distinct B", aliasA, aliasB, aliasAAgain)
}
service := anonymousprofile.NewService(reader, key, func() time.Time { return now.Add(2 * time.Minute) })
views, err := service.ListVisible(ctx, organization.ID())
if err != nil {
t.Fatalf("ListVisible() error = %v", err)
}
if len(views) != 5 {
t.Fatalf("ListVisible() returned %d views, want the five-member cohort", len(views))
}
if !privacyCohortHasViewAlias(views, aliasA) {
t.Fatal("organization A projection did not contain its stable candidate alias")
}
viewsB, err := service.ListVisible(ctx, organizationB.ID())
if err != nil {
t.Fatalf("ListVisible(B) error = %v", err)
}
viewsAAgain, err := service.ListVisible(ctx, organization.ID())
if err != nil {
t.Fatalf("ListVisible(A again) error = %v", err)
}
if len(viewsB) != 5 || !privacyCohortHasViewAlias(viewsB, aliasB) || !privacyCohortHasViewAlias(viewsAAgain, aliasAAgain) {
t.Fatalf("service projection A/B/A = %d/%d/%d aliases present=%t/%t", len(views), len(viewsB), len(viewsAAgain), privacyCohortHasViewAlias(viewsB, aliasB), privacyCohortHasViewAlias(viewsAAgain, aliasAAgain))
}
for _, view := range views {
if view.ExperienceBand == nil || *view.ExperienceBand != domain.CandidateExperienceBandThreeToSix {
t.Errorf("experience band = %v, want 3_6", view.ExperienceBand)
}
if len(view.Skills) != 1 || view.Skills[0] != domain.CandidateViewSkillGo {
t.Errorf("skills = %v, want only the recognized canonical value", view.Skills)
}
if len(view.WorkFormats) != 1 || view.WorkFormats[0] != domain.QuestionnaireWorkFormatRemote {
t.Errorf("work formats = %v, want explicitly selected remote", view.WorkFormats)
}
if len(view.Categories) != 0 || len(view.SelfAssessment) != 1 || view.SelfAssessment[0].DeclaredGrade == nil {
t.Errorf("confirmed categories and self-assessment were not kept separate: categories=%v self_assessment=%v", view.Categories, view.SelfAssessment)
}
if view.SalaryCompatibility != nil {
t.Errorf("salary compatibility = %v, want unknown without an approved computed result", view.SalaryCompatibility)
}
}
encoded, err := json.Marshal(views)
if err != nil {
t.Fatalf("Marshal() error = %v", err)
}
for _, marker := range []string{
"Private Name Marker", "private-contact-marker@example.test", "Private Employer Marker",
"Private Summary Marker", "Private Soft Skill Marker", "Private Location Marker",
"UniqueStackMarker", "180000", hidden.ID.String(), revoked.ID.String(),
} {
if strings.Contains(string(encoded), marker) {
t.Errorf("organization-facing cohort contains private marker %q", marker)
}
}
fixture.hide(t, visible[0], organization.ID(), now.Add(3*time.Minute))
fourSources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID())
if err != nil {
t.Fatalf("ListVisibleCandidateViewSources(four) error = %v", err)
}
fourViews, err := service.ListVisible(ctx, organization.ID())
if err != nil {
t.Fatalf("ListVisible(four) error = %v", err)
}
if len(fourSources) != 4 || len(fourViews) != 0 {
t.Fatalf("cohort of four sources/views = %d/%d, want 4/0 after suppression", len(fourSources), len(fourViews))
}
for index := 1; index < len(visible)-1; index++ {
fixture.hide(t, visible[index], organization.ID(), now.Add(time.Duration(index+3)*time.Minute))
}
oneSources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID())
if err != nil {
t.Fatalf("ListVisibleCandidateViewSources(one) error = %v", err)
}
oneViews, err := service.ListVisible(ctx, organization.ID())
if err != nil {
t.Fatalf("ListVisible(one) error = %v", err)
}
if len(oneSources) != 1 || len(oneViews) != 0 {
t.Fatalf("cohort of one source/view = %d/%d, want 1/0 after suppression", len(oneSources), len(oneViews))
}
}
func privacyCohortHasSource(sources []domain.CandidateViewSource, candidateID uuid.UUID) bool {
for _, source := range sources {
if source.CandidateID() == candidateID {
return true
}
}
return false
}
func privacyCohortHasViewAlias(views []domain.AnonymousCandidateViewDTO, alias string) bool {
for _, view := range views {
if view.Pseudonym == alias {
return true
}
}
return false
}
func verifyPrivacyCohortCandidate(t *testing.T, fixture candidatePrivacyFixture, candidate domain.User) {
t.Helper()
if _, err := fixture.identity.store.Users().MarkEmailVerified(fixture.ctx, candidate.ID, candidate.RegistrationVersion, fixture.now); err != nil {
t.Fatalf("MarkEmailVerified() error = %v", err)
}
}
func privacyCohortConfirmedItems[V comparable](values ...V) []domain.ProfileClaimInput[V] {
items := make([]domain.ProfileClaimInput[V], 0, len(values))
for _, value := range values {
items = append(items, domain.ProfileClaimInput[V]{Value: value, Status: domain.ProfileClaimConfirmed})
}
return items
}
@@ -0,0 +1,746 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
httpadapter "lincodex/backend/internal/adapter/primary/http"
"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/health"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/policy"
"lincodex/backend/internal/usecase/supportcase"
)
const supportCaseHTTPTimeout = 5 * time.Minute
type supportCaseHTTPHarness struct {
*sessionHTTPHarness
supportClock *testClock
}
func TestSupportCasesOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
owner := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "support-owner@example.test", passwordHash, true)
other := createSupportCaseHTTPEmployer(ctx, t, harness, "support-other@example.test", passwordHash)
ownerLogin := loginSessionHTTP(t, harness.sessionHTTPHarness, owner.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.231:1234")
otherLogin := loginSessionHTTP(t, harness.sessionHTTPHarness, other.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.232:1234")
ownerCookie, ownerCSRF := supportCaseLoginCredentials(t, ownerLogin)
otherCookie, otherCSRF := supportCaseLoginCredentials(t, otherLogin)
if got := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases", "", "", "", "", "192.0.2.233:1234").Code; got != http.StatusUnauthorized {
t.Fatalf("guest list status = %d, want 401", got)
}
createSupport := `{"type":"support","description":"The assessment is unavailable; please help with access."}`
created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport,
ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.234:1234")
if created.Code != http.StatusCreated || created.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("create support case = %d Cache-Control=%q: %s, want 201 no-store; server logs: %s", created.Code,
created.Header().Get("Cache-Control"), created.Body.String(), harness.logs.String())
}
var createdBody supportCaseHTTPResponse
if err := json.Unmarshal(created.Body.Bytes(), &createdBody); err != nil {
t.Fatalf("decode created support case: %v", err)
}
if createdBody.ID == "" || createdBody.Number == "" || createdBody.Type != "support" || createdBody.Status != "submitted" ||
createdBody.Description != "The assessment is unavailable; please help with access." || len(createdBody.History) != 1 || createdBody.History[0].Kind != "created" {
t.Fatalf("created support case = %+v", createdBody)
}
replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport,
ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.235:1234")
if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() {
t.Fatalf("same-key replay = %d %s, want original 201 body %s", replay.Code, replay.Body.String(), created.Body.String())
}
var supportCaseCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM support_cases WHERE id = $1::uuid", createdBody.ID).Scan(&supportCaseCount); err != nil {
t.Fatalf("count idempotent support case: %v", err)
}
if supportCaseCount != 1 {
t.Fatalf("same-key support create stored %d cases, want exactly one", supportCaseCount)
}
changedBody := `{"type":"support","description":"The assessment result is missing; please investigate."}`
changedReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", changedBody,
ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.235:1236")
requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused")
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3)
assertSupportCaseCount(t, ctx, harness, owner.ID, 1)
csrfDenied := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport,
ownerCookie, "", "support-csrf-denied", "192.0.2.235:1237")
requireSessionProblem(t, csrfDenied, http.StatusForbidden, "csrf_check_failed")
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3)
assertSupportCaseCount(t, ctx, harness, owner.ID, 1)
ownRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+createdBody.ID,
"", ownerCookie, "", "", "192.0.2.235:1235")
var ownReadBody supportCaseHTTPResponse
if ownRead.Code != http.StatusOK || ownRead.Header().Get("Cache-Control") != "no-store" ||
json.Unmarshal(ownRead.Body.Bytes(), &ownReadBody) != nil || ownReadBody.ID != createdBody.ID ||
ownReadBody.Number != createdBody.Number || ownReadBody.Status != "submitted" {
t.Fatalf("owner GET = %d Cache-Control=%q %s, want own submitted case %s", ownRead.Code,
ownRead.Header().Get("Cache-Control"), ownRead.Body.String(), createdBody.ID)
}
manualBody := `{"type":"manual_assessment","description":"Please assess my Go skills.","assessment_target":{"specialization":"backend","grade":"junior"}}`
manual := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody,
ownerCookie, ownerCSRF, "support-manual-1", "192.0.2.236:1234")
if manual.Code != http.StatusCreated {
t.Fatalf("manual assessment request without C3 or an earlier attempt = %d %s, want 201", manual.Code, manual.Body.String())
}
var manualCase supportCaseHTTPResponse
if err := json.Unmarshal(manual.Body.Bytes(), &manualCase); err != nil {
t.Fatalf("decode manual assessment request: %v", err)
}
if manualCase.Type != "manual_assessment" || manualCase.Status != "waiting_expert" || len(manualCase.History) != 2 ||
manualCase.History[1].Kind != "status_changed" || manualCase.RubricVersion != nil ||
manualCase.ResponseTarget.BusinessDays != 5 || manualCase.ResponseTarget.Kind != "operational_goal" {
t.Fatalf("manual assessment request = %+v, want expert queue, optional rubric, and five-day operational target", manualCase)
}
manualRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+manualCase.ID,
"", ownerCookie, "", "", "192.0.2.236:1235")
var manualReadBody supportCaseHTTPResponse
if manualRead.Code != http.StatusOK || json.Unmarshal(manualRead.Body.Bytes(), &manualReadBody) != nil ||
manualReadBody.ID != manualCase.ID || manualReadBody.Status != "waiting_expert" || manualReadBody.RubricVersion != nil {
t.Fatalf("manual case GET = %d %s, want unchanged waiting_expert case without a rubric", manualRead.Code, manualRead.Body.String())
}
var attemptCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id = $1", owner.ID).Scan(&attemptCount); err != nil {
t.Fatalf("read assessment attempts: %v", err)
}
if attemptCount != 0 {
t.Fatalf("manual request unexpectedly has %d prior assessment attempts", attemptCount)
}
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 4)
duplicateManual := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody,
ownerCookie, ownerCSRF, "support-manual-conflict", "192.0.2.236:1236")
requireSessionProblem(t, duplicateManual, http.StatusConflict, "state_conflict")
duplicateManualReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody,
ownerCookie, ownerCSRF, "support-manual-conflict", "192.0.2.236:1237")
requireSessionProblem(t, duplicateManualReplay, http.StatusConflict, "state_conflict")
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 6)
var openManualCount int64
if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM support_cases
WHERE owner_id = $1 AND case_type = 'manual_assessment' AND status NOT IN ('resolved', 'closed')`, owner.ID).
Scan(&openManualCount); err != nil {
t.Fatalf("count open manual assessment cases: %v", err)
}
if openManualCount != 1 {
t.Fatalf("duplicate manual request created %d open cases, want one", openManualCount)
}
invalidDescription := `{"type":"support","description":"\u0085"}`
invalidDomain := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", invalidDescription,
ownerCookie, ownerCSRF, "support-invalid-description", "192.0.2.236:1238")
requireSessionProblem(t, invalidDomain, http.StatusBadRequest, "validation_failed")
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 7)
invalidDomainRetry := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", invalidDescription,
ownerCookie, ownerCSRF, "support-invalid-description", "192.0.2.236:1239")
requireSessionProblem(t, invalidDomainRetry, http.StatusBadRequest, "validation_failed")
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 8)
var consentCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", owner.ID).Scan(&consentCount); err != nil {
t.Fatalf("read consent side effects: %v", err)
}
if consentCount != 0 {
t.Fatalf("manual assessment changed consent records to %d, want none", consentCount)
}
companyLimited := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody,
otherCookie, otherCSRF, "support-employer-manual", "192.0.2.236:1241")
requireSessionProblem(t, companyLimited, http.StatusForbidden, "forbidden")
requireSupportCaseRequestCount(t, ctx, harness, other.ID, 0)
resetSupportCaseRequestEvents(t, ctx, harness, owner.ID)
harness.supportClock.Advance(24 * time.Hour)
expiredKeyBody := `{"type":"support","description":"The original support key expired and was accepted again."}`
expiredKeyRetry := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", expiredKeyBody,
ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.236:1240")
var expiredKeyCase supportCaseHTTPResponse
if expiredKeyRetry.Code != http.StatusCreated || json.Unmarshal(expiredKeyRetry.Body.Bytes(), &expiredKeyCase) != nil ||
expiredKeyCase.ID == createdBody.ID || expiredKeyCase.Number == createdBody.Number ||
expiredKeyCase.Description != "The original support key expired and was accepted again." {
t.Fatalf("same key at exact 24-hour expiry = %d %s, want a new 201 case", expiredKeyRetry.Code, expiredKeyRetry.Body.String())
}
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 1)
otherCase := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport,
otherCookie, otherCSRF, "support-other-1", "192.0.2.237:1234")
if otherCase.Code != http.StatusCreated {
t.Fatalf("other account create = %d %s, want 201", otherCase.Code, otherCase.Body.String())
}
var otherCaseBody supportCaseHTTPResponse
if err := json.Unmarshal(otherCase.Body.Bytes(), &otherCaseBody); err != nil {
t.Fatalf("decode other account case: %v", err)
}
foreignReference := fmt.Sprintf(`{"type":"support","description":"Reference another account's case.","object":{"type":"support_case","id":%q}}`, otherCaseBody.ID)
foreign := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", foreignReference,
ownerCookie, ownerCSRF, "support-foreign-1", "192.0.2.238:1234")
requireSessionProblem(t, foreign, http.StatusNotFound, "not_found")
foreignReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", foreignReference,
ownerCookie, ownerCSRF, "support-foreign-1", "192.0.2.239:1234")
requireSessionProblem(t, foreignReplay, http.StatusNotFound, "not_found")
requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3)
foreignRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+otherCaseBody.ID,
"", ownerCookie, "", "", "192.0.2.240:1234")
requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found")
list := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases", "", ownerCookie, "", "", "192.0.2.241:1234")
if list.Code != http.StatusOK || list.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("list own cases = %d Cache-Control=%q: %s", list.Code, list.Header().Get("Cache-Control"), list.Body.String())
}
var listBody struct {
Items []json.RawMessage `json:"items"`
}
if err := json.Unmarshal(list.Body.Bytes(), &listBody); err != nil {
t.Fatalf("decode own support case list: %v", err)
}
if len(listBody.Items) != 3 || strings.Contains(list.Body.String(), "The assessment is unavailable") || strings.Contains(list.Body.String(), "history") {
t.Fatalf("owner list leaked another case or full-case fields: %s", list.Body.String())
}
pageOne := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases?limit=1", "",
ownerCookie, "", "", "192.0.2.241:1235")
var firstPage struct {
Items []json.RawMessage `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
NextCursor *string `json:"next_cursor"`
} `json:"page"`
}
if pageOne.Code != http.StatusOK || json.Unmarshal(pageOne.Body.Bytes(), &firstPage) != nil ||
len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" {
t.Fatalf("first support-case page = %d %s, want a cursor for more results", pageOne.Code, pageOne.Body.String())
}
pageTwo := supportCaseHTTP(t, harness, http.MethodGet,
"/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "",
ownerCookie, "", "", "192.0.2.241:1236")
var secondPage struct {
Items []json.RawMessage `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
NextCursor *string `json:"next_cursor"`
} `json:"page"`
}
if pageTwo.Code != http.StatusOK || json.Unmarshal(pageTwo.Body.Bytes(), &secondPage) != nil ||
len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil ||
string(secondPage.Items[0]) == string(firstPage.Items[0]) {
t.Fatalf("second support-case page = %d %s, want one item and another page", pageTwo.Code, pageTwo.Body.String())
}
pageThree := supportCaseHTTP(t, harness, http.MethodGet,
"/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*secondPage.Page.NextCursor), "",
ownerCookie, "", "", "192.0.2.241:1237")
var lastPage struct {
Items []json.RawMessage `json:"items"`
Page struct {
HasMore bool `json:"has_more"`
} `json:"page"`
}
if pageThree.Code != http.StatusOK || json.Unmarshal(pageThree.Body.Bytes(), &lastPage) != nil ||
len(lastPage.Items) != 1 || lastPage.Page.HasMore {
t.Fatalf("last support-case page = %d %s, want one item without another page", pageThree.Code, pageThree.Body.String())
}
foreignCursor := supportCaseHTTP(t, harness, http.MethodGet,
"/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "",
otherCookie, "", "", "192.0.2.241:1238")
requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed")
resetSupportCaseRequestEvents(t, ctx, harness, owner.ID, other.ID)
for index := range 10 {
body := fmt.Sprintf(`{"type":"support","description":"Rate limit request %d."}`, index)
response := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
ownerCookie, ownerCSRF, fmt.Sprintf("support-limit-%d", index), fmt.Sprintf("192.0.2.%d:1234", 242+index))
if response.Code != http.StatusCreated {
t.Fatalf("within-limit create %d = %d %s, want 201", index, response.Code, response.Body.String())
}
}
overLimit := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases",
`{"type":"support","description":"This request exceeds the account budget."}`,
ownerCookie, ownerCSRF, "support-limit-over", "192.0.2.247:1234")
if overLimit.Code != http.StatusTooManyRequests || overLimit.Header().Get("Retry-After") == "" {
t.Fatalf("eleventh owner create = %d Retry-After=%q %s, want 429 with a retry interval", overLimit.Code, overLimit.Header().Get("Retry-After"), overLimit.Body.String())
}
assertRowCount(ctx, t, harness.pool, pgx.Identifier{"support_case_request_events"}, 10)
}
func TestManualAssessmentPinsPublishedRubricAcrossReplayAndReopening(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
isolatedEnv := *env
isolatedEnv.Config.DatabaseURL = databaseURL
harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv)
firstPolicy, opening, bank, metadata := seedSupportManualRubric(ctx, t, harness)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
owner := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "support-rubric-owner@example.test", passwordHash, true)
login := loginSessionHTTP(t, harness.sessionHTTPHarness, owner.Email.Address(), sessionHTTPTestPass,
sessionHTTPTestOrigin, "", "192.0.2.251:1234")
cookie, csrf := supportCaseLoginCredentials(t, login)
body := `{"type":"manual_assessment","description":"Please assess my Go skills.","assessment_target":{"specialization":"backend","grade":"junior"}}`
created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1234")
var original supportCaseHTTPResponse
if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &original) != nil ||
original.RubricVersion == nil || *original.RubricVersion != firstPolicy.Version() || original.Status != "waiting_expert" {
t.Fatalf("manual request with a current reviewed rubric = %d %s, want 201 pinned to policy version %d",
created.Code, created.Body.String(), firstPolicy.Version())
}
if strings.Contains(created.Body.String(), "rubric_opening_id") || strings.Contains(created.Body.String(), "rubric_policy_version_id") {
t.Fatalf("public response exposed private rubric pin columns: %s", created.Body.String())
}
assertStoredSupportRubricPin(ctx, t, harness, original.ID, firstPolicy.Version(), opening.ID, firstPolicy.ID().UUID())
var consentCount, attemptCount int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", owner.ID).Scan(&consentCount); err != nil {
t.Fatalf("read manual-assessment consent side effects: %v", err)
}
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id = $1", owner.ID).Scan(&attemptCount); err != nil {
t.Fatalf("read manual-assessment attempt side effects: %v", err)
}
if consentCount != 0 || attemptCount != 0 {
t.Fatalf("manual request created %d consent records and %d attempts; want neither", consentCount, attemptCount)
}
read := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+original.ID,
"", cookie, "", "", "192.0.2.252:1235")
var readBody supportCaseHTTPResponse
if read.Code != http.StatusOK || json.Unmarshal(read.Body.Bytes(), &readBody) != nil ||
readBody.ID != original.ID || readBody.RubricVersion == nil || *readBody.RubricVersion != firstPolicy.Version() {
t.Fatalf("manual case GET = %d %s, want the original rubric version", read.Code, read.Body.String())
}
replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1236")
if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() {
t.Fatalf("same-key manual replay = %d %s, want the immutable original response %s", replay.Code, replay.Body.String(), created.Body.String())
}
secondProductPolicy := domain.DemoProductPolicyV2()
secondProductPolicy.Assessment.MaxAttemptsPerWindow++
secondPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now).Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo,
Author: domain.DemoPolicySeedAuthor, Policy: secondProductPolicy,
})
if err != nil || secondPolicy.Version() <= firstPolicy.Version() {
t.Fatalf("publish later product policy = v%d, %v; want a later immutable version", secondPolicy.Version(), err)
}
harness.supportClock.now = secondPolicy.EffectiveAt()
secondOpening, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
Category: opening.Category, GradingPolicyID: secondPolicy.ID(), OpenedBy: fixtureOpener, CatalogMetadata: &metadata,
})
if err != nil || secondOpening.ID == opening.ID {
t.Fatalf("reopen category under later policy = %+v, %v; want a distinct current opening", secondOpening, err)
}
current, err := bank.CategoryAvailability(ctx, opening.Category)
if err != nil || current.ID != secondOpening.ID {
t.Fatalf("current category opening = %+v, %v; want the later opening", current, err)
}
readAfterReopening := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+original.ID,
"", cookie, "", "", "192.0.2.252:1237")
replayAfterReopening := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body,
cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1238")
var readAfterBody supportCaseHTTPResponse
if readAfterReopening.Code != http.StatusOK || json.Unmarshal(readAfterReopening.Body.Bytes(), &readAfterBody) != nil ||
readAfterBody.RubricVersion == nil || *readAfterBody.RubricVersion != firstPolicy.Version() ||
replayAfterReopening.Code != http.StatusCreated || replayAfterReopening.Body.String() != created.Body.String() {
t.Fatalf("old manual case changed after category reopening: GET=%d %s replay=%d %s",
readAfterReopening.Code, readAfterReopening.Body.String(), replayAfterReopening.Code, replayAfterReopening.Body.String())
}
assertStoredSupportRubricPin(ctx, t, harness, original.ID, firstPolicy.Version(), opening.ID, firstPolicy.ID().UUID())
}
func seedSupportManualRubric(
ctx context.Context,
t *testing.T,
harness *supportCaseHTTPHarness,
) (domain.PolicyVersion, domain.AssessmentCategoryOpening, *assessment.Bank, domain.AssessmentCategoryCatalogMetadata) {
t.Helper()
policyStore := postgresadapter.NewPolicyStore(harness.pool)
policyVersion, err := policyStore.Policies().GetEffective(ctx, domain.ProductPolicyKey, harness.supportClock.Now())
if err != nil {
t.Fatalf("read current support policy for reviewed bank fixture: %v", err)
}
transactor := postgresadapter.NewTransactor(harness.pool)
bank := assessment.NewBank(transactor)
fixture := assessmentFixture{demoBundle: loadDemoBundleFile(t)}
required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy())
if err != nil {
t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err)
}
bundle := fixture.reviewedBundle(int(required))
bundle.Name = "support-case-manual-rubric"
bundle.Category = "support-case-manual-rubric"
if _, err := bank.ImportBundle(ctx, bundle); err != nil {
t.Fatalf("ImportBundle(support rubric fixture) error = %v", err)
}
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)
}
}
metadata, err := domain.NewAssessmentCategoryCatalogMetadata(
domain.SpecializationBackend, domain.GradeJunior, []domain.TaskLanguageCode{domain.TaskLanguageGo},
)
if err != nil {
t.Fatalf("NewAssessmentCategoryCatalogMetadata() error = %v", err)
}
category := domain.AssessmentCategory(bundle.Category)
opening, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{
Category: category, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener, CatalogMetadata: &metadata,
})
if err != nil {
t.Fatalf("OpenCategory(support rubric fixture) error = %v", err)
}
return policyVersion, opening, bank, metadata
}
func assertStoredSupportRubricPin(
ctx context.Context,
t *testing.T,
harness *supportCaseHTTPHarness,
caseID string,
version int32,
openingID uuid.UUID,
policyID uuid.UUID,
) {
t.Helper()
var storedVersion int32
var storedOpeningID, storedPolicyID uuid.UUID
err := harness.pool.QueryRow(ctx, `SELECT rubric_version, rubric_opening_id, rubric_policy_version_id
FROM support_cases WHERE id = $1::uuid`, caseID).Scan(&storedVersion, &storedOpeningID, &storedPolicyID)
if err != nil || storedVersion != version || storedOpeningID != openingID || storedPolicyID != policyID {
t.Fatalf("stored private rubric pin = v%d opening %s policy %s, %v; want v%d opening %s policy %s",
storedVersion, storedOpeningID, storedPolicyID, err, version, openingID, policyID)
}
}
func TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout)
defer cancel()
databaseURL := env.createIsolatedDatabase(ctx, t)
applyMigrations(ctx, t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
store := postgresadapter.NewIdentityStore(pool)
transactor := postgresadapter.NewTransactor(pool)
hasher, err := argon2id.NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
passwordHash, err := identity.NewCredentials(hasher).HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
address, err := domain.NewEmailAddress("support-budget@example.test")
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
registeredAt := time.Now().UTC().Truncate(time.Microsecond)
user, err := domain.NewUser(domain.Registration{
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioCandidate, RegisteredAt: registeredAt,
})
if err != nil {
t.Fatalf("NewUser() error = %v", err)
}
if err := store.Users().Create(ctx, user); err != nil {
t.Fatalf("Create(user) error = %v", err)
}
if _, err := store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond)); err != nil {
t.Fatalf("MarkEmailVerified() error = %v", err)
}
productPolicy := domain.DemoProductPolicyV2()
baseSupport := domain.DemoSupportPolicy()
limitedSupport, err := domain.NewSupportPolicy(domain.SupportPolicyInput{
SupportResponseDays: baseSupport.SupportResponseDays(), ComplaintResponseDays: baseSupport.ComplaintResponseDays(),
ManualAssessmentResponseDays: baseSupport.ManualAssessmentResponseDays(), AppealResponseDays: baseSupport.AppealResponseDays(),
MaxRequestsPerWindow: 1, RequestWindow: time.Hour, MaxAppealsPerTarget: baseSupport.MaxAppealsPerTarget(),
PauseWhenWaitingForUser: baseSupport.PausesWhenWaitingForUser(), BusinessCalendarVersion: baseSupport.BusinessCalendarVersion(),
})
if err != nil {
t.Fatalf("NewSupportPolicy() error = %v", err)
}
productPolicy.Support = &limitedSupport
policyClock := time.Now
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), policyClock).Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: productPolicy,
}); err != nil {
t.Fatalf("publish budget test policy: %v", err)
}
firstTimestamp := time.Now().UTC().Add(2 * time.Hour).Truncate(time.Microsecond)
var clockCalls atomic.Int32
clock := func() time.Time {
if clockCalls.Add(1) == 1 {
return firstTimestamp
}
return firstTimestamp.Add(-time.Hour)
}
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
service, err := supportcase.NewService(supportcase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock})
if err != nil {
t.Fatalf("NewSupportCaseService() error = %v", err)
}
start := make(chan struct{})
results := make(chan error, 2)
for index := range 2 {
go func(index int) {
<-start
_, err := service.Create(ctx, supportcase.CreateCommand{
ActorID: user.ID, IdempotencyKey: fmt.Sprintf("support-budget-%d", index),
Type: domain.SupportCaseTypeSupport, Description: fmt.Sprintf("Budget request %d.", index),
})
results <- err
}(index)
}
close(start)
firstError, secondError := <-results, <-results
if clockCalls.Load() != 2 {
t.Fatalf("service clock calls = %d, want one post-lock sample per request", clockCalls.Load())
}
successes := 0
limited := 0
for _, err := range []error{firstError, secondError} {
switch {
case err == nil:
successes++
case errors.Is(err, supportcase.ErrRateLimited):
limited++
default:
t.Fatalf("concurrent request error = %v, want one create and one rate limit", err)
}
}
if successes != 1 || limited != 1 {
t.Fatalf("concurrent requests had %d creates and %d rate limits, want one each", successes, limited)
}
assertRowCount(ctx, t, pool, pgx.Identifier{"support_cases"}, 1)
assertRowCount(ctx, t, pool, pgx.Identifier{"support_case_request_events"}, 1)
}
func requireSupportCaseRequestCount(
t *testing.T,
ctx context.Context,
harness *supportCaseHTTPHarness,
ownerID uuid.UUID,
want int64,
) {
t.Helper()
var count int64
if err := harness.pool.QueryRow(ctx,
"SELECT count(*) FROM support_case_request_events WHERE owner_id = $1", ownerID,
).Scan(&count); err != nil {
t.Fatalf("count support request events for owner: %v", err)
}
if count != want {
t.Fatalf("support request events for owner = %d, want %d", count, want)
}
}
func assertSupportCaseCount(t *testing.T, ctx context.Context, harness *supportCaseHTTPHarness, ownerID uuid.UUID, want int64) {
t.Helper()
var count int64
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM support_cases WHERE owner_id = $1", ownerID).Scan(&count); err != nil {
t.Fatalf("count support cases for owner: %v", err)
}
if count != want {
t.Fatalf("support cases for owner = %d, want %d", count, want)
}
}
func resetSupportCaseRequestEvents(
t *testing.T,
ctx context.Context,
harness *supportCaseHTTPHarness,
ownerIDs ...uuid.UUID,
) {
t.Helper()
for _, ownerID := range ownerIDs {
if _, err := harness.pool.Exec(ctx, "DELETE FROM support_case_request_events WHERE owner_id = $1", ownerID); err != nil {
t.Fatalf("reset support request events for owner: %v", err)
}
}
}
func createSupportCaseHTTPEmployer(
ctx context.Context,
t *testing.T,
harness *supportCaseHTTPHarness,
email string,
passwordHash domain.PasswordHash,
) domain.User {
t.Helper()
address, err := domain.NewEmailAddress(email)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
registeredAt := harness.clock.Now().Truncate(time.Microsecond)
user, err := domain.NewUser(domain.Registration{
Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: registeredAt,
})
if err != nil {
t.Fatalf("NewUser(employer) error = %v", err)
}
if err := harness.store.Users().Create(ctx, user); err != nil {
t.Fatalf("Create(employer) error = %v", err)
}
user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond))
if err != nil {
t.Fatalf("MarkEmailVerified(employer) error = %v", err)
}
return user
}
type supportCaseHTTPResponse struct {
ID string `json:"id"`
Number string `json:"number"`
Type string `json:"type"`
Status string `json:"status"`
Description string `json:"description"`
RubricVersion *int32 `json:"rubric_version"`
History []struct {
Kind string `json:"kind"`
} `json:"history"`
ResponseTarget struct {
Kind string `json:"kind"`
BusinessDays int32 `json:"business_days"`
} `json:"response_target"`
}
func newSupportCaseHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *supportCaseHTTPHarness {
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)}
supportClock := &testClock{now: clock.Now()}
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)
}
publishedPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), clock.Now).Publish(ctx, policy.PublishInput{
Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV2(),
})
if err != nil {
t.Fatalf("publish explicit support demo policy: %v", err)
}
// Publication time comes from PostgreSQL and is later than the fixed
// session clock. Start support requests at the returned effective time.
supportClock.now = publishedPolicy.EffectiveAt()
service, err := supportcase.NewService(supportcase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: supportClock.Now})
if err != nil {
t.Fatalf("NewSupportCaseService() error = %v", err)
}
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),
)
supportHandler := v1.NewSupportHandler(service)
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithSupport(supportHandler),
)
router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder,
prometheus.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return &supportCaseHTTPHarness{
sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs},
supportClock: supportClock,
}
}
func supportCaseLoginCredentials(t *testing.T, response *httptest.ResponseRecorder) (string, string) {
t.Helper()
if response.Code != http.StatusCreated {
t.Fatalf("login support case account = %d %s, want 201", response.Code, response.Body.String())
}
cookie := requireSessionCookie(t, response)
var body struct {
CSRFToken string `json:"csrf_token"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" {
t.Fatalf("decode support case login response: %v", err)
}
return cookie.Value, body.CSRFToken
}
func supportCaseHTTP(
t *testing.T,
harness *supportCaseHTTPHarness,
method, path, body, cookie, csrf, idempotencyKey, remoteAddr string,
) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
if method == http.MethodPost {
request.Header.Set("Origin", sessionHTTPTestOrigin)
request.Header.Set("Idempotency-Key", idempotencyKey)
}
if cookie != "" {
request.Header.Set("Cookie", "__Host-lincodex_session="+cookie)
}
if csrf != "" {
request.Header.Set("X-CSRF-Token", csrf)
}
request.RemoteAddr = remoteAddr
response := httptest.NewRecorder()
harness.router.ServeHTTP(response, request)
return response
}