activerecord-rls 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.devcontainer/Dockerfile +24 -0
- data/.devcontainer/compose.yaml +42 -0
- data/.devcontainer/devcontainer.json +22 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +10 -0
- data/LICENSE.txt +21 -0
- data/README.md +511 -0
- data/Rakefile +12 -0
- data/gemfiles/common.gemfile +12 -0
- data/gemfiles/rails_7.2.gemfile +9 -0
- data/gemfiles/rails_8.0.gemfile +9 -0
- data/gemfiles/rails_8.1.gemfile +9 -0
- data/lib/active_record/rls/command_recorders/default_privileges.rb +25 -0
- data/lib/active_record/rls/command_recorders/policies.rb +38 -0
- data/lib/active_record/rls/command_recorders/privileges.rb +25 -0
- data/lib/active_record/rls/command_recorders/rls_policies.rb +41 -0
- data/lib/active_record/rls/command_recorders/roles.rb +25 -0
- data/lib/active_record/rls/migration_methods.rb +45 -0
- data/lib/active_record/rls/model.rb +54 -0
- data/lib/active_record/rls/schema_dumper.rb +186 -0
- data/lib/active_record/rls/statements/default_privileges.rb +77 -0
- data/lib/active_record/rls/statements/policies.rb +125 -0
- data/lib/active_record/rls/statements/privileges.rb +233 -0
- data/lib/active_record/rls/statements/quoting.rb +60 -0
- data/lib/active_record/rls/statements/rls_policies.rb +50 -0
- data/lib/active_record/rls/statements/roles.rb +155 -0
- data/lib/active_record/rls/statements/runtime_variables.rb +60 -0
- data/lib/active_record/rls/test_databases.rb +15 -0
- data/lib/active_record/rls/version.rb +7 -0
- data/lib/active_record/rls.rb +77 -0
- metadata +135 -0
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord
|
|
4
|
+
module RLS
|
|
5
|
+
module Statements
|
|
6
|
+
module Privileges
|
|
7
|
+
include Quoting
|
|
8
|
+
|
|
9
|
+
Privilege = Struct.new(:object_type, :object, :schema, :role, :privileges, :columns, :arguments) do
|
|
10
|
+
def use_arguments?
|
|
11
|
+
!!object && !!arguments
|
|
12
|
+
end
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def all_privileges(schema: schema_names, ignore_tables: [])
|
|
16
|
+
privileges = execute <<~SQL
|
|
17
|
+
SELECT *
|
|
18
|
+
FROM (
|
|
19
|
+
/* Memberships */
|
|
20
|
+
SELECT NULL::varchar AS object_type,
|
|
21
|
+
NULL::varchar AS object,
|
|
22
|
+
NULL::varchar AS schema,
|
|
23
|
+
pg_auth_members.member::regrole::varchar AS role,
|
|
24
|
+
array_agg(DISTINCT pg_auth_members.roleid::regrole::varchar) AS privileges,
|
|
25
|
+
NULL::name[] AS columns,
|
|
26
|
+
NULL::varchar AS arguments
|
|
27
|
+
FROM pg_catalog.pg_auth_members
|
|
28
|
+
WHERE roleid::regrole::varchar NOT LIKE 'pg_%'
|
|
29
|
+
GROUP BY pg_auth_members.member
|
|
30
|
+
UNION
|
|
31
|
+
/* Tables and Sequences */
|
|
32
|
+
SELECT CASE
|
|
33
|
+
WHEN pg_class.relkind IN ('r', 't', 'v', 'm', 'f', 'p') THEN 'TABLE'
|
|
34
|
+
WHEN pg_class.relkind = 'S' THEN 'SEQUENCE'
|
|
35
|
+
END AS object_type,
|
|
36
|
+
pg_class.relname AS object,
|
|
37
|
+
pg_namespace.nspname AS schema,
|
|
38
|
+
CASE
|
|
39
|
+
WHEN a.grantee = 0 THEN 'public'
|
|
40
|
+
ELSE a.grantee::regrole::varchar
|
|
41
|
+
END AS role,
|
|
42
|
+
array_agg(DISTINCT a.privilege_type) AS privileges,
|
|
43
|
+
NULL::name[] AS columns,
|
|
44
|
+
NULL::varchar AS arguments
|
|
45
|
+
FROM pg_catalog.pg_class
|
|
46
|
+
JOIN pg_catalog.pg_namespace ON pg_class.relnamespace = pg_namespace.oid
|
|
47
|
+
JOIN aclexplode(pg_class.relacl) AS a ON true
|
|
48
|
+
WHERE pg_class.relkind IN ('r', 'S', 't', 'v', 'm', 'f', 'p')
|
|
49
|
+
AND (pg_class.relkind = 'S' OR NOT pg_class.relname = ANY (#{quote_text_array ignore_tables}))
|
|
50
|
+
GROUP BY pg_class.relname, pg_namespace.nspname, pg_class.relkind, a.grantee
|
|
51
|
+
UNION
|
|
52
|
+
/* Columns */
|
|
53
|
+
SELECT 'TABLE' AS object_type,
|
|
54
|
+
pg_class.relname AS object,
|
|
55
|
+
pg_namespace.nspname AS schema,
|
|
56
|
+
CASE
|
|
57
|
+
WHEN a.grantee = 0 THEN 'public'
|
|
58
|
+
ELSE a.grantee::regrole::varchar
|
|
59
|
+
END AS role,
|
|
60
|
+
array_agg(DISTINCT a.privilege_type) AS privileges,
|
|
61
|
+
array_agg(DISTINCT pg_attribute.attname) AS columns,
|
|
62
|
+
NULL::varchar AS arguments
|
|
63
|
+
FROM pg_catalog.pg_attribute
|
|
64
|
+
JOIN pg_catalog.pg_class ON pg_attribute.attrelid = pg_class.oid
|
|
65
|
+
JOIN pg_catalog.pg_namespace ON pg_class.relnamespace = pg_namespace.oid
|
|
66
|
+
JOIN aclexplode(pg_attribute.attacl) AS a ON true
|
|
67
|
+
/* Grouped by privilege type so each privilege keeps only the columns it was granted on. */
|
|
68
|
+
GROUP BY pg_class.relname, pg_namespace.nspname, a.grantee, a.privilege_type
|
|
69
|
+
UNION
|
|
70
|
+
/* Databases */
|
|
71
|
+
SELECT 'DATABASE' AS object_type,
|
|
72
|
+
pg_database.datname AS object,
|
|
73
|
+
NULL::varchar AS schema,
|
|
74
|
+
CASE
|
|
75
|
+
WHEN a.grantee = 0 THEN 'public'
|
|
76
|
+
ELSE a.grantee::regrole::varchar
|
|
77
|
+
END AS role,
|
|
78
|
+
array_agg(DISTINCT a.privilege_type) AS privileges,
|
|
79
|
+
NULL::name[] AS columns,
|
|
80
|
+
NULL::varchar AS arguments
|
|
81
|
+
FROM pg_catalog.pg_database
|
|
82
|
+
JOIN aclexplode(pg_database.datacl) AS a ON true
|
|
83
|
+
WHERE pg_database.datistemplate IS FALSE
|
|
84
|
+
GROUP BY pg_database.datname, a.grantee
|
|
85
|
+
UNION
|
|
86
|
+
/* Types */
|
|
87
|
+
SELECT CASE
|
|
88
|
+
WHEN pg_type.typtype = 'd' THEN 'DOMAIN'
|
|
89
|
+
ELSE 'TYPE'
|
|
90
|
+
END AS object_type,
|
|
91
|
+
pg_type.typname AS object,
|
|
92
|
+
NULL::varchar AS schema,
|
|
93
|
+
CASE
|
|
94
|
+
WHEN a.grantee = 0 THEN 'public'
|
|
95
|
+
ELSE a.grantee::regrole::varchar
|
|
96
|
+
END AS role,
|
|
97
|
+
array_agg(DISTINCT a.privilege_type) AS privileges,
|
|
98
|
+
NULL::name[] AS columns,
|
|
99
|
+
NULL::varchar AS arguments
|
|
100
|
+
FROM pg_catalog.pg_type
|
|
101
|
+
JOIN aclexplode(pg_type.typacl) AS a ON true
|
|
102
|
+
GROUP BY pg_type.typtype, pg_type.typname, a.grantee
|
|
103
|
+
UNION
|
|
104
|
+
/* Functions, Procedures, and Routines */
|
|
105
|
+
SELECT CASE
|
|
106
|
+
WHEN pg_proc.prokind IN ('f', 'a') THEN 'FUNCTION'
|
|
107
|
+
WHEN pg_proc.prokind = 'p' THEN 'PROCEDURE'
|
|
108
|
+
WHEN pg_proc.prokind = 'w' THEN 'ROUTINE'
|
|
109
|
+
END AS object_type,
|
|
110
|
+
pg_proc.proname AS object,
|
|
111
|
+
pg_namespace.nspname AS schema,
|
|
112
|
+
CASE
|
|
113
|
+
WHEN a.grantee = 0 THEN 'public'
|
|
114
|
+
ELSE a.grantee::regrole::varchar
|
|
115
|
+
END AS role,
|
|
116
|
+
array_agg(DISTINCT a.privilege_type) AS privileges,
|
|
117
|
+
NULL::name[] AS columns,
|
|
118
|
+
pg_get_function_arguments(pg_proc.oid) AS arguments
|
|
119
|
+
FROM pg_catalog.pg_proc
|
|
120
|
+
JOIN pg_catalog.pg_namespace ON pg_proc.pronamespace = pg_namespace.oid
|
|
121
|
+
JOIN aclexplode(pg_proc.proacl) AS a ON true
|
|
122
|
+
GROUP BY pg_proc.prokind, pg_proc.proname, pg_namespace.nspname, a.grantee, pg_get_function_arguments(pg_proc.oid)
|
|
123
|
+
UNION
|
|
124
|
+
/* Schema */
|
|
125
|
+
SELECT 'SCHEMA' AS object_type,
|
|
126
|
+
pg_namespace.nspname AS object,
|
|
127
|
+
NULL::varchar AS schema,
|
|
128
|
+
CASE
|
|
129
|
+
WHEN a.grantee = 0 THEN 'public'
|
|
130
|
+
ELSE a.grantee::regrole::varchar
|
|
131
|
+
END AS role,
|
|
132
|
+
array_agg(DISTINCT a.privilege_type) AS privileges,
|
|
133
|
+
NULL::name[] AS columns,
|
|
134
|
+
NULL::varchar AS arguments
|
|
135
|
+
FROM pg_catalog.pg_namespace
|
|
136
|
+
JOIN aclexplode(pg_namespace.nspacl) AS a ON true
|
|
137
|
+
WHERE pg_namespace.nspname NOT LIKE 'pg_%' AND
|
|
138
|
+
pg_namespace.nspname != 'information_schema'
|
|
139
|
+
GROUP BY pg_namespace.nspname, a.grantee
|
|
140
|
+
) AS privileges
|
|
141
|
+
WHERE (privileges.schema IS NULL
|
|
142
|
+
OR privileges.schema = ANY (#{quote_text_array schema}))
|
|
143
|
+
AND privileges.role NOT LIKE 'pg_%'
|
|
144
|
+
AND privileges.role NOT IN (
|
|
145
|
+
SELECT applicable_roles.grantee
|
|
146
|
+
FROM information_schema.applicable_roles
|
|
147
|
+
WHERE applicable_roles.role_name = 'pg_database_owner'
|
|
148
|
+
)
|
|
149
|
+
ORDER BY privileges.object_type NULLS FIRST,
|
|
150
|
+
privileges.object NULLS FIRST,
|
|
151
|
+
privileges.schema NULLS FIRST
|
|
152
|
+
SQL
|
|
153
|
+
|
|
154
|
+
privileges.map do |privilege|
|
|
155
|
+
Privilege.new(
|
|
156
|
+
privilege["object_type"],
|
|
157
|
+
privilege["object"],
|
|
158
|
+
privilege["schema"],
|
|
159
|
+
privilege["role"],
|
|
160
|
+
PG::TextDecoder::Array.new.decode(privilege["privileges"]),
|
|
161
|
+
PG::TextDecoder::Array.new.decode(privilege["columns"]),
|
|
162
|
+
privilege["arguments"]&.split(",")&.map(&:split)
|
|
163
|
+
)
|
|
164
|
+
end
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def grant_privileges_to(role, privileges, object_type, object_name, options = {})
|
|
168
|
+
execute build_privilege_sql(:grant, role, privileges, object_type, object_name, options)
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def revoke_privileges_from(role, privileges, object_type, object_name, options = {})
|
|
172
|
+
execute build_privilege_sql(:revoke, role, privileges, object_type, object_name, options)
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
private
|
|
176
|
+
|
|
177
|
+
def build_privilege_sql(action, role, privileges, object_type, object_name, options = {})
|
|
178
|
+
# Without an object type this is a role membership grant, so the
|
|
179
|
+
# "privileges" are the names of the roles being granted.
|
|
180
|
+
granted = object_type ? sql_keywords(privileges, "privilege") : quote_role_names(privileges)
|
|
181
|
+
|
|
182
|
+
sql = "#{action.to_s.upcase} #{granted}"
|
|
183
|
+
sql += " (#{quote_identifiers options[:columns]})" if options[:columns]
|
|
184
|
+
sql += " #{build_privilege_to_object(object_type, object_name, options)}" if object_type
|
|
185
|
+
sql += " #{action == :revoke ? "FROM" : "TO"} #{quote_role_names role}"
|
|
186
|
+
sql += " CASCADE" if action == :revoke && options[:cascade]
|
|
187
|
+
sql
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def build_privilege_to_object(object_type, object_name, options)
|
|
191
|
+
if object_name == :all
|
|
192
|
+
object_type = sql_keywords(object_type.to_s.pluralize, "object type")
|
|
193
|
+
|
|
194
|
+
"ON ALL #{object_type} IN SCHEMA #{quote_identifiers options.fetch(:schema, :public)}"
|
|
195
|
+
else
|
|
196
|
+
object_type = sql_keywords(object_type, "object type")
|
|
197
|
+
objects = if object_name.is_a?(Hash)
|
|
198
|
+
build_routine_privilege_arguments(object_name)
|
|
199
|
+
else
|
|
200
|
+
quote_privilege_objects(object_type, object_name)
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
"ON #{object_type} #{objects}"
|
|
204
|
+
end
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
def quote_privilege_objects(object_type, object_names)
|
|
208
|
+
case object_type
|
|
209
|
+
when "TABLE", "SEQUENCE", "TYPE", "DOMAIN", "FOREIGN TABLE"
|
|
210
|
+
quote_qualified_names(object_names)
|
|
211
|
+
when "FUNCTION", "PROCEDURE", "ROUTINE", "LARGE OBJECT"
|
|
212
|
+
# Routine signatures such as add(integer, integer) and large object
|
|
213
|
+
# oids are passed through as written.
|
|
214
|
+
Array(object_names).join(", ")
|
|
215
|
+
else
|
|
216
|
+
quote_identifiers(object_names)
|
|
217
|
+
end
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
# Builds routine signatures from a hash of routine names to arguments,
|
|
221
|
+
# the format returned by all_privileges, e.g.
|
|
222
|
+
# { "add" => [["a", "integer"], ["b", "integer"]] } => "add(a integer, b integer)"
|
|
223
|
+
def build_routine_privilege_arguments(routines)
|
|
224
|
+
routines.map do |name, arguments|
|
|
225
|
+
"#{quote_table_name name.to_s}(#{Array(arguments).map do |argument|
|
|
226
|
+
Array(argument).join(" ")
|
|
227
|
+
end.join(", ")})"
|
|
228
|
+
end.join(", ")
|
|
229
|
+
end
|
|
230
|
+
end
|
|
231
|
+
end
|
|
232
|
+
end
|
|
233
|
+
end
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord
|
|
4
|
+
module RLS
|
|
5
|
+
module Statements
|
|
6
|
+
# Quoting shared by the statements, so names with capitals, hyphens,
|
|
7
|
+
# spaces, or quotes work as given and can't change a statement.
|
|
8
|
+
#
|
|
9
|
+
# Quoting means names are no longer folded to lower case:
|
|
10
|
+
# create_role("AppUser") creates "AppUser", not appuser.
|
|
11
|
+
module Quoting
|
|
12
|
+
# Keywords PostgreSQL accepts in place of a role name. Quoting them
|
|
13
|
+
# would refer to a role literally named e.g. "PUBLIC" instead.
|
|
14
|
+
SPECIAL_ROLES = %w[PUBLIC CURRENT_ROLE CURRENT_USER SESSION_USER].freeze
|
|
15
|
+
|
|
16
|
+
# SQL keywords such as privileges (SELECT, ALL PRIVILEGES) and object
|
|
17
|
+
# types (TABLE, FOREIGN DATA WRAPPER) can't be quoted, so they are
|
|
18
|
+
# checked to be plain words instead.
|
|
19
|
+
KEYWORD = /\A[a-z]+(?: [a-z]+)*\z/i
|
|
20
|
+
|
|
21
|
+
private
|
|
22
|
+
|
|
23
|
+
def quote_role_name(role)
|
|
24
|
+
name = role.to_s
|
|
25
|
+
SPECIAL_ROLES.include?(name.upcase) ? name.upcase : quote_column_name(name)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def quote_role_names(roles)
|
|
29
|
+
Array(roles).map { |role| quote_role_name(role) }.join(", ")
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Schema, column, and other unqualified names.
|
|
33
|
+
def quote_identifiers(names)
|
|
34
|
+
Array(names).map { |name| quote_column_name(name.to_s) }.join(", ")
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Names that may be schema qualified, e.g. "other_schema.posts".
|
|
38
|
+
def quote_qualified_names(names)
|
|
39
|
+
Array(names).map { |name| quote_table_name(name.to_s) }.join(", ")
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# A text[] literal for comparisons with = ANY (...). Unlike IN (...),
|
|
43
|
+
# this is valid SQL when the list is empty.
|
|
44
|
+
def quote_text_array(values)
|
|
45
|
+
"ARRAY[#{Array(values).map { |value| quote(value.to_s) }.join(", ")}]::text[]"
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def sql_keywords(values, description)
|
|
49
|
+
keywords = Array(values).map { |value| value.to_s.tr("_", " ") }
|
|
50
|
+
|
|
51
|
+
keywords.each do |keyword|
|
|
52
|
+
raise ArgumentError, "Invalid #{description}: #{keyword.inspect}" unless KEYWORD.match?(keyword)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
keywords.map(&:upcase).join(", ")
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord
|
|
4
|
+
module RLS
|
|
5
|
+
module Statements
|
|
6
|
+
module RLSPolicies
|
|
7
|
+
include Quoting
|
|
8
|
+
|
|
9
|
+
RLSPolicy = Struct.new(:table_name, :enabled, :force, :schema)
|
|
10
|
+
|
|
11
|
+
def all_rls_policies(schema: schema_names)
|
|
12
|
+
policies = execute <<~SQL
|
|
13
|
+
SELECT tables.table_name AS table_name,
|
|
14
|
+
pg_class.relrowsecurity AS enable_rls,
|
|
15
|
+
pg_class.relforcerowsecurity AS enable_force_rls,
|
|
16
|
+
pg_namespace.nspname AS schema
|
|
17
|
+
FROM information_schema.tables
|
|
18
|
+
JOIN pg_catalog.pg_namespace ON tables.table_schema = pg_namespace.nspname
|
|
19
|
+
JOIN pg_catalog.pg_class ON tables.table_name = pg_class.relname
|
|
20
|
+
AND pg_class.relnamespace = pg_namespace.oid
|
|
21
|
+
WHERE tables.table_type = 'BASE TABLE'
|
|
22
|
+
AND tables.table_schema = ANY (#{quote_text_array schema})
|
|
23
|
+
AND (pg_class.relrowsecurity = true OR pg_class.relforcerowsecurity = true)
|
|
24
|
+
ORDER BY pg_namespace.nspname ASC, tables.table_name ASC;
|
|
25
|
+
SQL
|
|
26
|
+
|
|
27
|
+
policies.map do |policy|
|
|
28
|
+
RLSPolicy.new(policy["table_name"], policy["enable_rls"], policy["enable_force_rls"], policy["schema"])
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def enable_rls(table)
|
|
33
|
+
execute "ALTER TABLE #{quote_table_name table} ENABLE ROW LEVEL SECURITY"
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def enable_force_rls(table)
|
|
37
|
+
execute "ALTER TABLE #{quote_table_name table} FORCE ROW LEVEL SECURITY"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def disable_rls(table)
|
|
41
|
+
execute "ALTER TABLE #{quote_table_name table} DISABLE ROW LEVEL SECURITY"
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def disable_force_rls(table)
|
|
45
|
+
execute "ALTER TABLE #{quote_table_name table} NO FORCE ROW LEVEL SECURITY"
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
end
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord
|
|
4
|
+
module RLS
|
|
5
|
+
module Statements
|
|
6
|
+
module Roles
|
|
7
|
+
include Quoting
|
|
8
|
+
|
|
9
|
+
ROLE_PERMISSIONS_MAPPING = {
|
|
10
|
+
super_user: "SUPERUSER",
|
|
11
|
+
create_db: "CREATEDB",
|
|
12
|
+
create_role: "CREATEROLE",
|
|
13
|
+
inherit: "INHERIT",
|
|
14
|
+
replication: "REPLICATION",
|
|
15
|
+
bypass_rls: "BYPASSRLS",
|
|
16
|
+
password: "LOGIN"
|
|
17
|
+
}.freeze
|
|
18
|
+
|
|
19
|
+
Role = Struct.new(:name, :super_user, :inherit, :create_role, :create_db, :replication, :bypass_rls, :password)
|
|
20
|
+
|
|
21
|
+
def role_exists?(name)
|
|
22
|
+
execute("SELECT COUNT(*) FROM pg_catalog.pg_roles WHERE rolname = #{quote name.to_s}").getvalue(0, 0) == 1
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def database_owner_role
|
|
26
|
+
sql = <<~SQL
|
|
27
|
+
SELECT applicable_roles.grantee
|
|
28
|
+
FROM information_schema.applicable_roles
|
|
29
|
+
WHERE applicable_roles.role_name = 'pg_database_owner'
|
|
30
|
+
LIMIT 1
|
|
31
|
+
SQL
|
|
32
|
+
|
|
33
|
+
execute(sql).getvalue(0, 0)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def all_roles
|
|
37
|
+
roles = execute <<~SQL
|
|
38
|
+
SELECT pg_roles.rolname AS name,
|
|
39
|
+
pg_roles.rolsuper AS super_user,
|
|
40
|
+
pg_roles.rolinherit AS inherit,
|
|
41
|
+
pg_roles.rolcreaterole AS create_role,
|
|
42
|
+
pg_roles.rolcreatedb AS create_db,
|
|
43
|
+
pg_roles.rolreplication AS replication,
|
|
44
|
+
pg_roles.rolbypassrls AS bypass_rls,
|
|
45
|
+
pg_roles.rolcanlogin AS password
|
|
46
|
+
FROM pg_catalog.pg_roles
|
|
47
|
+
WHERE pg_roles.rolname NOT LIKE 'pg_%'
|
|
48
|
+
AND pg_roles.rolname NOT IN (
|
|
49
|
+
SELECT applicable_roles.grantee
|
|
50
|
+
FROM information_schema.applicable_roles
|
|
51
|
+
WHERE applicable_roles.role_name = 'pg_database_owner')
|
|
52
|
+
ORDER BY pg_roles.rolname
|
|
53
|
+
SQL
|
|
54
|
+
|
|
55
|
+
roles.map do |role|
|
|
56
|
+
Role.new(
|
|
57
|
+
role["name"],
|
|
58
|
+
role["super_user"],
|
|
59
|
+
role["inherit"],
|
|
60
|
+
role["create_role"],
|
|
61
|
+
role["create_db"],
|
|
62
|
+
role["replication"],
|
|
63
|
+
role["bypass_rls"],
|
|
64
|
+
role["password"]
|
|
65
|
+
)
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def create_role(name, options = {})
|
|
70
|
+
return if skip_role_updates?
|
|
71
|
+
|
|
72
|
+
sql = "CREATE ROLE #{quote_role_name name} #{extract_role_permissions(options).join(" ")}".strip
|
|
73
|
+
sql += role_password_sql(name) if options[:password]
|
|
74
|
+
execute sql
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def alter_role(name, options = {})
|
|
78
|
+
return if skip_role_updates?
|
|
79
|
+
|
|
80
|
+
sql = "ALTER ROLE #{quote_role_name name} #{extract_role_permissions(options).join(" ")}".strip
|
|
81
|
+
sql += role_password_sql(name) if options[:password]
|
|
82
|
+
execute sql
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def create_or_alter_role(name, options = {})
|
|
86
|
+
return if skip_role_updates?
|
|
87
|
+
|
|
88
|
+
if role_exists? name
|
|
89
|
+
alter_role name, options
|
|
90
|
+
else
|
|
91
|
+
create_role name, options
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def drop_role(name, options = {})
|
|
96
|
+
if options[:reassign]
|
|
97
|
+
assign_to = options[:reassign].is_a?(TrueClass) ? database_owner_role : options[:reassign]
|
|
98
|
+
|
|
99
|
+
execute <<~SQL
|
|
100
|
+
DO
|
|
101
|
+
$do$
|
|
102
|
+
BEGIN
|
|
103
|
+
REASSIGN OWNED BY #{quote_role_name name} TO #{quote_role_name assign_to};
|
|
104
|
+
DROP OWNED BY #{quote_role_name name};
|
|
105
|
+
DROP USER #{quote_role_name name};
|
|
106
|
+
END
|
|
107
|
+
$do$;
|
|
108
|
+
SQL
|
|
109
|
+
else
|
|
110
|
+
execute "DROP ROLE #{quote_role_name name}"
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def self.without_updates
|
|
115
|
+
Thread.current[:__activerecord_rls_skip_roles] = true
|
|
116
|
+
|
|
117
|
+
yield
|
|
118
|
+
ensure
|
|
119
|
+
Thread.current[:__activerecord_rls_skip_roles] = false
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
private
|
|
123
|
+
|
|
124
|
+
def skip_role_updates?
|
|
125
|
+
!!Thread.current[:__activerecord_rls_skip_roles]
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def extract_role_permissions(options)
|
|
129
|
+
options.slice(*ROLE_PERMISSIONS_MAPPING.keys).map do |(permission, enabled)|
|
|
130
|
+
"#{"NO" unless enabled}#{ROLE_PERMISSIONS_MAPPING[permission]}"
|
|
131
|
+
end
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def role_password_sql(role)
|
|
135
|
+
password = find_role_password(role)
|
|
136
|
+
password ? " PASSWORD #{quote password}" : ""
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# Rails is optional, so only use Rails.env and credentials when they are available.
|
|
140
|
+
def find_role_password(role)
|
|
141
|
+
rails = defined?(::Rails) ? ::Rails : nil
|
|
142
|
+
rails_env = rails.env if rails.respond_to?(:env)
|
|
143
|
+
|
|
144
|
+
(rails_env && ENV["#{rails_env}_DB_ROLE_#{role.upcase}_PASSWORD"]) ||
|
|
145
|
+
ENV["DB_ROLE_#{role.upcase}_PASSWORD"] ||
|
|
146
|
+
# Rails.application is nil when Rails is loaded without an application.
|
|
147
|
+
(if rails.respond_to?(:application)
|
|
148
|
+
rails.application&.credentials&.dig(:database, role.downcase.to_sym,
|
|
149
|
+
:password)
|
|
150
|
+
end)
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
end
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord
|
|
4
|
+
module RLS
|
|
5
|
+
module Statements
|
|
6
|
+
module RuntimeVariables
|
|
7
|
+
# Custom variable names such as rls.user_id. SET can't take a bound
|
|
8
|
+
# name, so names are checked to be plain dotted identifiers instead.
|
|
9
|
+
VARIABLE_NAME = /\A[a-z_][a-z0-9_]*(?:\.[a-z_][a-z0-9_]*)*\z/i
|
|
10
|
+
SCOPES = %i[local session].freeze
|
|
11
|
+
|
|
12
|
+
# Returns nil when the variable is not defined. current_setting with
|
|
13
|
+
# missing_ok is used instead of SHOW because SHOW raises an error for
|
|
14
|
+
# undefined variables, which aborts any open transaction.
|
|
15
|
+
def runtime_variable(name)
|
|
16
|
+
execute(Arel.sql("SELECT current_setting(#{quote name.to_s}, true)")).getvalue(0, 0)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def set_runtime_variable(name, value, scope: :local)
|
|
20
|
+
clear_query_cache
|
|
21
|
+
return reset_runtime_variable(name, scope: scope) unless value
|
|
22
|
+
|
|
23
|
+
execute(Arel.sql("SET #{runtime_variable_scope scope} #{runtime_variable_name name} = #{quote value}"))
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def reset_runtime_variable(name, scope: :local)
|
|
27
|
+
execute(Arel.sql("SET #{runtime_variable_scope scope} #{runtime_variable_name name} TO DEFAULT"))
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def with_runtime_variable(name, value, scope: :local)
|
|
31
|
+
current_value = runtime_variable name
|
|
32
|
+
return yield if current_value == value
|
|
33
|
+
|
|
34
|
+
set_runtime_variable name, value, scope: scope
|
|
35
|
+
yield
|
|
36
|
+
ensure
|
|
37
|
+
set_runtime_variable name, current_value, scope: scope
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
private
|
|
41
|
+
|
|
42
|
+
def runtime_variable_name(name)
|
|
43
|
+
name = name.to_s
|
|
44
|
+
raise ArgumentError, "Invalid runtime variable name: #{name.inspect}" unless VARIABLE_NAME.match?(name)
|
|
45
|
+
|
|
46
|
+
name
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def runtime_variable_scope(scope)
|
|
50
|
+
unless SCOPES.include?(scope.to_s.to_sym)
|
|
51
|
+
raise ArgumentError,
|
|
52
|
+
"Invalid runtime variable scope: #{scope.inspect}"
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
scope.to_s.upcase
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ActiveRecord
|
|
4
|
+
module RLS
|
|
5
|
+
module TestDatabases # :nodoc:
|
|
6
|
+
def create_and_load_schema(i, env_name:)
|
|
7
|
+
Statements::Roles.without_updates do
|
|
8
|
+
super
|
|
9
|
+
end
|
|
10
|
+
end
|
|
11
|
+
end
|
|
12
|
+
end
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
ActiveRecord::TestDatabases.singleton_class.prepend(ActiveRecord::RLS::TestDatabases)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "rls/version"
|
|
4
|
+
|
|
5
|
+
require "active_support"
|
|
6
|
+
|
|
7
|
+
module ActiveRecord
|
|
8
|
+
module RLS
|
|
9
|
+
extend ActiveSupport::Autoload
|
|
10
|
+
|
|
11
|
+
module CommandRecorders
|
|
12
|
+
extend ActiveSupport::Autoload
|
|
13
|
+
|
|
14
|
+
eager_autoload do
|
|
15
|
+
autoload :DefaultPrivileges
|
|
16
|
+
autoload :Policies
|
|
17
|
+
autoload :Privileges
|
|
18
|
+
autoload :RLSPolicies
|
|
19
|
+
autoload :Roles
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
module Statements
|
|
24
|
+
extend ActiveSupport::Autoload
|
|
25
|
+
|
|
26
|
+
eager_autoload do
|
|
27
|
+
autoload :DefaultPrivileges
|
|
28
|
+
autoload :Policies
|
|
29
|
+
autoload :Privileges
|
|
30
|
+
autoload :RLSPolicies
|
|
31
|
+
autoload :Roles
|
|
32
|
+
autoload :Quoting
|
|
33
|
+
autoload :RuntimeVariables
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
autoload :Model
|
|
38
|
+
autoload :MigrationMethods
|
|
39
|
+
|
|
40
|
+
eager_autoload do
|
|
41
|
+
autoload :SchemaDumper
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def self.eager_load!
|
|
45
|
+
super
|
|
46
|
+
|
|
47
|
+
Statements.eager_load!
|
|
48
|
+
CommandRecorders.eager_load!
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def self.config(&block)
|
|
52
|
+
tap(&block)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
mattr_accessor :default_runtime_variable_namespace
|
|
56
|
+
@@default_runtime_variable_namespace = :rls
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
ActiveSupport.on_load(:active_record) do
|
|
61
|
+
ActiveRecord::ConnectionAdapters::AbstractAdapter.include(ActiveRecord::RLS::Statements::DefaultPrivileges)
|
|
62
|
+
ActiveRecord::ConnectionAdapters::AbstractAdapter.include(ActiveRecord::RLS::Statements::Policies)
|
|
63
|
+
ActiveRecord::ConnectionAdapters::AbstractAdapter.include(ActiveRecord::RLS::Statements::Privileges)
|
|
64
|
+
ActiveRecord::ConnectionAdapters::AbstractAdapter.include(ActiveRecord::RLS::Statements::RLSPolicies)
|
|
65
|
+
ActiveRecord::ConnectionAdapters::AbstractAdapter.include(ActiveRecord::RLS::Statements::Roles)
|
|
66
|
+
ActiveRecord::ConnectionAdapters::AbstractAdapter.include(ActiveRecord::RLS::Statements::RuntimeVariables)
|
|
67
|
+
|
|
68
|
+
ActiveRecord::Migration::CommandRecorder.include(ActiveRecord::RLS::CommandRecorders::DefaultPrivileges)
|
|
69
|
+
ActiveRecord::Migration::CommandRecorder.include(ActiveRecord::RLS::CommandRecorders::Policies)
|
|
70
|
+
ActiveRecord::Migration::CommandRecorder.include(ActiveRecord::RLS::CommandRecorders::Privileges)
|
|
71
|
+
ActiveRecord::Migration::CommandRecorder.include(ActiveRecord::RLS::CommandRecorders::RLSPolicies)
|
|
72
|
+
ActiveRecord::Migration::CommandRecorder.include(ActiveRecord::RLS::CommandRecorders::Roles)
|
|
73
|
+
|
|
74
|
+
ActiveRecord::Migration.include(ActiveRecord::RLS::MigrationMethods)
|
|
75
|
+
|
|
76
|
+
ActiveRecord::SchemaDumper.prepend(ActiveRecord::RLS::SchemaDumper)
|
|
77
|
+
end
|