|
| 1 | +import time |
1 | 2 | from unittest import mock |
2 | 3 |
|
3 | 4 | from django.test.utils import override_settings |
@@ -30,14 +31,43 @@ def test_validate_trusted_proxy_header_bad_public_key(self, random_public_key): |
30 | 31 | with override_settings(ANSIBLE_BASE_JWT_KEY=random_public_key): |
31 | 32 | assert not validate_x_trusted_proxy_header("0-12345123451234512345") |
32 | 33 |
|
33 | | - def test_validate_x_trusted_proxy_header_invalid_signature(self, random_public_key, expected_log): |
| 34 | + def test_header_timeout(self, expected_log, rsa_keypair): |
| 35 | + header = generate_x_trusted_proxy_header(rsa_keypair.private) |
| 36 | + with override_settings(ANSIBLE_BASE_JWT_KEY=rsa_keypair.public): |
| 37 | + # Assert this header is valid if used right away |
| 38 | + assert validate_x_trusted_proxy_header(header) is True |
| 39 | + |
| 40 | + # By default the header is only valid for 300ms so a 1/2 second sleep will expire it |
| 41 | + time.sleep(0.5) |
| 42 | + with expected_log( |
| 43 | + 'ansible_base.jwt_consumer.common.util.logger', |
| 44 | + 'warning', |
| 45 | + 'was too old to be valid alter trusted_header_timeout_in_ns if needed', |
| 46 | + ): |
| 47 | + assert validate_x_trusted_proxy_header(header) is False |
| 48 | + |
| 49 | + def test_invalid_header_timestamp(self, expected_log, rsa_keypair): |
| 50 | + header = generate_x_trusted_proxy_header(rsa_keypair.private) |
| 51 | + _, signed_part = header.split('-') |
| 52 | + header = f'asdf-{signed_part}' |
| 53 | + with override_settings(ANSIBLE_BASE_JWT_KEY=rsa_keypair.public): |
| 54 | + with expected_log( |
| 55 | + 'ansible_base.jwt_consumer.common.util.logger', |
| 56 | + 'warning', |
| 57 | + 'Unable to convert timestamp (base64)', |
| 58 | + ): |
| 59 | + assert validate_x_trusted_proxy_header(header) is False |
| 60 | + |
| 61 | + def test_validate_x_trusted_proxy_header_invalid_signature(self, random_public_key, expected_log, rsa_keypair): |
34 | 62 | with override_settings(ANSIBLE_BASE_JWT_KEY=random_public_key): |
35 | | - # Idealy we would mock match bytes.fromhex but I couldn't get that to work |
| 63 | + # Ideally we would mock match bytes.fromhex but I couldn't get that to work |
36 | 64 | # with mock.patch('ansible_base.jwt_consumer.common.util.validate_x_trusted_proxy_header.bytes.fromhex', side_effect=ValueError()): |
| 65 | + header = generate_x_trusted_proxy_header(rsa_keypair.private) |
37 | 66 | with expected_log( |
38 | 67 | 'ansible_base.jwt_consumer.common.util.logger', |
39 | 68 | 'warning', |
40 | 69 | 'Failed to validate x-trusted-proxy-header, malformed, expected signature to well-formed base64', |
41 | 70 | ): |
42 | 71 | # 0 is invalid bytes |
43 | | - assert validate_x_trusted_proxy_header("0-0") is False |
| 72 | + timestamp, junk = header.split('-') |
| 73 | + assert validate_x_trusted_proxy_header(f"{timestamp}-0") is False |
0 commit comments