From dd95b992385f86db45b22430f98481a78a96023b Mon Sep 17 00:00:00 2001 From: "gpt-engineer-app[bot]" <159125892+gpt-engineer-app[bot]@users.noreply.github.com> Date: Fri, 17 Oct 2025 20:06:00 +0000 Subject: [PATCH] Fix: Update RLS policies for MFA checks --- src/integrations/supabase/types.ts | 4 ++ ...9_92d5e46f-745a-4570-8bd7-614f27deaf7c.sql | 52 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 supabase/migrations/20251017200539_92d5e46f-745a-4570-8bd7-614f27deaf7c.sql diff --git a/src/integrations/supabase/types.ts b/src/integrations/supabase/types.ts index d3254343..239ad5cb 100644 --- a/src/integrations/supabase/types.ts +++ b/src/integrations/supabase/types.ts @@ -3668,6 +3668,10 @@ export type Database = { Args: Record Returns: boolean } + has_mfa_enabled: { + Args: { _user_id: string } + Returns: boolean + } has_pending_dependents: { Args: { item_id: string } Returns: boolean diff --git a/supabase/migrations/20251017200539_92d5e46f-745a-4570-8bd7-614f27deaf7c.sql b/supabase/migrations/20251017200539_92d5e46f-745a-4570-8bd7-614f27deaf7c.sql new file mode 100644 index 00000000..4c88c322 --- /dev/null +++ b/supabase/migrations/20251017200539_92d5e46f-745a-4570-8bd7-614f27deaf7c.sql @@ -0,0 +1,52 @@ +-- Create SECURITY DEFINER function to safely check MFA enrollment +CREATE OR REPLACE FUNCTION public.has_mfa_enabled(_user_id uuid) +RETURNS boolean +LANGUAGE sql +STABLE +SECURITY DEFINER +SET search_path = auth, public +AS $$ + SELECT EXISTS ( + SELECT 1 + FROM auth.mfa_factors + WHERE user_id = _user_id + AND status = 'verified' + ); +$$; + +GRANT EXECUTE ON FUNCTION public.has_mfa_enabled(uuid) TO authenticated; + +-- Drop all existing policies on user_roles +DROP POLICY IF EXISTS "Users can view their own roles" ON public.user_roles; +DROP POLICY IF EXISTS "Moderators can manage roles" ON public.user_roles; +DROP POLICY IF EXISTS "Admins can assign moderator roles" ON public.user_roles; +DROP POLICY IF EXISTS "Users can delete their own user role" ON public.user_roles; +DROP POLICY IF EXISTS "Users can insert their own roles" ON public.user_roles; + +-- Recreate policies using has_mfa_enabled() function +CREATE POLICY "Users can view their own roles" +ON public.user_roles +FOR SELECT +TO authenticated +USING (auth.uid() = user_id); + +CREATE POLICY "Moderators can manage roles" +ON public.user_roles +FOR ALL +TO authenticated +USING ( + is_moderator(auth.uid()) AND + (NOT has_mfa_enabled(auth.uid()) OR has_aal2()) +) +WITH CHECK ( + is_moderator(auth.uid()) AND + (NOT has_mfa_enabled(auth.uid()) OR has_aal2()) +); + +CREATE POLICY "Users can delete their own user role" +ON public.user_roles +FOR DELETE +TO authenticated +USING (auth.uid() = user_id AND role = 'user'); + +GRANT SELECT ON public.user_roles TO authenticated; \ No newline at end of file