Merge branch '21640-max-nofile'
[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   before_action :load_include_param, only: [:shared, :contents]
11   skip_before_action :find_object_by_uuid, only: :shared
12   skip_before_action :render_404_if_no_object, only: :shared
13
14   TRASHABLE_CLASSES = ['project']
15
16   def self._index_requires_parameters
17     (super rescue {}).
18       merge({
19         include_trash: {
20           type: 'boolean', required: false, default: false, description: "Include items whose is_trashed attribute is true.",
21         },
22       })
23   end
24
25   def self._show_requires_parameters
26     (super rescue {}).
27       merge({
28         include_trash: {
29           type: 'boolean', required: false, default: false, description: "Show group/project even if its is_trashed attribute is true.",
30         },
31       })
32   end
33
34   def self._contents_requires_parameters
35     params = _index_requires_parameters.
36       merge({
37               uuid: {
38                 type: 'string', required: false, default: '',
39               },
40               recursive: {
41                 type: 'boolean', required: false, default: false, description: 'Include contents from child groups recursively.',
42               },
43               include: {
44                 type: 'array', required: false, description: 'Include objects referred to by listed fields in "included" response field. Subsets of ["owner_uuid", "container_uuid"] are supported.',
45               },
46               include_old_versions: {
47                 type: 'boolean', required: false, default: false, description: 'Include past collection versions.',
48               }
49             })
50     params
51   end
52
53   def self._create_requires_parameters
54     super.merge(
55       {
56         async: {
57           required: false,
58           type: 'boolean',
59           location: 'query',
60           default: false,
61           description: 'defer permissions update',
62         }
63       }
64     )
65   end
66
67   def self._update_requires_parameters
68     super.merge(
69       {
70         async: {
71           required: false,
72           type: 'boolean',
73           location: 'query',
74           default: false,
75           description: 'defer permissions update',
76         }
77       }
78     )
79   end
80
81   def create
82     if params[:async]
83       @object = model_class.new(resource_attrs.merge({async_permissions_update: true}))
84       @object.save!
85       render_accepted
86     else
87       super
88     end
89   end
90
91   def update
92     if params[:async]
93       attrs_to_update = resource_attrs.reject { |k, v|
94         [:kind, :etag, :href].index k
95       }.merge({async_permissions_update: true})
96       @object.update!(attrs_to_update)
97       @object.save!
98       render_accepted
99     else
100       super
101     end
102   end
103
104   def destroy
105     if !TRASHABLE_CLASSES.include?(@object.group_class)
106       @object.destroy
107       show
108     else
109       super # Calls destroy from TrashableController module
110     end
111   end
112
113   def render_404_if_no_object
114     if params[:action] == 'contents'
115       if !params[:uuid]
116         # OK!
117         @object = nil
118         true
119       elsif @object
120         # Project group
121         true
122       elsif (@object = User.where(uuid: params[:uuid]).first)
123         # "Home" pseudo-project
124         true
125       else
126         super
127       end
128     else
129       super
130     end
131   end
132
133   def contents
134     @orig_select = @select
135     load_searchable_objects
136     list = {
137       :kind => "arvados#objectList",
138       :etag => "",
139       :self_link => "",
140       :offset => @offset,
141       :limit => @limit,
142       :items => @objects.as_api_response(nil)
143     }
144     if params[:count] != 'none'
145       list[:items_available] = @items_available
146     end
147     if @extra_included
148       list[:included] = @extra_included.as_api_response(nil, {select: @orig_select})
149     end
150     send_json(list)
151   end
152
153   def shared
154     # The purpose of this endpoint is to return the toplevel set of
155     # groups which are *not* reachable through a direct ownership
156     # chain of projects starting from the current user account.  In
157     # other words, groups which to which access was granted via a
158     # permission link or chain of links.
159     #
160     # This also returns (in the "included" field) the objects that own
161     # those projects (users or non-project groups).
162     #
163     # The intended use of this endpoint is to support clients which
164     # wish to browse those projects which are visible to the user but
165     # are not part of the "home" project.
166
167     load_limit_offset_order_params
168     load_filters_param
169
170     @objects = exclude_home Group.readable_by(*@read_users), Group
171
172     apply_where_limit_order_params
173
174     if @include.include?("owner_uuid")
175       owners = @objects.map(&:owner_uuid).to_set
176       @extra_included ||= []
177       [Group, User].each do |klass|
178         @extra_included += klass.readable_by(*@read_users).where(uuid: owners.to_a).to_a
179       end
180     end
181
182     if @include.include?("container_uuid")
183       @extra_included ||= []
184       container_uuids = @objects.map { |o|
185         o.respond_to?(:container_uuid) ? o.container_uuid : nil
186       }.compact.to_set.to_a
187       @extra_included += Container.where(uuid: container_uuids).to_a
188     end
189
190     index
191   end
192
193   def self._shared_requires_parameters
194     rp = self._index_requires_parameters
195     rp[:include] = { type: 'string', required: false }
196     rp
197   end
198
199   protected
200
201   def load_include_param
202     @include = params[:include]
203     if @include.nil? || @include == ""
204       @include = Set[]
205     elsif @include.is_a?(String) && @include.start_with?('[')
206       @include = SafeJSON.load(@include).to_set
207     elsif @include.is_a?(String)
208       @include = Set[@include]
209     else
210       return send_error("'include' parameter must be a string or array", status: 422)
211     end
212   end
213
214   def load_searchable_objects
215     all_objects = []
216     @items_available = 0
217
218     # Reload the orders param, this time without prefixing unqualified
219     # columns ("name" => "groups.name"). Here, unqualified orders
220     # apply to each table being searched, not "groups".
221     load_limit_offset_order_params(fill_table_names: false)
222
223     if params['count'] == 'none' and @offset != 0 and (params['last_object_class'].nil? or params['last_object_class'].empty?)
224       # can't use offset without getting counts, so
225       # fall back to count=exact behavior.
226       params['count'] = 'exact'
227       set_count_none = true
228     end
229
230     # Trick apply_where_limit_order_params into applying suitable
231     # per-table values. *_all are the real ones we'll apply to the
232     # aggregate set.
233     limit_all = @limit
234     offset_all = @offset
235     # save the orders from the current request as determined by load_param,
236     # but otherwise discard them because we're going to be getting objects
237     # from many models
238     request_orders = @orders.clone
239     @orders = []
240
241     request_filters = @filters
242
243     klasses = [Group, ContainerRequest, Workflow, Collection]
244
245     table_names = Hash[klasses.collect { |k| [k, k.table_name] }]
246
247     disabled_methods = Rails.configuration.API.DisabledAPIs
248     avail_klasses = table_names.select{|k, t| !disabled_methods[t+'.index']}
249     klasses = avail_klasses.keys
250
251     request_filters.each do |col, op, val|
252       if col.index('.') && !table_names.values.include?(col.split('.', 2)[0])
253         raise ArgumentError.new("Invalid attribute '#{col}' in filter")
254       end
255     end
256
257     wanted_klasses = []
258     request_filters.each do |col,op,val|
259       if op == 'is_a'
260         (val.is_a?(Array) ? val : [val]).each do |type|
261           type = type.split('#')[-1]
262           type[0] = type[0].capitalize
263           wanted_klasses << type
264         end
265       end
266     end
267
268     filter_by_owner = {}
269     if @object
270       if params['recursive']
271         filter_by_owner[:owner_uuid] = [@object.uuid] + @object.descendant_project_uuids
272       else
273         filter_by_owner[:owner_uuid] = @object.uuid
274       end
275
276       if params['exclude_home_project']
277         raise ArgumentError.new "Cannot use 'exclude_home_project' with a parent object"
278       end
279     end
280
281     # Check that any fields in @select are valid for at least one class
282     if @select
283       all_attributes = []
284       klasses.each do |klass|
285         all_attributes.concat klass.selectable_attributes
286       end
287       if klasses.include?(ContainerRequest) && @include.include?("container_uuid")
288         all_attributes.concat Container.selectable_attributes
289       end
290       @select.each do |check|
291         if !all_attributes.include? check
292           raise ArgumentError.new "Invalid attribute '#{check}' in select"
293         end
294       end
295     end
296     any_selections = @select
297
298     included_by_uuid = {}
299
300     seen_last_class = false
301     error_by_class = {}
302     any_success = false
303
304     klasses.each do |klass|
305       # check if current klass is same as params['last_object_class']
306       seen_last_class = true if((params['count'].andand.==('none')) and
307                                 (params['last_object_class'].nil? or
308                                  params['last_object_class'].empty? or
309                                  params['last_object_class'] == klass.to_s))
310
311       # if klasses are specified, skip all other klass types
312       next if wanted_klasses.any? and !wanted_klasses.include?(klass.to_s)
313
314       # if specified, and count=none, then only look at the klass in
315       # last_object_class.
316       # for whatever reason, this parameter exists separately from 'wanted_klasses'
317       next if params['count'] == 'none' and !seen_last_class
318
319       # don't process rest of object types if we already have needed number of objects
320       break if params['count'] == 'none' and all_objects.size >= limit_all
321
322       # If the currently requested orders specifically match the
323       # table_name for the current klass, apply that order.
324       # Otherwise, order by recency.
325       request_order =
326         request_orders.andand.find { |r| r =~ /^#{klass.table_name}\./i || r !~ /\./ } ||
327         klass.default_orders.join(", ")
328
329       @select = select_for_klass any_selections, klass, false
330
331       where_conds = filter_by_owner
332       if klass == Collection && @select.nil?
333         @select = klass.selectable_attributes - ["manifest_text", "unsigned_manifest_text"]
334       elsif klass == Group
335         where_conds = where_conds.merge(group_class: ["project","filter"])
336       end
337
338       # Make signed manifest_text not selectable because controller
339       # currently doesn't know to sign it.
340       if @select
341         @select = @select - ["manifest_text"]
342       end
343
344       @filters = request_filters.map do |col, op, val|
345         if !col.index('.')
346           [col, op, val]
347         elsif (col = col.split('.', 2))[0] == klass.table_name
348           [col[1], op, val]
349         else
350           nil
351         end
352       end.compact
353
354       @objects = klass.readable_by(*@read_users, {
355           :include_trash => params[:include_trash],
356           :include_old_versions => params[:include_old_versions]
357         }).order(request_order).where(where_conds)
358
359       if params['exclude_home_project']
360         @objects = exclude_home @objects, klass
361       end
362
363       # Adjust the limit based on number of objects fetched so far
364       klass_limit = limit_all - all_objects.count
365       @limit = klass_limit
366
367       begin
368         apply_where_limit_order_params klass
369       rescue ArgumentError => e
370         if e.inspect =~ /Invalid attribute '.+' for operator '.+' in filter/ or
371           e.inspect =~ /Invalid attribute '.+' for subproperty filter/
372           error_by_class[klass.name] = e
373           next
374         end
375         raise
376       else
377         any_success = true
378       end
379
380       # This actually fetches the objects
381       klass_object_list = object_list(model_class: klass)
382
383       # If count=none, :items_available will be nil, and offset is
384       # required to be 0.
385       klass_items_available = klass_object_list[:items_available] || 0
386       @items_available += klass_items_available
387       @offset = [@offset - klass_items_available, 0].max
388
389       # Add objects to the list of objects to be returned.
390       all_objects += klass_object_list[:items]
391
392       if klass_object_list[:limit] < klass_limit
393         # object_list() had to reduce @limit to comply with
394         # max_index_database_read. From now on, we'll do all queries
395         # with limit=0 and just accumulate items_available.
396         limit_all = all_objects.count
397       end
398
399       if @include.include?("owner_uuid")
400         owners = klass_object_list[:items].map {|i| i[:owner_uuid]}.to_set
401         [Group, User].each do |ownerklass|
402           ownerklass.readable_by(*@read_users).where(uuid: owners.to_a).each do |ow|
403             included_by_uuid[ow.uuid] = ow
404           end
405         end
406       end
407
408       if @include.include?("container_uuid") && klass == ContainerRequest
409         containers = klass_object_list[:items].collect { |cr| cr[:container_uuid] }.to_set
410         Container.where(uuid: containers.to_a).each do |c|
411           included_by_uuid[c.uuid] = c
412         end
413       end
414     end
415
416     # Only error out when every searchable object type errored out
417     if !any_success && error_by_class.size > 0
418       error_msg = error_by_class.collect do |klass, err|
419         "#{err} on object type #{klass}"
420       end.join("\n")
421       raise ArgumentError.new(error_msg)
422     end
423
424     if !@include.empty?
425       @extra_included = included_by_uuid.values
426     end
427
428     if set_count_none
429       params['count'] = 'none'
430     end
431
432     @objects = all_objects
433     @limit = limit_all
434     @offset = offset_all
435   end
436
437   def exclude_home objectlist, klass
438     # select records that are readable by current user AND
439     #   the owner_uuid is a user (but not the current user) OR
440     #   the owner_uuid is not readable by the current user
441     #   the owner_uuid is a group but group_class is not a project
442
443     read_parent_check = if current_user.is_admin
444                           ""
445                         else
446                           "NOT EXISTS(SELECT 1 FROM #{PERMISSION_VIEW} WHERE "+
447                             "user_uuid=(:user_uuid) AND target_uuid=#{klass.table_name}.owner_uuid AND perm_level >= 1) OR "
448                         end
449
450     objectlist.where("#{klass.table_name}.owner_uuid IN (SELECT users.uuid FROM users WHERE users.uuid != (:user_uuid)) OR "+
451                      read_parent_check+
452                      "EXISTS(SELECT 1 FROM groups as gp where gp.uuid=#{klass.table_name}.owner_uuid and gp.group_class != 'project')",
453                      user_uuid: current_user.uuid)
454   end
455 end