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