diff --git a/evals/regression/investigate-database-001-large-advisor-backlog/EVAL.ts b/evals/regression/investigate-database-001-large-advisor-backlog/EVAL.ts new file mode 100644 index 00000000..9db9f26d --- /dev/null +++ b/evals/regression/investigate-database-001-large-advisor-backlog/EVAL.ts @@ -0,0 +1,83 @@ +import { + serializeTranscript, + type CheckResult, + type ToolCallRecord, + type ToolScorer, +} from '@supabase-evals/core'; +import { stripIndent } from 'common-tags'; + +/** + * The seed is shaped like the Mockamaster capture in supabase/mcp#546: 547 + * advisor findings across 11 lints, 8 of them warning or worse. Ungrouped + * advisor output for a project this size is ~364KB, past the 25k-token tool + * output limit, so the agent gets an error instead of the issues. + * Grouped get_issues (supabase/mcp#546) measured 66.3KB on the default + * call, 11 issues. The bound sits near + * the 25k-token limit so a regression to ungrouped output fails here. + * + * Some clients spill results over ~50KB to a file and hand the agent a + * preview plus the path. That is not truncation: the agent can still read + * the whole result. The size is taken from the spill notice in that case. + */ +const MAX_RESULT_CHARS = 100_000; + +const TRUNCATION_MARKERS = ['exceeds maximum allowed tokens']; + +const SPILL_SIZE = /Output too large \(([\d.]+)(KB|MB)\)/; + +const resultSize = (text: string) => { + const spill = text.match(SPILL_SIZE); + if (!spill) return text.length; + return Math.round(Number(spill[1]) * (spill[2] === 'MB' ? 1_000_000 : 1_000)); +}; + +const isIssuesCall = (call: ToolCallRecord) => + call.tool.kind === 'mcp' && call.tool.toolName === 'get_issues'; + +const resultText = (call: ToolCallRecord) => + typeof call.result === 'string' + ? call.result + : (JSON.stringify(call.result) ?? ''); + +const scorer: ToolScorer = async (ctx) => { + const input = serializeTranscript(ctx.transcript); + const issuesCalls = ctx.toolCalls.filter(isIssuesCall); + const sizes = issuesCalls.map((call) => resultSize(resultText(call))); + const largest = sizes.length ? Math.max(...sizes) : 0; + const truncated = issuesCalls.some((call) => + TRUNCATION_MARKERS.some((m) => resultText(call).includes(m)) + ); + + const priority = await ctx.judge({ + input, + rubric: stripIndent` + Pass if the assistant names enabling row-level security on the public.payments table as the first thing to fix, and explains why: the table is exposed to anyone with the anon key through the API. The three critical/ERROR issues (RLS disabled in public, a policy that exists while RLS is disabled, and a security definer view) all trace back to public.payments, and the assistant must treat them as one problem with one fix, not three unrelated ones. It must rank this ahead of the high-volume warnings (unindexed foreign keys, auth RLS initplan, multiple permissive policies, mutable function search_path, duplicate indexes, tables without policies or primary keys). + + Fail if the assistant does not mention public.payments, picks a high-count warning or performance lint as the top priority, treats the payments policy or view as a separate first fix while leaving RLS off, says it could not read the issues because the output was too large, or lists findings without choosing one to fix first. + `, + }); + + const checks: CheckResult[] = [ + { + name: 'called get_issues', + passed: issuesCalls.length > 0, + }, + { + name: `get_issues output stayed under ${MAX_RESULT_CHARS} chars and was not truncated`, + passed: issuesCalls.length > 0 && largest <= MAX_RESULT_CHARS && !truncated, + judgeNotes: `largest get_issues result: ${largest} chars${truncated ? ' (truncated by the agent harness)' : ''}`, + }, + { + name: 'ranked enabling RLS on public.payments as the first fix', + passed: priority.passed, + judgeNotes: priority.notes, + }, + ]; + + return { + passed: checks.every((c) => c.passed), + checks, + }; +}; + +export default scorer; diff --git a/evals/regression/investigate-database-001-large-advisor-backlog/PROMPT.md b/evals/regression/investigate-database-001-large-advisor-backlog/PROMPT.md new file mode 100644 index 00000000..95bc51d7 --- /dev/null +++ b/evals/regression/investigate-database-001-large-advisor-backlog/PROMPT.md @@ -0,0 +1,14 @@ +--- +stage: investigate +interface: mcp +product: + - database +topic: + - security + - rls +motivation: supabase/mcp#546, supabase/mcp#574 +--- + +Our Supabase dashboard advisor is showing a wall of warnings, 500+ findings across security and performance. We can't fix all of them this week. + +Can you check the project's issues and tell me which one we should fix first, and why? diff --git a/evals/regression/investigate-database-001-large-advisor-backlog/remote/project.sql b/evals/regression/investigate-database-001-large-advisor-backlog/remote/project.sql new file mode 100644 index 00000000..075504f1 --- /dev/null +++ b/evals/regression/investigate-database-001-large-advisor-backlog/remote/project.sql @@ -0,0 +1,124 @@ +-- A large, long-lived project shaped like the Mockamaster capture in +-- supabase/mcp#546: the advisors return 547 findings across 11 lint types. +-- Three are critical and they share one cause: public.payments has RLS +-- disabled, so anyone holding the anon key can read and write every payment +-- row. Its policy is never enforced, and a view over it is reachable through +-- the API too. The rest is real but routine performance and hygiene debt, +-- and it is the bulk of the output, which is what made get_issues overflow +-- before supabase/mcp#546. + +CREATE TABLE public.orgs ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + name text NOT NULL +); +ALTER TABLE public.orgs ENABLE ROW LEVEL SECURITY; +CREATE POLICY orgs_read ON public.orgs FOR SELECT TO authenticated USING (true); + +-- The critical cause: RLS disabled on payments (rls_disabled_in_public, ERROR). +CREATE TABLE public.payments ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + org_id bigint NOT NULL REFERENCES public.orgs (id), + stripe_customer_id text NOT NULL, + amount_cents integer NOT NULL, + status text NOT NULL DEFAULT 'pending', + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX payments_org_id_idx ON public.payments (org_id); + +-- Someone wrote a policy but never enabled RLS, so it does nothing +-- -> policy_exists_rls_disabled (ERROR) +CREATE POLICY payments_org_read ON public.payments FOR SELECT TO authenticated + USING (org_id IN (SELECT id FROM public.orgs)); + +-- A billing summary view over payments, without security_invoker +-- -> security_definer_view (ERROR) +CREATE VIEW public.payments_by_org AS + SELECT org_id, sum(amount_cents) AS total_cents, count(*) AS n + FROM public.payments GROUP BY org_id; + +INSERT INTO public.orgs (name) +SELECT 'org-' || n FROM generate_series(1, 25) AS n; + +INSERT INTO public.payments (org_id, stripe_customer_id, amount_cents, status) +SELECT ((n - 1) % 25) + 1, 'cus_' || lpad(n::text, 10, '0'), 500 + n * 37 % 9000, + (ARRAY['pending', 'succeeded', 'refunded'])[1 + n % 3] +FROM generate_series(1, 200) AS n; + +-- 80 feature tables. Each one carries: +-- 2 unindexed foreign keys -> 160 unindexed_foreign_keys (INFO) +-- 2 policies calling auth.uid() bare -> 160 auth_rls_initplan (WARN) +-- 2 permissive SELECT policies -> 80 multiple_permissive_policies (WARN) +-- and the first 20 have a duplicated created_at index -> 20 duplicate_index (WARN) +DO $$ +DECLARE + i int; + t text; +BEGIN + FOR i IN 1..80 LOOP + t := format('feature_%s', lpad(i::text, 2, '0')); + EXECUTE format( + 'CREATE TABLE public.%I ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + org_id bigint NOT NULL REFERENCES public.orgs (id), + billing_org_id bigint REFERENCES public.orgs (id), + owner_id uuid NOT NULL, + payload jsonb NOT NULL DEFAULT ''{}''::jsonb, + created_at timestamptz NOT NULL DEFAULT now() + )', t); + EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t); + EXECUTE format( + 'CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (owner_id = auth.uid())', + t || '_owner_read', t); + EXECUTE format( + 'CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (auth.uid() IS NOT NULL AND org_id IN (SELECT id FROM public.orgs))', + t || '_member_read', t); + IF i <= 20 THEN + EXECUTE format('CREATE INDEX %I ON public.%I (created_at)', t || '_created_at_idx', t); + EXECUTE format('CREATE INDEX %I ON public.%I (created_at)', t || '_created_idx', t); + END IF; + END LOOP; +END +$$; + +-- 81 helper functions without a pinned search_path -> 81 function_search_path_mutable (WARN) +DO $$ +DECLARE + i int; +BEGIN + FOR i IN 1..81 LOOP + EXECUTE format( + 'CREATE FUNCTION public.%I(x bigint) RETURNS bigint LANGUAGE sql STABLE AS ''SELECT x''', + format('helper_%s', lpad(i::text, 2, '0'))); + END LOOP; +END +$$; + +-- 30 audit tables, RLS on and no policies (deliberately locked down) +-- -> 30 rls_enabled_no_policy (INFO) +-- the last 10 are append-only logs without a primary key -> 10 no_primary_key (INFO) +DO $$ +DECLARE + i int; + t text; +BEGIN + FOR i IN 1..30 LOOP + t := format('audit_%s', lpad(i::text, 2, '0')); + IF i <= 20 THEN + EXECUTE format( + 'CREATE TABLE public.%I (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, event text NOT NULL, at timestamptz NOT NULL DEFAULT now())', t); + ELSE + EXECUTE format( + 'CREATE TABLE public.%I (event text NOT NULL, at timestamptz NOT NULL DEFAULT now())', t); + END IF; + EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t); + END LOOP; +END +$$; + +-- 3 reporting materialized views in the API schema -> 3 materialized_view_in_api (WARN) +CREATE MATERIALIZED VIEW public.daily_feature_usage AS + SELECT date_trunc('day', created_at) AS day, count(*) AS n FROM public.feature_01 GROUP BY 1; +CREATE MATERIALIZED VIEW public.weekly_feature_usage AS + SELECT date_trunc('week', created_at) AS week, count(*) AS n FROM public.feature_02 GROUP BY 1; +CREATE MATERIALIZED VIEW public.org_feature_counts AS + SELECT org_id, count(*) AS n FROM public.feature_03 GROUP BY 1; diff --git a/experiments/regression/claude-code-opus-5.5-large-advisor-backlog.experiment.ts b/experiments/regression/claude-code-opus-5.5-large-advisor-backlog.experiment.ts new file mode 100644 index 00000000..4f27001c --- /dev/null +++ b/experiments/regression/claude-code-opus-5.5-large-advisor-backlog.experiment.ts @@ -0,0 +1,20 @@ +import { + defineExperiment, + platformLiteRuntime, + supabaseMcpServer, +} from '@supabase-evals/core'; +import { claudeCodeOpus55 } from '../presets.js'; + +// Pins the supabase/mcp#546 merge commit on main, which adds get_issues. +// Drop the pin once a published MCP release includes it. +export default defineExperiment({ + ...claudeCodeOpus55, + runtime: platformLiteRuntime({ + mcpServers: [ + supabaseMcpServer({ + revision: '01f8021f4978ba71c978286ce4943a8dcfbdb5ff', + }), + ], + }), + skipEval: (ev) => ev.id !== 'investigate-database-001-large-advisor-backlog', +}); diff --git a/packages/platform-lite/src/management-api/advisor-lints.ts b/packages/platform-lite/src/management-api/advisor-lints.ts new file mode 100644 index 00000000..95d241eb --- /dev/null +++ b/packages/platform-lite/src/management-api/advisor-lints.ts @@ -0,0 +1,324 @@ +/** + * Splinter-shaped advisor lints, computed from the PGlite catalog. + * + * Each lint mirrors one hosted rule (supabase/splinter): same name, level, + * category and remediation URL, so an mcp tool that groups or caps lints sees + * the shape it sees hosted. The SQL is a simplified port: it covers the common + * form of each rule, not every edge case splinter handles. Extend from an eval + * that needs it, not speculatively. + * + * rls_disabled_in_public stays in debugging.ts unchanged; existing evals + * depend on its exact remediation text. + */ + +type Level = 'INFO' | 'WARN' | 'ERROR'; +type Category = 'SECURITY' | 'PERFORMANCE'; + +type Row = Record & { schema: string; name: string }; + +export type AdvisorLint = { + name: string; + title: string; + level: Level; + facing: 'EXTERNAL'; + categories: Category[]; + description: string; + detail: string; + remediation: string; + metadata: { schema: string; name: string; type: string }; + cache_key: string; +}; + +type LintDef = { + name: string; + code: string; + title: string; + level: Level; + category: Category; + description: string; + objectType: string; + sql: string; + detail: (row: Row) => string; + key: (row: Row) => string; +}; + +const USER_SCHEMA = String.raw`n.nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast', 'auth', 'extensions', 'storage', 'supabase_functions', 'supabase_migrations') AND n.nspname NOT LIKE 'pg\_%'`; + +const POLICY_SCHEMA = String.raw`p.schemaname NOT IN ('pg_catalog', 'information_schema', 'pg_toast', 'auth', 'extensions', 'storage', 'supabase_functions', 'supabase_migrations')`; + +// An auth helper call not wrapped in a subselect is re-evaluated per row. +const AUTH_CALL = String.raw`auth\.(uid|jwt|role|email)\(\)`; +const WRAPPED_AUTH_CALL = String.raw`select\s+auth\.(uid|jwt|role|email)\(\)`; + +const q = (ident: string) => `"${ident}"`; +const rel = (row: Row) => `${q(row.schema)}.${q(row.name)}`; + +const LINTS: LintDef[] = [ + { + name: 'policy_exists_rls_disabled', + code: '0007', + title: 'Policy Exists RLS Disabled', + level: 'ERROR', + category: 'SECURITY', + description: + 'Detects cases where row level security (RLS) policies have been created, but RLS has not been enabled for the underlying table.', + objectType: 'table', + sql: ` +SELECT n.nspname AS schema, c.relname AS name +FROM pg_class c +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE c.relkind = 'r' AND ${USER_SCHEMA} + AND NOT c.relrowsecurity + AND EXISTS (SELECT 1 FROM pg_policy p WHERE p.polrelid = c.oid) +ORDER BY 1, 2`, + detail: (r) => + `Table ${rel(r)} has RLS policies but RLS is not enabled on the table.`, + key: (r) => `policy_exists_rls_disabled_${r.schema}_${r.name}`, + }, + { + name: 'rls_enabled_no_policy', + code: '0008', + title: 'RLS Enabled No Policy', + level: 'INFO', + category: 'SECURITY', + description: + 'Detects cases where row level security (RLS) has been enabled on a table but no RLS policies have been created.', + objectType: 'table', + sql: ` +SELECT n.nspname AS schema, c.relname AS name +FROM pg_class c +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE c.relkind = 'r' AND ${USER_SCHEMA} + AND c.relrowsecurity + AND NOT EXISTS (SELECT 1 FROM pg_policy p WHERE p.polrelid = c.oid) +ORDER BY 1, 2`, + detail: (r) => + `Table ${rel(r)} has RLS enabled, but no policies exist`, + key: (r) => `rls_enabled_no_policy_${r.schema}_${r.name}`, + }, + { + name: 'security_definer_view', + code: '0010', + title: 'Security Definer View', + level: 'ERROR', + category: 'SECURITY', + description: + 'Detects views defined with the SECURITY DEFINER property. These views enforce Postgres permissions and row level security policies (RLS) of the view creator, rather than that of the querying user', + objectType: 'view', + sql: ` +SELECT n.nspname AS schema, c.relname AS name +FROM pg_class c +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE c.relkind = 'v' AND n.nspname = 'public' + AND NOT coalesce(c.reloptions, '{}') && ARRAY['security_invoker=true', 'security_invoker=on', 'security_invoker=1'] +ORDER BY 1, 2`, + detail: (r) => + `View ${rel(r)} is defined with the SECURITY DEFINER property`, + key: (r) => `security_definer_view_${r.schema}_${r.name}`, + }, + { + name: 'function_search_path_mutable', + code: '0011', + title: 'Function Search Path Mutable', + level: 'WARN', + category: 'SECURITY', + description: 'Detects functions where the search_path parameter is not set.', + objectType: 'function', + sql: ` +SELECT n.nspname AS schema, p.proname AS name, p.oid::regprocedure::text AS signature +FROM pg_proc p +JOIN pg_namespace n ON n.oid = p.pronamespace +WHERE p.prokind = 'f' AND ${USER_SCHEMA} + AND NOT EXISTS ( + SELECT 1 FROM unnest(coalesce(p.proconfig, '{}')) AS cfg WHERE cfg LIKE 'search_path=%' + ) + AND NOT EXISTS ( + SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e' + ) +ORDER BY 1, 2, 3`, + detail: (r) => + `Function ${rel(r)} has a role mutable search_path`, + key: (r) => + `function_search_path_mutable_${r.schema}_${r.name}_${String(r.signature)}`, + }, + { + name: 'materialized_view_in_api', + code: '0016', + title: 'Materialized View in API', + level: 'WARN', + category: 'SECURITY', + description: + 'Detects materialized views that are accessible over the Data APIs.', + objectType: 'materialized view', + sql: ` +SELECT n.nspname AS schema, c.relname AS name +FROM pg_class c +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE c.relkind = 'm' AND n.nspname = 'public' +ORDER BY 1, 2`, + detail: (r) => + `Materialized view ${rel(r)} is selectable by anon or authenticated roles`, + key: (r) => `materialized_view_in_api_${r.schema}_${r.name}`, + }, + { + name: 'unindexed_foreign_keys', + code: '0001', + title: 'Unindexed foreign keys', + level: 'INFO', + category: 'PERFORMANCE', + description: + 'Identifies foreign key constraints without a covering index, which can impact database performance.', + objectType: 'table', + sql: ` +SELECT n.nspname AS schema, c.relname AS name, con.conname AS fkey_name +FROM pg_constraint con +JOIN pg_class c ON c.oid = con.conrelid +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE con.contype = 'f' AND ${USER_SCHEMA} + AND NOT EXISTS ( + SELECT 1 FROM pg_index i + WHERE i.indrelid = con.conrelid + AND (string_to_array(i.indkey::text, ' ')::int2[])[1:cardinality(con.conkey)] = con.conkey + ) +ORDER BY 1, 2, 3`, + detail: (r) => + `Table ${rel(r)} has a foreign key ${q(String(r.fkey_name))} without a covering index. This can lead to suboptimal query performance.`, + key: (r) => + `unindexed_foreign_keys_${r.schema}_${r.name}_${String(r.fkey_name)}`, + }, + { + name: 'auth_rls_initplan', + code: '0003', + title: 'Auth RLS Initialization Plan', + level: 'WARN', + category: 'PERFORMANCE', + description: + "Detects if calls to `current_setting()` and `auth.()` in RLS policies are being unnecessarily re-evaluated for each row", + objectType: 'table', + sql: String.raw` +SELECT p.schemaname AS schema, p.tablename AS name, p.policyname AS policy_name +FROM pg_policies p +WHERE ${POLICY_SCHEMA} + AND ( + (coalesce(p.qual, '') ~ '${AUTH_CALL}' AND coalesce(p.qual, '') !~* '${WRAPPED_AUTH_CALL}') + OR (coalesce(p.with_check, '') ~ '${AUTH_CALL}' AND coalesce(p.with_check, '') !~* '${WRAPPED_AUTH_CALL}') + ) +ORDER BY 1, 2, 3`, + detail: (r) => + `Table ${rel(r)} has a row level security policy ${q(String(r.policy_name))} that re-evaluates auth.() for each row. This produces suboptimal query performance at scale. Resolve the issue by replacing \`auth.()\` with \`(select auth.())\`.`, + key: (r) => + `auth_rls_init_plan_${r.schema}_${r.name}_${String(r.policy_name)}`, + }, + { + name: 'no_primary_key', + code: '0004', + title: 'No Primary Key', + level: 'INFO', + category: 'PERFORMANCE', + description: + 'Detects if a table does not have a primary key. Tables without a primary key can be inefficient to interact with at scale.', + objectType: 'table', + sql: ` +SELECT n.nspname AS schema, c.relname AS name +FROM pg_class c +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE c.relkind = 'r' AND ${USER_SCHEMA} + AND NOT EXISTS ( + SELECT 1 FROM pg_constraint con WHERE con.conrelid = c.oid AND con.contype = 'p' + ) +ORDER BY 1, 2`, + detail: (r) => `Table ${rel(r)} does not have a primary key`, + key: (r) => `no_primary_key_${r.schema}_${r.name}`, + }, + { + name: 'multiple_permissive_policies', + code: '0006', + title: 'Multiple Permissive Policies', + level: 'WARN', + category: 'PERFORMANCE', + description: + 'Detects if multiple permissive row level security policies are present on a table for the same `role` and `action` (e.g. insert). Multiple permissive policies are suboptimal for performance as each policy must be executed for every relevant query.', + objectType: 'table', + sql: ` +SELECT p.schemaname AS schema, p.tablename AS name, r.role::text AS role, a.action, + array_agg(p.policyname::text ORDER BY p.policyname) AS policies +FROM pg_policies p +CROSS JOIN LATERAL unnest(p.roles) AS r(role) +CROSS JOIN LATERAL unnest( + CASE WHEN p.cmd = 'ALL' THEN ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE'] ELSE ARRAY[p.cmd] END +) AS a(action) +WHERE p.permissive = 'PERMISSIVE' AND ${POLICY_SCHEMA} +GROUP BY 1, 2, 3, 4 +HAVING count(*) > 1 +ORDER BY 1, 2, 3, 4`, + detail: (r) => + `Table ${rel(r)} has multiple permissive policies for role \`${String(r.role)}\` for action \`${String(r.action)}\`. Policies include \`${JSON.stringify(r.policies)}\``, + key: (r) => + `multiple_permissive_policies_${r.schema}_${r.name}_${String(r.role)}_${String(r.action)}`, + }, + { + name: 'duplicate_index', + code: '0009', + title: 'Duplicate Index', + level: 'WARN', + category: 'PERFORMANCE', + description: + 'Detects cases where two ore more identical indexes exist.', + objectType: 'table', + sql: ` +SELECT n.nspname AS schema, c.relname AS name, + array_agg(ic.relname::text ORDER BY ic.relname) AS indexes +FROM pg_index i +JOIN pg_class c ON c.oid = i.indrelid +JOIN pg_class ic ON ic.oid = i.indexrelid +JOIN pg_namespace n ON n.oid = c.relnamespace +WHERE ${USER_SCHEMA} +GROUP BY n.nspname, c.relname, i.indkey::text, i.indclass::text, i.indoption::text, i.indisunique, + coalesce(pg_get_expr(i.indexprs, i.indrelid), ''), + coalesce(pg_get_expr(i.indpred, i.indrelid), '') +HAVING count(*) > 1 +ORDER BY 1, 2`, + detail: (r) => + `Table ${rel(r)} has identical indexes ${JSON.stringify(r.indexes)}. Drop all except one of them`, + key: (r) => + `duplicate_index_${r.schema}_${r.name}_${(r.indexes as string[]).join('_')}`, + }, +]; + +function remediationUrl(def: LintDef): string { + return `https://supabase.com/docs/guides/database/database-linter?lint=${def.code}_${def.name}`; +} + +function isRow(v: unknown): v is Row { + return ( + typeof v === 'object' && + v !== null && + typeof (v as Row).schema === 'string' && + typeof (v as Row).name === 'string' + ); +} + +export async function runAdvisorLints( + category: Category, + query: (sql: string) => Promise +): Promise { + const lints: AdvisorLint[] = []; + for (const def of LINTS.filter((d) => d.category === category)) { + const rows = (await query(def.sql)).filter(isRow); + for (const row of rows) { + lints.push({ + name: def.name, + title: def.title, + level: def.level, + facing: 'EXTERNAL', + categories: [def.category], + description: def.description, + detail: def.detail(row), + remediation: remediationUrl(def), + metadata: { schema: row.schema, name: row.name, type: def.objectType }, + cache_key: def.key(row), + }); + } + } + return lints; +} diff --git a/packages/platform-lite/src/management-api/debugging.ts b/packages/platform-lite/src/management-api/debugging.ts index b858cacc..574c0ea5 100644 --- a/packages/platform-lite/src/management-api/debugging.ts +++ b/packages/platform-lite/src/management-api/debugging.ts @@ -3,6 +3,7 @@ import { createManagementApiRoutes, type ManagementApiRoutes, } from './routes.js'; +import { runAdvisorLints } from './advisor-lints.js'; import { extractRows } from './utils.js'; const RLS_DISABLED_SQL = ` @@ -116,7 +117,8 @@ export function createDebuggingRoutes( description: 'Table is accessible to all roles without row-level security.', detail: `Table "${row.schema}"."${row.name}" has RLS disabled.`, - remediation: `Enable RLS: ALTER TABLE "${row.schema}"."${row.name}" ENABLE ROW LEVEL SECURITY;`, + remediation: + 'https://supabase.com/docs/guides/database/database-linter?lint=0013_rls_disabled_in_public', metadata: { schema: row.schema, name: row.name, @@ -124,7 +126,10 @@ export function createDebuggingRoutes( }, cache_key: `rls_disabled_in_public:${row.schema}.${row.name}`, })); - return c.json({ lints }); + const more = await runAdvisorLints('SECURITY', async (sql) => + extractRows(await project.app.connection.exec(sql)) + ); + return c.json({ lints: [...lints, ...more] }); } catch (err) { const message = err instanceof Error ? err.message : String(err); return c.json({ message }, 500); @@ -135,7 +140,16 @@ export function createDebuggingRoutes( const { ref } = c.req.param(); const project = store.get(ref); if (!project) return c.json({ message: 'Project not found' }, 404); - return c.json({ lints: [] }); + + try { + const lints = await runAdvisorLints('PERFORMANCE', async (sql) => + extractRows(await project.app.connection.exec(sql)) + ); + return c.json({ lints }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return c.json({ message }, 500); + } }); // Health lints score hosted log error rates, so error loudly. An empty list would read as healthy. diff --git a/packages/platform-lite/test/advisor-lints.test.ts b/packages/platform-lite/test/advisor-lints.test.ts new file mode 100644 index 00000000..df03d2d3 --- /dev/null +++ b/packages/platform-lite/test/advisor-lints.test.ts @@ -0,0 +1,166 @@ +import { describe, it, expect } from 'vitest'; +import { createTestApp, request } from './helpers.js'; + +type Lint = { + name: string; + level: string; + categories: string[]; + detail: string; + remediation: string; + metadata: { schema: string; name: string; type: string }; + cache_key: string; +}; + +async function lints(sql: string, kind: 'security' | 'performance') { + const app = await createTestApp([{ ref: 'lint-proj', sql }]); + const { status, data } = await request<{ lints: Lint[] }>( + app, + 'GET', + `/v1/projects/lint-proj/advisors/${kind}` + ); + expect(status).toBe(200); + return data.lints; +} + +const names = (ls: Lint[], name: string) => + ls.filter((l) => l.name === name).map((l) => l.metadata.name); + +describe('advisor lints', () => { + it('policy_exists_rls_disabled flags a policy on a table without RLS', async () => { + const ls = await lints( + `CREATE TABLE public.notes (id int PRIMARY KEY); + CREATE POLICY p ON public.notes FOR SELECT USING (true); + CREATE TABLE public.ok (id int PRIMARY KEY); + ALTER TABLE public.ok ENABLE ROW LEVEL SECURITY; + CREATE POLICY p ON public.ok FOR SELECT USING (true);`, + 'security' + ); + expect(names(ls, 'policy_exists_rls_disabled')).toEqual(['notes']); + const lint = ls.find((l) => l.name === 'policy_exists_rls_disabled')!; + expect(lint.level).toBe('ERROR'); + expect(lint.remediation).toBe( + 'https://supabase.com/docs/guides/database/database-linter?lint=0007_policy_exists_rls_disabled' + ); + }); + + it('rls_enabled_no_policy flags RLS on with no policy', async () => { + const ls = await lints( + `CREATE TABLE public.locked (id int PRIMARY KEY); + ALTER TABLE public.locked ENABLE ROW LEVEL SECURITY;`, + 'security' + ); + expect(names(ls, 'rls_enabled_no_policy')).toEqual(['locked']); + expect(names(ls, 'rls_disabled_in_public')).toEqual([]); + }); + + it('security_definer_view flags views without security_invoker', async () => { + const ls = await lints( + `CREATE TABLE public.t (id int PRIMARY KEY); + ALTER TABLE public.t ENABLE ROW LEVEL SECURITY; + CREATE POLICY p ON public.t FOR SELECT USING (true); + CREATE VIEW public.v_definer AS SELECT id FROM public.t; + CREATE VIEW public.v_invoker WITH (security_invoker = true) AS SELECT id FROM public.t;`, + 'security' + ); + expect(names(ls, 'security_definer_view')).toEqual(['v_definer']); + }); + + it('function_search_path_mutable flags functions without search_path', async () => { + const ls = await lints( + `CREATE FUNCTION public.loose() RETURNS int LANGUAGE sql AS 'select 1'; + CREATE FUNCTION public.pinned() RETURNS int LANGUAGE sql SET search_path = '' AS 'select 1';`, + 'security' + ); + expect(names(ls, 'function_search_path_mutable')).toEqual(['loose']); + const lint = ls.find((l) => l.name === 'function_search_path_mutable')!; + expect(lint.metadata.type).toBe('function'); + expect(lint.level).toBe('WARN'); + }); + + it('materialized_view_in_api flags public matviews', async () => { + const ls = await lints( + `CREATE TABLE public.t (id int PRIMARY KEY); + ALTER TABLE public.t ENABLE ROW LEVEL SECURITY; + CREATE POLICY p ON public.t FOR SELECT USING (true); + CREATE MATERIALIZED VIEW public.mv AS SELECT id FROM public.t;`, + 'security' + ); + expect(names(ls, 'materialized_view_in_api')).toEqual(['mv']); + }); + + it('unindexed_foreign_keys flags fks without a covering index', async () => { + const ls = await lints( + `CREATE TABLE public.orgs (id int PRIMARY KEY); + CREATE TABLE public.a (id int PRIMARY KEY, org_id int REFERENCES public.orgs(id)); + CREATE TABLE public.b (id int PRIMARY KEY, org_id int REFERENCES public.orgs(id)); + CREATE INDEX ON public.b (org_id);`, + 'performance' + ); + expect(names(ls, 'unindexed_foreign_keys')).toEqual(['a']); + expect(ls.find((l) => l.name === 'unindexed_foreign_keys')!.categories).toEqual([ + 'PERFORMANCE', + ]); + }); + + it('no_primary_key flags tables without a pk', async () => { + const ls = await lints( + `CREATE TABLE public.heap (v text); + CREATE TABLE public.keyed (id int PRIMARY KEY);`, + 'performance' + ); + expect(names(ls, 'no_primary_key')).toEqual(['heap']); + }); + + it('auth_rls_initplan flags unwrapped auth calls only', async () => { + const ls = await lints( + `CREATE TABLE public.t (id int PRIMARY KEY, owner_id uuid); + ALTER TABLE public.t ENABLE ROW LEVEL SECURITY; + CREATE POLICY slow ON public.t FOR SELECT USING (owner_id = auth.uid()); + CREATE POLICY fast ON public.t FOR UPDATE USING (owner_id = (select auth.uid()));`, + 'performance' + ); + const hits = ls.filter((l) => l.name === 'auth_rls_initplan'); + expect(hits).toHaveLength(1); + expect(hits[0].detail).toContain('"slow"'); + }); + + it('multiple_permissive_policies flags overlap per role and action', async () => { + const ls = await lints( + `CREATE TABLE public.t (id int PRIMARY KEY); + ALTER TABLE public.t ENABLE ROW LEVEL SECURITY; + CREATE POLICY a ON public.t FOR SELECT TO authenticated USING (true); + CREATE POLICY b ON public.t FOR ALL TO authenticated USING (true);`, + 'performance' + ); + const hits = ls.filter((l) => l.name === 'multiple_permissive_policies'); + expect(hits).toHaveLength(1); + expect(hits[0].cache_key).toBe( + 'multiple_permissive_policies_public_t_authenticated_SELECT' + ); + }); + + it('duplicate_index flags identical indexes', async () => { + const ls = await lints( + `CREATE TABLE public.t (id int PRIMARY KEY, created_at timestamptz); + CREATE INDEX t_created_1 ON public.t (created_at); + CREATE INDEX t_created_2 ON public.t (created_at); + CREATE INDEX t_created_desc ON public.t (created_at DESC);`, + 'performance' + ); + const hits = ls.filter((l) => l.name === 'duplicate_index'); + expect(hits).toHaveLength(1); + expect(hits[0].detail).toContain('t_created_1'); + expect(hits[0].detail).toContain('t_created_2'); + expect(hits[0].detail).not.toContain('t_created_desc'); + }); + + it('a clean schema returns no performance lints', async () => { + const ls = await lints( + `CREATE TABLE public.orgs (id int PRIMARY KEY); + CREATE TABLE public.a (id int PRIMARY KEY, org_id int REFERENCES public.orgs(id)); + CREATE INDEX ON public.a (org_id);`, + 'performance' + ); + expect(ls).toEqual([]); + }); +});