-
Notifications
You must be signed in to change notification settings - Fork 16.2k
2321 lines (2071 loc) · 108 KB
/
Copy pathValidateSampleDeployments.yml
File metadata and controls
2321 lines (2071 loc) · 108 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
# ──────────────────────────────────────────────────────────────────────────────
# ValidateSampleDeployments.yml
#
# Combined workflow: AI-powered PR summary + ADX deployment validation.
#
# Job 1 – summarize:
# Posts an AI-generated reviewer-friendly summary comment on a PR using the
# instructions in .github/agents/summarizer.agent.md.
# Runs Microsoft Security DevOps (Template Analyzer, Checkov, Trivy, Terrascan)
# and feeds findings to the AI model via an agentic tool-calling loop.
#
# Job 2 – selected-pipeline:
# Validates sample deployments against Azure Data Explorer (ADX) logs.
# Requires the adx-readonly environment, MEMBER/OWNER/COLLABORATOR auth,
# and validate-samples.yml to have passed.
#
# Triggered by a "/validate" comment on a pull request. Uses issue_comment
# (not pull_request) so GITHUB_TOKEN has full permissions for fork PRs.
#
# Security gates (enforced in the `gate` job, before any PR-controlled code
# is read by downstream jobs):
# 1. Commenter authorization: only MEMBER/OWNER/COLLABORATOR can drive any
# job. `issue_comment` events fire for any GitHub user, so this gate
# is the only thing preventing fork-PR authors (or arbitrary commenters)
# from triggering `summarize`/`selected-pipeline` with `pull-requests:
# write` / `security-events: write` / Azure-OIDC tokens. ICM 31000000622897.
# 2. Protected-files safeguard: PRs that modify this workflow or the
# `summarizer.agent.md` system prompt are blocked unless the PR author
# is MEMBER/OWNER, so downstream jobs never read attacker-controlled
# copies of those files.
# Downstream jobs (`summarize`, `selected-pipeline`) re-assert the commenter
# check as defense-in-depth.
# ──────────────────────────────────────────────────────────────────────────────
name: Validate PR (Summarize + ADX)
on:
issue_comment:
types: [created]
# `pull_request_target` (not `pull_request`) for the post-merge
# commit-generated-on-merge job: GitHub forces GITHUB_TOKEN to read-only
# on `pull_request` events from forks regardless of the `permissions:`
# block, which 403s the auto-PR branch push. `pull_request_target` runs
# in the base-repo context with full token permissions even for fork
# PRs. This is safe here because the job only checks out the default
# branch (never the fork's PR head) and only downloads a pre-validated
# artifact — no fork code is executed.
pull_request_target:
types: [closed]
# Workflow-level concurrency: one run per PR
concurrency:
group: validate-pr-${{ github.event.issue.number || github.event.pull_request.number }}
cancel-in-progress: true
jobs:
# ============================================================================
# JOB 0 – gate
#
# Blocks the workflow until validate-samples.yml has reached a terminal
# success conclusion for the PR HEAD SHA.
# * completed + success -> proceed (exit 0)
# * completed + failure-like -> fail immediately
# * non-terminal (queued/in_progress/...) or no-run -> poll every 30s
# for up to 10 min, then re-evaluate as above.
#
# Both `summarize` and `selected-pipeline` declare `needs: [gate]` so a
# gate failure/timeout skips them entirely.
# ============================================================================
gate:
name: Wait for validate-samples.yml to succeed
runs-on: ubuntu-latest
timeout-minutes: 12
# Only run on /validate comments on pull requests
if: >-
github.event.issue.pull_request &&
startsWith(github.event.comment.body, '/validate')
permissions:
contents: read
pull-requests: read
actions: read
checks: write
outputs:
head_sha: ${{ steps.pr-head.outputs.head_sha }}
steps:
# ── Security gate 1/2: commenter authorization ─────────────────────
# `issue_comment` events fire for any GitHub user who can comment on
# the PR (i.e., anyone on a public repo). All downstream jobs read
# PR-controlled inputs and/or hold write tokens, so we authorize the
# commenter here, before any checkout or API call against the PR.
# See ICM 31000000622897 / MSRC 119361.
- name: Check commenter permission (basic)
shell: bash
run: |
set -euo pipefail
echo "Comment author association: ${{ github.event.comment.author_association }}"
case "${{ github.event.comment.author_association }}" in
MEMBER|OWNER|COLLABORATOR) ;;
*)
echo "::error::Not authorized to /validate. Comment author_association='${{ github.event.comment.author_association }}'; only MEMBER/OWNER/COLLABORATOR may trigger this workflow."
exit 1
;;
esac
# ── Security gate 2/2: block edits to protected workflow files ─────
# If the PR modifies this workflow or the `summarizer.agent.md`
# system prompt, the PR author must be MEMBER/OWNER. This prevents
# a fork-PR author from substituting a malicious system prompt or
# workflow definition that a maintainer would then run with
# `/validate`. Mirrors the in-job safeguard in `selected-pipeline`
# but lifted to `gate` so it short-circuits `summarize` as well.
- name: Safeguard – block protected-file edits by non MEMBER/OWNER
uses: actions/github-script@v7
with:
script: |
const allowed = new Set(["MEMBER", "OWNER"]);
const owner = context.repo.owner;
const repo = context.repo.repo;
const pull_number = context.payload.issue.number;
const [prData, files] = await Promise.all([
github.rest.pulls.get({ owner, repo, pull_number }),
github.paginate(
github.rest.pulls.listFiles,
{ owner, repo, pull_number, per_page: 100 }
)
]);
const assoc = prData.data.author_association;
// Any file executed with the privileged token/OIDC of this
// workflow (via checkout of PR HEAD) must be listed here so
// fork PRs cannot substitute a malicious version. Directory
// entries end with "/" and match by prefix; file entries
// match exactly. See ICM 31000000643564.
const protectedDirs = [
".github/workflows/",
".github/scripts/",
".github/actions/",
".github/agents/",
];
const protectedFiles = [
".github/CODEOWNERS",
];
const isProtected = (name) =>
protectedDirs.some(d => name.startsWith(d)) ||
protectedFiles.includes(name);
const touchedNames = files.map(f => f.filename).filter(isProtected);
const touched = touchedNames.length > 0;
core.info(`PR author_association=${assoc}; protected files touched=${touched}`);
if (touched && !allowed.has(assoc)) {
core.setFailed(
`Blocked: protected file(s) ${touchedNames.join(', ')} modified by PR author with ` +
`author_association='${assoc}'. Only MEMBER or OWNER may modify these files.`
);
}
# Sparse checkout just the helper script directory so subsequent steps
# can call .github/scripts/upsert-check-run.sh.
- name: Checkout helper scripts
uses: actions/checkout@v4
with:
sparse-checkout: |
.github/scripts
sparse-checkout-cone-mode: false
- name: Resolve PR HEAD SHA
id: pr-head
shell: bash
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.issue.number }}
run: |
set -euo pipefail
gh_api_retry () {
local out
if out=$(gh api "$@" 2>&1); then
printf '%s' "${out}"
return 0
fi
echo " (transient gh api failure, retrying once: ${out})" >&2
sleep 2
gh api "$@"
}
HEAD_SHA=$(gh_api_retry "/repos/${REPO}/pulls/${PR_NUMBER}" --jq '.head.sha')
if [[ -z "${HEAD_SHA}" ]]; then
echo "ERROR: Failed to resolve HEAD SHA for PR #${PR_NUMBER}." >&2
exit 1
fi
echo "PR #${PR_NUMBER} HEAD SHA: ${HEAD_SHA}"
echo "head_sha=${HEAD_SHA}" >> "$GITHUB_OUTPUT"
# Publish the required check as in_progress so reviewers see live status
# the moment /validate is acknowledged. The final conclusion is written
# by the `report-check` job at the end of the workflow.
- name: Mark adx-deployment-validation check in_progress
shell: bash
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
CHECK_NAME: adx-deployment-validation
HEAD_SHA: ${{ steps.pr-head.outputs.head_sha }}
STATUS: in_progress
TITLE: Validating in progress…
SUMMARY: |
`/validate` was received. Waiting for `validate-samples.yml`
to succeed for this commit, then running ADX deployment
validation.
DETAILS_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: bash .github/scripts/upsert-check-run.sh
- name: Wait for validate-samples.yml on PR HEAD SHA
shell: bash
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
HEAD_SHA: ${{ steps.pr-head.outputs.head_sha }}
POLL_INTERVAL_SECONDS: '30'
POLL_TIMEOUT_SECONDS: '600'
run: |
set -euo pipefail
# ── Helper: gh api with one immediate retry on transient failure ──
gh_api_retry () {
local out
if out=$(gh api "$@" 2>&1); then
printf '%s' "${out}"
return 0
fi
echo " (transient gh api failure, retrying once: ${out})" >&2
sleep 2
gh api "$@"
}
echo "Polling validate-samples.yml for SHA ${HEAD_SHA} every ${POLL_INTERVAL_SECONDS}s (timeout ${POLL_TIMEOUT_SECONDS}s)..."
# Conclusions considered terminal failures (immediate fail).
FAILURE_CONCLUSIONS="failure cancelled timed_out action_required startup_failure stale"
DEADLINE=$(( $(date +%s) + POLL_TIMEOUT_SECONDS ))
LAST_STATUS=""
ATTEMPT=0
while :; do
ATTEMPT=$((ATTEMPT + 1))
RUN_JSON=$(gh_api_retry \
"/repos/${REPO}/actions/workflows/validate-samples.yml/runs?head_sha=${HEAD_SHA}&per_page=1" \
--jq '.workflow_runs[0] // {}')
STATUS=$(echo "${RUN_JSON}" | jq -r '.status // empty')
CONCLUSION=$(echo "${RUN_JSON}" | jq -r '.conclusion // empty')
LAST_STATUS="${STATUS:-no-run-yet}"
echo "[attempt ${ATTEMPT}] status='${LAST_STATUS}' conclusion='${CONCLUSION:-<none>}'"
if [[ "${STATUS}" == "completed" ]]; then
if [[ "${CONCLUSION}" == "success" ]]; then
echo "✅ validate-samples.yml succeeded for SHA ${HEAD_SHA}."
exit 0
fi
for f in ${FAILURE_CONCLUSIONS}; do
if [[ "${CONCLUSION}" == "${f}" ]]; then
echo "❌ validate-samples.yml conclusion='${CONCLUSION}' for SHA ${HEAD_SHA}." >&2
echo " Fix the failures and push a new commit; once validate-samples passes, comment /validate again." >&2
exit 1
fi
done
# Unknown/neutral/skipped — treat as not-yet-success and keep polling.
echo " conclusion '${CONCLUSION}' is neither success nor a known failure; continuing to poll." >&2
fi
NOW=$(date +%s)
if (( NOW >= DEADLINE )); then
echo "⏱️ validate-samples.yml did not reach a terminal state within ${POLL_TIMEOUT_SECONDS} seconds (last status='${LAST_STATUS}')." >&2
echo " Wait for validate-samples to complete, then comment /validate again." >&2
exit 1
fi
sleep "${POLL_INTERVAL_SECONDS}"
done
summarize:
name: Summarize PR sample
runs-on: ubuntu-latest
needs: [gate]
# Only run on /validate comments on pull requests (and after gate succeeds)
if: >-
github.event.issue.pull_request &&
startsWith(github.event.comment.body, '/validate')
permissions:
contents: read
pull-requests: write
copilot-requests: write
security-events: write
steps:
# ── Commenter authorization (defense-in-depth) ─────────────────────
# `gate` already enforces this, but `issue_comment` triggers fire for
# any GitHub user and this job holds `pull-requests: write` +
# `security-events: write` while reading PR-controlled `.github/agents/
# summarizer.agent.md` as the AI system prompt. Re-asserting the
# commenter check here keeps `summarize` safe even if the `gate`
# check is ever bypassed or refactored. See ICM 31000000622897.
- name: Check commenter permission (basic)
shell: bash
run: |
set -euo pipefail
echo "Comment author association: ${{ github.event.comment.author_association }}"
case "${{ github.event.comment.author_association }}" in
MEMBER|OWNER|COLLABORATOR) ;;
*)
echo "::error::Not authorized to /validate. Comment author_association='${{ github.event.comment.author_association }}'; only MEMBER/OWNER/COLLABORATOR may trigger this workflow."
exit 1
;;
esac
# ── 1. Resolve the PR head ref ──────────────────────────────────────
- name: Get PR details
id: pr
uses: actions/github-script@v7
with:
script: |
const pr = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number
});
core.setOutput('head_ref', pr.data.head.ref);
core.setOutput('head_sha', pr.data.head.sha);
core.setOutput('head_repo', pr.data.head.repo.full_name);
# ── 2. Detect changed sample folders (API only, no checkout) ────────
- name: Detect changed sample folders
id: detect
uses: actions/github-script@v7
with:
script: |
const path = require('path');
const owner = context.repo.owner;
const repo = context.repo.repo;
const pull_number = context.issue.number;
const headSha = '${{ steps.pr.outputs.head_sha }}';
core.info(`Detecting changed samples for PR #${pull_number}...`);
// Get changed files via API (no checkout needed)
const files = await github.paginate(
github.rest.pulls.listFiles,
{ owner, repo, pull_number, per_page: 100 }
);
const changedFiles = files.map(f => f.filename);
core.info(`Changed files (${changedFiles.length}):`);
changedFiles.forEach(f => core.info(` ${f}`));
const SAMPLE_ROOTS = [
'quickstarts/',
'demos/',
'application-workloads/',
'modules/',
'subscription-deployments/',
'managementgroup-deployments/',
'tenant-deployments/'
];
// Build a set of all changed file paths for quick lookup
const changedSet = new Set(changedFiles);
// Use the Git tree API to check file existence at the PR head
// Cache tree lookups to avoid redundant API calls
const treeCache = new Map();
async function dirContains(dirPath, filename) {
if (treeCache.has(dirPath)) {
return treeCache.get(dirPath).has(filename);
}
try {
// Get the tree for this directory at the PR head commit
const { data } = await github.rest.git.getTree({
owner, repo,
tree_sha: `${headSha}:${dirPath}`
});
const names = new Set(data.tree.map(e => e.path));
treeCache.set(dirPath, names);
return names.has(filename);
} catch {
treeCache.set(dirPath, new Set());
return false;
}
}
const seenDirs = new Set();
for (const changedFile of changedFiles) {
const matchedRoot = SAMPLE_ROOTS.find(r => changedFile.startsWith(r));
if (!matchedRoot) continue;
const relRoot = matchedRoot.replace(/\/$/, '');
let dir = path.posix.dirname(changedFile);
while (dir !== relRoot && dir !== '.') {
if (seenDirs.has(dir)) break;
// Check if metadata.json and README.md exist via Git tree API
const hasMeta = await dirContains(dir, 'metadata.json');
const hasReadme = await dirContains(dir, 'README.md');
if (hasMeta && hasReadme) {
seenDirs.add(dir);
break;
}
dir = path.posix.dirname(dir);
}
}
const samplesList = [...seenDirs];
const samplesJson = JSON.stringify(samplesList);
core.info(`Detected sample folders: ${samplesJson}`);
core.setOutput('samples_json', samplesJson);
// Build sparse-checkout paths: agent instructions + sample folders
const sparsePaths = ['.github/agents/'];
for (const s of samplesList) {
sparsePaths.push(s + '/');
}
core.setOutput('sparse_paths', sparsePaths.join('\n'));
core.info(`Sparse checkout paths:\n${sparsePaths.join('\n')}`);
# ── 3. Sparse checkout PR head (only agent files + sample folders) ──
- name: Checkout PR head (sparse)
uses: actions/checkout@v4
with:
repository: ${{ steps.pr.outputs.head_repo }}
ref: ${{ steps.pr.outputs.head_sha }}
fetch-depth: 1
sparse-checkout: ${{ steps.detect.outputs.sparse_paths }}
# ── 4. Add reaction to acknowledge the command ──────────────────────
- name: React to comment
uses: actions/github-script@v7
with:
script: |
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'eyes'
});
# ── 5. Run Microsoft Security DevOps (Template Analyzer, Checkov, Trivy, Terrascan) ──
- name: Run MSDO security scan
id: msdo
uses: microsoft/security-devops-action@latest
continue-on-error: true
with:
tools: templateanalyzer,checkov,trivy,terrascan
categories: IaC
# ── 6. Parse SARIF security findings ────────────────────────────────
- name: Parse SARIF findings
id: security
uses: actions/github-script@v7
env:
SARIF_FILE: ${{ steps.msdo.outputs.sarifFile }}
SAMPLES_JSON: ${{ steps.detect.outputs.samples_json }}
with:
script: |
const fs = require('fs');
const path = require('path');
const sarifPath = process.env.SARIF_FILE;
const samples = JSON.parse(process.env.SAMPLES_JSON || '[]');
const findings = [];
if (!sarifPath || !fs.existsSync(sarifPath)) {
core.warning('SARIF file not found – security scan may have failed.');
core.setOutput('findings_json', JSON.stringify(findings));
core.setOutput('scan_status', 'unavailable');
return;
}
try {
const sarif = JSON.parse(fs.readFileSync(sarifPath, 'utf8'));
const workspace = process.env.GITHUB_WORKSPACE;
for (const run of (sarif.runs || [])) {
const toolName = run.tool?.driver?.name || 'unknown';
const rulesById = {};
for (const rule of (run.tool?.driver?.rules || [])) {
rulesById[rule.id] = rule;
}
for (const result of (run.results || [])) {
const ruleId = result.ruleId || 'unknown';
const rule = rulesById[ruleId] || {};
const level = result.level || rule.defaultConfiguration?.level || 'warning';
// Map SARIF levels to severity
const severityMap = { error: 'high', warning: 'medium', note: 'low', none: 'info' };
const severity = severityMap[level] || 'medium';
const location = result.locations?.[0]?.physicalLocation;
let filePath = location?.artifactLocation?.uri || '';
// Normalize file path relative to workspace
if (filePath.startsWith('file://')) {
filePath = filePath.replace('file://', '');
}
if (workspace && filePath.startsWith(workspace)) {
filePath = filePath.substring(workspace.length + 1);
}
// Only include findings in changed sample folders
const inSample = samples.length === 0 ||
samples.some(s => filePath.startsWith(s + '/') || filePath === s);
if (!inSample) continue;
findings.push({
tool: toolName,
ruleId,
severity,
message: result.message?.text || rule.shortDescription?.text || ruleId,
file: filePath,
startLine: location?.region?.startLine || null,
helpUri: rule.helpUri || null
});
}
}
// Sort: high → medium → low (use ?? to handle 0 correctly)
const severityOrder = { high: 0, medium: 1, low: 2, info: 3 };
findings.sort((a, b) => (severityOrder[a.severity] ?? 3) - (severityOrder[b.severity] ?? 3));
core.info(`Parsed ${findings.length} security finding(s) in sample folders.`);
} catch (err) {
core.warning(`Failed to parse SARIF: ${err.message}`);
}
// Cap findings to avoid blowing up the context
const capped = findings.slice(0, 50);
core.setOutput('findings_json', JSON.stringify(capped));
core.setOutput('scan_status', 'completed');
# ── 7. Build bounded context and run Copilot inference ──────────────
- name: Checkout trusted summarizer assets
uses: actions/checkout@v4
with:
repository: ${{ github.repository }}
ref: ${{ github.sha }}
fetch-depth: 1
path: .trusted-summary
sparse-checkout: |
.github/agents/summarizer.agent.md
.github/scripts/build-summary-prompt.cjs
sparse-checkout-cone-mode: false
- name: Prepare summary prompt
id: prompt
uses: actions/github-script@v7
env:
SAMPLES_JSON: ${{ steps.detect.outputs.samples_json }}
SECURITY_FINDINGS_JSON: ${{ steps.security.outputs.findings_json }}
SCAN_STATUS: ${{ steps.security.outputs.scan_status }}
with:
script: |
const fs = require('fs');
const path = require('path');
const { buildSummaryPrompt } = require(path.join(
process.env.GITHUB_WORKSPACE,
'.trusted-summary',
'.github',
'scripts',
'build-summary-prompt.cjs'
));
const owner = context.repo.owner;
const repo = context.repo.repo;
const pull_number = context.issue.number;
const samples = JSON.parse(process.env.SAMPLES_JSON || '[]');
const securityFindings = JSON.parse(
process.env.SECURITY_FINDINGS_JSON || '[]'
);
const prData = await github.rest.pulls.get({
owner, repo, pull_number
});
const files = await github.paginate(
github.rest.pulls.listFiles,
{ owner, repo, pull_number, per_page: 100 }
);
const changedFiles = files.map(file => file.filename);
const MAX_DIFF_CHARS = 2000;
const diffResponse = await github.rest.pulls.get({
owner, repo, pull_number,
mediaType: { format: 'diff' }
});
const fullDiff = typeof diffResponse.data === 'string'
? diffResponse.data
: '';
const diffExcerpt = fullDiff.length > MAX_DIFF_CHARS
? `${fullDiff.substring(0, MAX_DIFF_CHARS)}\n... (truncated)`
: fullDiff;
const prompt = buildSummaryPrompt({
workspaceRoot: process.env.GITHUB_WORKSPACE,
pullNumber: pull_number,
pullTitle: prData.data.title,
samples,
changedFiles,
diffExcerpt,
scanStatus: process.env.SCAN_STATUS || 'unavailable',
securityFindings
});
const promptFile = path.join(
process.env.RUNNER_TEMP,
'quickstart-summary-prompt.txt'
);
fs.writeFileSync(promptFile, prompt, 'utf8');
core.info(`Prepared bounded summary prompt (${Buffer.byteLength(prompt)} bytes).`);
core.setOutput('prompt_file', promptFile);
- name: Set up Node.js for Copilot CLI
uses: actions/setup-node@v6
with:
node-version: 24
- name: Install Copilot CLI
shell: bash
run: npm install --global @github/copilot@1.0.78
- name: Run Copilot inference
id: inference
continue-on-error: true
uses: actions/ai-inference@v1
env:
GITHUB_TOKEN: ${{ github.token }}
with:
provider: copilot
token: ${{ github.token }}
model: gpt-4.1
prompt-file: ${{ steps.prompt.outputs.prompt_file }}
system-prompt-file: .trusted-summary/.github/agents/summarizer.agent.md
# ── 8. Post the summary when inference succeeds ────────────────────
- name: Generate and post summary
uses: actions/github-script@v7
env:
INFERENCE_OUTCOME: ${{ steps.inference.outcome }}
INFERENCE_RESPONSE_FILE: ${{ steps.inference.outputs.response-file }}
with:
script: |
const fs = require('fs');
const outcome = process.env.INFERENCE_OUTCOME;
const responseFile = process.env.INFERENCE_RESPONSE_FILE;
if (outcome !== 'success' || !responseFile || !fs.existsSync(responseFile)) {
core.warning(
'Copilot inference was unavailable; skipping the informational PR summary.'
);
await core.summary
.addHeading('Quickstart sample summary')
.addRaw('Copilot inference was unavailable. Deployment validation was not affected.')
.write();
try {
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'confused'
});
} catch (reactionError) {
core.warning(`Could not add inference-failure reaction: ${reactionError.message}`);
}
return;
}
const summary = fs.readFileSync(responseFile, 'utf8').trim();
if (!summary) {
core.warning(
'Copilot inference returned an empty response; skipping the informational PR summary.'
);
await core.summary
.addHeading('Quickstart sample summary')
.addRaw('Copilot inference returned an empty response. Deployment validation was not affected.')
.write();
return;
}
const owner = context.repo.owner;
const repo = context.repo.repo;
const pull_number = context.issue.number;
const marker = '<!-- quickstart-summarizer-bot -->';
const commentBody = `${marker}\n## 🤖 Quickstart Sample Summary\n\n${summary}\n\n---\n*Generated by the quickstart summarizer agent (v3 · GitHub Copilot + MSDO security) · triggered by /validate*`;
const comments = await github.paginate(
github.rest.issues.listComments,
{ owner, repo, issue_number: pull_number, per_page: 100 }
);
const existing = comments.find(
comment => comment.body && comment.body.includes(marker)
);
if (existing) {
await github.rest.issues.updateComment({
owner, repo,
comment_id: existing.id,
body: commentBody
});
core.info(`Updated existing summary comment (id=${existing.id}).`);
} else {
await github.rest.issues.createComment({
owner, repo,
issue_number: pull_number,
body: commentBody
});
core.info('Created new summary comment on PR.');
}
await github.rest.reactions.createForIssueComment({
owner, repo,
comment_id: context.payload.comment.id,
content: 'rocket'
});
selected-pipeline:
name: Validate ARM Deployments via ADX
runs-on: ubuntu-latest
needs: [gate]
environment: adx-readonly
# Run if the gate confirmed validate-samples.yml succeeded for the PR HEAD
# SHA, regardless of how `summarize` concluded. (`summarize` is a separate
# informational job; its failure or cancellation must not skip the
# deployment validation that gates merge.)
if: >-
!cancelled() &&
needs.gate.result == 'success' &&
github.event.issue.pull_request &&
startsWith(github.event.comment.body, '/validate')
permissions:
# `contents: write` is required by the `Commit generated azuredeploy.json
# to PR head branch` step at the end of this job, which (for same-repo
# PRs only) pushes the generated ARM JSON onto the PR's head branch so
# the merge naturally carries it into master. Fork PRs are handled by
# the post-merge `commit-generated-on-merge` job's auto-PR fallback.
contents: write
pull-requests: read
issues: read
id-token: write
actions: read
# Job-level outputs consumed by the `report-check` job to map this job's
# result to a GitHub Check Run conclusion.
outputs:
skip: ${{ steps.preflight.outputs.skip }}
sample_count: ${{ steps.preflight.outputs.sample_count }}
steps:
- name: Check commenter permission (basic)
shell: bash
run: |
set -euo pipefail
echo "Comment author association: ${{ github.event.comment.author_association }}"
case "${{ github.event.comment.author_association }}" in
MEMBER|OWNER|COLLABORATOR) ;;
*)
echo "Not authorized to /validate"
exit 1
;;
esac
- name: Get PR number
id: pr
shell: bash
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.issue.number }}
run: |
set -euo pipefail
echo "number=${PR_NUMBER}" >> "$GITHUB_OUTPUT"
# Resolve head SHA so the artifact uploaded later in this job can be
# uniquely named per PR head commit and located by the merge job.
# Also resolve head_repo and head_ref so the path-A push step at the
# end of this job can decide whether the PR is from the same repo
# (push to head branch) or a fork (skip; merge job will auto-PR).
PR_JSON=$(gh api "/repos/${REPO}/pulls/${PR_NUMBER}")
HEAD_SHA=$(echo "${PR_JSON}" | jq -r '.head.sha')
HEAD_REF=$(echo "${PR_JSON}" | jq -r '.head.ref')
HEAD_REPO=$(echo "${PR_JSON}" | jq -r '.head.repo.full_name')
echo "head_sha=${HEAD_SHA}" >> "$GITHUB_OUTPUT"
echo "head_ref=${HEAD_REF}" >> "$GITHUB_OUTPUT"
echo "head_repo=${HEAD_REPO}" >> "$GITHUB_OUTPUT"
# ── Preflight: classify whether this PR contains deployment-affecting
# changes, and if so, in how many distinct sample folders.
#
# Outputs:
# skip - 'true' if the PR has NO deploy-affecting changes;
# downstream ADX steps are then skipped and the
# `report-check` job publishes a `success` check with
# "Auto-passed: no deployment-affecting changes."
# sample_count - number of distinct sample folders containing a
# deploy-affecting change.
#
# Multi-sample deployable PRs fail this step explicitly: the existing
# ADX validation only supports a single changed metadata.json/sample
# per PR. Authors are told to split the PR.
- name: Preflight – classify deploy-affecting changes
id: preflight
uses: actions/github-script@v7
with:
script: |
const owner = context.repo.owner;
const repo = context.repo.repo;
const pull_number = parseInt('${{ steps.pr.outputs.number }}', 10);
const prData = await github.rest.pulls.get({ owner, repo, pull_number });
const headSha = prData.data.head.sha;
const files = await github.paginate(
github.rest.pulls.listFiles,
{ owner, repo, pull_number, per_page: 100 }
);
const SAMPLE_ROOTS = [
'quickstarts/',
'demos/',
'application-workloads/',
'modules/',
'subscription-deployments/',
'managementgroup-deployments/',
'tenant-deployments/'
];
// Predicate: does this changed-file path affect a deployment?
// Conservative: unknown paths under a sample root count as
// deploy-affecting so we don't accidentally auto-pass a real
// template change.
function isDeployAffecting(filename) {
const matchedRoot = SAMPLE_ROOTS.find(r => filename.startsWith(r));
if (!matchedRoot) return false;
const lower = filename.toLowerCase();
const base = lower.split('/').pop();
// Always non-deploy-affecting (sample metadata / docs / images).
if (base === 'metadata.json') return false;
if (base === 'readme.md' || base === 'contributing.md') return false;
if (lower.endsWith('.md')) return false;
if (lower.endsWith('.png') || lower.endsWith('.jpg') ||
lower.endsWith('.jpeg') || lower.endsWith('.gif') ||
lower.endsWith('.svg') || lower.endsWith('.ico')) return false;
if (base === '.gitignore') return false;
// Always deploy-affecting (templates, params, scripts, prereqs).
if (lower.endsWith('.bicep') || lower.endsWith('.bicepparam')) return true;
if (lower.endsWith('.json')) return true;
if (lower.endsWith('.ps1') || lower.endsWith('.sh')) return true;
if (lower.includes('/prereqs/')) return true;
// Conservative default for anything else under a sample root.
return true;
}
const deployFiles = files
.filter(f => isDeployAffecting(f.filename));
core.info(`Total changed files: ${files.length}`);
core.info(`Deploy-affecting files: ${deployFiles.length}`);
for (const f of deployFiles) core.info(` ${f.status}\t${f.filename}`);
if (deployFiles.length === 0) {
core.info('No deployment-affecting changes detected — skipping ADX validation.');
core.setOutput('skip', 'true');
core.setOutput('sample_count', '0');
return;
}
// Resolve each deploy-affecting file to its sample folder by
// walking up the directory tree until we find a dir containing
// both metadata.json and README.md (mirrors validate-samples.yml).
const treeCache = new Map();
async function dirContains(dirPath, filename) {
if (treeCache.has(dirPath)) {
return treeCache.get(dirPath).has(filename);
}
try {
const { data } = await github.rest.git.getTree({
owner, repo, tree_sha: `${headSha}:${dirPath}`
});
const names = new Set(data.tree.map(e => e.path));
treeCache.set(dirPath, names);
return names.has(filename);
} catch {
treeCache.set(dirPath, new Set());
return false;
}
}
const sampleFolders = new Set();
for (const f of deployFiles) {
const root = SAMPLE_ROOTS.find(r => f.filename.startsWith(r));
const relRoot = root.replace(/\/$/, '');
let dir = f.filename.split('/').slice(0, -1).join('/');
while (dir && dir !== relRoot && dir !== '.') {
if (sampleFolders.has(dir)) break;
const hasMeta = await dirContains(dir, 'metadata.json');
const hasReadme = await dirContains(dir, 'README.md');
if (hasMeta && hasReadme) {
sampleFolders.add(dir);
break;
}
dir = dir.split('/').slice(0, -1).join('/');
}
}
const folderList = [...sampleFolders];
core.info(`Distinct sample folders touched: ${folderList.length}`);
for (const d of folderList) core.info(` ${d}`);
core.setOutput('sample_count', String(folderList.length));
core.setOutput('skip', 'false');
if (folderList.length > 1) {
core.setFailed(
`Multi-sample deployable PR detected (${folderList.length} sample folders). ` +
`The ADX validation pipeline only supports a single changed sample per PR. ` +
`Please split deployable changes across multiple PRs (one sample per PR).`
);
}
- name: Safeguard – block protected-file edits by non MEMBER/OWNER
id: safeguard
uses: actions/github-script@v7
with:
script: |
const allowed = new Set(["MEMBER", "OWNER"]);
const pull_number = parseInt("${{ steps.pr.outputs.number }}", 10);
const owner = context.repo.owner;
const repo = context.repo.repo;
const [prData, files] = await Promise.all([
github.rest.pulls.get({ owner, repo, pull_number }),
github.paginate(
github.rest.pulls.listFiles,
{ owner, repo, pull_number, per_page: 100 }
)
]);
const assoc = prData.data.author_association;
// Any file executed with the privileged token/OIDC of this
// workflow (via checkout of PR HEAD) must be listed here so
// fork PRs cannot substitute a malicious version. Directory
// entries end with "/" and match by prefix; file entries
// match exactly. See ICM 31000000643564.
const protectedDirs = [
".github/workflows/",
".github/scripts/",
".github/actions/",
".github/agents/",
];
const protectedFiles = [
".github/CODEOWNERS",
];
const isProtected = (name) =>
protectedDirs.some(d => name.startsWith(d)) ||
protectedFiles.includes(name);
const touchedNames = files.map(f => f.filename).filter(isProtected);
const touched = touchedNames.length > 0;
core.info(`PR author_association=${assoc}; protected files touched=${touched}`);
// Pin the head SHA observed here so the subsequent PR-HEAD
// checkout resolves to the same commit the safeguard just
// evaluated. Closes the TOCTOU window on refs/pull/N/head.
const headSha = prData.data.head.sha;
core.setOutput("head_sha", headSha);
core.info(`Pinned PR head SHA for downstream checkout: ${headSha}`);
if (touched && !allowed.has(assoc)) {
core.setFailed(
`Blocked: protected file(s) ${touchedNames.join(', ')} modified by PR author with ` +