package httpadapter import ( "bytes" "context" "encoding/json" "errors" "fmt" "log/slog" "net/http" "net/http/httptest" "reflect" "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, nil) 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", }, { // An unknown field inside an array element points at the array: // the decoder does not report the element index. name: "confirmed grade set by the candidate", body: questionnaireBody(strings.Replace(backendWithGo, `"stack"`, `"confirmed_grade":"senior","stack"`, 1)), statusCode: http.StatusBadRequest, pointer: "/specializations", 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, nil) 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: "/answer", 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: "/answer", 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, nil) 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 responder rebuilds the path of a missing nested field from // the decoder's field wrappers. 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: "/salary/value/tax_basis", code: "required", }, { // 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: "/salary", code: "invalid", }, { name: "grade as a bare value", request: create(strings.Replace(validNeedCreate, `{"value":"junior","status":"confirmed"}`, `"junior"`, 1)), location: api.ProblemFieldLocationBody, pointer: "/grade", 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: "/salary/value", 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", }, { // The decoder reports no index for an array element, so the // pointer stops at the array. name: "skill without a status", request: create(strings.Replace(validNeedCreate, `{"name":"Go","status":"confirmed"}`, `{"name":"Go"}`, 1)), location: api.ProblemFieldLocationBody, pointer: "/required_skills", 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: "/tasks", code: "invalid", }, { name: "update with a bare grade", request: update(`"grade":"middle"`), location: api.ProblemFieldLocationBody, pointer: "/grade", 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: "/expected_version", 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, nil) 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: "/object/id", 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, nil) 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) }) } } // Invitation request fixtures shared by the invitation tests. const ( organizationInvitationsPath = "/api/v1/organizations/01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01/invitations" organizationInvitationPath = organizationInvitationsPath + "/01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f" myInvitationsPath = "/api/v1/me/invitations" myInvitationPath = myInvitationsPath + "/01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f" invitationSalary = `{"salary_from":200000,"salary_to":260000,"currency":"RUB","period":"month","tax_basis":"net"}` invitationCommunication = `{"channel":"email","details":null}` invitationPackage = `{"bonus":{"status":"provided","description":"Годовой бонус"},` + `"equipment":{"status":"provided","description":"Ноутбук"},"training":{"status":"not_provided"},` + `"health_insurance":{"status":"not_provided"}}` validInvitationTerms = `{"role_title":"Middle Go-разработчик","specialization":"backend","grade":"middle",` + `"offer_type":"full_time","tasks":["Развивать сервис выплат"],"team":"Команда платежей из шести человек",` + `"tech_stack":["Go","PostgreSQL"],"work_formats":["remote"],"location":null,` + `"communication_method":` + invitationCommunication + `,"salary":` + invitationSalary + `,"package":` + invitationPackage + `}` validInvitationCreate = `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt",` + `"need":{"need_id":"01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12","requirements_version":3},` + `"response_period_days":7,"terms":` + validInvitationTerms + `}` validInvitationAccept = `{"expected_version":5,"terms_version":3,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true,"fields":["email"]}}` ) // invitationCreateWithTerms returns a CreateOrganizationInvitation body whose // terms are the valid terms with one replacement applied. func invitationCreateWithTerms(old, replacement string) string { return `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","terms":` + strings.Replace(validInvitationTerms, old, replacement, 1) + `}` } // The schema alone must accept a complete invitation and reject what the // contract never allows: terms without a required field, a package condition // left out instead of not_provided, a salary range without a valid RUB base, // a response period outside 3, 7, and 14, client-set state, versions, salary // indicator, or candidate contacts, an acceptance without terms_version or // with an empty or implicit C4 choice, and a decline without a known reason. // Security accepts the session here, so the request reaches validation; a // valid request then answers 501 until invitations are implemented. // Cross-field rules (A < B, the 10-40% width, a place of work for office or // hybrid) and the current terms version pass the schema; the server checks // them. func TestInvitationSchemaValidationPrecedesImplementation(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: organizationInvitationsPath, body: body, headers: command} } update := func(body string) identityRequest { return identityRequest{method: http.MethodPatch, path: organizationInvitationPath, body: body, headers: session} } post := func(path, body string) identityRequest { return identityRequest{method: http.MethodPost, path: path, body: body, headers: command} } accept := func(body string) identityRequest { return post(myInvitationPath+"/accept", body) } decline := func(body string) identityRequest { return post(myInvitationPath+"/decline", body) } for _, test := range []struct { name string request identityRequest location api.ProblemFieldLocation pointer string code string }{ { name: "list of an organization", request: identityRequest{method: http.MethodGet, path: organizationInvitationsPath + "?limit=20", headers: session}, }, { name: "list for an organization identifier that is not a UUID", request: identityRequest{method: http.MethodGet, path: "/api/v1/organizations/acme/invitations", headers: session}, location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid", }, { name: "create a complete draft from a need", request: create(validInvitationCreate), }, { name: "create a direct draft with the default response period", request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","need":null,"terms":` + validInvitationTerms + `}`), }, { // The cross-field salary rules and the place of work for an // office format are domain rules that the server checks after // the schema. name: "create with a reversed salary range", request: create(invitationCreateWithTerms(`"salary_from":200000,"salary_to":260000`, `"salary_from":260000,"salary_to":200000`)), }, { name: "create with a salary range wider than 40%", request: create(invitationCreateWithTerms(`"salary_to":260000`, `"salary_to":400000`)), }, { name: "create an office role without a place of work", request: create(invitationCreateWithTerms(`"work_formats":["remote"]`, `"work_formats":["office"]`)), }, { name: "create without an Idempotency-Key", request: identityRequest{method: http.MethodPost, path: organizationInvitationsPath, body: validInvitationCreate, headers: session}, location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required", }, { name: "create without a candidate handle", request: create(`{"terms":` + validInvitationTerms + `}`), location: api.ProblemFieldLocationBody, pointer: "/candidate_handle", code: "required", }, { name: "create for a candidate named by an email address", request: create(strings.Replace(validInvitationCreate, `"cand_7Qm2xVb9Lr4Kp0Zt"`, `"candidate@example.com"`, 1)), location: api.ProblemFieldLocationBody, pointer: "/candidate_handle", code: "invalid", }, { name: "create without terms", request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt"}`), location: api.ProblemFieldLocationBody, pointer: "/terms", code: "required", }, { // The responder rebuilds the path of a missing nested field from // the decoder's field wrappers. name: "terms without a tax basis", request: create(invitationCreateWithTerms(`,"tax_basis":"net"`, ``)), location: api.ProblemFieldLocationBody, pointer: "/terms/salary/tax_basis", code: "required", }, { name: "terms without a communication method", request: create(invitationCreateWithTerms(`"communication_method":`+invitationCommunication+`,`, ``)), location: api.ProblemFieldLocationBody, pointer: "/terms/communication_method", code: "required", }, { name: "terms with an unknown communication channel", request: create(invitationCreateWithTerms(`"channel":"email"`, `"channel":"carrier_pigeon"`)), location: api.ProblemFieldLocationBody, pointer: "/terms/communication_method/channel", code: "invalid", }, { name: "terms without a salary", request: create(invitationCreateWithTerms(`,"salary":`+invitationSalary, ``)), location: api.ProblemFieldLocationBody, pointer: "/terms/salary", code: "required", }, { name: "terms without tasks", request: create(invitationCreateWithTerms(`["Развивать сервис выплат"]`, `[]`)), location: api.ProblemFieldLocationBody, pointer: "/terms/tasks", code: "invalid", }, { name: "terms with a task that is not a text", request: create(invitationCreateWithTerms(`["Развивать сервис выплат"]`, `["Развивать сервис выплат",5]`)), location: api.ProblemFieldLocationBody, pointer: "/terms/tasks", code: "invalid", }, { name: "terms with an unknown field", request: create(invitationCreateWithTerms(`"role_title"`, `"benefits":"много","role_title"`)), location: api.ProblemFieldLocationBody, pointer: "/terms", code: "invalid", }, { name: "terms with an empty stack", request: create(invitationCreateWithTerms(`["Go","PostgreSQL"]`, `[]`)), location: api.ProblemFieldLocationBody, pointer: "/terms/tech_stack", code: "invalid", }, { name: "terms with a place of work left out instead of null", request: create(invitationCreateWithTerms(`"location":null,`, ``)), location: api.ProblemFieldLocationBody, pointer: "/terms/location", code: "required", }, { name: "package condition left out instead of not provided", request: create(invitationCreateWithTerms(`"training":{"status":"not_provided"},`, ``)), location: api.ProblemFieldLocationBody, pointer: "/terms/package/training", code: "required", }, { name: "package condition provided without a description", request: create(invitationCreateWithTerms(`{"status":"provided","description":"Ноутбук"}`, `{"status":"provided"}`)), location: api.ProblemFieldLocationBody, pointer: "/terms/package/equipment/description", code: "required", }, { name: "package condition not provided with a description", request: create(invitationCreateWithTerms(`"training":{"status":"not_provided"}`, `"training":{"status":"not_provided","description":"Курсы"}`)), location: api.ProblemFieldLocationBody, pointer: "/terms/package/training", code: "invalid", }, { name: "package condition as a bare text", request: create(invitationCreateWithTerms(`{"status":"provided","description":"Ноутбук"}`, `"Ноутбук"`)), location: api.ProblemFieldLocationBody, pointer: "/terms/package/equipment", code: "invalid", }, { name: "salary bound that is not a multiple of 1000", request: create(invitationCreateWithTerms(`"salary_to":260000`, `"salary_to":260500`)), location: api.ProblemFieldLocationBody, pointer: "/terms/salary/salary_to", code: "invalid", }, { name: "salary bound of zero", request: create(invitationCreateWithTerms(`"salary_from":200000`, `"salary_from":0`)), location: api.ProblemFieldLocationBody, pointer: "/terms/salary/salary_from", code: "invalid", }, { name: "salary with an unknown tax basis", request: create(invitationCreateWithTerms(`"tax_basis":"net"`, `"tax_basis":"net_or_gross"`)), location: api.ProblemFieldLocationBody, pointer: "/terms/salary/tax_basis", code: "invalid", }, { name: "salary in another currency", request: create(invitationCreateWithTerms(`"currency":"RUB"`, `"currency":"USD"`)), location: api.ProblemFieldLocationBody, pointer: "/terms/salary/currency", code: "invalid", }, { name: "response period outside the policy options", request: create(strings.Replace(validInvitationCreate, `"response_period_days":7`, `"response_period_days":10`, 1)), location: api.ProblemFieldLocationBody, pointer: "/response_period_days", code: "invalid", }, { name: "candidate minimum inside the salary range", request: create(invitationCreateWithTerms(`"tax_basis":"net"`, `"tax_basis":"net","candidate_minimum":230000`)), location: api.ProblemFieldLocationBody, pointer: "/terms/salary", code: "invalid", }, { name: "candidate email in the body", request: create(strings.Replace(validInvitationCreate, `{"candidate_handle"`, `{"candidate_email":"candidate@example.com","candidate_handle"`, 1)), location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "state set by the employer", request: create(strings.Replace(validInvitationCreate, `{"candidate_handle"`, `{"state":"accepted","candidate_handle"`, 1)), location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "salary indicator set by the employer", request: create(strings.Replace(validInvitationCreate, `{"candidate_handle"`, `{"salary_fit":"within_range","candidate_handle"`, 1)), location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "read of an organization", request: identityRequest{method: http.MethodGet, path: organizationInvitationPath, headers: session}, }, { name: "read with an invitation identifier that is not a UUID", request: identityRequest{method: http.MethodGet, path: organizationInvitationsPath + "/1", headers: session}, location: api.ProblemFieldLocationPath, pointer: "/invitation_id", code: "invalid", }, { name: "update the terms of a draft", request: update(`{"expected_version":1,"terms":` + validInvitationTerms + `}`), }, { name: "unlink the need of a draft", request: update(`{"expected_version":2,"need":null}`), }, { name: "update without an expected version", request: update(`{"terms":` + validInvitationTerms + `}`), location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required", }, { name: "update with version zero", request: update(`{"expected_version":0}`), location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid", }, { name: "update that sets the terms version itself", request: update(`{"expected_version":1,"terms_version":7}`), location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "update that changes the candidate", request: update(`{"expected_version":1,"candidate_handle":"cand_Hx3Tn8Wq1Ys6Fd2Vb"}`), location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "send", request: post(organizationInvitationPath+"/send", `{"expected_version":2}`), }, { name: "send without an expected version", request: post(organizationInvitationPath+"/send", `{}`), location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required", }, { name: "send without an Idempotency-Key", request: identityRequest{method: http.MethodPost, path: organizationInvitationPath + "/send", body: `{"expected_version":2}`, headers: session}, location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required", }, { name: "raise the upper salary bound", request: post(organizationInvitationPath+"/salary-raise", `{"expected_version":4,"salary_to":280000}`), }, { name: "raise that lowers the lower bound too", request: post(organizationInvitationPath+"/salary-raise", `{"expected_version":4,"salary_from":150000,"salary_to":280000}`), location: api.ProblemFieldLocationBody, pointer: "", code: "invalid", }, { name: "raise to a bound that is not a multiple of 1000", request: post(organizationInvitationPath+"/salary-raise", `{"expected_version":4,"salary_to":280500}`), location: api.ProblemFieldLocationBody, pointer: "/salary_to", code: "invalid", }, { name: "withdraw", request: post(organizationInvitationPath+"/withdraw", `{"expected_version":3}`), }, { name: "read the contacts", request: identityRequest{method: http.MethodGet, path: organizationInvitationPath + "/contacts", headers: session}, }, { name: "list of the candidate", request: identityRequest{method: http.MethodGet, path: myInvitationsPath + "?limit=20", headers: session}, }, { name: "open the terms", request: identityRequest{method: http.MethodGet, path: myInvitationPath, headers: session}, }, { name: "open an invitation identifier that is not a UUID", request: identityRequest{method: http.MethodGet, path: myInvitationsPath + "/1", headers: session}, location: api.ProblemFieldLocationPath, pointer: "/invitation_id", code: "invalid", }, { // The view command has no body, no Idempotency-Key, and no // expected_version: a repeat returns the current invitation. name: "record a view", request: identityRequest{method: http.MethodPost, path: myInvitationPath + "/view", headers: session}, }, { name: "record a view of an identifier that is not a UUID", request: identityRequest{method: http.MethodPost, path: myInvitationsPath + "/1/view", headers: session}, location: api.ProblemFieldLocationPath, pointer: "/invitation_id", code: "invalid", }, { // A stale terms version passes the schema; the server answers 412. name: "accept with the email address only", request: accept(validInvitationAccept), }, { name: "accept without a terms version", request: accept(`{"expected_version":5,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true,"fields":["email"]}}`), location: api.ProblemFieldLocationBody, pointer: "/terms_version", code: "required", }, { name: "accept with terms version zero", request: accept(strings.Replace(validInvitationAccept, `"terms_version":3`, `"terms_version":0`, 1)), location: api.ProblemFieldLocationBody, pointer: "/terms_version", code: "invalid", }, { name: "accept without an expected version", request: accept(strings.Replace(validInvitationAccept, `"expected_version":5,`, ``, 1)), location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required", }, { name: "accept without the consent C4", request: accept(`{"expected_version":5,"terms_version":3}`), location: api.ProblemFieldLocationBody, pointer: "/consent_c4", code: "required", }, { name: "accept with an empty choice of contact fields", request: accept(strings.Replace(validInvitationAccept, `["email"]`, `[]`, 1)), location: api.ProblemFieldLocationBody, pointer: "/consent_c4/fields", code: "invalid", }, { // A missing field choice is not a hidden default of every field. name: "accept without a choice of contact fields", request: accept(strings.Replace(validInvitationAccept, `,"fields":["email"]`, ``, 1)), location: api.ProblemFieldLocationBody, pointer: "/consent_c4/fields", code: "required", }, { name: "accept with an unknown contact field", request: accept(strings.Replace(validInvitationAccept, `["email"]`, `["passport"]`, 1)), location: api.ProblemFieldLocationBody, pointer: "/consent_c4/fields/0", code: "invalid", }, { name: "accept with a repeated contact field", request: accept(strings.Replace(validInvitationAccept, `["email"]`, `["email","email"]`, 1)), location: api.ProblemFieldLocationBody, pointer: "/consent_c4/fields", code: "invalid", }, { name: "accept with consent not given", request: accept(strings.Replace(validInvitationAccept, `"accepted":true`, `"accepted":false`, 1)), location: api.ProblemFieldLocationBody, pointer: "/consent_c4/accepted", code: "invalid", }, { name: "accept that carries a contact value", request: accept(strings.Replace(validInvitationAccept, `"fields":["email"]`, `"fields":["email"],"email":"candidate@example.com"`, 1)), location: api.ProblemFieldLocationBody, pointer: "/consent_c4", code: "invalid", }, { name: "decline with the reason other and no comment", request: decline(`{"expected_version":4,"reason":"other"}`), }, { name: "decline with a comment", request: decline(`{"expected_version":4,"reason":"salary","comment":"Вилка ниже ожиданий."}`), }, { name: "decline without a reason", request: decline(`{"expected_version":4,"comment":"Не подходит."}`), location: api.ProblemFieldLocationBody, pointer: "/reason", code: "required", }, { name: "decline with an unknown reason", request: decline(`{"expected_version":4,"reason":"too_old"}`), location: api.ProblemFieldLocationBody, pointer: "/reason", code: "invalid", }, { name: "decline with a blank comment", request: decline(`{"expected_version":4,"reason":"other","comment":" "}`), location: api.ProblemFieldLocationBody, pointer: "/comment", code: "invalid", }, { name: "decline with a comment over 500 characters", request: decline(`{"expected_version":4,"reason":"other","comment":"` + strings.Repeat("а", 501) + `"}`), location: api.ProblemFieldLocationBody, pointer: "/comment", code: "invalid", }, { name: "decline with a comment of exactly 500 characters", request: decline(`{"expected_version":4,"reason":"other","comment":"` + strings.Repeat("а", 500) + `"}`), }, { name: "cancel the participation", request: post(myInvitationPath+"/cancel", `{"expected_version":6}`), }, { name: "cancel without an expected version", request: post(myInvitationPath+"/cancel", `{}`), location: api.ProblemFieldLocationBody, 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, nil) 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 invitation operation requires a session; DenyAllSecurity grants none, // with or without a cookie and a CSRF token. func TestInvitationAccessBeforeImplementation(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: organizationInvitationsPath}, {method: http.MethodGet, path: organizationInvitationsPath, headers: map[string]string{"Cookie": testSessionCookie}}, {method: http.MethodPost, path: organizationInvitationsPath, body: validInvitationCreate, headers: command}, {method: http.MethodGet, path: organizationInvitationPath, headers: session}, {method: http.MethodPatch, path: organizationInvitationPath, body: `{"expected_version":1,"need":null}`, headers: session}, {method: http.MethodPost, path: organizationInvitationPath + "/send", body: `{"expected_version":2}`, headers: command}, {method: http.MethodPost, path: organizationInvitationPath + "/salary-raise", body: `{"expected_version":4,"salary_to":280000}`, headers: command}, {method: http.MethodPost, path: organizationInvitationPath + "/withdraw", body: `{"expected_version":3}`, headers: command}, {method: http.MethodGet, path: organizationInvitationPath + "/contacts", headers: session}, {method: http.MethodGet, path: myInvitationsPath, headers: session}, {method: http.MethodGet, path: myInvitationPath, headers: session}, {method: http.MethodPost, path: myInvitationPath + "/view", headers: session}, {method: http.MethodPost, path: myInvitationPath + "/accept", body: validInvitationAccept, headers: command}, {method: http.MethodPost, path: myInvitationPath + "/decline", body: `{"expected_version":4,"reason":"other"}`, headers: command}, {method: http.MethodPost, path: myInvitationPath + "/cancel", body: `{"expected_version":6}`, headers: command}, } { 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) }) } } // invitationResponsePrivateFields are fields that would disclose a candidate's // contact or hidden salary minimum, or the reason of an individual decline, // before a grant allows it. Only ContactDisclosure carries contact values. var invitationResponsePrivateFields = []string{ "email", "phone", "telegram", "full_name", "name", "contacts", "contact", "salary_minimum", "candidate_minimum", "minimum", "minimum_salary", "candidate_id", "profile_id", "account_id", "user_id", } // The invitation DTOs that either side reads before an acceptance must not be // able to carry a contact or the hidden minimum, and the organization's DTOs // must not carry the candidate's decline reason or comment. func TestInvitationDTOsCarryNoContactOrMinimum(t *testing.T) { for _, dto := range []any{ api.OrganizationInvitation{}, api.OrganizationInvitationSummary{}, api.InvitationTerms{}, api.InvitationContactAccess{}, api.CandidateInvitation{}, api.CandidateInvitationSummary{}, api.ContactGrant{}, api.ContactConsentOffer{}, } { assertNoJSONFields(t, dto, invitationResponsePrivateFields) } for _, dto := range []any{api.OrganizationInvitation{}, api.OrganizationInvitationSummary{}} { assertNoJSONFields(t, dto, []string{"decline", "decline_reason", "reason", "comment"}) } for _, dto := range []any{ api.OrganizationInvitationCreate{}, api.OrganizationInvitationUpdate{}, api.InvitationCommand{}, api.InvitationSalaryRaise{}, api.InvitationAcceptance{}, api.ContactConsentAcceptance{}, api.InvitationDeclineRequest{}, } { assertNoJSONFields(t, dto, append([]string{"state", "version", "salary_fit", "contact_access", "grant_id"}, invitationResponsePrivateFields...)) } } // myConsentsPath is the consent ledger of the session account. const myConsentsPath = "/api/v1/me/consents" // The schema alone must accept the read of the own ledger with an optional // state filter and reject an unknown state and malformed page parameters. // Security accepts the session here, so the request reaches validation; a // valid request then answers 501 until the ledger read is implemented. func TestConsentSchemaValidationPrecedesImplementation(t *testing.T) { session := map[string]string{"Cookie": testSessionCookie} for _, test := range []struct { name string query string pointer string }{ {name: "the whole history", query: ""}, {name: "the active consents", query: "?state=active"}, {name: "the revoked consents of the next page", query: "?state=revoked&limit=50&cursor=b3BhcXVlLWN1cnNvcg"}, {name: "an unknown state", query: "?state=granted", pointer: "/state"}, {name: "a purpose instead of a state", query: "?state=c4", pointer: "/state"}, {name: "a limit over 100", query: "?limit=101", pointer: "/limit"}, {name: "a malformed cursor", query: "?cursor=not%20a%20cursor", pointer: "/cursor"}, } { 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, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } response := serveIdentityRequest(t, router, identityRequest{method: http.MethodGet, path: myConsentsPath + test.query, headers: session}) if test.pointer == "" { requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented) return } body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed) want := api.ProblemFieldError{In: api.ProblemFieldLocationQuery, Pointer: test.pointer, Code: "invalid"} 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 ledger read requires a session; DenyAllSecurity grants none, with or // without a cookie, and a request cannot name another subject instead. func TestConsentAccessBeforeImplementation(t *testing.T) { for _, test := range []identityRequest{ {method: http.MethodGet, path: myConsentsPath}, {method: http.MethodGet, path: myConsentsPath + "?state=active", headers: map[string]string{"Cookie": testSessionCookie}}, {method: http.MethodGet, path: myConsentsPath + "?subject_id=01928f7a-0000-7000-8000-00000000c0de", 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) }) } } // The read model never carries the stored text hash, a subject, or a contact // value, and its parameters cannot select a subject. func TestConsentDTOsCarryNoHashSubjectOrContact(t *testing.T) { private := []string{"text_hash", "hash", "body_sha256", "subject_id", "user_id", "account_id", "email", "phone", "telegram", "full_name"} for _, dto := range []any{api.ConsentRecord{}, api.ConsentRecordList{}, api.ConsentOrganization{}} { assertNoJSONFields(t, dto, private) } params := reflect.TypeFor[api.ListMyConsentsParams]() names := make([]string, 0, params.NumField()) for i := range params.NumField() { names = append(names, params.Field(i).Name) } if got := strings.Join(names, ","); got != "State,Limit,Cursor" { t.Fatalf("ListMyConsentsParams fields = %s, want only the state filter and the page", got) } // The documented example is a valid response of the generated server. var page api.ConsentRecordList if err := page.UnmarshalJSON(supportCaseExample(t, "ConsentRecordListPage")); err != nil { t.Fatalf("decode the ConsentRecordListPage example: %v", err) } if err := page.Validate(); err != nil { t.Fatalf("validate the ConsentRecordListPage example: %v", err) } } 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, nil) 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/healthz", 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, nil) 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, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } return router }