Files
lincodex/backend/internal/adapter/primary/http/router_test.go
T

1616 lines
73 KiB
Go

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)
})
}
}
// Need request fixtures shared by the need tests.
const (
organizationNeedsPath = "/api/v1/organizations/01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01/needs"
organizationNeedPath = organizationNeedsPath + "/01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12"
netSalaryRange = `{"salary_from":120000,"salary_to":160000,"currency":"RUB","period":"month","tax_basis":"net"}`
validNeedCreate = `{"title":"Backend","specialization":{"value":"backend","status":"confirmed"},` +
`"grade":{"value":"junior","status":"confirmed"},"required_skills":[{"name":"Go","status":"confirmed"}],` +
`"work_formats":{"value":["remote"],"status":"confirmed"},"salary":{"value":` + netSalaryRange + `,"status":"confirmed"}}`
)
// needUpdateBody returns an UpdateOrganizationNeed body over version 1 with
// the given extra fields, for example `"grade":null`.
func needUpdateBody(fields string) string {
return `{"expected_version":1,` + fields + `}`
}
// needSalary returns a confirmed salary decision for the given range bounds
// and tax basis in RUB per month.
func needSalary(from, to, basis string) string {
return `{"value":{"salary_from":` + from + `,"salary_to":` + to + `,"currency":"RUB","period":"month","tax_basis":"` + basis + `"},"status":"confirmed"}`
}
// The schema alone must accept a need without a vacancy and reject what an
// employer may never send: membership, a recommendation score, or a
// candidate's minimum, a bare value without an explicit confirmation status,
// a salary range without a valid RUB base, and a missing or invalid
// expected_version. Security accepts the session here, so the request
// reaches validation; a valid request then answers 501 until needs are
// implemented. Cross-field salary rules (A < B, a width of 10-40%) and
// `extracted` with another value pass the schema; the server rejects them.
func TestNeedSchemaValidationPrecedesImplementation(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}
create := func(body string) identityRequest {
return identityRequest{method: http.MethodPost, path: organizationNeedsPath, body: body, headers: command}
}
update := func(fields string) identityRequest {
return identityRequest{method: http.MethodPatch, path: organizationNeedPath, body: needUpdateBody(fields), headers: session}
}
withSalary := func(salary string) string {
return strings.Replace(validNeedCreate, `{"value":`+netSalaryRange+`,"status":"confirmed"}`, salary, 1)
}
for _, test := range []struct {
name string
request identityRequest
location api.ProblemFieldLocation
pointer string
code string
}{
{
name: "list",
request: identityRequest{method: http.MethodGet, path: organizationNeedsPath + "?limit=20", headers: session},
},
{
name: "list with a limit above the maximum",
request: identityRequest{method: http.MethodGet, path: organizationNeedsPath + "?limit=101", headers: session},
location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid",
},
{
name: "list for an organization identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: "/api/v1/organizations/acme/needs", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
},
{
name: "create a manual need without a vacancy",
request: create(validNeedCreate),
},
{
name: "create from a text only",
request: create(`{"title":"Backend","source_text":"Ищем бэкенд-разработчика. Обязательно: Go."}`),
},
{
name: "create with an explicit null vacancy and unknown fields",
request: create(`{"title":"Backend","vacancy_id":null,"grade":null,"salary":null,"work_formats":null,"tasks":[]}`),
},
{
// The cross-field salary rules are domain rules that the server
// checks after the schema.
name: "create with a reversed salary range",
request: create(withSalary(needSalary("160000", "120000", "net"))),
},
{
name: "create with equal salary bounds",
request: create(withSalary(needSalary("150000", "150000", "net"))),
},
{
name: "create with a salary range wider than 40%",
request: create(withSalary(needSalary("100000", "200000", "net"))),
},
{
name: "create without a title",
request: create(`{"specialization":{"value":"backend","status":"confirmed"}}`),
location: api.ProblemFieldLocationBody, pointer: "/title", code: "required",
},
{
name: "create without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: organizationNeedsPath, body: validNeedCreate, headers: session},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
},
{
name: "salary bound of zero",
request: create(withSalary(needSalary("0", "160000", "net"))),
location: api.ProblemFieldLocationBody, pointer: "/salary/value/salary_from", code: "invalid",
},
{
name: "salary bound that is not a multiple of 1000",
request: create(withSalary(needSalary("120000", "160500", "net"))),
location: api.ProblemFieldLocationBody, pointer: "/salary/value/salary_to", code: "invalid",
},
{
name: "salary in another currency",
request: create(withSalary(strings.Replace(needSalary("120000", "160000", "net"), "RUB", "USD", 1))),
location: api.ProblemFieldLocationBody, pointer: "/salary/value/currency", code: "invalid",
},
{
name: "salary with an unknown tax basis",
request: create(withSalary(needSalary("120000", "160000", "after_tax"))),
location: api.ProblemFieldLocationBody, pointer: "/salary/value/tax_basis", code: "invalid",
},
{
name: "salary per hour",
request: create(withSalary(strings.Replace(needSalary("1000", "2000", "net"), "month", "hour", 1))),
location: api.ProblemFieldLocationBody, pointer: "/salary/value/period", code: "invalid",
},
{
// The decoder does not record the path of a missing field in a
// nested object, so the pointer is the whole body.
name: "salary without a tax basis",
request: create(withSalary(`{"value":{"salary_from":120000,"salary_to":160000,"currency":"RUB","period":"month"},"status":"confirmed"}`)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
// A bare range would confirm it implicitly; the status is explicit.
name: "salary range without a decision",
request: create(withSalary(netSalaryRange)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "grade as a bare value",
request: create(strings.Replace(validNeedCreate, `{"value":"junior","status":"confirmed"}`, `"junior"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "grade with an unknown status",
request: create(strings.Replace(validNeedCreate, `{"value":"junior","status":"confirmed"}`, `{"value":"junior","status":"unknown"}`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/grade/status", code: "invalid",
},
{
name: "recommendation score set by the employer",
request: create(strings.Replace(validNeedCreate, `{"title"`, `{"rec_score":0.99,"title"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "organization membership in the body",
request: create(strings.Replace(validNeedCreate, `{"title"`, `{"members":[{"user_id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","role":"owner"}],"title"`, 1)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "candidate minimum inside the salary range",
request: create(withSalary(`{"value":{"salary_from":120000,"salary_to":160000,"currency":"RUB","period":"month","tax_basis":"net","candidate_minimum":130000},"status":"confirmed"}`)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "skill with an unknown status",
request: create(strings.Replace(validNeedCreate, `{"name":"Go","status":"confirmed"}`, `{"name":"Go","status":"unknown"}`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/required_skills/0/status", code: "invalid",
},
{
name: "empty list of work formats",
request: create(strings.Replace(validNeedCreate, `["remote"]`, `[]`, 1)),
location: api.ProblemFieldLocationBody, pointer: "/work_formats/value", code: "invalid",
},
{
name: "read",
request: identityRequest{method: http.MethodGet, path: organizationNeedPath, headers: session},
},
{
name: "read with a need identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: organizationNeedsPath + "/1", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/need_id", code: "invalid",
},
{
name: "confirm suggestions, keep two open, and answer missing fields",
request: update(`"specialization":{"value":"backend","status":"confirmed"},"grade":{"value":"middle","status":"confirmed"},` +
`"required_skills":[{"name":"Go","status":"confirmed"},{"name":"Temporal","status":"confirmed"}],` +
`"desired_skills":[{"name":"Kafka","status":"extracted"}],"domain":{"value":"платежи","status":"extracted"},` +
`"salary":` + needSalary("250000", "320000", "gross")),
},
{
name: "delete requirements",
request: update(`"grade":null,"salary":null,"vacancy_id":null,"tasks":[]`),
},
{
name: "update with a list sent as null",
request: update(`"tasks":null`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "update with a bare grade",
request: update(`"grade":"middle"`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "update without an expected version",
request: identityRequest{method: http.MethodPatch, path: organizationNeedPath, body: `{"grade":null}`, headers: session},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
{
name: "update with version zero",
request: identityRequest{method: http.MethodPatch, path: organizationNeedPath, body: `{"expected_version":0,"grade":null}`, headers: session},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
},
{
name: "update with a version as text",
request: identityRequest{method: http.MethodPatch, path: organizationNeedPath, body: `{"expected_version":"1","grade":null}`, headers: session},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "update that sets the version itself",
request: update(`"version":7`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "update that sets the requirements version",
request: update(`"requirements_version":7`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "update with recommendations",
request: update(`"recommendations":{"status":"computed"}`),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "update with a salary in gross and net at once",
request: update(`"salary":` + needSalary("120000", "160000", "net_or_gross")),
location: api.ProblemFieldLocationBody, pointer: "/salary/value/tax_basis", code: "invalid",
},
{
name: "update with a negative salary bound",
request: update(`"salary":` + needSalary("-1000", "160000", "gross")),
location: api.ProblemFieldLocationBody, pointer: "/salary/value/salary_from", code: "invalid",
},
} {
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)
})
}
}
// A non-nullable optional list decodes to a plain slice, so an
// UpdateOrganizationNeed handler tells an absent list (unchanged) from an
// empty one (delete every item) only by nil; null is not a list and fails.
func TestNeedUpdateDecodingKeepsAbsentAndEmptyListsApart(t *testing.T) {
var empty api.NeedUpdate
if err := empty.UnmarshalJSON([]byte(`{"expected_version":1,"tasks":[]}`)); err != nil {
t.Fatalf("decode an empty list: %v", err)
}
if empty.Tasks == nil || len(empty.Tasks) != 0 {
t.Fatalf("tasks = %#v, want a non-nil empty slice", empty.Tasks)
}
var absent api.NeedUpdate
if err := absent.UnmarshalJSON([]byte(`{"expected_version":1}`)); err != nil {
t.Fatalf("decode an absent list: %v", err)
}
if absent.Tasks != nil || absent.RequiredSkills != nil || absent.DesiredSkills != nil {
t.Fatalf("lists = %#v %#v %#v, want nil for absent fields", absent.Tasks, absent.RequiredSkills, absent.DesiredSkills)
}
if absent.Grade.IsSet() || absent.Salary.IsSet() {
t.Fatal("absent field decisions are set, want unset")
}
var cleared api.NeedUpdate
if err := cleared.UnmarshalJSON([]byte(`{"expected_version":1,"grade":null}`)); err != nil {
t.Fatalf("decode a null field decision: %v", err)
}
if !cleared.Grade.IsSet() || !cleared.Grade.IsNull() {
t.Fatal("grade sent as null is not a set null, want a removal")
}
var null api.NeedUpdate
if err := null.UnmarshalJSON([]byte(`{"expected_version":1,"tasks":null}`)); err == nil {
t.Fatal("decode a list sent as null succeeded, want an error")
}
}
// Every need operation requires an employer session; DenyAllSecurity grants
// none, with or without a cookie and a CSRF token.
func TestNeedAccessBeforeImplementation(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 []identityRequest{
{method: http.MethodGet, path: organizationNeedsPath},
{method: http.MethodGet, path: organizationNeedsPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPost, path: organizationNeedsPath, body: validNeedCreate, headers: command},
{method: http.MethodGet, path: organizationNeedPath},
{method: http.MethodPatch, path: organizationNeedPath, body: needUpdateBody(`"grade":{"value":"middle","status":"confirmed"}`), headers: session},
} {
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)
})
}
}
// Support case request fixtures shared by the support case tests.
const (
supportCasesPath = "/api/v1/me/support-cases"
supportCasePath = supportCasesPath + "/01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d"
supportAttemptRef = `{"type":"assessment_attempt","id":"01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b"}`
supportOrganizationRef = `{"type":"organization","id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"}`
supportInvitationRef = `{"type":"invitation","id":"01928f7a-7f8a-7b9c-8d0e-1f2a3b4c5d6e"}`
supportCaseRef = `{"type":"support_case","id":"01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d"}`
validManualAssessment = `{"type":"manual_assessment","description":"Прошу ручную оценку.","assessment_target":{"specialization":"backend","grade":"middle"}}`
)
// supportCaseBody returns a CreateMySupportCase body of the given type with a
// valid description and the given extra fields, for example `"object":{...}`.
func supportCaseBody(caseType, fields string) string {
body := `{"type":"` + caseType + `","description":"Тест на Senior недоступен."`
if fields != "" {
body += `,` + fields
}
return body + `}`
}
// The schema alone must accept the five case types with the object types each
// allows, and reject what the client may never send: an empty or blank
// description, an unknown type, an object type that the case type does not
// accept, a missing field of the type, and a status, decision, moderator, or
// contact set by the client. Security accepts the session here, so the
// request reaches validation; a valid request then answers 501 until support
// cases are implemented. Ownership of the object and the complaint reason
// that requires an invitation pass the schema; the server checks them.
func TestSupportCaseSchemaValidationPrecedesImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie}
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: "list",
request: identityRequest{method: http.MethodGet, path: supportCasesPath + "?limit=50&cursor=c2MtMDAwMTIz", headers: session},
},
{
name: "list with limit zero",
request: identityRequest{method: http.MethodGet, path: supportCasesPath + "?limit=0", headers: session},
location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid",
},
{
name: "read",
request: identityRequest{method: http.MethodGet, path: supportCasePath, headers: session},
},
{
name: "read with an identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: supportCasesPath + "/SC-2026-000123", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/case_id", code: "invalid",
},
{
name: "support without context",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", ""), headers: command},
},
{
name: "support about an unavailable test",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"assessment_target":{"specialization":"backend","grade":"senior"}`), headers: command},
},
{
name: "support about an organization",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"object":`+supportOrganizationRef), headers: command},
},
{
name: "complaint about an invitation",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("complaint", `"complaint_reason":"salary_terms_violation","object":`+supportInvitationRef), headers: command},
},
{
name: "grade appeal",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":`+supportAttemptRef), headers: command},
},
{
// A category that an expert assigned without an attempt is
// disputed through the resolved manual assessment case.
name: "grade appeal of a manual assessment case",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":`+supportCaseRef), headers: command},
},
{
name: "support follow-up of another case",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"object":`+supportCaseRef), headers: command},
},
{
name: "anti-cheat appeal",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("anticheat_appeal", `"object":`+supportAttemptRef), headers: command},
},
{
name: "manual assessment without an attempt",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: validManualAssessment, headers: command},
},
{
name: "manual assessment with a prior attempt",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: strings.Replace(validManualAssessment, `}}`, `},"object":`+supportAttemptRef+`}`, 1), headers: command},
},
{
name: "description with line breaks",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":"Строка 1\nСтрока 2"}`, headers: command},
},
{
// ogen converts `\S` to the ECMAScript white space set, so Go and
// generated Zod both reject Unicode spaces such as U+00A0.
name: "description of only Unicode spaces",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":"\u00a0\u3000\u2003"}`, headers: command},
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
},
{
// U+0085 (NEL) is unicode.IsSpace but not ECMAScript white space,
// so it passes the schema. The implementation must reject it with
// a unicode.IsSpace domain check: 400 and the pointer /description.
name: "description of only NEL passes the schema",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":"\u0085"}`, headers: command},
},
{
name: "empty description",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":""}`, headers: command},
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
},
{
name: "blank description",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":" \n\t "}`, headers: command},
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
},
{
name: "description longer than 4000 characters",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support","description":"` + strings.Repeat("a", 4001) + `"}`, headers: command},
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
},
{
name: "missing description",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"type":"support"}`, headers: command},
location: api.ProblemFieldLocationBody, pointer: "/description", code: "required",
},
{
// The decoder selects the variant by `type` before it records a
// field path, so an unknown type points at the whole body.
name: "unknown type",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("feedback", ""), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "missing type",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: `{"description":"Тест недоступен."}`, headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "status set by the client",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"status":"resolved"`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "decision set by the client",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":`+supportAttemptRef+`,"decision":{"outcome":"upheld","reason":"ok"}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "moderator set by the client",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"moderator_id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "response target set by the client",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"response_target":{"due_at":"2026-10-07T09:00:00Z"}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
// Replies go to the case and to the account address only.
name: "reply address set by the client",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"reply_to":"other@example.com"`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "grade appeal of an organization",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":`+supportOrganizationRef), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid",
},
{
name: "complaint about an assessment attempt",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("complaint", `"complaint_reason":"other","object":`+supportAttemptRef), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid",
},
{
name: "anti-cheat appeal of a support case",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("anticheat_appeal", `"object":`+supportCaseRef), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid",
},
{
name: "complaint about a support case",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("complaint", `"complaint_reason":"other","object":`+supportCaseRef), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid",
},
{
name: "manual assessment based on a support case",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: strings.Replace(validManualAssessment, `}}`, `},"object":`+supportCaseRef+`}`, 1), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid",
},
{
name: "support about an unknown object type",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"object":{"type":"user","id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/object/type", code: "invalid",
},
{
name: "object reference that is not a UUID",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", `"object":{"type":"assessment_attempt","id":"42"}`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "grade appeal without a reference",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("grade_appeal", ""), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/object", code: "required",
},
{
name: "complaint without a reason",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("complaint", `"object":`+supportInvitationRef), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/complaint_reason", code: "required",
},
{
name: "support with a complaint reason",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("support", `"complaint_reason":"other"`), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "manual assessment without a category",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: supportCaseBody("manual_assessment", ""), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/assessment_target", code: "required",
},
{
name: "manual assessment for a grade outside the MVP scale",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: strings.Replace(validManualAssessment, `"middle"`, `"lead"`, 1), headers: command},
location: api.ProblemFieldLocationBody, pointer: "/assessment_target/grade", code: "invalid",
},
{
name: "manual assessment with a rubric chosen by the client",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: strings.Replace(validManualAssessment, `{"type"`, `{"rubric_version":1,"type"`, 1), headers: command},
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
{
name: "create without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: supportCasesPath, body: validManualAssessment, headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", 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, 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 support case operation requires a session; DenyAllSecurity grants
// none, with or without a cookie and a CSRF token.
func TestSupportCaseAccessBeforeImplementation(t *testing.T) {
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
for _, test := range []identityRequest{
{method: http.MethodGet, path: supportCasesPath},
{method: http.MethodGet, path: supportCasesPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPost, path: supportCasesPath, body: validManualAssessment, headers: command},
{method: http.MethodPost, path: supportCasesPath, body: validManualAssessment, headers: map[string]string{"Idempotency-Key": testIdempotencyKey}},
{method: http.MethodGet, path: supportCasePath},
{method: http.MethodGet, path: supportCasePath, headers: map[string]string{"Cookie": testSessionCookie}},
} {
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
}