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