//go:build integration package integration_test import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "slices" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" v1 "lincodex/backend/internal/adapter/primary/http/v1" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/anonymousprofile" "lincodex/backend/internal/usecase/assessment" "lincodex/backend/internal/usecase/candidateprivacy" "lincodex/backend/internal/usecase/candidateview" "lincodex/backend/internal/usecase/companyquota" "lincodex/backend/internal/usecase/evidence" ) const ( skillEvidenceHTTPTimeout = 10 * time.Minute // skillEvidenceMigrationVersion creates the skill evidence tables. skillEvidenceMigrationVersion = 35 // evidenceCohortSize is the smallest visible group of identical cards, so // the cohort rules of the card leave the category in place. evidenceCohortSize = 5 ) type skillEvidenceHarness struct { *assessmentAttemptHTTPHarness key domain.CandidateViewPseudonymKey } func newSkillEvidenceHarness(ctx context.Context, t *testing.T, env *testEnvironment) *skillEvidenceHarness { t.Helper() var key domain.CandidateViewPseudonymKey harness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, env, assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}, func(parts assessmentHarnessParts) []v1.HandlerOption { var err error if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil { t.Fatalf("CandidateViewPseudonymKey() error = %v", err) } projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now) quota := companyquota.NewService(parts.clock.Now) views, err := candidateview.NewService(candidateview.Dependencies{ Transactor: parts.transactor, Projector: projector, PseudonymKey: key, Clock: parts.clock.Now, Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { return quota.ReserveCardView(ctx, unit, organization, candidateID) }, }) if err != nil { t.Fatalf("candidateview.NewService() error = %v", err) } settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now}) if err != nil { t.Fatalf("candidateprivacy.NewService() error = %v", err) } evidenceService, err := evidence.NewService(evidence.Dependencies{ Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection, }) if err != nil { t.Fatalf("evidence.NewService() error = %v", err) } return []v1.HandlerOption{ v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)), v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)), } }) return &skillEvidenceHarness{assessmentAttemptHTTPHarness: harness, key: key} } // evidenceFactBody is the owner's fact as the contract declares it. type evidenceFactBody struct { ID uuid.UUID `json:"id"` Kind string `json:"kind"` Source struct { Type string `json:"type"` EventID uuid.UUID `json:"event_id"` ResultID uuid.UUID `json:"result_id"` } `json:"source"` Skills []string `json:"skills"` Result struct { Grade string `json:"grade"` Basis string `json:"basis"` CalibrationStatus string `json:"calibration_status"` } `json:"result"` Attribution string `json:"attribution"` Trust int `json:"trust"` OccurredAt time.Time `json:"occurred_at"` Visibility string `json:"visibility"` } type evidencePageBody struct { Items []evidenceFactBody `json:"items"` Page struct { HasMore bool `json:"has_more"` NextCursor *string `json:"next_cursor"` } `json:"page"` } func TestSkillEvidenceOverHTTP(t *testing.T) { env := bootstrap(t, postgresService, redisService) ctx, cancel := context.WithTimeout(t.Context(), skillEvidenceHTTPTimeout) defer cancel() databaseURL := env.createIsolatedDatabase(ctx, t) applyMigrations(ctx, t, databaseURL) isolatedEnv := *env isolatedEnv.Config.DatabaseURL = databaseURL harness := newSkillEvidenceHarness(ctx, t, &isolatedEnv) bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV2(), true) threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark)) client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx} transactor := postgresadapter.NewTransactor(harness.pool) now := time.Now().UTC().Truncate(time.Microsecond) identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identity, transactor: transactor, now: now} privacy := candidatePrivacyFixture{ ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now, } get := func(who categoryHTTPCandidate, path string) *httptest.ResponseRecorder { t.Helper() return harness.request(t, http.MethodGet, path, "", "", who.cookie, "", client.remote()) } readOwn := func(who categoryHTTPCandidate, query string) (evidencePageBody, *httptest.ResponseRecorder) { t.Helper() response := get(who, "/api/v1/me/evidence"+query) var page evidencePageBody if response.Code == http.StatusOK { if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { t.Fatalf("decode own evidence: %v\n%s", err, response.Body.String()) } } return page, response } countRows := func(query string, args ...any) int { t.Helper() var count int if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { t.Fatalf("count rows: %v", err) } return count } passingIntern := func(who categoryHTTPCandidate) attemptRun { t.Helper() run := client.run(t, who, "backend", "intern", func(int) int { return threshold }) if run.result["outcome"] != "confirmed" || decisionOf(t, run.result)["status"] != "assigned" { t.Fatalf("passing run of %s = %v, want a confirmed assigned category", who.email, run.result) } return run } // The cohort: five candidates with the same published category. A card is // shown only inside a group of five identical cards. cohort := make([]categoryHTTPCandidate, 0, evidenceCohortSize) runs := make(map[uuid.UUID]attemptRun, evidenceCohortSize) for index := range evidenceCohortSize { member := client.candidate(t, fmt.Sprintf("evidence-cohort-%d@example.test", index)) runs[member.id] = passingIntern(member) cohort = append(cohort, member) } target := cohort[0] targetRun := runs[target.id] consents := make(map[uuid.UUID]uuid.UUID, len(cohort)) for _, member := range cohort { c2 := privacy.grant(t, member.id, domain.ConsentPurposePublication, privacyC2Version, now) privacy.publish(t, member.id, c2.ID(), 0, domain.CardFieldCategories) consents[member.id] = c2.ID() } failed := client.candidate(t, "evidence-failed@example.test") failedRun := client.run(t, failed, "backend", "intern", func(int) int { return threshold - 1 }) if failedRun.result["outcome"] != "not_confirmed" { t.Fatalf("failing run = %v, want not_confirmed", failedRun.result["outcome"]) } employerAccount := client.employer(t, "evidence-employer@example.test") foreignAccount := client.employer(t, "evidence-foreign@example.test") organizationA := organizations.create(t, domain.User{ID: employerAccount.id}, organizations.completeProfile(t, "Evidence organization A"), now) organizationB := organizations.create(t, domain.User{ID: employerAccount.id}, organizations.completeProfile(t, "Evidence organization B"), now) foreignOrganization := organizations.create(t, domain.User{ID: foreignAccount.id}, organizations.completeProfile(t, "Evidence foreign organization"), now) // The policy and the organizations take effect when they are stored, which // is after the clock of the harness was read, and the card-view quota reads // both at the application time. harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond)) organizationPath := func(organizationID uuid.UUID, handle string) string { return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s/evidence", organizationID, handle) } aliasIn := func(organizationID, candidateID uuid.UUID) string { t.Helper() alias, err := harness.key.ForOrganization(organizationID, candidateID) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } return alias } organizationFacts := func(organizationID, candidateID uuid.UUID, categories ...domain.CandidateViewCategory) []domain.EvidenceOrganizationFact { t.Helper() var facts []domain.EvidenceOrganizationFact err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { var err error facts, err = unit.Evidence().ListOrganizationFacts(ctx, organizationID, candidateID, categories) return err }) if err != nil { t.Fatalf("ListOrganizationFacts() error = %v", err) } return facts } category := func(specialization domain.SpecializationCode, grade domain.GradeCode) domain.CandidateViewCategory { return domain.CandidateViewCategory{Specialization: specialization, Grade: grade, Strength: domain.CandidateViewStrengthStandard} } // A source records a fact together with its tags in one transaction, the // only time tags can join a fact. The helper rebuilds the projection from // the stored results and adds the tags to the fact of one event, as such a // source would. rebuildWithTags := func(eventID uuid.UUID, skills ...string) { t.Helper() tx, err := harness.pool.Begin(ctx) if err != nil { t.Fatalf("begin the rebuild: %v", err) } defer func() { _ = tx.Rollback(ctx) }() if _, err := tx.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil { t.Fatalf("empty the projection: %v", err) } if _, err := tx.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil { t.Fatalf("project the stored results: %v", err) } for _, skill := range skills { if _, err := tx.Exec(ctx, `INSERT INTO skill_evidence_skills (fact_id, skill_code) SELECT id, $2 FROM skill_evidence_facts WHERE event_id = $1`, eventID, skill); err != nil { t.Fatalf("tag the event with %s: %v", skill, err) } } if err := tx.Commit(ctx); err != nil { t.Fatalf("commit the rebuild: %v", err) } } t.Run("a confirmed assessment gives one fact tied to its result with trust 1", func(t *testing.T) { if domain.EvidenceTrustOnlineUnconfirmed != 1 { t.Fatalf("the trust of an online result without identity confirmation = %d, want 1", domain.EvidenceTrustOnlineUnconfirmed) } page, response := readOwn(target, "") if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || len(page.Items) != 1 || page.Page.HasMore || page.Page.NextCursor != nil { t.Fatalf("own evidence = %d %q %s, want one no-store fact", response.Code, response.Header().Get("Cache-Control"), response.Body.String()) } fact := page.Items[0] decidedAt, err := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string)) if err != nil { t.Fatalf("parse decided_at: %v", err) } if fact.ID == uuid.Nil || fact.Kind != "measurement" || fact.Source.Type != "assessment_result" || fact.Source.EventID != targetRun.id || fact.Source.ResultID != targetRun.id || !slices.Equal(fact.Skills, []string{"backend"}) || fact.Attribution != "personal" || fact.Trust != int(domain.EvidenceTrustOnlineUnconfirmed) || fact.Visibility != "visible" || fact.Result.Grade != "intern" || fact.Result.Basis != "synthetic_demo" || fact.Result.CalibrationStatus != "uncalibrated" || !fact.OccurredAt.Equal(decidedAt) { t.Fatalf("fact = %+v, want a visible online measurement of the intern result %s decided at %s", fact, targetRun.id, decidedAt) } // The same result is readable by its identifier. if status, _ := client.call(t, target, http.MethodGet, "/api/v1/me/assessment-attempts/"+fact.Source.ResultID.String()+"/result", "", ""); status != http.StatusOK { t.Fatalf("result named by the fact = %d, want 200", status) } for _, leak := range []string{"answer", "score", "points", "reference", "seed", "item_", "signal", "review", "not_confirmed"} { if strings.Contains(strings.ToLower(response.Body.String()), leak) { t.Fatalf("own evidence exposes %q: %s", leak, response.Body.String()) } } stored := countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1 AND trust = 1 AND kind = 'measurement' AND result_id = $2`, target.id, targetRun.id) if stored != 1 { t.Fatalf("stored facts of the result = %d, want 1", stored) } // Every owner reads only their own facts; a failed attempt gives none. for _, member := range cohort[1:] { memberPage, _ := readOwn(member, "") if len(memberPage.Items) != 1 || memberPage.Items[0].ID == fact.ID || memberPage.Items[0].Source.ResultID != runs[member.id].id { t.Fatalf("evidence of %s = %+v, want only their own fact", member.email, memberPage.Items) } } if failedPage, response := readOwn(failed, ""); response.Code != http.StatusOK || len(failedPage.Items) != 0 || failedPage.Page.HasMore { t.Fatalf("evidence after a failed attempt = %d %s, want no fact", response.Code, response.Body.String()) } if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, failed.id) != 0 { t.Fatal("a failed attempt stored a fact") } // Access: a guest, an employer, and a malformed request are refused. if response := get(categoryHTTPCandidate{}, "/api/v1/me/evidence"); response.Code != http.StatusUnauthorized { t.Fatalf("evidence without a session = %d, want 401", response.Code) } if response := get(employerAccount, "/api/v1/me/evidence"); response.Code != http.StatusForbidden { t.Fatalf("evidence of an employer account = %d, want 403", response.Code) } }) t.Run("several tags of one event stay one independent fact", func(t *testing.T) { rebuildWithTags(targetRun.id, "go", "postgresql") page, response := readOwn(target, "") if len(page.Items) != 1 || !slices.Equal(page.Items[0].Skills, []string{"backend", "go", "postgresql"}) { t.Fatalf("evidence after two more tags = %s, want a single fact with three tags", response.Body.String()) } fact := page.Items[0] if facts, events := countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, target.id), countRows(`SELECT count(DISTINCT event_id) FROM skill_evidence_facts WHERE candidate_id = $1`, target.id); facts != 1 || events != 1 { t.Fatalf("independent facts = %d over %d events, want 1 over 1", facts, events) } // One event is one fact whatever its tags, and the tags are a closed set. _, err := harness.pool.Exec(ctx, ` INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`, fact.ID) assertPgError(t, "second fact for one event", err, "23505", "skill_evidence_facts_event_key") // A stored fact is sealed: a later transaction cannot add a tag to it. _, err = harness.pool.Exec(ctx, `INSERT INTO skill_evidence_skills (fact_id, skill_code) VALUES ($1, 'qa')`, fact.ID) assertPgError(t, "tag added to a stored fact", err, "23000", "skill_evidence_skills_fact_sealed") _, err = harness.pool.Exec(ctx, `UPDATE skill_evidence_skills SET skill_code = 'qa' WHERE fact_id = $1 AND skill_code = 'go'`, fact.ID) assertPgError(t, "rewrite of a tag", err, "23000", "skill_evidence_skills_immutable") _, err = harness.pool.Exec(ctx, `DELETE FROM skill_evidence_skills WHERE fact_id = $1`, fact.ID) assertPgError(t, "removal of tags", err, "23000", "skill_evidence_skills_immutable") // Inside the creating transaction the tags are still a set from the closed list. tx, err := harness.pool.Begin(ctx) if err != nil { t.Fatalf("begin the tag check: %v", err) } defer func() { _ = tx.Rollback(ctx) }() if _, err := tx.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil { t.Fatalf("empty the projection: %v", err) } if _, err := tx.Exec(ctx, `SELECT skill_evidence_project_assessment_result($1)`, targetRun.id); err != nil { t.Fatalf("project the result: %v", err) } if _, err := tx.Exec(ctx, `SAVEPOINT repeated`); err != nil { t.Fatalf("savepoint: %v", err) } _, err = tx.Exec(ctx, `INSERT INTO skill_evidence_skills SELECT id, 'backend' FROM skill_evidence_facts`) assertPgError(t, "repeated tag", err, "23505", "skill_evidence_skills_pkey") if _, err := tx.Exec(ctx, `ROLLBACK TO SAVEPOINT repeated`); err != nil { t.Fatalf("roll back to the savepoint: %v", err) } _, err = tx.Exec(ctx, `INSERT INTO skill_evidence_skills SELECT id, 'rate-limiting' FROM skill_evidence_facts`) assertPgError(t, "tag outside the closed set", err, "23514", "skill_evidence_skills_code") }) t.Run("a stored fact keeps its result and trust and only its visibility changes", func(t *testing.T) { page, _ := readOwn(target, "") factID := page.Items[0].ID for name, test := range map[string]struct { sql, constraint string code string }{ "trust": {`UPDATE skill_evidence_facts SET trust = 2 WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, "grade": {`UPDATE skill_evidence_facts SET grade = 'senior' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, "attribution": {`UPDATE skill_evidence_facts SET attribution = 'team_role' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, "kind": {`UPDATE skill_evidence_facts SET kind = 'claim' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, "removal": {`DELETE FROM skill_evidence_facts WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, "bad hiding": {`UPDATE skill_evidence_facts SET visibility = 'public' WHERE id = $1`, "skill_evidence_facts_visibility", "23514"}, } { _, err := harness.pool.Exec(ctx, test.sql, factID) assertPgError(t, name, err, test.code, test.constraint) } // A fact is a measurement of level 1 to 3 or a claim of level 0, never both. for name, statement := range map[string]string{ "claim above level 0": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, 'claim', source_type, event_id, result_id, attribution, 1, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`, "measurement at level 0": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, 0, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`, "online result in person": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, 3, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`, } { if _, err := harness.pool.Exec(ctx, statement, factID); err == nil { t.Errorf("%s was stored", name) } } if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE id = $1`, factID); err != nil { t.Fatalf("hide the fact: %v", err) } hiddenPage, _ := readOwn(target, "") if len(hiddenPage.Items) != 1 || hiddenPage.Items[0].Visibility != "hidden" || hiddenPage.Items[0].Trust != 1 { t.Fatalf("own evidence after hiding = %+v, want the same fact with visibility hidden", hiddenPage.Items) } if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE id = $1`, factID); err != nil { t.Fatalf("show the fact again: %v", err) } }) t.Run("an express run creates no qualifying evidence, category, or cohort entry", func(t *testing.T) { expressOnly := client.candidate(t, "evidence-express@example.test") beforeBody := readOwnBody(t, get, target) beforeFacts := countRows(`SELECT count(*) FROM skill_evidence_facts`) beforeCategories := countStoredCategories(t, ctx, harness.pool, target.id) expressIDs := make([]uuid.UUID, 0, 2) for _, who := range []categoryHTTPCandidate{target, expressOnly} { expressIDs = append(expressIDs, runPerfectExpress(t, ctx, client, harness.assessmentAttemptHTTPHarness, who)) } if afterBody := readOwnBody(t, get, target); afterBody != beforeBody { t.Fatalf("evidence changed after an express run:\n%s\n%s", beforeBody, afterBody) } if page, _ := readOwn(expressOnly, ""); len(page.Items) != 0 { t.Fatalf("evidence after express only = %+v, want none", page.Items) } if afterFacts := countRows(`SELECT count(*) FROM skill_evidence_facts`); afterFacts != beforeFacts { t.Fatalf("facts after express = %d, want the %d before", afterFacts, beforeFacts) } if countStoredCategories(t, ctx, harness.pool, target.id) != beforeCategories || countStoredCategories(t, ctx, harness.pool, expressOnly.id) != 0 { t.Fatal("an express run changed a category") } // The database also refuses a fact whose source is an express result or // a failed attempt, even through a direct write. for name, source := range map[string]struct{ owner, attempt uuid.UUID }{ "express result of the owner": {target.id, expressIDs[0]}, "express result of an outsider": {expressOnly.id, expressIDs[1]}, "failed attempt": {failed.id, failedRun.id}, } { _, err := harness.pool.Exec(ctx, ` INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) VALUES ($1, 'measurement', 'assessment_result', $2, $2, 'personal', 1, 'intern', 'synthetic_demo', 'uncalibrated', now())`, source.owner, source.attempt) assertPgError(t, name, err, "23514", "skill_evidence_facts_source_result") } // Neither run enters the card cohort as a confirmed category. consent := privacy.grant(t, expressOnly.id, domain.ConsentPurposePublication, privacyC2Version, now) privacy.publish(t, expressOnly.id, consent.ID(), 0, domain.CardFieldCategories) sources, err := postgresadapter.NewPrivacyCohortStore(harness.pool).ListVisibleCandidateViewSources(ctx, organizationA.ID()) if err != nil { t.Fatalf("ListVisibleCandidateViewSources() error = %v", err) } for _, source := range sources { categories := source.Input("cv1_"+strings.Repeat("A", 43), now).ConfirmedCategories if source.CandidateID() == expressOnly.id && len(categories) != 0 { t.Fatalf("express-only candidate has categories %v in the cohort", categories) } } // Withdraw the express-only publication so that it does not join the cohort of the target. privacy.revokeC2(t, expressOnly.id, now.Add(time.Second)) }) t.Run("the list pages by a cursor bound to its owner", func(t *testing.T) { pager := client.candidate(t, "evidence-pager@example.test") first := passingIntern(pager) moveFinishedAttemptBack(t, ctx, harness.pool, first.id, categoryHTTPPromotionGap) second := client.run(t, pager, "backend", "junior", func(int) int { return threshold }) if second.result["outcome"] != "confirmed" { t.Fatalf("promotion run = %v, want confirmed", second.result["outcome"]) } firstPage, response := readOwn(pager, "?limit=1") if response.Code != http.StatusOK || len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || firstPage.Items[0].Source.ResultID != second.id || firstPage.Items[0].Result.Grade != "junior" { t.Fatalf("first page = %d %s, want the junior fact and a cursor", response.Code, response.Body.String()) } secondPage, response := readOwn(pager, "?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor)) if response.Code != http.StatusOK || len(secondPage.Items) != 1 || secondPage.Page.HasMore || secondPage.Page.NextCursor != nil || secondPage.Items[0].Source.ResultID != first.id || secondPage.Items[0].Result.Grade != "intern" { t.Fatalf("second page = %d %s, want the intern fact and no more", response.Code, response.Body.String()) } if firstPage.Items[0].ID == secondPage.Items[0].ID { t.Fatal("two events produced one fact") } for _, query := range []string{"?cursor=" + url.QueryEscape(*firstPage.Page.NextCursor), "?limit=0", "?limit=101", "?cursor=not-a-cursor"} { who := pager if strings.HasPrefix(query, "?cursor="+url.QueryEscape(*firstPage.Page.NextCursor)) { who = target // the cursor belongs to the pager } if response := get(who, "/api/v1/me/evidence"+query); response.Code != http.StatusBadRequest { t.Fatalf("evidence query %q = %d %s, want 400", query, response.Code, response.Body.String()) } } }) t.Run("the preview shows the one fact for each category that an organization would read", func(t *testing.T) { type previewBody struct { Card json.RawMessage `json:"card"` Evidence *struct { Items []struct { Skill string `json:"skill"` Grade string `json:"grade"` Trust int `json:"trust"` ObservedYear int `json:"observed_year"` Basis string `json:"basis"` Calibration string `json:"calibration_status"` } `json:"items"` } `json:"evidence"` } preview := func(who categoryHTTPCandidate) previewBody { t.Helper() response := get(who, "/api/v1/me/privacy/preview") var body previewBody if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || json.Unmarshal(response.Body.Bytes(), &body) != nil { t.Fatalf("preview of %s = %d %q %s", who.email, response.Code, response.Header().Get("Cache-Control"), response.Body.String()) } return body } decidedAt, _ := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string)) body := preview(target) if body.Evidence == nil || len(body.Evidence.Items) != 1 || body.Evidence.Items[0].Skill != "backend" || body.Evidence.Items[0].Grade != "intern" || body.Evidence.Items[0].Trust != 1 || body.Evidence.Items[0].Basis != "synthetic_demo" || body.Evidence.Items[0].Calibration != "uncalibrated" || body.Evidence.Items[0].ObservedYear != decidedAt.UTC().Year() { t.Fatalf("preview evidence = %+v, want the backend intern fact of %d", body.Evidence, decidedAt.UTC().Year()) } // A closed profile has no card and no evidence section. if closed := preview(failed); string(closed.Card) != "null" || closed.Evidence != nil { t.Fatalf("preview of a closed profile = card %s, evidence %+v, want both null", closed.Card, closed.Evidence) } // A candidate with a lower and a higher passed grade: one fact, the one // that supports the confirmed grade, whichever way it is asked for. pagerAccount := client.candidate(t, "evidence-supporting@example.test") lower := passingIntern(pagerAccount) moveFinishedAttemptBack(t, ctx, harness.pool, lower.id, categoryHTTPPromotionGap) higher := client.run(t, pagerAccount, "backend", "junior", func(int) int { return threshold }) if higher.result["outcome"] != "confirmed" { t.Fatalf("promotion run = %v, want confirmed", higher.result["outcome"]) } consent := privacy.grant(t, pagerAccount.id, domain.ConsentPurposePublication, privacyC2Version, now) privacy.publish(t, pagerAccount.id, consent.ID(), 0, domain.CardFieldCategories) body = preview(pagerAccount) if body.Evidence == nil || len(body.Evidence.Items) != 1 || body.Evidence.Items[0].Grade != "junior" { t.Fatalf("preview evidence with two passed grades = %+v, want only the junior fact", body.Evidence) } if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeJunior)); len(facts) != 1 || facts[0].Input().Grade != domain.GradeJunior { t.Fatalf("organization evidence for the junior category = %+v, want the junior fact", facts) } if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeIntern)); len(facts) != 1 || facts[0].Input().Grade != domain.GradeIntern { t.Fatalf("organization evidence for the intern category = %+v, want the intern fact", facts) } // A hidden fact leaves the preview as it leaves the organization. if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE candidate_id = $1`, pagerAccount.id); err != nil { t.Fatalf("hide the facts: %v", err) } if body = preview(pagerAccount); body.Evidence == nil || len(body.Evidence.Items) != 0 { t.Fatalf("preview evidence of hidden facts = %+v, want an empty list", body.Evidence) } if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeJunior)); len(facts) != 0 { t.Fatalf("organization evidence of hidden facts = %+v, want none", facts) } if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE candidate_id = $1`, pagerAccount.id); err != nil { t.Fatalf("show the facts: %v", err) } }) t.Run("an organization reads the permitted projection only while the card is visible", func(t *testing.T) { handle := aliasIn(organizationA.ID(), target.id) path := organizationPath(organizationA.ID(), handle) response := get(employerAccount, path) if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" { t.Fatalf("permitted projection = %d %q %s\n%s", response.Code, response.Header().Get("Cache-Control"), response.Body.String(), harness.logs.String()) } decidedAt, _ := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string)) // One fact for the one category of the card, with the skill, the grade, // the trust level, and the year only; the other tags stay with the candidate. wantBody := fmt.Sprintf(`{"items":[{"skill":"backend","grade":"intern","trust":1,"basis":"synthetic_demo","calibration_status":"uncalibrated","observed_year":%d}]}`, decidedAt.UTC().Year()) if strings.TrimSpace(response.Body.String()) != wantBody { t.Fatalf("permitted projection = %s, want %s", response.Body.String(), wantBody) } for _, private := range []string{target.id.String(), targetRun.id.String(), "event_id", "result_id", "occurred_at", "observed_month", "visibility", "answer", "score", "points", "signal", "review", "not_confirmed", `"id"`} { if strings.Contains(response.Body.String(), private) { t.Fatalf("permitted projection exposes %q: %s", private, response.Body.String()) } } // The read is a card view: the quota is used once and the candidate sees the access. for range 2 { if again := get(employerAccount, path); again.Code != http.StatusOK { t.Fatalf("repeated projection = %d %s", again.Code, again.Body.String()) } } if usage := countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, target.id, organizationA.ID()); usage != 1 { t.Fatalf("card-view quota usage = %d, want one distinct card", usage) } if audits := countRows(`SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' AND field_codes = ARRAY['categories']::text[]`, target.id, organizationA.ID()); audits != 3 { t.Fatalf("access records of the categories field = %d, want 3", audits) } // Access: the roles and the scope of the handle. if response := get(target, path); response.Code != http.StatusForbidden { t.Fatalf("candidate account reads the projection = %d, want 403", response.Code) } if response := get(categoryHTTPCandidate{}, path); response.Code != http.StatusUnauthorized { t.Fatalf("guest reads the projection = %d, want 401", response.Code) } for name, other := range map[string]string{ "other member's organization": organizationPath(foreignOrganization.ID(), handle), "unknown organization": organizationPath(uuid.New(), handle), "alias of another organization": organizationPath(organizationB.ID(), handle), "unknown alias": organizationPath(organizationA.ID(), "cv1_"+strings.Repeat("A", 43)), } { if response := get(employerAccount, other); response.Code != http.StatusNotFound { t.Fatalf("%s = %d %s, want 404", name, response.Code, response.Body.String()) } } if response := get(employerAccount, organizationPath(organizationA.ID(), "candidate")); response.Code != http.StatusBadRequest { t.Fatalf("malformed handle = %d, want 400", response.Code) } if response := get(foreignAccount, path); response.Code != http.StatusNotFound { t.Fatalf("employer without a membership = %d, want 404", response.Code) } // The statement itself rechecks the barrier, whatever the caller did. backendIntern := category(domain.SpecializationBackend, domain.GradeIntern) if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 1 || facts[0].Input() != (domain.EvidenceOrganizationFactInput{ Skill: "backend", Grade: domain.GradeIntern, Trust: 1, Basis: domain.AssessmentCategorySourceSyntheticDemo, CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, ObservedYear: int32(decidedAt.UTC().Year()), }) { t.Fatalf("repository projection = %+v, want the one backend intern fact", facts) } for name, categories := range map[string][]domain.CandidateViewCategory{ "a specialization without a fact": {category(domain.SpecializationQA, domain.GradeIntern)}, "a grade the candidate did not pass": {category(domain.SpecializationBackend, domain.GradeSenior)}, "no category on the card": nil, } { if facts := organizationFacts(organizationA.ID(), target.id, categories...); len(facts) != 0 { t.Fatalf("repository projection for %s = %+v, want none", name, facts) } } if facts := organizationFacts(organizationA.ID(), uuid.New(), backendIntern); len(facts) != 0 { t.Fatalf("repository projection for an unknown candidate = %+v, want none", facts) } // A hidden fact is absent from what the organization reads. if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE candidate_id = $1`, target.id); err != nil { t.Fatalf("hide the fact: %v", err) } hidden := get(employerAccount, path) if hidden.Code != http.StatusOK || strings.TrimSpace(hidden.Body.String()) != `{"items":[]}` { t.Fatalf("projection of a hidden fact = %d %s, want no data", hidden.Code, hidden.Body.String()) } if page, _ := readOwn(target, ""); len(page.Items) != 1 || page.Items[0].Visibility != "hidden" { t.Fatalf("owner after hiding = %+v, want the fact with visibility hidden", page.Items) } if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE candidate_id = $1`, target.id); err != nil { t.Fatalf("show the fact: %v", err) } // A card that does not publish the categories field carries no evidence. publication := privacy.loadPublication(t, target.id) privacy.publish(t, target.id, consents[target.id], publication.Version(), domain.CardFieldStack) if response := get(employerAccount, path); response.Code != http.StatusNotFound { t.Fatalf("projection of a card without categories = %d %s, want 404", response.Code, response.Body.String()) } if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 0 { t.Fatalf("repository projection without the categories field = %+v, want none", facts) } publication = privacy.loadPublication(t, target.id) privacy.publish(t, target.id, consents[target.id], publication.Version(), domain.CardFieldCategories) if response := get(employerAccount, path); response.Code != http.StatusOK { t.Fatalf("projection after publishing the categories again = %d %s", response.Code, response.Body.String()) } // Hiding the organization closes it for that organization only. privacy.hide(t, target.id, organizationA.ID(), now.Add(2*time.Second)) if response := get(employerAccount, path); response.Code != http.StatusNotFound { t.Fatalf("projection for a hidden organization = %d %s, want 404", response.Code, response.Body.String()) } if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 0 { t.Fatalf("repository projection for a hidden organization = %+v, want none", facts) } if facts := organizationFacts(organizationB.ID(), target.id, backendIntern); len(facts) != 1 { t.Fatalf("repository projection for another organization = %+v, want one fact", facts) } if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1`, target.id); err != nil { t.Fatalf("lift the hiding: %v", err) } if response := get(employerAccount, path); response.Code != http.StatusOK { t.Fatalf("projection after the hiding was lifted = %d %s", response.Code, response.Body.String()) } // C2 true, then false: after the revocation there is no data, for any organization. privacy.revokeC2(t, target.id, now.Add(3*time.Second)) for _, organization := range []domain.Organization{organizationA, organizationB} { response := get(employerAccount, organizationPath(organization.ID(), aliasIn(organization.ID(), target.id))) if response.Code != http.StatusNotFound || strings.Contains(response.Body.String(), "measurement") { t.Fatalf("projection after the C2 revocation = %d %s, want 404 without data", response.Code, response.Body.String()) } if facts := organizationFacts(organization.ID(), target.id, backendIntern); len(facts) != 0 { t.Fatalf("repository projection after the C2 revocation = %+v, want none", facts) } } if page, _ := readOwn(target, ""); len(page.Items) != 1 { t.Fatalf("owner evidence after the C2 revocation = %+v, want the fact kept", page.Items) } }) t.Run("deleting the account removes its facts through both cascade paths", func(t *testing.T) { erased := client.candidate(t, "evidence-erased@example.test") run := passingIntern(erased) if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, erased.id) != 1 { t.Fatal("the candidate to erase has no fact") } // The ledger and history guards keep a confirmed account; this fixture // lifts them for one transaction, as the deletion procedure will. The // foreign keys and the triggers of the evidence stay on. tx, err := harness.pool.Begin(ctx) if err != nil { t.Fatalf("begin the erasure: %v", err) } defer func() { _ = tx.Rollback(ctx) }() for _, statement := range []string{ `ALTER TABLE consent_records DISABLE TRIGGER USER`, `ALTER TABLE users DISABLE TRIGGER USER`, } { if _, err := tx.Exec(ctx, statement); err != nil { t.Fatalf("lift the retention guards (%s): %v", statement, err) } } // Both paths lead to the fact: the owner of the fact and the result it names. if _, err := tx.Exec(ctx, `ALTER TABLE assessment_attempt_results DISABLE TRIGGER assessment_attempt_result_refuse_mutation`); err != nil { t.Fatalf("lift the result guard: %v", err) } if _, err := tx.Exec(ctx, `ALTER TABLE candidate_assessment_categories DISABLE TRIGGER candidate_assessment_category_refuse_delete`); err != nil { t.Fatalf("lift the category guard: %v", err) } if _, err := tx.Exec(ctx, `DELETE FROM consent_records WHERE subject_id = $1`, erased.id); err != nil { t.Fatalf("delete the consent records: %v", err) } if _, err := tx.Exec(ctx, `DELETE FROM users WHERE id = $1`, erased.id); err != nil { t.Fatalf("delete the account: %v", err) } for table, column := range map[string]string{ "skill_evidence_facts": "candidate_id", "assessment_attempt_results": "user_id", } { var remaining int if err := tx.QueryRow(ctx, fmt.Sprintf(`SELECT count(*) FROM %s WHERE %s = $1`, table, column), erased.id).Scan(&remaining); err != nil || remaining != 0 { t.Fatalf("rows of %s after the account was deleted = %d (error %v), want 0", table, remaining, err) } } var tags int if err := tx.QueryRow(ctx, `SELECT count(*) FROM skill_evidence_skills AS tag WHERE NOT EXISTS (SELECT 1 FROM skill_evidence_facts WHERE id = tag.fact_id)`).Scan(&tags); err != nil || tags != 0 { t.Fatalf("orphan tags = %d (error %v), want 0", tags, err) } // The guards come back before the erasure is committed. for _, statement := range []string{ `ALTER TABLE consent_records ENABLE TRIGGER USER`, `ALTER TABLE users ENABLE TRIGGER USER`, `ALTER TABLE assessment_attempt_results ENABLE TRIGGER assessment_attempt_result_refuse_mutation`, `ALTER TABLE candidate_assessment_categories ENABLE TRIGGER candidate_assessment_category_refuse_delete`, } { if _, err := tx.Exec(ctx, statement); err != nil { t.Fatalf("restore the guard (%s): %v", statement, err) } } if err := tx.Commit(ctx); err != nil { t.Fatalf("commit the erasure: %v", err) } if countRows(`SELECT count(*) FROM pg_trigger WHERE tgenabled = 'D' AND NOT tgisinternal`) != 0 { t.Fatal("a trigger stayed disabled after the erasure") } if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE result_id = $1`, run.id) != 0 { t.Fatal("a fact of the erased account remains") } }) t.Run("the projection is rebuilt from the results and survives the migration", func(t *testing.T) { qualifying := countRows(` SELECT count(*) FROM assessment_attempt_results WHERE schema_version = 2 AND kind IN ('root', 'corrective') AND outcome = 'confirmed' AND category_decision ->> 'status' IN ('assigned', 'unchanged')`) eventsBefore := evidenceEventIDs(t, ctx, harness) // Cohort of five, two promotions of the pager and two of the candidate of the // preview; nothing from the failed or express runs. if want := evidenceCohortSize + 4; qualifying != want || len(eventsBefore) != want { t.Fatalf("qualifying results = %d, facts = %d, want %d of each", qualifying, len(eventsBefore), want) } // A fact without a skill cannot be committed. if _, err := harness.pool.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil { t.Fatalf("empty the projection: %v", err) } _, err := harness.pool.Exec(ctx, ` INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT user_id, 'measurement', 'assessment_result', attempt_id, attempt_id, 'personal', 1, category_decision ->> 'attempted_grade', category_decision ->> 'source', category_decision ->> 'calibration_status', decided_at FROM assessment_attempt_results WHERE attempt_id = $1`, targetRun.id) assertPgError(t, "fact without a skill", err, "23514", "skill_evidence_facts_require_skill") if _, err := harness.pool.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil { t.Fatalf("project the stored results again: %v", err) } if eventsAfter := evidenceEventIDs(t, ctx, harness); !slices.Equal(eventsAfter, eventsBefore) { t.Fatalf("rebuilt events = %v, want %v", eventsAfter, eventsBefore) } if _, err := harness.pool.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil { t.Fatalf("project the stored results a second time: %v", err) } if countRows(`SELECT count(*) FROM skill_evidence_facts`) != qualifying || countRows(`SELECT count(*) FROM skill_evidence_skills`) != qualifying { t.Fatal("a repeated projection duplicated facts or tags") } // Rolling the migration back removes the projection and applying it again // derives it once more from the results that stayed. migrator := newMigrator(t, databaseURL) // A fact that the candidate hid is a decision no result can bring back, so // the rollback refuses until nothing is hidden. if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE event_id = $1`, targetRun.id); err != nil { t.Fatalf("hide the fact: %v", err) } _, err = migrator.DownOne(ctx) assertPgError(t, "rollback with a hidden fact", err, "23000", "skill_evidence_retained") assertTablesExist(ctx, t, harness.pool, true, "skill_evidence_facts", "skill_evidence_skills") if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE event_id = $1`, targetRun.id); err != nil { t.Fatalf("show the fact: %v", err) } rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion-1) assertTablesExist(ctx, t, harness.pool, false, "skill_evidence_facts", "skill_evidence_skills") assertFunctionsExist(ctx, t, harness.pool, false, "skill_evidence_result_qualifies(assessment_attempt_results)", "skill_evidence_project_assessment_result(uuid)") applyMigrations(ctx, t, databaseURL) if eventsAfter := evidenceEventIDs(t, ctx, harness); !slices.Equal(eventsAfter, eventsBefore) { t.Fatalf("events after the migration was applied again = %v, want %v", eventsAfter, eventsBefore) } if page, _ := readOwn(target, ""); len(page.Items) != 1 || page.Items[0].Trust != 1 || page.Items[0].Source.ResultID != targetRun.id { t.Fatalf("evidence after the migration was applied again = %+v, want the backfilled fact", page.Items) } }) } // readOwnBody returns the raw body of the owner's evidence. func readOwnBody(t *testing.T, get func(categoryHTTPCandidate, string) *httptest.ResponseRecorder, who categoryHTTPCandidate) string { t.Helper() response := get(who, "/api/v1/me/evidence") if response.Code != http.StatusOK { t.Fatalf("own evidence = %d %s", response.Code, response.Body.String()) } return response.Body.String() } // evidenceEventIDs lists the source events of the stored facts in a stable order. func evidenceEventIDs(t *testing.T, ctx context.Context, harness *skillEvidenceHarness) []string { t.Helper() rows, err := harness.pool.Query(ctx, `SELECT event_id::text FROM skill_evidence_facts ORDER BY event_id`) if err != nil { t.Fatalf("list evidence events: %v", err) } defer rows.Close() events, err := pgx.CollectRows(rows, pgx.RowTo[string]) if err != nil { t.Fatalf("read evidence events: %v", err) } return events } // runPerfectExpress answers every item of an express training run correctly, // finalizes it, and returns its attempt identifier. func runPerfectExpress(t *testing.T, ctx context.Context, client *categoryHTTPClient, harness *assessmentAttemptHTTPHarness, who categoryHTTPCandidate) uuid.UUID { t.Helper() key := uuid.NewString() status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, key+"-create") var attempt assessmentAnswerHTTPAttempt if status != http.StatusCreated || json.Unmarshal(body, &attempt) != nil || attempt.ID == uuid.Nil { t.Fatalf("create express attempt = %d %s", status, body) } version := attempt.Version for _, item := range readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) { status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(assessmentAnswerHTTPBody(t, version, item)), fmt.Sprintf("%s-answer-%d", key, item.Ordinal)) var next assessmentAnswerHTTPAttempt if status != http.StatusOK || json.Unmarshal(body, &next) != nil { t.Fatalf("answer express item %d = %d %s", item.Ordinal, status, body) } version = next.Version } finalizeBody, err := json.Marshal(map[string]int64{"expected_version": version}) if err != nil { t.Fatalf("marshal finalize body: %v", err) } if status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", string(finalizeBody), key+"-finalize"); status != http.StatusOK { t.Fatalf("finalize express attempt = %d %s", status, body) } if result := client.result(t, who, attempt.ID); result["outcome"] != "demonstration" { t.Fatalf("express result = %v, want a demonstration", result) } return attempt.ID }