Repository navigation
Expand file tree
/
Copy pathGitHubAppAuthentication.php
More file actions
226 lines (189 loc) · 6.67 KB
/
Copy pathGitHubAppAuthentication.php
File metadata and controls
226 lines (189 loc) · 6.67 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
<?php
namespace JordanPartridge\GithubClient\Auth;
use DateTimeImmutable;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use JordanPartridge\GithubClient\Exceptions\AuthenticationException;
use JordanPartridge\GithubClient\Requests\Installations\CreateAccessToken;
use Saloon\Http\Auth\TokenAuthenticator;
/**
* GitHub App authentication strategy using JWT tokens.
*/
class GitHubAppAuthentication implements AuthenticationStrategy
{
private ?string $installationToken = null;
private ?DateTimeImmutable $installationTokenExpiry = null;
private ?object $connector = null;
public function __construct(
private readonly string $appId,
private readonly string $privateKey,
private readonly ?string $installationId = null,
) {}
public function getAuthorizationHeader(): string
{
if ($this->installationId && $this->hasValidInstallationToken()) {
return "Bearer {$this->installationToken}";
}
// Use JWT token for app-level authentication
return "Bearer {$this->generateJwtToken()}";
}
public function validate(): void
{
if (empty($this->appId)) {
throw AuthenticationException::githubAppAuthFailed('App ID is required');
}
if (! is_numeric($this->appId)) {
throw AuthenticationException::githubAppAuthFailed('App ID must be numeric');
}
if (empty($this->privateKey)) {
throw AuthenticationException::githubAppAuthFailed('Private key is required');
}
// Validate private key format
if (! $this->isValidPrivateKey()) {
throw AuthenticationException::githubAppAuthFailed('Invalid private key format');
}
}
public function getType(): string
{
return 'github_app';
}
public function needsRefresh(): bool
{
if (! $this->installationId) {
return false; // App-level JWT tokens are generated fresh each time
}
return ! $this->hasValidInstallationToken();
}
public function refresh(): void
{
if ($this->installationId) {
$this->refreshInstallationToken();
}
}
/**
* Generate a JWT token for GitHub App authentication.
*/
private function generateJwtToken(): string
{
$now = new DateTimeImmutable();
$expiry = $now->modify('+10 minutes'); // GitHub recommends max 10 minutes
$payload = [
'iat' => $now->getTimestamp(),
'exp' => $expiry->getTimestamp(),
'iss' => $this->appId,
];
$privateKey = $this->privateKey;
if (! str_contains($privateKey, '-----BEGIN')) {
$privateKey = base64_decode($privateKey, true) ?: $privateKey;
}
return JWT::encode($payload, $privateKey, 'RS256');
}
/**
* Check if we have a valid installation token.
*/
private function hasValidInstallationToken(): bool
{
if (! $this->installationToken || ! $this->installationTokenExpiry) {
return false;
}
// Add 5-minute buffer before expiry
$bufferTime = $this->installationTokenExpiry->modify('-5 minutes');
return new DateTimeImmutable() < $bufferTime;
}
/**
* Refresh the installation token.
*
* Note: This method requires the connector to be set via setConnector()
* before calling refresh(). The connector is typically injected when
* used with GithubConnector.
*/
private function refreshInstallationToken(): void
{
if (! $this->installationId) {
throw AuthenticationException::githubAppAuthFailed('Installation ID required for installation token');
}
// Import the required classes
$createTokenRequest = new CreateAccessToken(
(int) $this->installationId,
);
// The token exchange must use the app JWT, not the installation auth
// that is currently being refreshed by this connector.
$createTokenRequest->authenticate(new TokenAuthenticator($this->generateJwtToken()));
// Make the API call to get the installation token
// This will use JWT authentication (app-level) to get the installation token
try {
$response = $this->makeApiRequest($createTokenRequest);
if (! $response->successful()) {
throw AuthenticationException::githubAppAuthFailed(
'Failed to refresh installation token: ' . ($response->json('message') ?? 'Unknown error'),
);
}
$data = $response->json();
$this->installationToken = $data['token'];
$this->installationTokenExpiry = new DateTimeImmutable($data['expires_at']);
} catch (\Exception $e) {
throw AuthenticationException::githubAppAuthFailed(
'Failed to refresh installation token: ' . $e->getMessage(),
);
}
}
/**
* Make an API request (to be implemented by connector integration).
*
* @throws AuthenticationException
*/
private function makeApiRequest(object $request): mixed
{
if (! isset($this->connector)) {
throw AuthenticationException::githubAppAuthFailed(
'Connector not set. Cannot refresh installation token without connector.',
);
}
return $this->connector->send($request);
}
/**
* Set the connector for making API requests.
*/
public function setConnector(object $connector): void
{
$this->connector = $connector;
}
/**
* Validate the private key format.
*/
private function isValidPrivateKey(): bool
{
// Check if it's a valid PEM format
if (str_contains($this->privateKey, '-----BEGIN')) {
return openssl_pkey_get_private($this->privateKey) !== false;
}
// Check if it might be a base64 encoded key
$decoded = base64_decode($this->privateKey, true);
if ($decoded !== false && str_contains($decoded, '-----BEGIN')) {
return openssl_pkey_get_private($decoded) !== false;
}
return false;
}
/**
* Set an installation token directly (for when fetched externally).
*/
public function setInstallationToken(string $token, DateTimeImmutable $expiry): void
{
$this->installationToken = $token;
$this->installationTokenExpiry = $expiry;
}
/**
* Get the App ID.
*/
public function getAppId(): string
{
return $this->appId;
}
/**
* Get the Installation ID if set.
*/
public function getInstallationId(): ?string
{
return $this->installationId;
}
}