Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .agents/skills/database-security-review/SKILL.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 4 additions & 1 deletion .github/workflows/security-scan.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 * * *"
Expand Down Expand Up @@ -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: |
Expand Down
16 changes: 16 additions & 0 deletions docs/security/20261123-lovable-database-review.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
42 changes: 42 additions & 0 deletions scripts/check-rpc-security.ts
Original file line number Diff line number Diff line change
@@ -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;
70 changes: 70 additions & 0 deletions scripts/test-security-boundaries.sql
Original file line number Diff line number Diff line change
@@ -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;

18 changes: 17 additions & 1 deletion src/lib/admin/plans.functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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))
Expand Down
4 changes: 2 additions & 2 deletions src/routes/admin.plans.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading