15003: Merge branch 'master' into 15003-preprocess-config
[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
24     remote = false
25     reader_tokens = nil
26     if params["remote"] && request.get? && (
27          request.path.start_with?('/arvados/v1/groups') ||
28          request.path.start_with?('/arvados/v1/users/current'))
29       # Request from a remote API server, asking to validate a salted
30       # token.
31       remote = params["remote"]
32     elsif request.get? || params["_method"] == 'GET'
33       reader_tokens = params["reader_tokens"]
34       if reader_tokens.is_a? String
35         reader_tokens = SafeJSON.load(reader_tokens)
36       end
37     end
38
39     # Set current_user etc. based on the primary session token if a
40     # valid one is present. Otherwise, use the first valid token in
41     # reader_tokens.
42     accepted = false
43     auth = nil
44     [params["api_token"],
45      params["oauth_token"],
46      env["HTTP_AUTHORIZATION"].andand.match(/(OAuth2|Bearer) ([-\/a-zA-Z0-9]+)/).andand[2],
47      *reader_tokens,
48     ].each do |supplied|
49       next if !supplied
50       try_auth = ApiClientAuthorization.
51                  validate(token: supplied, remote: remote)
52       if try_auth.andand.user
53         auth = try_auth
54         accepted = supplied
55         break
56       end
57     end
58
59     Thread.current[:api_client_ip_address] = remote_ip
60     Thread.current[:api_client_authorization] = auth
61     Thread.current[:api_client_uuid] = auth.andand.api_client.andand.uuid
62     Thread.current[:api_client] = auth.andand.api_client
63     Thread.current[:token] = accepted
64     Thread.current[:user] = auth.andand.user
65
66     @app.call env if @app
67   end
68 end