1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
7 class Arvados::V1::GroupsController < ApplicationController
8 include TrashableController
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
14 def self._index_requires_parameters
18 type: 'boolean', required: false, default: false, description: "Include items whose is_trashed attribute is true.",
23 def self._show_requires_parameters
27 type: 'boolean', required: false, default: false, description: "Show group/project even if its is_trashed attribute is true.",
32 def self._contents_requires_parameters
33 params = _index_requires_parameters.
36 type: 'string', required: false, default: '',
39 type: 'boolean', required: false, default: false, description: 'Include contents from child groups recursively.',
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.',
44 include_old_versions: {
45 type: 'boolean', required: false, default: false, description: 'Include past collection versions.',
51 def self._create_requires_parameters
59 description: 'defer permissions update',
65 def self._update_requires_parameters
73 description: 'defer permissions update',
81 @object = model_class.new(resource_attrs.merge({async_permissions_update: true}))
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)
102 def render_404_if_no_object
103 if params[:action] == 'contents'
111 elsif (@object = User.where(uuid: params[:uuid]).first)
112 # "Home" pseudo-project
123 @orig_select = @select
124 load_searchable_objects
126 :kind => "arvados#objectList",
131 :items => @objects.as_api_response(nil)
133 if params[:count] != 'none'
134 list[:items_available] = @items_available
137 list[:included] = @extra_included.as_api_response(nil, {select: @orig_select})
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.
149 # This also returns (in the "included" field) the objects that own
150 # those projects (users or non-project groups).
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.
156 load_limit_offset_order_params
159 @objects = exclude_home Group.readable_by(*@read_users), Group
161 apply_where_limit_order_params
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
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
182 def self._shared_requires_parameters
183 rp = self._index_requires_parameters
184 rp[:include] = { type: 'string', required: false }
190 def load_include_param
191 @include = params[:include]
192 if @include.nil? || @include == ""
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]
199 return send_error("'include' parameter must be a string or array", status: 422)
203 def load_searchable_objects
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)
212 if params['count'] == 'none' and @offset != 0 and (params['last_object_class'].nil? or params['last_object_class'].empty?)
213 # can't use offset without getting counts, so
214 # fall back to count=exact behavior.
215 params['count'] = 'exact'
216 set_count_none = true
219 # Trick apply_where_limit_order_params into applying suitable
220 # per-table values. *_all are the real ones we'll apply to the
224 # save the orders from the current request as determined by load_param,
225 # but otherwise discard them because we're going to be getting objects
227 request_orders = @orders.clone
230 request_filters = @filters
232 klasses = [Group, ContainerRequest, Workflow, Collection]
234 table_names = Hash[klasses.collect { |k| [k, k.table_name] }]
236 disabled_methods = Rails.configuration.API.DisabledAPIs
237 avail_klasses = table_names.select{|k, t| !disabled_methods[t+'.index']}
238 klasses = avail_klasses.keys
240 request_filters.each do |col, op, val|
241 if col.index('.') && !table_names.values.include?(col.split('.', 2)[0])
242 raise ArgumentError.new("Invalid attribute '#{col}' in filter")
247 request_filters.each do |col,op,val|
249 (val.is_a?(Array) ? val : [val]).each do |type|
250 type = type.split('#')[-1]
251 type[0] = type[0].capitalize
252 wanted_klasses << type
259 if params['recursive']
260 filter_by_owner[:owner_uuid] = [@object.uuid] + @object.descendant_project_uuids
262 filter_by_owner[:owner_uuid] = @object.uuid
265 if params['exclude_home_project']
266 raise ArgumentError.new "Cannot use 'exclude_home_project' with a parent object"
270 # Check that any fields in @select are valid for at least one class
273 klasses.each do |klass|
274 all_attributes.concat klass.selectable_attributes
276 if klasses.include?(ContainerRequest) && @include.include?("container_uuid")
277 all_attributes.concat Container.selectable_attributes
279 @select.each do |check|
280 if !all_attributes.include? check
281 raise ArgumentError.new "Invalid attribute '#{check}' in select"
285 any_selections = @select
287 included_by_uuid = {}
289 seen_last_class = false
293 klasses.each do |klass|
294 # check if current klass is same as params['last_object_class']
295 seen_last_class = true if((params['count'].andand.==('none')) and
296 (params['last_object_class'].nil? or
297 params['last_object_class'].empty? or
298 params['last_object_class'] == klass.to_s))
300 # if klasses are specified, skip all other klass types
301 next if wanted_klasses.any? and !wanted_klasses.include?(klass.to_s)
303 # if specified, and count=none, then only look at the klass in
305 # for whatever reason, this parameter exists separately from 'wanted_klasses'
306 next if params['count'] == 'none' and !seen_last_class
308 # don't process rest of object types if we already have needed number of objects
309 break if params['count'] == 'none' and all_objects.size >= limit_all
311 # If the currently requested orders specifically match the
312 # table_name for the current klass, apply that order.
313 # Otherwise, order by recency.
315 request_orders.andand.find { |r| r =~ /^#{klass.table_name}\./i || r !~ /\./ } ||
316 klass.default_orders.join(", ")
318 @select = select_for_klass any_selections, klass, false
320 where_conds = filter_by_owner
321 if klass == Collection && @select.nil?
322 @select = klass.selectable_attributes - ["manifest_text", "unsigned_manifest_text"]
324 where_conds = where_conds.merge(group_class: ["project","filter"])
327 # Make signed manifest_text not selectable because controller
328 # currently doesn't know to sign it.
330 @select = @select - ["manifest_text"]
333 @filters = request_filters.map do |col, op, val|
336 elsif (col = col.split('.', 2))[0] == klass.table_name
343 @objects = klass.readable_by(*@read_users, {
344 :include_trash => params[:include_trash],
345 :include_old_versions => params[:include_old_versions]
346 }).order(request_order).where(where_conds)
348 if params['exclude_home_project']
349 @objects = exclude_home @objects, klass
352 # Adjust the limit based on number of objects fetched so far
353 klass_limit = limit_all - all_objects.count
357 apply_where_limit_order_params klass
358 rescue ArgumentError => e
359 if e.inspect =~ /Invalid attribute '.+' for operator '.+' in filter/ or
360 e.inspect =~ /Invalid attribute '.+' for subproperty filter/
361 error_by_class[klass.name] = e
369 # This actually fetches the objects
370 klass_object_list = object_list(model_class: klass)
372 # If count=none, :items_available will be nil, and offset is
374 klass_items_available = klass_object_list[:items_available] || 0
375 @items_available += klass_items_available
376 @offset = [@offset - klass_items_available, 0].max
378 # Add objects to the list of objects to be returned.
379 all_objects += klass_object_list[:items]
381 if klass_object_list[:limit] < klass_limit
382 # object_list() had to reduce @limit to comply with
383 # max_index_database_read. From now on, we'll do all queries
384 # with limit=0 and just accumulate items_available.
385 limit_all = all_objects.count
388 if @include.include?("owner_uuid")
389 owners = klass_object_list[:items].map {|i| i[:owner_uuid]}.to_set
390 [Group, User].each do |ownerklass|
391 ownerklass.readable_by(*@read_users).where(uuid: owners.to_a).each do |ow|
392 included_by_uuid[ow.uuid] = ow
397 if @include.include?("container_uuid") && klass == ContainerRequest
398 containers = klass_object_list[:items].collect { |cr| cr[:container_uuid] }.to_set
399 Container.where(uuid: containers.to_a).each do |c|
400 included_by_uuid[c.uuid] = c
405 # Only error out when every searchable object type errored out
406 if !any_success && error_by_class.size > 0
407 error_msg = error_by_class.collect do |klass, err|
408 "#{err} on object type #{klass}"
410 raise ArgumentError.new(error_msg)
414 @extra_included = included_by_uuid.values
418 params['count'] = 'none'
421 @objects = all_objects
426 def exclude_home objectlist, klass
427 # select records that are readable by current user AND
428 # the owner_uuid is a user (but not the current user) OR
429 # the owner_uuid is not readable by the current user
430 # the owner_uuid is a group but group_class is not a project
432 read_parent_check = if current_user.is_admin
435 "NOT EXISTS(SELECT 1 FROM #{PERMISSION_VIEW} WHERE "+
436 "user_uuid=(:user_uuid) AND target_uuid=#{klass.table_name}.owner_uuid AND perm_level >= 1) OR "
439 objectlist.where("#{klass.table_name}.owner_uuid IN (SELECT users.uuid FROM users WHERE users.uuid != (:user_uuid)) OR "+
441 "EXISTS(SELECT 1 FROM groups as gp where gp.uuid=#{klass.table_name}.owner_uuid and gp.group_class != 'project')",
442 user_uuid: current_user.uuid)