21030: Use a CTE instead of temporary table for update_permissions
[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 '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
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     ActiveRecord::Base.connection.exec_query %{
73 with temptable_perms as (
74   select * from compute_permission_subgraph($1, $2, $3, $4)),
75
76 /*
77     Now that we have recomputed a set of permissions, delete any
78     rows from the materialized_permissions table where (target_uuid,
79     user_uuid) is not present or has perm_level=0 in the recomputed
80     set.
81 */
82 delete_rows as (
83   delete from #{PERMISSION_VIEW} where
84     target_uuid in (select target_uuid from temptable_perms) and
85     not exists (select 1 from temptable_perms
86                 where target_uuid=#{PERMISSION_VIEW}.target_uuid and
87                       user_uuid=#{PERMISSION_VIEW}.user_uuid and
88                       val>0)
89 )
90
91 /*
92   Now insert-or-update permissions in the recomputed set.  The
93   WHERE clause is important to avoid redundantly updating rows
94   that haven't actually changed.
95 */
96 insert into #{PERMISSION_VIEW} (user_uuid, target_uuid, perm_level, traverse_owned)
97   select user_uuid, target_uuid, val as perm_level, traverse_owned from temptable_perms where val>0
98 on conflict (user_uuid, target_uuid) do update
99 set perm_level=EXCLUDED.perm_level, traverse_owned=EXCLUDED.traverse_owned
100 where #{PERMISSION_VIEW}.user_uuid=EXCLUDED.user_uuid and
101       #{PERMISSION_VIEW}.target_uuid=EXCLUDED.target_uuid and
102        (#{PERMISSION_VIEW}.perm_level != EXCLUDED.perm_level or
103         #{PERMISSION_VIEW}.traverse_owned != EXCLUDED.traverse_owned);
104 },
105                                              'update_permissions.select',
106                                              [[nil, perm_origin_uuid],
107                                               [nil, starting_uuid],
108                                               [nil, perm_level],
109                                               [nil, edge_id]]
110
111     if perm_level>0
112       check_permissions_against_full_refresh
113     end
114   end
115 end
116
117
118 def check_permissions_against_full_refresh
119   # No-op except when running tests
120   return unless Rails.env == 'test' and !Thread.current[:no_check_permissions_against_full_refresh] and !Thread.current[:suppress_update_permissions]
121
122   # For checking correctness of the incremental permission updates.
123   # Check contents of the current 'materialized_permission' table
124   # against a from-scratch permission refresh.
125
126   q1 = ActiveRecord::Base.connection.exec_query %{
127 select user_uuid, target_uuid, perm_level, traverse_owned from #{PERMISSION_VIEW}
128 order by user_uuid, target_uuid
129 }, "check_permissions_against_full_refresh.permission_table"
130
131   q2 = ActiveRecord::Base.connection.exec_query %{
132     select pq.origin_uuid as user_uuid, target_uuid, pq.val as perm_level, pq.traverse_owned from (
133     #{PERM_QUERY_TEMPLATE % {:base_case => %{
134         select uuid, uuid, 3, true, true from users
135 },
136 :edge_perm => 'edges.val'
137 } }) as pq order by origin_uuid, target_uuid
138 }, "check_permissions_against_full_refresh.full_recompute"
139
140   if q1.count != q2.count
141     puts "Didn't match incremental+: #{q1.count} != full refresh-: #{q2.count}"
142   end
143
144   if q1.count > q2.count
145     q1.each_with_index do |r, i|
146       if r != q2[i]
147         puts "+#{r}\n-#{q2[i]}"
148         raise "Didn't match"
149       end
150     end
151   else
152     q2.each_with_index do |r, i|
153       if r != q1[i]
154         puts "+#{q1[i]}\n-#{r}"
155         raise "Didn't match"
156       end
157     end
158   end
159 end
160
161 def skip_check_permissions_against_full_refresh
162   check_perm_was = Thread.current[:no_check_permissions_against_full_refresh]
163   Thread.current[:no_check_permissions_against_full_refresh] = true
164   begin
165     yield
166   ensure
167     Thread.current[:no_check_permissions_against_full_refresh] = check_perm_was
168   end
169 end
170
171 def batch_update_permissions
172   check_perm_was = Thread.current[:suppress_update_permissions]
173   Thread.current[:suppress_update_permissions] = true
174   begin
175     yield
176   ensure
177     Thread.current[:suppress_update_permissions] = check_perm_was
178     refresh_permissions
179   end
180 end
181
182 # Used to account for permissions that a user gains by having
183 # can_manage on another user.
184 #
185 # note: in theory a user could have can_manage access to a user
186 # through multiple levels, that isn't handled here (would require a
187 # recursive query).  I think that's okay because users getting
188 # transitive access through "can_manage" on a user is is rarely/never
189 # used feature and something we probably want to deprecate and remove.
190 USER_UUIDS_SUBQUERY_TEMPLATE = %{
191 select target_uuid from materialized_permissions where user_uuid in (%{user})
192 and target_uuid like '_____-tpzed-_______________' and traverse_owned=true and perm_level >= %{perm_level}
193 }