oauth2 1.4.1 → 1.4.9

Sign up to get free protection for your applications and to get access to all the features.
Files changed (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -10
  3. data/CODE_OF_CONDUCT.md +105 -46
  4. data/LICENSE +1 -1
  5. data/README.md +290 -98
  6. data/lib/oauth2/access_token.rb +15 -5
  7. data/lib/oauth2/authenticator.rb +13 -1
  8. data/lib/oauth2/client.rb +133 -51
  9. data/lib/oauth2/error.rb +3 -1
  10. data/lib/oauth2/mac_token.rb +18 -10
  11. data/lib/oauth2/response.rb +7 -3
  12. data/lib/oauth2/strategy/assertion.rb +6 -4
  13. data/lib/oauth2/strategy/auth_code.rb +3 -1
  14. data/lib/oauth2/strategy/base.rb +2 -0
  15. data/lib/oauth2/strategy/client_credentials.rb +3 -1
  16. data/lib/oauth2/strategy/implicit.rb +3 -1
  17. data/lib/oauth2/strategy/password.rb +5 -3
  18. data/lib/oauth2/version.rb +14 -8
  19. data/lib/oauth2.rb +2 -0
  20. data/spec/fixtures/README.md +11 -0
  21. data/spec/fixtures/RS256/jwtRS256.key +51 -0
  22. data/spec/fixtures/RS256/jwtRS256.key.pub +14 -0
  23. data/spec/helper.rb +33 -0
  24. data/spec/oauth2/access_token_spec.rb +218 -0
  25. data/spec/oauth2/authenticator_spec.rb +86 -0
  26. data/spec/oauth2/client_spec.rb +556 -0
  27. data/spec/oauth2/mac_token_spec.rb +122 -0
  28. data/spec/oauth2/response_spec.rb +96 -0
  29. data/spec/oauth2/strategy/assertion_spec.rb +113 -0
  30. data/spec/oauth2/strategy/auth_code_spec.rb +108 -0
  31. data/spec/oauth2/strategy/base_spec.rb +7 -0
  32. data/spec/oauth2/strategy/client_credentials_spec.rb +71 -0
  33. data/spec/oauth2/strategy/implicit_spec.rb +28 -0
  34. data/spec/oauth2/strategy/password_spec.rb +58 -0
  35. data/spec/oauth2/version_spec.rb +23 -0
  36. metadata +86 -77
  37. data/.document +0 -5
  38. data/.gitignore +0 -12
  39. data/.jrubyrc +0 -1
  40. data/.rspec +0 -2
  41. data/.rubocop.yml +0 -80
  42. data/.rubocop_rspec.yml +0 -26
  43. data/.rubocop_todo.yml +0 -15
  44. data/.travis.yml +0 -49
  45. data/CONTRIBUTING.md +0 -18
  46. data/Gemfile +0 -41
  47. data/Rakefile +0 -45
  48. data/gemfiles/jruby_1.7.gemfile +0 -11
  49. data/gemfiles/jruby_1.7.gemfile.lock +0 -81
  50. data/gemfiles/jruby_9.0.gemfile +0 -13
  51. data/gemfiles/jruby_9.1.gemfile +0 -17
  52. data/gemfiles/jruby_9.1.gemfile.lock +0 -112
  53. data/gemfiles/jruby_9.2.gemfile +0 -17
  54. data/gemfiles/jruby_9.2.gemfile.lock +0 -112
  55. data/gemfiles/jruby_head.gemfile +0 -17
  56. data/gemfiles/ruby_1.9.gemfile +0 -16
  57. data/gemfiles/ruby_1.9.gemfile.lock +0 -85
  58. data/gemfiles/ruby_2.0.gemfile +0 -17
  59. data/gemfiles/ruby_2.0.gemfile.lock +0 -90
  60. data/gemfiles/ruby_2.1.gemfile +0 -19
  61. data/gemfiles/ruby_2.1.gemfile.lock +0 -109
  62. data/gemfiles/ruby_2.2.gemfile +0 -17
  63. data/gemfiles/ruby_2.2.gemfile.lock +0 -108
  64. data/gemfiles/ruby_2.3.gemfile +0 -17
  65. data/gemfiles/ruby_2.3.gemfile.lock +0 -108
  66. data/gemfiles/ruby_2.4.gemfile +0 -17
  67. data/gemfiles/ruby_2.4.gemfile.lock +0 -108
  68. data/gemfiles/ruby_2.5.gemfile +0 -17
  69. data/gemfiles/ruby_2.5.gemfile.lock +0 -108
  70. data/gemfiles/ruby_head.gemfile +0 -17
  71. data/gemfiles/ruby_head.gemfile.lock +0 -108
  72. data/oauth2.gemspec +0 -40
@@ -0,0 +1,556 @@
1
+ # coding: utf-8
2
+ # frozen_string_literal: true
3
+
4
+ require 'nkf'
5
+
6
+ describe OAuth2::Client do
7
+ subject do
8
+ described_class.new('abc', 'def', {:site => 'https://api.example.com'}.merge(options)) do |builder|
9
+ builder.adapter :test do |stub|
10
+ stub.get('/success') { |env| [200, {'Content-Type' => 'text/awesome'}, 'yay'] }
11
+ stub.get('/reflect') { |env| [200, {}, env[:body]] }
12
+ stub.post('/reflect') { |env| [200, {}, env[:body]] }
13
+ stub.get('/unauthorized') { |env| [401, {'Content-Type' => 'application/json'}, MultiJson.encode(:error => error_value, :error_description => error_description_value)] }
14
+ stub.get('/conflict') { |env| [409, {'Content-Type' => 'text/plain'}, 'not authorized'] }
15
+ stub.get('/redirect') { |env| [302, {'Content-Type' => 'text/plain', 'location' => '/success'}, ''] }
16
+ stub.get('/redirect_no_loc') { |_env| [302, {'Content-Type' => 'text/plain'}, ''] }
17
+ stub.post('/redirect') { |env| [303, {'Content-Type' => 'text/plain', 'location' => '/reflect'}, ''] }
18
+ stub.get('/error') { |env| [500, {'Content-Type' => 'text/plain'}, 'unknown error'] }
19
+ stub.get('/empty_get') { |env| [204, {}, nil] }
20
+ stub.get('/different_encoding') { |env| [500, {'Content-Type' => 'application/json'}, NKF.nkf('-We', MultiJson.encode(:error => error_value, :error_description => '∞'))] }
21
+ stub.get('/ascii_8bit_encoding') { |env| [500, {'Content-Type' => 'application/json'}, MultiJson.encode(:error => 'invalid_request', :error_description => 'é').force_encoding('ASCII-8BIT')] }
22
+ end
23
+ end
24
+ end
25
+
26
+ let!(:error_value) { 'invalid_token' }
27
+ let!(:error_description_value) { 'bad bad token' }
28
+ let(:options) { {} }
29
+
30
+ describe '#initialize' do
31
+ it 'assigns id and secret' do
32
+ expect(subject.id).to eq('abc')
33
+ expect(subject.secret).to eq('def')
34
+ end
35
+
36
+ it 'assigns site from the options hash' do
37
+ expect(subject.site).to eq('https://api.example.com')
38
+ end
39
+
40
+ it 'assigns Faraday::Connection#host' do
41
+ expect(subject.connection.host).to eq('api.example.com')
42
+ end
43
+
44
+ it 'leaves Faraday::Connection#ssl unset' do
45
+ expect(subject.connection.ssl).to be_empty
46
+ end
47
+
48
+ it 'is able to pass a block to configure the connection' do
49
+ builder = double('builder')
50
+
51
+ allow(Faraday).to receive(:new).and_yield(builder)
52
+ allow(builder).to receive(:response)
53
+
54
+ expect(builder).to receive(:adapter).with(:test)
55
+
56
+ described_class.new('abc', 'def') do |client|
57
+ client.adapter :test
58
+ end.connection
59
+ end
60
+
61
+ it 'defaults raise_errors to true' do
62
+ expect(subject.options[:raise_errors]).to be true
63
+ end
64
+
65
+ it 'allows true/false for raise_errors option' do
66
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com', :raise_errors => false)
67
+ expect(client.options[:raise_errors]).to be false
68
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com', :raise_errors => true)
69
+ expect(client.options[:raise_errors]).to be true
70
+ end
71
+
72
+ it 'allows override of raise_errors option' do
73
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com', :raise_errors => true) do |builder|
74
+ builder.adapter :test do |stub|
75
+ stub.get('/notfound') { |_env| [404, {}, nil] }
76
+ end
77
+ end
78
+ expect(client.options[:raise_errors]).to be true
79
+ expect { client.request(:get, '/notfound') }.to raise_error(OAuth2::Error)
80
+ response = client.request(:get, '/notfound', :raise_errors => false)
81
+ expect(response.status).to eq(404)
82
+ end
83
+
84
+ it 'allows get/post for access_token_method option' do
85
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com', :access_token_method => :get)
86
+ expect(client.options[:access_token_method]).to eq(:get)
87
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com', :access_token_method => :post)
88
+ expect(client.options[:access_token_method]).to eq(:post)
89
+ end
90
+
91
+ it 'does not mutate the opts hash argument' do
92
+ opts = {:site => 'http://example.com/'}
93
+ opts2 = opts.dup
94
+ described_class.new 'abc', 'def', opts
95
+ expect(opts).to eq(opts2)
96
+ end
97
+ end
98
+
99
+ %w[authorize token].each do |url_type|
100
+ describe ":#{url_type}_url option" do
101
+ it "defaults to a path of /oauth/#{url_type}" do
102
+ expect(subject.send("#{url_type}_url")).to eq("https://api.example.com/oauth/#{url_type}")
103
+ end
104
+
105
+ it "is settable via the :#{url_type}_url option" do
106
+ subject.options[:"#{url_type}_url"] = '/oauth/custom'
107
+ expect(subject.send("#{url_type}_url")).to eq('https://api.example.com/oauth/custom')
108
+ end
109
+
110
+ it 'allows a different host than the site' do
111
+ subject.options[:"#{url_type}_url"] = 'https://api.foo.com/oauth/custom'
112
+ expect(subject.send("#{url_type}_url")).to eq('https://api.foo.com/oauth/custom')
113
+ end
114
+
115
+ context 'when a URL with path is used in the site' do
116
+ let(:options) do
117
+ {:site => 'https://example.com/blog'}
118
+ end
119
+
120
+ it 'generates an authorization URL relative to the site' do
121
+ expect(subject.send("#{url_type}_url")).to eq("https://example.com/blog/oauth/#{url_type}")
122
+ end
123
+ end
124
+
125
+ context 'when a URL with path is used in the site and urls overridden' do
126
+ let(:options) do
127
+ {
128
+ :site => 'https://example.com/blog',
129
+ :authorize_url => "oauth/#{url_type}/lampoon",
130
+ :token_url => "oauth/#{url_type}/lampoon",
131
+ }
132
+ end
133
+
134
+ it 'generates an authorization URL relative to the site' do
135
+ expect(subject.send("#{url_type}_url")).to eq("https://example.com/blog/oauth/#{url_type}/lampoon")
136
+ end
137
+ end
138
+ end
139
+ end
140
+
141
+ describe ':redirect_uri option' do
142
+ let(:auth_code_params) do
143
+ {
144
+ 'client_id' => 'abc',
145
+ 'client_secret' => 'def',
146
+ 'code' => 'code',
147
+ 'grant_type' => 'authorization_code',
148
+ }
149
+ end
150
+
151
+ context 'when blank' do
152
+ it 'there is no redirect_uri param added to authorization URL' do
153
+ expect(subject.authorize_url('a' => 'b')).to eq('https://api.example.com/oauth/authorize?a=b')
154
+ end
155
+
156
+ it 'does not add the redirect_uri param to the auth_code token exchange request' do
157
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com') do |builder|
158
+ builder.adapter :test do |stub|
159
+ stub.post('/oauth/token', auth_code_params) do
160
+ [200, {'Content-Type' => 'application/json'}, '{"access_token":"token"}']
161
+ end
162
+ end
163
+ end
164
+ client.auth_code.get_token('code')
165
+ end
166
+ end
167
+
168
+ context 'when set' do
169
+ before { subject.options[:redirect_uri] = 'https://site.com/oauth/callback' }
170
+
171
+ it 'adds the redirect_uri param to authorization URL' do
172
+ expect(subject.authorize_url('a' => 'b')).to eq('https://api.example.com/oauth/authorize?a=b&redirect_uri=https%3A%2F%2Fsite.com%2Foauth%2Fcallback')
173
+ end
174
+
175
+ it 'adds the redirect_uri param to the auth_code token exchange request' do
176
+ client = described_class.new('abc', 'def', :redirect_uri => 'https://site.com/oauth/callback', :site => 'https://api.example.com') do |builder|
177
+ builder.adapter :test do |stub|
178
+ stub.post('/oauth/token', auth_code_params.merge('redirect_uri' => 'https://site.com/oauth/callback')) do
179
+ [200, {'Content-Type' => 'application/json'}, '{"access_token":"token"}']
180
+ end
181
+ end
182
+ end
183
+ client.auth_code.get_token('code')
184
+ end
185
+ end
186
+
187
+ describe 'custom headers' do
188
+ context 'string key headers' do
189
+ it 'adds the custom headers to request' do
190
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com', :auth_scheme => :request_body) do |builder|
191
+ builder.adapter :test do |stub|
192
+ stub.post('/oauth/token') do |env|
193
+ expect(env.request_headers).to include({'CustomHeader' => 'CustomHeader'})
194
+ [200, {'Content-Type' => 'application/json'}, '{"access_token":"token"}']
195
+ end
196
+ end
197
+ end
198
+ header_params = {'headers' => {'CustomHeader' => 'CustomHeader'}}
199
+ client.auth_code.get_token('code', header_params)
200
+ end
201
+ end
202
+
203
+ context 'symbol key headers' do
204
+ it 'adds the custom headers to request' do
205
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com', :auth_scheme => :request_body) do |builder|
206
+ builder.adapter :test do |stub|
207
+ stub.post('/oauth/token') do |env|
208
+ expect(env.request_headers).to include({'CustomHeader' => 'CustomHeader'})
209
+ [200, {'Content-Type' => 'application/json'}, '{"access_token":"token"}']
210
+ end
211
+ end
212
+ end
213
+ header_params = {:headers => {'CustomHeader' => 'CustomHeader'}}
214
+ client.auth_code.get_token('code', header_params)
215
+ end
216
+ end
217
+
218
+ context 'string key custom headers with basic auth' do
219
+ it 'adds the custom headers to request' do
220
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com') do |builder|
221
+ builder.adapter :test do |stub|
222
+ stub.post('/oauth/token') do |env|
223
+ expect(env.request_headers).to include({'CustomHeader' => 'CustomHeader'})
224
+ [200, {'Content-Type' => 'application/json'}, '{"access_token":"token"}']
225
+ end
226
+ end
227
+ end
228
+ header_params = {'headers' => {'CustomHeader' => 'CustomHeader'}}
229
+ client.auth_code.get_token('code', header_params)
230
+ end
231
+ end
232
+
233
+ context 'symbol key custom headers with basic auth' do
234
+ it 'adds the custom headers to request' do
235
+ client = described_class.new('abc', 'def', :site => 'https://api.example.com') do |builder|
236
+ builder.adapter :test do |stub|
237
+ stub.post('/oauth/token') do |env|
238
+ expect(env.request_headers).to include({'CustomHeader' => 'CustomHeader'})
239
+ [200, {'Content-Type' => 'application/json'}, '{"access_token":"token"}']
240
+ end
241
+ end
242
+ end
243
+ header_params = {:headers => {'CustomHeader' => 'CustomHeader'}}
244
+ client.auth_code.get_token('code', header_params)
245
+ end
246
+ end
247
+ end
248
+ end
249
+
250
+ describe '#request' do
251
+ it 'works with a null response body' do
252
+ expect(subject.request(:get, 'empty_get').body).to eq('')
253
+ end
254
+
255
+ it 'returns on a successful response' do
256
+ response = subject.request(:get, '/success')
257
+ expect(response.body).to eq('yay')
258
+ expect(response.status).to eq(200)
259
+ expect(response.headers).to eq('Content-Type' => 'text/awesome')
260
+ end
261
+
262
+ it 'posts a body' do
263
+ response = subject.request(:post, '/reflect', :body => 'foo=bar')
264
+ expect(response.body).to eq('foo=bar')
265
+ end
266
+
267
+ it 'follows redirects properly' do
268
+ response = subject.request(:get, '/redirect')
269
+ expect(response.body).to eq('yay')
270
+ expect(response.status).to eq(200)
271
+ expect(response.headers).to eq('Content-Type' => 'text/awesome')
272
+ end
273
+
274
+ it 'redirects using GET on a 303' do
275
+ response = subject.request(:post, '/redirect', :body => 'foo=bar')
276
+ expect(response.body).to be_empty
277
+ expect(response.status).to eq(200)
278
+ end
279
+
280
+ it 'obeys the :max_redirects option' do
281
+ max_redirects = subject.options[:max_redirects]
282
+ subject.options[:max_redirects] = 0
283
+ response = subject.request(:get, '/redirect')
284
+ expect(response.status).to eq(302)
285
+ subject.options[:max_redirects] = max_redirects
286
+ end
287
+
288
+ it 'returns if raise_errors is false' do
289
+ subject.options[:raise_errors] = false
290
+ response = subject.request(:get, '/unauthorized')
291
+
292
+ expect(response.status).to eq(401)
293
+ expect(response.headers).to eq('Content-Type' => 'application/json')
294
+ expect(response.error).not_to be_nil
295
+ end
296
+
297
+ %w[/unauthorized /conflict /error /different_encoding /ascii_8bit_encoding].each do |error_path|
298
+ it "raises OAuth2::Error on error response to path #{error_path}" do
299
+ expect { subject.request(:get, error_path) }.to raise_error(OAuth2::Error)
300
+ end
301
+ end
302
+
303
+ # rubocop:disable Style/RedundantBegin
304
+ it 're-encodes response body in the error message' do
305
+ begin
306
+ subject.request(:get, '/ascii_8bit_encoding')
307
+ rescue StandardError => e
308
+ expect(e.message.encoding.name).to eq('UTF-8')
309
+ expect(e.message).to eq("invalid_request: é\n{\"error\":\"invalid_request\",\"error_description\":\"��\"}")
310
+ end
311
+ end
312
+
313
+ it 'parses OAuth2 standard error response' do
314
+ begin
315
+ subject.request(:get, '/unauthorized')
316
+ rescue StandardError => e
317
+ expect(e.code).to eq(error_value)
318
+ expect(e.description).to eq(error_description_value)
319
+ expect(e.to_s).to match(/#{error_value}/)
320
+ expect(e.to_s).to match(/#{error_description_value}/)
321
+ end
322
+ end
323
+
324
+ it 'provides the response in the Exception' do
325
+ begin
326
+ subject.request(:get, '/error')
327
+ rescue StandardError => e
328
+ expect(e.response).not_to be_nil
329
+ expect(e.to_s).to match(/unknown error/)
330
+ end
331
+ end
332
+ # rubocop:enable Style/RedundantBegin
333
+
334
+ context 'with ENV' do
335
+ include_context 'with stubbed env'
336
+ before do
337
+ stub_env('OAUTH_DEBUG' => 'true')
338
+ end
339
+
340
+ it 'outputs to $stdout when OAUTH_DEBUG=true' do
341
+ output = capture(:stdout) do
342
+ subject.request(:get, '/success')
343
+ end
344
+ logs = [
345
+ '-- request: GET https://api.example.com/success',
346
+ '-- response: Status 200',
347
+ '-- response: Content-Type: "text/awesome"',
348
+ ]
349
+ expect(output).to include(*logs)
350
+ end
351
+ end
352
+ end
353
+
354
+ describe '#get_token' do
355
+ it 'returns a configured AccessToken' do
356
+ client = stubbed_client do |stub|
357
+ stub.post('/oauth/token') do
358
+ [200, {'Content-Type' => 'application/json'}, MultiJson.encode('access_token' => 'the-token')]
359
+ end
360
+ end
361
+
362
+ token = client.get_token({})
363
+ expect(token).to be_a OAuth2::AccessToken
364
+ expect(token.token).to eq('the-token')
365
+ end
366
+
367
+ it 'authenticates with request parameters' do
368
+ client = stubbed_client(:auth_scheme => :request_body) do |stub|
369
+ stub.post('/oauth/token', 'client_id' => 'abc', 'client_secret' => 'def') do |env|
370
+ [200, {'Content-Type' => 'application/json'}, MultiJson.encode('access_token' => 'the-token')]
371
+ end
372
+ end
373
+ client.get_token({})
374
+ end
375
+
376
+ it 'authenticates with Basic auth' do
377
+ client = stubbed_client(:auth_scheme => :basic_auth) do |stub|
378
+ stub.post('/oauth/token') do |env|
379
+ raise Faraday::Adapter::Test::Stubs::NotFound unless env[:request_headers]['Authorization'] == OAuth2::Authenticator.encode_basic_auth('abc', 'def')
380
+
381
+ [200, {'Content-Type' => 'application/json'}, MultiJson.encode('access_token' => 'the-token')]
382
+ end
383
+ end
384
+ client.get_token({})
385
+ end
386
+
387
+ describe 'extract_access_token option' do
388
+ let(:client) do
389
+ client = stubbed_client(:extract_access_token => extract_access_token) do |stub|
390
+ stub.post('/oauth/token') do
391
+ [200, {'Content-Type' => 'application/json'}, MultiJson.encode('data' => {'access_token' => 'the-token'})]
392
+ end
393
+ end
394
+ end
395
+
396
+ context 'with proc extract_access_token' do
397
+ let(:extract_access_token) do
398
+ proc do |client, hash|
399
+ token = hash['data']['access_token']
400
+ OAuth2::AccessToken.new(client, token, hash)
401
+ end
402
+ end
403
+
404
+ it 'returns a configured AccessToken' do
405
+ token = client.get_token({})
406
+ expect(token).to be_a OAuth2::AccessToken
407
+ expect(token.token).to eq('the-token')
408
+ end
409
+ end
410
+
411
+ context 'with depracted Class.from_hash option' do
412
+ let(:extract_access_token) do
413
+ CustomAccessToken = Class.new(OAuth2::AccessToken)
414
+ CustomAccessToken.define_singleton_method(:from_hash) do |client, hash|
415
+ token = hash['data']['access_token']
416
+ OAuth2::AccessToken.new(client, token, hash)
417
+ end
418
+ CustomAccessToken
419
+ end
420
+
421
+ it 'returns a configured AccessToken' do
422
+ token = client.get_token({})
423
+ expect(token).to be_a OAuth2::AccessToken
424
+ expect(token.token).to eq('the-token')
425
+ end
426
+ end
427
+ end
428
+
429
+ describe ':raise_errors flag' do
430
+ let(:options) { {} }
431
+ let(:token_response) { nil }
432
+ let(:post_args) { [] }
433
+
434
+ let(:client) do
435
+ stubbed_client(options.merge(:raise_errors => raise_errors)) do |stub|
436
+ stub.post('/oauth/token', *post_args) do
437
+ # stub 200 response so that we're testing the get_token handling of :raise_errors flag not request
438
+ [200, {'Content-Type' => 'application/json'}, token_response]
439
+ end
440
+ end
441
+ end
442
+
443
+ context 'when set to false' do
444
+ let(:raise_errors) { false }
445
+
446
+ context 'when the request body is nil' do
447
+ it 'returns a nil :access_token' do
448
+ expect(client.get_token({})).to eq(nil)
449
+ end
450
+ end
451
+
452
+ context 'when the request body is missing the access_token' do
453
+ let(:token_response) { MultiJson.encode('unexpected_access_token' => 'the-token') }
454
+
455
+ it 'returns a nil :access_token' do
456
+ expect(client.get_token({})).to eq(nil)
457
+ end
458
+ end
459
+
460
+ context 'when the request body has an access token' do
461
+ let(:token_response) { MultiJson.encode('access_token' => 'the-token') }
462
+
463
+ it 'returns the parsed :access_token from body' do
464
+ token = client.get_token({})
465
+ expect(token).to be_a OAuth2::AccessToken
466
+ expect(token.token).to eq('the-token')
467
+ end
468
+
469
+ context 'when :auth_scheme => :request_body' do
470
+ context 'when arbitrary params are present' do
471
+ let(:post_args) { ['arbitrary' => 'parameter', 'client_id' => 'abc', 'client_secret' => 'def'] }
472
+ let(:options) { {:auth_scheme => :request_body} }
473
+
474
+ it 'does not affect access token' do
475
+ token = client.get_token(*post_args)
476
+ expect(token).to be_a OAuth2::AccessToken
477
+ expect(token.token).to eq('the-token')
478
+ end
479
+ end
480
+ end
481
+ end
482
+
483
+ context 'when extract_access_token raises an exception' do
484
+ let(:options) do
485
+ {
486
+ :extract_access_token => proc { |client, hash| raise ArgumentError },
487
+ }
488
+ end
489
+
490
+ it 'returns a nil :access_token' do
491
+ expect(client.get_token({})).to eq(nil)
492
+ end
493
+ end
494
+ end
495
+
496
+ context 'when set to true' do
497
+ let(:raise_errors) { true }
498
+
499
+ context 'when the request body is nil' do
500
+ it 'raises an error' do
501
+ expect { client.get_token({}) }.to raise_error OAuth2::Error
502
+ end
503
+ end
504
+
505
+ context 'when the request body is missing the access_token' do
506
+ let(:token_response) { MultiJson.encode('unexpected_access_token' => 'the-token') }
507
+
508
+ it 'raises an error' do
509
+ expect { client.get_token({}) }.to raise_error OAuth2::Error
510
+ end
511
+ end
512
+
513
+ context 'when extract_access_token raises an exception' do
514
+ let(:options) do
515
+ {
516
+ :extract_access_token => proc { |client, hash| raise ArgumentError },
517
+ }
518
+ end
519
+
520
+ it 'raises an error' do
521
+ expect { client.get_token({}) }.to raise_error OAuth2::Error
522
+ end
523
+ end
524
+ end
525
+ end
526
+
527
+ def stubbed_client(params = {}, &stubs)
528
+ params = {:site => 'https://api.example.com'}.merge(params)
529
+ OAuth2::Client.new('abc', 'def', params) do |builder|
530
+ builder.adapter :test, &stubs
531
+ end
532
+ end
533
+ end
534
+
535
+ it 'instantiates an AuthCode strategy with this client' do
536
+ expect(subject.auth_code).to be_kind_of(OAuth2::Strategy::AuthCode)
537
+ end
538
+
539
+ it 'instantiates an Implicit strategy with this client' do
540
+ expect(subject.implicit).to be_kind_of(OAuth2::Strategy::Implicit)
541
+ end
542
+
543
+ context 'with SSL options' do
544
+ subject do
545
+ cli = described_class.new('abc', 'def', :site => 'https://api.example.com', :ssl => {:ca_file => 'foo.pem'})
546
+ cli.connection = Faraday.new(cli.site, cli.options[:connection_opts]) do |b|
547
+ b.adapter :test
548
+ end
549
+ cli
550
+ end
551
+
552
+ it 'passes the SSL options along to Faraday::Connection#ssl' do
553
+ expect(subject.connection.ssl.fetch(:ca_file)).to eq('foo.pem')
554
+ end
555
+ end
556
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ describe OAuth2::MACToken do
4
+ subject { described_class.new(client, token, 'abc123') }
5
+
6
+ let(:token) { 'monkey' }
7
+ let(:client) do
8
+ OAuth2::Client.new('abc', 'def', :site => 'https://api.example.com') do |builder|
9
+ builder.request :url_encoded
10
+ builder.adapter :test do |stub|
11
+ VERBS.each do |verb|
12
+ stub.send(verb, '/token/header') { |env| [200, {}, env[:request_headers]['Authorization']] }
13
+ end
14
+ end
15
+ end
16
+ end
17
+
18
+ describe '#initialize' do
19
+ it 'assigns client and token' do
20
+ expect(subject.client).to eq(client)
21
+ expect(subject.token).to eq(token)
22
+ end
23
+
24
+ it 'assigns secret' do
25
+ expect(subject.secret).to eq('abc123')
26
+ end
27
+
28
+ it 'defaults algorithm to hmac-sha-256' do
29
+ pending_for(:engine => 'ruby', :versions => '1.9.3', :reason => "Ruby 1.9's OpenSSL uses instance of OpenSSL::Digest")
30
+ expect(subject.algorithm).to be_instance_of(OpenSSL::Digest::SHA256)
31
+ end
32
+
33
+ it 'handles hmac-sha-256' do
34
+ pending_for(:engine => 'ruby', :versions => '1.9.3', :reason => "Ruby 1.9's OpenSSL uses instance of OpenSSL::Digest")
35
+ mac = described_class.new(client, token, 'abc123', :algorithm => 'hmac-sha-256')
36
+ expect(mac.algorithm).to be_instance_of(OpenSSL::Digest::SHA256)
37
+ end
38
+
39
+ it 'handles hmac-sha-1' do
40
+ pending_for(:engine => 'ruby', :versions => '1.9.3', :reason => "Ruby 1.9's OpenSSL uses instance of OpenSSL::Digest")
41
+ mac = described_class.new(client, token, 'abc123', :algorithm => 'hmac-sha-1')
42
+ expect(mac.algorithm).to be_instance_of(OpenSSL::Digest::SHA1)
43
+ end
44
+
45
+ it 'raises on improper algorithm' do
46
+ expect { described_class.new(client, token, 'abc123', :algorithm => 'invalid-sha') }.to raise_error(ArgumentError)
47
+ end
48
+ end
49
+
50
+ describe '#request' do
51
+ VERBS.each do |verb|
52
+ it "sends the token in the Authorization header for a #{verb.to_s.upcase} request" do
53
+ expect(subject.post('/token/header').body).to include("MAC id=\"#{token}\"")
54
+ end
55
+ end
56
+ end
57
+
58
+ describe '#header' do
59
+ it 'does not generate the same header twice' do
60
+ header = subject.header('get', 'https://www.example.com/hello')
61
+ duplicate_header = subject.header('get', 'https://www.example.com/hello')
62
+
63
+ expect(header).not_to eq(duplicate_header)
64
+ end
65
+
66
+ it 'generates the proper format' do
67
+ header = subject.header('get', 'https://www.example.com/hello?a=1')
68
+ expect(header).to match(/MAC id="#{token}", ts="[0-9]+", nonce="[^"]+", mac="[^"]+"/)
69
+ end
70
+
71
+ it 'passes ArgumentError with an invalid url' do
72
+ expect { subject.header('get', 'this-is-not-valid') }.to raise_error(ArgumentError)
73
+ end
74
+
75
+ it 'passes URI::InvalidURIError through' do
76
+ expect { subject.header('get', nil) }.to raise_error(URI::InvalidURIError)
77
+ end
78
+ end
79
+
80
+ describe '#signature' do
81
+ it 'generates properly' do
82
+ signature = subject.signature(0, 'random-string', 'get', URI('https://www.google.com'))
83
+ expect(signature).to eq('rMDjVA3VJj3v1OmxM29QQljKia6msl5rjN83x3bZmi8=')
84
+ end
85
+ end
86
+
87
+ describe '#headers' do
88
+ it 'is an empty hash' do
89
+ expect(subject.headers).to eq({})
90
+ end
91
+ end
92
+
93
+ describe '.from_access_token' do
94
+ subject { described_class.from_access_token(access_token, 'hello') }
95
+
96
+ let(:access_token) do
97
+ OAuth2::AccessToken.new(
98
+ client, token,
99
+ :expires_at => 1,
100
+ :expires_in => 1,
101
+ :refresh_token => 'abc',
102
+ :random => 1
103
+ )
104
+ end
105
+
106
+ it 'initializes client, token, and secret properly' do
107
+ expect(subject.client).to eq(client)
108
+ expect(subject.token).to eq(token)
109
+ expect(subject.secret).to eq('hello')
110
+ end
111
+
112
+ it 'initializes configuration options' do
113
+ expect(subject.expires_at).to eq(1)
114
+ expect(subject.expires_in).to eq(1)
115
+ expect(subject.refresh_token).to eq('abc')
116
+ end
117
+
118
+ it 'initializes params' do
119
+ expect(subject.params).to eq(:random => 1)
120
+ end
121
+ end
122
+ end