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