-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscan.mjs
More file actions
1522 lines (1436 loc) · 49.9 KB
/
Copy pathscan.mjs
File metadata and controls
1522 lines (1436 loc) · 49.9 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
#!/usr/bin/env node
import { appendFile, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const TOOL_NAME = 'EMILIA Authority Map';
const PINNED_COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
const OFFICIAL_ACTION_OWNERS = new Set(['actions', 'github']);
const EXPRESSION = /\$\{\{/;
const CONTRIBUTOR_CONTROLLED_TRIGGERS = new Set([
'discussion',
'discussion_comment',
'issue_comment',
'issues',
'pull_request',
'pull_request_review',
'pull_request_review_comment',
'pull_request_target',
]);
const CANDIDATE_CHECKOUT_CONTEXT =
/\$\{\{[^}]*\b(?:github\.event\.pull_request\.head\.(?:sha|ref|repo\.full_name)|github\.head_ref)\b[^}]*\}\}/i;
const UNTRUSTED_SHELL_CONTEXT =
/\$\{\{[^}]*\b(?:github\.head_ref|github\.event\.(?:comment\.body|discussion\.(?:body|title)|issue\.(?:body|title)|pull_request\.(?:body|head\.(?:label|ref)|title)|review\.body))\b[^}]*\}\}/i;
/** @type {Array<[string, RegExp]>} */
const PRIVILEGED_COMMAND_PATTERNS = [
['package-publish', /(?:^|\n)\s*(?:npm|pnpm)\s+publish\b/im],
['package-publish', /(?:^|\n)\s*yarn\s+npm\s+publish\b/im],
['package-publish', /(?:^|\n)\s*(?:python(?:3)?\s+-m\s+)?twine\s+upload\b/im],
['package-publish', /(?:^|\n)\s*(?:cargo\s+publish|gem\s+push|dotnet\s+nuget\s+push)\b/im],
['release-mutation', /(?:^|\n)\s*gh\s+release\s+(?:create|delete|edit|upload)\b/im],
['repository-merge', /(?:^|\n)\s*gh\s+pr\s+merge\b/im],
['repository-push', /(?:^|\n)\s*git\s+push\b/im],
['container-push', /(?:^|\n)\s*(?:docker|podman)\s+push\b/im],
['infrastructure-deploy', /(?:^|\n)\s*kubectl\s+(?:apply|delete|patch|replace|set)\b/im],
['infrastructure-deploy', /(?:^|\n)\s*helm\s+(?:install|rollback|uninstall|upgrade)\b/im],
['infrastructure-deploy', /(?:^|\n)\s*terraform\s+(?:apply|destroy)\b/im],
['platform-deploy', /(?:^|\n)\s*(?:vercel|wrangler)\s+(?:deploy|--prod)\b/im],
];
export const STATIC_BOUNDARY = Object.freeze({
blocksMutations: false,
completeMediation: false,
repositoryConfigurationIsAuthority: false,
requiresApiPermissionsFor: Object.freeze([
'GitHub environment protection settings',
'GitHub rulesets',
'GitHub bypass actors and settings',
]),
statement:
'This report is static discovery only. It does not block mutations, is not complete mediation, and does not use repository configuration as authority. Without suitable GitHub API permissions it cannot know environment protection, ruleset, or bypass settings.',
});
function stripInlineComment(value) {
let quote = null;
let escaped = false;
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (escaped) {
escaped = false;
continue;
}
if (quote === '"' && character === '\\') {
escaped = true;
continue;
}
if (quote) {
if (character === quote) quote = null;
continue;
}
if (character === '"' || character === "'") {
quote = character;
continue;
}
if (character === '#' && (index === 0 || /\s/.test(value[index - 1]))) {
return value.slice(0, index).trimEnd();
}
}
return value.trimEnd();
}
function unquote(value) {
const trimmed = value.trim();
if (trimmed.length < 2) return trimmed;
if (trimmed.startsWith("'") && trimmed.endsWith("'")) {
return trimmed.slice(1, -1).replaceAll("''", "'");
}
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
try {
return JSON.parse(trimmed);
} catch {
return trimmed.slice(1, -1);
}
}
return trimmed;
}
function splitFlow(value) {
const parts = [];
let start = 0;
let quote = null;
let escaped = false;
let squareDepth = 0;
let curlyDepth = 0;
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (escaped) {
escaped = false;
continue;
}
if (quote === '"' && character === '\\') {
escaped = true;
continue;
}
if (quote) {
if (character === quote) quote = null;
continue;
}
if (character === '"' || character === "'") {
quote = character;
continue;
}
if (character === '[') squareDepth += 1;
if (character === ']') squareDepth -= 1;
if (character === '{') curlyDepth += 1;
if (character === '}') curlyDepth -= 1;
if (character === ',' && squareDepth === 0 && curlyDepth === 0) {
parts.push(value.slice(start, index).trim());
start = index + 1;
}
}
parts.push(value.slice(start).trim());
return parts.filter(Boolean);
}
function findMappingColon(value) {
let quote = null;
let escaped = false;
let squareDepth = 0;
let curlyDepth = 0;
for (let index = 0; index < value.length; index += 1) {
const character = value[index];
if (escaped) {
escaped = false;
continue;
}
if (quote === '"' && character === '\\') {
escaped = true;
continue;
}
if (quote) {
if (character === quote) quote = null;
continue;
}
if (character === '"' || character === "'") {
quote = character;
continue;
}
if (character === '[') squareDepth += 1;
if (character === ']') squareDepth -= 1;
if (character === '{') curlyDepth += 1;
if (character === '}') curlyDepth -= 1;
if (character === ':' && squareDepth === 0 && curlyDepth === 0) return index;
}
return -1;
}
function parseKeyValue(content) {
const colon = findMappingColon(content);
if (colon < 0) return null;
const rawKey = content.slice(0, colon).trim();
if (!rawKey) return null;
return {
key: unquote(rawKey),
value: stripInlineComment(content.slice(colon + 1)).trim(),
};
}
function parseFlowSequence(value) {
const trimmed = value.trim();
if (!trimmed.startsWith('[') || !trimmed.endsWith(']')) return null;
return splitFlow(trimmed.slice(1, -1)).map(unquote);
}
function parseFlowMapping(value) {
const trimmed = value.trim();
if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) return null;
const entries = [];
for (const part of splitFlow(trimmed.slice(1, -1))) {
const parsed = parseKeyValue(part);
if (!parsed) return null;
entries.push(parsed);
}
return entries;
}
function sourceLines(source) {
return source.split(/\r?\n/).map((raw, index) => {
const indentation = raw.match(/^[ ]*/)?.[0].length ?? 0;
const content = stripInlineComment(raw.slice(indentation));
return {
number: index + 1,
raw,
indent: indentation,
content,
trimmed: content.trim(),
};
});
}
function isSignificant(line) {
return line.trimmed !== '' && line.trimmed !== '---' && line.trimmed !== '...';
}
function blockEnd(lines, start, parentIndent, maximum = lines.length) {
for (let index = start + 1; index < maximum; index += 1) {
if (isSignificant(lines[index]) && lines[index].indent <= parentIndent) return index;
}
return maximum;
}
function directEntries(lines, start, end, parentIndent) {
let childIndent = Number.POSITIVE_INFINITY;
for (let index = start + 1; index < end; index += 1) {
const line = lines[index];
if (isSignificant(line) && line.indent > parentIndent) {
childIndent = Math.min(childIndent, line.indent);
}
}
if (!Number.isFinite(childIndent)) return [];
const entries = [];
for (let index = start + 1; index < end; index += 1) {
const line = lines[index];
if (!isSignificant(line) || line.indent !== childIndent) continue;
const parsed = parseKeyValue(line.trimmed);
if (parsed) entries.push({ ...parsed, index, line: line.number, indent: line.indent });
}
return entries;
}
function addAmbiguity(ambiguities, kind, line, message) {
const key = `${kind}:${line}:${message}`;
if (ambiguities.some((item) => item._key === key)) return;
ambiguities.push({ _key: key, kind, line, message });
}
function cleanAmbiguities(ambiguities) {
return ambiguities
.map(({ _key, ...item }) => item)
.sort((left, right) => left.line - right.line || left.kind.localeCompare(right.kind));
}
function structuralAmbiguities(lines, ambiguities) {
let documentCount = 0;
for (const line of lines) {
if (line.trimmed === '---') documentCount += 1;
if (/^\t/.test(line.raw) || /^ +\t/.test(line.raw)) {
addAmbiguity(
ambiguities,
'tab-indentation',
line.number,
'Tabs in indentation are unsupported by the conservative scanner.',
);
}
if (line.trimmed.startsWith('%')) {
addAmbiguity(
ambiguities,
'yaml-directive',
line.number,
'YAML directives are not interpreted.',
);
}
if (line.trimmed.startsWith('? ')) {
addAmbiguity(
ambiguities,
'complex-yaml-key',
line.number,
'Complex YAML keys are not interpreted.',
);
}
const structural = line.trimmed.startsWith('- ')
? line.trimmed.slice(2).trimStart()
: line.trimmed;
const parsed = parseKeyValue(structural);
if (!parsed) continue;
if (parsed.key === '<<') {
addAmbiguity(
ambiguities,
'yaml-merge-key',
line.number,
'YAML merge-key semantics are not resolved.',
);
}
if (/(?:^|[\s[{,])&[A-Za-z0-9_-]+(?:$|[\s\]},])/.test(parsed.value)) {
addAmbiguity(
ambiguities,
'yaml-anchor',
line.number,
'YAML anchors are noted but not resolved as authority facts.',
);
}
if (/^\*[A-Za-z0-9_-]+$/.test(parsed.value)) {
addAmbiguity(
ambiguities,
'yaml-alias',
line.number,
'YAML aliases are noted but not resolved as authority facts.',
);
}
if (/^!/.test(parsed.value)) {
addAmbiguity(
ambiguities,
'yaml-tag',
line.number,
'Tagged YAML values are not interpreted.',
);
}
}
if (documentCount > 1) {
addAmbiguity(
ambiguities,
'multiple-yaml-documents',
1,
'Only a single workflow document is inventoried per file.',
);
}
}
function topLevelEntries(lines) {
const entries = [];
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index];
if (!isSignificant(line) || line.indent !== 0) continue;
const parsed = parseKeyValue(line.trimmed);
if (parsed) entries.push({ ...parsed, index, line: line.number, indent: 0 });
}
return entries;
}
function duplicateKeyAmbiguities(entries, ambiguities, context) {
const seen = new Map();
for (const entry of entries) {
if (seen.has(entry.key)) {
addAmbiguity(
ambiguities,
'duplicate-key',
entry.line,
`Duplicate ${context} key "${entry.key}" is not resolved.`,
);
} else {
seen.set(entry.key, entry.line);
}
}
}
function parseTriggers(lines, entry, end, ambiguities) {
const value = entry.value;
if (EXPRESSION.test(value)) {
addAmbiguity(
ambiguities,
'dynamic-trigger',
entry.line,
'Expression-derived workflow triggers cannot be statically determined.',
);
return [];
}
const flowSequence = parseFlowSequence(value);
if (flowSequence) return flowSequence;
const flowMapping = parseFlowMapping(value);
if (flowMapping) return flowMapping.map((item) => item.key);
if (value && !['null', '~', '{}', '[]'].includes(value)) return [unquote(value)];
if (value === '{}') return [];
const children = directEntries(lines, entry.index, end, entry.indent);
duplicateKeyAmbiguities(children, ambiguities, 'trigger');
return children.map((item) => item.key);
}
function permissionRecord(form, line, entries = [], ambiguous = false) {
const writeScopes = entries
.filter((item) => unquote(item.value).toLowerCase() === 'write')
.map((item) => item.key)
.sort();
return {
form,
line,
writeAll: form === 'write-all',
writeScopes,
entries: Object.fromEntries(entries.map((item) => [item.key, unquote(item.value)])),
ambiguous,
};
}
function parsePermissions(lines, entry, end, ambiguities, context) {
const rawValue = entry.value;
const value = unquote(rawValue).toLowerCase();
if (value === 'write-all' || value === 'read-all') {
return permissionRecord(value, entry.line);
}
if (rawValue === '{}') return permissionRecord('empty', entry.line);
if (EXPRESSION.test(rawValue) || /^\*/.test(rawValue)) {
addAmbiguity(
ambiguities,
'dynamic-permission',
entry.line,
`${context} permissions cannot be statically determined.`,
);
return permissionRecord('ambiguous', entry.line, [], true);
}
const flow = parseFlowMapping(rawValue);
if (flow) {
let ambiguous = false;
for (const item of flow) {
if (EXPRESSION.test(item.value) || !['read', 'write', 'none'].includes(unquote(item.value))) {
ambiguous = true;
addAmbiguity(
ambiguities,
'dynamic-permission',
entry.line,
`${context} permission "${item.key}" has an unsupported or dynamic value.`,
);
}
}
return permissionRecord('map', entry.line, flow, ambiguous);
}
if (rawValue && !/^&[A-Za-z0-9_-]+$/.test(rawValue)) {
addAmbiguity(
ambiguities,
'unsupported-permission-form',
entry.line,
`${context} permissions use an unsupported scalar form.`,
);
return permissionRecord('ambiguous', entry.line, [], true);
}
const children = directEntries(lines, entry.index, end, entry.indent);
duplicateKeyAmbiguities(children, ambiguities, `${context} permission`);
let ambiguous = Boolean(rawValue);
for (const item of children) {
const itemValue = unquote(item.value).toLowerCase();
if (item.key === '<<') {
ambiguous = true;
continue;
}
if (EXPRESSION.test(item.value) || !['read', 'write', 'none'].includes(itemValue)) {
ambiguous = true;
addAmbiguity(
ambiguities,
'dynamic-permission',
item.line,
`${context} permission "${item.key}" has an unsupported or dynamic value.`,
);
}
}
return permissionRecord('map', entry.line, children, ambiguous);
}
function absentPermissions() {
return permissionRecord('absent', null);
}
function parseEnvironment(lines, entry, end, ambiguities, job) {
const rawValue = entry.value;
if (EXPRESSION.test(rawValue) || /^\*/.test(rawValue)) {
addAmbiguity(
ambiguities,
'dynamic-environment',
entry.line,
`Job "${job}" has an expression-derived environment.`,
);
return {
job,
value: unquote(rawValue),
line: entry.line,
production: /\bprod(?:uction)?\b/i.test(rawValue),
ambiguous: true,
};
}
const flow = parseFlowMapping(rawValue);
if (flow) {
const name = flow.find((item) => item.key === 'name');
if (!name || EXPRESSION.test(name.value)) {
addAmbiguity(
ambiguities,
'dynamic-environment',
entry.line,
`Job "${job}" has an environment mapping without a static name.`,
);
return {
job,
value: name ? unquote(name.value) : rawValue,
line: entry.line,
production: Boolean(name && /\bprod(?:uction)?\b/i.test(name.value)),
ambiguous: true,
};
}
const value = unquote(name.value);
return {
job,
value,
line: entry.line,
production: /\bprod(?:uction)?\b/i.test(value),
ambiguous: false,
};
}
if (rawValue) {
const value = unquote(rawValue);
return {
job,
value,
line: entry.line,
production: /\bprod(?:uction)?\b/i.test(value),
ambiguous: false,
};
}
const children = directEntries(lines, entry.index, end, entry.indent);
duplicateKeyAmbiguities(children, ambiguities, `job "${job}" environment`);
const name = children.find((item) => item.key === 'name');
if (!name || EXPRESSION.test(name.value) || /^\*/.test(name.value)) {
addAmbiguity(
ambiguities,
'dynamic-environment',
name?.line ?? entry.line,
`Job "${job}" has an environment mapping without a static name.`,
);
return {
job,
value: name ? unquote(name.value) : '',
line: name?.line ?? entry.line,
production: Boolean(name && /\bprod(?:uction)?\b/i.test(name.value)),
ambiguous: true,
};
}
const value = unquote(name.value);
return {
job,
value,
line: name.line,
production: /\bprod(?:uction)?\b/i.test(value),
ambiguous: false,
};
}
function runnerValue(lines, entry, end) {
if (entry.value) return entry.value;
const values = [];
for (let index = entry.index + 1; index < end; index += 1) {
const line = lines[index];
if (!isSignificant(line) || line.indent <= entry.indent) continue;
values.push(line.trimmed.replace(/^-\s*/, ''));
}
return values.join(', ');
}
function hasSelfHosted(value) {
return /(?:^|[\s,[{])['"]?self-hosted['"]?(?:$|[\s,\]}])/i.test(value);
}
function parseActionReference(value) {
const uses = unquote(value);
if (uses.startsWith('./') || uses.startsWith('docker://')) return { kind: 'local' };
if (EXPRESSION.test(uses)) return { kind: 'dynamic', uses };
const at = uses.lastIndexOf('@');
if (at <= 0) return { kind: 'unsupported', uses };
const target = uses.slice(0, at);
const ref = uses.slice(at + 1);
const owner = target.split('/')[0]?.toLowerCase();
if (!owner || target.split('/').length < 2) return { kind: 'unsupported', uses };
return {
kind: 'remote',
uses,
target,
owner,
ref,
thirdParty: !OFFICIAL_ACTION_OWNERS.has(owner),
pinned: PINNED_COMMIT.test(ref),
};
}
function parsedStructuralLine(line) {
const content = line.trimmed.startsWith('- ')
? line.trimmed.slice(2).trimStart()
: line.trimmed;
return parseKeyValue(content);
}
function nestedStepField(lines, start, end, key) {
for (let index = start + 1; index < end; index += 1) {
if (!isSignificant(lines[index])) continue;
const parsed = parsedStructuralLine(lines[index]);
if (parsed?.key === key) {
return { ...parsed, index, line: lines[index].number };
}
}
return null;
}
function runSource(lines, index, end, value) {
if (!/^[>|][+-]?$/.test(value)) return unquote(value);
const source = [];
for (let cursor = index + 1; cursor < end; cursor += 1) {
if (lines[cursor].indent <= lines[index].indent && isSignificant(lines[cursor])) break;
source.push(lines[cursor].raw.trim());
}
return source.join('\n');
}
function privilegedCommandSink(source) {
for (const [kind, pattern] of PRIVILEGED_COMMAND_PATTERNS) {
if (pattern.test(source)) return { kind, evidence: source.trim().split(/\r?\n/)[0] };
}
return null;
}
function privilegedActionSink(reference) {
if (reference.kind !== 'remote') return null;
const target = reference.target.toLowerCase();
if (
/(?:^|[/_-])(?:deploy|publish)(?:$|[/_-])/.test(target) ||
target.includes('gh-action-pypi-publish') ||
target === 'actions/deploy-pages'
) {
return { kind: 'publish-or-deploy-action', evidence: reference.uses };
}
return null;
}
function isDefaultCheckoutPath(value) {
if (!value) return true;
const normalized = unquote(value).trim();
return normalized === '.' || normalized === '${{ github.workspace }}';
}
function productionReferences(lines, environmentReferences) {
const references = environmentReferences
.filter((item) => item.production)
.map((item) => ({
kind: 'environment',
job: item.job,
value: item.value,
line: item.line,
ambiguous: item.ambiguous,
}));
const occupied = new Set(references.map((item) => item.line));
for (const line of lines) {
if (occupied.has(line.number)) continue;
const match = line.trimmed.match(/\bprod(?:uction)?\b/i);
if (!match) continue;
references.push({
kind: 'text',
job: null,
value: match[0],
line: line.number,
ambiguous: true,
});
}
return references.sort((left, right) => left.line - right.line);
}
function analyzeWorkflow(source, relativeFile) {
const lines = sourceLines(source);
const ambiguities = [];
structuralAmbiguities(lines, ambiguities);
const topEntries = topLevelEntries(lines);
duplicateKeyAmbiguities(topEntries, ambiguities, 'top-level');
const nameEntry = topEntries.find((item) => item.key === 'name');
const onEntry = topEntries.find((item) => item.key === 'on');
const permissionsEntry = topEntries.find((item) => item.key === 'permissions');
const jobsEntry = topEntries.find((item) => item.key === 'jobs');
if (!onEntry) {
addAmbiguity(
ambiguities,
'missing-trigger',
1,
'No statically recognizable top-level "on" key was found.',
);
}
if (!jobsEntry) {
addAmbiguity(
ambiguities,
'missing-jobs',
1,
'No statically recognizable top-level "jobs" key was found.',
);
}
const triggerEnd = onEntry ? blockEnd(lines, onEntry.index, onEntry.indent) : 0;
const triggers = onEntry ? parseTriggers(lines, onEntry, triggerEnd, ambiguities) : [];
const topPermissionEnd = permissionsEntry
? blockEnd(lines, permissionsEntry.index, permissionsEntry.indent)
: 0;
const topPermissions = permissionsEntry
? parsePermissions(lines, permissionsEntry, topPermissionEnd, ambiguities, 'Top-level')
: absentPermissions();
const jobs = [];
const jobPermissions = {};
const environmentReferences = [];
const selfHostedRunners = [];
const unpinnedThirdPartyActions = [];
const candidateCheckouts = [];
const dangerousPullRequestTargetCompositions = [];
const obviousPrivilegedSinks = [];
if (jobsEntry) {
const jobsEnd = blockEnd(lines, jobsEntry.index, jobsEntry.indent);
const jobEntries = directEntries(lines, jobsEntry.index, jobsEnd, jobsEntry.indent);
duplicateKeyAmbiguities(jobEntries, ambiguities, 'job');
for (let position = 0; position < jobEntries.length; position += 1) {
const jobEntry = jobEntries[position];
const job = jobEntry.key;
const jobEnd = position + 1 < jobEntries.length ? jobEntries[position + 1].index : jobsEnd;
const fields = directEntries(lines, jobEntry.index, jobEnd, jobEntry.indent);
duplicateKeyAmbiguities(fields, ambiguities, `job "${job}"`);
const permissionEntry = fields.find((item) => item.key === 'permissions');
const environmentEntry = fields.find((item) => item.key === 'environment');
const runsOnEntry = fields.find((item) => item.key === 'runs-on');
const permissionEnd = permissionEntry
? blockEnd(lines, permissionEntry.index, permissionEntry.indent, jobEnd)
: 0;
const permissions = permissionEntry
? parsePermissions(
lines,
permissionEntry,
permissionEnd,
ambiguities,
`Job "${job}"`,
)
: null;
if (permissions) jobPermissions[job] = permissions;
let environment = null;
if (environmentEntry) {
const environmentEnd = blockEnd(
lines,
environmentEntry.index,
environmentEntry.indent,
jobEnd,
);
environment = parseEnvironment(
lines,
environmentEntry,
environmentEnd,
ambiguities,
job,
);
environmentReferences.push(environment);
}
if (runsOnEntry) {
const runsOnEnd = blockEnd(lines, runsOnEntry.index, runsOnEntry.indent, jobEnd);
const value = runnerValue(lines, runsOnEntry, runsOnEnd);
if (EXPRESSION.test(value)) {
addAmbiguity(
ambiguities,
'dynamic-runner',
runsOnEntry.line,
`Job "${job}" has an expression-derived runner selection.`,
);
}
if (hasSelfHosted(value)) {
selfHostedRunners.push({ job, value, line: runsOnEntry.line });
}
} else if (!fields.some((item) => item.key === 'uses')) {
addAmbiguity(
ambiguities,
'missing-runner',
jobEntry.line,
`Job "${job}" has neither a static runs-on field nor a reusable-workflow uses field.`,
);
}
const jobCandidateCheckouts = [];
const jobLocalActions = [];
const jobRuns = [];
for (let index = jobEntry.index + 1; index < jobEnd; index += 1) {
const line = lines[index];
if (!isSignificant(line)) continue;
const parsed = parsedStructuralLine(line);
if (!parsed || parsed.key !== 'uses') continue;
const reference = parseActionReference(parsed.value);
const stepEnd = blockEnd(lines, index, line.indent, jobEnd);
if (reference.kind === 'dynamic') {
addAmbiguity(
ambiguities,
'dynamic-action-reference',
line.number,
`Job "${job}" has an expression-derived action or reusable-workflow reference.`,
);
} else if (reference.kind === 'unsupported') {
addAmbiguity(
ambiguities,
'unsupported-action-reference',
line.number,
`Job "${job}" has an unsupported action reference form.`,
);
} else if (reference.kind === 'remote' && reference.thirdParty && !reference.pinned) {
unpinnedThirdPartyActions.push({
job,
uses: reference.uses,
ref: reference.ref,
line: line.number,
reason: 'Third-party reference is not a full commit SHA.',
});
}
if (reference.kind === 'local') {
jobLocalActions.push({ job, line: line.number, index, uses: unquote(parsed.value) });
}
if (
reference.kind === 'remote' &&
reference.target.toLowerCase() === 'actions/checkout'
) {
const ref = nestedStepField(lines, index, stepEnd, 'ref');
const repository = nestedStepField(lines, index, stepEnd, 'repository');
const checkoutPath = nestedStepField(lines, index, stepEnd, 'path');
const sourceValues = [ref?.value, repository?.value].filter(Boolean);
if (sourceValues.some((value) => CANDIDATE_CHECKOUT_CONTEXT.test(value))) {
const checkout = {
job,
line: line.number,
index,
ref: ref ? unquote(ref.value) : null,
repository: repository ? unquote(repository.value) : null,
path: checkoutPath ? unquote(checkoutPath.value) : null,
defaultWorkspace: isDefaultCheckoutPath(checkoutPath?.value),
};
jobCandidateCheckouts.push(checkout);
candidateCheckouts.push(checkout);
}
}
const actionSink = privilegedActionSink(reference);
if (actionSink) {
obviousPrivilegedSinks.push({
job,
line: line.number,
source: 'uses',
...actionSink,
environment: environment?.value ?? null,
environmentAmbiguous: environment?.ambiguous ?? false,
});
}
}
for (let index = jobEntry.index + 1; index < jobEnd; index += 1) {
const line = lines[index];
if (!isSignificant(line)) continue;
const parsed = parsedStructuralLine(line);
if (!parsed || parsed.key !== 'run') continue;
const runEnd = blockEnd(lines, index, line.indent, jobEnd);
const source = runSource(lines, index, runEnd, parsed.value);
const run = { job, line: line.number, index, source };
jobRuns.push(run);
const commandSink = privilegedCommandSink(source);
if (commandSink) {
obviousPrivilegedSinks.push({
job,
line: line.number,
source: 'run',
...commandSink,
environment: environment?.value ?? null,
environmentAmbiguous: environment?.ambiguous ?? false,
});
}
}
if (triggers.includes('pull_request_target')) {
for (const run of jobRuns) {
if (!UNTRUSTED_SHELL_CONTEXT.test(run.source)) continue;
dangerousPullRequestTargetCompositions.push({
job,
line: run.line,
kind: 'untrusted-shell-expression',
evidence: 'A contributor-controlled GitHub context is interpolated directly into run.',
});
}
for (const checkout of jobCandidateCheckouts) {
const localExecution = jobLocalActions.find((item) => item.index > checkout.index);
const shellExecution = jobRuns.find((item) => item.index > checkout.index);
if (!checkout.defaultWorkspace || (!localExecution && !shellExecution)) continue;
const execution = /** @type {{ line: number }} */ (localExecution ?? shellExecution);
dangerousPullRequestTargetCompositions.push({
job,
line: checkout.line,
kind: 'candidate-code-execution',
evidence: localExecution
? `Candidate checkout is followed by local action ${localExecution.uses}.`
: `Candidate checkout is followed by a run step at line ${execution.line}.`,
});
}
}
jobs.push({
id: job,
line: jobEntry.line,
permissions,
environment,
});
}
}
const mutationSignals = [];
if (topPermissions.writeAll || topPermissions.writeScopes.length > 0) {
mutationSignals.push({
source: 'top-level-permissions',
job: null,
line: topPermissions.line,
writeAll: topPermissions.writeAll,
writeScopes: topPermissions.writeScopes,
});
}
const mutatingJobs = [];
const ambiguousMutationJobs = [];
for (const job of jobs) {
const effective = job.permissions ?? topPermissions;
const writes = effective.writeAll || effective.writeScopes.length > 0;
if (writes) {
mutatingJobs.push(job);
mutationSignals.push({
source: job.permissions ? 'job-permissions' : 'inherited-top-level-permissions',
job: job.id,
line: effective.line,
writeAll: effective.writeAll,
writeScopes: effective.writeScopes,
});
}
if (effective.ambiguous) ambiguousMutationJobs.push(job);
}
const jobsWithoutEnvironment = mutatingJobs.filter((job) => !job.environment);
const jobsWithAmbiguousEnvironment = mutatingJobs.filter(
(job) => job.environment?.ambiguous,
);
let environmentAssessment = 'not-applicable';
if (jobsWithoutEnvironment.length > 0) environmentAssessment = 'absent';
else if (
jobsWithAmbiguousEnvironment.length > 0 ||
ambiguousMutationJobs.some((job) => !job.environment || job.environment.ambiguous)
) {
environmentAssessment = 'ambiguous';
} else if (mutatingJobs.length > 0) environmentAssessment = 'present';
const cleanedAmbiguities = cleanAmbiguities(ambiguities);
return {
file: relativeFile,
name: nameEntry ? unquote(nameEntry.value) : path.basename(relativeFile),
triggers,
environmentReferences,
productionReferences: productionReferences(lines, environmentReferences),
permissions: {
topLevel: topPermissions,
jobs: jobPermissions,
},
hazards: {
pullRequestTarget: {
present: triggers.includes('pull_request_target'),
line: onEntry?.line ?? null,
},
contributorControlledTriggers: triggers.filter((trigger) =>
CONTRIBUTOR_CONTROLLED_TRIGGERS.has(trigger),
),
selfHostedRunners,
unpinnedThirdPartyActions,
candidateCheckouts: candidateCheckouts.map(({ index, ...item }) => item),
dangerousPullRequestTargetCompositions,
},
mutation: {
hasDeclaredWriteCapability: mutatingJobs.length > 0,
hasAmbiguousWriteCapability: ambiguousMutationJobs.length > 0,
signals: mutationSignals,
mutatingJobs: mutatingJobs.map((job) => job.id),
jobsWithoutEnvironment: jobsWithoutEnvironment.map((job) => job.id),
withoutEnvironment: jobsWithoutEnvironment.length > 0,
environmentAssessment,
obviousPrivilegedSinks,
staticBasis:
'Mutation capability is inferred only from declared effective GitHub token write permissions. Steps may mutate through other credentials or systems that static discovery cannot establish.',
},
ambiguities: cleanedAmbiguities,
};
}
/**
* @param {{
* code: string,
* severity: string,
* workflow: string,