21700: Install Bundler system-wide in Rails postinst
[arvados.git] / services / api / lib / update_permissions.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require_relative '20200501150153_permission_table_constants'
6
7 REVOKE_PERM = 0
8 CAN_MANAGE_PERM = 3
9
10 def update_permissions perm_origin_uuid, starting_uuid, perm_level, edge_id=nil, update_all_users=false
11   return if Thread.current[:suppress_update_permissions]
12
13   #
14   # Update a subset of the permission table affected by adding or
15   # removing a particular permission relationship (ownership or a
16   # permission link).
17   #
18   # perm_origin_uuid: This is the object that 'gets' the permission.
19   # It is the owner_uuid or tail_uuid.
20   #
21   # starting_uuid: The object we are computing permission for (or head_uuid)
22   #
23   # perm_level: The level of permission that perm_origin_uuid gets for starting_uuid.
24   #
25   # perm_level is a number from 0-3
26   #   can_read=1
27   #   can_write=2
28   #   can_manage=3
29   #   or call with perm_level=0 to revoke permissions
30   #
31   # check: for testing/debugging, compare the result of the
32   # incremental update against a full table recompute.  Throws an
33   # error if the contents are not identical (ie they produce different
34   # permission results)
35
36   # Theory of operation
37   #
38   # Give a change in a specific permission relationship, we recompute
39   # the set of permissions (for all users) that could possibly be
40   # affected by that relationship.  For example, if a project is
41   # shared with another user, we recompute all permissions for all
42   # projects in the hierarchy.  This returns a set of updated
43   # permissions, which we stash in a temporary table.
44   #
45   # Then, for each user_uuid/target_uuid in the updated permissions
46   # result set we insert/update a permission row in
47   # materialized_permissions, and delete any rows that exist in
48   # materialized_permissions that are not in the result set or have
49   # perm_level=0.
50   #
51   # see db/migrate/20200501150153_permission_table.rb for details on
52   # how the permissions are computed.
53
54   if edge_id.nil?
55     # For changes of ownership, edge_id is starting_uuid.  In turns
56     # out most invocations of update_permissions are for changes of
57     # ownership, so make this parameter optional to reduce
58     # clutter.
59     # For permission links, the uuid of the link object will be passed in for edge_id.
60     edge_id = starting_uuid
61   end
62
63   ActiveRecord::Base.transaction do
64
65     # "Conflicts with the ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE
66     # EXCLUSIVE, SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS
67     # EXCLUSIVE lock modes. This mode allows only concurrent ACCESS
68     # SHARE locks, i.e., only reads from the table can proceed in
69     # parallel with a transaction holding this lock mode."
70     ActiveRecord::Base.connection.execute "LOCK TABLE #{PERMISSION_VIEW} in EXCLUSIVE MODE"
71
72     # Workaround for
73     # BUG #15160: planner overestimates number of rows in join when there are more than 200 rows coming from CTE
74     # https://www.postgresql.org/message-id/152395805004.19366.3107109716821067806@wrigleys.postgresql.org
75     #
76     # For a crucial join in the compute_permission_subgraph() query, the
77     # planner mis-estimates the number of rows in a Common Table
78     # Expression (CTE, this is a subquery in a WITH clause) and as a
79     # result it chooses the wrong join order.  The join starts with the
80     # permissions table because it mistakenly thinks
81     # count(materalized_permissions) < count(new computed permissions)
82     # when actually it is the other way around.
83     #
84     # Because of the incorrect join order, it choose the wrong join
85     # strategy (merge join, which works best when two tables are roughly
86     # the same size).  As a workaround, we can tell it not to use that
87     # join strategy, this causes it to pick hash join instead, which
88     # turns out to be a bit better.  However, because the join order is
89     # still wrong, we don't get the full benefit of the index.
90     #
91     # This is very unfortunate because it makes the query performance
92     # dependent on the size of the materalized_permissions table, when
93     # the goal of this design was to make permission updates scale-free
94     # and only depend on the number of permissions affected and not the
95     # total table size.  In several hours of researching I wasn't able
96     # to find a way to force the correct join order, so I'm calling it
97     # here and I have to move on.
98     #
99     # This is apparently addressed in Postgres 12, but I developed &
100     # tested this on Postgres 9.6, so in the future we should reevaluate
101     # the performance & query plan on Postgres 12.
102     #
103     # Update: as of 2023-10-13, incorrect merge join behavior is still
104     # observed on at least one major user installation that is using
105     # Postgres 14, so it seems this workaround is still needed.
106     #
107     # https://git.furworks.de/opensourcemirror/postgresql/commit/a314c34079cf06d05265623dd7c056f8fa9d577f
108     #
109     # Disable merge join for just this query (also local for this transaction), then reenable it.
110     ActiveRecord::Base.connection.exec_query "SET LOCAL enable_mergejoin to false;"
111
112     if perm_origin_uuid[5..11] == '-tpzed-' && !update_all_users
113       # Modifying permission granted to a user, recompute the all permissions for that user
114
115       ActiveRecord::Base.connection.exec_query %{
116 with origin_user_perms as (
117     select pq.origin_uuid as user_uuid, target_uuid, pq.val, pq.traverse_owned from (
118     #{PERM_QUERY_TEMPLATE % {:base_case => %{
119         select '#{perm_origin_uuid}'::varchar(255), '#{perm_origin_uuid}'::varchar(255), 3, true, true
120                where exists (select uuid from users where uuid='#{perm_origin_uuid}')
121 },
122 :edge_perm => %{
123 case (edges.edge_id = '#{edge_id}')
124                                when true then #{perm_level}
125                                else edges.val
126                             end
127 }
128 } }) as pq),
129
130 /*
131      Because users always have permission on themselves, this
132      query also makes sure those permission rows are always
133      returned.
134 */
135 temptable_perms as (
136       select * from origin_user_perms
137     union all
138       select target_uuid as user_uuid, target_uuid, 3, true
139         from origin_user_perms
140         where origin_user_perms.target_uuid like '_____-tpzed-_______________' and
141               origin_user_perms.target_uuid != '#{perm_origin_uuid}'
142 ),
143
144 /*
145     Now that we have recomputed a set of permissions, delete any
146     rows from the materialized_permissions table where (target_uuid,
147     user_uuid) is not present or has perm_level=0 in the recomputed
148     set.
149 */
150 delete_rows as (
151   delete from #{PERMISSION_VIEW} where
152     user_uuid='#{perm_origin_uuid}' and
153     not exists (select 1 from temptable_perms
154                 where target_uuid=#{PERMISSION_VIEW}.target_uuid and
155                       user_uuid='#{perm_origin_uuid}' and
156                       val>0)
157 )
158
159 /*
160   Now insert-or-update permissions in the recomputed set.  The
161   WHERE clause is important to avoid redundantly updating rows
162   that haven't actually changed.
163 */
164 insert into #{PERMISSION_VIEW} (user_uuid, target_uuid, perm_level, traverse_owned)
165   select user_uuid, target_uuid, val as perm_level, traverse_owned from temptable_perms where val>0
166 on conflict (user_uuid, target_uuid) do update
167 set perm_level=EXCLUDED.perm_level, traverse_owned=EXCLUDED.traverse_owned
168 where #{PERMISSION_VIEW}.user_uuid=EXCLUDED.user_uuid and
169       #{PERMISSION_VIEW}.target_uuid=EXCLUDED.target_uuid and
170        (#{PERMISSION_VIEW}.perm_level != EXCLUDED.perm_level or
171         #{PERMISSION_VIEW}.traverse_owned != EXCLUDED.traverse_owned);
172
173 }
174     else
175       # Modifying permission granted to a group, recompute permissions for everything accessible through that group
176     ActiveRecord::Base.connection.exec_query %{
177 with temptable_perms as (
178   select * from compute_permission_subgraph($1, $2, $3, $4)),
179
180 /*
181     Now that we have recomputed a set of permissions, delete any
182     rows from the materialized_permissions table where (target_uuid,
183     user_uuid) is not present or has perm_level=0 in the recomputed
184     set.
185 */
186 delete_rows as (
187   delete from #{PERMISSION_VIEW} where
188     target_uuid in (select target_uuid from temptable_perms) and
189     not exists (select 1 from temptable_perms
190                 where target_uuid=#{PERMISSION_VIEW}.target_uuid and
191                       user_uuid=#{PERMISSION_VIEW}.user_uuid and
192                       val>0)
193 )
194
195 /*
196   Now insert-or-update permissions in the recomputed set.  The
197   WHERE clause is important to avoid redundantly updating rows
198   that haven't actually changed.
199 */
200 insert into #{PERMISSION_VIEW} (user_uuid, target_uuid, perm_level, traverse_owned)
201   select user_uuid, target_uuid, val as perm_level, traverse_owned from temptable_perms where val>0
202 on conflict (user_uuid, target_uuid) do update
203 set perm_level=EXCLUDED.perm_level, traverse_owned=EXCLUDED.traverse_owned
204 where #{PERMISSION_VIEW}.user_uuid=EXCLUDED.user_uuid and
205       #{PERMISSION_VIEW}.target_uuid=EXCLUDED.target_uuid and
206        (#{PERMISSION_VIEW}.perm_level != EXCLUDED.perm_level or
207         #{PERMISSION_VIEW}.traverse_owned != EXCLUDED.traverse_owned);
208 },
209                                              'update_permissions.select',
210                                              [perm_origin_uuid,
211                                               starting_uuid,
212                                               perm_level,
213                                               edge_id]
214     end
215
216     if perm_level>0
217       check_permissions_against_full_refresh
218     end
219   end
220 end
221
222
223 def check_permissions_against_full_refresh
224   # No-op except when running tests
225   return unless Rails.env == 'test' and !Thread.current[:no_check_permissions_against_full_refresh] and !Thread.current[:suppress_update_permissions]
226
227   # For checking correctness of the incremental permission updates.
228   # Check contents of the current 'materialized_permission' table
229   # against a from-scratch permission refresh.
230
231   q1 = ActiveRecord::Base.connection.exec_query %{
232 select user_uuid, target_uuid, perm_level, traverse_owned from #{PERMISSION_VIEW}
233 order by user_uuid, target_uuid
234 }, "check_permissions_against_full_refresh.permission_table"
235
236   q2 = ActiveRecord::Base.connection.exec_query %{
237     select pq.origin_uuid as user_uuid, target_uuid, pq.val as perm_level, pq.traverse_owned from (
238     #{PERM_QUERY_TEMPLATE % {:base_case => %{
239         select uuid, uuid, 3, true, true from users
240 },
241 :edge_perm => 'edges.val'
242 } }) as pq order by origin_uuid, target_uuid
243 }, "check_permissions_against_full_refresh.full_recompute"
244
245   if q1.count != q2.count
246     puts "Didn't match incremental+: #{q1.count} != full refresh-: #{q2.count}"
247   end
248
249   if q1.count > q2.count
250     q1.each_with_index do |r, i|
251       if r != q2[i]
252         puts "+#{r}\n-#{q2[i]}"
253         raise "Didn't match"
254       end
255     end
256   else
257     q2.each_with_index do |r, i|
258       if r != q1[i]
259         puts "+#{q1[i]}\n-#{r}"
260         raise "Didn't match"
261       end
262     end
263   end
264 end
265
266 def skip_check_permissions_against_full_refresh
267   check_perm_was = Thread.current[:no_check_permissions_against_full_refresh]
268   Thread.current[:no_check_permissions_against_full_refresh] = true
269   begin
270     yield
271   ensure
272     Thread.current[:no_check_permissions_against_full_refresh] = check_perm_was
273   end
274 end
275
276 def batch_update_permissions
277   check_perm_was = Thread.current[:suppress_update_permissions]
278   Thread.current[:suppress_update_permissions] = true
279   begin
280     yield
281   ensure
282     Thread.current[:suppress_update_permissions] = check_perm_was
283     refresh_permissions
284   end
285 end
286
287 # Used to account for permissions that a user gains by having
288 # can_manage on another user.
289 #
290 # note: in theory a user could have can_manage access to a user
291 # through multiple levels, that isn't handled here (would require a
292 # recursive query).  I think that's okay because users getting
293 # transitive access through "can_manage" on a user is is rarely/never
294 # used feature and something we probably want to deprecate and remove.
295 USER_UUIDS_SUBQUERY_TEMPLATE = %{
296 select target_uuid from materialized_permissions where user_uuid in (%{user})
297 and target_uuid like '_____-tpzed-_______________' and traverse_owned=true and perm_level >= %{perm_level}
298 }