|
| 1 | +import jwt |
| 2 | +import pytest |
| 3 | +from cryptography.hazmat.primitives import serialization |
| 4 | +from cryptography.hazmat.primitives.asymmetric import rsa |
| 5 | +from pytest_django.fixtures import SettingsWrapper |
| 6 | +from pytest_mock import MockerFixture |
| 7 | + |
| 8 | +from integrations.github.client import generate_jwt_token, generate_token |
| 9 | + |
| 10 | + |
| 11 | +@pytest.fixture() |
| 12 | +def rsa_private_key() -> rsa.RSAPrivateKey: |
| 13 | + return rsa.generate_private_key(public_exponent=65537, key_size=2048) |
| 14 | + |
| 15 | + |
| 16 | +@pytest.fixture(autouse=True) |
| 17 | +def github_pem(settings: SettingsWrapper, rsa_private_key: rsa.RSAPrivateKey) -> None: |
| 18 | + settings.GITHUB_PEM = rsa_private_key.private_bytes( |
| 19 | + encoding=serialization.Encoding.PEM, |
| 20 | + format=serialization.PrivateFormat.PKCS8, |
| 21 | + encryption_algorithm=serialization.NoEncryption(), |
| 22 | + ).decode() |
| 23 | + |
| 24 | + |
| 25 | +def test_generate_token__valid_credentials__returns_installation_token( |
| 26 | + mocker: MockerFixture, |
| 27 | +) -> None: |
| 28 | + # Given |
| 29 | + mock_installation_auth = mocker.MagicMock() |
| 30 | + mock_installation_auth.token = "installation-token" |
| 31 | + mocker.patch( |
| 32 | + "integrations.github.client.Auth.AppAuth.get_installation_auth", |
| 33 | + return_value=mock_installation_auth, |
| 34 | + ) |
| 35 | + mocker.patch("integrations.github.client.Github") |
| 36 | + |
| 37 | + # When |
| 38 | + result = generate_token(installation_id="12345", app_id=67890) |
| 39 | + |
| 40 | + # Then |
| 41 | + assert result == "installation-token" |
| 42 | + |
| 43 | + |
| 44 | +def test_generate_jwt_token__valid_credentials__returns_decodable_jwt( |
| 45 | + rsa_private_key: rsa.RSAPrivateKey, |
| 46 | +) -> None: |
| 47 | + # Given |
| 48 | + app_id = 12345 |
| 49 | + |
| 50 | + # When |
| 51 | + token = generate_jwt_token(app_id=app_id) |
| 52 | + |
| 53 | + # Then |
| 54 | + decoded = jwt.decode( |
| 55 | + token, |
| 56 | + rsa_private_key.public_key(), |
| 57 | + algorithms=["RS256"], |
| 58 | + options={"verify_exp": False}, |
| 59 | + ) |
| 60 | + assert decoded["iss"] == str(app_id) |
0 commit comments