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