Repository navigation
Expand file tree
/
Copy pathsmoke-test.js
More file actions
4221 lines (3769 loc) · 194 KB
/
Copy pathsmoke-test.js
File metadata and controls
4221 lines (3769 loc) · 194 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
/**
* Smoke Test for safe-settings
*
* Usage:
* 1. Ensure `.env` is configured with GH_ORG, APP_ID, PRIVATE_KEY, WEBHOOK_PROXY_URL, etc.
* 2. Set GH_TOKEN env var to a fine-grained PAT with org admin + repo permissions.
* This is required for drift-remediation tests (Phases 2 & 3) so that
* changes appear as a human (not Bot) and trigger safe-settings webhooks.
* 3. Run: `node smoke-test.js`
* Add --interactive to pause after each phase for manual validation.
* Set SMOKE_VERBOSE=1 for live safe-settings logs.
* Optional (Phase 16 — ruleset name resolution): set SMOKE_NR_USER to a
* username and/or SMOKE_NR_APP_SLUG to an installed GitHub App slug to also
* exercise User and Integration bypass-actor name resolution.
*
* Auth:
* - Octokit (GitHub App): APP_ID + PRIVATE_KEY from .env — used for most operations.
* - gh CLI (user PAT): GH_TOKEN env var — used for drift tests only.
*/
const { execSync, spawn } = require('child_process')
const fs = require('fs')
const path = require('path')
const readline = require('readline')
// ─── Configuration ───────────────────────────────────────────────────────────
function loadEnv () {
const envPath = path.join(__dirname, '.env')
if (!fs.existsSync(envPath)) throw new Error('.env file not found')
const lines = fs.readFileSync(envPath, 'utf8').split('\n')
let currentKey = null
let currentValue = ''
let inMultiline = false
for (const line of lines) {
if (inMultiline) {
currentValue += '\n' + line
if (line.includes('"') || line.includes("'")) {
const val = currentValue.replace(/^["']|["']$/g, '')
// Like dotenv: .env values don't override existing env vars
if (!(currentKey in process.env)) process.env[currentKey] = val
inMultiline = false
}
continue
}
const trimmed = line.trim()
if (!trimmed || trimmed.startsWith('#')) continue
const eqIdx = trimmed.indexOf('=')
if (eqIdx === -1) continue
currentKey = trimmed.slice(0, eqIdx).trim()
currentValue = trimmed.slice(eqIdx + 1).trim()
if ((currentValue.startsWith('"') && !currentValue.endsWith('"')) ||
(currentValue.startsWith("'") && !currentValue.endsWith("'"))) {
inMultiline = true
continue
}
const val = currentValue.replace(/^["']|["']$/g, '')
if (!(currentKey in process.env)) process.env[currentKey] = val
}
}
loadEnv()
const ORG = process.env.GH_ORG || 'decyjphr-emu'
const ADMIN_REPO = process.env.ADMIN_REPO || 'admin'
const CONFIG_PATH = process.env.CONFIG_PATH || '.github'
const APP_ID = process.env.APP_ID
const PRIVATE_KEY = (process.env.PRIVATE_KEY || '').replace(/\\n/g, '\n')
const TEST_REPOS = ['test', 'demo-repo-service1', 'demo-repo-service2', 'combined-settings-repo', 'smoke-team-filter']
const TEST_TEAMS = ['AD-GRP-PAYMENTS-PLATFORM-OWNERS', 'awesometeam-a-approvers', 'jefeish-edj-test']
// Teams exercised by the team include/exclude filter phase (Phase 18).
const SMOKE_FILTER_REPO = 'smoke-team-filter'
const SMOKE_FILTER_TEAMS = ['smoke-filter-included', 'smoke-filter-excluded', 'smoke-filter-nomatch']
// Principals created on demand for the ruleset name-resolution phase (Phase 16)
const SMOKE_NR_TEAM = 'safe-settings-smoke-nr-team'
const SMOKE_NR_ROLE = 'safe-settings-smoke-nr-role'
const POLL_INTERVAL_MS = 5000
const MAX_POLL_MS = 120000
const WEBHOOK_SETTLE_MS = 15000
// Fine-grained PAT for drift tests (must appear as a human, not Bot)
const GH_TOKEN = process.env.GH_TOKEN || ''
// ─── App installation plugin config (Phase 17) ───────────────────────────────
// Enterprise slug — required for the app_installations plugin, which manages
// GitHub App installation repository access via the Enterprise organization
// installations API. Read from GH_ENTERPRISE (same var safe-settings uses).
const GH_ENTERPRISE = process.env.GH_ENTERPRISE || ''
// One or more enterprise-level GitHub App slugs to exercise the plugin.
// ONE app is sufficient for full lifecycle coverage; providing a second app
// (comma-separated) additionally verifies that changes to one app's
// installation do not affect another's. Pre-create these as enterprise GitHub
// Apps and install them on the org (creation requires a human).
// SMOKE_APP_SLUGS=app-one,app-two (or singular SMOKE_APP_SLUG=app-one)
const APP_SLUGS = (process.env.SMOKE_APP_SLUGS || process.env.SMOKE_APP_SLUG || '')
.split(',').map(s => s.trim()).filter(Boolean)
// Dedicated repos created/managed by the app_installations phase.
const APP_TEST_REPOS = ['smoke-app-repo-1', 'smoke-app-repo-2', 'smoke-app-repo-3']
// Enterprise org installations API version (matches lib/appOctokitClient.js).
const APPS_API_VERSION = '2026-03-10'
// Interactive mode: pause after each phase for manual validation
// Accepts --interactive flag or bare positional "interactive" word.
const INTERACTIVE = process.argv.includes('--interactive') || process.argv.slice(2).includes('interactive')
// Phase filter: supports single, comma-separated, or range values.
// --phase 3 → only phase 3
// --phase 1,2,3 → phases 1, 2, and 3
// --phase 1-3 → phases 1 through 3
// npm run smoke-test:phase -- 1-3 interactive
const PHASE_ARG_IDX = process.argv.indexOf('--phase')
const _parsePhaseSet = (raw) => {
if (!raw) return null
const nums = new Set()
for (const part of raw.split(',')) {
const range = part.match(/^(\d+)-(\d+)$/)
if (range) {
const lo = parseInt(range[1], 10)
const hi = parseInt(range[2], 10)
for (let i = lo; i <= hi; i++) nums.add(i)
} else if (/^\d+$/.test(part.trim())) {
nums.add(parseInt(part.trim(), 10))
}
}
return nums.size > 0 ? nums : null
}
const ONLY_PHASES = PHASE_ARG_IDX !== -1
? _parsePhaseSet(process.argv[PHASE_ARG_IDX + 1])
: (() => {
// Accept bare positional phase spec (e.g. "3" or "1-3" or "1,2,3")
const positional = process.argv.slice(2).find(a => !a.startsWith('--') && /^[\d,\-]+$/.test(a) && !/^-\d/.test(a))
return positional !== undefined ? _parsePhaseSet(positional) : null
})()
class InteractiveExit extends Error {
constructor (action) {
super(`interactive:${action}`)
this.action = action
}
}
// ─── Octokit client (initialized in main) ────────────────────────────────────
let octokit = null
let orgInstallation = null
// Enterprise-installation-authenticated client (Phase 17). Null when the app
// is not installed on the enterprise or GH_ENTERPRISE is unset.
let entOctokit = null
// Snapshot of each managed app's installation state, captured at the start of
// Phase 17 and restored during teardown so shared apps are left untouched.
const appInstallSnapshot = {}
// ─── Helpers ─────────────────────────────────────────────────────────────────
let passCount = 0
let failCount = 0
const failures = []
function log (msg) { console.log(`\x1b[36m[smoke]\x1b[0m ${msg}`) }
function logPass (msg) { passCount++; console.log(`\x1b[32m ✓ ${msg}\x1b[0m`) }
function logFail (msg) { failCount++; failures.push(msg); console.log(`\x1b[31m ✗ ${msg}\x1b[0m`) }
function logPhase (msg) { console.log(`\n\x1b[35m═══ ${msg} ═══\x1b[0m`) }
function assert (condition, msg) {
if (condition) logPass(msg)
else logFail(msg)
return condition
}
function sleep (ms) { return new Promise(resolve => setTimeout(resolve, ms)) }
async function poll (fn, { timeout = MAX_POLL_MS, interval = POLL_INTERVAL_MS, desc = 'condition' } = {}) {
const start = Date.now()
while (Date.now() - start < timeout) {
const result = await fn()
if (result) return result
await sleep(interval)
}
log(` ⚠ Timed out waiting for ${desc}`)
return null
}
// ─── Interactive mode ─────────────────────────────────────────────────────────
let skipNext = false
async function pause (phaseName) {
return new Promise((resolve) => {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
process.stdout.write(
`\n\x1b[33m[interactive] "${phaseName}" complete.\x1b[0m\n` +
` \x1b[90mPress Enter to continue, 's' skip next, 'q' quit+teardown, 'a' abort: \x1b[0m`
)
rl.once('line', (answer) => {
const input = answer.trim().toLowerCase()
if (input === 's') resolve('skip')
else if (input === 'q') resolve('quit')
else if (input === 'a') resolve('abort')
else resolve('continue')
rl.close()
})
rl.once('close', () => resolve('continue'))
})
}
async function runPhase (label, fn) {
if (skipNext) {
log(`\x1b[33m[interactive] Skipping ${label}\x1b[0m`)
skipNext = false
return 'skipped'
}
await fn()
if (!INTERACTIVE) return 'continue'
const action = await pause(label)
if (action === 'skip') skipNext = true
return action
}
async function confirmMerge (owner, repo, prNumber) {
return new Promise((resolve) => {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
process.stdout.write(
`\n\x1b[33m[interactive] PR #${prNumber} is ready to merge.\x1b[0m\n` +
` \x1b[90mPress Enter to merge, 'c' to close PR, 'q' quit+teardown, 'a' abort: \x1b[0m`
)
rl.once('line', (answer) => {
const input = answer.trim().toLowerCase()
if (input === 'c') resolve('close')
else if (input === 'q') resolve('quit')
else if (input === 'a') resolve('abort')
else resolve('merge')
rl.close()
})
rl.once('close', () => resolve('merge'))
})
}
async function safeMerge (owner, repo, prNumber) {
if (INTERACTIVE) {
const action = await confirmMerge(owner, repo, prNumber)
if (action !== 'merge') {
try { await octokit.rest.pulls.update({ owner, repo, pull_number: prNumber, state: 'closed' }) } catch { /* ok */ }
log(`\x1b[33m[interactive] PR #${prNumber} closed.\x1b[0m`)
if (action === 'quit' || action === 'abort') throw new InteractiveExit(action)
return false
}
}
log('Merging PR...')
await mergePR(owner, repo, prNumber)
return true
}
// ─── GitHub API helpers ──────────────────────────────────────────────────────
async function getDefaultBranch () {
const { data } = await octokit.rest.repos.get({ owner: ORG, repo: ADMIN_REPO })
return data.default_branch || 'main'
}
async function createOrUpdateFile (owner, repo, filePath, content, branch, message) {
const b64 = Buffer.from(content).toString('base64')
let sha = null
try {
const { data } = await octokit.rest.repos.getContent({ owner, repo, path: filePath, ref: branch })
sha = data.sha
} catch { /* file doesn't exist */ }
const params = { owner, repo, path: filePath, message, content: b64, branch }
if (sha) params.sha = sha
return (await octokit.rest.repos.createOrUpdateFileContents(params)).data
}
async function deleteFile (owner, repo, filePath, branch, message) {
try {
const { data } = await octokit.rest.repos.getContent({ owner, repo, path: filePath, ref: branch })
await octokit.rest.repos.deleteFile({ owner, repo, path: filePath, message, sha: data.sha, branch })
} catch { /* file doesn't exist */ }
}
async function cleanDirectory (owner, repo, dirPath) {
const branch = await getDefaultBranch()
try {
const { data } = await octokit.rest.repos.getContent({ owner, repo, path: dirPath, ref: branch })
if (Array.isArray(data)) {
for (const file of data) {
if (file.type === 'file') {
await deleteFile(owner, repo, file.path, branch, `Clean up ${file.path}`)
}
}
}
} catch { /* directory doesn't exist */ }
}
async function createBranch (owner, repo, branchName) {
const defaultBranch = await getDefaultBranch()
const { data: ref } = await octokit.rest.git.getRef({ owner, repo, ref: `heads/${defaultBranch}` })
await octokit.rest.git.createRef({ owner, repo, ref: `refs/heads/${branchName}`, sha: ref.object.sha })
}
async function deleteBranch (owner, repo, branch) {
try { await octokit.rest.git.deleteRef({ owner, repo, ref: `heads/${branch}` }) } catch { /* ok */ }
}
async function createPR (owner, repo, title, head, base) {
const { data } = await octokit.rest.pulls.create({ owner, repo, title, head, base, body: `Smoke test: ${title}` })
log(` Created PR #${data.number}`)
return data
}
async function mergePR (owner, repo, prNumber) {
return (await octokit.rest.pulls.merge({ owner, repo, pull_number: prNumber, merge_method: 'merge' })).data
}
async function deleteRepo (owner, repo) {
try { await octokit.rest.repos.delete({ owner, repo }) } catch { /* ok */ }
}
async function deleteTeam (org, teamSlug) {
try { await octokit.rest.teams.deleteInOrg({ org, team_slug: teamSlug }) } catch { /* ok */ }
}
async function ensureTeam (org, name) {
try {
const { data } = await octokit.rest.teams.getByName({ org, team_slug: name })
return data
} catch { /* team doesn't exist yet */ }
try {
const { data } = await octokit.rest.teams.create({ org, name, privacy: 'closed' })
return data
} catch { return null }
}
async function getCustomRepositoryRole (org, name) {
try {
const { data } = await octokit.request('GET /orgs/{org}/custom-repository-roles', { org })
return (data.custom_roles || []).find(role => role.name === name) || null
} catch { return null }
}
async function createCustomRepositoryRole (org, name, description) {
const existing = await getCustomRepositoryRole(org, name)
if (existing) return existing
return (await octokit.request('POST /orgs/{org}/custom-repository-roles', {
org,
name,
description,
base_role: 'read',
permissions: ['delete_alerts_code_scanning']
})).data
}
async function deleteCustomRepositoryRole (org, name) {
const role = await getCustomRepositoryRole(org, name)
if (!role) return
await octokit.request('DELETE /orgs/{org}/custom-repository-roles/{role_id}', { org, role_id: role.id })
}
async function getOrgRuleset (org, name) {
try {
const { data: rulesets } = await octokit.request('GET /orgs/{org}/rulesets', { org })
return rulesets.find(ruleset => ruleset.name === name) || null
} catch { return null }
}
async function getRepoRuleset (owner, repo, name) {
try {
const { data: rulesets } = await octokit.request('GET /repos/{owner}/{repo}/rulesets', { owner, repo })
return rulesets.find(ruleset => ruleset.name === name) || null
} catch { return null }
}
async function getRepoRulesetDetails (owner, repo, rulesetId) {
try {
const { data } = await octokit.request('GET /repos/{owner}/{repo}/rulesets/{ruleset_id}', { owner, repo, ruleset_id: rulesetId })
return data
} catch { return null }
}
async function setRepoCustomProperty (owner, repo, propertyName, value) {
await octokit.request('PATCH /repos/{owner}/{repo}/properties/values', {
owner,
repo,
properties: [
{ property_name: propertyName, value }
]
})
}
async function createOrgRuleset (org, name) {
const existing = await getOrgRuleset(org, name)
if (existing) return existing
return (await octokit.request('POST /orgs/{org}/rulesets', {
org,
name,
target: 'repository',
source_type: 'Organization',
source: org,
enforcement: 'disabled',
conditions: {
repository_property: {
exclude: [],
include: [
{ name: 'visibility', source: 'system', property_values: ['private'] }
]
}
},
rules: [{ type: 'repository_delete' }]
})).data
}
async function deleteOrgRuleset (org, name) {
const ruleset = await getOrgRuleset(org, name)
if (!ruleset) return
await octokit.request('DELETE /orgs/{org}/rulesets/{ruleset_id}', { org, ruleset_id: ruleset.id })
}
async function waitForCheckRun (owner, repo, sha, { timeout = MAX_POLL_MS } = {}) {
return poll(async () => {
const { data } = await octokit.rest.checks.listForRef({ owner, repo, ref: sha })
const cr = data.check_runs.find(c => c.name === 'Safe-setting validator')
return (cr && cr.status === 'completed') ? cr : null
}, { timeout, desc: 'check run to complete' })
}
// Ensure a repository exists in the org (create it directly if missing).
async function ensureRepo (name) {
try {
await octokit.rest.repos.get({ owner: ORG, repo: name })
return
} catch { /* needs creation */ }
try {
await octokit.rest.repos.createInOrg({ org: ORG, name, private: true, auto_init: true })
await poll(async () => {
try { await octokit.rest.repos.get({ owner: ORG, repo: name }); return true } catch { return null }
}, { desc: `repo ${name} to be created`, timeout: 30000 })
} catch (e) { log(` Could not create repo ${name}: ${e.message}`) }
}
// ─── Enterprise organization installations API helpers (Phase 17) ────────────
async function listOrgAppInstallations () {
const options = entOctokit.request.endpoint.merge(
'GET /enterprises/{enterprise}/apps/organizations/{org}/installations',
{ enterprise: GH_ENTERPRISE, org: ORG, headers: { 'X-GitHub-Api-Version': APPS_API_VERSION } }
)
return entOctokit.paginate(options)
}
async function getAppInstallation (appSlug) {
const installations = await listOrgAppInstallations()
return installations.find(i => i.app_slug === appSlug) || null
}
async function listInstallationRepoNames (installationId) {
const options = entOctokit.request.endpoint.merge(
'GET /enterprises/{enterprise}/apps/organizations/{org}/installations/{installation_id}/repositories',
{ enterprise: GH_ENTERPRISE, org: ORG, installation_id: installationId, headers: { 'X-GitHub-Api-Version': APPS_API_VERSION } }
)
const repos = await entOctokit.paginate(options)
return repos.map(r => r.name)
}
async function setInstallationSelection (installationId, selection, repositories) {
const params = {
enterprise: GH_ENTERPRISE,
org: ORG,
installation_id: installationId,
repository_selection: selection,
headers: { 'X-GitHub-Api-Version': APPS_API_VERSION }
}
if (selection === 'selected') params.repositories = repositories || []
await entOctokit.request('PATCH /enterprises/{enterprise}/apps/organizations/{org}/installations/{installation_id}/repositories', params)
}
async function addInstallationRepos (installationId, repositoryNames) {
await entOctokit.request('PATCH /enterprises/{enterprise}/apps/organizations/{org}/installations/{installation_id}/repositories/add', {
enterprise: GH_ENTERPRISE,
org: ORG,
installation_id: installationId,
repositories: repositoryNames,
headers: { 'X-GitHub-Api-Version': APPS_API_VERSION }
})
}
// ─── Safe-settings process management ────────────────────────────────────────
let ssProcess = null
function startSafeSettings () {
log('Starting safe-settings...')
ssProcess = spawn('npm', ['start'], {
cwd: __dirname,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe']
})
ssProcess.stdout.on('data', (d) => { if (process.env.SMOKE_VERBOSE) process.stdout.write(d) })
ssProcess.stderr.on('data', (d) => { if (process.env.SMOKE_VERBOSE) process.stderr.write(d) })
ssProcess.on('exit', (code) => { log(`safe-settings exited with code ${code}`) })
}
function stopSafeSettings () {
if (ssProcess) {
log('Stopping safe-settings...')
ssProcess.kill('SIGTERM')
ssProcess = null
}
}
// ─── YAML Configs ────────────────────────────────────────────────────────────
const REPO_TEST_YML = `repository:
name: test
description: Demo repository created via safe-settings
private: true
auto_init: true
force_create: true
has_issues: true
has_projects: false
has_wiki: false
delete_branch_on_merge: true
allow_squash_merge: true
allow_merge_commit: false
allow_rebase_merge: true
teams:
- name: expert-services-developers
permission: push
custom_properties:
- property_name: ent-ownership
value: expert-services
- property_name: ent-supervisory-org
value: expert-services
rulesets:
- name: synk
target: branch
enforcement: disabled
bypass_actors:
- actor_id: 1
actor_type: OrganizationAdmin
bypass_mode: pull_request
conditions:
ref_name:
include: ["~DEFAULT_BRANCH"]
exclude: ["refs/heads/oldmaster"]
rules:
- type: creation
- type: update
- type: deletion
- type: required_linear_history
- type: required_signatures
- type: pull_request
parameters:
dismiss_stale_reviews_on_push: true
require_code_owner_review: true
require_last_push_approval: true
required_approving_review_count: 2
required_review_thread_resolution: true
- type: commit_message_pattern
parameters:
name: test commit_message_pattern
negate: true
operator: starts_with
pattern: skip*
- type: commit_author_email_pattern
parameters:
name: test commit_author_email_pattern
negate: false
operator: regex
pattern: "^.*@example.com$"
- type: committer_email_pattern
parameters:
name: test committer_email_pattern
negate: false
operator: regex
pattern: "^.*@example.com$"
- type: branch_name_pattern
parameters:
name: test branch_name_pattern
negate: false
operator: regex
pattern: ".*\\\\/.*"
- name: Prevent merges when new SONAR alerts are introduced
target: branch
enforcement: active
conditions:
ref_name:
include:
- "~DEFAULT_BRANCH"
exclude: []
bypass_actors:
- actor_type: OrganizationAdmin
bypass_mode: always
rules:
- type: code_scanning
parameters:
code_scanning_tools:
- tool: Sonar
alerts_threshold: none
security_alerts_threshold: medium_or_higher
`
const REPO_TEST_OTHER_OWNERSHIP_YML = REPO_TEST_YML.replace(
' - property_name: ent-ownership\n value: expert-services',
' - property_name: ent-ownership\n value: other-services'
)
const REPO_DEMO_SERVICE1_YML = `# Safe-Settings Configuration
repository:
name: demo-repo-service1
description: "Repository 2 sample"
visibility: private
default_branch: main
homepage: ""
auto_init: true
force_create: true
delete_branch_on_merge: true
archived: false
topics:
- topic1
- topic2
teams:
- name: AD-GRP-PAYMENTS-PLATFORM-OWNERS
permission: admin
- name: awesometeam-a-approvers
permission: push
- name: expert-services-developers
permission: push
branches:
- name: main
protection:
required_status_checks:
strict: true
contexts: []
required_pull_request_reviews:
required_approving_review_count: 2
dismiss_stale_reviews: false
require_code_owner_reviews: true
require_last_push_approval: false
bypass_pull_request_allowances:
apps: []
users: []
teams: []
dismissal_restrictions:
users: []
teams: []
enforce_admins: true
restrictions:
apps: []
users: []
teams: []
- name: develop
protection:
required_status_checks:
strict: true
contexts: []
required_pull_request_reviews:
required_approving_review_count: 1
dismiss_stale_reviews: false
require_code_owner_reviews: true
require_last_push_approval: false
bypass_pull_request_allowances:
apps: []
users: []
teams: []
dismissal_restrictions:
users: []
teams: []
enforce_admins: true
restrictions:
apps: []
users: []
teams: []
`
const SUBORG_EXPERT_SERVICES_YML = `suborgteams:
- expert-services-developers
rulesets:
- name: Protect release and production branches
target: branch
enforcement: active
conditions:
ref_name:
include:
- refs/heads/release/*
- refs/heads/production
exclude: []
bypass_actors:
- actor_type: OrganizationAdmin
bypass_mode: always
rules:
- type: creation
- type: pull_request
parameters:
required_approving_review_count: 1
dismiss_stale_reviews_on_push: false
require_code_owner_review: false
require_last_push_approval: false
required_review_thread_resolution: false
allowed_merge_methods:
- merge
- squash
- rebase
required_reviewers:
- minimum_approvals: 1
file_patterns:
- "*.js"
reviewer:
id: 11721733
type: Team
`
const SUBORG_EXPERT_SERVICES_PROPERTY_YML = SUBORG_EXPERT_SERVICES_YML.replace(
'suborgteams:\n - expert-services-developers',
'suborgproperties:\n - ent-ownership: expert-services'
)
// Suborg config that narrows targeting to only the 'test' repo via
// suborgrepos. Used to test that repos dropping out of suborg targeting
// (due to targeting rule changes in the suborg.yml) have their
// suborg-applied rulesets removed.
const SUBORG_EXPERT_SERVICES_NARROW_YML = SUBORG_EXPERT_SERVICES_YML.replace(
'suborgteams:\n - expert-services-developers',
'suborgrepos:\n - test'
)
const REPO_DEMO_SERVICE1_ARCHIVED_YML = `# Safe-Settings Configuration
repository:
name: demo-repo-service1
description: "Repository 2 sample"
visibility: private
default_branch: main
homepage: ""
auto_init: true
force_create: true
delete_branch_on_merge: true
archived: true
`
const REPO_DEMO_SERVICE2_YML = `# Safe-Settings Configuration
repository:
name: demo-repo-service2
description: "Repository 2 sample"
visibility: private
default_branch: main
homepage: ""
auto_init: true
force_create: true
delete_branch_on_merge: true
archived: false
topics:
- topic1
- topic2
teams:
- name: expert-services-developers
permission: push
`
const REPO_DEMO_SERVICE2_EXTERNAL_GROUP_YML = `# Safe-Settings Configuration
repository:
name: demo-repo-service2
description: "Repository 2 sample"
visibility: private
default_branch: main
homepage: ""
auto_init: true
force_create: true
delete_branch_on_merge: true
archived: false
topics:
- topic1
- topic2
teams:
- name: expert-services-developers
permission: push
- name: jefeish-edj-test
permission: push
external_group: jefeish-edj-test
`
const REPO_DEMO_SERVICE2_NO_EXTERNAL_GROUP_YML = `# Safe-Settings Configuration
repository:
name: demo-repo-service2
description: "Repository 2 sample"
visibility: private
default_branch: main
homepage: ""
auto_init: true
force_create: true
delete_branch_on_merge: true
archived: false
topics:
- topic1
- topic2
teams:
- name: expert-services-developers
permission: push
`
const SETTINGS_YML_ORG = `# Org-level safe-settings configuration
rulesets:
- name: test
target: repository
source_type: Organization
source: ${ORG}
enforcement: disabled
conditions:
repository_property:
exclude: []
include:
- name: visibility
source: system
property_values:
- internal
rules:
- type: repository_delete
custom_repository_roles:
- name: security-engineer
description: Can contribute code and manage the security pipeline
base_role: maintain
permissions:
- delete_alerts_code_scanning
`
// Phase 10a: settings.yml that disables custom_repository_roles at org-self,
// and tries to add a NEW role ("disabled-role"). The new role must NOT be created.
const SETTINGS_YML_DISABLE_CRR = `# Org-level settings with disable_plugins (custom_repository_roles)
disable_plugins:
- plugin: custom_repository_roles
target: self
rulesets:
- name: test
target: repository
source_type: Organization
source: ${ORG}
enforcement: disabled
conditions:
repository_property:
exclude: []
include:
- name: visibility
source: system
property_values:
- internal
rules:
- type: repository_delete
custom_repository_roles:
- name: security-engineer
description: Can contribute code and manage the security pipeline
base_role: maintain
permissions:
- delete_alerts_code_scanning
- name: disabled-role
description: This role MUST NOT be created (custom_repository_roles disabled)
base_role: read
permissions:
- delete_alerts_code_scanning
`
// Phase 10b: settings.yml with invalid disable_plugins entry — should fail validation
const SETTINGS_YML_INVALID_DISABLE = `# Org-level settings with invalid disable_plugins
disable_plugins:
- not-a-real-plugin
`
// Phase 11a: settings.yml with additive_plugins for labels and custom_properties.
// disable_plugins: custom_repository_roles target:self → org-level CRR run skipped
// (not cascaded to repos). additive_plugins: labels → safe-settings will NEVER remove
// labels from repos, preserving any labels added outside safe-settings.
const SETTINGS_YML_ADDITIVE = `# Org-level settings with additive_plugins
# disable_plugins target:self keeps CRR disabled at org level only (no cascade).
# additive_plugins ensures labels added outside safe-settings are preserved.
disable_plugins:
- plugin: custom_repository_roles
target: self
additive_plugins:
- labels
- custom_properties
labels:
- name: safe-settings-base
color: '0075ca'
description: Baseline label applied by safe-settings policy
rulesets:
- name: test
target: repository
source_type: Organization
source: ${ORG}
enforcement: disabled
conditions:
repository_property:
exclude: []
include:
- name: visibility
source: system
property_values:
- internal
rules:
- type: repository_delete
custom_repository_roles:
- name: security-engineer
description: Can contribute code and manage the security pipeline
base_role: maintain
permissions:
- delete_alerts_code_scanning
`
// Phase 11b trigger: same as SETTINGS_YML_ADDITIVE with a comment bump so the
// push event fires and safe-settings re-processes all repos.
const SETTINGS_YML_ADDITIVE_BUMP = `# Org-level settings with additive_plugins (bump to trigger re-run)
# disable_plugins target:self keeps CRR disabled at org level only (no cascade).
# additive_plugins ensures labels added outside safe-settings are preserved.
disable_plugins:
- plugin: custom_repository_roles
target: self
additive_plugins:
- labels
- custom_properties
labels:
- name: safe-settings-base
color: '0075ca'
description: Baseline label applied by safe-settings policy
rulesets:
- name: test
target: repository
source_type: Organization
source: ${ORG}
enforcement: disabled
conditions:
repository_property:
exclude: []
include:
- name: visibility
source: system
property_values:
- internal
rules:
- type: repository_delete
custom_repository_roles:
- name: security-engineer
description: Can contribute code and manage the security pipeline
base_role: maintain
permissions:
- delete_alerts_code_scanning
`
// Phase 11c: same labels policy but WITHOUT additive_plugins — used to confirm
// that without additive mode safe-settings DOES remove the external label.
const SETTINGS_YML_NO_ADDITIVE = `# Org-level settings WITHOUT additive_plugins (for contrast test)
disable_plugins:
- plugin: custom_repository_roles
target: self
labels:
- name: safe-settings-base
color: '0075ca'
description: Baseline label applied by safe-settings policy
rulesets:
- name: test
target: repository
source_type: Organization
source: ${ORG}
enforcement: disabled