package httpadapter import ( "slices" "strings" "testing" "github.com/ogen-go/ogen" "lincodex/backend/internal/adapter/primary/http/api" ) const ( evidenceOwnPath = "/api/v1/me/evidence" evidenceOrganizationPath = "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence" ) // evidenceSchemas are the schemas of the evidence family. var evidenceSchemas = []string{ "EvidenceKind", "EvidenceSourceType", "EvidenceAttribution", "EvidenceTrustLevel", "EvidenceVisibility", "EvidenceSkillCode", "EvidenceBasis", "EvidenceCalibrationStatus", "EvidenceResult", "EvidenceSource", "EvidenceFact", "EvidenceFactList", "OrganizationEvidenceFact", "OrganizationEvidence", } // rawAssessmentPropertyNames are properties that carry raw answers, failures, // per-item data, or anti-cheat data. No organization operation and no evidence // operation may declare one. var rawAssessmentPropertyNames = []string{ "answer", "answers", "answer_key", "reference_answer", "raw_score", "basic_score", "pass_points", "pass_mark_basis_points", "scored_items", "uncertainty", "weak_domains", "practice_results", "practice", "signals", "events", "item_instance_id", "items_answered", "seed", "variant", "hidden_checks", "category_decision", "next_step", "not_determined_reason", "band", "reasons", "attempt_id", } // Both evidence operations follow the project conventions: the session cookie // alone (they only read), the unauthenticated and forbidden problems, no-store // on the success, and the shared cursor parameters for the paged list. No new // problem code is needed. func TestEvidenceOperationsFollowTheConventions(t *testing.T) { spec := parsePublicContract(t) own := operationByID(t, spec, "ListMyEvidence") organization := operationByID(t, spec, "GetOrganizationCandidateEvidence") for _, operation := range []*ogen.Operation{own, organization} { if !slices.Contains(operation.Tags, "evidence") { t.Errorf("%s is not in the evidence tag", operation.OperationID) } if !hasSecurity(operation, "sessionCookie") || hasSecurity(operation, "sessionCsrf") { t.Errorf("%s security = %v, want the session cookie without a CSRF token for a read", operation.OperationID, operation.Security) } for _, status := range []string{"400", "401", "403", "default"} { if operation.Responses[status] == nil { t.Errorf("%s does not declare %s", operation.OperationID, status) } } 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.RequestBody != nil { t.Errorf("%s takes a body, but it only reads", operation.OperationID) } } names := []string{} for _, parameter := range own.Parameters { names = append(names, parameterName(parameter)) } if !slices.Contains(names, "PageLimit") || !slices.Contains(names, "PageCursor") { t.Errorf("ListMyEvidence parameters = %v, want the shared PageLimit and PageCursor", names) } names = names[:0] for _, parameter := range organization.Parameters { names = append(names, parameterName(parameter)) } if !slices.Equal(names, []string{"OrganizationId", "CandidateHandle"}) { t.Errorf("GetOrganizationCandidateEvidence parameters = %v, want the organization and the candidate handle", names) } // The organization read answers an unknown, hidden, unpublished, and // suppressed card alike, and the quota with Retry-After. if organization.Responses["404"] == nil || organization.Responses["429"] == nil { t.Error("GetOrganizationCandidateEvidence must declare 404 and 429") } if own.Responses["404"] != nil { t.Error("ListMyEvidence declares 404: a list has no missing resource") } codes := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProblemCode"})) for _, code := range []string{"validation_failed", "unauthenticated", "forbidden", "not_found", "rate_limited"} { if !slices.Contains(codes, code) { t.Errorf("ProblemCode has no %s", code) } } if spec.Paths[evidenceOwnPath] == nil || spec.Paths[evidenceOrganizationPath] == nil { t.Errorf("the contract lacks the paths %s and %s", evidenceOwnPath, evidenceOrganizationPath) } } // A claim and a measurement are different kinds with different trust ranges, // every evidence object is closed, and the organization fact has no identifier // and no exact time. func TestEvidenceSchemasAreClosedAndSeparateClaimsFromMeasurements(t *testing.T) { spec := parsePublicContract(t) if got := enumValues(t, spec.Components.Schemas["EvidenceKind"]); !slices.Equal(got, []string{"claim", "measurement"}) { t.Errorf("EvidenceKind = %v, want claim and measurement", got) } trust := spec.Components.Schemas["EvidenceTrustLevel"] if string(trust.Minimum) != "0" || string(trust.Maximum) != "3" { t.Errorf("EvidenceTrustLevel range = %s..%s, want 0..3", trust.Minimum, trust.Maximum) } for _, pair := range []struct { name string want []string }{ {"EvidenceFact", []string{"attribution", "id", "kind", "occurred_at", "result", "skills", "source", "trust", "visibility"}}, {"EvidenceSource", []string{"event_id", "result_id", "type"}}, {"EvidenceResult", []string{"basis", "calibration_status", "grade"}}, {"EvidenceFactList", []string{"items", "page"}}, {"OrganizationEvidenceFact", []string{"basis", "calibration_status", "grade", "observed_year", "skill", "trust"}}, {"OrganizationEvidence", []string{"items"}}, } { 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 properties", pair.name) } if required := slices.Sorted(slices.Values(schema.Required)); !slices.Equal(required, pair.want) { t.Errorf("%s requires %v, want every property %v", pair.name, required, pair.want) } } assertNoJSONFields(t, api.OrganizationEvidenceFact{}, []string{"id", "event_id", "result_id", "occurred_at", "visibility", "candidate_id", "user_id"}) for _, property := range spec.Components.Schemas["EvidenceFact"].Properties { if property.Name == "skills" && (!property.Schema.UniqueItems || property.Schema.MinItems == nil || *property.Schema.MinItems != 1) { t.Errorf("EvidenceFact.skills must be a non-empty set: one event with several tags is one fact") } } // An organization reads at most one fact for each category of the card. items := spec.Components.Schemas["OrganizationEvidence"].Properties for _, property := range items { if property.Name == "items" && (property.Schema.MaxItems == nil || *property.Schema.MaxItems != 9) { t.Errorf("OrganizationEvidence.items maxItems = %v, want 9: one fact for each of the nine possible categories", property.Schema.MaxItems) } } } // No organization operation reaches raw answers, failures, per-item data, or // anti-cheat data, and neither does the evidence of the candidate. The walk // covers every request body, response, parameter, and header through all // references, so a new organization operation cannot reach an assessment // result, attempt, or signal schema by reuse. func TestNoOrganizationOperationReachesRawAssessmentData(t *testing.T) { spec := parsePublicContract(t) index := componentsIndex(t, spec) walked := 0 for path, item := range spec.Paths { organizationOperation := strings.HasPrefix(path, "/api/v1/organizations") if !organizationOperation && path != evidenceOwnPath { continue } walked++ value := mustJSONValue(t, item) properties := map[string]bool{} declaredPropertyNames(value, properties) for schemaName := range reachableSchemas(index, value) { if strings.HasPrefix(schemaName, "Assessment") || strings.HasPrefix(schemaName, "Practice") || strings.HasPrefix(schemaName, "ItemContent") || strings.Contains(schemaName, "Signal") || strings.Contains(schemaName, "Review") { t.Errorf("%s reaches the assessment schema %s", path, schemaName) } declaredPropertyNames(mustJSONValue(t, index["#/components/schemas/"+schemaName]), properties) } if path == evidenceOwnPath && !properties["skills"] { t.Errorf("%s declares no skills property: the walk did not reach the schemas", path) } for _, raw := range rawAssessmentPropertyNames { if properties[raw] { t.Errorf("%s declares the raw assessment property %q", path, raw) } } } if walked < 10 { t.Fatalf("walked only %d organization and evidence paths, want all of them", walked) } } // The walk is not vacuous: it reaches the evidence family from both // operations, and the family keeps the failure outcomes out of its enums. func TestEvidenceWalkReachesTheEvidenceFamily(t *testing.T) { spec := parsePublicContract(t) index := componentsIndex(t, spec) for operationID, want := range map[string][]string{ "ListMyEvidence": {"EvidenceFact", "EvidenceSource", "EvidenceResult", "EvidenceTrustLevel"}, "GetOrganizationCandidateEvidence": {"OrganizationEvidenceFact", "EvidenceSkillCode", "EvidenceTrustLevel"}, } { reached := reachableSchemas(index, mustJSONValue(t, operationByID(t, spec, operationID))) for _, name := range want { if !reached[name] { t.Errorf("%s does not reach %s", operationID, name) } } } enums := map[string]bool{} for _, name := range evidenceSchemas { declaredEnumValues(mustJSONValue(t, spec.Components.Schemas[name]), enums) } for _, failure := range []string{"not_confirmed", "not_determined", "failed", "expired", "demonstration", "demo_express", "review", "attention"} { if enums[failure] { t.Errorf("the evidence family declares the enum value %q", failure) } } }