-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathtest_jwt.py
More file actions
436 lines (388 loc) · 14.9 KB
/
test_jwt.py
File metadata and controls
436 lines (388 loc) · 14.9 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import base64
import logging
from datetime import datetime
import freezegun
import jwt
import pytest
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from airbyte_cdk.sources.declarative.auth.jwt import JwtAuthenticator
from airbyte_cdk.sources.declarative.requesters.request_option import (
RequestOption,
RequestOptionType,
)
LOGGER = logging.getLogger(__name__)
class TestJwtAuthenticator:
"""
Test class for JWT Authenticator.
"""
@pytest.mark.parametrize(
"algorithm, kid, typ, cty, additional_jwt_headers, expected",
[
(
"ALGORITHM",
"test_kid",
"test_typ",
"test_cty",
{"test": "test"},
{
"kid": "test_kid",
"typ": "test_typ",
"cty": "test_cty",
"test": "test",
"alg": "ALGORITHM",
},
),
("ALGORITHM", None, None, None, None, {"alg": "ALGORITHM"}),
],
)
def test_get_jwt_headers(self, algorithm, kid, typ, cty, additional_jwt_headers, expected):
authenticator = JwtAuthenticator(
config={},
parameters={},
algorithm=algorithm,
secret_key="test_key",
token_duration=1200,
kid=kid,
typ=typ,
cty=cty,
additional_jwt_headers=additional_jwt_headers,
)
assert authenticator._get_jwt_headers() == expected
def test_given_overriden_reserverd_properties_get_jwt_headers_throws_error(self):
authenticator = JwtAuthenticator(
config={},
parameters={},
algorithm="ALGORITHM",
secret_key="test_key",
token_duration=1200,
additional_jwt_headers={"kid": "test_kid"},
)
with pytest.raises(ValueError):
authenticator._get_jwt_headers()
@pytest.mark.parametrize(
"iss, sub, aud, additional_jwt_payload, expected",
[
(
"test_iss",
"test_sub",
"test_aud",
{"test": "test"},
{"iss": "test_iss", "sub": "test_sub", "aud": "test_aud", "test": "test"},
),
(None, None, None, None, {}),
],
)
def test_get_jwt_payload(self, iss, sub, aud, additional_jwt_payload, expected):
authenticator = JwtAuthenticator(
config={},
parameters={},
algorithm="ALGORITHM",
secret_key="test_key",
token_duration=1000,
iss=iss,
sub=sub,
aud=aud,
additional_jwt_payload=additional_jwt_payload,
)
with freezegun.freeze_time("2022-01-01 00:00:00"):
expected["iat"] = int(datetime.now().timestamp())
expected["exp"] = expected["iat"] + 1000
expected["nbf"] = expected["iat"]
assert authenticator._get_jwt_payload() == expected
def test_given_overriden_reserverd_properties_get_jwt_payload_throws_error(self):
authenticator = JwtAuthenticator(
config={},
parameters={},
algorithm="ALGORITHM",
secret_key="test_key",
token_duration=0,
additional_jwt_payload={"exp": 1234},
)
with pytest.raises(ValueError):
authenticator._get_jwt_payload()
@pytest.mark.parametrize(
"base64_encode_secret_key, secret_key, expected",
[
(True, "test", base64.b64encode("test".encode()).decode()),
(False, "test", "test"),
],
)
def test_get_secret_key(self, base64_encode_secret_key, secret_key, expected):
authenticator = JwtAuthenticator(
config={},
parameters={},
secret_key=secret_key,
algorithm="test_algo",
token_duration=1200,
base64_encode_secret_key=base64_encode_secret_key,
)
assert authenticator._get_secret_key() == expected
def test_get_secret_key_from_config(
self,
):
authenticator = JwtAuthenticator(
config={"secrets": '{"secret_key": "test"}'},
parameters={},
secret_key="{{ json_loads(config['secrets'])['secret_key'] }}",
algorithm="test_algo",
token_duration=1200,
base64_encode_secret_key=False,
)
expected = "test"
assert authenticator._get_secret_key() == expected
def test_get_signed_token(self):
authenticator = JwtAuthenticator(
config={},
parameters={},
secret_key="test",
algorithm="HS256",
token_duration=1000,
typ="JWT",
iss="iss",
)
assert authenticator._get_signed_token() == jwt.encode(
payload=authenticator._get_jwt_payload(),
key=authenticator._get_secret_key(),
algorithm=authenticator._algorithm,
headers=authenticator._get_jwt_headers(),
)
def test_given_invalid_algorithm_get_signed_token_throws_error(self):
authenticator = JwtAuthenticator(
config={},
parameters={},
secret_key="test",
algorithm="invalid algorithm type",
token_duration=1000,
base64_encode_secret_key=False,
header_prefix="Bearer",
typ="JWT",
iss="iss",
additional_jwt_headers={},
additional_jwt_payload={},
)
with pytest.raises(ValueError):
authenticator._get_signed_token()
@pytest.mark.parametrize("header_prefix, expected", [("test", "test"), (None, None)])
def test_get_header_prefix(self, header_prefix, expected):
authenticator = JwtAuthenticator(
config={},
parameters={},
secret_key="key",
algorithm="test_algo",
token_duration=1200,
header_prefix=header_prefix,
)
assert authenticator._get_header_prefix() == expected
def test_get_secret_key_with_passphrase(self):
"""Test _get_secret_key method with encrypted private key and passphrase."""
# Generate a test RSA private key
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
passphrase = b"test_passphrase"
encrypted_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(passphrase),
)
authenticator = JwtAuthenticator(
config={},
parameters={},
secret_key=encrypted_pem.decode(),
algorithm="RS256",
token_duration=1200,
passphrase="test_passphrase",
)
result_key = authenticator._get_secret_key()
assert isinstance(result_key, rsa.RSAPrivateKey)
original_public_key = private_key.public_key()
result_public_key = result_key.public_key()
original_public_numbers = original_public_key.public_numbers()
result_public_numbers = result_public_key.public_numbers()
assert original_public_numbers.n == result_public_numbers.n
assert original_public_numbers.e == result_public_numbers.e
def test_get_secret_key_with_wrong_passphrase_raises_error(self):
"""Test that _get_secret_key raises error with wrong passphrase."""
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
passphrase = b"correct_passphrase"
encrypted_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(passphrase),
)
authenticator = JwtAuthenticator(
config={},
parameters={},
secret_key=encrypted_pem.decode(),
algorithm="RS256",
token_duration=1200,
passphrase="wrong_passphrase",
)
with pytest.raises(Exception):
authenticator._get_secret_key()
def test_get_signed_token_with_passphrase_protected_key(self):
"""Test that JWT signing works with passphrase-protected RSA private key."""
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
passphrase = b"test_passphrase"
encrypted_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.BestAvailableEncryption(passphrase),
)
authenticator = JwtAuthenticator(
config={},
parameters={},
secret_key=encrypted_pem.decode(),
algorithm="RS256",
token_duration=1000,
passphrase="test_passphrase",
typ="JWT",
iss="test_issuer",
)
signed_token = authenticator._get_signed_token()
assert isinstance(signed_token, str)
assert len(signed_token.split(".")) == 3
public_key = private_key.public_key()
decoded_payload = jwt.decode(signed_token, public_key, algorithms=["RS256"])
assert decoded_payload["iss"] == "test_issuer"
assert "iat" in decoded_payload
assert "exp" in decoded_payload
@pytest.mark.parametrize(
"request_option, expected_request_key",
[
pytest.param(
RequestOption(
inject_into=RequestOptionType.request_parameter,
field_name="custom_parameter",
parameters={},
),
"custom_parameter",
id="test_get_request_headers",
),
pytest.param(
RequestOption(
inject_into=RequestOptionType.body_data, field_name="custom_body", parameters={}
),
"custom_body",
id="test_get_request_headers",
),
pytest.param(
RequestOption(
inject_into=RequestOptionType.body_json, field_name="custom_json", parameters={}
),
"custom_json",
id="test_get_request_headers",
),
],
)
def test_get_request_options(self, request_option, expected_request_key):
authenticator = JwtAuthenticator(
config={},
parameters={},
algorithm="HS256",
secret_key="test_key",
token_duration=1000,
iss="test_iss",
sub="test_sub",
aud="test_aud",
additional_jwt_payload={"kid": "test_kid"},
request_option=request_option,
)
expected_request_options = {
expected_request_key: jwt.encode(
payload=authenticator._get_jwt_payload(),
key=authenticator._get_secret_key(),
algorithm=authenticator._algorithm,
headers=authenticator._get_jwt_headers(),
)
}
match request_option.inject_into:
case RequestOptionType.request_parameter:
actual_request_options = authenticator.get_request_params()
case RequestOptionType.body_data:
actual_request_options = authenticator.get_request_body_data()
case RequestOptionType.body_json:
actual_request_options = authenticator.get_request_body_json()
case _:
actual_request_options = None
assert actual_request_options == expected_request_options
@pytest.mark.parametrize(
"request_option, expected_header_key",
[
pytest.param(
RequestOption(
inject_into=RequestOptionType.header,
field_name="custom_authorization",
parameters={},
),
"custom_authorization",
id="test_get_request_headers",
),
pytest.param(None, "Authorization", id="test_with_default_authorization_header"),
],
)
def test_get_request_headers(self, request_option, expected_header_key):
authenticator = JwtAuthenticator(
config={},
parameters={},
algorithm="HS256",
secret_key="test_key",
token_duration=1000,
iss="test_iss",
sub="test_sub",
aud="test_aud",
additional_jwt_payload={"kid": "test_kid"},
request_option=request_option,
)
expected_headers = {
expected_header_key: jwt.encode(
payload=authenticator._get_jwt_payload(),
key=authenticator._get_secret_key(),
algorithm=authenticator._algorithm,
headers=authenticator._get_jwt_headers(),
)
}
assert authenticator.get_auth_header() == expected_headers
def test_get_signed_token_with_escaped_newlines_in_pem_key(self):
"""Test that JWT signing works with PEM keys containing escaped newlines."""
# Generate a test RSA private key
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=default_backend()
)
# Get the PEM representation with actual newlines
pem_with_newlines = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
).decode()
# Create a version with escaped newlines (as stored in some systems)
pem_with_escaped_newlines = pem_with_newlines.replace("\n", "\\n")
# Test with escaped newlines - should work after normalization
authenticator = JwtAuthenticator(
config={},
parameters={},
secret_key=pem_with_escaped_newlines,
algorithm="RS256",
token_duration=1000,
typ="JWT",
iss="test_issuer",
)
signed_token = authenticator._get_signed_token()
# Verify the token is valid
assert isinstance(signed_token, str)
assert len(signed_token.split(".")) == 3
# Verify we can decode it with the public key
public_key = private_key.public_key()
decoded_payload = jwt.decode(signed_token, public_key, algorithms=["RS256"])
assert decoded_payload["iss"] == "test_issuer"
assert "iat" in decoded_payload
assert "exp" in decoded_payload