17589: Disallow offset with group contents count=none
[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   def self._index_requires_parameters
14     (super rescue {}).
15       merge({
16         include_trash: {
17           type: 'boolean', required: false, default: false, description: "Include items whose is_trashed attribute is true.",
18         },
19       })
20   end
21
22   def self._show_requires_parameters
23     (super rescue {}).
24       merge({
25         include_trash: {
26           type: 'boolean', required: false, default: false, description: "Show group/project even if its is_trashed attribute is true.",
27         },
28       })
29   end
30
31   def self._contents_requires_parameters
32     params = _index_requires_parameters.
33       merge({
34               uuid: {
35                 type: 'string', required: false, default: nil,
36               },
37               recursive: {
38                 type: 'boolean', required: false, default: false, description: 'Include contents from child groups recursively.',
39               },
40               include: {
41                 type: 'string', required: false, description: 'Include objects referred to by listed field in "included" (only owner_uuid).',
42               },
43               include_old_versions: {
44                 type: 'boolean', required: false, default: false, description: 'Include past collection versions.',
45               }
46             })
47     params.delete(:select)
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_attributes!(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     load_searchable_objects
124     list = {
125       :kind => "arvados#objectList",
126       :etag => "",
127       :self_link => "",
128       :offset => @offset,
129       :limit => @limit,
130       :items => @objects.as_api_response(nil)
131     }
132     if params[:count] != 'none'
133       list[:items_available] = @items_available
134     end
135     if @extra_included
136       list[:included] = @extra_included.as_api_response(nil, {select: @select})
137     end
138     send_json(list)
139   end
140
141   def shared
142     # The purpose of this endpoint is to return the toplevel set of
143     # groups which are *not* reachable through a direct ownership
144     # chain of projects starting from the current user account.  In
145     # other words, groups which to which access was granted via a
146     # permission link or chain of links.
147     #
148     # This also returns (in the "included" field) the objects that own
149     # those projects (users or non-project groups).
150     #
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 params["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     index
172   end
173
174   def self._shared_requires_parameters
175     rp = self._index_requires_parameters
176     rp[:include] = { type: 'string', required: false }
177     rp
178   end
179
180   protected
181
182   def load_searchable_objects
183     all_objects = []
184     @items_available = 0
185
186     # Reload the orders param, this time without prefixing unqualified
187     # columns ("name" => "groups.name"). Here, unqualified orders
188     # apply to each table being searched, not "groups".
189     load_limit_offset_order_params(fill_table_names: false)
190
191     if params['count'] == 'none' and @offset != 0
192       raise ArgumentError.new("Cannot use count=none with a nonzero offset")
193     end
194
195     # Trick apply_where_limit_order_params into applying suitable
196     # per-table values. *_all are the real ones we'll apply to the
197     # aggregate set.
198     limit_all = @limit
199     offset_all = @offset
200     # save the orders from the current request as determined by load_param,
201     # but otherwise discard them because we're going to be getting objects
202     # from many models
203     request_orders = @orders.clone
204     @orders = []
205
206     request_filters = @filters
207
208     klasses = [Group,
209      Job, PipelineInstance, PipelineTemplate, ContainerRequest, Workflow,
210      Collection,
211      Human, Specimen, Trait]
212
213     table_names = Hash[klasses.collect { |k| [k, k.table_name] }]
214
215     disabled_methods = Rails.configuration.API.DisabledAPIs
216     avail_klasses = table_names.select{|k, t| !disabled_methods[t+'.index']}
217     klasses = avail_klasses.keys
218
219     request_filters.each do |col, op, val|
220       if col.index('.') && !table_names.values.include?(col.split('.', 2)[0])
221         raise ArgumentError.new("Invalid attribute '#{col}' in filter")
222       end
223     end
224
225     wanted_klasses = []
226     request_filters.each do |col,op,val|
227       if op == 'is_a'
228         (val.is_a?(Array) ? val : [val]).each do |type|
229           type = type.split('#')[-1]
230           type[0] = type[0].capitalize
231           wanted_klasses << type
232         end
233       end
234     end
235
236     filter_by_owner = {}
237     if @object
238       if params['recursive']
239         filter_by_owner[:owner_uuid] = [@object.uuid] + @object.descendant_project_uuids
240       else
241         filter_by_owner[:owner_uuid] = @object.uuid
242       end
243
244       if params['exclude_home_project']
245         raise ArgumentError.new "Cannot use 'exclude_home_project' with a parent object"
246       end
247     end
248
249     included_by_uuid = {}
250
251     seen_last_class = false
252     klasses.each do |klass|
253       # if current klass is same as params['last_object_class'], mark that fact
254       seen_last_class = true if((params['count'].andand.==('none')) and
255                                 (params['last_object_class'].nil? or
256                                  params['last_object_class'].empty? or
257                                  params['last_object_class'] == klass.to_s))
258
259       # if klasses are specified, skip all other klass types
260       next if wanted_klasses.any? and !wanted_klasses.include?(klass.to_s)
261
262       # don't reprocess klass types that were already seen
263       next if params['count'] == 'none' and !seen_last_class
264
265       # don't process rest of object types if we already have needed number of objects
266       break if params['count'] == 'none' and all_objects.size >= limit_all
267
268       # If the currently requested orders specifically match the
269       # table_name for the current klass, apply that order.
270       # Otherwise, order by recency.
271       request_order =
272         request_orders.andand.find { |r| r =~ /^#{klass.table_name}\./i || r !~ /\./ } ||
273         klass.default_orders.join(", ")
274
275       @select = nil
276       where_conds = filter_by_owner
277       if klass == Collection
278         @select = klass.selectable_attributes - ["manifest_text", "unsigned_manifest_text"]
279       elsif klass == Group
280         where_conds = where_conds.merge(group_class: ["project","filter"])
281       end
282
283       @filters = request_filters.map do |col, op, val|
284         if !col.index('.')
285           [col, op, val]
286         elsif (col = col.split('.', 2))[0] == klass.table_name
287           [col[1], op, val]
288         else
289           nil
290         end
291       end.compact
292
293       @objects = klass.readable_by(*@read_users, {
294           :include_trash => params[:include_trash],
295           :include_old_versions => params[:include_old_versions]
296         }).order(request_order).where(where_conds)
297
298       if params['exclude_home_project']
299         @objects = exclude_home @objects, klass
300       end
301
302       # Adjust the limit based on number of objects fetched so far
303       klass_limit = limit_all - all_objects.count
304       @limit = klass_limit
305       apply_where_limit_order_params klass
306
307       # This actually fetches the objects
308       klass_object_list = object_list(model_class: klass)
309
310       # If count=none, :items_available will be nil, and offset is
311       # required to be 0.
312       klass_items_available = klass_object_list[:items_available] || 0
313       @items_available += klass_items_available
314       @offset = [@offset - klass_items_available, 0].max
315
316       # Add objects to the list of objects to be returned.
317       all_objects += klass_object_list[:items]
318
319       if klass_object_list[:limit] < klass_limit
320         # object_list() had to reduce @limit to comply with
321         # max_index_database_read. From now on, we'll do all queries
322         # with limit=0 and just accumulate items_available.
323         limit_all = all_objects.count
324       end
325
326       if params["include"] == "owner_uuid"
327         owners = klass_object_list[:items].map {|i| i[:owner_uuid]}.to_set
328         [Group, User].each do |ownerklass|
329           ownerklass.readable_by(*@read_users).where(uuid: owners.to_a).each do |ow|
330             included_by_uuid[ow.uuid] = ow
331           end
332         end
333       end
334     end
335
336     if params["include"]
337       @extra_included = included_by_uuid.values
338     end
339
340     @objects = all_objects
341     @limit = limit_all
342     @offset = offset_all
343   end
344
345   protected
346
347   def exclude_home objectlist, klass
348     # select records that are readable by current user AND
349     #   the owner_uuid is a user (but not the current user) OR
350     #   the owner_uuid is not readable by the current user
351     #   the owner_uuid is a group but group_class is not a project
352
353     read_parent_check = if current_user.is_admin
354                           ""
355                         else
356                           "NOT EXISTS(SELECT 1 FROM #{PERMISSION_VIEW} WHERE "+
357                             "user_uuid=(:user_uuid) AND target_uuid=#{klass.table_name}.owner_uuid AND perm_level >= 1) OR "
358                         end
359
360     objectlist.where("#{klass.table_name}.owner_uuid IN (SELECT users.uuid FROM users WHERE users.uuid != (:user_uuid)) OR "+
361                      read_parent_check+
362                      "EXISTS(SELECT 1 FROM groups as gp where gp.uuid=#{klass.table_name}.owner_uuid and gp.group_class != 'project')",
363                      user_uuid: current_user.uuid)
364   end
365
366 end