Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(settings): restrict organization updates to admins and lock server-managed columns (#755)
Gökhan Geyikd73c6f852c06
diff --git a/supabase/migrations/00062_organization_client_write_guard.sql b/supabase/migrations/00062_organization_client_write_guard.sqlnew file mode 100644index 000000000..25236fd24--- /dev/null+++ b/supabase/migrations/00062_organization_client_write_guard.sql@@ -0,0 +1,81 @@+-- Organizations: restrict client-side updates to admins, and keep+-- server-managed columns out of the client's reach entirely.+--+-- Two permissive UPDATE policies were in force. Postgres ORs permissive+-- policies together, so the wider of the two decided the outcome and the+-- admin restriction never applied. The wider policy's name states an intent+-- its WITH CHECK does not carry out: it names no columns, so it allowed a+-- row's every column to be rewritten by any member of the org.+--+-- Column-level intent cannot be expressed in a policy at all. WITH CHECK sees+-- only the new row, so "this column may not change" has nowhere to compare+-- against. A BEFORE UPDATE trigger can see both rows, and that is where the+-- rule belongs.++DROP POLICY IF EXISTS "Users cannot update plan fields directly" ON "public"."organizations";+DROP POLICY IF EXISTS "organizations: admin update" ON "public"."organizations";++-- USING picks the rows an admin may reach; WITH CHECK keeps the updated row+-- inside the same set, so an org cannot be handed to somebody else.+CREATE POLICY "organizations: admin update" ON "public"."organizations"+ FOR UPDATE+ USING (+ "id" IN (+ SELECT "profiles"."organization_id"+ FROM "public"."profiles"+ WHERE "profiles"."id" = "auth"."uid"()+ AND "profiles"."role" = 'admin'::"public"."user_role"+ )+ )+ WITH CHECK (+ "id" IN (+ SELECT "profiles"."organization_id"+ FROM "public"."profiles"+ WHERE "profiles"."id" = "auth"."uid"()+ AND "profiles"."role" = 'admin'::"public"."user_role"+ )+ );++-- Billing state belongs to Stripe and the webhook that mirrors it; the API key+-- columns hold ciphertext produced server-side. Neither is the client's to+-- write, admin or not.+CREATE OR REPLACE FUNCTION "public"."guard_organization_server_columns"()+RETURNS "trigger"+LANGUAGE "plpgsql"+SET "search_path" = ''+AS $$+BEGIN+ -- A role that already bypasses row-level security is server-side by+ -- definition -- the service role key, migrations, psql -- and this guard is+ -- not aimed at it. Everything else is a request carrying an end user's JWT.+ -- Naming the client roles instead would fail open on any role nobody+ -- thought of; asking about the privilege fails closed.+ IF (SELECT "rolbypassrls" FROM "pg_catalog"."pg_roles" WHERE "rolname" = current_user) THEN+ RETURN NEW;+ END IF;++ IF NEW."plan" IS DISTINCT FROM OLD."plan"+ OR NEW."plan_overrides" IS DISTINCT FROM OLD."plan_overrides"+ OR NEW."subscription_status" IS DISTINCT FROM OLD."subscription_status"+ OR NEW."subscription_ends_at" IS DISTINCT FROM OLD."subscription_ends_at"+ OR NEW."stripe_customer_id" IS DISTINCT FROM OLD."stripe_customer_id"+ OR NEW."stripe_subscription_id" IS DISTINCT FROM OLD."stripe_subscription_id"+ OR NEW."anthropic_api_key_encrypted" IS DISTINCT FROM OLD."anthropic_api_key_encrypted"+ OR NEW."anthropic_api_key_last4" IS DISTINCT FROM OLD."anthropic_api_key_last4"+ OR NEW."anthropic_api_key_set_at" IS DISTINCT FROM OLD."anthropic_api_key_set_at"+ OR NEW."anthropic_api_key_set_by" IS DISTINCT FROM OLD."anthropic_api_key_set_by"+ THEN+ RAISE EXCEPTION 'organization column is managed server-side and cannot be set from the client'+ USING ERRCODE = '42501';+ END IF;++ RETURN NEW;+END;+$$;++DROP TRIGGER IF EXISTS "organizations_guard_server_columns" ON "public"."organizations";++CREATE TRIGGER "organizations_guard_server_columns"+ BEFORE UPDATE ON "public"."organizations"+ FOR EACH ROW+ EXECUTE FUNCTION "public"."guard_organization_server_columns"();diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 87bcb1507..c3f819a6f 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -6254,3 +6254,88 @@ comment on function public.citations_urls(uuid, timestamptz, timestamptz, text[]comment on function public.citations_window_stats(uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[]) is'Answers scanned and regions observed in a Citations window (#732) — the denominator for every usage percentage, including answers that cite nothing.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00062_organization_client_write_guard.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Organizations: restrict client-side updates to admins, and keep+-- server-managed columns out of the client's reach entirely.+--+-- Two permissive UPDATE policies were in force. Postgres ORs permissive+-- policies together, so the wider of the two decided the outcome and the+-- admin restriction never applied. The wider policy's name states an intent+-- its WITH CHECK does not carry out: it names no columns, so it allowed a+-- row's every column to be rewritten by any member of the org.+--+-- Column-level intent cannot be expressed in a policy at all. WITH CHECK sees+-- only the new row, so "this column may not change" has nowhere to compare+-- against. A BEFORE UPDATE trigger can see both rows, and that is where the+-- rule belongs.++DROP POLICY IF EXISTS "Users cannot update plan fields directly" ON "public"."organizations";+DROP POLICY IF EXISTS "organizations: admin update" ON "public"."organizations";++-- USING picks the rows an admin may reach; WITH CHECK keeps the updated row+-- inside the same set, so an org cannot be handed to somebody else.+CREATE POLICY "organizations: admin update" ON "public"."organizations"+ FOR UPDATE+ USING (+ "id" IN (+ SELECT "profiles"."organization_id"+ FROM "public"."profiles"+ WHERE "profiles"."id" = "auth"."uid"()+ AND "profiles"."role" = 'admin'::"public"."user_role"+ )+ )+ WITH CHECK (+ "id" IN (+ SELECT "profiles"."organization_id"+ FROM "public"."profiles"+ WHERE "profiles"."id" = "auth"."uid"()+ AND "profiles"."role" = 'admin'::"public"."user_role"+ )+ );++-- Billing state belongs to Stripe and the webhook that mirrors it; the API key+-- columns hold ciphertext produced server-side. Neither is the client's to+-- write, admin or not.+CREATE OR REPLACE FUNCTION "public"."guard_organization_server_columns"()+RETURNS "trigger"+LANGUAGE "plpgsql"+SET "search_path" = ''+AS $$+BEGIN+ -- A role that already bypasses row-level security is server-side by+ -- definition -- the service role key, migrations, psql -- and this guard is+ -- not aimed at it. Everything else is a request carrying an end user's JWT.+ -- Naming the client roles instead would fail open on any role nobody+ -- thought of; asking about the privilege fails closed.+ IF (SELECT "rolbypassrls" FROM "pg_catalog"."pg_roles" WHERE "rolname" = current_user) THEN+ RETURN NEW;+ END IF;++ IF NEW."plan" IS DISTINCT FROM OLD."plan"+ OR NEW."plan_overrides" IS DISTINCT FROM OLD."plan_overrides"+ OR NEW."subscription_status" IS DISTINCT FROM OLD."subscription_status"+ OR NEW."subscription_ends_at" IS DISTINCT FROM OLD."subscription_ends_at"+ OR NEW."stripe_customer_id" IS DISTINCT FROM OLD."stripe_customer_id"+ OR NEW."stripe_subscription_id" IS DISTINCT FROM OLD."stripe_subscription_id"+ OR NEW."anthropic_api_key_encrypted" IS DISTINCT FROM OLD."anthropic_api_key_encrypted"+ OR NEW."anthropic_api_key_last4" IS DISTINCT FROM OLD."anthropic_api_key_last4"+ OR NEW."anthropic_api_key_set_at" IS DISTINCT FROM OLD."anthropic_api_key_set_at"+ OR NEW."anthropic_api_key_set_by" IS DISTINCT FROM OLD."anthropic_api_key_set_by"+ THEN+ RAISE EXCEPTION 'organization column is managed server-side and cannot be set from the client'+ USING ERRCODE = '42501';+ END IF;++ RETURN NEW;+END;+$$;++DROP TRIGGER IF EXISTS "organizations_guard_server_columns" ON "public"."organizations";++CREATE TRIGGER "organizations_guard_server_columns"+ BEFORE UPDATE ON "public"."organizations"+ FOR EACH ROW+ EXECUTE FUNCTION "public"."guard_organization_server_columns"();+diff --git a/web/src/app/api/stripe/checkout/route.ts b/web/src/app/api/stripe/checkout/route.tsindex 6ff1817a6..0243a15a6 100644--- a/web/src/app/api/stripe/checkout/route.ts+++ b/web/src/app/api/stripe/checkout/route.ts@@ -1,5 +1,6 @@import { NextRequest, NextResponse } from 'next/server';import { createClient } from '@/lib/supabase/server';+import { supabaseAdmin } from '@/lib/supabase/admin';import { stripe, PRICE_IDS } from '@/lib/stripe';export async function POST(req: NextRequest) {@@ -23,6 +24,20 @@ export async function POST(req: NextRequest) {return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });}+ // The org id arrives in the request body, so confirm the caller is+ // actually in it. Row-level security used to be the only thing standing+ // between this and another org's row; the customer id below is now+ // written with the service role, which answers to nothing but this check.+ const { data: callerProfile } = await supabase+ .from('profiles')+ .select('organization_id')+ .eq('id', user.id)+ .single();++ if (callerProfile?.organization_id !== organizationId) {+ return NextResponse.json({ error: 'Forbidden' }, { status: 403 });+ }+const priceId = PRICE_IDS[planId]?.monthly;if (!priceId) {console.error(@@ -54,7 +69,7 @@ export async function POST(req: NextRequest) {});customerId = customer.id;- await supabase+ await supabaseAdmin.from('organizations').update({ stripe_customer_id: customerId }).eq('id', organizationId);diff --git a/web/src/app/api/stripe/subscription/route.ts b/web/src/app/api/stripe/subscription/route.tsindex 52bffc486..56f5ced48 100644--- a/web/src/app/api/stripe/subscription/route.ts+++ b/web/src/app/api/stripe/subscription/route.ts@@ -1,5 +1,6 @@import { NextRequest, NextResponse } from 'next/server';import { createClient } from '@/lib/supabase/server';+import { supabaseAdmin } from '@/lib/supabase/admin';import { stripe, PRICE_IDS } from '@/lib/stripe';import { SUBSCRIBABLE_PLANS } from '@/config/plans';import { alignPromptsToPlanForOrg } from '@/lib/plan-engines';@@ -170,9 +171,10 @@ export async function PATCH(req: NextRequest) {proration_behavior: 'create_prorations',})) as unknown as SubscriptionRaw;- // Optimistic DB update- const supabase = await createClient();- await supabase.from('organizations').update({ plan: newPlanId }).eq('id', org.id);+ // Optimistic DB update. Stripe has already accepted the plan change, so+ // this is the server mirroring its own decision, not the caller writing+ // their own plan — hence the service role, same as the webhook.+ await supabaseAdmin.from('organizations').update({ plan: newPlanId }).eq('id', org.id);// Align prompts to the new plan's engine set so an upgrade actually// expands (Starter → Growth: 2 → 8 engines) or trims (Growth → Starter: