Merge branch 'master' into 14946-ruby-2.5
[arvados.git] / services / api / app / controllers / arvados / v1 / groups_controller.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require "trashable"
6
7 class Arvados::V1::GroupsController < ApplicationController
8   include TrashableController
9
10   skip_before_action :find_object_by_uuid, only: :shared
11   skip_before_action :render_404_if_no_object, only: :shared
12
13   def self._index_requires_parameters
14     (super rescue {}).
15       merge({
16         include_trash: {
17           type: 'boolean', required: false, description: "Include items whose is_trashed attribute is true."
18         },
19       })
20   end
21
22   def self._show_requires_parameters
23     (super rescue {}).
24       merge({
25         include_trash: {
26           type: 'boolean', required: false, description: "Show group/project even if its is_trashed attribute is true."
27         },
28       })
29   end
30
31   def self._contents_requires_parameters
32     params = _index_requires_parameters.
33       merge({
34               uuid: {
35                 type: 'string', required: false, default: nil
36               },
37               recursive: {
38                 type: 'boolean', required: false, description: 'Include contents from child groups recursively.'
39               },
40             })
41     params.delete(:select)
42     params
43   end
44
45   def self._create_requires_parameters
46     super.merge(
47       {
48         async: {
49           required: false,
50           type: 'boolean',
51           location: 'query',
52           default: false,
53           description: 'defer permissions update'
54         }
55       }
56     )
57   end
58
59   def self._update_requires_parameters
60     super.merge(
61       {
62         async: {
63           required: false,
64           type: 'boolean',
65           location: 'query',
66           default: false,
67           description: 'defer permissions update'
68         }
69       }
70     )
71   end
72
73   def create
74     if params[:async]
75       @object = model_class.new(resource_attrs.merge({async_permissions_update: true}))
76       @object.save!
77       render_accepted
78     else
79       super
80     end
81   end
82
83   def update
84     if params[:async]
85       attrs_to_update = resource_attrs.reject { |k, v|
86         [:kind, :etag, :href].index k
87       }.merge({async_permissions_update: true})
88       @object.update_attributes!(attrs_to_update)
89       @object.save!
90       render_accepted
91     else
92       super
93     end
94   end
95
96   def render_404_if_no_object
97     if params[:action] == 'contents'
98       if !params[:uuid]
99         # OK!
100         @object = nil
101         true
102       elsif @object
103         # Project group
104         true
105       elsif (@object = User.where(uuid: params[:uuid]).first)
106         # "Home" pseudo-project
107         true
108       else
109         super
110       end
111     else
112       super
113     end
114   end
115
116   def contents
117     load_searchable_objects
118     list = {
119       :kind => "arvados#objectList",
120       :etag => "",
121       :self_link => "",
122       :offset => @offset,
123       :limit => @limit,
124       :items_available => @items_available,
125       :items => @objects.as_api_response(nil)
126     }
127     if @extra_included
128       list[:included] = @extra_included.as_api_response(nil, {select: @select})
129     end
130     send_json(list)
131   end
132
133   def shared
134     # The purpose of this endpoint is to return the toplevel set of
135     # groups which are *not* reachable through a direct ownership
136     # chain of projects starting from the current user account.  In
137     # other words, groups which to which access was granted via a
138     # permission link or chain of links.
139     #
140     # This also returns (in the "included" field) the objects that own
141     # those projects (users or non-project groups).
142     #
143     #
144     # The intended use of this endpoint is to support clients which
145     # wish to browse those projects which are visible to the user but
146     # are not part of the "home" project.
147
148     load_limit_offset_order_params
149     load_filters_param
150
151     @objects = exclude_home Group.readable_by(*@read_users), Group
152
153     apply_where_limit_order_params
154
155     if params["include"] == "owner_uuid"
156       owners = @objects.map(&:owner_uuid).to_set
157       @extra_included = []
158       [Group, User].each do |klass|
159         @extra_included += klass.readable_by(*@read_users).where(uuid: owners.to_a).to_a
160       end
161     end
162
163     index
164   end
165
166   def self._shared_requires_parameters
167     rp = self._index_requires_parameters
168     rp[:include] = { type: 'string', required: false }
169     rp
170   end
171
172   protected
173
174   def load_searchable_objects
175     all_objects = []
176     @items_available = 0
177
178     # Reload the orders param, this time without prefixing unqualified
179     # columns ("name" => "groups.name"). Here, unqualified orders
180     # apply to each table being searched, not "groups".
181     load_limit_offset_order_params(fill_table_names: false)
182
183     # Trick apply_where_limit_order_params into applying suitable
184     # per-table values. *_all are the real ones we'll apply to the
185     # aggregate set.
186     limit_all = @limit
187     offset_all = @offset
188     # save the orders from the current request as determined by load_param,
189     # but otherwise discard them because we're going to be getting objects
190     # from many models
191     request_orders = @orders.clone
192     @orders = []
193
194     request_filters = @filters
195
196     klasses = [Group,
197      Job, PipelineInstance, PipelineTemplate, ContainerRequest, Workflow,
198      Collection,
199      Human, Specimen, Trait]
200
201     table_names = Hash[klasses.collect { |k| [k, k.table_name] }]
202
203     disabled_methods = Rails.configuration.API.DisabledAPIs
204     avail_klasses = table_names.select{|k, t| !disabled_methods.include?(t+'.index')}
205     klasses = avail_klasses.keys
206
207     request_filters.each do |col, op, val|
208       if col.index('.') && !table_names.values.include?(col.split('.', 2)[0])
209         raise ArgumentError.new("Invalid attribute '#{col}' in filter")
210       end
211     end
212
213     wanted_klasses = []
214     request_filters.each do |col,op,val|
215       if op == 'is_a'
216         (val.is_a?(Array) ? val : [val]).each do |type|
217           type = type.split('#')[-1]
218           type[0] = type[0].capitalize
219           wanted_klasses << type
220         end
221       end
222     end
223
224     filter_by_owner = {}
225     if @object
226       if params['recursive']
227         filter_by_owner[:owner_uuid] = [@object.uuid] + @object.descendant_project_uuids
228       else
229         filter_by_owner[:owner_uuid] = @object.uuid
230       end
231
232       if params['exclude_home_project']
233         raise ArgumentError.new "Cannot use 'exclude_home_project' with a parent object"
234       end
235     end
236
237     included_by_uuid = {}
238
239     seen_last_class = false
240     klasses.each do |klass|
241       @offset = 0 if seen_last_class  # reset offset for the new next type being processed
242
243       # if current klass is same as params['last_object_class'], mark that fact
244       seen_last_class = true if((params['count'].andand.==('none')) and
245                                 (params['last_object_class'].nil? or
246                                  params['last_object_class'].empty? or
247                                  params['last_object_class'] == klass.to_s))
248
249       # if klasses are specified, skip all other klass types
250       next if wanted_klasses.any? and !wanted_klasses.include?(klass.to_s)
251
252       # don't reprocess klass types that were already seen
253       next if params['count'] == 'none' and !seen_last_class
254
255       # don't process rest of object types if we already have needed number of objects
256       break if params['count'] == 'none' and all_objects.size >= limit_all
257
258       # If the currently requested orders specifically match the
259       # table_name for the current klass, apply that order.
260       # Otherwise, order by recency.
261       request_order =
262         request_orders.andand.find { |r| r =~ /^#{klass.table_name}\./i || r !~ /\./ } ||
263         klass.default_orders.join(", ")
264
265       @select = nil
266       where_conds = filter_by_owner
267       if klass == Collection
268         @select = klass.selectable_attributes - ["manifest_text"]
269       elsif klass == Group
270         where_conds = where_conds.merge(group_class: "project")
271       end
272
273       @filters = request_filters.map do |col, op, val|
274         if !col.index('.')
275           [col, op, val]
276         elsif (col = col.split('.', 2))[0] == klass.table_name
277           [col[1], op, val]
278         else
279           nil
280         end
281       end.compact
282
283       @objects = klass.readable_by(*@read_users, {:include_trash => params[:include_trash]}).
284                  order(request_order).where(where_conds)
285
286       if params['exclude_home_project']
287         @objects = exclude_home @objects, klass
288       end
289
290       klass_limit = limit_all - all_objects.count
291       @limit = klass_limit
292       apply_where_limit_order_params klass
293       klass_object_list = object_list(model_class: klass)
294       klass_items_available = klass_object_list[:items_available] || 0
295       @items_available += klass_items_available
296       @offset = [@offset - klass_items_available, 0].max
297       all_objects += klass_object_list[:items]
298
299       if klass_object_list[:limit] < klass_limit
300         # object_list() had to reduce @limit to comply with
301         # max_index_database_read. From now on, we'll do all queries
302         # with limit=0 and just accumulate items_available.
303         limit_all = all_objects.count
304       end
305
306       if params["include"] == "owner_uuid"
307         owners = klass_object_list[:items].map {|i| i[:owner_uuid]}.to_set
308         [Group, User].each do |ownerklass|
309           ownerklass.readable_by(*@read_users).where(uuid: owners.to_a).each do |ow|
310             included_by_uuid[ow.uuid] = ow
311           end
312         end
313       end
314     end
315
316     if params["include"]
317       @extra_included = included_by_uuid.values
318     end
319
320     @objects = all_objects
321     @limit = limit_all
322     @offset = offset_all
323   end
324
325   protected
326
327   def exclude_home objectlist, klass
328     # select records that are readable by current user AND
329     #   the owner_uuid is a user (but not the current user) OR
330     #   the owner_uuid is not readable by the current user
331     #   the owner_uuid is a group but group_class is not a project
332
333     read_parent_check = if current_user.is_admin
334                           ""
335                         else
336                           "NOT EXISTS(SELECT 1 FROM #{PERMISSION_VIEW} WHERE "+
337                             "user_uuid=(:user_uuid) AND target_uuid=#{klass.table_name}.owner_uuid AND perm_level >= 1) OR "
338                         end
339
340     objectlist.where("#{klass.table_name}.owner_uuid IN (SELECT users.uuid FROM users WHERE users.uuid != (:user_uuid)) OR "+
341                      read_parent_check+
342                      "EXISTS(SELECT 1 FROM groups as gp where gp.uuid=#{klass.table_name}.owner_uuid and gp.group_class != 'project')",
343                      user_uuid: current_user.uuid)
344   end
345
346 end