18947: Remove errant uses of runsu.sh.
[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.delete(:select)
50     params
51   end
52
53   def self._create_requires_parameters
54     super.merge(
55       {
56         async: {
57           required: false,
58           type: 'boolean',
59           location: 'query',
60           default: false,
61           description: 'defer permissions update',
62         }
63       }
64     )
65   end
66
67   def self._update_requires_parameters
68     super.merge(
69       {
70         async: {
71           required: false,
72           type: 'boolean',
73           location: 'query',
74           default: false,
75           description: 'defer permissions update',
76         }
77       }
78     )
79   end
80
81   def create
82     if params[:async]
83       @object = model_class.new(resource_attrs.merge({async_permissions_update: true}))
84       @object.save!
85       render_accepted
86     else
87       super
88     end
89   end
90
91   def update
92     if params[:async]
93       attrs_to_update = resource_attrs.reject { |k, v|
94         [:kind, :etag, :href].index k
95       }.merge({async_permissions_update: true})
96       @object.update_attributes!(attrs_to_update)
97       @object.save!
98       render_accepted
99     else
100       super
101     end
102   end
103
104   def destroy
105     if !TRASHABLE_CLASSES.include?(@object.group_class)
106       return @object.destroy
107       show
108     else
109       super # Calls destroy from TrashableController module
110     end
111   end
112
113   def render_404_if_no_object
114     if params[:action] == 'contents'
115       if !params[:uuid]
116         # OK!
117         @object = nil
118         true
119       elsif @object
120         # Project group
121         true
122       elsif (@object = User.where(uuid: params[:uuid]).first)
123         # "Home" pseudo-project
124         true
125       else
126         super
127       end
128     else
129       super
130     end
131   end
132
133   def contents
134     load_searchable_objects
135     list = {
136       :kind => "arvados#objectList",
137       :etag => "",
138       :self_link => "",
139       :offset => @offset,
140       :limit => @limit,
141       :items => @objects.as_api_response(nil)
142     }
143     if params[:count] != 'none'
144       list[:items_available] = @items_available
145     end
146     if @extra_included
147       list[:included] = @extra_included.as_api_response(nil, {select: @select})
148     end
149     send_json(list)
150   end
151
152   def shared
153     # The purpose of this endpoint is to return the toplevel set of
154     # groups which are *not* reachable through a direct ownership
155     # chain of projects starting from the current user account.  In
156     # other words, groups which to which access was granted via a
157     # permission link or chain of links.
158     #
159     # This also returns (in the "included" field) the objects that own
160     # those projects (users or non-project groups).
161     #
162     #
163     # The intended use of this endpoint is to support clients which
164     # wish to browse those projects which are visible to the user but
165     # are not part of the "home" project.
166
167     load_limit_offset_order_params
168     load_filters_param
169
170     @objects = exclude_home Group.readable_by(*@read_users), Group
171
172     apply_where_limit_order_params
173
174     if params["include"] == "owner_uuid"
175       owners = @objects.map(&:owner_uuid).to_set
176       @extra_included = []
177       [Group, User].each do |klass|
178         @extra_included += klass.readable_by(*@read_users).where(uuid: owners.to_a).to_a
179       end
180     end
181
182     index
183   end
184
185   def self._shared_requires_parameters
186     rp = self._index_requires_parameters
187     rp[:include] = { type: 'string', required: false }
188     rp
189   end
190
191   protected
192
193   def load_searchable_objects
194     all_objects = []
195     @items_available = 0
196
197     # Reload the orders param, this time without prefixing unqualified
198     # columns ("name" => "groups.name"). Here, unqualified orders
199     # apply to each table being searched, not "groups".
200     load_limit_offset_order_params(fill_table_names: false)
201
202     if params['count'] == 'none' and @offset != 0 and (params['last_object_class'].nil? or params['last_object_class'].empty?)
203       # can't use offset without getting counts, so
204       # fall back to count=exact behavior.
205       params['count'] = 'exact'
206       set_count_none = true
207     end
208
209     # Trick apply_where_limit_order_params into applying suitable
210     # per-table values. *_all are the real ones we'll apply to the
211     # aggregate set.
212     limit_all = @limit
213     offset_all = @offset
214     # save the orders from the current request as determined by load_param,
215     # but otherwise discard them because we're going to be getting objects
216     # from many models
217     request_orders = @orders.clone
218     @orders = []
219
220     request_filters = @filters
221
222     klasses = [Group,
223      Job, PipelineInstance, PipelineTemplate, ContainerRequest, Workflow,
224      Collection,
225      Human, Specimen, Trait]
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     included_by_uuid = {}
264
265     seen_last_class = false
266     klasses.each do |klass|
267       # check if current klass is same as params['last_object_class']
268       seen_last_class = true if((params['count'].andand.==('none')) and
269                                 (params['last_object_class'].nil? or
270                                  params['last_object_class'].empty? or
271                                  params['last_object_class'] == klass.to_s))
272
273       # if klasses are specified, skip all other klass types
274       next if wanted_klasses.any? and !wanted_klasses.include?(klass.to_s)
275
276       # if specified, and count=none, then only look at the klass in
277       # last_object_class.
278       # for whatever reason, this parameter exists separately from 'wanted_klasses'
279       next if params['count'] == 'none' and !seen_last_class
280
281       # don't process rest of object types if we already have needed number of objects
282       break if params['count'] == 'none' and all_objects.size >= limit_all
283
284       # If the currently requested orders specifically match the
285       # table_name for the current klass, apply that order.
286       # Otherwise, order by recency.
287       request_order =
288         request_orders.andand.find { |r| r =~ /^#{klass.table_name}\./i || r !~ /\./ } ||
289         klass.default_orders.join(", ")
290
291       @select = nil
292       where_conds = filter_by_owner
293       if klass == Collection
294         @select = klass.selectable_attributes - ["manifest_text", "unsigned_manifest_text"]
295       elsif klass == Group
296         where_conds = where_conds.merge(group_class: ["project","filter"])
297       end
298
299       @filters = request_filters.map do |col, op, val|
300         if !col.index('.')
301           [col, op, val]
302         elsif (col = col.split('.', 2))[0] == klass.table_name
303           [col[1], op, val]
304         else
305           nil
306         end
307       end.compact
308
309       @objects = klass.readable_by(*@read_users, {
310           :include_trash => params[:include_trash],
311           :include_old_versions => params[:include_old_versions]
312         }).order(request_order).where(where_conds)
313
314       if params['exclude_home_project']
315         @objects = exclude_home @objects, klass
316       end
317
318       # Adjust the limit based on number of objects fetched so far
319       klass_limit = limit_all - all_objects.count
320       @limit = klass_limit
321       apply_where_limit_order_params klass
322
323       # This actually fetches the objects
324       klass_object_list = object_list(model_class: klass)
325
326       # If count=none, :items_available will be nil, and offset is
327       # required to be 0.
328       klass_items_available = klass_object_list[:items_available] || 0
329       @items_available += klass_items_available
330       @offset = [@offset - klass_items_available, 0].max
331
332       # Add objects to the list of objects to be returned.
333       all_objects += klass_object_list[:items]
334
335       if klass_object_list[:limit] < klass_limit
336         # object_list() had to reduce @limit to comply with
337         # max_index_database_read. From now on, we'll do all queries
338         # with limit=0 and just accumulate items_available.
339         limit_all = all_objects.count
340       end
341
342       if params["include"] == "owner_uuid"
343         owners = klass_object_list[:items].map {|i| i[:owner_uuid]}.to_set
344         [Group, User].each do |ownerklass|
345           ownerklass.readable_by(*@read_users).where(uuid: owners.to_a).each do |ow|
346             included_by_uuid[ow.uuid] = ow
347           end
348         end
349       end
350     end
351
352     if params["include"]
353       @extra_included = included_by_uuid.values
354     end
355
356     if set_count_none
357       params['count'] = 'none'
358     end
359
360     @objects = all_objects
361     @limit = limit_all
362     @offset = offset_all
363   end
364
365   def exclude_home objectlist, klass
366     # select records that are readable by current user AND
367     #   the owner_uuid is a user (but not the current user) OR
368     #   the owner_uuid is not readable by the current user
369     #   the owner_uuid is a group but group_class is not a project
370
371     read_parent_check = if current_user.is_admin
372                           ""
373                         else
374                           "NOT EXISTS(SELECT 1 FROM #{PERMISSION_VIEW} WHERE "+
375                             "user_uuid=(:user_uuid) AND target_uuid=#{klass.table_name}.owner_uuid AND perm_level >= 1) OR "
376                         end
377
378     objectlist.where("#{klass.table_name}.owner_uuid IN (SELECT users.uuid FROM users WHERE users.uuid != (:user_uuid)) OR "+
379                      read_parent_check+
380                      "EXISTS(SELECT 1 FROM groups as gp where gp.uuid=#{klass.table_name}.owner_uuid and gp.group_class != 'project')",
381                      user_uuid: current_user.uuid)
382   end
383
384 end