Files

771 lines
37 KiB
Go

//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/consent"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/policy"
questionnaireusecase "lincodex/backend/internal/usecase/questionnaire"
"lincodex/backend/internal/usecase/supportcase"
)
const supportCaseHTTPTimeout = 5 * time.Minute
type supportCaseHTTPHarness struct {
*sessionHTTPHarness
supportClock *testClock
keyring *identity.Keyring
}
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"`
Decision *json.RawMessage `json:"decision"`
AssessmentTarget *struct {
Specialization string `json:"specialization"`
Grade string `json:"grade"`
} `json:"assessment_target"`
History []struct {
Kind string `json:"kind"`
Actor string `json:"actor"`
Status string `json:"status"`
} `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)
// Consent, questionnaire, and assessment routes share the support clock and
// policy so one test can drive a C3 revocation, a failed attempt, and a
// manual assessment request through the real router.
consentHandler := v1.NewConsentHandler(
consent.NewQueryService(postgresadapter.NewConsentStore(pool), time.Now), consent.NewService(transactor, time.Now),
)
questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, supportClock.Now))
attemptService, err := assessment.NewAttemptService(transactor, transactor, keyring, supportClock.Now)
if err != nil {
t.Fatalf("NewAttemptService() error = %v", err)
}
handler := v1.NewHandler(healthHandler, responder,
v1.WithIdentity(identityHandler), v1.WithSupport(supportHandler),
v1.WithConsent(consentHandler), v1.WithQuestionnaire(questionnaireHandler),
v1.WithAssessment(v1.NewAssessmentHandler(attemptService)),
)
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,
keyring: keyring,
}
}
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
}