-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgithub-identity.mjs
More file actions
2203 lines (2119 loc) · 68.6 KB
/
Copy pathgithub-identity.mjs
File metadata and controls
2203 lines (2119 loc) · 68.6 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 { execFile, spawn } from 'node:child_process'
import { constants } from 'node:fs'
import { access, lstat, readdir, realpath } from 'node:fs/promises'
import { devNull } from 'node:os'
import path from 'node:path'
import { promisify } from 'node:util'
import { fileURLToPath } from 'node:url'
import {
assertIssueNumber,
assertNonEmpty,
paginateGitHubApi,
parseGitHubTarget,
readJson,
sameGitHubLogin,
} from './common.mjs'
import { reconcileActiveJournal } from './active-journal.mjs'
import {
checkpointRecordDigest,
checkpointWorktreeHead,
parseCheckpointRecord,
validateCheckpointRecord,
verifyLatestDurableCheckpoint,
} from './checkpoint-proof.mjs'
import { verifyPublishedEvolveRequest } from './evolve.mjs'
import { loadDurableFinalizationRecords } from './finalization-journal.mjs'
import {
parseReviewPublisherArguments,
reviewPublisherSyntheticGitHubArguments,
} from './review-publication.mjs'
import { readEvents } from './run-store.mjs'
const execFileAsync = promisify(execFile)
const moduleDirectory = path.dirname(fileURLToPath(import.meta.url))
const identityBinDirectory = path.resolve(moduleDirectory, '..', 'identity-bin')
const commandGatePath = path.resolve(moduleDirectory, '..', 'github-command-gate.mjs')
const roleFields = {
automation: {
login: 'automationGitHubLogin',
environmentVariable: 'automationGitHubConfigEnvironmentVariable',
},
reviewer: {
login: 'reviewerGitHubLogin',
environmentVariable: 'reviewerGitHubConfigEnvironmentVariable',
},
}
const historicalValidationCapabilities = new WeakSet()
const inheritedEnvironmentNames = new Set([
'CI',
'COLORTERM',
'FORCE_COLOR',
'HOME',
'LANG',
'LOGNAME',
'NO_COLOR',
'PATH',
'SHELL',
'TEMP',
'TERM',
'TMP',
'TMPDIR',
'USER',
'XDG_RUNTIME_DIR',
])
function safeBaseEnvironment(channel, environment) {
const safe = {}
const dynamicNames = new Set([channel.webhookEnvironmentVariable].filter(Boolean))
for (const [name, value] of Object.entries(environment)) {
if (inheritedEnvironmentNames.has(name) || dynamicNames.has(name) || name.startsWith('LC_')) {
safe[name] = value
}
}
return safe
}
export function resolveGitHubRoleEnvironment({ channel, role, environment = process.env }) {
const fields = roleFields[role]
if (!fields) throw new Error('GitHub role must be automation or reviewer')
const expectedLogin = assertNonEmpty(channel[fields.login], `channel.${fields.login}`)
if (sameGitHubLogin(expectedLogin, channel.ownerGitHubLogin)) {
throw new Error(`GitHub ${role} identity must differ from the owner`)
}
const variableName = assertNonEmpty(
channel[fields.environmentVariable],
`channel.${fields.environmentVariable}`,
)
if (!/^[A-Z][A-Z0-9_]*$/.test(variableName)) {
throw new Error(`channel.${fields.environmentVariable} must name an environment variable`)
}
const configDirectory = assertNonEmpty(environment[variableName], variableName)
if (!path.isAbsolute(configDirectory)) {
throw new Error(`${variableName} must contain an absolute directory path`)
}
const repositoryUrl = canonicalRepositoryUrl(
assertNonEmpty(channel.repository, 'channel.repository'),
)
const routedEnvironment = {
...safeBaseEnvironment(channel, environment),
GH_CONFIG_DIR: configDirectory,
}
Object.assign(routedEnvironment, {
GH_PAGER: 'cat',
GH_PROMPT_DISABLED: '1',
GIT_CONFIG_GLOBAL: devNull,
GIT_CONFIG_NOSYSTEM: '1',
GIT_CONFIG_COUNT: '15',
GIT_CONFIG_KEY_0: 'credential.helper',
GIT_CONFIG_VALUE_0: '',
GIT_CONFIG_KEY_1: 'credential.helper',
GIT_CONFIG_VALUE_1: `!${shellQuote(process.execPath)} ${shellQuote(
commandGatePath,
)} credential`,
GIT_CONFIG_KEY_2: 'core.hooksPath',
GIT_CONFIG_VALUE_2: devNull,
GIT_CONFIG_KEY_3: 'core.fsmonitor',
GIT_CONFIG_VALUE_3: 'false',
GIT_CONFIG_KEY_4: 'protocol.ext.allow',
GIT_CONFIG_VALUE_4: 'never',
GIT_CONFIG_KEY_5: `url.${repositoryUrl}.insteadOf`,
GIT_CONFIG_VALUE_5: repositoryUrl,
GIT_CONFIG_KEY_6: `url.${repositoryUrl}.pushInsteadOf`,
GIT_CONFIG_VALUE_6: repositoryUrl,
GIT_CONFIG_KEY_7: 'http.proxy',
GIT_CONFIG_VALUE_7: '',
GIT_CONFIG_KEY_8: 'http.extraHeader',
GIT_CONFIG_VALUE_8: '',
GIT_CONFIG_KEY_9: 'http.cookieFile',
GIT_CONFIG_VALUE_9: devNull,
GIT_CONFIG_KEY_10: 'http.saveCookies',
GIT_CONFIG_VALUE_10: 'false',
GIT_CONFIG_KEY_11: 'http.sslVerify',
GIT_CONFIG_VALUE_11: 'true',
GIT_CONFIG_KEY_12: 'http.curloptResolve',
GIT_CONFIG_VALUE_12: '',
GIT_CONFIG_KEY_13: 'remote.origin.proxy',
GIT_CONFIG_VALUE_13: '',
GIT_CONFIG_KEY_14: 'http.followRedirects',
GIT_CONFIG_VALUE_14: 'initial',
GIT_PAGER: 'cat',
GIT_TERMINAL_PROMPT: '0',
PAGER: 'cat',
})
return { configDirectory, expectedLogin, routedEnvironment }
}
function containsPath(root, target) {
return target === root || target.startsWith(`${root}${path.sep}`)
}
function repositoryRootForLoop(loopRoot) {
const loopsRoot = path.dirname(loopRoot)
return path.basename(loopsRoot) === 'loops' ? path.dirname(loopsRoot) : path.resolve(loopRoot)
}
async function assertPrivateCredentialTree(root) {
const expectedUid = typeof process.getuid === 'function' ? process.getuid() : null
const visit = async (target) => {
const stats = await lstat(target)
if (stats.isSymbolicLink() || (!stats.isDirectory() && !stats.isFile())) {
throw new Error(`GitHub credential profile contains an unsafe entry: ${target}`)
}
if ((stats.mode & 0o077) !== 0) {
throw new Error(`GitHub credential profile entries must deny group/other access: ${target}`)
}
if (expectedUid !== null && stats.uid !== expectedUid) {
throw new Error(`GitHub credential profile must be owned by the scheduler user: ${target}`)
}
if (stats.isDirectory()) {
for (const entry of await readdir(target)) await visit(path.join(target, entry))
}
}
await visit(root)
}
export async function assertCredentialProfileIsolation({
channel,
configDirectory,
environment = process.env,
requiredUntrustedRoots = [],
}) {
const variableName = assertNonEmpty(
channel.untrustedRootsEnvironmentVariable,
'channel.untrustedRootsEnvironmentVariable',
)
let configuredRoots
try {
configuredRoots = JSON.parse(assertNonEmpty(environment[variableName], variableName))
} catch {
throw new Error(`${variableName} must contain a JSON array of absolute untrusted roots`)
}
if (
!Array.isArray(configuredRoots) ||
configuredRoots.length === 0 ||
configuredRoots.some((root) => typeof root !== 'string' || !path.isAbsolute(root))
) {
throw new Error(`${variableName} must contain a non-empty JSON array of absolute paths`)
}
const lexicalConfigDirectory = path.resolve(configDirectory)
const configuredProfileStats = await lstat(lexicalConfigDirectory)
if (configuredProfileStats.isSymbolicLink() || !configuredProfileStats.isDirectory()) {
throw new Error('GitHub credential profile path must be a real directory, not a symlink')
}
const [canonicalConfigDirectory, canonicalRoots, canonicalRequiredRoots] = await Promise.all([
realpath(lexicalConfigDirectory),
Promise.all(configuredRoots.map((root) => realpath(root))),
Promise.all(requiredUntrustedRoots.map((root) => realpath(root))),
])
for (const requiredRoot of canonicalRequiredRoots) {
if (!canonicalRoots.some((root) => containsPath(root, requiredRoot))) {
throw new Error(`${variableName} must cover the repository and every untrusted agent root`)
}
}
if (canonicalRoots.some((root) => containsPath(root, canonicalConfigDirectory))) {
throw new Error('GitHub credential profiles must be outside every untrusted agent root')
}
await assertPrivateCredentialTree(canonicalConfigDirectory)
return canonicalConfigDirectory
}
function canonicalRepositoryUrl(repository) {
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) {
throw new Error('configured repository must be an owner/name pair')
}
return `https://github.com/${repository}.git`
}
export function hardenedGitArguments(args, { expectedRepository = null } = {}) {
const subcommand = gitSubcommand(args)
const hardened = [...args]
if (['diff', 'show', 'log'].includes(subcommand.name)) {
hardened.splice(subcommand.index + 1, 0, '--no-ext-diff', '--no-textconv')
}
if (!expectedRepository) return hardened
const repositoryUrl = canonicalRepositoryUrl(expectedRepository)
if (subcommand.name === 'push') {
const lease = args[subcommand.index + 1]
const deleteRef = args.at(-1)
const rollback = lease?.match(
/^--force-with-lease=(refs\/heads\/codex\/issue-[1-9][0-9]*):([0-9a-f]{40})$/,
)
if (rollback && sameArguments(args, ['push', lease, 'origin', `:${rollback[1]}`])) {
return ['push', lease, repositoryUrl, deleteRef]
}
const branch = args.at(-1)
return ['push', repositoryUrl, `refs/heads/${branch}:refs/heads/${branch}`]
}
if (subcommand.name === 'fetch') {
const branch = args.at(-1)
return ['fetch', repositoryUrl, `refs/heads/${branch}:refs/remotes/origin/${branch}`]
}
if (subcommand.name === 'ls-remote') {
return ['ls-remote', '--heads', repositoryUrl, 'refs/heads/codex/issue-*']
}
return hardened
}
function sameArguments(actual, expected) {
return (
actual.length === expected.length &&
actual.every((argument, index) => argument === expected[index])
)
}
function gitSubcommand(args) {
let index = 0
while (index < args.length && args[index].startsWith('-')) {
const argument = args[index]
if (['-C', '--git-dir', '--work-tree', '--namespace'].includes(argument)) {
index += 2
continue
}
if (
['--no-pager', '--paginate', '--literal-pathspecs', '--no-optional-locks'].includes(
argument,
) ||
['--git-dir=', '--work-tree=', '--namespace='].some((prefix) => argument.startsWith(prefix))
) {
index += 1
continue
}
return { index, name: null }
}
return { index, name: args[index] ?? null }
}
function authorizedPushBranches(authorization) {
return new Set([authorization?.issue?.branch, authorization?.evolve?.branch].filter(Boolean))
}
export function assertGitCommandPolicy(role, args, { authorization = null } = {}) {
const subcommand = gitSubcommand(args)
const restoreCleanlinessProbe =
role === 'automation' &&
(sameArguments(args, ['ls-files', '-v', '-z']) ||
sameArguments(args, [
'-c',
'core.fileMode=true',
'diff',
'--quiet',
'--no-ext-diff',
'--no-textconv',
'HEAD',
'--',
]))
if (restoreCleanlinessProbe) return
if (subcommand.name === 'push') {
if (role === 'reviewer') throw new Error('reviewer identity cannot run git push')
const claimBranch = authorization?.issue?.branch
const claimRollback =
authorization?.rootIntent === 'start' &&
authorization?.issue?.status === 'starting' &&
sameArguments(args, [
'push',
`--force-with-lease=refs/heads/${claimBranch}:${authorization?.issue?.baseSha}`,
'origin',
`:refs/heads/${claimBranch}`,
])
if (claimRollback) return
const branch = args.at(-1)
const isLoopBranch = authorizedPushBranches(authorization).has(branch)
const isAllowedShape =
subcommand.index === 0 &&
isLoopBranch &&
[['push', 'origin', branch]].some((expected) => sameArguments(args, expected))
if (!isAllowedShape) {
throw new Error('GitHub automation may push only one explicit loop branch')
}
return
}
if (
args.some(
(argument) =>
['--ext-diff', '--textconv', '--exec-path'].includes(argument) ||
['--ext-diff=', '--textconv=', '--exec-path=', '--output='].some((prefix) =>
argument.startsWith(prefix),
) ||
argument === '--output',
)
) {
throw new Error(`git command is outside the authenticated ${role} command tree`)
}
const readOnly = new Set(['rev-parse', 'status', 'merge-base', 'show', 'diff', 'log'])
if (readOnly.has(subcommand.name)) return
if (
subcommand.name === 'branch' &&
args
.slice(subcommand.index + 1)
.every((argument) => ['--show-current', '--list', '-l'].includes(argument))
) {
return
}
if (
subcommand.name === 'config' &&
args.some((argument) =>
['--get', '--get-all', '--get-regexp', '--list', '-l', '--show-origin'].includes(argument),
)
) {
return
}
if (
sameArguments(args.slice(subcommand.index), ['remote', '-v']) ||
sameArguments(args.slice(subcommand.index), ['remote', 'get-url', 'origin'])
) {
return
}
if (
role === 'automation' &&
subcommand.index === 0 &&
sameArguments(args.slice(subcommand.index), [
'ls-remote',
'--heads',
'origin',
'refs/heads/codex/issue-*',
])
) {
return
}
if (
role === 'automation' &&
subcommand.index === 0 &&
subcommand.name === 'fetch' &&
authorizedPushBranches(authorization).has(args.at(-1)) &&
sameArguments(args.slice(subcommand.index), ['fetch', 'origin', args.at(-1)])
) {
return
}
if (
role === 'automation' &&
subcommand.index === 0 &&
sameArguments(args.slice(subcommand.index), ['fetch', 'origin', 'dev'])
) {
return
}
throw new Error(`git command is outside the authenticated ${role} command tree`)
}
function commandAfterGroup(args, groupIndex) {
let index = groupIndex + 1
while (index < args.length) {
const argument = args[index]
if (['--repo', '-R', '--hostname'].includes(argument)) {
index += 2
continue
}
if (argument.startsWith('-')) {
return { index: -1, name: null }
}
return { index, name: argument }
}
return { index: -1, name: null }
}
function githubGroup(args) {
const groups = new Set(['api', 'issue', 'pr', 'run', 'repo'])
let index = 0
while (index < args.length) {
const argument = args[index]
if (['--repo', '-R', '--hostname'].includes(argument)) {
if (!args[index + 1]) return { index: -1, name: null }
index += 2
continue
}
if (['--repo=', '--hostname='].some((prefix) => argument.startsWith(prefix))) {
index += 1
continue
}
if (argument.startsWith('-') || !groups.has(argument)) {
return { index: -1, name: null }
}
return { index, name: argument }
}
return { index: -1, name: null }
}
function githubApiRequest(apiArguments) {
const optionsWithValue = new Set([
'--method',
'-X',
'-f',
'-F',
'--field',
'--raw-field',
'--input',
'--preview',
'--hostname',
'--jq',
'-q',
'--template',
'-t',
'--cache',
'--header',
'-H',
])
const bodyOptions = new Set(['-f', '-F', '--field', '--raw-field', '--input'])
const booleanOptions = new Set(['--paginate', '--slurp', '--verbose', '--silent', '--include'])
let explicitMethod = null
let endpoint = null
let hasRequestBody = false
let usesFileExpansion = false
let usesInput = false
let valid = true
const fields = []
for (let index = 0; index < apiArguments.length; index += 1) {
const argument = apiArguments[index]
if (optionsWithValue.has(argument)) {
const value = apiArguments[index + 1]
if (value === undefined) {
valid = false
break
}
if (argument === '--method' || argument === '-X') explicitMethod = value
if (argument === '--input') usesInput = true
if (bodyOptions.has(argument)) {
hasRequestBody = true
fields.push(value)
if (
['-F', '--field'].includes(argument) &&
(value.startsWith('@') || value.slice(value.indexOf('=') + 1).startsWith('@'))
) {
usesFileExpansion = true
}
}
index += 1
continue
}
const longOption = [...optionsWithValue].find(
(name) => name.startsWith('--') && argument.startsWith(`${name}=`),
)
if (longOption) {
const value = argument.slice(longOption.length + 1)
if (!value) {
valid = false
break
}
if (longOption === '--method') explicitMethod = value
if (longOption === '--input') usesInput = true
if (bodyOptions.has(longOption)) {
hasRequestBody = true
fields.push(value)
if (
longOption === '--field' &&
(value.startsWith('@') || value.slice(value.indexOf('=') + 1).startsWith('@'))
) {
usesFileExpansion = true
}
}
continue
}
if (/^-X[A-Za-z]+$/.test(argument)) {
explicitMethod = argument.slice(2)
continue
}
if (/^-[fF].+/.test(argument)) {
hasRequestBody = true
const value = argument.slice(2)
fields.push(value)
if (
argument.startsWith('-F') &&
(value.startsWith('@') || value.slice(value.indexOf('=') + 1).startsWith('@'))
) {
usesFileExpansion = true
}
continue
}
if (
booleanOptions.has(argument) ||
[...booleanOptions].some((name) => argument.startsWith(`${name}=`))
) {
continue
}
if (argument.startsWith('-') || endpoint !== null) {
valid = false
break
}
endpoint = argument
}
const method = (explicitMethod ?? (hasRequestBody ? 'POST' : 'GET')).toUpperCase()
return {
endpoint: valid ? (endpoint?.replace(/^\//, '').split('?')[0] ?? null) : null,
method,
mutating: !valid || method !== 'GET',
valid,
fields,
usesFileExpansion,
usesInput,
}
}
function parseOptions(args, startIndex, { valueOptions = {}, booleanOptions = {} } = {}) {
const values = new Map()
const booleans = new Map()
const positional = []
const valueAliases = new Map(Object.entries(valueOptions))
const booleanAliases = new Map(Object.entries(booleanOptions))
let valid = true
for (let index = startIndex; index < args.length; index += 1) {
const argument = args[index]
if (valueAliases.has(argument)) {
const value = args[index + 1]
if (value === undefined) {
valid = false
break
}
const name = valueAliases.get(argument)
values.set(name, [...(values.get(name) ?? []), value])
index += 1
continue
}
const longValueOption = [...valueAliases].find(
([option]) => option.startsWith('--') && argument.startsWith(`${option}=`),
)
if (longValueOption) {
const value = argument.slice(longValueOption[0].length + 1)
if (!value) {
valid = false
break
}
const name = longValueOption[1]
values.set(name, [...(values.get(name) ?? []), value])
continue
}
if (booleanAliases.has(argument)) {
booleans.set(booleanAliases.get(argument), true)
continue
}
const longBooleanOption = [...booleanAliases].find(
([option]) => option.startsWith('--') && argument.startsWith(`${option}=`),
)
if (longBooleanOption) {
const value = argument.slice(longBooleanOption[0].length + 1)
if (!['true', 'false'].includes(value)) {
valid = false
break
}
booleans.set(longBooleanOption[1], value === 'true')
continue
}
if (argument.startsWith('-')) {
valid = false
break
}
positional.push(argument)
}
return { booleans, positional, valid, values }
}
function exactlyOne(values, name) {
const candidates = values.get(name) ?? []
return candidates.length === 1 ? candidates[0] : null
}
function pullRequestTargetMatches(target, authorization, expectedRepository, repositoryOption) {
const expectedNumber = authorization?.issue?.prNumber
if (!Number.isInteger(expectedNumber)) return false
if (/^\d+$/.test(target)) {
return (
Number(target) === expectedNumber && repositoryInScope(repositoryOption, expectedRepository)
)
}
const parsed = parseGitHubTarget(target)
return (
parsed?.kind === 'pull' &&
parsed.number === expectedNumber &&
repositoryInScope(`${parsed.owner}/${parsed.repo}`, expectedRepository) &&
(repositoryOption === null || repositoryInScope(repositoryOption, expectedRepository))
)
}
const repositoryValueOptions = {
'--repo': 'repository',
'-R': 'repository',
}
function parseReviewPublication(body, authorization, { requireCurrentHead = true } = {}) {
if (typeof body !== 'string') return null
const matches = [
...body.matchAll(
/<!-- issue-dev-loop:([^:]+):review-cycle:([1-9][0-9]*):round:([12]):head:([0-9a-f]{40}) -->/gi,
),
]
if (
matches.length !== 1 ||
matches[0][1] !== authorization?.issue?.runId ||
(requireCurrentHead &&
matches[0][4].toLowerCase() !== authorization?.issue?.headSha?.toLowerCase())
) {
return null
}
return {
kind: 'cycle',
cycle: Number(matches[0][2]),
round: Number(matches[0][3]),
headSha: matches[0][4].toLowerCase(),
}
}
function parseAdjudicationPublication(body, authorization) {
if (typeof body !== 'string') return null
const matches = [
...body.matchAll(
/<!-- issue-dev-loop:([^:]+):(RVW-[1-9][0-9]*-[12]-[1-9][0-9]*):adjudication:(REJECT_FINDING):head:([0-9a-f]{40}) -->/gi,
),
]
if (
matches.length !== 1 ||
matches[0][1] !== authorization?.issue?.runId ||
matches[0][4].toLowerCase() !== authorization?.issue?.headSha?.toLowerCase()
) {
return null
}
return {
kind: 'adjudication',
findingId: matches[0][2],
verdict: matches[0][3],
headSha: matches[0][4].toLowerCase(),
marker: matches[0][0],
}
}
function reviewerCommentReview(args, commandIndex, authorization) {
const parsed = parseOptions(args, commandIndex + 1, {
valueOptions: {
...repositoryValueOptions,
'--body': 'body',
'-b': 'body',
},
booleanOptions: { '--comment': 'comment', '-c': 'comment' },
})
const body = exactlyOne(parsed.values, 'body')
const cyclePublication = parseReviewPublication(body, authorization)
const adjudicationPublication = parseAdjudicationPublication(body, authorization)
return {
parsed,
body,
publication:
Boolean(cyclePublication) === Boolean(adjudicationPublication)
? null
: (cyclePublication ?? adjudicationPublication),
}
}
function reviewerCommentReviewAllowed(args, commandIndex, authorization, expectedRepository) {
const { parsed, body, publication } = reviewerCommentReview(args, commandIndex, authorization)
return (
parsed.valid &&
parsed.booleans.get('comment') === true &&
parsed.positional.length === 1 &&
pullRequestTargetMatches(
parsed.positional[0],
authorization,
expectedRepository,
exactlyOne(parsed.values, 'repository'),
) &&
Boolean(body) &&
Boolean(publication)
)
}
function pullRequestCreateAllowed(args, commandIndex, authorization, expectedRepository) {
const parsed = parseOptions(args, commandIndex + 1, {
valueOptions: {
...repositoryValueOptions,
'--base': 'base',
'-B': 'base',
'--head': 'head',
'-H': 'head',
'--title': 'title',
'-t': 'title',
'--body': 'body',
'-b': 'body',
},
booleanOptions: { '--draft': 'draft', '-d': 'draft' },
})
if (
!parsed.valid ||
parsed.positional.length !== 0 ||
parsed.booleans.get('draft') !== true ||
!repositoryInScope(exactlyOne(parsed.values, 'repository'), expectedRepository) ||
exactlyOne(parsed.values, 'base') !== 'dev' ||
!exactlyOne(parsed.values, 'title') ||
!exactlyOne(parsed.values, 'body')
) {
return false
}
const head = exactlyOne(parsed.values, 'head')
if (head === authorization?.issue?.branch && authorization.issue.prNumber === null) {
return true
}
if (head !== authorization?.evolve?.branch) return false
const body = exactlyOne(parsed.values, 'body')
return body?.includes(`<!-- issue-dev-loop:evolve-request:${authorization.evolve.requestId} -->`)
}
function pullRequestMutationAllowed(kind, args, commandIndex, authorization, expectedRepository) {
const valueOptions =
kind === 'edit'
? {
...repositoryValueOptions,
'--title': 'title',
'-t': 'title',
'--body': 'body',
'-b': 'body',
'--add-reviewer': 'addReviewer',
}
: kind === 'comment'
? {
...repositoryValueOptions,
'--body': 'body',
'-b': 'body',
}
: repositoryValueOptions
const parsed = parseOptions(args, commandIndex + 1, {
valueOptions,
booleanOptions: kind === 'ready' ? { '--undo': 'undo' } : {},
})
if (
!parsed.valid ||
parsed.positional.length !== 1 ||
!pullRequestTargetMatches(
parsed.positional[0],
authorization,
expectedRepository,
exactlyOne(parsed.values, 'repository'),
)
) {
return false
}
if (kind === 'ready') {
return (
parsed.values.size <= 1 && parsed.booleans.size === 1 && parsed.booleans.get('undo') === true
)
}
if (kind === 'comment') {
const body = exactlyOne(parsed.values, 'body')
return Boolean(body) && !reservedAutomationComment(body)
}
const reviewers = (parsed.values.get('addReviewer') ?? []).flatMap((value) =>
value.split(',').map((login) => login.trim()),
)
if (reviewers.some((login) => !sameGitHubLogin(login, authorization?.ownerGitHubLogin))) {
return false
}
const editedFields = [...parsed.values.keys()].filter((name) => name !== 'repository')
return editedFields.length > 0
}
function reservedAutomationComment(body) {
return (
body.includes('**pr_completed**') ||
body.includes('<!-- issue-dev-loop:evolve-completion:') ||
body.includes('<!-- issue-dev-loop:checkpoint:')
)
}
function checkpointPublicationAllowed(body, authorization) {
const markers = [
...body.matchAll(/<!-- issue-dev-loop:checkpoint:([^:]+):sha256:([0-9a-f]{64}) -->/g),
]
if (markers.length !== 1 || markers[0][1] !== authorization?.issue?.runId) {
return false
}
try {
const record = validateCheckpointRecord(parseCheckpointRecord(body))
return (
record.run.runId === authorization.issue.runId &&
record.run.issueNumber === authorization.issue.issueNumber &&
record.run.branch === authorization.issue.branch &&
checkpointRecordDigest(record) === markers[0][2]
)
} catch {
return false
}
}
function automationCommentBodyAllowed(body, authorization) {
if (!reservedAutomationComment(body)) return true
if (body.includes('<!-- issue-dev-loop:checkpoint:')) {
return checkpointPublicationAllowed(body, authorization)
}
if (body.includes('**pr_completed**')) {
return authorization?.rootIntent === 'prepare-finalization'
}
return authorization?.rootIntent === 'evolve-complete'
}
function automationApiMutationAllowed(
{ endpoint, method, fields, usesFileExpansion, usesInput },
authorization,
) {
if (!endpoint || usesInput || usesFileExpansion) return false
if (
endpoint.match(/^repos\/[^/]+\/[^/]+\/git\/refs$/) &&
method === 'POST' &&
authorization?.rootIntent === 'start' &&
authorization?.issue?.status === 'starting'
) {
return sameArguments(fields, [
`ref=refs/heads/${authorization.issue.branch}`,
`sha=${authorization.issue.baseSha}`,
])
}
const labels = endpoint.match(/^repos\/[^/]+\/[^/]+\/issues\/(\d+)\/labels(?:\/([^/]+))?$/)
if (labels && Number(labels[1]) === authorization?.issue?.issueNumber) {
if (method === 'POST') {
return labels[2] === undefined && sameArguments(fields, ['labels[]=loop:claimed'])
}
return method === 'DELETE' && labels[2] === 'loop%3Aclaimed' && fields.length === 0
}
const issueComment = endpoint.match(/^repos\/[^/]+\/[^/]+\/issues\/(\d+)\/comments$/)
const commentTargets = new Set(
[
authorization?.issue?.issueNumber,
authorization?.issue?.prNumber,
authorization?.stateIssueNumber,
].filter(Number.isInteger),
)
if (issueComment && method === 'POST' && commentTargets.has(Number(issueComment[1]))) {
const body = fields.length === 1 && fields[0].startsWith('body=') ? fields[0].slice(5) : null
const checkpointBody = body?.includes('<!-- issue-dev-loop:checkpoint:')
return (
Boolean(body) &&
(!checkpointBody || Number(issueComment[1]) === authorization?.stateIssueNumber) &&
automationCommentBodyAllowed(body, authorization)
)
}
const reply = endpoint.match(/^repos\/[^/]+\/[^/]+\/pulls\/(\d+)\/comments\/\d+\/replies$/)
return (
reply !== null &&
method === 'POST' &&
Number(reply[1]) === authorization?.issue?.prNumber &&
fields.length === 1 &&
fields[0].startsWith('body=')
)
}
function apiField(field) {
const separator = field.indexOf('=')
return separator === -1
? { name: field, value: '' }
: { name: field.slice(0, separator), value: field.slice(separator + 1) }
}
function githubRepositoryFlags(args) {
const repositories = []
for (let index = 0; index < args.length; index += 1) {
const argument = args[index]
if (argument === '--repo' || argument === '-R') {
repositories.push(args[index + 1] ?? null)
index += 1
continue
}
if (argument.startsWith('--repo=')) {
repositories.push(argument.slice('--repo='.length) || null)
continue
}
if (argument.startsWith('-R') && argument.length > 2) {
repositories.push(argument.slice(2))
}
}
return repositories
}
function githubHostnameFlags(args) {
const hostnames = []
for (let index = 0; index < args.length; index += 1) {
const argument = args[index]
if (argument === '--hostname') {
const hostname = args[index + 1]
if (hostname) hostnames.push(hostname)
index += 1
continue
}
if (argument.startsWith('--hostname=')) {
hostnames.push(argument.slice('--hostname='.length))
}
}
return hostnames
}
function endpointRepository(endpoint) {
const match = endpoint?.match(/^repos\/([^/]+\/[^/]+)(?:\/|$)/)
return match?.[1] ?? null
}
function repositoryInScope(actual, expected) {
return (
typeof actual === 'string' &&
typeof expected === 'string' &&
actual.toLowerCase() === expected.toLowerCase()
)
}
export function assertGitHubCliPolicy(
role,
args,
{ expectedRepository = null, authorization = null } = {},
) {
const reject = () => {
throw new Error(`GitHub action is prohibited for the ${role} role`)
}
if (
expectedRepository &&
githubRepositoryFlags(args).some(
(repository) => !repositoryInScope(repository, expectedRepository),
)
) {
reject()
}
if (githubHostnameFlags(args).some((hostname) => hostname.toLowerCase() !== 'github.com')) {
reject()
}
const group = githubGroup(args)
if (!group.name) reject()
const subcommand = commandAfterGroup(args, group.index)
const readOnlyIdentityRequest = (request) =>
request.valid && !request.mutating && request.endpoint === 'user' && request.fields.length === 0
if (role === 'reviewer') {
if (group.name === 'api') {
const request = githubApiRequest(args.slice(group.index + 1))
if (readOnlyIdentityRequest(request)) return
if (
!request.valid ||
request.mutating ||
request.endpoint === 'graphql' ||
(expectedRepository &&
!repositoryInScope(endpointRepository(request.endpoint), expectedRepository))
) {