package db import ( "os" "path/filepath" "regexp" "slices" "strings" "testing" ) // directPublicationReaders are the only queries that may name the table // candidate_publications. The first three are the candidate's own settings // queries; the remaining reads are narrowly scoped lock/recheck operations // that require current C2. Organization reads also exclude hidden // organizations, and candidate preview reads remain owner-scoped. A new // query that reads the table directly fails this test until it is reviewed. // // Only queries/*.sql are covered: the project keeps SQL in sqlc queries and // migrations, and the standards forbid raw SQL in Go code. var directPublicationReaders = []string{ "ReadCandidatePrivacySettings", "ReadCandidatePublication", "InsertCandidatePublication", "UpdateCandidatePublication", } var ownerScopedPublicationQueries = []string{ "LockPublicationForCandidatePreview", "LockVisiblePublicationForView", "LockCandidatePublicationForConsentRevocation", } var ownerPreviewQueries = []string{"ReadCandidateViewSourceForPreview"} var ( // sqlc accepts both comment forms and tolerates trailing whitespace. queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`) // Any mention of the marker, to count headers that the pattern missed. queryMarkerPattern = regexp.MustCompile(`(?i)name:\s*\w+\s+:\w+`) publicationTableName = regexp.MustCompile(`(?i)\bcandidate_publications\b`) effectiveViewName = regexp.MustCompile(`(?i)\bcandidate_effective_publications\b`) hiddenTableName = regexp.MustCompile(`(?i)\bcandidate_hidden_organizations\b`) lineComment = regexp.MustCompile(`(?m)--.*$`) blockComment = regexp.MustCompile(`(?s)/\*.*?\*/`) ) func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { files, err := filepath.Glob("queries/*.sql") if err != nil || len(files) == 0 { t.Fatalf("list the query files = %v, %v", files, err) } var found []string 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) if markers := len(queryMarkerPattern.FindAllString(text, -1)); markers != len(headers) { t.Fatalf("%s has %d query markers but %d parsed headers: use the sqlc header form so every query is checked", file, markers, len(headers)) } for index, header := range headers { end := len(text) if index+1 < len(headers) { end = headers[index+1][0] } // Comments may name the table; statements may not. statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "") name := text[header[2]:header[3]] statements[name] = strings.Join(strings.Fields(statement), " ") if publicationTableName.MatchString(statement) { found = append(found, name) } if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) && !slices.Contains(ownerPreviewQueries, name) { t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name) } } } slices.Sort(found) want := slices.Concat(slices.Clone(directPublicationReaders), ownerScopedPublicationQueries) slices.Sort(want) if !slices.Equal(found, want) { t.Fatalf("queries that name candidate_publications = %v, want only settings queries and owner-scoped consent revocation: %v", found, want) } closeQuery := strings.ToLower(statements["LockCandidatePublicationForConsentRevocation"]) for _, required := range []string{ "select greatest(candidate_publications.published_at, consent_records.revoked_at)", "inner join consent_records", "candidate_publications.user_id = sqlc.arg(user_id)", "candidate_publications.state = 'published'", "consent_records.id = any(sqlc.arg(consent_record_ids)::uuid [])", "consent_records.subject_id = candidate_publications.user_id", "consent_records.purpose = 'c2'", "consent_records.revoked_at is not null", "for update of candidate_publications", } { if !strings.Contains(closeQuery, required) { t.Errorf("consent revocation query lacks %q: %s", required, closeQuery) } } settingsQuery := strings.ToLower(statements["ReadCandidatePrivacySettings"]) for _, required := range []string{ "users.id = sqlc.arg(user_id)", "left join candidate_publications", "left join consent_records", "left join candidate_search_statuses", "from candidate_hidden_organizations", } { if !strings.Contains(settingsQuery, required) { t.Errorf("candidate settings query lacks %q: %s", required, settingsQuery) } } for _, forbidden := range []string{"candidate_profiles", "profile_claims", "candidate_questionnaires", "contact_email", "contact_phone"} { if strings.Contains(settingsQuery, forbidden) { t.Errorf("candidate settings query reaches private profile data %q: %s", forbidden, settingsQuery) } } if strings.Contains(closeQuery, "update candidate_publications") || strings.Contains(closeQuery, "set state = 'closed'") { t.Fatalf("consent revocation query rewrites the stored publication instead of preserving its ledger link: %s", closeQuery) } previewQuery := strings.ToLower(statements["ReadCandidateViewSourceForPreview"]) for _, required := range []string{ "from candidate_effective_publications as effective", "where effective.user_id = sqlc.arg(candidate_id)", "claim.kind in ('stack', 'role', 'experience')", "coalesce(questionnaire.work_formats, '{}'::text[])", } { if !strings.Contains(previewQuery, required) { t.Errorf("owner preview query lacks %q: %s", required, previewQuery) } } visibleLock := strings.ToLower(statements["LockVisiblePublicationForView"]) for _, required := range []string{ "candidate_publications.user_id = sqlc.arg(candidate_id)", "candidate_publications.state = 'published'", "candidate_publications.consent_record_id = sqlc.arg(consent_record_id)", "consent_records.purpose = 'c2'", "consent_records.revoked_at is null", "candidate_hidden_organizations", "for share of candidate_publications, consent_records", } { if !strings.Contains(visibleLock, required) { t.Errorf("organization card lock lacks %q: %s", required, visibleLock) } } visibleSource := strings.ToLower(statements["ListVisibleCandidateViewSources"]) if !effectiveViewName.MatchString(visibleSource) || !hiddenTableName.MatchString(visibleSource) { t.Errorf("organization cohort source must use the effective publication view and hidden-organization filter: %s", visibleSource) } }