8784: Fix test for latest firefox.
[arvados.git] / services / api / test / integration / cross_origin_test.rb
1 require 'test_helper'
2
3 class CrossOriginTest < ActionDispatch::IntegrationTest
4   def options *args
5     # Rails doesn't support OPTIONS the same way as GET, POST, etc.
6     reset! unless integration_session
7     integration_session.__send__(:process, :options, *args).tap do
8       copy_session_variables!
9     end
10   end
11
12   %w(/login /logout /auth/example/callback /auth/joshid).each do |path|
13     test "OPTIONS requests are refused at #{path}" do
14       options path, {}, {}
15       assert_no_cors_headers
16     end
17
18     test "CORS headers do not exist at GET #{path}" do
19       get path, {}, {}
20       assert_no_cors_headers
21     end
22   end
23
24   %w(/discovery/v1/apis/arvados/v1/rest).each do |path|
25     test "CORS headers are set at GET #{path}" do
26       get path, {}, {}
27       assert_response :success
28       assert_cors_headers
29     end
30   end
31
32   ['/arvados/v1/collections',
33    '/arvados/v1/users',
34    '/arvados/v1/api_client_authorizations'].each do |path|
35     test "CORS headers are set and body is stub at OPTIONS #{path}" do
36       options path, {}, {}
37       assert_response :success
38       assert_cors_headers
39       assert_equal '-', response.body
40     end
41
42     test "CORS headers are set at authenticated GET #{path}" do
43       get path, {}, auth(:active_trustedclient)
44       assert_response :success
45       assert_cors_headers
46     end
47
48     # CORS headers are OK only if cookies are *not* used to determine
49     # whether a transaction is allowed. The following is a (far from
50     # perfect) test that the usual Rails cookie->session mechanism
51     # does not grant access to any resources.
52     ['GET', 'POST'].each do |method|
53       test "Session does not work at #{method} #{path}" do
54         send method.downcase, path, {format: 'json'}, {user_id: 1}
55         assert_response 401
56         assert_cors_headers
57       end
58     end
59   end
60
61   protected
62   def assert_cors_headers
63     assert_equal '*', response.headers['Access-Control-Allow-Origin']
64     allowed = response.headers['Access-Control-Allow-Methods'].split(', ')
65     %w(GET HEAD POST PUT DELETE).each do |m|
66       assert_includes allowed, m, "A-C-A-Methods should include #{m}"
67     end
68     assert_equal 'Authorization', response.headers['Access-Control-Allow-Headers']
69   end
70
71   def assert_no_cors_headers
72     response.headers.keys.each do |h|
73       assert_no_match(/^Access-Control-/i, h)
74     end
75   end
76 end