From 03811afcf9bdcd649827f3b6c4ce1702eb594c41 Mon Sep 17 00:00:00 2001 From: Gustavo Caetano Date: Mon, 23 Nov 2026 16:17:50 -0300 Subject: [PATCH] fix(security): restrict privileged RPCs and public plan access --- .../skills/database-security-review/SKILL.md | 15 ++ .github/workflows/security-scan.yml | 5 +- .../20261123-lovable-database-review.md | 16 ++ package.json | 3 +- scripts/check-rpc-security.ts | 42 ++++ scripts/test-security-boundaries.sql | 70 ++++++ src/lib/admin/plans.functions.ts | 18 +- src/routes/admin.plans.tsx | 4 +- ...1123193000_lovable_security_boundaries.sql | 230 ++++++++++++++++++ 9 files changed, 398 insertions(+), 5 deletions(-) create mode 100644 .agents/skills/database-security-review/SKILL.md create mode 100644 docs/security/20261123-lovable-database-review.md create mode 100644 scripts/check-rpc-security.ts create mode 100644 scripts/test-security-boundaries.sql create mode 100644 supabase/migrations/20261123193000_lovable_security_boundaries.sql diff --git a/.agents/skills/database-security-review/SKILL.md b/.agents/skills/database-security-review/SKILL.md new file mode 100644 index 00000000..ab05dccf --- /dev/null +++ b/.agents/skills/database-security-review/SKILL.md @@ -0,0 +1,15 @@ +--- +name: database-security-review +description: Investigate Super Agent Skill database security findings, trace RPC callers, validate role boundaries and deploy reviewed fixes. +--- + +# Database security review + +Use repository scripts rather than rebuilding the audit. Read docs/security/20261123-lovable-database-review.md for the current caller boundaries and intentional transactional definers. + +- Record exact signatures, live ACLs, search_path and policies behind each scanner finding. A grouped warning is not a count of vulnerable functions. +- Trace service-role versus authenticated callers before revoking grants or changing definer to invoker. Preserve auth.uid() binding in purchases, referrals and team transactions. Never clear findings by weakening RLS. +- Test the migration plus scripts/test-security-boundaries.sql in one rolled-back transaction first. Review SQL before execution; the test creates a temporary transactional fixture and must finish with ROLLBACK. +- Apply only reviewed, authorized migration SQL, then run npm run check:security with backend URL/publishable key from the environment. Reports must be nonempty. Run npm run check:project and PR checks before merge and app deploy. +- Re-run Lovable scans. Classify remaining intentional behavior only with specific guard evidence and tests. Do not ignore a whole group to hide unreviewed functions. +- Verify the exact Git commit in Lovable's tracked branch and confirmed publication plus production health. Do not switch tracked branches, resize the database or change a plan as part of a security fix. diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index c116e6a7..433afedd 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -13,7 +13,7 @@ name: security re-scan on: push: - branches: [main] + branches: [main, codex/jev-agent-match-usd10] pull_request: schedule: - cron: "0 6 * * *" @@ -55,6 +55,9 @@ jobs: - name: Public access rules (blocking) run: npm run check:public-access + - name: RPC security boundaries (blocking) + run: npm run check:rpc-security + - name: Summary if: always() run: | diff --git a/docs/security/20261123-lovable-database-review.md b/docs/security/20261123-lovable-database-review.md new file mode 100644 index 00000000..993df795 --- /dev/null +++ b/docs/security/20261123-lovable-database-review.md @@ -0,0 +1,16 @@ +# Lovable database findings — 2026-11-23 + +The scanner grouped 21 definer RPCs, four unpinned email RPCs and an unconditional plans policy into three findings. Database catalogue inspection reproduced all three categories before changes. + +- 24 internal RPCs (CRM including tracking, email queues, OAuth token operations, idempotency, pack/review projections) now grant execution only to service_role. Their existing callers use the server client. The same restriction covers write counterparts of flagged reads. +- The four pgmq wrappers pin an empty search_path; their pgmq references were already schema-qualified. +- search_packages, get_review_eligibility and agent_onboarding_funnel use SECURITY INVOKER. Their callers retain public catalogue, own-user and admin-only table policies respectively. +- Plans public reads permit only the existing public slugs free/pro/enterprise/unlimited. An authenticated user can still read an assigned internal plan. Admin listing is separately authenticated; public serialization omits provider IDs. New public slugs require deliberate publication in this policy. +- Public review projections exclude hidden reviews and unpublished packages; public pack projections exclude unpublished children. + +Four transactional SECURITY DEFINER RPCs intentionally remain authenticated-only: +claim_referral binds the beneficiary to auth.uid(), prevents self/referral reuse and returns only the claim result; purchase_pack and purchase_package bind the buyer to auth.uid(), require an approved published item and perform atomic credit accounting; team_action requires membership/role, checks invite email against auth.jwt(), protects ownership and independent review. Changing these to invoker would require granting clients protected ledger/team writes. Scanner exceptions must be scoped to these exact functions and justified by their guards, not blanket suppression. + +Validation: scripts/test-security-boundaries.sql executes anonymous, ordinary-user and service-role probes in a rolled-back transaction. scripts/check-rpc-security.ts runs the read-only five-verdict catalogue check in CI alongside the existing RLS and table-exposure checks. Empty, missing or malformed reports fail with exit 2; regressions exit 1. + +No database size, plan, prices, balances or subscription assignments are changed by this migration. diff --git a/package.json b/package.json index 3fdb1f02..b86226ae 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "build:dev": "vite build --mode development", "check:rls": "node --experimental-strip-types scripts/check-rls.ts", "check:public-access": "node --experimental-strip-types scripts/check-public-access.ts", - "check:security": "npm run check:rls && npm run check:public-access", + "check:security": "npm run check:rls && npm run check:public-access && npm run check:rpc-security", + "check:rpc-security": "node --experimental-strip-types scripts/check-rpc-security.ts", "predeploy": "npm run check:security", "preview": "vite preview", "lint": "node scripts/lint.mjs", diff --git a/scripts/check-rpc-security.ts b/scripts/check-rpc-security.ts new file mode 100644 index 00000000..7085707a --- /dev/null +++ b/scripts/check-rpc-security.ts @@ -0,0 +1,42 @@ +#!/usr/bin/env node +/** Read-only production/CI verification. 0=pass, 1=regression, 2=incomplete. */ +import { createClient } from "@supabase/supabase-js"; +const url = process.env.SUPABASE_URL || process.env.VITE_SUPABASE_URL; +const key = + process.env.SUPABASE_PUBLISHABLE_KEY || + process.env.VITE_SUPABASE_PUBLISHABLE_KEY || + process.env.SUPABASE_ANON_KEY; +if (!url || !key) { + console.error("[rpc-security] Missing backend configuration."); + process.exit(2); +} +const client = createClient(url, key, { auth: { persistSession: false } }); +const { data, error } = await client.rpc("check_security_boundaries"); +const expected = [ + "server_rpc_acl", + "email_search_path", + "rls_invoker_reads", + "authenticated_transactions", + "plans_explicit_public_rows", +]; +if ( + error || + !Array.isArray(data) || + data.length !== expected.length || + expected.some( + (name) => + data.filter((row) => row.check_name === name && typeof row.passed === "boolean").length !== 1, + ) +) { + console.error("[rpc-security] Incomplete security report.", error?.message ?? ""); + process.exit(2); +} +const failed = data.filter((row) => row.passed !== true); +console.log( + JSON.stringify( + { checks: data, passed: data.length - failed.length, failed: failed.length }, + null, + 2, + ), +); +process.exitCode = failed.length ? 1 : 0; diff --git a/scripts/test-security-boundaries.sql b/scripts/test-security-boundaries.sql new file mode 100644 index 00000000..6ea5f0af --- /dev/null +++ b/scripts/test-security-boundaries.sql @@ -0,0 +1,70 @@ +-- Run after the migration in a transaction. All probes are rolled back. +BEGIN; +INSERT INTO public.plans(slug,name) VALUES ('security-private-probe-20261123','Security rollback fixture'); +DO $test$ +DECLARE failures text; +BEGIN + SELECT string_agg(check_name, ', ') INTO failures FROM public.check_security_boundaries() WHERE passed IS DISTINCT FROM true; + IF failures IS NOT NULL OR (SELECT count(*) FROM public.check_security_boundaries()) <> 5 THEN + RAISE EXCEPTION 'Security boundary regression: %', failures; + END IF; +END $test$; +SET LOCAL ROLE anon; +DO $test$ +BEGIN + BEGIN + PERFORM public.crm_customers(1,0,NULL); + RAISE EXCEPTION 'Anonymous CRM call succeeded'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + BEGIN + PERFORM public.enqueue_email('security_probe', '{}'::jsonb); + RAISE EXCEPTION 'Anonymous email enqueue succeeded'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + IF EXISTS (SELECT 1 FROM public.plans WHERE slug NOT IN ('free','pro','enterprise','unlimited')) THEN + RAISE EXCEPTION 'Internal plans exposed'; + END IF; + PERFORM * FROM public.search_packages('security',NULL,1,0); + IF public.get_review_eligibility('00000000-0000-0000-0000-000000000000')->>'authenticated' <> 'false' THEN + RAISE EXCEPTION 'Anonymous eligibility changed'; + END IF; +END $test$; +RESET ROLE; +SET LOCAL ROLE authenticated; +SELECT set_config('request.jwt.claims','{"sub":"00000000-0000-0000-0000-000000000001","role":"authenticated"}',true); +DO $test$ +BEGIN + BEGIN + PERFORM public.crm_customers(1,0,NULL); + RAISE EXCEPTION 'Ordinary user CRM call succeeded'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + BEGIN + PERFORM public.mcp_oauth_get_client('security_probe'); + RAISE EXCEPTION 'Ordinary user OAuth internal call succeeded'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + IF EXISTS (SELECT 1 FROM public.agent_onboarding_funnel(1)) THEN + RAISE EXCEPTION 'Non-admin received onboarding statistics'; + END IF; + BEGIN + PERFORM public.team_action('invite','00000000-0000-0000-0000-000000000000','{}'); + RAISE EXCEPTION 'Non-member team action succeeded'; + EXCEPTION WHEN insufficient_privilege THEN NULL; END; + IF public.get_review_eligibility('00000000-0000-0000-0000-000000000000')->>'can_review' <> 'false' THEN + RAISE EXCEPTION 'Unknown package eligibility changed'; + END IF; +END $test$; +RESET ROLE; +SELECT set_config('request.jwt.claims','{"role":"service_role"}',true); +SET LOCAL ROLE service_role; +DO $test$ +BEGIN + PERFORM public.mcp_oauth_get_client('security_probe_nonexistent'); + PERFORM public.mcp_idempotency_get('00000000-0000-0000-0000-000000000000','security_probe','probe'); + PERFORM public.get_pack_with_items('security_probe_nonexistent'); + IF public.delete_email('security_probe_nonexistent',-1) IS DISTINCT FROM false THEN + RAISE EXCEPTION 'Email queue missing-table behavior changed'; + END IF; +END $test$; +RESET ROLE; +ROLLBACK; +SELECT 'passed' AS security_role_probes; + diff --git a/src/lib/admin/plans.functions.ts b/src/lib/admin/plans.functions.ts index 500082be..b710e792 100644 --- a/src/lib/admin/plans.functions.ts +++ b/src/lib/admin/plans.functions.ts @@ -23,7 +23,9 @@ const PlanInput = z.object({ export const listPlansPublic = createServerFn({ method: "GET" }).handler(async () => { const { data, error } = await anon .from("plans") - .select("*") + .select( + "id,slug,name,monthly_runs_limit,max_installed_packages,price_cents,features,sort_order,monthly_credits", + ) .order("sort_order", { ascending: true }); if (error) throw new Response(error.message, { status: 500 }); return { @@ -34,6 +36,20 @@ export const listPlansPublic = createServerFn({ method: "GET" }).handler(async ( }; }); +// Admin listing must include internal plans without publishing them anonymously. +export const listPlansAdmin = createServerFn({ method: "GET" }) + .middleware([requireAdmin]) + .handler(async ({ context }) => { + const { data, error } = await context.supabase.from("plans").select("*").order("sort_order"); + if (error) throw new Response(error.message, { status: 500 }); + return { + plans: (data ?? []).map((plan) => ({ + ...plan, + features: z.array(z.string()).parse(plan.features), + })), + }; + }); + export const upsertPlan = createServerFn({ method: "POST" }) .middleware([requireAdmin]) .inputValidator((d: unknown) => PlanInput.parse(d)) diff --git a/src/routes/admin.plans.tsx b/src/routes/admin.plans.tsx index bc6a963f..77a2ccd1 100644 --- a/src/routes/admin.plans.tsx +++ b/src/routes/admin.plans.tsx @@ -2,7 +2,7 @@ import { createFileRoute } from "@tanstack/react-router"; import { useServerFn } from "@tanstack/react-start"; import { useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { listPlansPublic, upsertPlan, deletePlan } from "@/lib/admin/plans.functions"; +import { listPlansAdmin, upsertPlan, deletePlan } from "@/lib/admin/plans.functions"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; @@ -35,7 +35,7 @@ const empty: PlanRow = { }; function PlansPage() { - const listFn = useServerFn(listPlansPublic); + const listFn = useServerFn(listPlansAdmin); const upsertFn = useServerFn(upsertPlan); const deleteFn = useServerFn(deletePlan); const qc = useQueryClient(); diff --git a/supabase/migrations/20261123193000_lovable_security_boundaries.sql b/supabase/migrations/20261123193000_lovable_security_boundaries.sql new file mode 100644 index 00000000..1fa4f2fc --- /dev/null +++ b/supabase/migrations/20261123193000_lovable_security_boundaries.sql @@ -0,0 +1,230 @@ +-- Harden the database boundaries identified by the Lovable security review. +BEGIN; + +REVOKE EXECUTE ON FUNCTION public.crm_active_hours(uuid) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_active_hours(uuid) TO service_role; +REVOKE EXECUTE ON FUNCTION public.crm_activity_hours(uuid,integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_activity_hours(uuid,integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.crm_customers(integer,integer,uuid) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_customers(integer,integer,uuid) TO service_role; +REVOKE EXECUTE ON FUNCTION public.crm_effectiveness(integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_effectiveness(integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.crm_effectiveness_by_segment(integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_effectiveness_by_segment(integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.crm_segment_send_hour_stats(integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_segment_send_hour_stats(integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.crm_send_hour_stats(integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_send_hour_stats(integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.crm_track_click(text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_track_click(text) TO service_role; +REVOKE EXECUTE ON FUNCTION public.crm_track_open(text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.crm_track_open(text) TO service_role; +REVOKE EXECUTE ON FUNCTION public.delete_email(text,bigint) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.delete_email(text,bigint) TO service_role; +REVOKE EXECUTE ON FUNCTION public.enqueue_email(text,jsonb) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.enqueue_email(text,jsonb) TO service_role; +REVOKE EXECUTE ON FUNCTION public.get_pack_with_items(text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.get_pack_with_items(text) TO service_role; +REVOKE EXECUTE ON FUNCTION public.get_package_ratings(uuid) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.get_package_ratings(uuid) TO service_role; +REVOKE EXECUTE ON FUNCTION public.list_package_reviews(uuid,integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.list_package_reviews(uuid,integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_idempotency_get(uuid,text,text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_idempotency_get(uuid,text,text) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_idempotency_put(uuid,text,text,jsonb) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_idempotency_put(uuid,text,text,jsonb) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_exchange_code(text,text,text,text,text,integer,integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_exchange_code(text,text,text,text,text,integer,integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_get_client(text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_get_client(text) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_refresh_token(text,text,text,text,integer,integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_refresh_token(text,text,text,text,integer,integer) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_register_client(text,text[],text,text,text,text,text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_register_client(text,text[],text,text,text,text,text) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_revoke_token(text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_revoke_token(text) TO service_role; +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_verify_access(text) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_verify_access(text) TO service_role; +REVOKE EXECUTE ON FUNCTION public.move_to_dlq(text,text,bigint,jsonb) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.move_to_dlq(text,text,bigint,jsonb) TO service_role; +REVOKE EXECUTE ON FUNCTION public.read_email_batch(text,integer,integer) FROM PUBLIC, anon, authenticated; +GRANT EXECUTE ON FUNCTION public.read_email_batch(text,integer,integer) TO service_role; + +ALTER FUNCTION public.agent_onboarding_funnel(integer) SECURITY INVOKER; + +ALTER FUNCTION public.search_packages(text,text,integer,integer) SECURITY INVOKER; + +ALTER FUNCTION public.get_review_eligibility(uuid) SECURITY INVOKER; + +REVOKE EXECUTE ON FUNCTION public.claim_referral(text,text,text) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.claim_referral(text,text,text) TO authenticated, service_role; + +REVOKE EXECUTE ON FUNCTION public.purchase_pack(uuid) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.purchase_pack(uuid) TO authenticated, service_role; + +REVOKE EXECUTE ON FUNCTION public.purchase_package(uuid) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.purchase_package(uuid) TO authenticated, service_role; + +REVOKE EXECUTE ON FUNCTION public.team_action(text,uuid,jsonb) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.team_action(text,uuid,jsonb) TO authenticated, service_role; + +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_issue_code(text,text,text,text,text,text,integer) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_issue_code(text,text,text,text,text,text,integer) TO authenticated, service_role; + +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_list_user_connections() FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_list_user_connections() TO authenticated, service_role; + +REVOKE EXECUTE ON FUNCTION public.mcp_oauth_revoke_client_for_user(text) FROM PUBLIC, anon; +GRANT EXECUTE ON FUNCTION public.mcp_oauth_revoke_client_for_user(text) TO authenticated, service_role; + +ALTER FUNCTION public.delete_email(text,bigint) SET search_path = ''; + +ALTER FUNCTION public.enqueue_email(text,jsonb) SET search_path = ''; + +ALTER FUNCTION public.move_to_dlq(text,text,bigint,jsonb) SET search_path = ''; + +ALTER FUNCTION public.read_email_batch(text,integer,integer) SET search_path = ''; + +-- Public catalogue is explicit: new/internal plans are not published automatically. +ALTER POLICY "plans public read" ON public.plans USING (slug IN ('free', 'pro', 'enterprise', 'unlimited')); +CREATE POLICY "plans assigned read" ON public.plans FOR SELECT TO authenticated +USING (EXISTS (SELECT 1 FROM public.account_plans a WHERE a.plan_id = plans.id AND a.user_id = auth.uid())); + +CREATE OR REPLACE FUNCTION public.get_pack_with_items(_slug text) + RETURNS jsonb + LANGUAGE sql + STABLE SECURITY DEFINER + SET search_path TO 'public' +AS $function$ + with p as ( + select * from public.packs where slug = _slug + and ((is_published and review_status='approved') or author_id = auth.uid() or has_role(auth.uid(),'admin')) + ) + select case when (select id from p) is null then null else + jsonb_build_object( + 'pack', to_jsonb((select row_to_json(p) from p)), + 'items', coalesce(( + select jsonb_agg(jsonb_build_object( + 'package_id', pk.id, + 'slug', pk.slug, + 'name', pk.name, + 'type', pk.type, + 'description', pk.description, + 'role', pi.role, + 'sort_order', pi.sort_order + ) order by pi.sort_order, pk.name) + from public.pack_items pi + join public.packages pk on pk.id = pi.package_id + where pi.pack_id = (select id from p) + and pk.is_published and pk.review_status = 'approved' + ), '[]'::jsonb), + 'owned', exists ( + select 1 from public.pack_purchases pu + where pu.pack_id = (select id from p) and pu.buyer_id = auth.uid() + ) + ) + end; +$function$; + +CREATE OR REPLACE FUNCTION public.get_package_ratings(_package_id uuid) + RETURNS jsonb + LANGUAGE sql + STABLE SECURITY DEFINER + SET search_path TO 'public' +AS $function$ + with agg as ( + select + rater_kind, + count(*)::int as cnt, + round(avg(rating)::numeric, 2) as avg_rating + from public.reviews + where package_id = _package_id and is_hidden = false + and exists (select 1 from public.packages p where p.id = _package_id and p.is_published and p.review_status = 'approved') + group by rater_kind + ), + totals as ( + select count(*)::int as cnt, round(avg(rating)::numeric, 2) as avg_rating + from public.reviews where package_id = _package_id and is_hidden = false + and exists (select 1 from public.packages p where p.id = _package_id and p.is_published and p.review_status = 'approved') + ) + select jsonb_build_object( + 'human_count', coalesce((select cnt from agg where rater_kind='human'), 0), + 'human_avg', coalesce((select avg_rating from agg where rater_kind='human'), 0), + 'agent_count', coalesce((select cnt from agg where rater_kind='agent'), 0), + 'agent_avg', coalesce((select avg_rating from agg where rater_kind='agent'), 0), + 'total_count', coalesce((select cnt from totals), 0), + 'total_avg', coalesce((select avg_rating from totals), 0) + ); +$function$; + +CREATE OR REPLACE FUNCTION public.list_package_reviews(_package_id uuid, _limit integer DEFAULT 50) + RETURNS TABLE(id uuid, rating integer, body text, rater_kind text, verified_purchase boolean, created_at timestamp with time zone, user_id uuid, display_name text, avatar_url text) + LANGUAGE sql + STABLE SECURITY DEFINER + SET search_path TO 'public' +AS $function$ + SELECT r.id, r.rating, r.body, r.rater_kind, r.verified_purchase, r.created_at, + r.user_id, p.display_name, p.avatar_url + FROM public.reviews r + LEFT JOIN public.profiles p ON p.id = r.user_id + WHERE r.package_id = _package_id + AND r.is_hidden = false + AND EXISTS (SELECT 1 FROM public.packages pk WHERE pk.id = _package_id AND pk.is_published AND pk.review_status = 'approved') + ORDER BY r.created_at DESC + LIMIT LEAST(GREATEST(COALESCE(_limit, 50), 1), 100); +$function$; + + +-- Exposes verdicts only, for the existing anonymous CI security gate. +CREATE OR REPLACE FUNCTION public.check_security_boundaries() +RETURNS TABLE(check_name text, passed boolean) +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = '' +AS $audit$ +WITH server_functions(signature) AS (VALUES ('public.crm_active_hours(uuid)'), +('public.crm_activity_hours(uuid,integer)'), +('public.crm_customers(integer,integer,uuid)'), +('public.crm_effectiveness(integer)'), +('public.crm_effectiveness_by_segment(integer)'), +('public.crm_segment_send_hour_stats(integer)'), +('public.crm_send_hour_stats(integer)'), +('public.crm_track_click(text)'), +('public.crm_track_open(text)'), +('public.delete_email(text,bigint)'), +('public.enqueue_email(text,jsonb)'), +('public.get_pack_with_items(text)'), +('public.get_package_ratings(uuid)'), +('public.list_package_reviews(uuid,integer)'), +('public.mcp_idempotency_get(uuid,text,text)'), +('public.mcp_idempotency_put(uuid,text,text,jsonb)'), +('public.mcp_oauth_exchange_code(text,text,text,text,text,integer,integer)'), +('public.mcp_oauth_get_client(text)'), +('public.mcp_oauth_refresh_token(text,text,text,text,integer,integer)'), +('public.mcp_oauth_register_client(text,text[],text,text,text,text,text)'), +('public.mcp_oauth_revoke_token(text)'), +('public.mcp_oauth_verify_access(text)'), +('public.move_to_dlq(text,text,bigint,jsonb)'), +('public.read_email_batch(text,integer,integer)')) +SELECT 'server_rpc_acl', count(*) = 24 AND bool_and( + NOT pg_catalog.has_function_privilege('anon', signature, 'EXECUTE') AND + NOT pg_catalog.has_function_privilege('authenticated', signature, 'EXECUTE') AND + pg_catalog.has_function_privilege('service_role', signature, 'EXECUTE')) FROM server_functions +UNION ALL +SELECT 'email_search_path', count(*) = 4 AND bool_and(p.proconfig @> ARRAY['search_path=""']) +FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace +WHERE n.nspname='public' AND p.proname IN ('enqueue_email','read_email_batch','delete_email','move_to_dlq') +UNION ALL +SELECT 'rls_invoker_reads', count(*) = 3 AND bool_and(NOT p.prosecdef) +FROM pg_catalog.pg_proc p WHERE p.oid IN ('public.agent_onboarding_funnel(integer)'::pg_catalog.regprocedure,'public.search_packages(text,text,integer,integer)'::pg_catalog.regprocedure,'public.get_review_eligibility(uuid)'::pg_catalog.regprocedure) +UNION ALL +SELECT 'authenticated_transactions', count(*) = 7 AND bool_and( + NOT pg_catalog.has_function_privilege('anon', signature, 'EXECUTE') AND + pg_catalog.has_function_privilege('authenticated', signature, 'EXECUTE')) +FROM (VALUES ('public.claim_referral(text,text,text)'),('public.purchase_pack(uuid)'),('public.purchase_package(uuid)'),('public.team_action(text,uuid,jsonb)'),('public.mcp_oauth_issue_code(text,text,text,text,text,text,integer)'),('public.mcp_oauth_list_user_connections()'),('public.mcp_oauth_revoke_client_for_user(text)')) f(signature) +UNION ALL +SELECT 'plans_explicit_public_rows', count(*) = 1 AND bool_and(qual <> 'true' AND qual LIKE '%slug%') +FROM pg_catalog.pg_policies WHERE schemaname='public' AND tablename='plans' AND policyname='plans public read'; +$audit$; +REVOKE ALL ON FUNCTION public.check_security_boundaries() FROM PUBLIC; +GRANT EXECUTE ON FUNCTION public.check_security_boundaries() TO anon, authenticated, service_role; +COMMIT; +