feat(tenant): enforce tenant isolation with row-level security
Every query runs inside a transaction carrying app.org_id, app.user_id or the explicit system scope. Without a scope no rows are visible. Closes #2 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
95da376ac1
commit
ccc0fe58b8
4 files changed
+318
No files matched your search
@@ -0,0 +1,53 @@
|
||||
-- +goose Up
|
||||
-- Tenant context is carried in transaction-local settings (set_config(..., true)).
|
||||
-- Without any setting nothing is visible, so a forgotten scope fails closed.
|
||||
-- app.scope = 'system' is reserved for cross-tenant work such as scheduling.
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION app_scope_system() RETURNS boolean
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT coalesce(current_setting('app.scope', true), '') = 'system'
|
||||
$$;
|
||||
|
||||
CREATE FUNCTION app_org_id() RETURNS uuid
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT nullif(current_setting('app.org_id', true), '')::uuid
|
||||
$$;
|
||||
|
||||
CREATE FUNCTION app_user_id() RETURNS uuid
|
||||
LANGUAGE sql STABLE AS $$
|
||||
SELECT nullif(current_setting('app.user_id', true), '')::uuid
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
ALTER TABLE orgs ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE orgs FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY orgs_read ON orgs FOR SELECT
|
||||
USING (
|
||||
app_scope_system() OR id = app_org_id()
|
||||
OR EXISTS (SELECT 1 FROM memberships m WHERE m.org_id = orgs.id AND m.user_id = app_user_id())
|
||||
);
|
||||
CREATE POLICY orgs_write ON orgs FOR ALL
|
||||
USING (app_scope_system() OR id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR id = app_org_id());
|
||||
|
||||
ALTER TABLE memberships ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE memberships FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY memberships_read ON memberships FOR SELECT
|
||||
USING (app_scope_system() OR org_id = app_org_id() OR user_id = app_user_id());
|
||||
CREATE POLICY memberships_write ON memberships FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
-- +goose Down
|
||||
DROP POLICY memberships_write ON memberships;
|
||||
DROP POLICY memberships_read ON memberships;
|
||||
ALTER TABLE memberships NO FORCE ROW LEVEL SECURITY;
|
||||
ALTER TABLE memberships DISABLE ROW LEVEL SECURITY;
|
||||
DROP POLICY orgs_write ON orgs;
|
||||
DROP POLICY orgs_read ON orgs;
|
||||
ALTER TABLE orgs NO FORCE ROW LEVEL SECURITY;
|
||||
ALTER TABLE orgs DISABLE ROW LEVEL SECURITY;
|
||||
DROP FUNCTION app_user_id();
|
||||
DROP FUNCTION app_org_id();
|
||||
DROP FUNCTION app_scope_system();
|
||||
Reference in new issue
Block a user