package db import ( "os" "path/filepath" "regexp" "slices" "strings" "testing" ) var ( evidenceTableName = regexp.MustCompile(`(?i)\bskill_evidence_(facts|skills)\b`) // evidenceReaders are the only queries that may name the evidence tables. evidenceReaders = []string{ "ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence", "ListOrganizationVisibleEvidenceBatch", } // evidenceForbiddenSources are tables whose content must never reach the // evidence reads: raw answers and items, results with their scores, // attempts, signals, and the anti-cheat review band. evidenceForbiddenSources = []string{ "assessment_attempt_results", "assessment_attempt_items", "assessment_attempts", "assessment_attempt_reviews", "assessment_attempt_origin_marks", "assessment_answer_observations", "assessment_answer_fingerprint_holders", "assessment_answer_family_totals", "assessment_signal_events", "assessment_signal_batches", "assessment_signal_idempotency_outcomes", "assessment_attempt_idempotency_outcomes", "candidate_assessment_categories", "assessment_synthetic_category_reviews", "candidate_profile_claims", "candidate_questionnaires", } ) // evidenceStatements returns the statement of every query of the query files // by name, with comments removed. func evidenceStatements(t *testing.T) map[string]string { t.Helper() files, err := filepath.Glob("queries/*.sql") if err != nil || len(files) == 0 { t.Fatalf("list the query files = %v, %v", files, err) } statements := make(map[string]string) for _, file := range files { content, err := os.ReadFile(file) if err != nil { t.Fatalf("read %s: %v", file, err) } text := string(content) headers := queryHeaderPattern.FindAllStringSubmatchIndex(text, -1) for index, header := range headers { end := len(text) if index+1 < len(headers) { end = headers[index+1][0] } statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "") statements[text[header[2]:header[3]]] = strings.ToLower(strings.Join(strings.Fields(statement), " ")) } } return statements } // Only the evidence reads name the projection, and the projection reads // reach no table of raw answers, scores, failures, or anti-cheat data. func TestEvidenceReadsNameOnlyTheProjection(t *testing.T) { statements := evidenceStatements(t) var found []string for name, statement := range statements { if evidenceTableName.MatchString(statement) { found = append(found, name) } } slices.Sort(found) want := slices.Clone(evidenceReaders) slices.Sort(want) if !slices.Equal(found, want) { t.Fatalf("queries that name the evidence tables = %v, want only %v", found, want) } for _, name := range evidenceReaders { statement := statements[name] for _, forbidden := range evidenceForbiddenSources { if regexp.MustCompile(`\b` + forbidden + `\b`).MatchString(statement) { t.Errorf("%s reads %s: %s", name, forbidden, statement) } } } } // The organization read goes through the effective publication view, excludes // the candidates that hide the organization, requires the categories field, // and returns an allowlist of columns with no identifier. func TestOrganizationEvidenceReadUsesTheVisibilityBarrier(t *testing.T) { statement := evidenceStatements(t)["ListOrganizationVisibleEvidence"] if statement == "" { t.Fatal("the organization evidence query is missing") } for _, required := range []string{ "from candidate_effective_publications as effective", "from candidate_hidden_organizations as hidden", "not exists", "hidden.organization_id = sqlc.arg(organization_id)", "'categories' = any(effective.fields)", "fact.visibility = 'visible'", "effective.user_id = sqlc.arg(candidate_id)", "select distinct on (skill.skill_code)", "(skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])", "fact.kind = 'measurement'", } { if !strings.Contains(statement, required) { t.Errorf("organization evidence query lacks %q: %s", required, statement) } } selected := statement[len("select"):strings.Index(statement, " from candidate_effective_publications")] for _, private := range []string{"fact.id", "event_id", "result_id", "candidate_id", "visibility"} { if strings.Contains(selected, private) { t.Errorf("organization evidence query selects %q: %s", private, selected) } } // The columns are exactly the skill, the grade, the trust level, and the // year, with the basis and calibration of the method: nothing else of the // fact leaves. const wantSelected = " distinct on (skill.skill_code) skill.skill_code as skill, fact.grade, fact.trust, " + "fact.basis, fact.calibration_status, " + "extract(year from fact.occurred_at at time zone 'utc')::integer as observed_year" if selected != wantSelected { t.Errorf("organization evidence query selects %q, want %q", selected, wantSelected) } if strings.Contains(statement, "candidate_publications") { t.Errorf("organization evidence query reads the publication table directly: %s", statement) } } // The batch read repeats every barrier of the single organization read, and // the match-search queries name no evidence table. func TestOrganizationEvidenceBatchReadRepeatsTheVisibilityBarrier(t *testing.T) { statements := evidenceStatements(t) statement := statements["ListOrganizationVisibleEvidenceBatch"] if statement == "" { t.Fatal("the batch organization evidence query is missing") } for _, required := range []string{ "inner join candidate_effective_publications as effective", "from candidate_hidden_organizations as hidden", "not exists", "hidden.organization_id = sqlc.arg(organization_id)", "'categories' = any(effective.fields)", "fact.visibility = 'visible'", "fact.kind = 'measurement'", "(skill.skill_code || '/' || fact.grade) = wanted.category", } { if !strings.Contains(statement, required) { t.Errorf("batch organization evidence query lacks %q: %s", required, statement) } } if strings.Contains(statement, "candidate_publications") && !strings.Contains(statement, "candidate_effective_publications") { t.Errorf("batch organization evidence query reads the publication table directly: %s", statement) } for _, private := range []string{"fact.id,", "event_id", "result_id", "fact.visibility,", "occurred_at,"} { selected := statement[len("select"):strings.Index(statement, " from (")] if strings.Contains(selected, private) { t.Errorf("batch organization evidence query selects %q: %s", private, selected) } } for name, search := range statements { if strings.HasPrefix(name, "CountReal") && evidenceTableName.MatchString(search) { t.Errorf("%s names an evidence table: %s", name, search) } } }