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