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; every read on behalf of an organization must go through the view // candidate_effective_publications (published and backed by an unrevoked C2) // and exclude the hidden organizations, as ReadPublicationVisibleToOrganization // does. A new query that reads the table directly fails this test, so it // cannot leak a closed or revoked publication by accident. // // 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{ "ReadCandidatePublication", "InsertCandidatePublication", "UpdateCandidatePublication", } var ownerScopedPublicationQueries = []string{ "LockCandidatePublicationForConsentRevocation", } 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]] if publicationTableName.MatchString(statement) { found = append(found, name) statements[name] = strings.Join(strings.Fields(statement), " ") } if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) { 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) } if strings.Contains(strings.Join(found, ","), "Visible") { t.Fatal("the organization-facing read names the table directly") } 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) } } 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) } }