-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathaccess-token-manager.ts
More file actions
1130 lines (1018 loc) · 42.5 KB
/
access-token-manager.ts
File metadata and controls
1130 lines (1018 loc) · 42.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {Octokit as OctokitCore} from '@octokit/core';
import {paginateRest} from "@octokit/plugin-paginate-rest";
import {restEndpointMethods} from "@octokit/plugin-rest-endpoint-methods";
import {retry as retryPlugin} from '@octokit/plugin-retry';
import {z} from 'zod';
import type {components} from '@octokit/openapi-types';
import {createAppAuth} from '@octokit/auth-app';
import limit from 'p-limit';
import {formatZodIssue, YamlTransformer} from './common/zod-utils.js';
import {
_throw,
ensureHasEntries,
escapeRegexp,
filterObjectEntries,
findFirstNotNull,
hasEntries,
indent,
isRecord,
mapObjectEntries,
resultOf,
unique,
} from './common/common-utils.js';
import {
aggregatePermissions,
GitHubActionsJwtPayload,
GitHubAppPermissions,
GitHubAppPermissionsSchema,
GitHubAppRepositoryPermissions,
GitHubAppRepositoryPermissionsSchema,
GitHubRepositorySchema,
normalizePermissionScopes,
parseOIDCSubject,
parseRepository,
validatePermissions,
verifyPermissions,
} from './common/github-utils.js';
import {Status} from './common/http-utils.js';
import {logger} from './logger.js';
import {RestEndpointMethodTypes} from '@octokit/rest';
const Octokit = OctokitCore
.plugin(restEndpointMethods, paginateRest, retryPlugin);
const ACCESS_POLICY_MAX_SIZE = 100 * 1024; // 100kb
const GITHUB_API_CONCURRENCY_LIMIT = limit(8);
// BE AWARE to always use NOT_AUTHORIZED_MESSAGE if no permissions are granted to caller identity.
// otherwise, unintended leaks of repository existence could happen.
const NOT_AUTHORIZED_MESSAGE = 'Not authorized';
/**
* GitHub Access Manager
* @param options - options
* @return access token manager
*/
export async function accessTokenManager(options: {
githubAppAuth: { appId: string, privateKey: string, },
accessPolicyLocation: {
owner: { paths: string[], repo: string },
repo: { paths: string[] }
}
}) {
logger.debug({appId: options.githubAppAuth.appId}, 'GitHub app');
const GITHUB_APP_CLIENT = new Octokit({
authStrategy: createAppAuth,
auth: options.githubAppAuth,
});
const GITHUB_APP = await GITHUB_APP_CLIENT.rest.apps.getAuthenticated()
.then((res) => res.data ?? _throw(new Error('GitHub app not found')));
/**
* Creates a GitHub Actions Access Token
* @param callerIdentity - caller identity
* @param tokenRequest - token request
* @return access token
*/
async function createAccessToken(callerIdentity: GitHubActionsJwtPayload, tokenRequest: GitHubAccessTokenRequest) {
const effectiveCallerIdentitySubjects = getEffectiveCallerIdentitySubjects(callerIdentity);
normalizeTokenRequest(tokenRequest, callerIdentity);
// grant requested permissions explicitly to prevent accidental permission escalation
const grantedTokenPermissions: Record<string, string> = {};
const pendingTokenPermissions: Record<string, string> = {...tokenRequest.permissions};
// --- get target app installation ---------------------------------------------------------------------------------
const appInstallation = await getAppInstallation(GITHUB_APP_CLIENT, {
owner: tokenRequest.owner,
});
// === verify target app installation ==============================================================================
{
if (!appInstallation) {
logger.info({owner: tokenRequest.owner},
`'${GITHUB_APP.name}' has not been installed`);
throw new GitHubAccessTokenError([{
owner: tokenRequest.owner,
// BE AWARE to prevent leaking owner existence
issues: callerIdentity.repository_owner === tokenRequest.owner ?
[`'${GITHUB_APP.name}' has not been installed. Install from ${GITHUB_APP.html_url}`] :
[NOT_AUTHORIZED_MESSAGE],
}], effectiveCallerIdentitySubjects);
}
logger.debug({appInstallation}, 'App installation');
const accessPolicyPaths = [
...options.accessPolicyLocation.owner.paths,
...options.accessPolicyLocation.repo.paths,
];
if (!accessPolicyPaths.every((path) =>
appInstallation.single_file_paths?.includes(path) || appInstallation.single_file_name === path)) {
logger.info({owner: tokenRequest.owner, required: accessPolicyPaths, actual: appInstallation.single_file_paths},
`'${GITHUB_APP.name}' is not authorized to read all access policy file(s) by 'single_file' permission`);
throw new GitHubAccessTokenError([{
owner: tokenRequest.owner,
// BE AWARE to prevent leaking owner existence
issues: callerIdentity.repository_owner === tokenRequest.owner ?
[`'${GITHUB_APP.name}' is not authorized to read all access policy file(s) by 'single_file' permission`] :
[NOT_AUTHORIZED_MESSAGE],
}], effectiveCallerIdentitySubjects);
}
}
// === verify against target app installation permissions ==========================================================
{
const requestedAppInstallationPermissions = verifyPermissions({
granted: normalizePermissionScopes(appInstallation.permissions),
requested: tokenRequest.permissions,
});
if (hasEntries(requestedAppInstallationPermissions.pending)) {
logger.info({owner: tokenRequest.owner, denied: requestedAppInstallationPermissions.pending},
`App installation is not authorized`);
throw new GitHubAccessTokenError([{
owner: tokenRequest.owner,
// BE AWARE to prevent leaking owner existence
issues: callerIdentity.repository_owner === tokenRequest.owner ?
Object.entries(requestedAppInstallationPermissions.pending)
.map(([scope, permission]) => ({
scope, permission,
message: `'${GITHUB_APP.name}' installation not authorized`,
})) :
[NOT_AUTHORIZED_MESSAGE],
}], effectiveCallerIdentitySubjects);
}
}
const appInstallationClient = await createOctokit(GITHUB_APP_CLIENT, appInstallation, {
// single_file to read access policy files
permissions: {single_file: 'read', contents: 'read'},
});
// === verify against owner policy =================================================================================
{
// --- load owner access policy ----------------------------------------------------------------------------------
const accessPolicy = await getOwnerAccessPolicy(appInstallationClient, {
owner: tokenRequest.owner,
repo: options.accessPolicyLocation.owner.repo,
paths: options.accessPolicyLocation.owner.paths,
strict: false, // ignore invalid access policy entries
}).catch((error) => {
if (error instanceof GithubAccessPolicyError) {
logger.info({owner: tokenRequest.owner, issues: error.issues},
`Owner access policy - ${error.message}`);
throw new GitHubAccessTokenError([{
owner: tokenRequest.owner,
// BE AWARE to prevent leaking owner existence
issues: callerIdentity.repository === `${tokenRequest.owner}/${options.accessPolicyLocation.owner.repo}` ?
[formatAccessPolicyError(error)] :
tokenRequest.owner === callerIdentity.repository_owner ?
[error.message] :
[NOT_AUTHORIZED_MESSAGE],
}], effectiveCallerIdentitySubjects);
}
throw error;
});
logger.debug({owner: tokenRequest.owner, ownerAccessPolicy: accessPolicy}, 'Owner access policy');
// if allowed-subjects is not defined, allow any subjects from the policy owner
const allowedSubjects = accessPolicy['allowed-subjects'] ??
[`repo:${tokenRequest.owner}/*:**`]; // e.g., ['repo:qoomon/*:**' ]
if (!matchSubject(allowedSubjects, effectiveCallerIdentitySubjects)) {
logger.info({owner: tokenRequest.owner},
'OIDC token subject is not allowed by owner access policy');
throw new GitHubAccessTokenError([{
owner: tokenRequest.owner,
// BE AWARE to prevent leaking owner existence
issues: callerIdentity.repository_owner === tokenRequest.owner ?
['OIDC token subject is not allowed by owner access policy'] :
[NOT_AUTHORIZED_MESSAGE],
}], effectiveCallerIdentitySubjects);
}
const grantedPermissions = evaluateGrantedPermissions({
statements: accessPolicy.statements,
callerIdentitySubjects: effectiveCallerIdentitySubjects,
});
const verifiedPermissions = verifyPermissions({
granted: grantedPermissions,
requested: pendingTokenPermissions,
});
// --- grant owner permissions
Object.entries(verifiedPermissions.granted).forEach(([scope, permission]) => {
grantedTokenPermissions[scope] = permission;
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete pendingTokenPermissions[scope];
});
// --- ensure owner access policy has granted all requested owner permissions
const pendingOwnerPermissions = filterValidPermissions('!repo', pendingTokenPermissions);
if (hasEntries(pendingOwnerPermissions)) {
// --- reject all pending owner permissions
logger.info({owner: tokenRequest.owner, denied: pendingOwnerPermissions},
'Owner access policy - permission(s) not granted');
throw new GitHubAccessTokenError([{
owner: tokenRequest.owner,
issues: Object.entries(pendingOwnerPermissions)
.map(([scope, permission]) => ({
scope, permission: String(permission),
message: callerIdentity.repository_owner === tokenRequest.owner ?
'Not allowed by owner access policy' :
NOT_AUTHORIZED_MESSAGE,
})),
}], effectiveCallerIdentitySubjects);
}
if (hasEntries(pendingTokenPermissions)) {
if (tokenRequest.repositories === 'ALL') {
// --- ensure owner access policy has granted all requested repository permissions
// --- reject all pending permissions
logger.info({owner: tokenRequest.owner, denied: pendingTokenPermissions},
'Owner access policy - permission(s) not granted');
throw new GitHubAccessTokenError([{
owner: tokenRequest.owner,
issues: Object.entries(pendingTokenPermissions)
.map(([scope, permission]) => ({
scope, permission: String(permission),
message: callerIdentity.repository_owner === tokenRequest.owner ?
'Not allowed by owner access policy' :
NOT_AUTHORIZED_MESSAGE,
})),
}], effectiveCallerIdentitySubjects);
} else {
// --- ensure owner access policy explicitly allows all pending repository permissions
const forbiddenRepositoryPermissions = verifyPermissions({
granted: accessPolicy['allowed-repository-permissions'],
requested: pendingTokenPermissions,
}).pending;
if (hasEntries(forbiddenRepositoryPermissions)) {
// --- reject all repository permissions that are not allowed by owner access policy
logger.info({owner: tokenRequest.owner, denied: forbiddenRepositoryPermissions},
'Owner access policy - permission(s) not allowed');
throw new GitHubAccessTokenError([{
owner: tokenRequest.owner,
issues: Object.entries(forbiddenRepositoryPermissions)
.map(([scope, permission]) => ({
scope, permission,
message: callerIdentity.repository_owner === tokenRequest.owner ?
'Not allowed by owner access policy' :
NOT_AUTHORIZED_MESSAGE,
})),
}], effectiveCallerIdentitySubjects);
}
}
}
}
// === verify against repository policies ==========================================================================
if (hasEntries(pendingTokenPermissions)) {
if (hasEntries(validatePermissions(pendingTokenPermissions, 'repo').invalid)) {
throw new Error('SAFEGUARD Error - ' +
'Non repository permissions should have been handled within owner access policy section');
}
if (tokenRequest.repositories === 'ALL') {
throw new Error('SAFEGUARD Error - ' +
`'ALL' repositories scope should have been handled within owner access policy section`);
}
const repositoryVerifyResults = await Promise.all(
tokenRequest.repositories.map((repo) => GITHUB_API_CONCURRENCY_LIMIT(async () => {
const result = {
owner: tokenRequest.owner,
repo,
issues: [] as GitHubAccessTokenErrorIssue[],
granted: {} as GitHubAppRepositoryPermissions,
};
const accessPolicyResult = await resultOf(getRepoAccessPolicy(appInstallationClient, {
owner: tokenRequest.owner, repo,
paths: options.accessPolicyLocation.repo.paths,
strict: false, // ignore invalid access policy entries
}));
if (!accessPolicyResult.success) {
const error = accessPolicyResult.error;
if (error instanceof GithubAccessPolicyError) {
logger.info({owner: tokenRequest.owner, repo, issues: error.issues},
`Repository access policy - ${error.message}`);
if (callerIdentity.repository_owner === tokenRequest.owner) {
result.issues.push(formatAccessPolicyError(error))
} else {
// BE AWARE to prevent leaking owner existence
result.issues.push(NOT_AUTHORIZED_MESSAGE)
}
return result;
}
throw error;
}
const repoAccessPolicy = accessPolicyResult.value;
logger.debug({owner: tokenRequest.owner, repo, repoAccessPolicy},
'Repository access policy');
const grantedPermissions = evaluateGrantedPermissions({
statements: repoAccessPolicy.statements,
callerIdentitySubjects: effectiveCallerIdentitySubjects,
});
if (!hasEntries(grantedPermissions)) {
logger.info({owner: tokenRequest.owner, repo},
'Repository access policy - no permissions granted');
// BE AWARE to prevent leaking owner existence
result.issues.push(NOT_AUTHORIZED_MESSAGE);
return result;
}
const verifiedPermissions = verifyPermissions({
granted: grantedPermissions,
requested: pendingTokenPermissions,
});
// --- deny permissions
Object.entries(verifiedPermissions.pending).forEach(([scope, permission]) => {
result.issues.push({
scope, permission,
message: NOT_AUTHORIZED_MESSAGE,
});
});
// --- grant permissions
result.granted = verifiedPermissions.granted;
return result;
})));
// --- ensure no pending permissions for any target repository
const pendingRepositoryPermissions = repositoryVerifyResults
.map((it) => verifyPermissions({
granted: it.granted,
requested: pendingTokenPermissions,
}).pending)
if (pendingRepositoryPermissions.some(hasEntries)) {
throw new GitHubAccessTokenError(repositoryVerifyResults, effectiveCallerIdentitySubjects);
}
const grantedPermissions = aggregatePermissions(
repositoryVerifyResults.map((it) => it.granted));
// --- grant repository permission only if all repositories have granted the specific permission
for (const [scope, permission] of Object.entries(grantedPermissions)) {
grantedTokenPermissions[scope] = permission;
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete pendingTokenPermissions[scope];
}
}
// === create requested access token ===============================================================================
if (hasEntries(pendingTokenPermissions)) {
throw new Error('SAFEGUARD Error - Unexpected pending permissions');
}
if (!arePermissionsEqual(tokenRequest.permissions, grantedTokenPermissions)) {
throw new Error('SAFEGUARD Error - Unexpected mismatch between requested and granted permissions');
}
const accessToken = await createInstallationAccessToken(GITHUB_APP_CLIENT, appInstallation, {
// BE AWARE that an empty object will result in a token with all app installation permissions
permissions: ensureHasEntries(grantedTokenPermissions),
// BE AWARE that an empty array will result in a token with access to all app installation repositories
repositories: tokenRequest.repositories === 'ALL' ? undefined : ensureHasEntries(tokenRequest.repositories),
});
return {
owner: appInstallation.account?.name ?? tokenRequest.owner,
...accessToken,
};
}
return {
createAccessToken,
};
}
/**
* Normalize access token request body
* @param tokenRequest - access token request body
* @param callerIdentity - caller identity
* @return normalized access token request body
*/
function normalizeTokenRequest(
tokenRequest: GitHubAccessTokenRequest,
callerIdentity: GitHubActionsJwtPayload,
): asserts tokenRequest is GitHubAccessTokenRequest & { owner: string } {
if (!hasEntries(tokenRequest.permissions)) {
throw new GitHubAccessTokenError([
'Invalid token request - permissions must have at least one entry',
]);
}
if (tokenRequest.repositories === 'ALL') {
if (!tokenRequest.owner) {
tokenRequest.owner = callerIdentity.repository_owner
}
} else {
if (tokenRequest.owner && !hasEntries(tokenRequest.repositories)) {
throw new GitHubAccessTokenError([
'Invalid token request - repositories must have at least one entry if owner is specified explicitly',
]);
}
if (!hasEntries(tokenRequest.repositories)) {
tokenRequest.repositories.push(callerIdentity.repository);
}
const repositories = tokenRequest.repositories
.map((repository) => parseRepository(
repository,
tokenRequest.owner ?? callerIdentity.repository_owner,
));
const repositoriesOwnerSet = new Set<string>();
if (tokenRequest.owner) {
repositoriesOwnerSet.add(tokenRequest.owner);
}
const repositoriesNameSet = new Set<string>();
for (const repository of repositories) {
repositoriesOwnerSet.add(repository.owner);
repositoriesNameSet.add(repository.repo);
}
if (repositoriesOwnerSet.size > 1) {
if (tokenRequest.owner) {
throw new GitHubAccessTokenError([
`Invalid token request - All repositories owners must match the specified owner ${tokenRequest.owner}`,
]);
} else {
throw new GitHubAccessTokenError([
'Invalid token request - All repositories must have one common owner',
]);
}
}
const repositoriesOwner = repositoriesOwnerSet.keys().next().value;
if (!tokenRequest.owner) {
tokenRequest.owner = repositoriesOwner;
}
// replace repositories with their names only
tokenRequest.repositories = Array.from(repositoriesNameSet);
}
}
// --- Access Manager Functions --------------------------------------------------------------------------------------
/**
* Get owner access policy
* @param client - GitHub client for target repository
* @param owner - repository owner
* @param repo - repository name
* @param path - file path
* @param strict - throw error on invalid access policy
* @return access policy
*/
async function getOwnerAccessPolicy(client: Octokit, {
owner, repo, paths, strict,
}: {
owner: string,
repo: string,
paths: string[],
strict: boolean,
}): Promise<Omit<GitHubOwnerAccessPolicy, 'origin'>> {
const policy = await getAccessPolicy(client, {
owner, repo, paths,
schema: GitHubOwnerAccessPolicySchema,
preprocessor: (value) => {
value = normalizeAccessPolicyEntries(value);
if (!strict) {
value = filterValidAccessPolicyEntries(value);
}
return value;
},
});
policy.statements?.forEach((statement) => {
resolveAccessPolicyStatementSubjects(statement, {owner, repo});
});
return policy;
function normalizeAccessPolicyEntries(policy: unknown) {
if (isRecord(policy)) {
if (isRecord(policy['allowed-repository-permissions'])) {
policy['allowed-repository-permissions'] = normalizePermissionScopes(policy['allowed-repository-permissions']);
}
if (Array.isArray(policy.statements)) {
policy.statements = policy.statements.map((statement: unknown) => {
if (isRecord(statement) && isRecord(statement.permissions)) {
statement.permissions = normalizePermissionScopes(statement.permissions);
}
return statement;
});
}
}
return policy;
}
function filterValidAccessPolicyEntries(policy: unknown) {
if (isRecord(policy)) {
if (Array.isArray(policy['allowed-subjects'])) {
policy['allowed-subjects'] = filterValidSubjects(
policy['allowed-subjects']);
}
if (isRecord(policy['allowed-repository-permissions'])) {
policy['allowed-repository-permissions'] = filterValidPermissions(
'repo', policy['allowed-repository-permissions']);
}
if (Array.isArray(policy.statements)) {
policy.statements = filterValidStatements(
policy.statements, 'owner');
}
}
return policy;
}
}
/**
* Get repository access policy
* @param client - GitHub client for target repository
* @param owner - repository owner
* @param repo - repository name
* @param path - file path
* @param strict - throw error on invalid access policy
* @return access policy
*/
async function getRepoAccessPolicy(client: Octokit, {
owner, repo, paths, strict,
}: {
owner: string,
repo: string,
paths: string[],
strict: boolean,
}): Promise<Omit<GitHubRepositoryAccessPolicy, 'origin'>> {
const policy = await getAccessPolicy(client, {
owner, repo, paths,
schema: GitHubRepositoryAccessPolicySchema,
preprocessor: (value) => {
value = normalizeAccessPolicyEntries(value);
if (!strict) {
value = filterValidAccessPolicyEntries(value);
}
return value;
},
});
policy.statements?.forEach((statement) => {
resolveAccessPolicyStatementSubjects(statement, {owner, repo});
});
return policy;
function normalizeAccessPolicyEntries(policy: unknown) {
if (isRecord(policy) && Array.isArray(policy.statements)) {
policy.statements = policy.statements.map((statement: unknown) => {
if (isRecord(statement) && isRecord(statement.permissions)) {
statement.permissions = normalizePermissionScopes(statement.permissions);
}
return statement;
});
}
return policy;
}
function filterValidAccessPolicyEntries(policy: unknown) {
if (isRecord(policy) && Array.isArray(policy.statements)) {
policy.statements = filterValidStatements(policy.statements, 'repo');
}
return policy;
}
}
/**
* Get access policy
* @param client - GitHub client for target repository
* @param owner - repository owner
* @param repo - repository name
* @param path - file path
* @param schema - access policy schema
* @param preprocessor - preprocessor function to transform policy object
* @return access policy
*/
async function getAccessPolicy<T extends typeof GitHubAccessPolicySchema>(client: Octokit, {
owner, repo, paths, schema, preprocessor,
}: {
owner: string,
repo: string,
paths: string[],
schema: T,
preprocessor: (value: unknown) => unknown,
}): Promise<z.infer<T>> {
const policyValue = await findFirstNotNull(paths, async (path) => {
return getRepositoryFileContent(client, {owner, repo, path, maxSize: ACCESS_POLICY_MAX_SIZE})
.catch((error) => {
logger.error({owner, repo, path, error: String(error)}, 'Failed to get access policy file content');
return null;
});
});
if (!policyValue) {
throw new GithubAccessPolicyError(`Access policy not found`);
}
const policyParseResult = YamlTransformer
.transform(preprocessor)
.pipe(schema)
.safeParse(policyValue);
if (policyParseResult.error) {
const issues = policyParseResult.error.issues.map(formatZodIssue);
throw new GithubAccessPolicyError(`Invalid access policy`, issues);
}
const policy = policyParseResult.data;
const expectedPolicyOrigin = `${owner}/${repo}`;
if (policy.origin.toLowerCase() !== expectedPolicyOrigin.toLowerCase()) {
const issues = [`Policy origin '${policy.origin}' does not match repository '${expectedPolicyOrigin}'`];
throw new GithubAccessPolicyError(`Invalid access policy`, issues);
}
return policy;
}
/**
* Filter invalid access policy statements
* @param statements - access policy statements
* @param permissionsType - permission type
* @return valid statements
*/
function filterValidStatements(statements: unknown[], permissionsType: 'owner' | 'repo')
: unknown | GitHubAccessStatement[] {
return statements
.map((statementObject: unknown) => {
if (isRecord(statementObject)) {
// ---- subjects
if ('subjects' in statementObject && Array.isArray(statementObject.subjects)) {
// ignore invalid subjects
statementObject.subjects = filterValidSubjects(statementObject.subjects);
}
// ---- permissions
if ('permissions' in statementObject && isRecord(statementObject.permissions)) {
// ignore invalid permissions
statementObject.permissions = filterValidPermissions(permissionsType, statementObject.permissions);
}
}
return statementObject;
})
.filter((statementObject: unknown) => GitHubAccessStatementSchema.safeParse(statementObject).success);
}
/**
* Filter invalid subjects
* @param subjects - access policy subjects
* @return valid subjects
*/
function filterValidSubjects(subjects: unknown[]): unknown[] {
return subjects.filter((it: unknown) => GitHubSubjectPatternSchema.safeParse(it).success);
}
function filterValidPermissions(scopeType: 'repo',
permissions: Record<string, unknown>)
: GitHubAppRepositoryPermissions
function filterValidPermissions(scopeType: 'owner',
permissions: Record<string, unknown>)
: GitHubAppPermissions
function filterValidPermissions(scopeType: '!owner' | '!repo',
permissions: Record<string, unknown>)
: Record<string, unknown>
function filterValidPermissions(scopeType: 'owner' | '!owner' | 'repo' | '!repo',
permissions: Record<string, unknown>)
: GitHubAppPermissions | GitHubAppRepositoryPermissions
/**
* Filter invalid permissions
* @param scopeType - permission scope type, either 'owner' or 'repo'
* @param permissions - access policy permissions
* @return valid permissions
*/
function filterValidPermissions(
scopeType: "owner" | "!owner" | "repo" | "!repo",
permissions: Record<string, unknown>
) {
const negate = scopeType.startsWith('!');
const _scopeType = scopeType.replace(/^!/, '') as 'owner' | 'repo';
const permissionSchema = _scopeType === 'owner'
? GitHubAppPermissionsSchema
: GitHubAppRepositoryPermissionsSchema;
return filterObjectEntries(
permissions,
([scope, permission]) => negate !== permissionSchema.safeParse({[scope]: permission}).success,
);
}
/**
* Check if access permission objects are equal
* @param permissionsA - one permissions object
* @param permissionsB - another permissions object
* @return true if permissions are equal
*/
function arePermissionsEqual(permissionsA: Record<string, string>, permissionsB: Record<string, string>) {
const permissionsAEntries = Object.entries(permissionsA);
const permissionsBEntries = Object.entries(permissionsB);
return permissionsAEntries.length === permissionsBEntries.length &&
permissionsAEntries.every(([scope, permission]) => permissionsB[scope] === permission);
}
/**
* Resolves access policy statement subjects
* @param statement - access policy statement
* @param owner - policy owner
* @param repo - policy repository
* @return void
*/
function resolveAccessPolicyStatementSubjects(statement: { subjects: string[] }, {owner, repo}: {
owner: string,
repo: string,
}) {
statement.subjects = statement.subjects
.map((it) => resolveAccessPolicyStatementSubject(it, {owner, repo}));
// LEGACY SUPPORT for the artificial subject pattern
const artificialSubjects = getArtificialAccessPolicyStatementSubjects(statement.subjects, {owner, repo});
statement.subjects.push(...artificialSubjects);
}
/**
* LEGACY SUPPORT
* Get artificial access policy statement subjects
* @param subjects - access policy statement subjects
* @param owner - policy owner
* @param repo - policy repository
* @return artificial subjects
*/
function getArtificialAccessPolicyStatementSubjects(subjects: string[], {owner, repo}: {
owner: string,
repo: string,
}) {
const artificialSubjects: string[] = [];
subjects.forEach((it) => {
const subjectRepo = it.match(/(^|:)repo:(?<repo>[^:]+)/)?.groups?.repo ?? `${owner}/${repo}`;
let artificialSubject = it;
// prefix subject with repo claim, if not already prefixed
artificialSubject = artificialSubject.startsWith('repo:') ? artificialSubject :
`repo:${subjectRepo}:${artificialSubject}`;
// prefix (job_)workflow_ref claim value with repo, if not already prefixed
artificialSubject = artificialSubject.replace(
/(?<=^|:)(?<claim>(job_)?workflow_ref):(?<value>[^:]+)/,
(match, ...args) => {
const {claim, value} = args.at(-1);
if (value.startsWith('/')) return `${claim}:${subjectRepo}${value}`;
return match;
},
);
if (artificialSubject !== it) {
artificialSubjects.push(artificialSubject);
}
});
return artificialSubjects;
}
/**
* Normalise access policy statement subject
* @param subject - access policy statement subject
* @param owner - policy owner
* @param repo - policy repository
* @return normalised subject
*/
function resolveAccessPolicyStatementSubject(subject: string, {owner, repo}: {
owner: string,
repo: string
}): string {
// resolve variables
return subject.replaceAll('${origin}', `${owner}/${repo}`);
}
/**
* Evaluate granted permissions for caller identity
* @param accessPolicy - access policy
* @param callerIdentitySubjects - caller identity subjects
* @return granted permissions
*/
function evaluateGrantedPermissions({statements, callerIdentitySubjects}: {
statements: GitHubAccessStatement[],
callerIdentitySubjects: string[],
}): Record<string, string> {
const permissions = statements
.filter(statementSubjectPredicate(callerIdentitySubjects))
.map((it) => it.permissions);
return aggregatePermissions(permissions);
/**
* Create statement subject predicate
* @param subjects - caller identity subjects
* @return true if statement subjects match any of the given subject patterns
*/
function statementSubjectPredicate(subjects: string[]) {
return (statement: GitHubAccessStatement) => subjects
.some((subject) => statement.subjects
.some((subjectPattern) => matchSubject(subjectPattern, subject)));
}
}
/**
* Get effective caller identity subjects
* @param callerIdentity - caller identity
* @return effective caller identity subjects
*/
function getEffectiveCallerIdentitySubjects(callerIdentity: GitHubActionsJwtPayload): string[] {
const subjects = [callerIdentity.sub];
// --- add artificial subjects
// Be Aware to not add artificial subjects for pull requests e.g., 'ref:refs/pull/1/head'
if (callerIdentity.ref.startsWith('refs/heads/') ||
callerIdentity.ref.startsWith('refs/tags/')) {
// repo : ref
// => repo:qoomon/sandbox:ref:refs/heads/main
subjects.push(`repo:${callerIdentity.repository}:ref:${callerIdentity.ref}`);
}
// Be Aware to not add artificial subjects for pull requests e.g., 'workflow_ref:...@refs/pull/1/head'
if (callerIdentity.workflow_ref.split('@')[1]?.startsWith('refs/heads/') ||
callerIdentity.workflow_ref.split('@')[1]?.startsWith('refs/tags/')) {
// repo : workflow_ref
// => repo:qoomon/sandbox:workflow_ref:qoomon/sandbox/.github/workflows/build.yml@refs/heads/main
subjects.push(`repo:${callerIdentity.repository}:workflow_ref:${callerIdentity.workflow_ref}`);
}
// Be Aware to not add artificial subjects for pull requests e.g., 'job_workflow_ref:...@refs/pull/1/head'
if (callerIdentity.job_workflow_ref.split('@')[1]?.startsWith('refs/heads/') ||
callerIdentity.job_workflow_ref.split('@')[1]?.startsWith('refs/tags/')) {
// repo : job_workflow_ref
// => repo:qoomon/sandbox:job_workflow_ref:qoomon/sandbox/.github/workflows/build.yml@refs/heads/main
subjects.push(`repo:${callerIdentity.repository}:job_workflow_ref:${callerIdentity.job_workflow_ref}`);
}
return unique(subjects);
}
/**
* Verify if subject is granted by grantedSubjectPatterns
* @param subjectPattern - subject pattern
* @param subject - subject e.g. 'repo:spongebob/sandbox:ref:refs/heads/main'
* @return true if subject matches any granted subject pattern
*/
function matchSubject(subjectPattern: string | string[], subject: string | string[]): boolean {
if (Array.isArray(subject)) {
return subject.some((subject) => matchSubject(subjectPattern, subject));
}
if (Array.isArray(subjectPattern)) {
return subjectPattern.some((subjectPattern) => matchSubject(subjectPattern, subject));
}
// subject pattern claims must not contain wildcards to prevent granting access accidentally
// repo:foo/bar:* is NOT allowed
// repo:foo/bar:** is allowed
// repo:foo/*:** is allowed
const explicitSubjectPattern = subjectPattern.replace(/:\*\*$/, '')
if (Object.keys(parseOIDCSubject(explicitSubjectPattern)).some((claim) => claim.includes('*'))) {
return false;
}
// grantedSubjectPattern example: repo:qoomon/sandbox:ref:refs/heads/*
// identity.sub example: repo:qoomon/sandbox:ref:refs/heads/main
return regexpOfSubjectPattern(subjectPattern).test(subject);
}
/**
* Create regexp of wildcard subject pattern
* @param subjectPattern - wildcard subject pattern
* @return regexp
*/
function regexpOfSubjectPattern(subjectPattern: string): RegExp {
const regexp = escapeRegexp(subjectPattern)
.replaceAll('\\*\\*', '(?:.*)') // ** matches zero or more characters
.replaceAll('\\*', '(?:[^:]*)') // * matches zero or more characters except ':'
.replaceAll('\\?', '[^:]'); // ? matches one character except ':'
return RegExp(`^${regexp}$`, 'i');
}
/**
* Format access policy error
* @param error - access policy error
* @return formatted error message
*/
function formatAccessPolicyError(error: GithubAccessPolicyError) {
return error.message + (!error.issues?.length ? '' : '\n' +
error.issues.map((issue) => indent(issue, '- ')).join('\n'));
}
// --- GitHub Functions ----------------------------------------------------------------------------------------------
/**
* Get GitHub app installation for a repository or owner
* @param client - GitHub client
* @param owner - app installation owner
* @return installation or null if app is not installed for target
*/
async function getAppInstallation(client: Octokit, {owner}: {
owner: string
}): Promise<GitHubAppInstallation | null> {
return client.rest.apps.getUserInstallation({username: owner})
.then((res) => res.data)
.catch(async (error) => (error.status === Status.NOT_FOUND ? null : _throw(error)));
}
/**
* Create installation access token
* @param client - GitHub client
* @param installation - target installation id
* @param repositories - target repositories
* @param permissions - requested permissions
* @return access token
*/
async function createInstallationAccessToken(client: Octokit, installation: GitHubAppInstallation, {
repositories, permissions,
}: {
repositories?: string[],
permissions: GitHubAppPermissions
}): Promise<GitHubAppInstallationAccessToken> {
// noinspection TypeScriptValidateJSTypes
return client.rest.apps.createInstallationAccessToken({
installation_id: installation.id,
// BE AWARE that an empty object will result in a token with all app installation permissions
permissions: ensureHasEntries(mapObjectEntries(permissions, ([scope, permission]) => [
scope.replaceAll('-', '_'), permission,
])),
repositories,
}).then((res) => res.data);
}
/**
* Create octokit instance for app installation
* @param client - GitHub client
* @param installation - app installation
* @param permissions - requested permissions
* @param repositories - requested repositories
* @return octokit instance
*/
async function createOctokit(client: Octokit, installation: GitHubAppInstallation, {permissions, repositories}: {
permissions: components['schemas']['app-permissions'],
repositories?: string[]
}): Promise<Octokit> {
const installationAccessToken = await createInstallationAccessToken(client, installation, {
permissions,
repositories,
});
return new Octokit({auth: installationAccessToken.token});
}
/**
* Get repository file content
* @param client - GitHub client for target repository
* @param owner - repository owner
* @param repo - repository name
* @param path - file path
* @param maxSize - max file size
* @return file content or null if the file does not exist
*/
async function getRepositoryFileContent(client: Octokit, {
owner, repo, path, maxSize,
}: {
owner: string,
repo: string,
path: string,
maxSize?: number
}): Promise<string | null> {
return client.rest.repos.getContent({owner, repo, path})
.then((res) => {
if ('type' in res.data && res.data.type === 'file') {
if (maxSize !== undefined && res.data.size > maxSize) {
throw new Error(`Expect file size to be less than ${maxSize}b, but was ${res.data.size}b` +
`${owner}/${repo}/${path}`);
}
return Buffer.from(
res.data.content,
'base64',
).toString();
}