Hardens the upload path check and the deploy verification

A remote of . or .. could have made the cleanup pass delete the wrong folder, so
such paths are refused before anything runs. A connection error now ends in the
normal summary instead of aborting the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-01 19:31:21 +01:00
co-authored by Claude Opus 5.5
parent afd9923950
commit 6d4d01238a
9 changed files with 215 additions and 15 deletions
+80 -2
View File
@@ -13,10 +13,88 @@ fi
dist="${1%/}"
remote="${2%/}"
# De paden komen in een lftp-opdracht; daarom geen spaties of quotes
# De paden komen in een lftp-opdracht; daarom geen spaties of quotes. Ook geen
# '.' of '..' (ronde 3 verwijdert: '.' is de FTP-thuismap, '..' de map erboven),
# geen lege segmenten en niets dat met '-' begint (zou een optie worden).
safe='^[A-Za-z0-9._/-]+$'
valid_path() {
local value="$1" segment
[[ "$value" =~ $safe ]] || return 1
[[ "$value" != -* ]] || return 1
[[ "$value" != *//* ]] || return 1
local IFS=/
for segment in ${value#/}; do
case "$segment" in . | ..) return 1 ;; esac
done
}
for value in "$dist" "$remote"; do
if ! [[ "$value" =~ $safe ]]; then
if ! valid_path "$value"; then
echo "Ongeldig pad: '$value'" >&2
exit 2
fi
done
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
bash "$here/check-artifact.sh" "$dist"
cp "$here/iis/web.config" "$dist/web.config"
pass="${UPLOAD_PASS:-all}"
case "$pass" in
all | 1 | 2 | 3) ;;
*) echo "Ongeldige UPLOAD_PASS: '$pass'" >&2; exit 2 ;;
esac
wants() { [ "$pass" = all ] || [ "$pass" = "$1" ]; }
settings="set ftp:ssl-force true; set ftp:ssl-protect-data true; set net:max-retries 3;"
# Elke opdracht krijgt een eigen lftp-sessie, zodat het script bij een mislukte
# ronde stopt (set -e) voordat de volgende ronde begint: de HTML gaat nooit
# omhoog na een mislukte asset-ronde (FR-PR-18).
run_lftp() {
local commands="$settings $1 quit"
if [ -n "${LFTP_OPEN:-}" ]; then
lftp -e "$commands" "$LFTP_OPEN"
else
: "${FTP_HOST:?FTP_HOST ontbreekt}" "${FTP_USER:?FTP_USER ontbreekt}"
: "${LFTP_PASSWORD:?LFTP_PASSWORD ontbreekt}"
lftp --env-password -u "$FTP_USER" "$FTP_HOST" -e "$commands"
fi
}
# Ronde 1: alles behalve HTML en web.config, dus ook /assets. Nieuwe
# bestanden met hash in de naam storen de oude release niet.
if wants 1; then
echo "== Ronde 1: alles behalve HTML en web.config"
run_lftp "mirror --reverse --verbose --exclude-glob '*.html' --exclude-glob web.config $dist/ $remote/;"
fi
# Ronde 2: web.config vlak voor de HTML (de regels passen bij de nieuwe
# bestanden), dan alle HTML, ook de geneste pagina's en 404.html. Pas nu
# verwijst iets naar de nieuwe assets.
if wants 2; then
echo "== Ronde 2: web.config en alle HTML"
run_lftp "put -O $remote $dist/web.config;"
run_lftp "mirror --reverse --verbose --include-glob '*.html' $dist/ $remote/;"
fi
# Ronde 3: opruimen als laatste, zodat bezoekers met de oude HTML hun oude
# assets nog vinden tot de nieuwe HTML helemaal staat.
if wants 3; then
echo "== Ronde 3: oude bestanden opruimen"
run_lftp "mirror --reverse --delete --verbose $dist/ $remote/;"
fi
valid_path() {
local value="$1" segment
[[ "$value" =~ $safe ]] || return 1
[[ "$value" != -* ]] || return 1
# Het eerste segment van een absoluut pad is leeg; dat is toegestaan
for segment in ${value#/}; do :; done
local rest="${value#/}" IFS=/
for segment in $rest; do
case "$segment" in '' | . | ..) return 1 ;; esac
done
}
for value in "$dist" "$remote"; do
if ! valid_path "$value"; then
echo "Ongeldig pad: '$value'" >&2
exit 2
fi
+7 -2
View File
@@ -49,8 +49,13 @@ fetch() {
shift
: > "$work/headers"
: > "$work/body"
status="$(curl -sS --max-time 30 -o "$work/body" -D "$work/headers" \
-w '%{http_code}' "$@" "$base$path")"
# Geen verbinding of antwoord telt als fout; het script loopt door tot de
# samenvatting in plaats van af te breken
if ! status="$(curl -sS --max-time 30 -o "$work/body" -D "$work/headers" \
-w '%{http_code}' "$@" "$base$path")"; then
status="000"
fail "$path: geen antwoord van de server (curl faalde)"
fi
}
# Waarde van een header uit de laatst opgehaalde respons (hoofdletterongevoelig)
+116 -2
View File
@@ -16,7 +16,7 @@ import {
} from 'node:http';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
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';
@@ -81,12 +81,17 @@ function runScript(
script: string,
args: string[],
env: Record<string, string> = {},
cwd?: string,
): Promise<Run> {
return new Promise((done) => {
execFile(
bashBin ?? 'bash',
[`${deployDir}/${script}`, ...args],
{ env: { ...process.env, ...env }, maxBuffer: 16 * 1024 * 1024 },
{
cwd,
env: { ...process.env, ...env },
maxBuffer: 16 * 1024 * 1024,
},
(error, stdout, stderr) =>
done({
code: error ? Number(error.code ?? 1) : 0,
@@ -195,6 +200,8 @@ interface StubOptions {
omitHeader?: string;
gzip?: boolean;
robots?: boolean;
// Pad waarvan de verbinding wordt verbroken, zonder antwoord
drop?: string;
}
async function startStub(
@@ -240,6 +247,10 @@ async function startStub(
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
@@ -418,6 +429,23 @@ describe.skipIf(toolsMissing)('verify-deployment.sh', () => {
);
});
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) => {
@@ -529,3 +557,89 @@ describe.skipIf(toolsMissing || lftpMissing)('upload-production.sh', () => {
);
});
});
// 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.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);
});
},
);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import { afterEach, vi } from 'vitest';
// breakpoint hooks (min-width queries) and prefers-reduced-motion behave as
// in a browser. jsdom has no layout and ignores @media rules, so the
// responsive display of the desktop list and the mobile menu is applied by a
// style element here (the browser check is Step 17). The stub is undone by
// style element here (the browser tests in e2e/ check the real layout). The stub is undone by
// vi.restoreAllMocks() in the global afterEach.
const styleId = 'nav-viewport-style';