Fix/critical issues (#351)
* fix: add 15s timeout to accounting provider HTTP clients Node's built-in fetch has no default timeout, so a stalled provider could hold a serverless worker open for many minutes — worse with withRetry (6x on Fortnox, 3x on others) and getPaginated stacking across pages. Wrap each fetch() in the Fortnox, Visma, Bokio, Briox, and Björn Lundén clients with signal: AbortSignal.timeout(15_000), and treat TimeoutError/AbortError as retryable so a single stalled attempt retries cleanly instead of hanging the request. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: add timeouts to OAuth token endpoints Wrap every OAuth2 token exchange, refresh, and revoke POST in an AbortController via a new fetchWithTimeout helper. Without this, a hung provider endpoint holds the request thread indefinitely — worst case being Skatteverket, where refreshAccessToken sits on the hot path of every bookkeeping action and exchangeCodeForTokens races the 5-minute BankID auth-code TTL. On timeout, the Skatteverket OAuth callback now redirects to /reports?tab=vat-declaration with a Swedish retry message instead of leaving the user stranded on the callback URL. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: close RLS escalation on membership and settings tables Any authenticated user who was a member (including viewer) could issue a direct PostgREST PATCH against company_members and promote themselves to owner, bypassing the app-layer requireWritePermission guard entirely. Reproduced on prod, then verified the fix on staging. Tighten INSERT/UPDATE/DELETE policies on company_members, team_members, api_keys, company_invitations, team_invitations, companies, teams, and company_settings to require the caller to hold role IN ('owner','admin') in the target company/team. Role check is wrapped in SECURITY DEFINER helpers (user_is_company_admin, user_is_team_admin, user_role_in_company) to avoid RLS recursion when a policy on company_members references company_members in its subquery. Add a BEFORE UPDATE trigger on company_members that rejects any role change unless the caller already holds role='owner', so admins cannot mint further owners even though they can otherwise write. Legitimate write paths are unaffected: company creation goes through the create_company_with_owner SECURITY DEFINER RPC, invite acceptance uses the service role, and team->company membership syncs via SECURITY DEFINER triggers. All bypass RLS. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(migrations): resolve duplicate schema_migrations version 20260421160000 Two migration files shared timestamp 20260421160000 on main (booking_template_usage.sql and opening_balances_rpc.sql), causing supabase_migrations.schema_migrations PK collisions on any fresh CI run: duplicate key value violates unique constraint "schema_migrations_pkey" Key (version)=(20260421160000) already exists. Bump opening_balances_rpc.sql to 20260421160500. booking_template_usage keeps 20260421160000 because its table already exists on prod; the renamed file has an idempotent CREATE OR REPLACE FUNCTION body and has not yet been deployed to prod, so moving its version is free. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(migrations): make booking_template_usage migration idempotent The table already exists on prod (applied out-of-band) but prod's schema_migrations does not track version 20260421160000, so the next PR-driven deploy would re-run this migration and fail on `CREATE TABLE public.booking_template_usage` with a duplicate-relation error. Add IF NOT EXISTS to CREATE TABLE and CREATE INDEX, and DROP POLICY IF EXISTS before each CREATE POLICY. No functional change on fresh databases; prod just silently no-ops the table/index creates and re-declares policies without dropping-then-missing them. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: implement isTimeoutError utility and enforce role restrictions on company_members insert * fix: implement fallback for user_id in commit_journal_entry function when auth.uid() is NULL --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
e13a450e21
commit
02f94ef631
@@ -12,7 +12,7 @@
|
||||
--
|
||||
-- One row per (template_id, company_id). Upsert on use.
|
||||
|
||||
CREATE TABLE public.booking_template_usage (
|
||||
CREATE TABLE IF NOT EXISTS public.booking_template_usage (
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
template_id UUID NOT NULL REFERENCES public.booking_template_library(id) ON DELETE CASCADE,
|
||||
company_id UUID NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
@@ -25,28 +25,32 @@ CREATE TABLE public.booking_template_usage (
|
||||
-- RLS
|
||||
ALTER TABLE public.booking_template_usage ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
DROP POLICY IF EXISTS "btu_select" ON public.booking_template_usage;
|
||||
CREATE POLICY "btu_select" ON public.booking_template_usage
|
||||
FOR SELECT USING (
|
||||
company_id IN (SELECT public.user_company_ids())
|
||||
);
|
||||
|
||||
DROP POLICY IF EXISTS "btu_insert" ON public.booking_template_usage;
|
||||
CREATE POLICY "btu_insert" ON public.booking_template_usage
|
||||
FOR INSERT WITH CHECK (
|
||||
company_id IN (SELECT public.user_company_ids())
|
||||
);
|
||||
|
||||
DROP POLICY IF EXISTS "btu_update" ON public.booking_template_usage;
|
||||
CREATE POLICY "btu_update" ON public.booking_template_usage
|
||||
FOR UPDATE USING (
|
||||
company_id IN (SELECT public.user_company_ids())
|
||||
);
|
||||
|
||||
DROP POLICY IF EXISTS "btu_delete" ON public.booking_template_usage;
|
||||
CREATE POLICY "btu_delete" ON public.booking_template_usage
|
||||
FOR DELETE USING (
|
||||
company_id IN (SELECT public.user_company_ids())
|
||||
);
|
||||
|
||||
-- Index for the sort query: fetch last_used_at for a given company.
|
||||
CREATE INDEX idx_btu_company_last_used
|
||||
CREATE INDEX IF NOT EXISTS idx_btu_company_last_used
|
||||
ON public.booking_template_usage (company_id, last_used_at DESC);
|
||||
|
||||
-- Schema reload for PostgREST
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
-- =============================================================================
|
||||
-- Fix RLS escalation across multi-tenant authorization layer.
|
||||
--
|
||||
-- The INSERT/UPDATE/DELETE policies defined in
|
||||
-- 20260330130000_multi_tenant_company_refactor.sql
|
||||
-- 20260330140000_company_invitations.sql
|
||||
-- 20260331010000_teams_table_refactor.sql
|
||||
-- gated writes only on `user_company_ids()` / `user_team_ids()` — i.e. any
|
||||
-- membership regardless of role. This allowed a user with role='viewer' to
|
||||
-- issue a direct PATCH against PostgREST and promote themselves to 'owner'
|
||||
-- (confirmed in production), bypassing the app-layer requireWritePermission
|
||||
-- guard entirely.
|
||||
--
|
||||
-- Fix: require the caller to hold role IN ('owner','admin') in the target
|
||||
-- company/team for every write on the authorization-sensitive tables. All
|
||||
-- legitimate app flows write via service role or SECURITY DEFINER RPCs/
|
||||
-- triggers, which bypass RLS — so these tightened policies only block
|
||||
-- direct PostgREST calls from user sessions, which was the exploit path.
|
||||
--
|
||||
-- Role check is wrapped in SECURITY DEFINER helpers (user_is_company_admin,
|
||||
-- user_is_team_admin) matching the existing user_company_ids() pattern.
|
||||
-- This is necessary because inlining `EXISTS (SELECT ... FROM company_members)`
|
||||
-- inside a policy ON company_members is detected by Postgres as recursive.
|
||||
-- SECURITY DEFINER functions bypass RLS internally, breaking the cycle.
|
||||
--
|
||||
-- Additionally: a BEFORE UPDATE trigger on company_members blocks any role
|
||||
-- change unless the caller already holds role='owner'. This reserves
|
||||
-- promotion to 'owner' (or demotion of one) to existing owners — admins
|
||||
-- cannot mint further owners even though they can otherwise write.
|
||||
-- =============================================================================
|
||||
|
||||
-- =============================================================================
|
||||
-- 1. SECURITY DEFINER helper functions
|
||||
-- =============================================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.user_is_company_admin(p_company_id uuid)
|
||||
RETURNS boolean
|
||||
LANGUAGE sql
|
||||
STABLE
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM public.company_members cm
|
||||
WHERE cm.company_id = p_company_id
|
||||
AND cm.user_id = auth.uid()
|
||||
AND cm.role IN ('owner', 'admin')
|
||||
);
|
||||
$$;
|
||||
|
||||
GRANT EXECUTE ON FUNCTION public.user_is_company_admin(uuid) TO authenticated;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.user_is_team_admin(p_team_id uuid)
|
||||
RETURNS boolean
|
||||
LANGUAGE sql
|
||||
STABLE
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM public.team_members tm
|
||||
WHERE tm.team_id = p_team_id
|
||||
AND tm.user_id = auth.uid()
|
||||
AND tm.role IN ('owner', 'admin')
|
||||
) OR EXISTS (
|
||||
SELECT 1 FROM public.teams t
|
||||
WHERE t.id = p_team_id
|
||||
AND t.created_by = auth.uid()
|
||||
);
|
||||
$$;
|
||||
|
||||
GRANT EXECUTE ON FUNCTION public.user_is_team_admin(uuid) TO authenticated;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.user_role_in_company(p_company_id uuid)
|
||||
RETURNS text
|
||||
LANGUAGE sql
|
||||
STABLE
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
SELECT role FROM public.company_members
|
||||
WHERE company_id = p_company_id AND user_id = auth.uid();
|
||||
$$;
|
||||
|
||||
GRANT EXECUTE ON FUNCTION public.user_role_in_company(uuid) TO authenticated;
|
||||
|
||||
-- =============================================================================
|
||||
-- 2. company_members — tighten write policies
|
||||
-- =============================================================================
|
||||
|
||||
DROP POLICY IF EXISTS "company_members_insert" ON public.company_members;
|
||||
DROP POLICY IF EXISTS "company_members_update" ON public.company_members;
|
||||
DROP POLICY IF EXISTS "company_members_delete" ON public.company_members;
|
||||
|
||||
CREATE POLICY "company_members_insert" ON public.company_members
|
||||
FOR INSERT WITH CHECK (public.user_is_company_admin(company_id));
|
||||
|
||||
CREATE POLICY "company_members_update" ON public.company_members
|
||||
FOR UPDATE
|
||||
USING (public.user_is_company_admin(company_id))
|
||||
WITH CHECK (public.user_is_company_admin(company_id));
|
||||
|
||||
CREATE POLICY "company_members_delete" ON public.company_members
|
||||
FOR DELETE USING (public.user_is_company_admin(company_id));
|
||||
|
||||
-- =============================================================================
|
||||
-- 3. team_members — tighten write policies
|
||||
-- =============================================================================
|
||||
|
||||
DROP POLICY IF EXISTS "team_members_insert" ON public.team_members;
|
||||
DROP POLICY IF EXISTS "team_members_update" ON public.team_members;
|
||||
DROP POLICY IF EXISTS "team_members_delete" ON public.team_members;
|
||||
|
||||
CREATE POLICY "team_members_insert" ON public.team_members
|
||||
FOR INSERT WITH CHECK (public.user_is_team_admin(team_id));
|
||||
|
||||
CREATE POLICY "team_members_update" ON public.team_members
|
||||
FOR UPDATE
|
||||
USING (public.user_is_team_admin(team_id))
|
||||
WITH CHECK (public.user_is_team_admin(team_id));
|
||||
|
||||
CREATE POLICY "team_members_delete" ON public.team_members
|
||||
FOR DELETE USING (public.user_is_team_admin(team_id));
|
||||
|
||||
-- =============================================================================
|
||||
-- 4. api_keys — tighten write policies
|
||||
-- A viewer minting an API key with broad scopes is catastrophic.
|
||||
-- =============================================================================
|
||||
|
||||
DROP POLICY IF EXISTS "api_keys_insert" ON public.api_keys;
|
||||
DROP POLICY IF EXISTS "api_keys_update" ON public.api_keys;
|
||||
DROP POLICY IF EXISTS "api_keys_delete" ON public.api_keys;
|
||||
|
||||
CREATE POLICY "api_keys_insert" ON public.api_keys
|
||||
FOR INSERT WITH CHECK (public.user_is_company_admin(company_id));
|
||||
|
||||
CREATE POLICY "api_keys_update" ON public.api_keys
|
||||
FOR UPDATE
|
||||
USING (public.user_is_company_admin(company_id))
|
||||
WITH CHECK (public.user_is_company_admin(company_id));
|
||||
|
||||
CREATE POLICY "api_keys_delete" ON public.api_keys
|
||||
FOR DELETE USING (public.user_is_company_admin(company_id));
|
||||
|
||||
-- =============================================================================
|
||||
-- 5. company_invitations — tighten write policies
|
||||
-- =============================================================================
|
||||
|
||||
DROP POLICY IF EXISTS "company_invitations_insert" ON public.company_invitations;
|
||||
DROP POLICY IF EXISTS "company_invitations_update" ON public.company_invitations;
|
||||
DROP POLICY IF EXISTS "company_invitations_delete" ON public.company_invitations;
|
||||
|
||||
CREATE POLICY "company_invitations_insert" ON public.company_invitations
|
||||
FOR INSERT WITH CHECK (public.user_is_company_admin(company_id));
|
||||
|
||||
CREATE POLICY "company_invitations_update" ON public.company_invitations
|
||||
FOR UPDATE
|
||||
USING (public.user_is_company_admin(company_id))
|
||||
WITH CHECK (public.user_is_company_admin(company_id));
|
||||
|
||||
CREATE POLICY "company_invitations_delete" ON public.company_invitations
|
||||
FOR DELETE USING (public.user_is_company_admin(company_id));
|
||||
|
||||
-- =============================================================================
|
||||
-- 6. team_invitations — tighten write policies
|
||||
-- =============================================================================
|
||||
|
||||
DROP POLICY IF EXISTS "team_invitations_insert" ON public.team_invitations;
|
||||
DROP POLICY IF EXISTS "team_invitations_update" ON public.team_invitations;
|
||||
DROP POLICY IF EXISTS "team_invitations_delete" ON public.team_invitations;
|
||||
|
||||
CREATE POLICY "team_invitations_insert" ON public.team_invitations
|
||||
FOR INSERT WITH CHECK (public.user_is_team_admin(team_id));
|
||||
|
||||
CREATE POLICY "team_invitations_update" ON public.team_invitations
|
||||
FOR UPDATE
|
||||
USING (public.user_is_team_admin(team_id))
|
||||
WITH CHECK (public.user_is_team_admin(team_id));
|
||||
|
||||
CREATE POLICY "team_invitations_delete" ON public.team_invitations
|
||||
FOR DELETE USING (public.user_is_team_admin(team_id));
|
||||
|
||||
-- =============================================================================
|
||||
-- 7. companies — tighten UPDATE policy (INSERT keeps created_by check)
|
||||
-- =============================================================================
|
||||
|
||||
DROP POLICY IF EXISTS "companies_update" ON public.companies;
|
||||
|
||||
CREATE POLICY "companies_update" ON public.companies
|
||||
FOR UPDATE
|
||||
USING (public.user_is_company_admin(id))
|
||||
WITH CHECK (public.user_is_company_admin(id));
|
||||
|
||||
-- =============================================================================
|
||||
-- 8. teams — tighten UPDATE policy (INSERT keeps created_by check)
|
||||
-- =============================================================================
|
||||
|
||||
DROP POLICY IF EXISTS "teams_update" ON public.teams;
|
||||
|
||||
CREATE POLICY "teams_update" ON public.teams
|
||||
FOR UPDATE
|
||||
USING (public.user_is_team_admin(id) OR created_by = auth.uid())
|
||||
WITH CHECK (public.user_is_team_admin(id) OR created_by = auth.uid());
|
||||
|
||||
-- =============================================================================
|
||||
-- 9. company_settings — tighten write policies
|
||||
-- =============================================================================
|
||||
|
||||
DROP POLICY IF EXISTS "company_settings_insert" ON public.company_settings;
|
||||
DROP POLICY IF EXISTS "company_settings_update" ON public.company_settings;
|
||||
|
||||
CREATE POLICY "company_settings_insert" ON public.company_settings
|
||||
FOR INSERT WITH CHECK (public.user_is_company_admin(company_id));
|
||||
|
||||
CREATE POLICY "company_settings_update" ON public.company_settings
|
||||
FOR UPDATE
|
||||
USING (public.user_is_company_admin(company_id))
|
||||
WITH CHECK (public.user_is_company_admin(company_id));
|
||||
|
||||
-- =============================================================================
|
||||
-- 10. BEFORE UPDATE trigger on company_members:
|
||||
-- block role transitions unless the caller already holds role='owner'.
|
||||
-- Service role / SECURITY DEFINER / direct SQL (migration apply) pass through
|
||||
-- because auth.uid() is NULL in those contexts.
|
||||
-- =============================================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.enforce_company_member_role_transitions()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
caller_role text;
|
||||
BEGIN
|
||||
-- Service role, SECURITY DEFINER cascades, and direct SQL have no auth context.
|
||||
IF auth.uid() IS NULL THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
-- Nothing to enforce if the role field isn't changing.
|
||||
IF NEW.role IS NOT DISTINCT FROM OLD.role THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
caller_role := public.user_role_in_company(OLD.company_id);
|
||||
|
||||
IF caller_role IS DISTINCT FROM 'owner' THEN
|
||||
RAISE EXCEPTION
|
||||
'Only owners can change member roles (your role: %)',
|
||||
COALESCE(caller_role, 'none');
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
DROP TRIGGER IF EXISTS enforce_company_member_role_transitions
|
||||
ON public.company_members;
|
||||
|
||||
CREATE TRIGGER enforce_company_member_role_transitions
|
||||
BEFORE UPDATE ON public.company_members
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.enforce_company_member_role_transitions();
|
||||
|
||||
-- Force PostgREST to pick up the new policies immediately.
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,80 @@
|
||||
-- =============================================================================
|
||||
-- Close INSERT bypass in company_members owner-role guard.
|
||||
--
|
||||
-- 20260422120000_fix_rls_role_gates_on_membership_tables.sql added a
|
||||
-- BEFORE UPDATE trigger that blocks non-owners from promoting members to
|
||||
-- role='owner'. The trigger fires only on UPDATE, and the INSERT policy
|
||||
-- (company_members_insert) passes any caller with role IN ('owner','admin')
|
||||
-- with no constraint on NEW.role. An admin could therefore bypass the guard
|
||||
-- entirely via a direct PostgREST INSERT with role='owner', contradicting
|
||||
-- the stated guarantee that only owners can mint further owners.
|
||||
--
|
||||
-- Fix: add a BEFORE INSERT trigger that blocks role='owner' unless the
|
||||
-- caller already holds role='owner' in the target company.
|
||||
--
|
||||
-- Bootstrap case: create_company_with_owner() (SECURITY DEFINER RPC)
|
||||
-- preserves auth.uid() while inserting the first owner membership for a
|
||||
-- freshly created company. The trigger must allow this path. The helper
|
||||
-- user_role_in_company() returns NULL at that moment (no prior membership),
|
||||
-- so we permit the insert when (a) the caller is inserting themselves and
|
||||
-- (b) the company has no existing owner. Both conditions together pin the
|
||||
-- escape hatch to genuine first-time bootstrap; a subsequent attempt to
|
||||
-- inject a second owner fails on condition (b).
|
||||
-- =============================================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.enforce_company_member_role_on_insert()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
caller_role text;
|
||||
BEGIN
|
||||
-- Service role and direct SQL (migration apply, admin console) have no
|
||||
-- auth context; pass through unchanged.
|
||||
IF auth.uid() IS NULL THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
-- Only the 'owner' role is gated; admin/member/viewer pass through so that
|
||||
-- admins retain the ability to add non-owner members.
|
||||
IF NEW.role IS DISTINCT FROM 'owner' THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
caller_role := public.user_role_in_company(NEW.company_id);
|
||||
|
||||
-- Existing owners can always mint owners.
|
||||
IF caller_role = 'owner' THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
-- Bootstrap: create_company_with_owner RPC inserts the first owner
|
||||
-- membership. The caller has no prior membership (caller_role IS NULL)
|
||||
-- and inserts themselves. Reject if an owner already exists to prevent
|
||||
-- this path from being reused to mint a second owner.
|
||||
IF caller_role IS NULL
|
||||
AND NEW.user_id = auth.uid()
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM public.company_members
|
||||
WHERE company_id = NEW.company_id
|
||||
AND role = 'owner'
|
||||
)
|
||||
THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
RAISE EXCEPTION
|
||||
'Only owners can add members with role ''owner'' (your role: %)',
|
||||
COALESCE(caller_role, 'none');
|
||||
END;
|
||||
$$;
|
||||
|
||||
DROP TRIGGER IF EXISTS enforce_company_member_role_on_insert
|
||||
ON public.company_members;
|
||||
|
||||
CREATE TRIGGER enforce_company_member_role_on_insert
|
||||
BEFORE INSERT ON public.company_members
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION public.enforce_company_member_role_on_insert();
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
Reference in New Issue
Block a user