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