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