package httpadapter import ( "bytes" "context" "encoding/json" "errors" "fmt" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" "lincodex/backend/internal/adapter/primary/http/api" "lincodex/backend/internal/adapter/primary/http/problem" v1 "lincodex/backend/internal/adapter/primary/http/v1" metrics "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/usecase/health" ) // internalFailureText stands for internal error text that must stay in logs. const internalFailureText = "dial tcp 10.0.0.5:5432: connection refused" type readinessFunc func(context.Context) error func (check readinessFunc) Check(ctx context.Context) error { return check(ctx) } // healthzOverride replaces GetHealthz of the production composite handler, // keeping its NewError, so a test can drive operation error handling without // adding operations to the public contract. type healthzOverride struct { *v1.Handler getHealthz func(context.Context) (*api.HealthResponse, error) } func (handler healthzOverride) GetHealthz(ctx context.Context) (*api.HealthResponse, error) { return handler.getHealthz(ctx) } func TestOperationalHealthRoutes(t *testing.T) { for _, test := range []struct { name string check readinessFunc path string statusCode int bodyStatus string }{ {name: "live", check: func(context.Context) error { return nil }, path: "/healthz", statusCode: http.StatusOK, bodyStatus: "ok"}, {name: "ready", check: func(context.Context) error { return nil }, path: "/readyz", statusCode: http.StatusOK, bodyStatus: "ready"}, {name: "not ready", check: func(context.Context) error { return context.DeadlineExceeded }, path: "/readyz", statusCode: http.StatusServiceUnavailable, bodyStatus: "not_ready"}, } { t.Run(test.name, func(t *testing.T) { router := newTestRouter(t, test.check) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, test.path, nil)) if response.Code != test.statusCode { t.Fatalf("status code = %d, want %d", response.Code, test.statusCode) } var body struct { Status string `json:"status"` } if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { t.Fatalf("decode response: %v", err) } if body.Status != test.bodyStatus { t.Fatalf("status = %q, want %q", body.Status, test.bodyStatus) } }) } } func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return context.DeadlineExceeded }) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) if response.Code != http.StatusOK { t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String()) } var body api.HealthResponse if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil { t.Fatalf("decode response %s: %v", response.Body.String(), err) } if body.Status != api.HealthResponseStatusOk { t.Fatalf("status = %q, want %q", body.Status, api.HealthResponseStatusOk) } } // An operation without a business implementation must answer 501 through the // router instead of a successful stub or a generic 500. GetHealthz served by // api.UnimplementedHandler stands in for any such operation, so the check needs // no extra contract operation. func TestPublicUnimplementedOperationReturnsNotImplementedProblem(t *testing.T) { healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) router := newTestRouterWithAPI(t, healthHandler, api.UnimplementedHandler{}, slog.New(slog.DiscardHandler)) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) body := requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) if body.Errors != nil { t.Fatalf("errors = %v, want none", body.Errors) } } // Identity request fixtures shared by the router tests. const ( testSessionCookie = "__Host-lincodex_session=opaque-session-value" testCSRFToken = "Xk4pR9tV2mQ7wL1sN8bC5dF0gH3jZ6yA9eU2iO7rT4c" testIdempotencyKey = "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11" registrationPath = "/api/v1/identity/registrations" currentSessionPath = "/api/v1/identity/sessions/current" ) // registrationBody returns a valid RegisterAccount body with replaced parts. func registrationBody(password, consent string) string { return `{"email":"candidate@example.com","password":"` + password + `","scenario":"candidate","consent_c1":` + consent + `}` } const ( validPassword = "correct horse battery staple" validConsent = `{"text_version":"c1-2026-10-01","accepted":true}` ) type identityRequest struct { method string path string body string headers map[string]string } func serveIdentityRequest(t *testing.T, router http.Handler, request identityRequest) *httptest.ResponseRecorder { t.Helper() httpRequest := httptest.NewRequest(request.method, request.path, strings.NewReader(request.body)) if request.body != "" { httpRequest.Header.Set("Content-Type", "application/json") } for name, value := range request.headers { httpRequest.Header.Set(name, value) } response := httptest.NewRecorder() router.ServeHTTP(response, httpRequest) return response } // Identity operations are in the contract before their business logic. Public // ones must answer 501 only after request validation, and session-protected // ones must stay closed: DenyAllSecurity grants no session, with or without a // cookie and a CSRF token. func TestIdentityOperationsBeforeImplementation(t *testing.T) { for _, test := range []struct { name string request identityRequest statusCode int code api.ProblemCode }{ { name: "public registration", request: identityRequest{ method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent), headers: map[string]string{"Idempotency-Key": testIdempotencyKey}, }, statusCode: http.StatusNotImplemented, code: api.ProblemCodeNotImplemented, }, { name: "public email verification resend", request: identityRequest{ method: http.MethodPost, path: "/api/v1/identity/email-verification-requests", body: `{"email":"candidate@example.com"}`, }, statusCode: http.StatusNotImplemented, code: api.ProblemCodeNotImplemented, }, { name: "public email confirmation", request: identityRequest{ method: http.MethodPost, path: "/api/v1/identity/email-verifications", body: `{"token":"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE"}`, }, statusCode: http.StatusNotImplemented, code: api.ProblemCodeNotImplemented, }, { name: "public login", request: identityRequest{ method: http.MethodPost, path: "/api/v1/identity/sessions", body: `{"email":"candidate@example.com","password":"correct horse battery staple"}`, }, statusCode: http.StatusNotImplemented, code: api.ProblemCodeNotImplemented, }, { name: "public consent text", request: identityRequest{method: http.MethodGet, path: "/api/v1/identity/consent-texts/c1"}, statusCode: http.StatusNotImplemented, code: api.ProblemCodeNotImplemented, }, { name: "current account without a session cookie", request: identityRequest{method: http.MethodGet, path: "/api/v1/identity/me"}, statusCode: http.StatusUnauthorized, code: api.ProblemCodeUnauthenticated, }, { name: "current account with a session cookie", request: identityRequest{ method: http.MethodGet, path: "/api/v1/identity/me", headers: map[string]string{"Cookie": testSessionCookie}, }, statusCode: http.StatusUnauthorized, code: api.ProblemCodeUnauthenticated, }, { name: "current session without a session cookie", request: identityRequest{method: http.MethodGet, path: currentSessionPath}, statusCode: http.StatusUnauthorized, code: api.ProblemCodeUnauthenticated, }, { name: "logout with a session cookie and a CSRF token", request: identityRequest{ method: http.MethodDelete, path: currentSessionPath, headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, }, statusCode: http.StatusUnauthorized, code: api.ProblemCodeUnauthenticated, }, { name: "logout with only a CSRF token", request: identityRequest{ method: http.MethodDelete, path: currentSessionPath, headers: map[string]string{"X-CSRF-Token": testCSRFToken}, }, statusCode: http.StatusUnauthorized, code: api.ProblemCodeUnauthenticated, }, { name: "logout with only a session cookie", request: identityRequest{ method: http.MethodDelete, path: currentSessionPath, headers: map[string]string{"Cookie": testSessionCookie}, }, statusCode: http.StatusUnauthorized, code: api.ProblemCodeUnauthenticated, }, } { t.Run(test.name, func(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) response := serveIdentityRequest(t, router, test.request) requireProblem(t, response, test.statusCode, test.code) if cookie := response.Header().Get("Set-Cookie"); test.statusCode == http.StatusNotImplemented && cookie != "" { t.Fatalf("Set-Cookie = %q, want none from an unimplemented operation", cookie) } }) } // The security handler does not affect operations without security. router := newTestRouter(t, func(context.Context) error { return nil }) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) if response.Code != http.StatusOK { t.Fatalf("healthz status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String()) } } // Registration rejects invalid requests with 400 before the 501 of the // missing business logic, with pointers to the failing fields. func TestRegistrationValidationPrecedesImplementation(t *testing.T) { const fourteenCharacters = "fourteen-chars" withKey := map[string]string{"Idempotency-Key": testIdempotencyKey} for _, test := range []struct { name string body string headers map[string]string location api.ProblemFieldLocation pointer string code string }{ { // Unknown fields are rejected, so no other consent, such as C4, // can be given at registration. name: "consent C4 at registration", body: `{"email":"candidate@example.com","password":"` + validPassword + `","scenario":"candidate","consent_c1":` + validConsent + `,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true}}`, headers: withKey, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "consent C1 not accepted", body: registrationBody(validPassword, `{"text_version":"c1-2026-10-01","accepted":false}`), headers: withKey, location: api.ProblemFieldLocationBody, pointer: "/consent_c1/accepted", code: "invalid", }, { name: "password shorter than 15 characters", body: registrationBody(fourteenCharacters, validConsent), headers: withKey, location: api.ProblemFieldLocationBody, pointer: "/password", code: "invalid", }, { name: "missing Idempotency-Key", body: registrationBody(validPassword, validConsent), location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required", }, } { t.Run(test.name, func(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) response := serveIdentityRequest(t, router, identityRequest{ method: http.MethodPost, path: registrationPath, body: test.body, headers: test.headers, }) body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed) want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code} for _, field := range body.Errors { if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { return } } t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want) }) } } // sessionPrincipalKey marks the context returned by HandleSessionCookie. type sessionPrincipalKey struct{} // recordingSecurity accepts every scheme value and records the order of the // calls and whether HandleSessionCsrf saw the context of HandleSessionCookie. type recordingSecurity struct { calls []string csrfSawPrincipal bool } func (security *recordingSecurity) HandleSessionCookie(ctx context.Context, _ api.OperationName, _ api.SessionCookie) (context.Context, error) { security.calls = append(security.calls, "SessionCookie") return context.WithValue(ctx, sessionPrincipalKey{}, "principal"), nil } func (security *recordingSecurity) HandleSessionCsrf(ctx context.Context, _ api.OperationName, _ api.SessionCsrf) (context.Context, error) { security.calls = append(security.calls, "SessionCsrf") security.csrfSawPrincipal = ctx.Value(sessionPrincipalKey{}) != nil return ctx, nil } // The session-bound CSRF check of TASK-056 relies on the generated server // calling HandleSessionCookie before HandleSessionCsrf and passing the // returned context on. ogen orders the calls by scheme name, so renaming a // scheme or upgrading ogen must keep this test green. func TestGeneratedServerSecurityOrder(t *testing.T) { for _, test := range []struct { name string headers map[string]string calls []string csrfSawPrincipal bool statusCode int }{ { name: "cookie and CSRF token", headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, calls: []string{"SessionCookie", "SessionCsrf"}, csrfSawPrincipal: true, statusCode: http.StatusNotImplemented, }, { // Without a cookie HandleSessionCsrf still runs, with the // original context, and the unsatisfied requirement answers 401. name: "CSRF token without a cookie", headers: map[string]string{"X-CSRF-Token": testCSRFToken}, calls: []string{"SessionCsrf"}, statusCode: http.StatusUnauthorized, }, { name: "cookie without a CSRF token", headers: map[string]string{"Cookie": testSessionCookie}, calls: []string{"SessionCookie"}, statusCode: http.StatusUnauthorized, }, } { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) security := &recordingSecurity{} router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } response := serveIdentityRequest(t, router, identityRequest{method: http.MethodDelete, path: currentSessionPath, headers: test.headers}) if response.Code != test.statusCode { t.Fatalf("status code = %d, want %d: %s", response.Code, test.statusCode, response.Body.String()) } if fmt.Sprint(security.calls) != fmt.Sprint(test.calls) { t.Fatalf("security calls = %v, want %v", security.calls, test.calls) } if security.csrfSawPrincipal != test.csrfSawPrincipal { t.Fatalf("HandleSessionCsrf saw the session context = %t, want %t", security.csrfSawPrincipal, test.csrfSawPrincipal) } }) } } const questionnairePath = "/api/v1/me/questionnaire" // Questionnaire specialization items shared by the questionnaire tests. const ( backendWithGo = `{"specialization":"backend","self_assessed_grade":"middle","task_languages":["go"],"stack":["PostgreSQL"],"experience":{"commercial_months":30,"academic_months":12}}` networkEngineer = `{"specialization":"network_engineer","self_assessed_grade":"junior","task_languages":[],"stack":[],"experience":null}` frontendInterest = `{"specialization":"frontend","self_assessed_grade":"junior","task_languages":[],"stack":["React"],"experience":null}` ) // questionnaireBody returns a SaveMyQuestionnaire body with the given // specialization items. func questionnaireBody(specializations ...string) string { return `{"expected_version":0,"specializations":[` + strings.Join(specializations, ",") + `],"work_context":{"work_formats":["remote"]}}` } // The schema alone must reject the questionnaire values that FR03 forbids: // more than two specializations, a grade outside the scale, a task language // that is not a bank language, and a confirmed grade set by the candidate. // Security accepts the session here, so the request reaches body validation; // a valid body then answers 501 until the questionnaire is implemented. func TestQuestionnaireSchemaValidationPrecedesImplementation(t *testing.T) { for _, test := range []struct { name string body string statusCode int pointer string code string }{ { // Go is a task language of the backend specialization, not a // category of its own. name: "Backend with Go and Network Engineer", body: questionnaireBody(backendWithGo, networkEngineer), statusCode: http.StatusNotImplemented, }, { name: "three specializations", body: questionnaireBody(backendWithGo, networkEngineer, frontendInterest), statusCode: http.StatusBadRequest, pointer: "/specializations", code: "invalid", }, { name: "no specialization", body: questionnaireBody(), statusCode: http.StatusBadRequest, pointer: "/specializations", code: "invalid", }, { name: "grade outside the MVP scale", body: questionnaireBody(strings.Replace(backendWithGo, `"middle"`, `"lead"`, 1)), statusCode: http.StatusBadRequest, pointer: "/specializations/0/self_assessed_grade", code: "invalid", }, { // A language is never a specialization code. name: "language as a specialization", body: questionnaireBody(strings.Replace(backendWithGo, `"backend"`, `"go"`, 1)), statusCode: http.StatusBadRequest, pointer: "/specializations/0/specialization", code: "invalid", }, { name: "task language outside the bank languages", body: questionnaireBody(strings.Replace(backendWithGo, `["go"]`, `["rust"]`, 1)), statusCode: http.StatusBadRequest, pointer: "/specializations/0/task_languages/0", code: "invalid", }, { // The decoder does not record the path of an unknown field in a // nested object, so the pointer is the whole body. name: "confirmed grade set by the candidate", body: questionnaireBody(strings.Replace(backendWithGo, `"stack"`, `"confirmed_grade":"senior","stack"`, 1)), statusCode: http.StatusBadRequest, pointer: "", code: "invalid", }, { name: "missing expected version", body: strings.Replace(questionnaireBody(backendWithGo), `"expected_version":0,`, "", 1), statusCode: http.StatusBadRequest, pointer: "/expected_version", code: "required", }, } { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } response := serveIdentityRequest(t, router, identityRequest{ method: http.MethodPut, path: questionnairePath, body: test.body, headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, }) if test.statusCode == http.StatusNotImplemented { requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) return } body := requireProblem(t, response, test.statusCode, api.ProblemCodeValidationFailed) want := api.ProblemFieldError{In: api.ProblemFieldLocationBody, Pointer: test.pointer, Code: test.code} for _, field := range body.Errors { if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { return } } t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want) }) } } // The catalog is public; the questionnaire stays closed without a session. func TestCatalogAndQuestionnaireAccessBeforeImplementation(t *testing.T) { for _, test := range []struct { name string request identityRequest statusCode int code api.ProblemCode }{ { name: "public catalog", request: identityRequest{method: http.MethodGet, path: "/api/v1/specializations"}, statusCode: http.StatusNotImplemented, code: api.ProblemCodeNotImplemented, }, { name: "questionnaire read without a session", request: identityRequest{method: http.MethodGet, path: questionnairePath}, statusCode: http.StatusUnauthorized, code: api.ProblemCodeUnauthenticated, }, { name: "questionnaire save with a denied session", request: identityRequest{ method: http.MethodPut, path: questionnairePath, body: questionnaireBody(backendWithGo), headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, }, statusCode: http.StatusUnauthorized, code: api.ProblemCodeUnauthenticated, }, } { t.Run(test.name, func(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) requireProblem(t, serveIdentityRequest(t, router, test.request), test.statusCode, test.code) }) } } // Assessment request fixtures shared by the assessment tests. const ( assessmentAttemptsPath = "/api/v1/me/assessment-attempts" assessmentAttemptPath = assessmentAttemptsPath + "/01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b" assessmentAnswersPath = assessmentAttemptPath + "/answers" assessmentFinalizePath = assessmentAttemptPath + "/finalize" assessmentResultPath = assessmentAttemptPath + "/result" assessmentItemID = "01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01" validAttemptCreate = `{"specialization":"backend","target_grade":"junior","task_language":"go"}` ) // assessmentAnswerBody returns a SubmitMyAssessmentAnswer body for version 1 // of the attempt with the given answer. func assessmentAnswerBody(answer string) string { return `{"expected_version":1,"item_id":"` + assessmentItemID + `","answer":` + answer + `}` } // The schema alone must accept every answer format of FR05 and reject what a // candidate may never send: a score, a seed, a mode, a format mixed with the // fields of another format, or a missing version or Idempotency-Key. Security // accepts the session here, so the request reaches validation; a valid request // then answers 501 until the assessment is implemented. func TestAssessmentSchemaValidationPrecedesImplementation(t *testing.T) { session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken} command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey} for _, test := range []struct { name string request identityRequest location api.ProblemFieldLocation pointer string code string }{ { name: "availability", request: identityRequest{method: http.MethodGet, path: "/api/v1/me/assessment-availability", headers: session}, }, { name: "create", request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: command}, }, { name: "create without a task language choice", request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: `{"specialization":"network_engineer","target_grade":"middle","task_language":null}`, headers: command}, }, { // The server picks the mode from the published bank. name: "create with a mode chosen by the client", request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: strings.Replace(validAttemptCreate, `}`, `,"mode":"demo_basic"}`, 1), headers: command}, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "create for a grade outside the MVP scale", request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: strings.Replace(validAttemptCreate, `"junior"`, `"lead"`, 1), headers: command}, location: api.ProblemFieldLocationBody, pointer: "/target_grade", code: "invalid", }, { name: "create without an Idempotency-Key", request: identityRequest{method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: session}, location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required", }, { name: "resume", request: identityRequest{method: http.MethodGet, path: assessmentAttemptPath, headers: session}, }, { name: "resume with an identifier that is not a UUID", request: identityRequest{method: http.MethodGet, path: assessmentAttemptsPath + "/1", headers: session}, location: api.ProblemFieldLocationPath, pointer: "/attempt_id", code: "invalid", }, { name: "choice answer", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","option_ids":["x9"]}`), headers: command}, }, { name: "number answer", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":254}`), headers: command}, }, { name: "string answer", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"string","text":"Retry-After"}`), headers: command}, }, { name: "order answer", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"order","element_ids":["b1","a7","d3"]}`), headers: command}, }, { name: "find-error answer", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"find_error","line_numbers":[5]}`), headers: command}, }, { name: "configuration answer", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"configuration","config":"interface Gi0/1"}`), headers: command}, }, { name: "practice answer", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"practice","language":"python","source_code":"print(1)"}`), headers: command}, }, { // The server scores the answer with the key of the item instance. name: "answer with a score set by the candidate", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: strings.Replace(assessmentAnswerBody(`{"format":"choice","option_ids":["x9"]}`), `{"expected_version"`, `{"score":1,"expected_version"`, 1), headers: command}, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "practice answer with a seed", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"practice","language":"python","source_code":"print(1)","seed":42}`), headers: command}, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "format with the fields of another format", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","number":254}`), headers: command}, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "unknown answer format", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"essay","text":"..."}`), headers: command}, location: api.ProblemFieldLocationBody, pointer: "/answer/format", code: "invalid", }, { name: "choice answer without an option", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"choice","option_ids":[]}`), headers: command}, location: api.ProblemFieldLocationBody, pointer: "/answer/option_ids", code: "invalid", }, { name: "answer without an expected version", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: `{"item_id":"` + assessmentItemID + `","answer":{"format":"number","number":1}}`, headers: command}, location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required", }, { name: "answer without an Idempotency-Key", request: identityRequest{method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":1}`), headers: session}, location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required", }, { name: "finalize", request: identityRequest{method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":17}`, headers: command}, }, { name: "finalize with version zero", request: identityRequest{method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":0}`, headers: command}, location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid", }, { name: "result", request: identityRequest{method: http.MethodGet, path: assessmentResultPath, headers: session}, }, } { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } response := serveIdentityRequest(t, router, test.request) if test.code == "" { requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) return } body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed) want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code} for _, field := range body.Errors { if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { return } } t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want) }) } } // Every assessment operation requires a candidate session; DenyAllSecurity // grants none, with or without a cookie and a CSRF token. func TestAssessmentAccessBeforeImplementation(t *testing.T) { command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey} for _, test := range []identityRequest{ {method: http.MethodGet, path: "/api/v1/me/assessment-availability"}, {method: http.MethodPost, path: assessmentAttemptsPath, body: validAttemptCreate, headers: command}, {method: http.MethodGet, path: assessmentAttemptPath}, {method: http.MethodGet, path: assessmentAttemptPath, headers: map[string]string{"Cookie": testSessionCookie}}, {method: http.MethodPost, path: assessmentAnswersPath, body: assessmentAnswerBody(`{"format":"number","number":1}`), headers: command}, {method: http.MethodPost, path: assessmentFinalizePath, body: `{"expected_version":1}`, headers: command}, {method: http.MethodGet, path: assessmentResultPath}, } { t.Run(test.method+" "+test.path, func(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated) }) } } func TestPublicOperationInternalErrorIsLoggedButNotExposed(t *testing.T) { var logs bytes.Buffer logger := slog.New(slog.NewJSONHandler(&logs, nil)) router := newOverrideRouter(t, logger, func(context.Context) (*api.HealthResponse, error) { return nil, fmt.Errorf("HealthHandler.GetHealthz - check database: %w", errors.New(internalFailureText)) }) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) body := requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal) if body.Title != "Internal server error" { t.Fatalf("title = %q, want the fixed internal title", body.Title) } if strings.Contains(response.Body.String(), "connection refused") || strings.Contains(response.Body.String(), "HealthHandler") { t.Fatalf("response exposes internal error text: %s", response.Body.String()) } if !strings.Contains(logs.String(), internalFailureText) { t.Fatalf("internal error was not logged at the HTTP boundary: %s", logs.String()) } if requestID := response.Header().Get("X-Request-ID"); !strings.Contains(logs.String(), requestID) { t.Fatalf("log entry has no request ID %q: %s", requestID, logs.String()) } } // recordedRequest is one observation passed to the metrics middleware. type recordedRequest struct { route string status int } type requestRecorder struct { requests []recordedRequest } func (recorder *requestRecorder) ObserveRequest(_, route string, status int, _ time.Duration) { recorder.requests = append(recorder.requests, recordedRequest{route: route, status: status}) } func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) { const panicText = "nil map write for candidate jane@example.com" var logs bytes.Buffer logger := slog.New(slog.NewJSONHandler(&logs, nil)) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) handler := healthzOverride{ Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) }, } recorder := &requestRecorder{} router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) body := requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal) if body.Title != "Internal server error" { t.Fatalf("title = %q, want the fixed internal title", body.Title) } if strings.Contains(response.Body.String(), "jane") || strings.Contains(response.Body.String(), "nil map") { t.Fatalf("response exposes the panic: %s", response.Body.String()) } if count := strings.Count(logs.String(), "public API request panicked"); count != 1 { t.Fatalf("panic logged %d times, want once: %s", count, logs.String()) } if !strings.Contains(logs.String(), response.Header().Get("X-Request-ID")) { t.Fatalf("panic log has no request ID: %s", logs.String()) } if strings.Contains(logs.String(), "jane@example.com") { t.Fatalf("panic value with personal data reached the logs: %s", logs.String()) } want := []recordedRequest{{route: "/api/v1/*", status: http.StatusInternalServerError}} if fmt.Sprint(recorder.requests) != fmt.Sprint(want) { t.Fatalf("metrics observed %v, want %v", recorder.requests, want) } } // http.ErrAbortHandler must reach net/http, which then aborts the response // instead of sending a problem or a success. func TestPublicOperationAbortPropagatesToTheServer(t *testing.T) { recorder := &requestRecorder{} router := newOverrideRouterWithMetrics(t, recorder, func(context.Context) (*api.HealthResponse, error) { panic(http.ErrAbortHandler) }) func() { defer func() { if recovered := recover(); recovered != http.ErrAbortHandler { //nolint:errorlint // net/http compares the sentinel by identity t.Fatalf("recovered %v, want http.ErrAbortHandler", recovered) } }() router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) t.Fatal("ServeHTTP returned instead of re-raising http.ErrAbortHandler") }() server := httptest.NewServer(router) defer server.Close() request, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL+"/api/v1/healthz", nil) if err != nil { t.Fatalf("build request: %v", err) } response, err := server.Client().Do(request) if err == nil { _ = response.Body.Close() t.Fatalf("server answered %d, want an aborted connection", response.StatusCode) } } func TestUnknownAPIPathsOutsideTheVersionReturnNotFoundProblem(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) for _, path := range []string{"/api", "/api/", "/api/v2/healthz", "/api/v1"} { t.Run(path, func(t *testing.T) { response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil)) requireProblem(t, response, http.StatusNotFound, api.ProblemCodeNotFound) }) } } // Operations report expected failures as typed problems, which the generated // server encodes directly with their own status. func TestPublicOperationTypedProblemKeepsItsStatus(t *testing.T) { for _, test := range []struct { name string code api.ProblemCode statusCode int }{ {name: "forbidden", code: api.ProblemCodeForbidden, statusCode: http.StatusForbidden}, {name: "version conflict", code: api.ProblemCodeVersionConflict, statusCode: http.StatusPreconditionFailed}, } { t.Run(test.name, func(t *testing.T) { router := newOverrideRouter(t, slog.New(slog.DiscardHandler), func(ctx context.Context) (*api.HealthResponse, error) { return nil, problem.New(ctx, test.code) }) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil)) requireProblem(t, response, test.statusCode, test.code) }) } } func TestPublicUnknownRouteReturnsNotFoundProblem(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/missing", nil)) requireProblem(t, response, http.StatusNotFound, api.ProblemCodeNotFound) } func TestPublicUnsupportedMethodReturnsMethodNotAllowedProblem(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/v1/healthz", nil)) requireProblem(t, response, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed) if allowed := response.Header().Get("Allow"); allowed != http.MethodGet { t.Fatalf("Allow = %q, want %q", allowed, http.MethodGet) } } func TestPublicPreflightKeepsEmptyResponse(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) response := httptest.NewRecorder() router.ServeHTTP(response, httptest.NewRequest(http.MethodOptions, "/api/v1/healthz", nil)) if response.Code != http.StatusNoContent || response.Body.Len() != 0 { t.Fatalf("preflight = %d %q, want empty 204", response.Code, response.Body.String()) } if methods := response.Header().Get("Access-Control-Allow-Methods"); methods != http.MethodGet { t.Fatalf("Access-Control-Allow-Methods = %q, want %q", methods, http.MethodGet) } } // requireProblem checks the problem+json envelope and returns the body decoded // and validated by the generated contract types. func requireProblem(t *testing.T, response *httptest.ResponseRecorder, statusCode int, code api.ProblemCode) api.Problem { t.Helper() if response.Code != statusCode { t.Fatalf("status code = %d, want %d: %s", response.Code, statusCode, response.Body.String()) } if contentType := response.Header().Get("Content-Type"); contentType != problem.MediaType { t.Fatalf("Content-Type = %q, want %q", contentType, problem.MediaType) } var body api.Problem if err := body.UnmarshalJSON(response.Body.Bytes()); err != nil { t.Fatalf("decode problem %s: %v", response.Body.String(), err) } if err := body.Validate(); err != nil { t.Fatalf("problem %s violates the contract: %v", response.Body.String(), err) } if body.Code != code || int(body.Status) != statusCode { t.Fatalf("problem code/status = %q/%d, want %q/%d", body.Code, body.Status, code, statusCode) } if body.Type != "urn:lincodex:problem:"+string(code) { t.Fatalf("problem type = %q", body.Type) } traceID, ok := body.TraceID.Get() if !ok || traceID != response.Header().Get("X-Request-ID") { t.Fatalf("trace_id = %q, want the X-Request-ID header %q", traceID, response.Header().Get("X-Request-ID")) } return body } func newTestRouter(t *testing.T, checker readinessFunc) http.Handler { t.Helper() logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(checker) return newTestRouterWithAPI(t, healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), logger) } func newOverrideRouter(t *testing.T, logger *slog.Logger, getHealthz func(context.Context) (*api.HealthResponse, error)) http.Handler { t.Helper() healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz} return newTestRouterWithAPI(t, healthHandler, handler, logger) } func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler { return v1.NewHealthHandler(health.NewReadiness(checker), time.Second) } func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler { t.Helper() router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } return router } func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getHealthz func(context.Context) (*api.HealthResponse, error)) http.Handler { t.Helper() logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz} router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger) if err != nil { t.Fatalf("NewRouter() error = %v", err) } return router }