-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalma_jwt_validator_spec.rb
More file actions
92 lines (77 loc) · 2.65 KB
/
Copy pathalma_jwt_validator_spec.rb
File metadata and controls
92 lines (77 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
require 'rails_helper'
require 'jwt'
require 'json'
require 'openssl'
describe AlmaJwtValidator do
let(:alma_institution_code) { '01UCS_BER' }
let(:jwks_url) { "https://api-na.hosted.exlibrisgroup.com/auth/#{alma_institution_code}/jwks.json" }
let(:expected_iss) { 'Prima' }
# Generate an EC key pair for testing
let(:ec_key) { OpenSSL::PKey::EC.generate('prime256v1') }
let(:kid) { 'test-key-id' }
let(:test_payload) { { 'userName' => '10335026', 'iss' => expected_iss } }
# Helper to create JWK hash from EC key using JWT::JWK
def create_jwk_hash(key, kid)
jwk = JWT::JWK.new(key, kid: kid)
jwk.export
end
# Helper to generate a valid JWT
def generate_jwt(payload, key, kid, algorithm = 'ES256')
header = { 'kid' => kid, 'alg' => algorithm }
JWT.encode(payload, key, algorithm, header)
end
before do
jwk = create_jwk_hash(ec_key, kid)
stub_request(:get, jwks_url)
.to_return(
status: 200,
body: { 'keys' => [jwk] }.to_json,
headers: { 'Content-Type' => 'application/json' }
)
end
describe '.decode_and_verify_jwt' do
context 'with a valid JWT' do
it 'returns the decoded payload' do
token = generate_jwt(test_payload, ec_key, kid)
result = AlmaJwtValidator.decode_and_verify_jwt(token)
expect(result).to be_an(Array)
expect(result[0]['userName']).to eq('10335026')
expect(result[1]['kid']).to eq(kid)
end
end
context 'with an invalid signature' do
it 'raises JWT::DecodeError' do
# Generate a token with a different key
different_key = OpenSSL::PKey::EC.generate('prime256v1')
token = generate_jwt(test_payload, different_key, kid)
expect do
AlmaJwtValidator.decode_and_verify_jwt(token)
end.to raise_error(JWT::DecodeError)
end
end
context 'with an unknown key id' do
it 'raises JWT::DecodeError' do
token = generate_jwt(test_payload, ec_key, 'unknown-kid')
expect do
AlmaJwtValidator.decode_and_verify_jwt(token)
end.to raise_error(JWT::DecodeError)
end
end
context 'with a malformed JWT' do
it 'raises JWT::DecodeError' do
expect do
AlmaJwtValidator.decode_and_verify_jwt('not.a.jwt')
end.to raise_error(JWT::DecodeError)
end
end
context 'when JWKS endpoint is unreachable' do
it 'raises an error' do
stub_request(:get, jwks_url).to_return(status: 500)
token = generate_jwt(test_payload, ec_key, kid)
expect do
AlmaJwtValidator.decode_and_verify_jwt(token)
end.to raise_error(StandardError)
end
end
end
end