package httpadapter import ( "context" "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 ( privacyBasePath = "/api/v1/me/privacy" privacyPublicationPath = privacyBasePath + "/publication" privacySearchStatusPath = privacyBasePath + "/search-status" privacyHiddenPath = privacyBasePath + "/hidden-organizations" privacyOrganizationID = "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01" ) // Each visibility setting is its own family of schemas. The three never // refer to one another, so a client cannot read or write one setting through // the DTO of another, and the search status is not a consent. var ( publicationSchemas = []string{"Publication", "PublicationUpdate", "PublicationVersion", "PublicationState", "PublicationClosedReason", "CardField", "CardFieldSet"} searchStatusSchemas = []string{"SearchStatus", "SearchStatusUpdate", "SearchStatusVersion", "SearchStatusValue"} hiddenSchemas = []string{"HiddenOrganization", "HiddenOrganizationList", "PrivacyOrganization"} privacyOnlySchemas = []string{"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList"} // sharedLeafSchemas are the reusable leaves that the privacy family may // refer to; none of them identifies a person or carries a contact. sharedLeafSchemas = []string{"Timestamp", "PageInfo", "SpecializationCode", "GradeCode", "StackTag"} ) func isPrivacySchema(name string) bool { return slices.Contains(publicationSchemas, name) || slices.Contains(searchStatusSchemas, name) || slices.Contains(hiddenSchemas, name) || slices.Contains(privacyOnlySchemas, name) } // parameterName names a parameter by its component when it is a reference. func parameterName(parameter *ogen.Parameter) string { if parameter.Ref != "" { return parameter.Ref[strings.LastIndex(parameter.Ref, "/")+1:] } return parameter.Name } func privacyOperations(t *testing.T, spec *ogen.Spec) []*ogen.Operation { t.Helper() operations := make([]*ogen.Operation, 0, 9) for _, id := range []string{ "GetMyPrivacySettings", "SetMyPublication", "GetMyCardPreview", "SetMySearchStatus", "ListMyHiddenOrganizations", "HideOrganization", "UnhideOrganization", "ListMyPrivacyHistory", "ListMyCardAccessHistory", } { operations = append(operations, operationByID(t, spec, id)) } return operations } // Every visibility operation follows the project conventions: the session // only for reads, the session and the CSRF token for changes, the version in // the body with 412, 409 for a state that does not allow the change, 404 // without a distinction, and no new problem code. func TestPrivacyOperationsFollowTheConventions(t *testing.T) { spec := parsePublicContract(t) unsafe := map[string]bool{"SetMyPublication": true, "SetMySearchStatus": true, "HideOrganization": true, "UnhideOrganization": true} for _, operation := range privacyOperations(t, spec) { if !slices.Contains(operation.Tags, "privacy") { t.Errorf("%s is not in the privacy tag", operation.OperationID) } if !hasSecurity(operation, "sessionCookie") || hasSecurity(operation, "sessionCsrf") != unsafe[operation.OperationID] { t.Errorf("%s security = %v, want the session cookie, and the CSRF token exactly for a change", operation.OperationID, operation.Security) } for _, status := range []string{"401", "403"} { if operation.Responses[status] == nil { t.Errorf("%s does not declare %s", operation.OperationID, status) } } for _, parameter := range operation.Parameters { name := parameterName(parameter) if strings.EqualFold(name, "IdempotencyKey") || strings.EqualFold(name, "IfMatch") || strings.EqualFold(name, "Idempotency-Key") || strings.EqualFold(name, "If-Match") { t.Errorf("%s takes %s, but every setting is a replaced state with its version in the body", operation.OperationID, name) } } if success := operation.Responses["200"]; success != nil && success.Headers["Cache-Control"] == nil { t.Errorf("%s does not mark its 200 response no-store", operation.OperationID) } if operation.Responses["default"] == nil { t.Errorf("%s does not declare the problem default", operation.OperationID) } } for _, id := range []string{"SetMyPublication", "SetMySearchStatus"} { operation := operationByID(t, spec, id) if operation.Responses["412"] == nil || operation.Responses["400"] == nil { t.Errorf("%s does not declare 400 and 412", id) } update := resolveSchema(t, spec, operation.RequestBody.Content["application/json"].Schema) if !slices.Contains(update.Required, "expected_version") { t.Errorf("%s does not require expected_version", id) } } // Publishing needs the C2 consent, and a missing one is a state conflict. if operationByID(t, spec, "SetMyPublication").Responses["409"] == nil { t.Error("SetMyPublication does not declare 409 state_conflict for a missing C2 consent") } if operationByID(t, spec, "SetMySearchStatus").Responses["409"] != nil { t.Error("SetMySearchStatus declares 409: the status never depends on a consent") } // Hiding uses the same 404 for an unknown organization and one the // candidate cannot see; lifting the hiding reveals nothing and has no 404. hide := operationByID(t, spec, "HideOrganization") if hide.Responses["404"] == nil || hide.Responses["409"] == nil || hide.Responses["429"] == nil || hide.RequestBody != nil { t.Error("HideOrganization must declare 404, 409, and 429 and take no body") } unhide := operationByID(t, spec, "UnhideOrganization") if unhide.Responses["204"] == nil || unhide.Responses["404"] != nil { t.Error("UnhideOrganization must answer 204 and declare no 404: it reveals nothing about the organization") } // Lists page with the shared cursor parameters. for _, id := range []string{"ListMyHiddenOrganizations", "ListMyPrivacyHistory", "ListMyCardAccessHistory"} { names := []string{} for _, parameter := range operationByID(t, spec, id).Parameters { names = append(names, parameterName(parameter)) } if !slices.Contains(names, "PageLimit") || !slices.Contains(names, "PageCursor") { t.Errorf("%s parameters = %v, want the shared PageLimit and PageCursor", id, names) } } // No new problem code: every code of the privacy responses already exists. codes := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProblemCode"})) for _, code := range []string{"state_conflict", "version_conflict", "not_found", "rate_limited", "validation_failed"} { if !slices.Contains(codes, code) { t.Errorf("ProblemCode has no %s", code) } } } // The publication stores which fields are published and refers to the C2 // consent of the ledger; it neither carries nor changes a consent. The search // status is not a consent either. func TestPublicationAndSearchStatusAreNotConsents(t *testing.T) { spec := parsePublicContract(t) index := componentsIndex(t, spec) for _, pair := range []struct { name string want []string }{ // The body names no consent: the server binds the active C2 record. {"PublicationUpdate", []string{"expected_version", "fields", "state"}}, {"SearchStatusUpdate", []string{"expected_version", "value"}}, {"Publication", []string{"closed_reason", "consent_id", "fields", "published_at", "state", "version"}}, {"SearchStatus", []string{"confirmed_at", "lapsed", "lapses_at", "value", "version"}}, {"HiddenOrganization", []string{"hidden_at", "organization"}}, {"PrivacySettings", []string{"hidden_organizations_total", "publication", "search_status"}}, } { schema := spec.Components.Schemas[pair.name] if schema == nil { t.Fatalf("the contract has no schema %s", pair.name) } if got := propertyNames(schema); !slices.Equal(got, pair.want) { t.Errorf("%s properties = %v, want %v", pair.name, got, pair.want) } if schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool { t.Errorf("%s accepts unknown fields", pair.name) } } // The families do not reach one another. PrivacySettings is the one place // that reads the three together. families := map[string][]string{"publication": publicationSchemas, "search status": searchStatusSchemas, "hidden organizations": hiddenSchemas} for name, members := range families { for _, member := range members { for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[member])) { for otherName, others := range families { if otherName != name && slices.Contains(others, reached) { t.Errorf("the %s schema %s reaches the %s schema %s", name, member, otherName, reached) } } } } } // A consent, a profile, an account, or an invitation is reachable from // none of the settings: the status is a statement, never a consent. for _, name := range slices.Concat(publicationSchemas, searchStatusSchemas, hiddenSchemas, privacyOnlySchemas) { for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) { if strings.HasPrefix(reached, "Consent") || strings.HasPrefix(reached, "Profile") || strings.HasPrefix(reached, "CandidateProfile") || strings.HasPrefix(reached, "Invitation") || strings.HasPrefix(reached, "Contact") || reached == "Session" || reached == "User" { t.Errorf("%s reaches %s", name, reached) } } } // The search status operation reaches no publication or hidden schema. statusOperation := reachableSchemas(index, mustJSONValue(t, spec.Paths[privacySearchStatusPath])) for _, name := range slices.Concat(publicationSchemas, hiddenSchemas, privacyOnlySchemas) { if statusOperation[name] { t.Errorf("the search status path reaches %s", name) } } // The published field set cannot name a name, a contact, or the salary. fields := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CardField"})) want := []string{"categories", "stack", "experience", "soft_skills", "location", "relocation"} slices.Sort(fields) slices.Sort(want) if !slices.Equal(fields, want) { t.Errorf("CardField = %v, want %v", fields, want) } if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != uint64(len(want)) { t.Error("CardFieldSet must hold distinct items and at most one per field") } status := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/SearchStatusValue"})) if !slices.Equal(status, []string{"looking", "not_looking"}) { t.Errorf("SearchStatusValue = %v, want looking and not_looking", status) } } // The anonymous card never reaches a profile, a contact, or an identifier: // whatever an organization reads of a candidate before an accepted invitation // is limited to its own closed set of properties. func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) { spec := parsePublicContract(t) index := componentsIndex(t, spec) card := spec.Components.Schemas["AnonymousCardContent"] if card == nil { t.Fatal("the contract has no AnonymousCardContent") } if got, want := propertyNames(card), []string{"categories", "experience_months", "location", "relocation", "soft_skills", "stack"}; !slices.Equal(got, want) { t.Errorf("AnonymousCardContent properties = %v, want %v", got, want) } if card.AdditionalProperties.Bool == nil || *card.AdditionalProperties.Bool { t.Error("AnonymousCardContent accepts unknown properties") } // Each property is a card field and nothing else; a null is a hidden or // missing value, never a flag that tells which. for _, forbidden := range []string{"email", "phone", "telegram", "contact", "name", "salary", "user", "account", "profile", "employer", "id", "url", "link", "github", "resume"} { for _, name := range propertyNames(card) { if strings.Contains(name, forbidden) { t.Errorf("AnonymousCardContent has the property %q, which looks like %q", name, forbidden) } } } // What the card and the preview reach is a small closed list of leaves. allowed := []string{"AnonymousCardContent", "CardCategory", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode", "GradeCode", "StackTag", "Timestamp", "CardPreview"} for _, name := range []string{"AnonymousCardContent", "CardPreview"} { for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) { if !slices.Contains(allowed, reached) { t.Errorf("%s reaches %s, which the anonymous card must not carry", name, reached) } } } // The private profile, the contact formats, and the contact disclosure // are not reachable from any privacy schema or operation. for path, item := range spec.Paths { if !strings.HasPrefix(path, privacyBasePath) { continue } for reached := range reachableSchemas(index, mustJSONValue(t, item)) { if isProfileSchema(reached) || strings.HasPrefix(reached, "Contact") || reached == "EmailAddress" || reached == "PhoneNumber" || strings.HasPrefix(reached, "Invitation") || strings.HasPrefix(reached, "Need") || strings.HasPrefix(reached, "Consent") { t.Errorf("%s reaches %s", path, reached) } if !isPrivacySchema(reached) && !slices.Contains(sharedLeafSchemas, reached) && !strings.HasPrefix(reached, "Problem") && reached != "Problem" && reached != "ProblemCode" { t.Errorf("%s reaches %s, which is neither a privacy schema nor a shared leaf", path, reached) } } } // The reverse: the private profile family does not reach the card or any // visibility schema, and an organization path reaches no setting of a // candidate. The card content stays the only privacy schema meant for // organization-visible operations later (TASK-185). for name, schema := range spec.Components.Schemas { if isPrivacySchema(name) { continue } for reached := range reachableSchemas(index, mustJSONValue(t, schema)) { if isPrivacySchema(reached) && reached != "AnonymousCardContent" && reached != "CardCategory" && reached != "CardField" && reached != "CardFieldSet" { t.Errorf("%s reaches the candidate-private schema %s", name, reached) } } } for path, item := range spec.Paths { if !strings.HasPrefix(path, "/api/v1/organizations") { continue } for reached := range reachableSchemas(index, mustJSONValue(t, item)) { if isPrivacySchema(reached) { t.Errorf("%s reaches the candidate-private schema %s", path, reached) } } } for _, dto := range []any{api.AnonymousCardContent{}, api.CardCategory{}, api.CardPreview{}} { assertNoJSONFields(t, dto, []string{ "full_name", "name", "email", "phone", "telegram", "contacts", "salary_minimum", "user_id", "account_id", "profile_id", "employer", "resume", }) } } // The generated request DTOs carry only what the candidate may choose: no // consent identifier, time, interval, or policy version. func TestGeneratedPrivacyDTOsCarryNoServerOwnedFields(t *testing.T) { assertNoJSONFields(t, api.PublicationUpdate{}, []string{"consent_id", "consent", "published_at", "version", "user_id", "contacts", "full_name", "salary_minimum"}) assertNoJSONFields(t, api.SearchStatusUpdate{}, []string{"confirmed_at", "lapses_at", "lapsed", "interval", "policy_version", "policy_version_id", "consent_id", "version"}) assertNoJSONFields(t, api.SearchStatus{}, []string{"consent_id", "published", "fields", "hidden_organizations", "policy_version_id"}) assertNoJSONFields(t, api.HiddenOrganization{}, []string{"user_id", "candidate_id", "candidate", "reason"}) } func newPrivacyRouter(t *testing.T) http.Handler { t.Helper() 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) } return router } // The 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 no body reaches the handler without validation. func TestPrivacySchemaValidationPrecedesImplementation(t *testing.T) { session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken} for _, test := range []struct { name string method string path string body string statusCode int location api.ProblemFieldLocation pointer string code string }{ {name: "a valid publication", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["categories","stack"]}`, statusCode: http.StatusNotImplemented}, {name: "a valid closing", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":3,"state":"closed","fields":[]}`, statusCode: http.StatusNotImplemented}, {name: "a missing version", method: http.MethodPut, path: privacyPublicationPath, body: `{"state":"closed","fields":[]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required"}, {name: "a negative version", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":-1,"state":"closed","fields":[]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid"}, {name: "a contact as a card field", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["phone"]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/fields/0", code: "invalid"}, {name: "the full name as a card field", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["full_name"]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/fields/0", code: "invalid"}, {name: "a repeated card field", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["stack","stack"]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/fields", code: "invalid"}, {name: "a state outside the enum", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"draft","fields":[]}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/state", code: "invalid"}, {name: "a consent identifier from the client", method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"published","fields":["stack"],"consent_id":"01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60"}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid"}, {name: "a valid status", method: http.MethodPut, path: privacySearchStatusPath, body: `{"expected_version":0,"value":"looking"}`, statusCode: http.StatusNotImplemented}, {name: "a status outside the enum", method: http.MethodPut, path: privacySearchStatusPath, body: `{"expected_version":0,"value":"open"}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "/value", code: "invalid"}, {name: "a confirmation time from the client", method: http.MethodPut, path: privacySearchStatusPath, body: `{"expected_version":0,"value":"looking","confirmed_at":"2026-10-06T09:00:00Z"}`, statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationBody, pointer: "", code: "invalid"}, {name: "hiding an organization", method: http.MethodPut, path: privacyHiddenPath + "/" + privacyOrganizationID, statusCode: http.StatusNotImplemented}, {name: "hiding a malformed identifier", method: http.MethodPut, path: privacyHiddenPath + "/not-a-uuid", statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid"}, {name: "lifting a hiding", method: http.MethodDelete, path: privacyHiddenPath + "/" + privacyOrganizationID, statusCode: http.StatusNotImplemented}, {name: "lifting a malformed identifier", method: http.MethodDelete, path: privacyHiddenPath + "/not-a-uuid", statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid"}, {name: "the settings", method: http.MethodGet, path: privacyBasePath, statusCode: http.StatusNotImplemented}, {name: "the preview", method: http.MethodGet, path: privacyBasePath + "/preview", statusCode: http.StatusNotImplemented}, {name: "the hidden list", method: http.MethodGet, path: privacyHiddenPath + "?limit=50", statusCode: http.StatusNotImplemented}, {name: "a hidden list limit over 100", method: http.MethodGet, path: privacyHiddenPath + "?limit=101", statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid"}, {name: "the history", method: http.MethodGet, path: privacyBasePath + "/history", statusCode: http.StatusNotImplemented}, {name: "a malformed history cursor", method: http.MethodGet, path: privacyBasePath + "/history?cursor=not%20a%20cursor", statusCode: http.StatusBadRequest, location: api.ProblemFieldLocationQuery, pointer: "/cursor", code: "invalid"}, {name: "the access history", method: http.MethodGet, path: privacyBasePath + "/access-history", statusCode: http.StatusNotImplemented}, } { t.Run(test.name, func(t *testing.T) { response := serveIdentityRequest(t, newPrivacyRouter(t), identityRequest{method: test.method, path: test.path, body: test.body, headers: session}) 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: test.location, 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) }) } } // Nothing here is reachable without a session: the deny-all security of the // scaffold answers 401 for every operation, with or without a cookie. func TestPrivacyAccessBeforeImplementation(t *testing.T) { session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken} for _, test := range []identityRequest{ {method: http.MethodGet, path: privacyBasePath}, {method: http.MethodGet, path: privacyBasePath + "/preview"}, {method: http.MethodGet, path: privacyBasePath + "/history", headers: session}, {method: http.MethodGet, path: privacyBasePath + "/access-history"}, {method: http.MethodGet, path: privacyHiddenPath}, {method: http.MethodPut, path: privacyPublicationPath, body: `{"expected_version":0,"state":"closed","fields":[]}`, headers: session}, {method: http.MethodPut, path: privacySearchStatusPath, body: `{"expected_version":0,"value":"not_looking"}`, headers: session}, {method: http.MethodPut, path: privacyHiddenPath + "/" + privacyOrganizationID, headers: session}, {method: http.MethodDelete, path: privacyHiddenPath + "/" + privacyOrganizationID, 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) }) } }