import crypto from 'crypto'; import { readGitConfig, keyId } from './config.js'; import { createTokenCrypto } from './crypto.js'; import { assertUrlAllowed, parseRepoUrl, isPrivateAddress } from './urlPolicy.js'; import { validatePath, validateBranch, validateDir, slugify } from './validate.js'; import { redact, GitError } from './errors.js'; import { createLocks, createSemaphore } from './locks.js'; const key = ()=>crypto.randomBytes(32); describe('Token-Verschlüsselung (ADR 0003 §3)', ()=>{ const k = key(); const c = createTokenCrypto({ key: k }); test('Roundtrip, Format v1...., zufälliger IV', ()=>{ const enc = c.encrypt('ghp_geheim', 'conn-1'); const parts = enc.split('.'); expect(parts).toHaveLength(5); expect(parts[0]).toBe('v1'); expect(parts[1]).toBe(keyId(k)); expect(enc).not.toContain('ghp_geheim'); expect(c.decrypt(enc, 'conn-1')).toEqual({ token: 'ghp_geheim', rotate: false }); expect(c.encrypt('ghp_geheim', 'conn-1')).not.toBe(enc); }); test('falsche AAD (andere Verbindung) schlägt fehl', ()=>{ const enc = c.encrypt('t', 'conn-1'); expect(()=>c.decrypt(enc, 'conn-2')).toThrow(); }); test('manipuliertes Chiffrat und unbekanntes Format schlagen fehl', ()=>{ const enc = c.encrypt('t', 'conn-1').split('.'); enc[3] = Buffer.from('xxxx').toString('base64url'); expect(()=>c.decrypt(enc.join('.'), 'conn-1')).toThrow(); expect(()=>c.decrypt('quatsch', 'conn-1')).toThrow(); }); test('Rotation: alter Schlüssel entschlüsselt und meldet rotate', ()=>{ const old = key(); const enc = createTokenCrypto({ key: old }).encrypt('t', 'c'); const rotated = createTokenCrypto({ key: k, oldKeys: [old] }); expect(rotated.decrypt(enc, 'c')).toEqual({ token: 't', rotate: true }); expect(()=>createTokenCrypto({ key: k }).decrypt(enc, 'c')).toThrow(/Schlüssel/); }); }); describe('Konfiguration', ()=>{ test('ohne HB_GIT_TOKEN_KEY deaktiviert', ()=>{ expect(readGitConfig({}).enabled).toBe(false); }); test('Schlüssel muss 32 Byte lang sein', ()=>{ expect(()=>readGitConfig({ HB_GIT_TOKEN_KEY: Buffer.from('kurz').toString('base64') })).toThrow(/32 Byte/); expect(readGitConfig({ HB_GIT_TOKEN_KEY: key().toString('base64') }).enabled).toBe(true); }); test('Standardwerte und Grenzen', ()=>{ const cfg = readGitConfig({ HB_GIT_TOKEN_KEY: key().toString('base64'), HB_PUBLIC_URL: 'https://hb.example.test', HB_GIT_OPEN_TIMEOUT_MS: '999999' }); expect(cfg).toMatchObject({ timeoutMs: 20000, openTimeoutMs: 20000, maxFileBytes: 5242880, maxConcurrency: 2, committerName: 'Homebrewery', committerEmail: 'homebrewery@hb.example.test', allowPrivate: false, allowHttp: false }); expect(readGitConfig({ HB_GIT_OPEN_TIMEOUT_MS: '10' }).openTimeoutMs).toBe(1000); expect(readGitConfig({}).openTimeoutMs).toBe(4000); }); }); describe('URL-Policy (SSRF)', ()=>{ const cfg = { allowedHosts: [], allowPrivate: false, allowHttp: false }; const pub = async ()=>[{ address: '93.184.216.34' }]; test.each([ ['http://git.example.test/a/b', /https/], ['https://user:pw@git.example.test/a/b', /Zugangsdaten/], ['https://git.example.test/a/b?x=1', /Query/], ['https://git.example.test/a/b#f', /Query/], ['https://git.example.test/', /Pfad/], ['ssh://git@git.example.test/a/b', /https/], ['file:///etc/passwd', /https/], ['kein url', /ungültig/] ])('lehnt %s ab', async (url, msg)=>{ await expect(assertUrlAllowed(url, cfg, { lookup: pub })).rejects.toThrow(msg); }); test('öffentlicher Host ist erlaubt', async ()=>{ await expect(assertUrlAllowed('https://git.example.test:8443/a/b.git', cfg, { lookup: pub })).resolves.toBeDefined(); }); test.each(['127.0.0.1', '10.1.2.3', '172.16.0.1', '172.31.255.255', '192.168.1.1', '169.254.169.254', '100.64.0.1', '0.0.0.0', '::1', 'fd00::1', 'fe80::1', '::ffff:127.0.0.1', '::ffff:7f00:1', '::ffff:a9fe:a9fe', '::ffff:10.0.0.1', '0:0:0:0:0:ffff:7f00:1', '64:ff9b::7f00:1', '::7f00:1', '::a9fe:a9fe', '224.0.0.1'])('%s gilt als intern', (ip)=>{ expect(isPrivateAddress(ip)).toBe(true); }); test.each(['8.8.8.8', '93.184.216.34', '172.32.0.1', '2606:4700::1111'])('%s gilt als öffentlich', (ip)=>{ expect(isPrivateAddress(ip)).toBe(false); }); test('Host, der auf interne Adresse auflöst, wird abgelehnt (auch gemischt)', async ()=>{ const lookup = async ()=>[{ address: '93.184.216.34' }, { address: '10.0.0.5' }]; await expect(assertUrlAllowed('https://evil.example.test/a/b', cfg, { lookup })).rejects.toThrow(/privat|intern/i); await expect(assertUrlAllowed('https://127.0.0.1/a/b', cfg, { lookup: pub })).rejects.toThrow(); await expect(assertUrlAllowed('https://[::1]/a/b', cfg, { lookup: pub })).rejects.toThrow(); }); test.each(['[::ffff:127.0.0.1]', '[::ffff:a9fe:a9fe]', '[::ffff:10.0.0.1]', '[64:ff9b::7f00:1]', '[::7f00:1]'])('IPv6-Literal %s in der URL wird abgelehnt', async (host)=>{ await expect(assertUrlAllowed(`https://${host}/a/b.git`, cfg, { lookup: pub })).rejects.toMatchObject({ HBErrorCode: 'G08' }); }); test('HB_GIT_ALLOW_PRIVATE erlaubt interne Ziele, HB_GIT_ALLOW_HTTP http://', async ()=>{ await expect(assertUrlAllowed('http://127.0.0.1:3000/a/b', { ...cfg, allowPrivate: true, allowHttp: true })).resolves.toBeDefined(); expect(()=>parseRepoUrl('http://x.test/a/b', { allowHttp: true })).not.toThrow(); }); test('Allowlist: nur passende Hosts, Wildcard *.example.org', async ()=>{ const c = { ...cfg, allowedHosts: ['github.com', '*.example.org'] }; const never = async ()=>{ throw new Error('kein DNS nötig'); }; await expect(assertUrlAllowed('https://github.com/a/b', c, { lookup: never })).resolves.toBeDefined(); await expect(assertUrlAllowed('https://git.example.org/a/b', c, { lookup: never })).resolves.toBeDefined(); await expect(assertUrlAllowed('https://example.org/a/b', c, { lookup: never })).rejects.toThrow(/nicht erlaubt/); await expect(assertUrlAllowed('https://evilgithub.com/a/b', c, { lookup: never })).rejects.toThrow(/nicht erlaubt/); }); }); describe('Pfad- und Branch-Validierung', ()=>{ test.each(['brews/a.md', 'a.md', 'x/y/z.md'])('Pfad %s ok', (p)=>expect(validatePath(p)).toBe(p)); test.each(['', '/abs.md', '../a.md', 'a/../b.md', 'a//b.md', 'a/./b.md', '.git/config.md', 'x/.git/a.md', 'a.txt', 'a\\b.md', `${'a'.repeat(256)}.md`, 'a\0.md'])('Pfad %j abgelehnt', (p)=>{ expect(()=>validatePath(p)).toThrow(GitError); }); test('Ordner', ()=>{ expect(validateDir('brews/')).toBe('brews'); expect(validateDir('')).toBe(''); expect(()=>validateDir('../x')).toThrow(); expect(()=>validateDir('/x')).toThrow(); }); test('Branch per git check-ref-format', async ()=>{ await expect(validateBranch('main')).resolves.toBe('main'); await expect(validateBranch('feature/x-1')).resolves.toBe('feature/x-1'); for (const bad of ['', '-x', 'a..b', 'a b', 'a~1', 'a^', 'a:b', 'a?', 'a*', 'a[', 'x.lock', '@{-1}', '--upload-pack=evil', 'a//b', '/a']) { await expect(validateBranch(bad)).rejects.toBeInstanceOf(GitError); } }); test('slugify', ()=>{ expect(slugify('Dungeon Mäster: Teil 1!')).toBe('dungeon-master-teil-1'); expect(slugify('')).toBe('brew'); expect(slugify('../../etc')).toBe('etc'); }); }); describe('redact', ()=>{ test('entfernt Token, Basic-Header und Userinfo', ()=>{ const token = 'ghp_abcdef123456'; const basic = Buffer.from(`git:${token}`).toString('base64'); const text = `fatal: x ${token} Authorization: Basic ${basic} https://git:${token}@host/a ${Buffer.from(token).toString('base64')}`; const out = redact(text, token); expect(out).not.toContain(token); expect(out).not.toContain(basic); expect(out).not.toContain(Buffer.from(token).toString('base64')); expect(out).not.toMatch(/Basic [A-Za-z0-9+/=]{8,}/); }); }); describe('Locks', ()=>{ test('Concurrency-Limit und Queue-Limit (503/G05)', async ()=>{ const sem = createSemaphore(1, 1); const r1 = await sem.acquire(); const p2 = sem.acquire(); await expect(sem.acquire()).rejects.toMatchObject({ HBErrorCode: 'G05' }); r1(); (await p2)(); expect(sem.active).toBe(0); }); test('Warten wird per AbortSignal abgebrochen (G04)', async ()=>{ const sem = createSemaphore(1); const r1 = await sem.acquire(); const ac = new AbortController(); const p = sem.acquire(ac.signal); ac.abort(); await expect(p).rejects.toMatchObject({ HBErrorCode: 'G04' }); r1(); (await sem.acquire())(); expect(sem.waiting).toBe(0); }); test('Mutex pro Brew serialisiert, verschiedene Brews laufen parallel, Schlüssel werden aufgeräumt', async ()=>{ const locks = createLocks(); const order = []; const task = (name, ms)=>locks.withKey('brew-1', async ()=>{ order.push(`start ${name}`); await new Promise((r)=>setTimeout(r, ms)); order.push(`end ${name}`); }); await Promise.all([task('a', 30), task('b', 1)]); expect(order).toEqual(['start a', 'end a', 'start b', 'end b']); let parallel = 0; let max = 0; await Promise.all(['x', 'y'].map((k)=>locks.withKey(k, async ()=>{ max = Math.max(max, ++parallel); await new Promise((r)=>setTimeout(r, 20)); parallel--; }))); expect(max).toBe(2); expect(locks.keyCount).toBe(0); }); test('acquireKey/release hält den Mutex über mehrere Schritte', async ()=>{ const locks = createLocks(); const release = await locks.acquireKey('k'); let got = false; const p = locks.withKey('k', async ()=>{ got = true; }); await new Promise((r)=>setTimeout(r, 10)); expect(got).toBe(false); release(); release(); await p; expect(got).toBe(true); }); });