11453: Check HTTP method of token validation request.
[arvados.git] / services / api / app / middlewares / arvados_api_token.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 # Perform api_token checking very early in the request process.  We want to do
6 # this in the Rack stack instead of in ApplicationController because
7 # websockets needs access to authentication but doesn't use any of the rails
8 # active dispatch infrastructure.
9 class ArvadosApiToken
10
11   # Create a new ArvadosApiToken handler
12   # +app+  The next layer of the Rack stack.
13   def initialize(app = nil, options = nil)
14     @app = app.respond_to?(:call) ? app : nil
15   end
16
17   def call env
18     request = Rack::Request.new(env)
19     params = request.params
20     remote_ip = env["action_dispatch.remote_ip"]
21
22     Thread.current[:request_starttime] = Time.now
23     Thread.current[:supplied_token] =
24       params["api_token"] ||
25       params["oauth_token"] ||
26       env["HTTP_AUTHORIZATION"].andand.
27         match(/(OAuth2|Bearer) ([-\/a-zA-Z0-9]+)/).andand[2]
28
29     if params[:remote] && request.get? && (
30          request.path.start_with?('/arvados/v1/groups') ||
31          request.path.start_with?('/arvados/v1/users/current'))
32       # Request from a remote API server, asking to validate a salted
33       # token.
34       remote = params[:remote]
35     else
36       # Normal request.
37       remote = false
38     end
39     auth = ApiClientAuthorization.
40            validate(token: Thread.current[:supplied_token],
41                     remote: remote)
42
43     Thread.current[:api_client_ip_address] = remote_ip
44     Thread.current[:api_client_authorization] = auth
45     Thread.current[:api_client_uuid] = auth.andand.api_client.andand.uuid
46     Thread.current[:api_client] = auth.andand.api_client
47     Thread.current[:user] = auth.andand.user
48
49     @app.call env if @app
50   end
51 end