Files
AndreaSlopFotografie/web/e2e/deployScripts.e2e.ts
T
SluijsensandClaude Sonnet 5.5 41a6e7be5a Prepares the test site for the CMS host
The test route on the proxy Pi now points at the CMS host on port 5200.
verify-deployment.sh gets a --cms mode that checks the exact security
headers, caching, gzip only, a percent-encoded redirect, the 405 for
POST, and the CMS routes. The deploy-test job uses it once the Gitea
variable ASF_TEST_SERVED_BY_CMS is true.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 02:05:59 +01:00

720 lines
24 KiB
TypeScript

import { execFile, spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import {
mkdir,
mkdtemp,
readdir,
readFile,
rm,
writeFile,
} from 'node:fs/promises';
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'node:http';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { basename, delimiter, dirname, join, resolve } from 'node:path';
import { gzipSync } from 'node:zlib';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { startPreviewServer } from '../config/previewServer.ts';
import { securityHeaders } from '../config/securityHeaders.ts';
import { createFixtureSite, type FixtureSite } from './support/fixtureSite.ts';
// De deploy-scripts uit web/deploy: de artefactcontrole, de controle na een
// deploy en de upload naar productie (BR-HST-14, 15, 18). Alles draait tegen
// een fixture-site, een stub of een lokaal doel; er gaat niets het netwerk op.
const inCi = Boolean(process.env.CI);
const deployDir = resolve('deploy').replaceAll('\\', '/');
// Op Windows is `bash` in het PATH soms de WSL-launcher in System32; die
// start een distributie. Daarom Git Bash zoeken, naast git.exe of in het PATH.
function findBash(): string | undefined {
if (process.platform !== 'win32') {
return spawnSync('bash', ['-c', 'true']).status === 0
? 'bash'
: undefined;
}
const candidates = (process.env.PATH ?? '')
.split(';')
.filter(Boolean)
.flatMap((dir) => [
join(dir, 'bash.exe'),
join(dir, '..', 'bin', 'bash.exe'),
join(dir, '..', 'usr', 'bin', 'bash.exe'),
])
.filter((candidate) => !/system32/i.test(candidate));
return candidates.find(
(candidate) =>
existsSync(candidate) &&
spawnSync(candidate, ['-c', 'true']).status === 0,
);
}
const hasCommand = (name: string) =>
spawnSync(name, ['--version'], { stdio: 'ignore' }).status === 0;
const bashBin = findBash();
const toolsMissing = !bashBin || !hasCommand('curl');
// Zonder bash of curl: in CI een duidelijke fout, lokaal een zichtbare melding
if (toolsMissing) {
describe('deploy-scripts', () => {
it('bash of curl niet gevonden: deploy-scripttests overgeslagen', (context) => {
if (inCi) throw new Error('bash of curl ontbreekt in CI');
console.log(context.task.name);
context.skip();
});
});
}
interface Run {
code: number;
stdout: string;
stderr: string;
}
function runScript(
script: string,
args: string[],
env: Record<string, string> = {},
cwd?: string,
): Promise<Run> {
return new Promise((done) => {
execFile(
bashBin ?? 'bash',
[`${deployDir}/${script}`, ...args],
{
cwd,
env: { ...process.env, ...env },
maxBuffer: 16 * 1024 * 1024,
},
(error, stdout, stderr) =>
done({
code: error ? Number(error.code ?? 1) : 0,
stdout,
stderr,
}),
);
});
}
const slash = (path: string) => path.replaceAll('\\', '/');
const temporaryDirs: string[] = [];
async function makeTemp(prefix: string): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), prefix));
temporaryDirs.push(dir);
return dir;
}
afterAll(async () => {
await Promise.all(
temporaryDirs.map((dir) => rm(dir, { recursive: true, force: true })),
);
});
async function tree(dir: string, base = dir): Promise<string[]> {
const result: string[] = [];
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) result.push(...(await tree(full, base)));
else result.push(slash(full.slice(base.length + 1)));
}
return result.sort();
}
async function write(dir: string, file: string, content = file) {
const target = join(dir, file);
await mkdir(dirname(target), { recursive: true });
await writeFile(target, content);
}
// Een minimale, geldige dist voor de artefactcontrole en de upload
const validFiles = [
'index.html',
'404.html',
'over-mij.html',
'soorten-fotoshoots/newborn.html',
'assets/a.js',
'robots.txt',
];
async function makeDist(): Promise<string> {
const dir = await makeTemp('andreaslop-dist-');
for (const file of validFiles) await write(dir, file);
return dir;
}
describe.skipIf(toolsMissing)('check-artifact.sh', () => {
it('laat een geldige build door en meldt wat het vond', async () => {
const dist = await makeDist();
const run = await runScript('check-artifact.sh', [slash(dist)]);
expect(run.code).toBe(0);
expect(run.stdout).toContain('index.html');
expect(run.stdout).toContain('404.html');
expect(run.stdout).toContain('over-mij.html');
});
it.each(['index.html', '404.html', 'over-mij.html'])(
'weigert een build zonder %s',
async (file) => {
const dist = await makeDist();
await rm(join(dist, file));
const run = await runScript('check-artifact.sh', [slash(dist)]);
expect(run.code).toBe(1);
expect(run.stderr).toContain(`${file} ontbreekt`);
},
);
it('weigert een build met een servermap', async () => {
const dist = await makeDist();
await write(dist, 'server/server.js');
const run = await runScript('check-artifact.sh', [slash(dist)]);
expect(run.code).toBe(1);
expect(run.stderr).toContain('server');
});
it('weigert een source map, ook diep in de map', async () => {
const dist = await makeDist();
await write(dist, 'assets/deep/a.js.map');
const run = await runScript('check-artifact.sh', [slash(dist)]);
expect(run.code).toBe(1);
expect(run.stderr).toContain('a.js.map');
});
it('weigert een map die niet bestaat', async () => {
const run = await runScript('check-artifact.sh', [
slash(join(tmpdir(), 'bestaat-niet-andreaslop')),
]);
expect(run.code).not.toBe(0);
});
});
// Een kleine server met de bedoelde regels (nieuw) of met het oude gedrag van
// de SPA-config (oud: elk pad geeft index.html met 200). Bij 'nieuw' kan een
// header of de gzip weggelaten worden.
interface StubOptions {
behaviour: 'new' | 'old';
omitHeader?: string;
gzip?: boolean;
robots?: boolean;
// Pad waarvan de verbinding wordt verbroken, zonder antwoord
drop?: string;
}
async function startStub(
dir: string,
options: StubOptions,
): Promise<{ origin: string; close: () => Promise<void> }> {
const headers: Record<string, string> = {
...securityHeaders('production'),
};
if (options.robots) headers['X-Robots-Tag'] = 'noindex, nofollow';
if (options.omitHeader) delete headers[options.omitHeader];
const files = new Set(await tree(dir));
const pages = new Set(
[...files]
.filter((file) => file.endsWith('.html') && file !== '404.html')
.map((file) =>
file === 'index.html' ? '/' : '/' + file.slice(0, -5),
),
);
const reply = async (
request: IncomingMessage,
response: ServerResponse,
status: number,
file: string,
) => {
const body = await readFile(join(dir, file));
const gzipped =
options.gzip === true &&
file.endsWith('.js') &&
/gzip/.test(request.headers['accept-encoding'] ?? '');
response.writeHead(status, {
...headers,
...(gzipped ? { 'Content-Encoding': 'gzip' } : {}),
});
response.end(gzipped ? gzipSync(body) : body);
};
const redirect = (response: ServerResponse, location: string) => {
response.writeHead(301, { ...headers, Location: location });
response.end();
};
const server: Server = createServer((request, response) => {
const path = (request.url ?? '/').split('?')[0];
if (path === options.drop) {
request.socket.destroy();
return;
}
void (async () => {
if (options.behaviour === 'old') {
// Oude nginx: bestaand bestand, anders de homepage met 200
const file = path.slice(1);
await reply(
request,
response,
200,
files.has(file) ? file : 'index.html',
);
return;
}
if (files.has(path.slice(1)) && path !== '/') {
await reply(request, response, 200, path.slice(1));
} else if (pages.has(path)) {
await reply(
request,
response,
200,
path === '/' ? 'index.html' : `${path.slice(1)}.html`,
);
} else if (path.length > 1 && path.endsWith('/')) {
redirect(response, path.slice(0, -1));
} else if (pages.has(path.toLowerCase())) {
redirect(response, path.toLowerCase());
} else {
await reply(request, response, 404, '404.html');
}
})();
});
await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
const { port } = server.address() as AddressInfo;
return {
origin: `http://127.0.0.1:${port}`,
close: () =>
new Promise<void>((done, fail) => {
server.close((error) => (error ? fail(error) : done()));
server.closeAllConnections();
}),
};
}
describe.skipIf(toolsMissing)('verify-deployment.sh', () => {
let site: FixtureSite;
let dist: string;
beforeAll(async () => {
site = await createFixtureSite();
dist = slash(site.dir);
// De homepage verwijst naar de JavaScript, voor de compressiecontrole
await writeFile(
join(site.dir, 'index.html'),
'<!doctype html><html><head><script src="/assets/index-AbC123xYz.js"></script></head><body>fixture:index.html</body></html>',
);
});
afterAll(() => site.remove());
const withStub = async <T>(
options: StubOptions,
action: (origin: string) => Promise<T>,
) => {
const stub = await startStub(site.dir, options);
try {
return await action(stub.origin);
} finally {
await stub.close();
}
};
it('slaagt tegen de previewserver op de fixture-site', async () => {
const server = await startPreviewServer(site.dir, 0);
const { port } = server.address() as AddressInfo;
try {
const run = await runScript('verify-deployment.sh', [
`http://127.0.0.1:${port}`,
dist,
]);
expect(run.stderr).not.toContain('FOUT');
expect(run.code).toBe(0);
expect(run.stdout).toContain('Controle geslaagd');
} finally {
await new Promise<void>((done) => {
server.close(() => done());
server.closeAllConnections();
});
}
});
it('slaagt tegen een server met de bedoelde regels, ook met een slash aan het eind van de URL', async () => {
await withStub({ behaviour: 'new' }, async (origin) => {
const run = await runScript('verify-deployment.sh', [
`${origin}/`,
dist,
]);
expect(run.stderr).not.toContain('FOUT');
expect(run.code).toBe(0);
});
});
it('faalt tegen het oude gedrag (homepage voor elk pad) en noemt de bytes van /over-mij (V11)', async () => {
await withStub({ behaviour: 'old' }, async (origin) => {
const run = await runScript('verify-deployment.sh', [origin, dist]);
expect(run.code).toBe(1);
expect(run.stderr).toContain(
'/over-mij: antwoord is niet gelijk aan over-mij.html',
);
expect(run.stderr).toContain('status 200, verwacht 404');
expect(run.stderr).toContain(
'/over-mij/: status 200, verwacht 301',
);
});
});
it.each(Object.keys(securityHeaders('production')))(
'faalt als %s ontbreekt',
async (name) => {
await withStub(
{ behaviour: 'new', omitHeader: name },
async (origin) => {
const run = await runScript('verify-deployment.sh', [
origin,
dist,
]);
expect(run.code).toBe(1);
expect(run.stderr).toContain(`header ${name} ontbreekt`);
},
);
},
);
it('met --test: slaagt met X-Robots-Tag en gzip', async () => {
await withStub(
{ behaviour: 'new', robots: true, gzip: true },
async (origin) => {
const run = await runScript('verify-deployment.sh', [
origin,
dist,
'--test',
]);
expect(run.stderr).not.toContain('FOUT');
expect(run.code).toBe(0);
},
);
});
it('met --test: faalt zonder X-Robots-Tag', async () => {
await withStub({ behaviour: 'new', gzip: true }, async (origin) => {
const run = await runScript('verify-deployment.sh', [
origin,
dist,
'--test',
]);
expect(run.code).toBe(1);
expect(run.stderr).toContain('header X-Robots-Tag ontbreekt');
});
});
it('met --test: faalt zonder gzip, zonder --test is dat een waarschuwing', async () => {
await withStub(
{ behaviour: 'new', robots: true, gzip: false },
async (origin) => {
const strict = await runScript('verify-deployment.sh', [
origin,
dist,
'--test',
]);
expect(strict.code).toBe(1);
expect(strict.stderr).toContain('geen Content-Encoding: gzip');
const lenient = await runScript('verify-deployment.sh', [
origin,
dist,
]);
expect(lenient.code).toBe(0);
expect(lenient.stderr).toContain('WAARSCHUWING');
},
);
});
it('met --cms: weigert te starten zonder EXPECTED_CSP', async () => {
const run = await runScript(
'verify-deployment.sh',
['http://127.0.0.1:9', dist, '--test', '--cms'],
{ EXPECTED_CSP: '' },
);
expect(run.code).toBe(2);
expect(run.stderr).toContain('EXPECTED_CSP');
});
it('met --cms: meldt een afwijkende CSP en de ontbrekende CMS-routes', async () => {
// De gewone stub is een nginx-achtige server: geen /health, /admin/
// of API, en een andere CSP dan hier verwacht
await withStub(
{ behaviour: 'new', robots: true, gzip: true },
async (origin) => {
const run = await runScript(
'verify-deployment.sh',
[origin, dist, '--test', '--cms'],
{ EXPECTED_CSP: "default-src 'none'" },
);
expect(run.code).toBe(1);
expect(run.stderr).toContain(
"header Content-Security-Policy is '",
);
expect(run.stderr).toContain('/health: status 404');
expect(run.stderr).toContain('/admin/: status 301');
},
);
});
it('telt een verbroken verbinding als fout en eindigt met de samenvatting', async () => {
await withStub(
{ behaviour: 'new', drop: '/over-mij' },
async (origin) => {
const run = await runScript('verify-deployment.sh', [
origin,
dist,
]);
expect(run.code).toBe(1);
expect(run.stderr).toContain(
'/over-mij: geen antwoord van de server',
);
expect(run.stderr).toContain('Controle mislukt');
},
);
});
it.each(['', 'ftp://example.nl', 'http://a b', 'example.nl'])(
'weigert de ongeldige URL %j',
async (url) => {
const run = await runScript('verify-deployment.sh', [url, dist]);
expect(run.code).toBe(2);
expect(run.stderr).toContain('Ongeldige URL');
},
);
});
// lftp staat niet overal (lokaal vaak niet; CI installeert het): zonder lftp
// lokaal een zichtbare melding, in CI een fout
const lftpMissing = !hasCommand('lftp') || process.platform === 'win32';
if (lftpMissing) {
describe('upload-production.sh', () => {
it('lftp niet gevonden: uploadtest overgeslagen (de lftp-syntaxis blijft onbewezen)', (context) => {
if (inCi) throw new Error('lftp ontbreekt in CI');
console.log(context.task.name);
context.skip();
});
});
}
describe.skipIf(toolsMissing || lftpMissing)('upload-production.sh', () => {
const upload = async (
dist: string,
target: string,
pass?: '1' | '2' | '3',
) =>
runScript('upload-production.sh', [slash(dist), slash(target)], {
LFTP_OPEN: 'file:///',
...(pass ? { UPLOAD_PASS: pass } : {}),
});
async function setup() {
const dist = await makeDist();
const target = await makeTemp('andreaslop-target-');
await write(target, 'stale.txt');
return { dist, target };
}
it('zet de rondes in volgorde: eerst alles behalve HTML, dan HTML, dan opruimen', async () => {
const { dist, target } = await setup();
const first = await upload(dist, target, '1');
expect(first.code).toBe(0);
expect(await tree(target)).toEqual([
'assets/a.js',
'robots.txt',
'stale.txt',
]);
const second = await upload(dist, target, '2');
expect(second.code).toBe(0);
expect(await tree(target)).toEqual([
'404.html',
'assets/a.js',
'index.html',
'over-mij.html',
'robots.txt',
'soorten-fotoshoots/newborn.html',
'stale.txt',
'web.config',
]);
const third = await upload(dist, target, '3');
expect(third.code).toBe(0);
expect(await tree(target)).toEqual([
'404.html',
'assets/a.js',
'index.html',
'over-mij.html',
'robots.txt',
'soorten-fotoshoots/newborn.html',
'web.config',
]);
});
it('doet de rondes in volgorde en eindigt met de volledige boom (FR-PR-18)', async () => {
const { dist, target } = await setup();
const run = await upload(dist, target);
expect(run.code).toBe(0);
// De volgorde zelf volgt uit de rondes hierboven (na ronde 1 staat er
// nog geen HTML); hier alleen dat het script ze in die volgorde doet
const rounds = [...run.stdout.matchAll(/^== Ronde (\d)/gm)].map(
(match) => match[1],
);
expect(rounds).toEqual(['1', '2', '3']);
const expected = [...validFiles, 'web.config'].sort();
expect(await tree(target)).toEqual(expected);
});
it('laat bij een tweede deploy geen back-upbestanden met ~ achter', async () => {
const { dist, target } = await setup();
expect((await upload(dist, target)).code).toBe(0);
// Nu bestaat web.config al op de host, en alles wordt overschreven
await write(dist, 'robots.txt', 'nieuwe inhoud');
expect((await upload(dist, target)).code).toBe(0);
const files = await tree(target);
expect(files.filter((file) => file.includes('~'))).toEqual([]);
expect(files).toContain('web.config');
});
it('weigert een ongeldige build en uploadt dan niets', async () => {
const { dist, target } = await setup();
await rm(join(dist, 'index.html'));
const run = await upload(dist, target);
expect(run.code).not.toBe(0);
expect(await tree(target)).toEqual(['stale.txt']);
});
it('neemt de web.config uit deploy/iis over', async () => {
const { dist, target } = await setup();
const run = await upload(dist, target);
expect(run.code).toBe(0);
expect(await readFile(join(target, 'web.config'), 'utf8')).toBe(
await readFile(join(deployDir, 'iis/web.config'), 'utf8'),
);
});
});
// Pad-controle van upload-production.sh: een nep-lftp laat zien of er iets
// gestart is. Ronde 3 verwijdert, dus '.' of '..' als doel mag nooit door.
describe.skipIf(toolsMissing)('upload-production.sh (padcontrole)', () => {
async function withFakeLftp<T>(
action: (env: Record<string, string>, marker: string) => Promise<T>,
) {
const bin = await makeTemp('andreaslop-fakebin-');
const marker = join(bin, 'gestart');
await writeFile(
join(bin, 'lftp'),
`#!/bin/sh
touch '${slash(marker)}'
`,
{ mode: 0o755 },
);
return action(
{
PATH: `${bin}${delimiter}${process.env.PATH ?? ''}`,
LFTP_OPEN: 'file:///',
},
marker,
);
}
it.each([
'.',
'..',
'../x',
'a/../b',
'./x',
'a/./b',
'-x',
'',
'/',
'a//b',
])('weigert de doelmap %j en start niets', async (remote) => {
const dist = await makeDist();
await withFakeLftp(async (env, marker) => {
const run = await runScript(
'upload-production.sh',
[slash(dist), remote],
env,
);
expect(run.code).toBe(2);
expect(run.stderr).toContain('Ongeldig pad');
expect(existsSync(marker)).toBe(false);
});
expect(existsSync(join(dist, 'web.config'))).toBe(false);
});
it.each(['.', '..', '-d', 'a/../dist'])(
'weigert de dist-map %j en start niets',
async (dist) => {
await withFakeLftp(async (env, marker) => {
const run = await runScript(
'upload-production.sh',
[dist, 'wwwroot'],
env,
);
expect(run.code).toBe(2);
expect(run.stderr).toContain('Ongeldig pad');
expect(existsSync(marker)).toBe(false);
});
},
);
it('zet in elke lftp-sessie de back-ups uit en de TLS-eisen aan', async () => {
const dist = await makeDist();
const bin = await makeTemp('andreaslop-fakebin-');
const log = join(bin, 'opdrachten');
await writeFile(
join(bin, 'lftp'),
`#!/bin/sh
printf '%s\\n' "$2" >> '${slash(log)}'
`,
{ mode: 0o755 },
);
const run = await runScript(
'upload-production.sh',
[basename(dist), 'wwwroot'],
{
PATH: `${bin}${delimiter}${process.env.PATH ?? ''}`,
LFTP_OPEN: 'file:///',
},
dirname(dist),
);
expect(run.code).toBe(0);
const sessions = (await readFile(log, 'utf8'))
.split('\n')
.filter(Boolean);
// Ronde 1, web.config, ronde 2 (HTML) en ronde 3
expect(sessions).toHaveLength(4);
for (const commands of sessions) {
expect(commands).toContain('set xfer:make-backup no;');
expect(commands).toContain('set ftp:ssl-force true;');
}
});
it.each(['wwwroot', 'sites/andreaslop.nl', '/srv/site', 'wwwroot/'])(
'laat de doelmap %j door',
async (remote) => {
const dist = await makeDist();
await withFakeLftp(async (env, marker) => {
// Relatief aan de map erboven: een Windows-pad met een
// stationsletter haalt de padcontrole niet
const run = await runScript(
'upload-production.sh',
[basename(dist), remote],
env,
dirname(dist),
);
expect(run.code).toBe(0);
expect(existsSync(marker)).toBe(true);
});
},
);
});