Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+210
View File
@@ -0,0 +1,210 @@
"use strict";
// Tests for the pinned download headers (utils/download-headers.js),
// remediation for the download-proxy hardening: the panel (/files/download)
// and nodes.js (/api/nodes/server/:name/download) relays used to forward
// node-supplied Content-Type/Content-Disposition verbatim, so a malicious
// node declaring text/html inline could execute HTML on the panel origin.
// Run: node --test utils/download-headers.test.js
//
// The suite proves: the sanitized filename strips exactly what could break
// the quoted-string or smuggle paths/headers, caps its length, falls back
// when nothing usable remains, passes ordinary names through untouched, and
// the setter pins both headers unconditionally (upstream values are never
// consulted).
const test = require("node:test");
const assert = require("node:assert");
const http = require("node:http");
const {
DOWNLOAD_CONTENT_TYPE,
DOWNLOAD_FILENAME_FALLBACK,
DOWNLOAD_FILENAME_MAX_LENGTH,
DOWNLOAD_FILENAME_STAR_CHARSET,
buildContentDisposition,
encodeRfc5987Value,
sanitizeDownloadFilename,
setPinnedDownloadHeaders,
} = require("./download-headers");
// ─── control characters ─────────────────────────────────────────────────────
test("strips control characters, including CRLF header injection", () => {
assert.strictEqual(sanitizeDownloadFilename("re\u0007port.txt"), "report.txt");
assert.strictEqual(sanitizeDownloadFilename("a\r\nX-Injected: 1.txt"), "aX-Injected: 1.txt");
assert.strictEqual(sanitizeDownloadFilename("\u001b[31mred.txt"), "[31mred.txt");
assert.strictEqual(sanitizeDownloadFilename("del\u007fte.txt"), "delte.txt");
});
test("strips quotes so the quoted-string cannot be closed or escaped", () => {
assert.strictEqual(sanitizeDownloadFilename('evil".txt'), "evil.txt");
assert.strictEqual(sanitizeDownloadFilename("it's.txt"), "its.txt");
assert.strictEqual(sanitizeDownloadFilename('a"b\\c.txt'), "abc.txt");
});
test("strips path separators from both families", () => {
assert.strictEqual(sanitizeDownloadFilename("sub/dir/file.txt"), "subdirfile.txt");
assert.strictEqual(sanitizeDownloadFilename("..\\..\\win.ini"), "....win.ini");
assert.strictEqual(sanitizeDownloadFilename("/etc/passwd"), "etcpasswd");
});
// ─── length cap ─────────────────────────────────────────────────────────────
test("caps the filename length", () => {
const long = "a".repeat(500);
const cleaned = sanitizeDownloadFilename(long);
assert.strictEqual(cleaned.length, DOWNLOAD_FILENAME_MAX_LENGTH);
assert.strictEqual(cleaned, "a".repeat(DOWNLOAD_FILENAME_MAX_LENGTH));
assert.ok(DOWNLOAD_FILENAME_MAX_LENGTH <= 150);
});
// ─── fallback ───────────────────────────────────────────────────────────────
test("falls back to 'download' when nothing usable remains", () => {
assert.strictEqual(sanitizeDownloadFilename(""), DOWNLOAD_FILENAME_FALLBACK);
assert.strictEqual(sanitizeDownloadFilename("///"), DOWNLOAD_FILENAME_FALLBACK);
assert.strictEqual(sanitizeDownloadFilename("\r\n\t"), DOWNLOAD_FILENAME_FALLBACK);
assert.strictEqual(sanitizeDownloadFilename('"\''), DOWNLOAD_FILENAME_FALLBACK);
assert.strictEqual(sanitizeDownloadFilename(null), DOWNLOAD_FILENAME_FALLBACK);
assert.strictEqual(sanitizeDownloadFilename(undefined), DOWNLOAD_FILENAME_FALLBACK);
// Non-string input is coerced; "42" is a harmless usable name.
assert.strictEqual(sanitizeDownloadFilename(42), "42");
});
// ─── passthrough ────────────────────────────────────────────────────────────
test("passes an ordinary filename through untouched", () => {
assert.strictEqual(sanitizeDownloadFilename("world.zip"), "world.zip");
assert.strictEqual(sanitizeDownloadFilename("backup-2026-10-26.tar.gz"), "backup-2026-10-26.tar.gz");
// Surrounding whitespace is trimmed; interior spacing is legitimate content.
assert.strictEqual(sanitizeDownloadFilename(" spaced name .log "), "spaced name .log");
// Non-ASCII names are legitimate content, not smuggling: the sanitizer
// preserves them (the disposition builder carries them via filename*).
assert.strictEqual(sanitizeDownloadFilename("möbelstück.txt"), "möbelstück.txt");
});
// ─── Latin-1 safety / RFC 5987 (adpanel:download-header-latin1) ─────────────
//
// Node's res.setHeader throws TypeError: Invalid character in header content
// for any header-value char > 0xFF, and both download routes call the setter
// inside the async upstream-response callback OUTSIDE their try/catch — a
// CJK/emoji basename (the upload sanitizer allows non-ASCII) killed the whole
// panel worker. These tests pin the constraint: every emitted header value is
// Latin-1-safe, the original spelling rides in the RFC 5987 filename*
// parameter, and pure-ASCII names keep the historical single-parameter shape.
function assertHeaderValueIsHeaderSafe(name, value) {
// Byte-exact statement of Node's own header-value admission rule:
// \t, 0x20-0x7E and obs-text 0x80-0xFF only.
for (const ch of value) {
const code = ch.codePointAt(0);
assert.ok(
code === 0x09 || (code >= 0x20 && code <= 0x7e) || (code >= 0x80 && code <= 0xff),
`${name}: char U+${code.toString(16)} (from ${JSON.stringify(ch)}) is not header-safe`
);
}
// The real validator: must not throw ERR_INVALID_CHAR.
assert.doesNotThrow(() => http.validateHeaderValue(name, value));
}
test("CJK filename: no setHeader throw, Latin-1 fallback + RFC 5987 filename*", () => {
const header = buildContentDisposition("テスト.txt");
assertHeaderValueIsHeaderSafe("Content-Disposition", header);
// Exact pin of the new two-parameter shape: Latin-1 projection (one "_" per
// CJK char) first, percent-encoded original spelling second.
assert.strictEqual(
header,
`attachment; filename="___.txt"; filename*=${DOWNLOAD_FILENAME_STAR_CHARSET}%E3%83%86%E3%82%B9%E3%83%88.txt`
);
});
test("setPinnedDownloadHeaders does not throw for a CJK basename (the crash scenario)", () => {
const headers = {};
const fakeRes = { setHeader: (name, value) => { headers[name] = value; } };
assert.doesNotThrow(() => setPinnedDownloadHeaders(fakeRes, "テスト.txt"));
assert.strictEqual(headers["Content-Type"], DOWNLOAD_CONTENT_TYPE);
assertHeaderValueIsHeaderSafe("Content-Disposition", headers["Content-Disposition"]);
assert.match(headers["Content-Disposition"], /^attachment; filename="__\_\.txt"; filename\*=UTF-8''/);
});
test("emoji (astral plane) encodes as one UTF-8 sequence, never lone surrogates", () => {
const sanitized = sanitizeDownloadFilename("map \u{1F5FA}.txt");
const header = buildContentDisposition(sanitized);
assertHeaderValueIsHeaderSafe("Content-Disposition", header);
const encoded = header.split(`filename*=${DOWNLOAD_FILENAME_STAR_CHARSET}`)[1];
assert.strictEqual(encoded, "map%20%F0%9F%97%BA.txt");
assert.strictEqual(decodeURIComponent(encoded), sanitized);
});
test("RFC 5987 value round-trips to the sanitized original", () => {
// Pure-ASCII names take the single-parameter shape (pinned above), so only
// non-ASCII names carry a filename* to decode.
for (const raw of ["テスト.txt", "möbelstück.txt", "заявка.zip", "café 100% rid.txt", "map 🗺.txt"]) {
const sanitized = sanitizeDownloadFilename(raw);
const header = buildContentDisposition(sanitized);
assertHeaderValueIsHeaderSafe("Content-Disposition", header);
const encoded = header.split(`filename*=${DOWNLOAD_FILENAME_STAR_CHARSET}`)[1];
assert.ok(encoded, `no filename* parameter for ${raw}`);
assert.strictEqual(decodeURIComponent(encoded), sanitized);
}
});
test("percent, apostrophe and attribute separators are always encoded in filename*", () => {
// Only A-Z a-z 0-9 - . _ ~ stay literal; % and ' must not survive raw or
// the ext-value could be closed or a parameter injected.
const encoded = encodeRfc5987Value("a%b'c;d=e?f g");
assert.strictEqual(encoded, "a%25b%27c%3Bd%3De%3Ff%20g");
for (const ch of encoded) {
assert.match(ch, /^[A-Za-z0-9._~%]$/, "unexpected literal char in encoded value");
}
});
test("Latin-1 names (ö/ü) are header-legal obs-text and keep their spelling in filename=", () => {
const sanitized = sanitizeDownloadFilename("möbelstück.txt");
const header = buildContentDisposition(sanitized);
assertHeaderValueIsHeaderSafe("Content-Disposition", header);
// The fallback keeps 0x80-0xFF (Node admits obs-text); filename* carries
// the same name percent-encoded.
assert.strictEqual(
header,
`attachment; filename="möbelstück.txt"; filename*=${DOWNLOAD_FILENAME_STAR_CHARSET}m%C3%B6belst%C3%BCck.txt`
);
});
test("non-ASCII names hit the same length cap (cap applies before the Latin-1 projection)", () => {
const cleaned = sanitizeDownloadFilename("テ".repeat(500));
assert.strictEqual(cleaned.length, DOWNLOAD_FILENAME_MAX_LENGTH);
const header = buildContentDisposition(cleaned);
assertHeaderValueIsHeaderSafe("Content-Disposition", header);
// 150 CJK chars cap to 150 chars; the projection is 150 "_" in the
// quoted-string, the full spelling rides in filename*.
assert.match(header, new RegExp(`^attachment; filename="${"_".repeat(150)}"; filename\\*=`));
});
test("pure-ASCII names keep the historical single-parameter header (no filename*)", () => {
assert.strictEqual(buildContentDisposition("world.zip"), 'attachment; filename="world.zip"');
assert.strictEqual(buildContentDisposition("spaced name .log"), 'attachment; filename="spaced name .log"');
assert.strictEqual(buildContentDisposition("42"), 'attachment; filename="42"');
assert.strictEqual(
buildContentDisposition("a".repeat(DOWNLOAD_FILENAME_MAX_LENGTH)),
`attachment; filename="${"a".repeat(DOWNLOAD_FILENAME_MAX_LENGTH)}"`
);
});
// ─── header pinning ─────────────────────────────────────────────────────────
test("setPinnedDownloadHeaders always pins octet-stream + attachment, ignoring upstream type", () => {
const headers = {};
const fakeRes = { setHeader: (name, value) => { headers[name] = value; } };
setPinnedDownloadHeaders(fakeRes, "world.zip");
assert.strictEqual(headers["Content-Type"], "application/octet-stream");
assert.strictEqual(headers["Content-Type"], DOWNLOAD_CONTENT_TYPE);
assert.strictEqual(headers["Content-Disposition"], 'attachment; filename="world.zip"');
});
test("pinned disposition is safe even for hostile input", () => {
assert.strictEqual(buildContentDisposition('a\r\nX-Evil: 1'), 'attachment; filename="aX-Evil: 1"');
assert.strictEqual(buildContentDisposition('..\\..\\win.ini'), 'attachment; filename="....win.ini"');
assert.strictEqual(buildContentDisposition(""), `attachment; filename="${DOWNLOAD_FILENAME_FALLBACK}"`);
});