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