Merge branch 'main' from workbench2.git
[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/api_client_authorizations/current') ||
29          request.path.start_with?('/arvados/v1/users/current'))
30       # Request from a remote API server, asking to validate a salted
31       # token.
32       remote = params["remote"]
33     elsif request.get? || params["_method"] == 'GET'
34       reader_tokens = params["reader_tokens"]
35       if reader_tokens.is_a? String
36         reader_tokens = SafeJSON.load(reader_tokens)
37       end
38     end
39
40     # Set current_user etc. based on the primary session token if a
41     # valid one is present. Otherwise, use the first valid token in
42     # reader_tokens.
43     accepted = false
44     auth = nil
45     remote_errcodes = []
46     remote_errmsgs = []
47     [params["api_token"],
48      params["oauth_token"],
49      env["HTTP_AUTHORIZATION"].andand.match(/(OAuth2|Bearer) ([!-~]+)/).andand[2],
50      *reader_tokens,
51     ].each do |supplied|
52       next if !supplied
53       begin
54         try_auth = ApiClientAuthorization.validate(token: supplied, remote: remote)
55       rescue => e
56         begin
57           remote_errcodes.append(e.http_status)
58         rescue NoMethodError
59           # The exception is an internal validation problem, not a remote error.
60           next
61         end
62         begin
63           errors = SafeJSON.load(e.res.content)["errors"]
64         rescue
65           errors = nil
66         end
67         remote_errmsgs += errors if errors.is_a?(Array)
68       else
69         if try_auth.andand.user
70           auth = try_auth
71           accepted = supplied
72           break
73         end
74       end
75     end
76
77     Thread.current[:api_client_ip_address] = remote_ip
78     Thread.current[:api_client_authorization] = auth
79     Thread.current[:api_client_uuid] = auth.andand.api_client.andand.uuid
80     Thread.current[:api_client] = auth.andand.api_client
81     Thread.current[:token] = accepted
82     Thread.current[:user] = auth.andand.user
83
84     if auth.nil? and not remote_errcodes.empty?
85       # If we failed to validate any tokens because of remote validation
86       # errors, pass those on to the client. This code is functionally very
87       # similar to ApplicationController#render_error, but the implementation
88       # is very different because we're a Rack middleware, not in
89       # ActionDispatch land yet.
90       remote_errmsgs.prepend("failed to validate remote token")
91       error_content = {
92         error_token: "%d+%08x" % [Time.now.utc.to_i, rand(16 ** 8)],
93         errors: remote_errmsgs,
94       }
95       [
96         remote_errcodes.max,
97         {"Content-Type": "application/json"},
98         SafeJSON.dump(error_content).html_safe,
99       ]
100     else
101       @app.call env if @app
102     end
103   end
104 end