Repository navigation
Expand file tree
/
Copy pathclone.test.mjs
More file actions
526 lines (493 loc) · 34.6 KB
/
Copy pathclone.test.mjs
File metadata and controls
526 lines (493 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// Self-check for lib/data.mjs --repo cloning: node clone.test.mjs
// Hermetic: fixture git repos live in a temp dir; no network is touched.
// Covers: unambiguous spec parsing (path with '@', ref containing '@'),
// credential-free argv/env, redaction of raw/encoded/base64 credentials,
// and failure cleanup without data loss.
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { chmodSync, copyFileSync, existsSync, linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { delimiter, join, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { DEFAULT_GITHUB_HOST, GITHUB_HOST_ENV, assertSourceInside, checkDestination, cleanupData, cloneCommand, dataHost, dataRepoUrl, descriptionText, forAll, gitAuthEnv, githubHost, keepTemp, parseDataSpec, parseGithubHost, redactSecrets, resolveDataDir, ruleProblems } from './lib/data.mjs';
const tmp = mkdtempSync(join(tmpdir(), 'alate-clone-'));
const TOKEN = 'ghp_abc123/+=XYZ'; // fake: '/' '+' '=' stress the encoded/base64 shapes
const encoded = encodeURIComponent(TOKEN);
const basic = Buffer.from(`x-access-token:${TOKEN}`).toString('base64');
const git = args => spawnSync('git', args, { encoding: 'utf8' });
const initRepo = (dir, marker) => {
mkdirSync(dir, { recursive: true });
assert.equal(git(['init', '-q', '-b', 'main', dir]).status, 0);
git(['-C', dir, 'config', 'user.name', 't']);
git(['-C', dir, 'config', 'user.email', 't@t']);
writeFileSync(join(dir, 'marker.txt'), marker);
git(['-C', dir, 'add', '-A']);
assert.equal(git(['-C', dir, 'commit', '-qm', 'fixture']).status, 0);
};
const marker = (dir, name = 'marker.txt') => readFileSync(join(dir, name), 'utf8').replaceAll('\r\n', '\n');
const scanForToken = root => {
const hits = [];
(function walk(d) {
for (const e of readdirSync(d, { withFileTypes: true })) {
const p = join(d, e.name);
if (e.isDirectory()) walk(p);
else for (const [label, shape] of [['raw', TOKEN], ['encoded', encoded], ['basic', basic]]) {
if (readFileSync(p).includes(shape)) hits.push(`${label} in ${p}`);
}
}
})(root);
return hits;
};
try {
// Fixtures: default branch, a branch whose name contains '@', and a path with '@'.
const repo = join(tmp, 'repo');
initRepo(repo, 'main\n');
assert.equal(git(['-C', repo, 'checkout', '-qb', 'feature@draft']).status, 0);
writeFileSync(join(repo, 'marker.txt'), 'draft\n');
git(['-C', repo, 'commit', '-qam', 'draft']);
git(['-C', repo, 'checkout', '-q', 'main']);
const odd = join(tmp, 'odd@name');
initRepo(odd, 'odd\n');
const plain = join(tmp, 'plain'); // exists but not a repo -> clone must fail
mkdirSync(plain);
// --- parseDataSpec: existing path wins whole; ref is the entire first-@ suffix.
assert.deepEqual(parseDataSpec('owner/repo'), { name: 'owner/repo', ref: '', host: '' });
assert.deepEqual(parseDataSpec('owner/repo@feature@draft'), { name: 'owner/repo', ref: 'feature@draft', host: '' });
assert.deepEqual(parseDataSpec('owner/repo@v1.2'), { name: 'owner/repo', ref: 'v1.2', host: '' });
assert.deepEqual(parseDataSpec('owner/repo@'), { name: 'owner/repo', ref: '', host: '' });
assert.deepEqual(parseDataSpec(odd), { name: odd, ref: '', host: '' }, 'existing path with @ stays whole');
assert.equal(parseDataSpec('no-slash-here'), null);
assert.equal(parseDataSpec('bad@name'), null);
for (const url of ['https://github.com/owner/repo', 'https://github.com/owner/repo.git/']) {
assert.deepEqual(parseDataSpec(url), { name: 'owner/repo', ref: '', host: 'github.com' });
}
assert.deepEqual(parseDataSpec('https://github.com/owner/repo.git@feature@draft'), { name: 'owner/repo', ref: 'feature@draft', host: 'github.com' });
for (const spec of ['https://github.com.evil/owner/repo', 'https://user:password@github.com/owner/repo', 'https://github.com/../repo', 'https://github.com/owner/..', '-owner/repo']) {
assert.equal(parseDataSpec(spec), null);
}
// --- parseGithubHost: total host parser; apiBase follows the host family.
assert.deepEqual(parseGithubHost('github.com'), { host: 'github.com', isDefault: true, apiBase: 'https://api.github.com', webBase: 'https://github.com' });
assert.deepEqual(parseGithubHost('acme.ghe.com'), { host: 'acme.ghe.com', isDefault: false, apiBase: 'https://api.acme.ghe.com', webBase: 'https://acme.ghe.com' });
assert.deepEqual(parseGithubHost('ghe.acme.corp'), { host: 'ghe.acme.corp', isDefault: false, apiBase: 'https://ghe.acme.corp/api/v3', webBase: 'https://ghe.acme.corp' });
assert.deepEqual(parseGithubHost('ACME.GHE.COM'), { host: 'acme.ghe.com', isDefault: false, apiBase: 'https://api.acme.ghe.com', webBase: 'https://acme.ghe.com' }, 'hosts normalize to lowercase');
const refusesHost = raw => {
const parsed = parseGithubHost(raw);
assert.ok(parsed.error && parsed.error.startsWith('ALATE_GITHUB_HOST:'), `error shape for ${JSON.stringify(raw)}`);
assert.match(parsed.error, /use a bare hostname, for example github\.com or acme\.ghe\.com/);
return parsed.error;
};
refusesHost('');
refusesHost('a b');
refusesHost('a_b');
refusesHost('-x.y');
refusesHost('x-.y');
refusesHost('https://x');
refusesHost('a'.repeat(254));
for (const raw of ['github.com', 'acme.ghe.com', 'ghe.acme.corp', 'ACME.GHE.COM']) assert.equal(parseGithubHost(raw).error, undefined, `no error for ${raw}`);
// --- githubHost: ambient setting; blank/unset falls back to the default, invalid throws.
assert.equal(GITHUB_HOST_ENV, 'ALATE_GITHUB_HOST');
assert.equal(DEFAULT_GITHUB_HOST, 'github.com');
assert.deepEqual(githubHost({}), { host: 'github.com', isDefault: true, apiBase: 'https://api.github.com', webBase: 'https://github.com' });
assert.deepEqual(githubHost({ [GITHUB_HOST_ENV]: ' ' }).host, 'github.com', 'blank env value is the default host');
assert.equal(githubHost({ [GITHUB_HOST_ENV]: 'acme.ghe.com' }).host, 'acme.ghe.com');
assert.throws(() => githubHost({ [GITHUB_HOST_ENV]: 'not a host' }), e => e.message.startsWith('ALATE_GITHUB_HOST:'));
// --- parseDataSpec host forms: explicit host on any GitHub host; look-alikes refused.
assert.deepEqual(parseDataSpec('acme.ghe.com/own/repo'), { name: 'own/repo', ref: '', host: 'acme.ghe.com' });
assert.deepEqual(parseDataSpec('acme.ghe.com/own/repo@v1'), { name: 'own/repo', ref: 'v1', host: 'acme.ghe.com' });
assert.deepEqual(parseDataSpec('ghe.acme.corp/own/repo@feature@draft'), { name: 'own/repo', ref: 'feature@draft', host: 'ghe.acme.corp' }, 'ref keeps everything after the first @');
assert.deepEqual(parseDataSpec('https://acme.ghe.com/own/repo.git@f@d'), { name: 'own/repo', ref: 'f@d', host: 'acme.ghe.com' });
assert.deepEqual(parseDataSpec('https://GITHUB.COM/own/repo'), { name: 'own/repo', ref: '', host: 'github.com' }, 'URL hosts normalize to lowercase');
for (const spec of ['https://github.com.evil/own/repo', 'github.com.evil/own/repo', 'www.github.com/own/repo', 'owner/repo/extra', 'localhost/own/repo', 'https://a/own/repo', 'a/own/nm/extra']) {
assert.equal(parseDataSpec(spec), null, `refusal for ${spec}`);
}
// --- redactSecrets: raw, URL-encoded and base64 credential shapes.
assert.equal(redactSecrets('x ghp_abc123/+=XYZ y', TOKEN), 'x *** y');
assert.equal(redactSecrets(`u:${encoded}@host`, TOKEN), 'u:***@host');
assert.equal(redactSecrets(`AUTHORIZATION: basic ${basic}`, TOKEN), 'AUTHORIZATION: basic ***');
assert.equal(redactSecrets(`basic ${basic} enc ${encoded} raw ${TOKEN}`, TOKEN), 'basic *** enc *** raw ***');
assert.equal(redactSecrets('unchanged', ''), 'unchanged');
// --- cloneCommand: token never reaches argv; auth rides in per-process env config.
const dir = join(tmp, 'dst');
let cmd = cloneCommand('https://github.com/owner/repo', 'feature@draft', TOKEN, dir, {});
assert.deepEqual(cmd.args, ['clone', '--quiet', '--depth', '1', '--config', 'core.autocrlf=false', '--config', 'core.eol=lf', '--branch', 'feature@draft', 'https://github.com/owner/repo', dir]);
assert.equal(cmd.env.GIT_CONFIG_KEY_0, 'http.https://github.com/.extraheader');
assert.equal(cmd.env.GIT_CONFIG_VALUE_0, `AUTHORIZATION: basic ${basic}`);
assert.equal(cmd.env.GIT_TERMINAL_PROMPT, '0');
assert.equal(cmd.env.GIT_CONFIG_COUNT, '1', 'exactly one injected config entry');
for (const shape of [TOKEN, encoded, basic]) assert.ok(!cmd.args.join(' ').includes(shape), 'token shape in argv');
cmd = cloneCommand('https://github.com/owner/repo', '', undefined, dir, {});
assert.ok(!('GIT_CONFIG_COUNT' in cmd.env), 'no auth config without a token');
cmd = cloneCommand(odd, '', TOKEN, dir, {});
assert.ok(!('GIT_CONFIG_COUNT' in cmd.env), 'local path needs no auth config');
cmd = cloneCommand('file://x/repo', '', TOKEN, dir, {});
assert.ok(!('GIT_CONFIG_COUNT' in cmd.env), 'file:// needs no auth config');
cmd = cloneCommand('http://github.com/own/repo', '', TOKEN, dir, {});
assert.ok(!('GIT_CONFIG_COUNT' in cmd.env), 'http:// needs no auth config');
// --- Token isolation across hosts: the token rides only to the configured host
// (ALATE_GITHUB_HOST, github.com by default); a clone URL on any other host gets no auth.
const savedHost = process.env[GITHUB_HOST_ENV];
try {
delete process.env[GITHUB_HOST_ENV]; // default env: github.com is the configured host
cmd = cloneCommand('https://acme.ghe.com/own/repo', '', TOKEN, dir, {});
assert.deepEqual(cmd.args.at(-2), 'https://acme.ghe.com/own/repo', 'clone URL in argv for ghe.com tenant');
assert.ok(!('GIT_CONFIG_COUNT' in cmd.env), 'foreign host gets no auth config by default');
assert.ok(!JSON.stringify(cmd.env).includes('AUTHORIZATION: basic'), 'no basic credential for a foreign host');
assert.ok(!JSON.stringify(cmd.env).includes(basic), 'encoded credential absent for a foreign host');
assert.ok(!cmd.args.join(' ').includes('github.com'), 'ghe clone argv never names github.com');
process.env[GITHUB_HOST_ENV] = 'acme.ghe.com';
cmd = cloneCommand('https://acme.ghe.com/own/repo', '', TOKEN, dir, {});
assert.equal(cmd.env.GIT_CONFIG_KEY_0, 'http.https://acme.ghe.com/.extraheader');
assert.equal(cmd.env.GIT_CONFIG_VALUE_0, `AUTHORIZATION: basic ${basic}`);
assert.equal(cmd.env.GIT_CONFIG_COUNT, '1', 'exactly one injected config entry for the configured host');
for (const [k, v] of Object.entries(cmd.env)) assert.ok(k.startsWith('GIT_CONFIG') ? !String(v).includes('github.com') : true, `ghe clone env ${k} never names github.com`);
cmd = cloneCommand('https://github.com/own/repo', '', TOKEN, dir, {});
assert.deepEqual(cmd.args.at(-2), 'https://github.com/own/repo', 'clone URL in argv for github.com');
assert.ok(!('GIT_CONFIG_COUNT' in cmd.env), 'github.com is now the foreign host: no auth config');
} finally {
if (savedHost === undefined) delete process.env[GITHUB_HOST_ENV];
else process.env[GITHUB_HOST_ENV] = savedHost;
}
// --- Parse-to-clone path: a spec naming a foreign host yields an auth-free clone env.
const spec = parseDataSpec('attacker.example/o/n');
assert.deepEqual(spec, { name: 'o/n', ref: '', host: 'attacker.example' });
const specUrl = dataRepoUrl(spec);
assert.equal(specUrl, 'https://attacker.example/o/n');
cmd = cloneCommand(specUrl, spec.ref, TOKEN, dir, {});
assert.ok(!('GIT_CONFIG_COUNT' in cmd.env), 'foreign-host spec gets no auth config');
assert.ok(!('GIT_CONFIG_KEY_0' in cmd.env) && !('GIT_CONFIG_VALUE_0' in cmd.env), 'no extraheader keys for a foreign host');
for (const shape of [basic, TOKEN, encoded]) assert.ok(!JSON.stringify(cmd.env).includes(shape), 'credential shape absent from env for a foreign host');
const savedHost2 = process.env[GITHUB_HOST_ENV];
try {
process.env[GITHUB_HOST_ENV] = 'attacker.example';
cmd = cloneCommand(dataRepoUrl(spec), spec.ref, TOKEN, dir, {});
assert.equal(cmd.env.GIT_CONFIG_KEY_0, 'http.https://attacker.example/.extraheader');
assert.equal(cmd.env.GIT_CONFIG_COUNT, '1');
process.env[GITHUB_HOST_ENV] = 'not a host';
cmd = cloneCommand('https://github.com/o/n', '', TOKEN, dir, {});
assert.ok(!('GIT_CONFIG_COUNT' in cmd.env), 'invalid ALATE_GITHUB_HOST fails closed: no auth config');
} finally {
if (savedHost2 === undefined) delete process.env[GITHUB_HOST_ENV];
else process.env[GITHUB_HOST_ENV] = savedHost2;
}
// --- Runtime config reset: auth and every early return discard inherited entries.
// Host policy stays ambient; only the child environment comes from the injected base.
const emptyConfig = join(tmp, 'empty.gitconfig');
writeFileSync(emptyConfig, '');
const runtimeBase = {
PATH: process.env.PATH,
ALATE_TEST_MARKER: 'preserved',
GIT_CONFIG_GLOBAL: emptyConfig,
GIT_CONFIG_SYSTEM: emptyConfig,
GIT_CONFIG_NOSYSTEM: '1',
GIT_TERMINAL_PROMPT: '1',
GIT_CONFIG_COUNT: '2',
GIT_CONFIG_KEY_0: 'gc.auto',
GIT_CONFIG_VALUE_0: '0',
GIT_CONFIG_KEY_1: 'maintenance.auto',
GIT_CONFIG_VALUE_1: 'false',
GIT_CONFIG_KEY_17: 'http.https://foreign.example/.extraheader',
GIT_CONFIG_VALUE_17: 'stale-header',
GIT_CONFIG_KEY_003: 'credential.helper',
GIT_CONFIG_VALUE_29: 'stale-value',
};
const savedRuntimeHost = process.env[GITHUB_HOST_ENV];
try {
const cases = [
['eligible HTTPS', 'https://github.com/o/n', TOKEN, 'github.com', true],
['no token', 'https://github.com/o/n', undefined, 'github.com', false],
['local path', odd, TOKEN, 'github.com', false],
['file URL', 'file://x/repo', TOKEN, 'github.com', false],
['HTTP URL', 'http://github.com/o/n', TOKEN, 'github.com', false],
['foreign HTTPS', 'https://foreign.example/o/n', TOKEN, 'github.com', false],
['invalid host', 'https://github.com/o/n', TOKEN, 'not a host', false],
];
for (const [label, url, token, host, auth] of cases) {
process.env[GITHUB_HOST_ENV] = host;
const before = { ...runtimeBase };
const env = gitAuthEnv(url, token, runtimeBase);
assert.deepEqual(runtimeBase, before, `${label}: input stays unchanged`);
assert.equal(env.GIT_TERMINAL_PROMPT, '0', `${label}: prompts stay disabled`);
for (const key of ['PATH', 'ALATE_TEST_MARKER', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_SYSTEM', 'GIT_CONFIG_NOSYSTEM']) {
assert.equal(env[key], before[key], `${label}: preserve ${key}`);
}
assert.deepEqual(Object.keys(env).filter(key => /^GIT_CONFIG_(?:COUNT|KEY_\d+|VALUE_\d+)$/.test(key)).sort(),
auth ? ['GIT_CONFIG_COUNT', 'GIT_CONFIG_KEY_0', 'GIT_CONFIG_VALUE_0'] : [], `${label}: no inherited runtime entries`);
const query = key => spawnSync('git', ['config', '--get', key], { cwd: tmp, encoding: 'utf8', env });
for (const key of ['gc.auto', 'maintenance.auto', 'credential.helper', 'http.https://foreign.example/.extraheader']) {
const result = query(key);
assert.equal(result.status, 1, `${label}: ${key} stays absent: ${result.stderr}`);
assert.equal(result.stdout, '', `${label}: no inherited value for ${key}`);
}
const header = query('http.https://github.com/.extraheader');
assert.equal(header.status, auth ? 0 : 1, `${label}: Git accepts the runtime config: ${header.stderr}`);
assert.equal(header.stdout, auth ? `AUTHORIZATION: basic ${basic}\n` : '', `${label}: Git sees only eligible auth`);
if (auth) assert.equal(env.GIT_CONFIG_COUNT, '1', `${label}: exactly one auth entry`);
else for (const shape of [TOKEN, encoded, basic]) assert.ok(!JSON.stringify(env).includes(shape), `${label}: no credential shape`);
}
process.env[GITHUB_HOST_ENV] = 'github.com';
for (const count of [undefined, '0', '', 'bogus', '-1', '1.5', '999999999999999999999']) {
const base = { ...runtimeBase };
if (count === undefined) delete base.GIT_CONFIG_COUNT;
else base.GIT_CONFIG_COUNT = count;
for (const token of [undefined, TOKEN]) {
const before = { ...base };
const env = gitAuthEnv('https://github.com/o/n', token, base);
assert.deepEqual(base, before, `count ${count}: input stays unchanged`);
assert.deepEqual(Object.fromEntries(Object.entries(env).filter(([key]) => /^GIT_CONFIG_(?:COUNT|KEY_\d+|VALUE_\d+)$/.test(key))),
token ? { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader', GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basic}` } : {},
`count ${count}: stale entries disappear even without a valid count`);
}
}
} finally {
if (savedRuntimeHost === undefined) delete process.env[GITHUB_HOST_ENV];
else process.env[GITHUB_HOST_ENV] = savedRuntimeHost;
}
// --- dataHost / dataRepoUrl: ambient host decides plain specs; explicit host wins.
assert.equal(dataRepoUrl({ name: 'own/repo', ref: '', host: '' }), 'https://github.com/own/repo');
assert.equal(dataRepoUrl({ name: 'own/repo', ref: '', host: 'acme.ghe.com' }), 'https://acme.ghe.com/own/repo');
assert.equal(dataRepoUrl({ name: 'own/repo', ref: '', host: '' }, { [GITHUB_HOST_ENV]: 'acme.ghe.com' }), 'https://acme.ghe.com/own/repo');
assert.equal(dataRepoUrl({ name: 'own/repo', ref: '', host: '' }, { [GITHUB_HOST_ENV]: 'ghe.acme.corp' }), 'https://ghe.acme.corp/own/repo');
assert.equal(dataRepoUrl({ name: odd, ref: '', host: '' }), odd, 'an existing local path passes through unchanged');
assert.equal(dataHost({ name: 'own/repo', ref: '', host: 'ghe.acme.corp' }), 'ghe.acme.corp', 'explicit host beats the env');
assert.equal(dataHost({ name: 'own/repo', ref: '', host: '' }), 'github.com');
assert.throws(() => dataHost({ name: 'own/repo', ref: '', host: '' }, { [GITHUB_HOST_ENV]: 'not a host' }), e => e.message.startsWith('ALATE_GITHUB_HOST:'));
// --- Integration: ref containing '@' clones for real; then a whole path containing '@'.
const refDst = join(tmp, 'dst-ref');
cmd = cloneCommand(repo, 'feature@draft', TOKEN, refDst);
const real = spawnSync('git', cmd.args, { encoding: 'utf8', env: cmd.env });
assert.equal(real.status, 0, real.stderr);
assert.equal(marker(refDst), 'draft\n', 'branch feature@draft checked out');
assert.deepEqual(scanForToken(refDst), [], 'token leaked into clone');
// --- A host-wide core.autocrlf=true (Windows default) must not turn the clone's LF into CRLF.
const crlfConfig = join(tmp, 'crlf.gitconfig');
writeFileSync(crlfConfig, '[core]\n\tautocrlf = true\n\teol = crlf\n');
const lfDst = join(tmp, 'dst-lf');
cmd = cloneCommand(repo, '', undefined, lfDst);
const lf = spawnSync('git', cmd.args, { encoding: 'utf8', env: { ...cmd.env, GIT_CONFIG_GLOBAL: crlfConfig } });
assert.equal(lf.status, 0, lf.stderr);
assert.equal(readFileSync(join(lfDst, 'marker.txt'), 'latin1'), 'main\n', 'clone keeps LF under autocrlf=true');
let data = resolveDataDir({ values: { '--repo': odd }, flags: new Set() }, { allowClone: true });
assert.equal(marker(data.dir), 'odd\n');
const url = git(['-C', data.dir, 'config', '--get', 'remote.origin.url']).stdout.trim();
assert.equal(url, odd, 'remote URL is the plain path, credentials never included');
assert.deepEqual(scanForToken(data.dir), [], 'token leaked into clone or .git/config');
cleanupData(data);
if (!keepTemp()) assert.ok(!existsSync(data.dir), 'cleanupData removes the temp clone');
// --- Failure paths via the real CLI: unusable spec, and failed clone with token set.
const scriptDir = join(tmp, 'tool');
mkdirSync(join(scriptDir, 'lib'), { recursive: true });
copyFileSync(fileURLToPath(new URL('./sync.mjs', import.meta.url)), join(scriptDir, 'sync.mjs'));
copyFileSync(fileURLToPath(new URL('./lib/data.mjs', import.meta.url)), join(scriptDir, 'lib', 'data.mjs'));
// The child's HOME is a scratch dir distinct from the target: a dropped positional or
// default (a Stryker mutant) writes into the sandbox, never the machine home.
const childHome = join(tmp, 'child-home');
mkdirSync(childHome, { recursive: true });
const runSync = (repoSpec, env = {}) => {
const child = { ...process.env, ...env, HOME: childHome, USERPROFILE: childHome, ALATE_DATA: join(tmp, 'no-aldata') };
delete child.PI_CODING_AGENT_DIR; // sync.mjs prefers it over HOME; an inherited value could be a real agent dir
return spawnSync(process.execPath, [join(scriptDir, 'sync.mjs'), join(tmp, 'target'), '--repo', repoSpec], { encoding: 'utf8', env: child });
};
let r = runSync('no-slash-here');
assert.equal(r.status, 1);
assert.match(r.stderr, /--repo must be <owner\/name\[@ref\]>, <host>\/owner\/name\[@ref\] or an existing path/);
const tempBefore = readdirSync(tmpdir()).filter(n => n.startsWith('alate-data-'));
r = runSync(plain, { GH_TOKEN: TOKEN });
assert.equal(r.status, 1);
assert.match(r.stderr, /git clone failed for .+plain\b/);
for (const shape of [TOKEN, encoded, basic]) assert.ok(!r.stderr.includes(shape), 'token shape in clone error');
const leftover = readdirSync(tmpdir()).filter(n => n.startsWith('alate-data-') && !tempBefore.includes(n));
assert.deepEqual(leftover, [], 'failed clone leaves no temp dir behind');
// A spec that parses as owner/name[@ref] is cloned from the github URL template, and
// the failure message carries git's own stderr through redactSecrets. A stub git makes
// the failure deterministic without a network.
if (process.platform !== 'win32') {
const stubDir = join(tmp, 'git-stub');
mkdirSync(stubDir, { recursive: true });
writeFileSync(join(stubDir, 'git'), '#!/bin/sh\necho "fatal: stub clone failure: $*" >&2\nexit 128\n');
chmodSync(join(stubDir, 'git'), 0o755);
r = runSync('no-such-owner/no-such-repo@v9', { PATH: `${stubDir}${delimiter}${process.env.PATH ?? ''}` });
assert.equal(r.status, 1);
assert.match(r.stderr, /git clone failed for no-such-owner\/no-such-repo@v9:\nfatal: stub clone failure: clone .* https:\/\/github\.com\/no-such-owner\/no-such-repo/);
}
// --- checkDestination: every documented refusal, by its exact message.
const gateRoot = join(tmp, 'gate-root');
mkdirSync(join(gateRoot, 'dir'), { recursive: true });
writeFileSync(join(gateRoot, 'file.txt'), 'x');
const refusesDest = (dest, message) => assert.throws(() => checkDestination(gateRoot, dest), e => e.message === message, message);
assert.doesNotThrow(() => checkDestination(gateRoot, join(gateRoot, 'dir', 'new.txt')), 'a fresh nested path is fine');
assert.doesNotThrow(() => checkDestination(gateRoot, join(gateRoot, 'file.txt')), 'an existing single-link file is fine');
refusesDest(gateRoot, `Destination ${gateRoot} is outside ${gateRoot}`);
refusesDest(join(gateRoot, '..'), `Destination ${join(gateRoot, '..')} is outside ${gateRoot}`);
refusesDest(join(tmp, 'elsewhere.txt'), `Destination ${join(tmp, 'elsewhere.txt')} is outside ${gateRoot}`);
if (process.platform !== 'win32') {
const outsideDir = join(tmp, 'outside-dir');
mkdirSync(outsideDir, { recursive: true });
symlinkSync(outsideDir, join(gateRoot, 'link'), 'dir');
refusesDest(join(gateRoot, 'link', 'f.txt'), `${join(gateRoot, 'link')} is a symbolic link below the chosen root ${gateRoot}`);
}
refusesDest(join(gateRoot, 'file.txt', 'sub', 'x.txt'), `${join(gateRoot, 'file.txt')} is not a directory`);
refusesDest(join(gateRoot, 'dir'), `${join(gateRoot, 'dir')} exists and is not a regular file`);
writeFileSync(join(gateRoot, 'one.txt'), 'x');
linkSync(join(gateRoot, 'one.txt'), join(gateRoot, 'two.txt'));
refusesDest(join(gateRoot, 'two.txt'), `${join(gateRoot, 'two.txt')} has 2 hard links; refusing to write it`);
// --- assertSourceInside: realpath-based guard, the root itself allowed.
const srcRoot = join(tmp, 'src-root');
mkdirSync(srcRoot, { recursive: true });
writeFileSync(join(srcRoot, 'f.txt'), 'x');
const outsideFile = join(tmp, 'outside.txt');
writeFileSync(outsideFile, 'x');
assert.doesNotThrow(() => assertSourceInside(srcRoot, srcRoot), 'the root itself is allowed');
assert.doesNotThrow(() => assertSourceInside(srcRoot, join(srcRoot, 'f.txt')), 'a file inside is allowed');
const refusesSrc = (path, message) => assert.throws(() => assertSourceInside(srcRoot, path), e => e.message === message, message);
refusesSrc(outsideFile, `Source ${outsideFile} is outside ${srcRoot}`);
refusesSrc(join(srcRoot, '..'), `Source ${join(srcRoot, '..')} is outside ${srcRoot}`);
// --- parseDataSpec: dot segments and extra segments are refused.
assert.equal(parseDataSpec('x/.'), null, 'a single-dot segment is refused');
assert.equal(parseDataSpec('x/..'), null, 'a parent segment is refused');
assert.equal(parseDataSpec('owner/repo/extra'), null, 'a third path segment is refused');
// --- descriptionText: the YAML-free description reader the frontmatter gate relies on.
assert.equal(descriptionText('title: x'), null, 'no description key');
assert.equal(descriptionText('mydescription: hi'), null, 'only a line-start description key counts');
assert.equal(descriptionText('description:x'), 'x', 'the value needs no space');
assert.equal(descriptionText('description: plain # trailing'), 'plain', 'a comment needs whitespace before #');
assert.equal(descriptionText('description: C# tips'), 'C# tips', 'no whitespace before # keeps the value');
assert.equal(descriptionText('description: x#y'), 'x#y');
assert.equal(descriptionText('description: # only a comment'), null, 'a comment-only value is blank');
assert.equal(descriptionText('description: "dq # kept"'), 'dq # kept', 'a quoted value keeps its #');
assert.equal(descriptionText('description: " x "'), 'x', 'a quoted value is trimmed');
assert.equal(descriptionText('description: "a\\b"'), 'ab', 'double-quote escapes are unwrapped');
assert.equal(descriptionText('description: "x" # c'), 'x', 'a comment after a quote goes');
assert.equal(descriptionText('description: "x" junk'), '"x" junk', 'an unterminated quote stays raw text');
assert.equal(descriptionText('description: "ab"'), 'ab');
assert.equal(descriptionText("description: 'sq'"), 'sq');
assert.equal(descriptionText("description: 'it''s fine'"), "it's fine", "'' escapes a quote");
assert.equal(descriptionText("description: 'sq' # c"), 'sq', 'a comment after a single quote goes');
assert.equal(descriptionText("description: junk 'x'"), "junk 'x'", 'an unterminated single quote stays raw text');
assert.equal(descriptionText("description: 'sq' junk"), "'sq' junk", 'a single quote must close before the value ends');
assert.equal(descriptionText('description: a|'), 'a|', 'a mid-value pipe is plain text');
assert.equal(descriptionText('description: |x'), '|x', 'a block indicator must end the value');
assert.equal(descriptionText('description: x'), 'x', 'a plain word is no block');
assert.equal(descriptionText('description: |'), null, 'an empty block is no description');
assert.equal(descriptionText('description: | '), null, 'trailing spaces keep the block indicator');
assert.equal(descriptionText('description: |-'), null);
assert.equal(descriptionText('description: >'), null);
assert.equal(descriptionText('description: |\n a\n b'), 'a b', 'block lines join with spaces');
assert.equal(descriptionText('description: |\n a\n\n b'), 'a b', 'blank block lines vanish');
assert.equal(descriptionText('description: |\n a\nnext: 1'), 'a', 'a dedented line ends the block');
assert.equal(descriptionText('description: >\n wrapped\n text'), 'wrapped text');
assert.equal(descriptionText('title: t\ndescription: |\n a\n b'), 'a b', 'block lines collect only after the description line, not from the frontmatter start');
assert.equal(descriptionText('description: |\n \n '), null, 'whitespace-only block lines are blank');
assert.equal(descriptionText('description: "x" # c'), 'x', 'a comment may follow any whitespace run after the quote');
// --- ruleProblems: hidden characters plus the frontmatter gate.
assert.deepEqual(ruleProblems('r.md', 'no frontmatter here\n'), ['r.md: needs frontmatter with a description']);
assert.deepEqual(ruleProblems('r.md', 'intro\n---\ndescription: x\n---\nbody\n'), ['r.md: needs frontmatter with a description'], 'frontmatter must open the file');
assert.deepEqual(ruleProblems('r.md', '---\r\ndescription: CRLF\r\n---\nbody\n'), [], 'CRLF frontmatter is accepted');
assert.deepEqual(ruleProblems('r.md', '---\n\n---\ndescription: real\n---\nbody\n'), ['r.md: needs frontmatter with a description'], 'the first frontmatter block decides');
assert.deepEqual(ruleProblems('r.md', '---\ndescription: ok\n---\ntext \u0007 bell\n'), ['r.md:4:6: hidden character U+0007']);
assert.deepEqual(ruleProblems('ctx.md', 'text \u200B zwsp\n', { frontmatter: false }), ['ctx.md:1:6: hidden character U+200B'], 'agent-context files scan hidden characters only');
// Emoji text passes: a text/emoji-style selector (U+FE0E/U+FE0F) right after an emoji or
// symbol code point, and a ZWJ (U+200D) joining two emoji with a skin-tone modifier
// between. An upstream skill bump carrying these must not stop every provision.
assert.deepEqual(
ruleProblems('r.md', '---\ndescription: ok\n---\n\u26A0\uFE0F \u2733\uFE0E \u{1F469}\u{1F3FD}\u200D\u{1F4BB}\n'),
[],
'emoji selector and ZWJ sequences are accepted'
);
// Every other hit stays fatal: zero-width space, a bidi override, a selector with no emoji
// or symbol before it, and a ZWJ outside an emoji run.
assert.deepEqual(ruleProblems('r.md', '---\ndescription: ok\n---\ntext \u200B here\n'), ['r.md:4:6: hidden character U+200B'], 'zero-width space stays fatal');
assert.deepEqual(ruleProblems('r.md', '---\ndescription: ok\n---\ntext \u202E here\n'), ['r.md:4:6: hidden character U+202E'], 'a bidi override stays fatal');
assert.deepEqual(ruleProblems('r.md', '---\ndescription: ok\n---\n\uFE0F leading\n'), ['r.md:4:1: hidden character U+FE0F'], 'a selector with no emoji or symbol before it stays fatal');
assert.deepEqual(ruleProblems('r.md', '---\ndescription: ok\n---\na\u200Db\n'), ['r.md:4:2: hidden character U+200D'], 'a ZWJ outside an emoji run stays fatal');
// Property checks (fuzz tier via forAll in lib/data.mjs). Gate: 200 runs, fixed seed
// 42; PROP_RUNS=<n> re-seeds randomly for the review deep tier.
{
const ident = (rand, size) => {
const head = 'abcdefgh0123456789';
let s = head[Math.floor(rand() * head.length)];
for (let i = 0, n = Math.floor(rand() * (size + 2)); i < n; i++) s += (head + '-._')[Math.floor(rand() * 19)];
return s;
};
// checkDestination: acceptance implies the destination resolves inside the root, and
// every refusal names one of its documented reasons. NUL stays out of scope: names
// below a root come from the OS (readdir), which cannot produce one.
const destRoot = join(tmp, 'prop-dest');
mkdirSync(join(destRoot, 'sub'), { recursive: true });
writeFileSync(join(destRoot, 'file.txt'), 'x');
const REFUSES = /outside|symbolic link below|is not a directory|is not a regular file|hard links/;
const PIECES = ['file.txt', 'sub', 'new.txt', 'dir2', '..', '.', '', 'x y'];
forAll((rand, size) => {
let s = rand() < 0.15 ? join(tmpdir(), 'elsewhere') : rand() < 0.1 ? '/' : '';
for (let i = 0, n = 1 + Math.floor(rand() * (size + 1)); i < n; i++) s += PIECES[Math.floor(rand() * PIECES.length)] + (rand() < 0.85 ? '/' : '');
return s;
}, dest => {
let ok = false;
try { checkDestination(destRoot, dest); ok = true; }
catch (e) { assert.match(e.message, REFUSES, `documented refusal for ${JSON.stringify(dest)}`); }
if (ok) {
const r = resolve(destRoot);
assert.ok(resolve(destRoot, dest) === r || resolve(destRoot, dest).startsWith(r + sep), `accepted destination stays inside the root: ${JSON.stringify(dest)}`);
}
});
// parseDataSpec: never throws, whatever the string.
forAll((rand, size) => {
const junk = ['', '@', '@@', 'abc@', '/abs/path', './own/nm', 'own//nm', '-own/nm', 'own/..', 'a.b/own/nm', 'https://a.b/own/nm', 'https://github.com/own/nm.git/', `${ident(rand, 3)}@${ident(rand, 3)}@${ident(rand, 3)}`];
return junk[Math.floor(rand() * junk.length)];
}, spec => { parseDataSpec(spec); });
// parseDataSpec: canonical owner/name[@ref] specs parse exactly once and round trip.
forAll(rand => {
const spec = `${ident(rand, 5)}/${ident(rand, 5)}`;
return rand() < 0.5 ? spec : `${spec}@${ident(rand, 5)}`;
}, spec => {
const p = parseDataSpec(spec);
assert.deepEqual(p, { name: spec.split('@')[0], ref: spec.includes('@') ? spec.slice(spec.indexOf('@') + 1) : '', host: '' }, `canonical parse: ${spec}`);
assert.deepEqual(parseDataSpec(p.ref ? `${p.name}@${p.ref}` : p.name), p, `round trip: ${spec}`);
});
// An existing local path wins whole, including one that contains '@'.
writeFileSync(join(tmp, 'at@path'), 'x');
assert.deepEqual(parseDataSpec(join(tmp, 'at@path')), { name: join(tmp, 'at@path'), ref: '', host: '' }, 'a local path containing @ wins whole');
// gitAuthEnv: host policy and runtime reset hold for arbitrary inherited entries.
forAll(rand => {
const hosts = ['github.com', 'acme.ghe.com', 'github.com.evil', 'www.github.com', 'evil.example', 'not a host'];
const counts = [undefined, '0', '2', '', '-1', 'bad'];
return {
configuredHost: hosts[Math.floor(rand() * hosts.length)],
urlHost: hosts[Math.floor(rand() * (hosts.length - 1))],
token: rand() < 0.5 ? TOKEN : undefined,
count: counts[Math.floor(rand() * counts.length)],
index: String(1 + Math.floor(rand() * 1000)),
};
}, ({ configuredHost, urlHost, token, count, index }) => {
const saved = process.env[GITHUB_HOST_ENV];
process.env[GITHUB_HOST_ENV] = configuredHost;
try {
const base = { ...runtimeBase, [`GIT_CONFIG_KEY_${index}`]: 'gc.auto', [`GIT_CONFIG_VALUE_${index}`]: '123' };
if (count === undefined) delete base.GIT_CONFIG_COUNT;
else base.GIT_CONFIG_COUNT = count;
const before = { ...base };
const env = gitAuthEnv(`https://${urlHost}/o/n`, token, base);
const auth = Boolean(token) && urlHost === configuredHost;
assert.deepEqual(base, before, 'runtime reset never mutates the input');
assert.deepEqual(env, {
PATH: base.PATH,
ALATE_TEST_MARKER: base.ALATE_TEST_MARKER,
GIT_CONFIG_GLOBAL: base.GIT_CONFIG_GLOBAL,
GIT_CONFIG_SYSTEM: base.GIT_CONFIG_SYSTEM,
GIT_CONFIG_NOSYSTEM: base.GIT_CONFIG_NOSYSTEM,
GIT_TERMINAL_PROMPT: '0',
...(auth ? {
GIT_CONFIG_COUNT: '1',
GIT_CONFIG_KEY_0: `http.https://${configuredHost}/.extraheader`,
GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basic}`,
} : {}),
}, `only eligible auth survives runtime reset for ${urlHost} under ${configuredHost}`);
} finally {
if (saved === undefined) delete process.env[GITHUB_HOST_ENV];
else process.env[GITHUB_HOST_ENV] = saved;
}
});
}
console.log('clone.test.mjs ok');
} finally {
if (!keepTemp()) rmSync(tmp, { recursive: true, force: true });
}