16306: Merge branch 'master'
[arvados.git] / services / api / app / controllers / arvados / v1 / api_client_authorizations_controller.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'safe_json'
6
7 class Arvados::V1::ApiClientAuthorizationsController < ApplicationController
8   accept_attribute_as_json :scopes, Array
9   before_action :current_api_client_is_trusted, :except => [:current]
10   before_action :admin_required, :only => :create_system_auth
11   skip_before_action :render_404_if_no_object, :only => [:create_system_auth, :current]
12   skip_before_action :find_object_by_uuid, :only => [:create_system_auth, :current]
13
14   def self._create_system_auth_requires_parameters
15     {
16       api_client_id: {type: 'integer', required: false},
17       scopes: {type: 'array', required: false}
18     }
19   end
20   def create_system_auth
21     @object = ApiClientAuthorization.
22       new(user_id: system_user.id,
23           api_client_id: params[:api_client_id] || current_api_client.andand.id,
24           created_by_ip_address: remote_ip,
25           scopes: SafeJSON.load(params[:scopes] || '["all"]'))
26     @object.save!
27     show
28   end
29
30   def create
31     # Note: the user could specify a owner_uuid for a different user, which on
32     # the surface appears to be a security hole.  However, the record will be
33     # rejected before being saved to the database by the ApiClientAuthorization
34     # model which enforces that user_id == current user or the user is an
35     # admin.
36
37     if resource_attrs[:owner_uuid]
38       # The model has an owner_id attribute instead of owner_uuid, but
39       # we can't expect the client to know the local numeric ID. We
40       # translate UUID to numeric ID here.
41       resource_attrs[:user_id] =
42         User.where(uuid: resource_attrs.delete(:owner_uuid)).first.andand.id
43     elsif not resource_attrs[:user_id]
44       resource_attrs[:user_id] = current_user.id
45     end
46     resource_attrs[:api_client_id] = Thread.current[:api_client].id
47     super
48   end
49
50   def current
51     @object = Thread.current[:api_client_authorization]
52     show
53   end
54
55   protected
56
57   def default_orders
58     ["#{table_name}.created_at desc"]
59   end
60
61   def find_objects_for_index
62     # Here we are deliberately less helpful about searching for client
63     # authorizations.  We look up tokens belonging to the current user
64     # and filter by exact matches on uuid, api_token, and scopes.
65     wanted_scopes = []
66     if @filters
67       wanted_scopes.concat(@filters.map { |attr, operator, operand|
68         ((attr == 'scopes') and (operator == '=')) ? operand : nil
69       })
70       @filters.select! { |attr, operator, operand|
71         operator == '=' && (attr == 'uuid' || attr == 'api_token')
72       }
73     end
74     if @where
75       wanted_scopes << @where['scopes']
76       @where.select! { |attr, val|
77         # "where":{"uuid":"zzzzz-zzzzz-zzzzzzzzzzzzzzz"} is OK but
78         # "where":{"api_client_id":1} is not supported
79         # "where":{"uuid":["contains","-"]} is not supported
80         # "where":{"uuid":["uuid1","uuid2","uuid3"]} is not supported
81         val.is_a?(String) && (attr == 'uuid' || attr == 'api_token')
82       }
83     end
84     if current_api_client_authorization.andand.api_token != Rails.configuration.SystemRootToken
85       @objects = model_class.where('user_id=?', current_user.id)
86     end
87     if wanted_scopes.compact.any?
88       # We can't filter on scopes effectively using AR/postgres.
89       # Instead we get the entire result set, do our own filtering on
90       # scopes to get a list of UUIDs, then start a new query
91       # (restricted to the selected UUIDs) so super can apply the
92       # offset/limit/order params in the usual way.
93       @request_limit = @limit
94       @request_offset = @offset
95       @limit = @objects.count
96       @offset = 0
97       super
98       wanted_scopes.compact.each do |scope_list|
99         if @objects.respond_to?(:where) && scope_list.length < 2
100           @objects = @objects.
101                      where('scopes in (?)',
102                            [scope_list.to_yaml, SafeJSON.dump(scope_list)])
103         else
104           if @objects.respond_to?(:where)
105             # Eliminate rows with scopes=['all'] before doing the
106             # expensive filter. They are typically the majority of
107             # rows, and they obviously won't match given
108             # scope_list.length>=2, so loading them all into
109             # ActiveRecord objects is a huge waste of time.
110             @objects = @objects.
111                        where('scopes not in (?)',
112                              [['all'].to_yaml, SafeJSON.dump(['all'])])
113           end
114           sorted_scopes = scope_list.sort
115           @objects = @objects.select { |auth| auth.scopes.sort == sorted_scopes }
116         end
117       end
118       @limit = @request_limit
119       @offset = @request_offset
120       @objects = model_class.where('uuid in (?)', @objects.collect(&:uuid))
121     end
122     super
123   end
124
125   def find_object_by_uuid
126     uuid_param = params[:uuid] || params[:id]
127     if (uuid_param != current_api_client_authorization.andand.uuid &&
128         !Thread.current[:api_client].andand.is_trusted)
129       return forbidden
130     end
131     @limit = 1
132     @offset = 0
133     @orders = []
134     @where = {}
135     @filters = [['uuid', '=', uuid_param]]
136     find_objects_for_index
137     @object = @objects.first
138   end
139
140   def current_api_client_is_trusted
141     if Thread.current[:api_client].andand.is_trusted
142       return true
143     end
144     # A non-trusted client can do a search for its own token if it
145     # explicitly restricts the search to its own UUID or api_token.
146     # Any other kind of query must return 403, even if it matches only
147     # the current token, because that's currently how Workbench knows
148     # (after searching on scopes) the difference between "the token
149     # I'm using now *is* the only sharing token for this collection"
150     # (403) and "my token is trusted, and there is one sharing token
151     # for this collection" (200).
152     #
153     # The @filters test here also prevents a non-trusted token from
154     # filtering on its own scopes, and discovering whether any _other_
155     # equally scoped tokens exist (403=yes, 200=no).
156     return forbidden if !@objects
157     full_set = @objects.except(:limit).except(:offset) if @objects
158     if (full_set.count == 1 and
159         full_set.first.uuid == current_api_client_authorization.andand.uuid and
160         (@filters.map(&:first) & %w(uuid api_token)).any?)
161       return true
162     end
163     forbidden
164   end
165
166   def forbidden
167     send_error('Forbidden: this API client cannot manipulate other clients\' access tokens.',
168                status: 403)
169   end
170 end