|
| 1 | +"""Tests for the github_app module.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +from unittest.mock import MagicMock, patch |
| 7 | + |
| 8 | +import jwt |
| 9 | +import pytest |
| 10 | +from cryptography.hazmat.backends import default_backend |
| 11 | +from cryptography.hazmat.primitives import serialization |
| 12 | +from cryptography.hazmat.primitives.asymmetric import rsa |
| 13 | +from lib.github_app import ( |
| 14 | + generate_jwt, |
| 15 | + get_github_app_token, |
| 16 | + get_installation_id, |
| 17 | + get_installation_token, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +def generate_test_key_pair(): |
| 22 | + """Generate a test RSA key pair.""" |
| 23 | + private_key = rsa.generate_private_key( |
| 24 | + public_exponent=65537, |
| 25 | + key_size=2048, |
| 26 | + backend=default_backend(), |
| 27 | + ) |
| 28 | + |
| 29 | + pem_private = private_key.private_bytes( |
| 30 | + encoding=serialization.Encoding.PEM, |
| 31 | + format=serialization.PrivateFormat.TraditionalOpenSSL, |
| 32 | + encryption_algorithm=serialization.NoEncryption(), |
| 33 | + ).decode() |
| 34 | + |
| 35 | + pem_public = ( |
| 36 | + private_key.public_key() |
| 37 | + .public_bytes( |
| 38 | + encoding=serialization.Encoding.PEM, |
| 39 | + format=serialization.PublicFormat.SubjectPublicKeyInfo, |
| 40 | + ) |
| 41 | + .decode() |
| 42 | + ) |
| 43 | + |
| 44 | + return pem_private, pem_public |
| 45 | + |
| 46 | + |
| 47 | +def test_generate_jwt_returns_string(): |
| 48 | + """Test that generate_jwt returns a JWT string.""" |
| 49 | + test_private_key, _ = generate_test_key_pair() |
| 50 | + |
| 51 | + jwt_token = generate_jwt("12345", test_private_key) |
| 52 | + |
| 53 | + assert isinstance(jwt_token, str) |
| 54 | + assert len(jwt_token.split(".")) == 3 # JWT has 3 parts separated by dots |
| 55 | + |
| 56 | + |
| 57 | +def test_generate_jwt_contains_correct_claims(): |
| 58 | + """Test that the generated JWT contains the correct claims.""" |
| 59 | + test_private_key, test_public_key = generate_test_key_pair() |
| 60 | + |
| 61 | + jwt_token = generate_jwt("12345", test_private_key) |
| 62 | + |
| 63 | + decoded = jwt.decode(jwt_token, test_public_key, algorithms=["RS256"]) |
| 64 | + |
| 65 | + assert decoded["iss"] == "12345" |
| 66 | + assert "iat" in decoded |
| 67 | + assert "exp" in decoded |
| 68 | + # exp should be about 10 minutes after iat (with 60s clock drift adjustment) |
| 69 | + assert abs((decoded["exp"] - decoded["iat"]) - 11 * 60) < 5 |
| 70 | + |
| 71 | + |
| 72 | +def test_get_installation_id_success(): |
| 73 | + """Test successful installation ID retrieval.""" |
| 74 | + mock_response = MagicMock() |
| 75 | + mock_response.read.return_value = json.dumps([ |
| 76 | + {"id": 111, "account": {"login": "other-org"}}, |
| 77 | + {"id": 222, "account": {"login": "compiler-explorer"}}, |
| 78 | + ]).encode() |
| 79 | + |
| 80 | + with patch("urllib.request.urlopen", return_value=mock_response): |
| 81 | + result = get_installation_id("fake_jwt", org="compiler-explorer") |
| 82 | + |
| 83 | + assert result == 222 |
| 84 | + |
| 85 | + |
| 86 | +def test_get_installation_id_not_found(): |
| 87 | + """Test error when installation is not found.""" |
| 88 | + mock_response = MagicMock() |
| 89 | + mock_response.read.return_value = json.dumps([ |
| 90 | + {"id": 111, "account": {"login": "other-org"}}, |
| 91 | + ]).encode() |
| 92 | + |
| 93 | + with patch("urllib.request.urlopen", return_value=mock_response): |
| 94 | + with pytest.raises(RuntimeError, match="not installed"): |
| 95 | + get_installation_id("fake_jwt", org="compiler-explorer") |
| 96 | + |
| 97 | + |
| 98 | +def test_get_installation_token_success(): |
| 99 | + """Test successful installation token retrieval.""" |
| 100 | + mock_response = MagicMock() |
| 101 | + mock_response.read.return_value = json.dumps({ |
| 102 | + "token": "ghs_xxxxxxxxxxxxxxxxxxxx", |
| 103 | + "expires_at": "2024-01-01T00:00:00Z", |
| 104 | + }).encode() |
| 105 | + |
| 106 | + with patch("urllib.request.urlopen", return_value=mock_response): |
| 107 | + result = get_installation_token("fake_jwt", 12345) |
| 108 | + |
| 109 | + assert result == "ghs_xxxxxxxxxxxxxxxxxxxx" |
| 110 | + |
| 111 | + |
| 112 | +def test_get_github_app_token_success(): |
| 113 | + """Test successful end-to-end token retrieval.""" |
| 114 | + test_private_key, _ = generate_test_key_pair() |
| 115 | + |
| 116 | + mock_ssm_client = MagicMock() |
| 117 | + mock_ssm_client.get_parameter.return_value = {"Parameter": {"Value": test_private_key}} |
| 118 | + |
| 119 | + mock_installations_response = MagicMock() |
| 120 | + mock_installations_response.read.return_value = json.dumps([ |
| 121 | + {"id": 67890, "account": {"login": "compiler-explorer"}}, |
| 122 | + ]).encode() |
| 123 | + |
| 124 | + mock_token_response = MagicMock() |
| 125 | + mock_token_response.read.return_value = json.dumps({ |
| 126 | + "token": "ghs_test_token_12345", |
| 127 | + }).encode() |
| 128 | + |
| 129 | + with ( |
| 130 | + patch("lib.github_app.get_ssm_param", return_value="12345"), |
| 131 | + patch("lib.github_app.ssm_client", mock_ssm_client), |
| 132 | + patch("urllib.request.urlopen", side_effect=[mock_installations_response, mock_token_response]), |
| 133 | + ): |
| 134 | + result = get_github_app_token() |
| 135 | + |
| 136 | + assert result == "ghs_test_token_12345" |
| 137 | + |
| 138 | + |
| 139 | +def test_get_github_app_token_missing_app_id(): |
| 140 | + """Test error when App ID is missing from SSM.""" |
| 141 | + |
| 142 | + def mock_get_ssm_param(param): |
| 143 | + if "app-id" in param: |
| 144 | + raise Exception("Parameter not found") |
| 145 | + return "some_value" |
| 146 | + |
| 147 | + with patch("lib.github_app.get_ssm_param", side_effect=mock_get_ssm_param): |
| 148 | + with pytest.raises(RuntimeError, match="App ID"): |
| 149 | + get_github_app_token() |
| 150 | + |
| 151 | + |
| 152 | +def test_get_github_app_token_missing_private_key(): |
| 153 | + """Test error when private key is missing from SSM.""" |
| 154 | + mock_ssm_client = MagicMock() |
| 155 | + mock_ssm_client.get_parameter.side_effect = Exception("Parameter not found") |
| 156 | + |
| 157 | + with ( |
| 158 | + patch("lib.github_app.get_ssm_param", return_value="12345"), |
| 159 | + patch("lib.github_app.ssm_client", mock_ssm_client), |
| 160 | + ): |
| 161 | + with pytest.raises(RuntimeError, match="private key"): |
| 162 | + get_github_app_token() |
0 commit comments