-
Notifications
You must be signed in to change notification settings - Fork 722
Expand file tree
/
Copy pathauth.test.ts
More file actions
396 lines (329 loc) · 14.5 KB
/
auth.test.ts
File metadata and controls
396 lines (329 loc) · 14.5 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
import { createAppAuth } from '@octokit/auth-app';
import { StrategyOptions } from '@octokit/auth-app/dist-types/types';
import { request } from '@octokit/request';
import { RequestInterface, RequestParameters } from '@octokit/types';
import { getParameters } from '@aws-github-runner/aws-ssm-util';
import { generateKeyPairSync } from 'node:crypto';
import * as nock from 'nock';
import { createGithubAppAuth, createOctokitClient, getStoredInstallationId, resetAppCredentialsCache } from './auth';
import { describe, it, expect, beforeEach, vi } from 'vitest';
type MockProxy<T> = T & {
mockImplementation: (fn: (...args: T[]) => T) => MockProxy<T>;
mockResolvedValue: (value: T) => MockProxy<T>;
mockRejectedValue: (value: T) => MockProxy<T>;
mockReturnValue: (value: T) => MockProxy<T>;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mock = <T>(implementation?: any): MockProxy<T> => vi.fn(implementation) as any;
vi.mock('@aws-github-runner/aws-ssm-util');
vi.mock('@octokit/auth-app');
const cleanEnv = process.env;
const ENVIRONMENT = 'dev';
const GITHUB_APP_ID = '1';
const PARAMETER_GITHUB_APP_ID_NAME = `/actions-runner/${ENVIRONMENT}/github_app_id`;
const PARAMETER_GITHUB_APP_KEY_BASE64_NAME = `/actions-runner/${ENVIRONMENT}/github_app_key_base64`;
const mockedGetParameters = vi.mocked(getParameters);
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
resetAppCredentialsCache();
process.env = { ...cleanEnv };
process.env.PARAMETER_GITHUB_APP_ID_NAME = PARAMETER_GITHUB_APP_ID_NAME;
process.env.PARAMETER_GITHUB_APP_KEY_BASE64_NAME = PARAMETER_GITHUB_APP_KEY_BASE64_NAME;
nock.disableNetConnect();
});
describe('Test createOctoClient', () => {
it('Creates app client to GitHub public', async () => {
// Arrange
const token = '123456';
// Act
const result = await createOctokitClient(token);
// Assert
expect(result.request.endpoint.DEFAULTS.baseUrl).toBe('https://api.github.com');
});
it('Creates app client to GitHub ES', async () => {
// Arrange
const enterpriseServer = 'https://github.enterprise.notgoingtowork';
const token = '123456';
// Act
const result = await createOctokitClient(token, enterpriseServer);
// Assert
expect(result.request.endpoint.DEFAULTS.baseUrl).toBe(enterpriseServer);
expect(result.request.endpoint.DEFAULTS.mediaType.previews).toStrictEqual(['antiope']);
});
});
describe('Test createGithubAppAuth', () => {
const mockedCreatAppAuth = vi.mocked(createAppAuth);
let mockedRequestInterface: MockProxy<RequestInterface>;
const installationId = 1;
const authType = 'app';
const token = '123456';
const decryptedValue = 'decryptedValue';
const b64 = Buffer.from(decryptedValue, 'binary').toString('base64');
beforeEach(() => {
process.env.ENVIRONMENT = ENVIRONMENT;
});
it('Throws early when PARAMETER_GITHUB_APP_ID_NAME is not set', async () => {
delete process.env.PARAMETER_GITHUB_APP_ID_NAME;
await expect(createGithubAppAuth(installationId)).rejects.toThrow(
'Environment variable PARAMETER_GITHUB_APP_ID_NAME is not set',
);
expect(mockedGetParameters).not.toHaveBeenCalled();
});
it('Throws early when PARAMETER_GITHUB_APP_KEY_BASE64_NAME is not set', async () => {
delete process.env.PARAMETER_GITHUB_APP_KEY_BASE64_NAME;
await expect(createGithubAppAuth(installationId)).rejects.toThrow(
'Environment variable PARAMETER_GITHUB_APP_KEY_BASE64_NAME is not set',
);
expect(mockedGetParameters).not.toHaveBeenCalled();
});
it('Creates auth object with createJwt callback including jti claim', async () => {
// Arrange
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64],
]),
);
const mockedAuth = vi.fn();
mockedAuth.mockResolvedValue({ token });
const mockWithHook = Object.assign(mockedAuth, { hook: vi.fn() });
mockedCreatAppAuth.mockReturnValue(mockWithHook);
// Act
await createGithubAppAuth(installationId);
// Assert
expect(mockedCreatAppAuth).toBeCalledTimes(1);
const callArgs = mockedCreatAppAuth.mock.calls[0][0] as Record<string, unknown>;
expect(callArgs.appId).toBe(parseInt(GITHUB_APP_ID));
expect(callArgs.createJwt).toBeTypeOf('function');
expect(callArgs).not.toHaveProperty('privateKey');
expect(callArgs.installationId).toBe(installationId);
});
it('createJwt callback produces unique JWTs with jti', async () => {
// Arrange — need a real RSA key since createJwt actually signs
const { privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
publicKeyEncoding: { type: 'spki', format: 'pem' },
});
const b64Key = Buffer.from(privateKey as string).toString('base64');
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64Key],
]),
);
let capturedCreateJwt: (appId: string | number, timeDifference?: number) => Promise<{ jwt: string }>;
mockedCreatAppAuth.mockImplementation((opts: StrategyOptions) => {
capturedCreateJwt = (opts as Record<string, unknown>).createJwt as typeof capturedCreateJwt;
const mockedAuth = vi.fn().mockResolvedValue({ token });
return Object.assign(mockedAuth, { hook: vi.fn() });
});
// Act
await createGithubAppAuth(installationId);
// Generate two JWTs and verify they are different (jti makes them unique)
const jwt1 = await capturedCreateJwt!(1);
const jwt2 = await capturedCreateJwt!(1);
// Assert — JWTs must differ even when generated in the same second
expect(jwt1.jwt).not.toBe(jwt2.jwt);
// Verify JWT structure: header.payload.signature
const parts = jwt1.jwt.split('.');
expect(parts).toHaveLength(3);
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
expect(payload).toHaveProperty('jti');
expect(payload).toHaveProperty('iat');
expect(payload).toHaveProperty('exp');
expect(payload).toHaveProperty('iss');
});
it('Creates auth object with line breaks in SSH key.', async () => {
// Arrange
const b64PrivateKeyWithLineBreaks = Buffer.from(decryptedValue + '\n' + decryptedValue, 'binary').toString(
'base64',
);
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64PrivateKeyWithLineBreaks],
]),
);
const mockedAuth = vi.fn();
mockedAuth.mockResolvedValue({ token });
const mockWithHook = Object.assign(mockedAuth, { hook: vi.fn() });
mockedCreatAppAuth.mockReturnValue(mockWithHook);
// Act
const result = await createGithubAppAuth(installationId);
// Assert
expect(getParameters).toBeCalledWith([PARAMETER_GITHUB_APP_ID_NAME, PARAMETER_GITHUB_APP_KEY_BASE64_NAME]);
expect(mockedCreatAppAuth).toBeCalledTimes(1);
expect(mockedAuth).toBeCalledWith({ type: authType });
expect(result.token).toBe(token);
});
it('Creates auth object for public GitHub', async () => {
// Arrange
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64],
]),
);
const mockedAuth = vi.fn();
mockedAuth.mockResolvedValue({ token });
const mockWithHook = Object.assign(mockedAuth, { hook: vi.fn() });
mockedCreatAppAuth.mockReturnValue(mockWithHook);
// Act
const result = await createGithubAppAuth(installationId);
// Assert
expect(getParameters).toBeCalledWith([PARAMETER_GITHUB_APP_ID_NAME, PARAMETER_GITHUB_APP_KEY_BASE64_NAME]);
expect(mockedCreatAppAuth).toBeCalledTimes(1);
const callArgs = mockedCreatAppAuth.mock.calls[0][0] as Record<string, unknown>;
expect(callArgs.appId).toBe(parseInt(GITHUB_APP_ID));
expect(callArgs.createJwt).toBeTypeOf('function');
expect(callArgs.installationId).toBe(installationId);
expect(mockedAuth).toBeCalledWith({ type: authType });
expect(result.token).toBe(token);
});
it('Creates auth object for Enterprise Server', async () => {
// Arrange
const githubServerUrl = 'https://github.enterprise.notgoingtowork';
mockedRequestInterface = mock<RequestInterface>();
vi.spyOn(request, 'defaults').mockImplementation(
() => mockedRequestInterface as RequestInterface<object & RequestParameters>,
);
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64],
]),
);
const mockedAuth = vi.fn();
mockedAuth.mockResolvedValue({ token });
// eslint-disable-next-line @typescript-eslint/no-unused-vars
mockedCreatAppAuth.mockImplementation((authOptions: StrategyOptions) => {
return Object.assign(mockedAuth, { hook: vi.fn() });
});
// Act
const result = await createGithubAppAuth(installationId, githubServerUrl);
// Assert
expect(getParameters).toBeCalledWith([PARAMETER_GITHUB_APP_ID_NAME, PARAMETER_GITHUB_APP_KEY_BASE64_NAME]);
expect(mockedCreatAppAuth).toBeCalledTimes(1);
const callArgs = mockedCreatAppAuth.mock.calls[0][0] as Record<string, unknown>;
expect(callArgs.appId).toBe(parseInt(GITHUB_APP_ID));
expect(callArgs.createJwt).toBeTypeOf('function');
expect(callArgs.installationId).toBe(installationId);
expect(callArgs.request).toBeDefined();
expect(mockedAuth).toBeCalledWith({ type: authType });
expect(result.token).toBe(token);
});
it('Creates auth object for Enterprise Server with no ID', async () => {
// Arrange
const githubServerUrl = 'https://github.enterprise.notgoingtowork';
mockedRequestInterface = mock<RequestInterface>();
vi.spyOn(request, 'defaults').mockImplementation(
() => mockedRequestInterface as RequestInterface<object & RequestParameters>,
);
const installationId = undefined;
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64],
]),
);
const mockedAuth = vi.fn();
mockedAuth.mockResolvedValue({ token });
const mockWithHook = Object.assign(mockedAuth, { hook: vi.fn() });
mockedCreatAppAuth.mockReturnValue(mockWithHook);
// Act
const result = await createGithubAppAuth(installationId, githubServerUrl);
// Assert
expect(getParameters).toBeCalledWith([PARAMETER_GITHUB_APP_ID_NAME, PARAMETER_GITHUB_APP_KEY_BASE64_NAME]);
expect(mockedCreatAppAuth).toBeCalledTimes(1);
const callArgs = mockedCreatAppAuth.mock.calls[0][0] as Record<string, unknown>;
expect(callArgs.appId).toBe(parseInt(GITHUB_APP_ID));
expect(callArgs.createJwt).toBeTypeOf('function');
expect(callArgs).not.toHaveProperty('installationId');
expect(callArgs.request).toBeDefined();
expect(mockedAuth).toBeCalledWith({ type: authType });
expect(result.token).toBe(token);
});
});
describe('Test getStoredInstallationId', () => {
const decryptedValue = 'decryptedValue';
const b64 = Buffer.from(decryptedValue, 'binary').toString('base64');
beforeEach(() => {
const mockedAuth = vi.fn();
mockedAuth.mockResolvedValue({ token: 'token' });
const mockWithHook = Object.assign(mockedAuth, { hook: vi.fn() });
vi.mocked(createAppAuth).mockReturnValue(mockWithHook);
});
it('returns stored installation ID when configured', async () => {
const installationIdParam = `/actions-runner/${ENVIRONMENT}/github_app_installation_id`;
process.env.PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME = installationIdParam;
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64],
[installationIdParam, '12345'],
]),
);
const result = await getStoredInstallationId(0);
expect(result).toBe(12345);
});
it('returns undefined when installation ID param is empty', async () => {
process.env.PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME = '';
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64],
]),
);
const result = await getStoredInstallationId(0);
expect(result).toBeUndefined();
});
it('returns undefined when env var is not set', async () => {
delete process.env.PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME;
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64],
]),
);
const result = await getStoredInstallationId(0);
expect(result).toBeUndefined();
});
it('returns undefined for out-of-bounds appIndex', async () => {
process.env.PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME = '';
mockedGetParameters.mockResolvedValueOnce(
new Map([
[PARAMETER_GITHUB_APP_ID_NAME, GITHUB_APP_ID],
[PARAMETER_GITHUB_APP_KEY_BASE64_NAME, b64],
]),
);
const result = await getStoredInstallationId(99);
expect(result).toBeUndefined();
});
it('loads installation IDs for multi-app setup', async () => {
const app1IdParam = `/actions-runner/${ENVIRONMENT}/github_app_id`;
const app2IdParam = `/actions-runner/${ENVIRONMENT}/additional_github_app_0_id`;
const app1KeyParam = `/actions-runner/${ENVIRONMENT}/github_app_key_base64`;
const app2KeyParam = `/actions-runner/${ENVIRONMENT}/additional_github_app_0_key_base64`;
const app2InstallParam = `/actions-runner/${ENVIRONMENT}/additional_github_app_0_installation_id`;
process.env.PARAMETER_GITHUB_APP_ID_NAME = `${app1IdParam}:${app2IdParam}`;
process.env.PARAMETER_GITHUB_APP_KEY_BASE64_NAME = `${app1KeyParam}:${app2KeyParam}`;
process.env.PARAMETER_GITHUB_APP_INSTALLATION_ID_NAME = `:${app2InstallParam}`;
mockedGetParameters.mockResolvedValueOnce(
new Map([
[app1IdParam, '1'],
[app1KeyParam, b64],
[app2IdParam, '2'],
[app2KeyParam, b64],
[app2InstallParam, '67890'],
]),
);
// Primary app (index 0) has no stored installation ID
const result0 = await getStoredInstallationId(0);
expect(result0).toBeUndefined();
// Additional app (index 1) has stored installation ID
const result1 = await getStoredInstallationId(1);
expect(result1).toBe(67890);
});
});