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