1d9c1006b88860b691bfe30d6cc5106d9ec2ef1a
[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
11   #
12   # Update a subset of the permission table affected by adding or
13   # removing a particular permission relationship (ownership or a
14   # permission link).
15   #
16   # perm_origin_uuid: This is the object that 'gets' the permission.
17   # It is the owner_uuid or tail_uuid.
18   #
19   # starting_uuid: The object we are computing permission for (or head_uuid)
20   #
21   # perm_level: The level of permission that perm_origin_uuid gets for starting_uuid.
22   #
23   # perm_level is a number from 0-3
24   #   can_read=1
25   #   can_write=2
26   #   can_manage=3
27   #   or call with perm_level=0 to revoke permissions
28   #
29   # check: for testing/debugging, compare the result of the
30   # incremental update against a full table recompute.  Throws an
31   # error if the contents are not identical (ie they produce different
32   # permission results)
33
34   # Theory of operation
35   #
36   # Give a change in a specific permission relationship, we recompute
37   # the set of permissions (for all users) that could possibly be
38   # affected by that relationship.  For example, if a project is
39   # shared with another user, we recompute all permissions for all
40   # projects in the hierarchy.  This returns a set of updated
41   # permissions, which we stash in a temporary table.
42   #
43   # Then, for each user_uuid/target_uuid in the updated permissions
44   # result set we insert/update a permission row in
45   # materialized_permissions, and delete any rows that exist in
46   # materialized_permissions that are not in the result set or have
47   # perm_level=0.
48   #
49   # see db/migrate/20200501150153_permission_table.rb for details on
50   # how the permissions are computed.
51
52   ActiveRecord::Base.transaction do
53
54     # "Conflicts with the ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE, SHARE
55     # ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE lock modes. This
56     # mode protects a table against concurrent data changes."
57     ActiveRecord::Base.connection.execute "LOCK TABLE #{PERMISSION_VIEW} in SHARE MODE"
58
59     # Workaround for
60     # BUG #15160: planner overestimates number of rows in join when there are more than 200 rows coming from CTE
61     # https://www.postgresql.org/message-id/152395805004.19366.3107109716821067806@wrigleys.postgresql.org
62     #
63     # For a crucial join in the compute_permission_subgraph() query, the
64     # planner mis-estimates the number of rows in a Common Table
65     # Expression (CTE, this is a subquery in a WITH clause) and as a
66     # result it chooses the wrong join order.  The join starts with the
67     # permissions table because it mistakenly thinks
68     # count(materalized_permissions) < count(new computed permissions)
69     # when actually it is the other way around.
70     #
71     # Because of the incorrect join order, it choose the wrong join
72     # strategy (merge join, which works best when two tables are roughly
73     # the same size).  As a workaround, we can tell it not to use that
74     # join strategy, this causes it to pick hash join instead, which
75     # turns out to be a bit better.  However, because the join order is
76     # still wrong, we don't get the full benefit of the index.
77     #
78     # This is very unfortunate because it makes the query performance
79     # dependent on the size of the materalized_permissions table, when
80     # the goal of this design was to make permission updates scale-free
81     # and only depend on the number of permissions affected and not the
82     # total table size.  In several hours of researching I wasn't able
83     # to find a way to force the correct join order, so I'm calling it
84     # here and I have to move on.
85     #
86     # This is apparently addressed in Postgres 12, but I developed &
87     # tested this on Postgres 9.6, so in the future we should reevaluate
88     # the performance & query plan on Postgres 12.
89     #
90     # https://git.furworks.de/opensourcemirror/postgresql/commit/a314c34079cf06d05265623dd7c056f8fa9d577f
91     #
92     # Disable merge join for just this query (also local for this transaction), then reenable it.
93     ActiveRecord::Base.connection.exec_query "SET LOCAL enable_mergejoin to false;"
94
95     temptable_perms = "temp_perms_#{rand(2**64).to_s(10)}"
96     ActiveRecord::Base.connection.exec_query %{
97 create temporary table #{temptable_perms} on commit drop
98 as select * from compute_permission_subgraph($1, $2, $3)
99 },
100                                              'update_permissions.select',
101                                              [[nil, perm_origin_uuid],
102                                               [nil, starting_uuid],
103                                               [nil, perm_level]]
104
105     ActiveRecord::Base.connection.exec_query "SET LOCAL enable_mergejoin to true;"
106
107     ActiveRecord::Base.connection.exec_delete %{
108 delete from #{PERMISSION_VIEW} where
109   target_uuid in (select target_uuid from #{temptable_perms}) and
110   not exists (select 1 from #{temptable_perms}
111               where target_uuid=#{PERMISSION_VIEW}.target_uuid and
112                     user_uuid=#{PERMISSION_VIEW}.user_uuid and
113                     val>0)
114 },
115                                               "update_permissions.delete"
116
117     ActiveRecord::Base.connection.exec_query %{
118 insert into #{PERMISSION_VIEW} (user_uuid, target_uuid, perm_level, traverse_owned)
119   select user_uuid, target_uuid, val as perm_level, traverse_owned from #{temptable_perms} where val>0
120 on conflict (user_uuid, target_uuid) do update set perm_level=EXCLUDED.perm_level, traverse_owned=EXCLUDED.traverse_owned;
121 },
122                                              "update_permissions.insert"
123
124     if perm_level>0
125       check_permissions_against_full_refresh
126     end
127   end
128 end
129
130
131 def check_permissions_against_full_refresh
132   # No-op except when running tests
133   return unless Rails.env == 'test' and !Thread.current[:no_check_permissions_against_full_refresh]
134
135   # For checking correctness of the incremental permission updates.
136   # Check contents of the current 'materialized_permission' table
137   # against a from-scratch permission refresh.
138
139   q1 = ActiveRecord::Base.connection.exec_query %{
140 select user_uuid, target_uuid, perm_level, traverse_owned from #{PERMISSION_VIEW}
141 order by user_uuid, target_uuid
142 }, "check_permissions_against_full_refresh.permission_table"
143
144   q2 = ActiveRecord::Base.connection.exec_query %{
145     select pq.origin_uuid as user_uuid, target_uuid, pq.val as perm_level, pq.traverse_owned from (
146     #{PERM_QUERY_TEMPLATE % {:base_case => %{
147         select uuid, uuid, 3, true, true from users
148 },
149 :override => ''
150 } }) as pq order by origin_uuid, target_uuid
151 }, "check_permissions_against_full_refresh.full_recompute"
152
153   if q1.count != q2.count
154     puts "Didn't match incremental+: #{q1.count} != full refresh-: #{q2.count}"
155   end
156
157   if q1.count > q2.count
158     q1.each_with_index do |r, i|
159       if r != q2[i]
160         puts "+#{r}\n-#{q2[i]}"
161         raise "Didn't match"
162       end
163     end
164   else
165     q2.each_with_index do |r, i|
166       if r != q1[i]
167         puts "+#{q1[i]}\n-#{r}"
168         raise "Didn't match"
169       end
170     end
171   end
172 end
173
174 def skip_check_permissions_against_full_refresh
175   check_perm_was = Thread.current[:no_check_permissions_against_full_refresh]
176   Thread.current[:no_check_permissions_against_full_refresh] = true
177   begin
178     yield
179   ensure
180     Thread.current[:no_check_permissions_against_full_refresh] = check_perm_was
181   end
182 end
183
184 # Used to account for permissions that a user gains by having
185 # can_manage on another user.
186 #
187 # note: in theory a user could have can_manage access to a user
188 # through multiple levels, that isn't handled here (would require a
189 # recursive query).  I think that's okay because users getting
190 # transitive access through "can_manage" on a user is is rarely/never
191 # used feature and something we probably want to deprecate and remove.
192 USER_UUIDS_SUBQUERY_TEMPLATE = %{
193 select target_uuid from materialized_permissions where user_uuid in (%{user})
194 and target_uuid like '_____-tpzed-_______________' and traverse_owned=true and perm_level >= %{perm_level}
195 }