Module: RlsMultiTenant::RlsHelper

Defined in:
lib/rls_multi_tenant/rls_helper.rb

Class Method Summary collapse

Class Method Details

.disable_rls_for_table(table_name) ⇒ Object

Disable RLS on a table



25
26
27
28
29
30
31
32
33
34
# File 'lib/rls_multi_tenant/rls_helper.rb', line 25

def disable_rls_for_table(table_name)
  # Drop policy
  policy_name = "#{table_name}_app_user"
  ActiveRecord::Base.connection.execute("DROP POLICY IF EXISTS #{policy_name} ON #{table_name}")

  # Disable RLS
  ActiveRecord::Base.connection.execute("ALTER TABLE #{table_name} DISABLE ROW LEVEL SECURITY, NO FORCE ROW LEVEL SECURITY")

  Rails.logger&.info "✅ RLS disabled for table #{table_name}"
end

.enable_rls_for_table(table_name, tenant_column: RlsMultiTenant.tenant_id_column) ⇒ Object

Enable RLS on a table with a policy



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rls_multi_tenant/rls_helper.rb', line 7

def enable_rls_for_table(table_name, tenant_column: RlsMultiTenant.tenant_id_column)
  # Enable RLS
  ActiveRecord::Base.connection.execute("ALTER TABLE #{table_name} ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY")

  # Create policy (drop if exists first)
  policy_name = "#{table_name}_app_user"
  ActiveRecord::Base.connection.execute("DROP POLICY IF EXISTS #{policy_name} ON #{table_name}")

  tenant_session_var = "rls.#{RlsMultiTenant.tenant_id_column}"
  policy_sql = "CREATE POLICY #{policy_name} ON #{table_name} " \
               "USING (#{tenant_column} = NULLIF(current_setting('#{tenant_session_var}', TRUE), '')::uuid)"

  ActiveRecord::Base.connection.execute(policy_sql)

  Rails.logger&.info "✅ RLS enabled for table #{table_name} with policy #{policy_name}"
end

.rls_enabled?(table_name) ⇒ Boolean

Check if RLS is enabled on a table

Returns:

  • (Boolean)


37
38
39
40
41
42
43
# File 'lib/rls_multi_tenant/rls_helper.rb', line 37

def rls_enabled?(table_name)
  result = ActiveRecord::Base.connection.execute(
    "SELECT relrowsecurity FROM pg_class WHERE relname = '#{table_name}'"
  ).first

  result&.dig('relrowsecurity') == true && result&.dig('relforcerowsecurity') == true
end

.rls_policies(table_name) ⇒ Object

Get all RLS policies for a table



46
47
48
49
50
# File 'lib/rls_multi_tenant/rls_helper.rb', line 46

def rls_policies(table_name)
  ActiveRecord::Base.connection.execute(
    "SELECT policyname, permissive, roles, cmd, qual FROM pg_policies WHERE tablename = '#{table_name}'"
  )
end