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