package httpadapter import ( "context" "encoding/json" "log/slog" "net/http" "slices" "strings" "testing" "github.com/ogen-go/ogen" "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" ) const profilePath = "/api/v1/me/profile" // isProfileSchema names the schemas that exist only for the private candidate // profile. The schemas it shares with other contracts, such as the contact // value formats, do not match. func isProfileSchema(name string) bool { return name == "CandidateProfile" || name == "CandidateProfileUpdate" || strings.HasPrefix(name, "Profile") } func propertyNames(schema *ogen.Schema) []string { names := make([]string, 0, len(schema.Properties)) for _, property := range schema.Properties { names = append(names, property.Name) } slices.Sort(names) return names } func hasSecurity(operation *ogen.Operation, scheme string) bool { return slices.ContainsFunc(operation.Security, func(requirement ogen.SecurityRequirement) bool { _, ok := requirement[scheme] return ok }) } // A save of the profile follows the project conventions of a versioned // replacement: session and CSRF, the version in the body, 412 for a stale one // and no Idempotency-Key, because replacing the whole state is idempotent. func TestCandidateProfileOperationsFollowTheConventions(t *testing.T) { spec := parsePublicContract(t) get := operationByID(t, spec, "GetMyProfile") if !hasSecurity(get, "sessionCookie") || hasSecurity(get, "sessionCsrf") { t.Errorf("GetMyProfile security = %v, want the session cookie only", get.Security) } save := operationByID(t, spec, "SaveMyProfile") if !hasSecurity(save, "sessionCookie") || !hasSecurity(save, "sessionCsrf") { t.Errorf("SaveMyProfile security = %v, want the session cookie and the CSRF token", save.Security) } for _, status := range []string{"400", "401", "403", "412"} { if _, ok := save.Responses[status]; !ok { t.Errorf("SaveMyProfile does not declare %s", status) } } if _, ok := save.Responses["409"]; ok { t.Error("SaveMyProfile declares 409: a stale version is 412 version_conflict") } for _, status := range []string{"401", "403"} { if _, ok := get.Responses[status]; !ok { t.Errorf("GetMyProfile does not declare %s", status) } } for _, operation := range []*ogen.Operation{get, save} { for _, parameter := range operation.Parameters { if strings.EqualFold(parameter.Name, "Idempotency-Key") || strings.EqualFold(parameter.Name, "If-Match") { t.Errorf("%s takes %s, want the version in the body", operation.OperationID, parameter.Name) } } ok := operation.Responses["200"] if ok == nil || ok.Headers["Cache-Control"] == nil { t.Errorf("%s does not mark its 200 response no-store", operation.OperationID) } } update := resolveSchema(t, spec, save.RequestBody.Content["application/json"].Schema) if !slices.Contains(update.Required, "expected_version") { t.Error("the profile update does not require expected_version") } version := resolveSchema(t, spec, schemaProperty(t, update, "expected_version")) if string(version.Minimum) != "0" { t.Error("expected_version does not start at 0, the version of a profile never saved") } problem412 := save.Responses["412"] if problem412 == nil || problem412.Ref == "" { t.Error("the 412 response is not a reusable response") } } // The self-assessed grade of a role and the confirmed category are different // facts: only an assessment result confirms a category, so no request carries // one and every profile claim stays unverified. func TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory(t *testing.T) { spec := parsePublicContract(t) profile := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfile"}) if !slices.Contains(profile.Required, "confirmed_categories") { t.Error("the profile does not state confirmed categories apart from the claims") } update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfileUpdate"}) wantUpdate := []string{"confirmed_parallel_periods", "contacts", "expected_version", "experience", "full_name", "projects", "roles", "soft_skills", "stack", "terms"} if got := propertyNames(update); !slices.Equal(got, wantUpdate) { t.Errorf("CandidateProfileUpdate properties = %v, want %v", got, wantUpdate) } profile = resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfile"}) if !slices.Contains(profile.Required, "experience_overlaps") { t.Error("CandidateProfile does not report every overlapping experience pair") } confirmation := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileParallelPeriodConfirmation"}) if got := propertyNames(confirmation); !slices.Equal(got, []string{"first_index", "first_period", "second_index", "second_period"}) { t.Errorf("ProfileParallelPeriodConfirmation properties = %v, want indices and exact periods only", got) } role := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileRoleItemInput"}) if got := propertyNames(role); !slices.Equal(got, []string{"self_assessed_grade", "specialization", "status"}) { t.Errorf("ProfileRoleItemInput properties = %v, want the self-assessed grade only", got) } storedRole := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileRoleItem"}) for _, forbidden := range []string{"confirmed_grade", "category", "grade"} { if slices.Contains(propertyNames(storedRole), forbidden) { t.Errorf("ProfileRoleItem has %q: a role holds the claim, never a confirmed grade", forbidden) } } category := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileConfirmedCategory"}) for _, field := range []string{"specialization", "grade", "confirmed_at", "attempt_id"} { if !slices.Contains(category.Required, field) { t.Errorf("ProfileConfirmedCategory does not require %s: a confirmed category names its assessment", field) } } // The same grade scale and specialization codes as the catalog and the // questionnaire, not copies of them. for _, test := range []struct { schema, property, ref string }{ {"ProfileConfirmedCategory", "grade", "#/components/schemas/GradeCode"}, {"ProfileConfirmedCategory", "specialization", "#/components/schemas/SpecializationCode"}, {"ProfileRoleItemInput", "specialization", "#/components/schemas/SpecializationCode"}, {"ProfileStackItemInput", "tag", "#/components/schemas/StackTag"}, } { parent := spec.Components.Schemas[test.schema] if got := schemaProperty(t, parent, test.property); got.Ref != test.ref { t.Errorf("%s.%s = %q, want a reference to %s", test.schema, test.property, got.Ref, test.ref) } } // A request cannot set provenance, a trust level, or a confirmed // category: the request schemas close their objects and name none. for name, schema := range spec.Components.Schemas { if !isProfileSchema(name) { continue } if schema.Type == "object" && (schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool) { t.Errorf("%s accepts unknown fields", name) } if !strings.HasSuffix(name, "Input") && name != "CandidateProfileUpdate" { continue } for _, forbidden := range []string{"source", "trust_level", "origin", "confirmed_at", "confirmed_categories", "confirmed_grade", "category", "quote", "extraction_version"} { if slices.Contains(propertyNames(schema), forbidden) { t.Errorf("%s accepts %q from the client", name, forbidden) } } } } // Every value of the profile carries its confirmation state and its source, // and the source gives imported claims trust level 0. func TestCandidateProfileClaimsCarrySourceAndTrustLevelZero(t *testing.T) { spec := parsePublicContract(t) source := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileClaimSource"}) for _, field := range []string{"origin", "trust_level", "quote", "extraction_version", "confirmed_at"} { if !slices.Contains(source.Required, field) { t.Errorf("ProfileClaimSource does not require %s", field) } } trust := resolveSchema(t, spec, schemaProperty(t, source, "trust_level")) if string(trust.Minimum) != "0" || string(trust.Maximum) != "0" { t.Errorf("trust_level range = %s..%s, want exactly 0", trust.Minimum, trust.Maximum) } origins := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProfileClaimOrigin"})) for _, origin := range []string{"manual", "extracted_from_resume", "imported"} { if !slices.Contains(origins, origin) { t.Errorf("ProfileClaimOrigin has no %s", origin) } } for _, name := range []string{ "ProfileFullNameClaim", "ProfileEmailClaim", "ProfilePhoneClaim", "ProfileTelegramClaim", "ProfileLocationClaim", "ProfileRelocationClaim", "ProfileSalaryMinimumClaim", } { claim := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name}) for _, field := range []string{"status", "value", "source"} { if !slices.Contains(claim.Required, field) { t.Errorf("%s does not require %s", name, field) } } } for _, name := range []string{"ProfileStackItem", "ProfileSoftSkillItem", "ProfileRoleItem", "ProfileExperienceItem"} { item := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name}) for _, field := range []string{"status", "source"} { if !slices.Contains(item.Required, field) { t.Errorf("%s does not require %s", name, field) } } itemSource := schemaProperty(t, spec.Components.Schemas[name], "source") if itemSource.Ref != "#/components/schemas/ProfileClaimSource" { t.Errorf("%s.source = %q, want the shared ProfileClaimSource", name, itemSource.Ref) } } // Contacts reuse the formats of the contact disclosure, so a disclosure // never has to convert a stored value. for _, test := range []struct{ schema, ref string }{ {"ProfileFullNameClaim", "#/components/schemas/ContactFullName"}, {"ProfilePhoneClaim", "#/components/schemas/ContactPhoneNumber"}, {"ProfileTelegramClaim", "#/components/schemas/ContactTelegramUsername"}, } { value := schemaProperty(t, spec.Components.Schemas[test.schema], "value") if len(value.OneOf) == 0 || value.OneOf[0].Ref != test.ref { t.Errorf("%s.value = %+v, want %s", test.schema, value, test.ref) } } } // componentsIndex returns the components of the contract as generic JSON, so // a reference can be followed by its pointer whatever its kind. func componentsIndex(t *testing.T, spec *ogen.Spec) map[string]any { t.Helper() encoded, err := json.Marshal(spec.Components) if err != nil { t.Fatalf("encode the components: %v", err) } var kinds map[string]map[string]any if err := json.Unmarshal(encoded, &kinds); err != nil { t.Fatalf("decode the components: %v", err) } index := map[string]any{} for kind, components := range kinds { for name, component := range components { index["#/components/"+kind+"/"+name] = component } } return index } func collectReferences(value any, found *[]string) { switch typed := value.(type) { case map[string]any: for key, child := range typed { if reference, ok := child.(string); ok && key == "$ref" { *found = append(*found, reference) continue } collectReferences(child, found) } case []any: for _, child := range typed { collectReferences(child, found) } } } // reachableSchemas returns the schema names that start reaches by references. func reachableSchemas(index map[string]any, start any) map[string]bool { reached := map[string]bool{} var pending []string collectReferences(start, &pending) for len(pending) > 0 { reference := pending[len(pending)-1] pending = pending[:len(pending)-1] if reached[reference] { continue } reached[reference] = true if component, ok := index[reference]; ok { collectReferences(component, &pending) } } names := map[string]bool{} for reference := range reached { if name, ok := strings.CutPrefix(reference, "#/components/schemas/"); ok { names[name] = true } } return names } // The private profile holds personal data that an organization must never // read, so no schema that an organization can see may refer to it, and the // profile schemas refer to nothing of an organization. The check follows // references through request bodies, responses, parameters, and headers. func TestPrivateProfileSchemasAreNotMixedWithOrganizationVisibleDTOs(t *testing.T) { spec := parsePublicContract(t) index := componentsIndex(t, spec) // The profile family is not empty and its operations reach it. profileOperations := reachableSchemas(index, mustJSONValue(t, spec.Paths[profilePath])) if !profileOperations["CandidateProfile"] || !profileOperations["CandidateProfileUpdate"] { t.Fatalf("the profile path reaches %v, want CandidateProfile and CandidateProfileUpdate", profileOperations) } // No schema outside the profile family refers to a profile schema. for name, schema := range spec.Components.Schemas { if isProfileSchema(name) { continue } for reached := range reachableSchemas(index, mustJSONValue(t, schema)) { if isProfileSchema(reached) { t.Errorf("%s reaches the private profile schema %s", name, reached) } } } // No operation of an organization, and none that an organization can // read, reaches a profile schema. for path, item := range spec.Paths { if !strings.HasPrefix(path, "/api/v1/organizations") { continue } for reached := range reachableSchemas(index, mustJSONValue(t, item)) { if isProfileSchema(reached) { t.Errorf("%s reaches the private profile schema %s", path, reached) } } } // The family refers to no organization, invitation, or need schema except // the shared money and label leaves it reuses. shared := []string{"RubAmount", "CurrencyCode", "SalaryPeriod", "SalaryTaxBasis", "NeedVersionLabel"} for name, schema := range spec.Components.Schemas { if !isProfileSchema(name) { continue } for reached := range reachableSchemas(index, mustJSONValue(t, schema)) { isOrganizationSide := strings.HasPrefix(reached, "Organization") || strings.HasPrefix(reached, "Invitation") || strings.HasPrefix(reached, "Need") || strings.HasPrefix(reached, "CandidateOrganization") || reached == "ContactDisclosure" if isOrganizationSide && !slices.Contains(shared, reached) { t.Errorf("%s reaches the organization-side schema %s", name, reached) } } } } func mustJSONValue(t *testing.T, value any) any { t.Helper() encoded, err := json.Marshal(value) if err != nil { t.Fatalf("encode a contract value: %v", err) } var decoded any if err := json.Unmarshal(encoded, &decoded); err != nil { t.Fatalf("decode a contract value: %v", err) } return decoded } // The generated DTOs keep claims and the private profile apart from the // organization DTOs at the Go type level too. func TestGeneratedProfileDTOsCarryNoConfirmedGradeInRequests(t *testing.T) { for _, dto := range []any{api.CandidateProfileUpdate{}, api.ProfileRoleItemInput{}, api.ProfileStackItemInput{}, api.ProfileExperienceItemInput{}} { assertNoJSONFields(t, dto, []string{ "confirmed_grade", "category", "confirmed_categories", "trust_level", "source", "origin", "version", "updated_at", }) } assertNoJSONFields(t, api.ProfileRoleItem{}, []string{"confirmed_grade", "category", "grade", "trust_level"}) } // The profile operations are in the contract before their business logic: a // schema failure answers 400 before anything else, a valid request with an // accepted session answers 501, and a denied session answers 401. func TestProfileSchemaValidationPrecedesImplementation(t *testing.T) { const ( stackItem = `{"tag":"PostgreSQL","status":"confirmed"}` roleItem = `{"specialization":"backend","self_assessed_grade":"middle","status":"confirmed"}` ) body := func(replace ...string) string { document := `{"expected_version":0,` + `"full_name":{"value":"Anna Sokolova","status":"confirmed"},` + `"contacts":{"email":null,"phone":{"value":"+79000000000","status":"confirmed"},"telegram":null},` + `"stack":[` + stackItem + `],"roles":[` + roleItem + `],"experience":[],"soft_skills":[],` + `"terms":{"location":null,"relocation":null,"salary_minimum":{"value":{"amount":180000,"currency":"RUB","period":"month","tax_basis":"net"},"status":"confirmed"}}}` for index := 0; index+1 < len(replace); index += 2 { if !strings.Contains(document, replace[index]) { t.Fatalf("body has no %q to replace", replace[index]) } document = strings.Replace(document, replace[index], replace[index+1], 1) } return document } for _, test := range []struct { name string body string statusCode int pointer string code string }{ {name: "a valid profile", body: body(), statusCode: http.StatusNotImplemented}, {name: "a profile saved with nothing set", body: `{"expected_version":3,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null},"stack":[],"roles":[],"experience":[],"soft_skills":[],"terms":{"location":null,"relocation":null,"salary_minimum":null}}`, statusCode: http.StatusNotImplemented}, {name: "missing expected version", body: body(`"expected_version":0,`, ""), statusCode: http.StatusBadRequest, pointer: "/expected_version", code: "required"}, {name: "phone outside E.164", body: body(`+79000000000`, `8 900 000 00 00`), statusCode: http.StatusBadRequest, pointer: "/contacts/phone/value", code: "invalid"}, {name: "decision outside confirmed and extracted", body: body(`"status":"confirmed"}],"roles"`, `"status":"unknown"}],"roles"`), statusCode: http.StatusBadRequest, pointer: "/stack/0/status", code: "invalid"}, {name: "salary not a multiple of 1000", body: body(`180000`, `180500`), statusCode: http.StatusBadRequest, pointer: "/terms/salary_minimum/value/amount", code: "invalid"}, {name: "salary in another currency", body: body(`"RUB"`, `"USD"`), statusCode: http.StatusBadRequest, pointer: "/terms/salary_minimum/value/currency", code: "invalid"}, {name: "grade outside the scale", body: body(`"middle"`, `"lead"`), statusCode: http.StatusBadRequest, pointer: "/roles/0/self_assessed_grade", code: "invalid"}, {name: "confirmed grade sent in a role", body: body(roleItem, strings.Replace(roleItem, `"status"`, `"confirmed_grade":"senior","status"`, 1)), statusCode: http.StatusBadRequest, pointer: "/roles", code: "invalid"}, {name: "confirmed categories sent by the client", body: body(`"experience":[]`, `"experience":[],"confirmed_categories":[]`), statusCode: http.StatusBadRequest, pointer: "", code: "invalid"}, {name: "provenance sent by the client", body: body(stackItem, strings.Replace(stackItem, `"status"`, `"source":{"origin":"imported"},"status"`, 1)), statusCode: http.StatusBadRequest, pointer: "/stack", 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, identityRequest{ method: http.MethodPut, path: profilePath, 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 } problemBody := requireProblem(t, response, test.statusCode, api.ProblemCodeValidationFailed) want := api.ProblemFieldError{In: api.ProblemFieldLocationBody, Pointer: test.pointer, Code: test.code} for _, field := range problemBody.Errors { if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code { return } } t.Fatalf("errors = %+v, want an entry %+v", problemBody.Errors, want) }) } } func TestProfileAccessBeforeImplementation(t *testing.T) { for _, test := range []struct { name string request identityRequest }{ {"read without a session", identityRequest{method: http.MethodGet, path: profilePath}}, {"save with a denied session", identityRequest{ method: http.MethodPut, path: profilePath, body: `{"expected_version":0,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null},"stack":[],"roles":[],"experience":[],"soft_skills":[],"terms":{"location":null,"relocation":null,"salary_minimum":null}}`, headers: map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}, }}, } { t.Run(test.name, func(t *testing.T) { router := newTestRouter(t, func(context.Context) error { return nil }) requireProblem(t, serveIdentityRequest(t, router, test.request), http.StatusUnauthorized, api.ProblemCodeUnauthenticated) }) } }