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
4 changes: 4 additions & 0 deletions .agents/skills/database-security-review/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@ Use repository scripts rather than rebuilding the audit. Read docs/security/2026
- 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.

For advanced application findings, also trace every HTTP, server-function and MCP entry point. Test identity binding and anonymous capabilities centrally; do not treat a database UUID as authorization. Keep public catalogue metadata separate from paid prompt contents. Caller telemetry cannot attest itself as verified. Checkout quantities must follow the exact product lookup key, and redirects must use an explicit origin allowlist.

Run `node --experimental-strip-types --test tests/security-findings.test.ts` and `scripts/test-advanced-security.sql` after the corresponding migration inside a rolled-back transaction. Verify legitimate star increments/decrements as well as denied direct count updates. Check for concurrent Lovable edits before committing or applying migrations; preserve stronger guards already present. Re-scan the exact integrated commit before publishing.
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Technical decisions

- Pro entitlements use explicit price lookup keys and all matching subscriptions in the current payments environment through `subscription-entitlements.ts` and `auth/pro-subscription.server.ts`; standalone Agent Pass is separate. Why: a paid seat or newest subscription must not grant or hide Pro access.

- `src/integrations/supabase/database.ts` merges hand-written schema contracts (`optional-schema.ts`, `platform-schema.ts`) only for entries missing from the generated `types.ts`; generated entries always win. Why: intersecting duplicate table definitions with different `Relationships` breaks supabase-js embedded-resource type parsing (embedded selects like `packages(slug)` fail to resolve).

- Scheduled callbacks under `/api/public/*` authenticate with the managed cron secret via `authenticateCronRequest` (`integrations/supabase/cron-auth.ts`), never with publishable/anon keys. Why: the publishable key ships to every browser.
- Public catalog surfaces read classification from `packages.vertical` (DB-synced from the latest version's rules) and never select `package_versions` content for non-owners. Why: version rules/prompts are author/purchaser-only data.
49 changes: 49 additions & 0 deletions docs/security/20261123-advanced-findings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Advanced security review — 2026-11-23

Reviewed all 22 groups from the advanced Lovable scan (9 critical groups). The scan grouped 27 underlying findings. During the review, a parallel Lovable run committed `e4e9fbd4`; this change builds on that commit and preserves its managed cron authentication, public classification column, RLS fixes and one-shot diagnosis writes. No database plan or size changed.

## Disposition of the original groups

| # | Group | Disposition and evidence |
| --- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | Unverified email joins workspace (critical) | Auto-confirm email disabled in Lovable Auth. `team_action` requires a sent-and-confirmed link or a provider-verified matching address; existing auto-confirmed accounts do not qualify. SQL tests deny an unverified invite, then accept after genuine confirmation timestamps. |
| 2 | Public private drift (critical) | `compute_skill_drift` service-only; role probes reject authenticated callers. |
| 3 | Cross-user diagnoses / curriculum (critical, 2 findings) | Central identity/capability check covers HTTP, server functions and MCP. Owned records require verified owner. Anonymous references are HMAC-signed; raw UUIDs and tampered references fail. One-shot updates prevent overwrites. |
| 4 | Authors forge stars (critical) | Insert count forced to zero; direct updates preserve prior count; nested star trigger may update. SQL tests verify denial plus real increment/decrement. |
| 5 | Approved version tampering / unpurchased customization (critical, 2 findings) | Author writes denied for approved live versions. Customizations require purchase both in RLS and execution; initial state must be queued with empty results. |
| 6 | Unpublished Forge reports (critical) | Public only for approved published free packages; private/paid reports require author/admin. |
| 7 | Forged MCP usage history | `mcp_check_and_log_call` server-only. |
| 8 | Restricted classifications in discovery | Public classification is now `packages.vertical`; discovery no longer loads restricted version rules. Categories remain public by product intent. |
| 9 | Paid instructions in detail | Shared public detail cache omits paid prompt, rules and examples. Full HTTP/MCP deliveries check author/admin/direct or pack purchase; paid responses use private/no-store. Exports resolve the approved latest version. |
| 10 | Inflated trust from self-reports | Public/MCP reports remain unverified. Trust RPC, cached v2 scores and weekly snapshots count only server-attested `is_verified` runs. Existing reports are not retroactively trusted. Cached v2 scores recomputed. |
| 11 | Caller-controlled favorites expose private packages | Reads use the caller's RLS-scoped client. Star inserts require published/approved packages. |
| 12 | Restricted classifications in list | Same public-column boundary as #8. |
| 13 | Precise individual execution timestamps | Public evaluation data no longer queries or returns the last execution timestamp. |
| 14 | Hidden packages via stars | Caller-scoped reads enforce package visibility. |
| 15 | Cross-user credit balance | `get_credit_balance` uses invoker privileges/RLS; SQL probe denies another account's balance. |
| 16 | Transactional SECURITY DEFINER functions (informational, 4 findings) | Intentionally retained: claim_referral, purchase_pack, purchase_package, team_action require authentication and bind writes to auth.uid(); team accept strengthened in #1. Definer existence alone is not a vulnerability. |
| 17 | Arbitrary checkout return URL | Exact project/domain hosts, HTTPS, no userinfo or arbitrary ports. Reject lookalike preview hosts containing the project UUID. |
| 18 | CRM privileged actions (critical, 3 findings) | All three routes call managed `authenticateCronRequest`, never publishable keys. Scheduler secret configured by Lovable; current/previous secret tests pass. |
| 19 | Arbitrary transactional email (critical) | Generic template sender requires verified JWT plus administrator role, before body/template processing. Auth email webhook and managed CRM retain their own trusted paths. |
| 20 | Publicly triggerable scheduled CRM | Duplicate surface of #18. Also revoked public execution on nightly trust recompute and weekly snapshots; existing owner-run SQL cron remains functional. |
| 21 | Unreleased compatibility results | Requires an approved published package before querying results. |
| 22 | Caller-chosen checkout quantity (critical) | Pro/other products always quantity 1; only exact sak_agent_pass_monthly supports seats. Browser adjustable flag cannot override product policy. |

## Additional related gaps closed

Stripe customer reuse is bound to verified user UUID metadata; an unverified email claim can no longer reassign another customer's metadata. Both `has_active_subscription` overloads now use invoker/RLS privileges. Security audit RPCs remain public intentionally: they expose booleans for deployment checks, not customer records or credentials.

## Validation and reusable workflow

- `scripts/test-advanced-security.sql`: synthetic fixtures, negative/positive role probes, always rolled back. Tested together with the migration before applying it.
- `scripts/test-security-boundaries.sql`: previous role regression suite; updated expected report count to 8.
- `npm run check:rpc-security`: 8 nonempty named checks, including 29 service-only RPC signatures, account read isolation, verified telemetry and customization ownership.
- `tests/security-findings.test.ts`: managed cron, capability integrity, exact product quantities and redirect boundaries.
- `tests/diagnosis-persistence.test.ts`: bundled real server round trip against a stub database; verifies signed external reference but raw UUID foreign keys and cross-owner denial.
- Existing `database-security-review` skill extended with the proven advanced-review method.

Jev 1.14.0 advisory review flagged the initial anonymous UUID-as-capability boundary (gap probability 0.83). That design was replaced with HMAC references and tested. It supported separating verified trust from self-reported telemetry (0.82); classification evidence was less decisive (0.61), so the integrated implementation explicitly separates public metadata in its own column. Jev is not an approval or security gate.

Anonymous exams created before this change must be restarted; plain UUIDs no longer authorize anonymous history. Rotating the server signing credential invalidates anonymous capabilities. No existing user records are deleted. Historical unverified telemetry remains stored but no longer increases verified trust.

Validation recorded: 466 tests passed; all 12 project checks passed (the final lint rerun reports 825 files, 0 blocking errors and 0 explicit-any violations). Both SQL probe suites passed in rolled-back transactions; the applied migration returned 8/8 named security checks. Generated Supabase files received formatting-only normalization required by the repository lint. The platform dependency change had left npm's lockfile stale; it is synchronized without changing package versions beyond that existing platform update.
3 changes: 3 additions & 0 deletions scripts/check-rpc-security.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ const expected = [
"rls_invoker_reads",
"authenticated_transactions",
"plans_explicit_public_rows",
"account_reads_invoker",
"verified_telemetry_only",
"customization_purchase_required",
];
if (
error ||
Expand Down
67 changes: 67 additions & 0 deletions scripts/test-advanced-security.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
-- Transactional probes only: synthetic identities, no emails or charges.
BEGIN;
INSERT INTO auth.users(id,email,raw_user_meta_data) VALUES
('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01','security-owner@example.invalid','{}'),
('dddddddd-dddd-4ddd-8ddd-dddddddddd02','security-other@example.invalid','{}');
INSERT INTO public.user_roles(user_id,role) VALUES ('dddddddd-dddd-4ddd-8ddd-dddddddddd02','admin');
SELECT set_config('request.jwt.claims','{"sub":"dddddddd-dddd-4ddd-8ddd-dddddddddd02","role":"authenticated"}',true);
INSERT INTO public.packages(id,slug,name,type,description,author_id,is_published,review_status)
VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03','security-rollback-fixture','Fixture','skill','Rollback only','eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01',true,'approved');
INSERT INTO public.package_versions(package_id,version,system_prompt) VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03','0.1.0','Original approved content');
INSERT INTO public.packs(id,slug,name,description,price_credits) VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee04','security-rollback-pack','Fixture','Rollback only',10);
INSERT INTO public.credit_ledger(user_id,delta,balance_after,reason) VALUES ('dddddddd-dddd-4ddd-8ddd-dddddddddd02',77,77,'purchase');
INSERT INTO public.team_workspaces(id,name,owner_id) VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee05','Rollback workspace','dddddddd-dddd-4ddd-8ddd-dddddddddd02');
INSERT INTO public.team_invites(workspace_id,email,role,token_hash,created_by) VALUES ('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee05','security-owner@example.invalid','viewer',encode(extensions.digest('rollback-only-token','sha256'),'hex'),'dddddddd-dddd-4ddd-8ddd-dddddddddd02');
SET LOCAL ROLE authenticated;
SELECT set_config('request.jwt.claims','{"sub":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01","role":"authenticated","email":"security-owner@example.invalid"}',true);
DO $test$
DECLARE n int;
BEGIN
BEGIN
PERFORM public.team_action('accept',NULL,'{"token":"rollback-only-token"}');
RAISE EXCEPTION 'Unverified email joined workspace';
EXCEPTION WHEN insufficient_privilege THEN NULL; END;
IF public.get_credit_balance('dddddddd-dddd-4ddd-8ddd-dddddddddd02') <> 0 THEN RAISE EXCEPTION 'Cross-user credits leaked'; END IF;
UPDATE public.packages SET star_count=999 WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03';
IF (SELECT star_count FROM public.packages WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03') <> 0 THEN RAISE EXCEPTION 'Author forged stars'; END IF;
INSERT INTO public.package_stars(user_id,package_id) VALUES(auth.uid(),'eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03');
IF (SELECT star_count FROM public.packages WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03') <> 1 THEN RAISE EXCEPTION 'Legitimate star did not increment'; END IF;
DELETE FROM public.package_stars WHERE user_id=auth.uid() AND package_id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03';
IF (SELECT star_count FROM public.packages WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03') <> 0 THEN RAISE EXCEPTION 'Legitimate star did not decrement'; END IF;
UPDATE public.package_versions SET system_prompt='Bypass' WHERE package_id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03';
GET DIAGNOSTICS n=ROW_COUNT;
IF n<>0 THEN RAISE EXCEPTION 'Author changed approved content'; END IF;
BEGIN
INSERT INTO public.pack_customizations(user_id,pack_id,brief) VALUES(auth.uid(),'eeeeeeee-eeee-4eee-8eee-eeeeeeeeee04','Unauthorized customization');
RAISE EXCEPTION 'Unpurchased customization accepted';
EXCEPTION WHEN insufficient_privilege THEN NULL; END;
BEGIN
PERFORM public.mcp_check_and_log_call(auth.uid(),'probe','probe',false);
RAISE EXCEPTION 'User forged MCP log';
EXCEPTION WHEN insufficient_privilege THEN NULL; END;
BEGIN
PERFORM public.compute_skill_drift('eeeeeeee-eeee-4eee-8eee-eeeeeeeeee03');
RAISE EXCEPTION 'User read private drift';
EXCEPTION WHEN insufficient_privilege THEN NULL; END;
BEGIN
PERFORM public.report_skill_execution('security-rollback-fixture',true);
RAISE EXCEPTION 'User called internal telemetry RPC';
EXCEPTION WHEN insufficient_privilege THEN NULL; END;
END $test$;
RESET ROLE;
SELECT set_config('request.jwt.claims','{"role":"service_role"}',true);
SET LOCAL ROLE service_role;
SELECT public.report_skill_execution('security-rollback-fixture',true);
DO $test$
BEGIN
IF (public.get_skill_trust('security-rollback-fixture')->>'trust_score') IS NOT NULL THEN RAISE EXCEPTION 'Unverified telemetry inflated trust'; END IF;
IF (public.get_skill_trust('security-rollback-fixture')->>'battle_tested')::boolean THEN RAISE EXCEPTION 'Unverified battle badge'; END IF;
END $test$;
RESET ROLE;
UPDATE auth.users SET confirmation_sent_at=now()-interval '1 minute',email_confirmed_at=now() WHERE id='eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01';
SET LOCAL ROLE authenticated;
SELECT set_config('request.jwt.claims','{"sub":"eeeeeeee-eeee-4eee-8eee-eeeeeeeeee01","role":"authenticated","email":"security-owner@example.invalid"}',true);
SELECT public.team_action('accept',NULL,'{"token":"rollback-only-token"}');
RESET ROLE;
ROLLBACK;
SELECT 'passed' AS advanced_security_role_probes;
2 changes: 1 addition & 1 deletion scripts/test-security-boundaries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ 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
IF failures IS NOT NULL OR (SELECT count(*) FROM public.check_security_boundaries()) <> 8 THEN
RAISE EXCEPTION 'Security boundary regression: %', failures;
END IF;
END $test$;
Expand Down
Loading
Loading