13146: Don't return "included" field unless non-nil
[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     send_json({
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   end
68
69   def shared
70     # The purpose of this endpoint is to return the toplevel set of
71     # groups which are *not* reachable through a direct ownership
72     # chain of projects starting from the current user account.  In
73     # other words, groups which to which access was granted via a
74     # permission link or chain of links.
75     #
76     # This also returns (in the "included" field) the objects that own
77     # those projects (users or non-project groups).
78     #
79     # select groups that are readable by current user AND
80     #   the owner_uuid is a user (but not the current user) OR
81     #   the owner_uuid is not readable by the current user
82     #   the owner_uuid is a group but group_class is not a project
83     #
84     # The intended use of this endpoint is to support clients which
85     # wish to browse those projects which are visible to the user but
86     # are not part of the "home" project.
87
88     load_limit_offset_order_params
89     load_filters_param
90
91     read_parent_check = if current_user.is_admin
92                           ""
93                         else
94                           "NOT EXISTS(SELECT 1 FROM #{PERMISSION_VIEW} WHERE "+
95                             "user_uuid=(:user_uuid) AND target_uuid=groups.owner_uuid AND perm_level >= 1) OR "
96                         end
97
98     @objects = Group.readable_by(*@read_users).where("groups.owner_uuid IN (SELECT users.uuid FROM users WHERE users.uuid != (:user_uuid)) OR "+
99                                                      read_parent_check+
100                                                      "EXISTS(SELECT 1 FROM groups as gp where gp.uuid=groups.owner_uuid and gp.group_class != 'project')",
101                                             user_uuid: current_user.uuid)
102     apply_where_limit_order_params
103
104     owners = @objects.map(&:owner_uuid).to_a
105
106     if params["include"] == "owner_uuid"
107       @extra_included = []
108       [Group, User].each do |klass|
109         @extra_included += klass.readable_by(*@read_users).where(uuid: owners).to_a
110       end
111     end
112
113     index
114   end
115
116   def self._shared_requires_parameters
117     rp = self._index_requires_parameters
118     rp[:include] = { type: 'string', required: false }
119     rp
120   end
121
122   protected
123
124   def load_searchable_objects
125     all_objects = []
126     @items_available = 0
127
128     # Trick apply_where_limit_order_params into applying suitable
129     # per-table values. *_all are the real ones we'll apply to the
130     # aggregate set.
131     limit_all = @limit
132     offset_all = @offset
133     # save the orders from the current request as determined by load_param,
134     # but otherwise discard them because we're going to be getting objects
135     # from many models
136     request_orders = @orders.clone
137     @orders = []
138
139     request_filters = @filters
140
141     klasses = [Group,
142      Job, PipelineInstance, PipelineTemplate, ContainerRequest, Workflow,
143      Collection,
144      Human, Specimen, Trait]
145
146     table_names = Hash[klasses.collect { |k| [k, k.table_name] }]
147
148     disabled_methods = Rails.configuration.disable_api_methods
149     avail_klasses = table_names.select{|k, t| !disabled_methods.include?(t+'.index')}
150     klasses = avail_klasses.keys
151
152     request_filters.each do |col, op, val|
153       if col.index('.') && !table_names.values.include?(col.split('.', 2)[0])
154         raise ArgumentError.new("Invalid attribute '#{col}' in filter")
155       end
156     end
157
158     wanted_klasses = []
159     request_filters.each do |col,op,val|
160       if op == 'is_a'
161         (val.is_a?(Array) ? val : [val]).each do |type|
162           type = type.split('#')[-1]
163           type[0] = type[0].capitalize
164           wanted_klasses << type
165         end
166       end
167     end
168
169     filter_by_owner = {}
170     if @object
171       if params['recursive']
172         filter_by_owner[:owner_uuid] = [@object.uuid] + @object.descendant_project_uuids
173       else
174         filter_by_owner[:owner_uuid] = @object.uuid
175       end
176     end
177
178     seen_last_class = false
179     klasses.each do |klass|
180       @offset = 0 if seen_last_class  # reset offset for the new next type being processed
181
182       # if current klass is same as params['last_object_class'], mark that fact
183       seen_last_class = true if((params['count'].andand.==('none')) and
184                                 (params['last_object_class'].nil? or
185                                  params['last_object_class'].empty? or
186                                  params['last_object_class'] == klass.to_s))
187
188       # if klasses are specified, skip all other klass types
189       next if wanted_klasses.any? and !wanted_klasses.include?(klass.to_s)
190
191       # don't reprocess klass types that were already seen
192       next if params['count'] == 'none' and !seen_last_class
193
194       # don't process rest of object types if we already have needed number of objects
195       break if params['count'] == 'none' and all_objects.size >= limit_all
196
197       # If the currently requested orders specifically match the
198       # table_name for the current klass, apply that order.
199       # Otherwise, order by recency.
200       request_order =
201         request_orders.andand.find { |r| r =~ /^#{klass.table_name}\./i } ||
202         klass.default_orders.join(", ")
203
204       @select = nil
205       where_conds = filter_by_owner
206       if klass == Collection
207         @select = klass.selectable_attributes - ["manifest_text"]
208       elsif klass == Group
209         where_conds = where_conds.merge(group_class: "project")
210       end
211
212       @filters = request_filters.map do |col, op, val|
213         if !col.index('.')
214           [col, op, val]
215         elsif (col = col.split('.', 2))[0] == klass.table_name
216           [col[1], op, val]
217         else
218           nil
219         end
220       end.compact
221
222       @objects = klass.readable_by(*@read_users, {:include_trash => params[:include_trash]}).
223                  order(request_order).where(where_conds)
224
225       klass_limit = limit_all - all_objects.count
226       @limit = klass_limit
227       apply_where_limit_order_params klass
228       klass_object_list = object_list(model_class: klass)
229       klass_items_available = klass_object_list[:items_available] || 0
230       @items_available += klass_items_available
231       @offset = [@offset - klass_items_available, 0].max
232       all_objects += klass_object_list[:items]
233
234       if klass_object_list[:limit] < klass_limit
235         # object_list() had to reduce @limit to comply with
236         # max_index_database_read. From now on, we'll do all queries
237         # with limit=0 and just accumulate items_available.
238         limit_all = all_objects.count
239       end
240     end
241
242     @objects = all_objects
243     @limit = limit_all
244     @offset = offset_all
245   end
246
247 end