phase 1 rework
This commit is contained in:
1 parent
211bfd174d
commit
20054198f3
38 files changed
+5001
-1019
No files matched your search
@@ -0,0 +1,213 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { executeJob, processClaimedJob, claimNextJob, RESULT_PREFIX } = require('../queue_worker');
|
||||
|
||||
const repository = path.resolve(__dirname, '..');
|
||||
const cookie = 'fixture_cookie=fixture-value==';
|
||||
|
||||
async function offlineCli(t, mode, { filename = 'Fixture Episode' } = {}) {
|
||||
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'proxer-cli-integration-'));
|
||||
const outputDir = path.join(directory, 'output');
|
||||
const fakeLibrary = path.join(directory, 'lib');
|
||||
await fs.mkdir(outputDir);
|
||||
await fs.mkdir(fakeLibrary);
|
||||
await fs.copyFile(path.join(repository, 'scripts/proxer-dl-video.py'), path.join(directory, 'proxer-dl-video.py'));
|
||||
await fs.copyFile(path.join(repository, 'scripts/request_validation.py'), path.join(directory, 'request_validation.py'));
|
||||
await fs.writeFile(path.join(fakeLibrary, '__init__.py'), '# Offline fixture package only.\n');
|
||||
const stub = mode === 'missing-dependency'
|
||||
? 'raise ImportError("Synthetic missing dependency; fixture-value==")\n'
|
||||
: `import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
CALLS = []
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
class NetworkError(Exception):
|
||||
pass
|
||||
|
||||
class NotFoundError(Exception):
|
||||
pass
|
||||
|
||||
def record(name):
|
||||
CALLS.append(name)
|
||||
(ROOT / "calls.json").write_text(json.dumps(CALLS), encoding="utf-8")
|
||||
|
||||
def get_embed_url(url, auth_cookie):
|
||||
assert CALLS == []
|
||||
assert url == "https://proxer.me/watch/42/1/engsub"
|
||||
assert auth_cookie == ("fixture_cookie", "fixture-value==")
|
||||
assert "--token-stdin" in sys.argv
|
||||
assert not any("fixture-value" in argument for argument in sys.argv)
|
||||
assert sys.dont_write_bytecode is True
|
||||
assert os.environ["PYTHONDONTWRITEBYTECODE"] == "1"
|
||||
record("embed")
|
||||
if ${mode === 'embed-resolution' ? 'True' : 'False'}:
|
||||
raise NotFoundError("Synthetic missing embed fixture-value==")
|
||||
return "https://fixture.invalid/embed"
|
||||
|
||||
def get_mp4_url(embed_url):
|
||||
assert CALLS == ["embed"]
|
||||
assert embed_url == "https://fixture.invalid/embed"
|
||||
record("media")
|
||||
if ${mode === 'media-resolution' ? 'True' : 'False'}:
|
||||
raise NotFoundError("Synthetic missing media fixture-value==")
|
||||
return "https://fixture.invalid/video.mp4?signature=synthetic-secret"
|
||||
|
||||
def download_mp4(mp4_url, save_path, label=""):
|
||||
assert CALLS == ["embed", "media"]
|
||||
assert mp4_url == "https://fixture.invalid/video.mp4?signature=synthetic-secret"
|
||||
assert label == ${JSON.stringify('Downloading ' + filename)}
|
||||
assert Path(save_path).parent == ROOT / "output"
|
||||
record("download")
|
||||
if ${mode === 'network-error' ? 'True' : 'False'}:
|
||||
raise NetworkError("Synthetic request failure fixture-value== " + mp4_url)
|
||||
Path(save_path).write_bytes(b"synthetic-MP4-payload")
|
||||
`;
|
||||
await fs.writeFile(path.join(fakeLibrary, 'proxer_utils.py'), stub);
|
||||
let child = null;
|
||||
t.after(async () => {
|
||||
if (child) child.kill('SIGTERM');
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
const settings = {
|
||||
projectRoot: directory,
|
||||
videoScript: path.join(directory, 'proxer-dl-video.py'),
|
||||
outputDir,
|
||||
pythonPath: process.env.TEST_PYTHON || 'python3',
|
||||
};
|
||||
const job = {
|
||||
_id: 'integration-fixture', filename,
|
||||
url: 'https://www.proxer.me:443/watch/42/1/engsub/#player', token: cookie,
|
||||
};
|
||||
const result = await executeJob(job, { settings, onChild: process => { child = process; } });
|
||||
return { directory, outputDir, result, job };
|
||||
}
|
||||
|
||||
function resultRecord(output) {
|
||||
const records = output.split(/\r?\n/).filter(line => line.startsWith(RESULT_PREFIX));
|
||||
assert.equal(records.length, 1, 'exactly one machine-readable result must survive the subprocess protocol');
|
||||
return JSON.parse(records[0].slice(RESULT_PREFIX.length));
|
||||
}
|
||||
|
||||
async function assertNoBytecode(directory) {
|
||||
const entries = await fs.readdir(directory, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
assert.notEqual(entry.name, '__pycache__');
|
||||
assert.ok(!entry.name.endsWith('.pyc'));
|
||||
if (entry.isDirectory()) await assertNoBytecode(path.join(directory, entry.name));
|
||||
}
|
||||
}
|
||||
|
||||
test('real Node-to-Python subprocess preserves stdin credentials, stream call order and successful completion', { timeout: 10000 }, async t => {
|
||||
const { directory, outputDir, result } = await offlineCli(t, 'success');
|
||||
assert.equal(result.ok, true, result.output);
|
||||
assert.equal(result.exitCode, 0);
|
||||
assert.deepEqual(resultRecord(result.output), { version: 1, status: 'completed' });
|
||||
assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')), ['embed', 'media', 'download']);
|
||||
assert.equal(await fs.readFile(path.join(outputDir, 'Fixture Episode.mp4'), 'utf8'), 'synthetic-MP4-payload');
|
||||
assert.doesNotMatch(result.output, /fixture-value|synthetic-secret|fixture\.invalid/);
|
||||
await assertNoBytecode(directory);
|
||||
});
|
||||
|
||||
test('real Python stream failure exits nonzero and reaches Node with a sanitized network result', { timeout: 10000 }, async t => {
|
||||
const { directory, outputDir, result } = await offlineCli(t, 'network-error');
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.exitCode, 1);
|
||||
assert.equal(result.errorCategory, 'network');
|
||||
assert.equal(result.infrastructureFailure, false);
|
||||
const record = resultRecord(result.output);
|
||||
assert.equal(record.status, 'failed');
|
||||
assert.equal(record.errorCategory, 'network');
|
||||
assert.match(record.message, /source could not be reached or the transfer was interrupted/);
|
||||
assert.doesNotMatch(result.output, /fixture-value|synthetic-secret|Synthetic request failure|Traceback|fixture\.invalid/);
|
||||
assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')), ['embed', 'media', 'download']);
|
||||
assert.deepEqual(await fs.readdir(outputDir), []);
|
||||
await assertNoBytecode(directory);
|
||||
});
|
||||
|
||||
test('real Python dependency failure becomes an infrastructure result without a transfer', { timeout: 10000 }, async t => {
|
||||
const { directory, outputDir, result } = await offlineCli(t, 'missing-dependency');
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.exitCode, 1);
|
||||
assert.equal(result.errorCategory, 'configuration');
|
||||
assert.equal(result.infrastructureFailure, true);
|
||||
const record = resultRecord(result.output);
|
||||
assert.equal(record.status, 'failed');
|
||||
assert.match(record.message, /dependencies could not be loaded/);
|
||||
assert.doesNotMatch(result.output, /fixture-value|Synthetic missing dependency|Traceback/);
|
||||
assert.deepEqual(await fs.readdir(outputDir), []);
|
||||
await assert.rejects(fs.access(path.join(directory, 'calls.json')));
|
||||
await assertNoBytecode(directory);
|
||||
});
|
||||
|
||||
test('real subprocess treats a leading-dash filename as a value rather than a CLI option', { timeout: 10000 }, async t => {
|
||||
const filename = '-Fixture Episode';
|
||||
const { directory, outputDir, result } = await offlineCli(t, 'success', { filename });
|
||||
assert.equal(result.ok, true, result.output);
|
||||
assert.equal(result.exitCode, 0);
|
||||
assert.equal(resultRecord(result.output).status, 'completed');
|
||||
assert.equal(await fs.readFile(path.join(outputDir, `${filename}.mp4`), 'utf8'), 'synthetic-MP4-payload');
|
||||
await assertNoBytecode(directory);
|
||||
});
|
||||
|
||||
test('real resolver failures pause the queue, preserve both episodes, and do not claim the next one', { timeout: 10000 }, async t => {
|
||||
for (const mode of ['embed-resolution', 'media-resolution']) {
|
||||
const { directory, outputDir, result, job } = await offlineCli(t, mode);
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.exitCode, 1);
|
||||
assert.equal(result.errorCategory, 'resolution');
|
||||
assert.equal(resultRecord(result.output).errorCategory, 'resolution');
|
||||
assert.doesNotMatch(result.output, /fixture-value|Synthetic missing|Traceback/);
|
||||
assert.deepEqual(await fs.readdir(outputDir), []);
|
||||
assert.deepEqual(JSON.parse(await fs.readFile(path.join(directory, 'calls.json'), 'utf8')),
|
||||
mode === 'embed-resolution' ? ['embed'] : ['embed', 'media']);
|
||||
|
||||
const queue = [{ ...job, processing: true, started_at: new Date() },
|
||||
{ ...job, _id: 'next-episode', filename: 'Fixture Episode 2', url: 'https://proxer.me/watch/42/2/engsub' }];
|
||||
const original = queue.map(entry => ({ ...entry }));
|
||||
const global = { captcha_blocked: false };
|
||||
const history = [];
|
||||
let claims = 0;
|
||||
const db = { collection(name) {
|
||||
if (name === 'settings') return {
|
||||
updateOne: async (filter, update) => { Object.assign(global, update.$set); return { acknowledged: true }; },
|
||||
findOne: async () => ({ ...global }),
|
||||
};
|
||||
if (name === 'failed') return { insertOne: async record => {
|
||||
assert.equal(global.captcha_blocked, true, 'pause must precede history');
|
||||
history.push(record); return { acknowledged: true };
|
||||
} };
|
||||
assert.equal(name, 'queue');
|
||||
return {
|
||||
updateOne: async (filter, update) => {
|
||||
const entry = queue.find(candidate => candidate._id === filter._id && candidate.processing === true);
|
||||
assert.ok(entry);
|
||||
for (const field of Object.keys(update.$unset)) delete entry[field];
|
||||
return { acknowledged: true };
|
||||
},
|
||||
deleteOne: async () => { assert.fail('a resolution pause must not delete an episode'); },
|
||||
findOneAndUpdate: async () => { claims += 1; return queue[1]; },
|
||||
};
|
||||
} };
|
||||
await processClaimedJob(queue[0], { db, execute: async () => result });
|
||||
assert.deepEqual(global, { captcha_blocked: true, pause_reason: 'resolution' });
|
||||
assert.equal(queue.length, 2);
|
||||
assert.equal(queue[0].token, cookie);
|
||||
assert.equal(queue[0].url, original[0].url);
|
||||
assert.equal(queue[0].filename, original[0].filename);
|
||||
assert.equal(queue[0].processing, undefined);
|
||||
assert.equal(queue[0].started_at, undefined);
|
||||
assert.deepEqual(queue[1], original[1]);
|
||||
assert.equal(history.length, 1);
|
||||
assert.equal(history[0].error_category, 'resolution');
|
||||
assert.equal(history[0].token, undefined);
|
||||
assert.equal(await claimNextJob(db), null);
|
||||
assert.equal(claims, 0);
|
||||
await assertNoBytecode(directory);
|
||||
}
|
||||
});
|
||||
Vendored
+85
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"version": 1,
|
||||
"baselineCommit": "211bfd174dd78eac36f3c74411ecaa72f56eec79",
|
||||
"description": "Synthetic examples captured from the reviewed source. IDs, tokens, timestamps, filenames, and logs are fictional. These fixtures must never initiate network requests.",
|
||||
"cli": {
|
||||
"video": {
|
||||
"script": "scripts/proxer-dl-video.py",
|
||||
"requiredFlags": [["-u", "--url"], ["-f", "--filename"], ["-t", "--token"], ["-o", "--output"]]
|
||||
},
|
||||
"series": {
|
||||
"script": "scripts/proxer-dl-series.py",
|
||||
"requiredFlags": [["-i", "--id"], ["-n", "--name"], ["-e", "--episodes"], ["-l", "--language"], ["-t", "--token"], ["-o", "--output"]],
|
||||
"languages": ["engsub", "engdub", "gersub", "gerdub"]
|
||||
}
|
||||
},
|
||||
"namingCases": [
|
||||
{
|
||||
"entrypoint": "web-video",
|
||||
"input": { "url": "https://proxer.me/watch/999999999/2/engsub" },
|
||||
"expectedFilenames": ["999999999 E2 engsub"]
|
||||
},
|
||||
{
|
||||
"entrypoint": "web-video",
|
||||
"input": { "url": "https://proxer.me/watch/999999999/2/engsub", "filename": "Fixture Video S01E02" },
|
||||
"expectedFilenames": ["Fixture Video S01E02"]
|
||||
},
|
||||
{
|
||||
"entrypoint": "web-series",
|
||||
"input": { "id": "999999999", "name": "Fixture Series ", "episode_from": "9", "episode_to": "10", "language": "gersub" },
|
||||
"expectedFilenames": ["Fixture SeriesE09_gersub", "Fixture SeriesE10_gersub"]
|
||||
},
|
||||
{
|
||||
"entrypoint": "web-series",
|
||||
"input": { "id": "999999999", "episode_from": "1", "episode_to": "2", "language": "gerdub" },
|
||||
"expectedFilenames": ["999999999E1_gerdub", "999999999E2_gerdub"]
|
||||
},
|
||||
{
|
||||
"entrypoint": "cli-series",
|
||||
"input": { "id": "999999999", "name": "Fixture Series", "episodes": "9-10", "language": "engdub" },
|
||||
"expectedFilenames": ["Fixture Series_Episode_9_engdub.mp4", "Fixture Series_Episode_10_engdub.mp4"]
|
||||
}
|
||||
],
|
||||
"legacyDocuments": {
|
||||
"queue": [
|
||||
{
|
||||
"_id": "000000000000000000000001",
|
||||
"url": "https://proxer.me/watch/999999999/1/engsub",
|
||||
"token": "PHASE1_FIXTURE_COOKIE=NOT_A_REAL_TOKEN==",
|
||||
"filename": "Fixture SeriesE1_engsub",
|
||||
"created_at": "2026-01-01T12:00:00.000Z"
|
||||
},
|
||||
{
|
||||
"_id": "000000000000000000000002",
|
||||
"url": "https://proxer.me/watch/999999999/2/engsub",
|
||||
"token": "PHASE1_FIXTURE_COOKIE=NOT_A_REAL_TOKEN==",
|
||||
"filename": "Fixture SeriesE2_engsub",
|
||||
"created_at": "2026-01-01T12:00:00.000Z",
|
||||
"processing": true
|
||||
}
|
||||
],
|
||||
"done": [
|
||||
{
|
||||
"_id": "000000000000000000000003",
|
||||
"filename": "Fixture Completed",
|
||||
"finished_at": "2026-01-01T12:10:00.000Z",
|
||||
"output_log": "Synthetic completed download log."
|
||||
}
|
||||
],
|
||||
"failed": [
|
||||
{
|
||||
"_id": "000000000000000000000004",
|
||||
"filename": "Fixture Failed",
|
||||
"failed_at": "2026-01-01T12:11:00.000Z",
|
||||
"output_log": "Synthetic network failure log."
|
||||
}
|
||||
],
|
||||
"settings": [{ "_id": "global", "captcha_blocked": false }]
|
||||
},
|
||||
"intentionalPhase1Corrections": [
|
||||
"The video web form's name field becomes a usable filename fallback; explicit legacy filename remains supported.",
|
||||
"Python failures must exit nonzero and produce a failed result; historical zero-exit failures are not preserved.",
|
||||
"Unsafe or malformed paths, URLs, cookies, and unbounded episode ranges are rejected.",
|
||||
"Public status documents exclude credential fields."
|
||||
]
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"version": 1,
|
||||
"baselineCommit": "211bfd174dd78eac36f3c74411ecaa72f56eec79",
|
||||
"protectedRoot": "scripts/lib",
|
||||
"entries": [
|
||||
{ "path": ".", "type": "directory" },
|
||||
{ "path": "__pycache__", "type": "directory" },
|
||||
{ "path": "__pycache__/proxer_utils.cpython-311.pyc", "type": "file", "sha256": "031db0ff7cdf5658ee6e722f387c40e0d77075c74c889c7e90a0594039fa7c06", "executable": true },
|
||||
{ "path": "__pycache__/proxer_utils.cpython-313.pyc", "type": "file", "sha256": "6f2f3533e4a73876977d4036be681efaa025a658e666c2fda19f961c34a88a05", "executable": true },
|
||||
{ "path": "__pycache__/proxer_utils.cpython-38.pyc", "type": "file", "sha256": "84525538e325d3345596147e8f7895c42be89374f03673546a3533db00aecf28", "executable": true },
|
||||
{ "path": "__pycache__/script_utils.cpython-313.pyc", "type": "file", "sha256": "bf60ab460120ace66aa3cd78b3317fc4193de6339b1150d8e5dcdb30d583e5e0", "executable": true },
|
||||
{ "path": "__pycache__/script_utils.cpython-38.pyc", "type": "file", "sha256": "cc0fc12c9dfb77d2be003e4c23d020c1940d3694a0be457205f391de31529a45", "executable": true },
|
||||
{ "path": "proxer_utils.py", "type": "file", "sha256": "52820651360fd5fd351d28fe979fda494092a6947467ae65f600064722941789", "executable": true },
|
||||
{ "path": "script_utils.py", "type": "file", "sha256": "dfc4e19fd5395b77c746871b34a14c134022883c571e3603bb35346307e9e017", "executable": true }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { verifyProtectedTree, readManifest } = require('../tools/check-protected-lib');
|
||||
|
||||
const repositoryRoot = path.resolve(__dirname, '..');
|
||||
const manifest = readManifest();
|
||||
|
||||
function temporaryRepository(t) {
|
||||
// Keep temporary writes within the checkout; no source fixture is modified.
|
||||
const directory = fs.mkdtempSync(path.join(repositoryRoot, '.protected-test-'));
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
fs.mkdirSync(path.join(directory, 'scripts'));
|
||||
fs.cpSync(path.join(repositoryRoot, 'scripts/lib'), path.join(directory, 'scripts/lib'), { recursive: true });
|
||||
return directory;
|
||||
}
|
||||
|
||||
test('the actual protected library matches the reviewed baseline', () => {
|
||||
const result = verifyProtectedTree(repositoryRoot, manifest);
|
||||
assert.equal(result.ok, true, result.errors.join('\n'));
|
||||
assert.equal(result.fileCount, 7);
|
||||
});
|
||||
|
||||
test('an unchanged complete copy passes', t => {
|
||||
const result = verifyProtectedTree(temporaryRepository(t), manifest);
|
||||
assert.equal(result.ok, true, result.errors.join('\n'));
|
||||
});
|
||||
|
||||
test('changed protected source is detected', t => {
|
||||
const directory = temporaryRepository(t);
|
||||
fs.appendFileSync(path.join(directory, 'scripts/lib/proxer_utils.py'), '\n# test change\n');
|
||||
const result = verifyProtectedTree(directory, manifest);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.errors.join('\n'), /content changed: scripts\/lib\/proxer_utils\.py/);
|
||||
});
|
||||
|
||||
test('missing protected bytecode is detected', t => {
|
||||
const directory = temporaryRepository(t);
|
||||
fs.unlinkSync(path.join(directory, 'scripts/lib/__pycache__/proxer_utils.cpython-311.pyc'));
|
||||
const result = verifyProtectedTree(directory, manifest);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.errors.join('\n'), /Missing protected entry/);
|
||||
});
|
||||
|
||||
test('new bytecode and hidden files are detected even if git would ignore them', t => {
|
||||
const directory = temporaryRepository(t);
|
||||
fs.writeFileSync(path.join(directory, 'scripts/lib/__pycache__/proxer_utils.cpython-314.pyc'), 'new bytecode');
|
||||
fs.writeFileSync(path.join(directory, 'scripts/lib/.generated'), 'new hidden file');
|
||||
const result = verifyProtectedTree(directory, manifest);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.errors.join('\n'), /Unexpected protected entry: scripts\/lib\/__pycache__\/proxer_utils\.cpython-314\.pyc/);
|
||||
assert.match(result.errors.join('\n'), /Unexpected protected entry: scripts\/lib\/\.generated/);
|
||||
});
|
||||
|
||||
test('an added empty directory is detected', t => {
|
||||
const directory = temporaryRepository(t);
|
||||
fs.mkdirSync(path.join(directory, 'scripts/lib/generated'));
|
||||
const result = verifyProtectedTree(directory, manifest);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.errors.join('\n'), /Unexpected protected entry: scripts\/lib\/generated/);
|
||||
});
|
||||
|
||||
test('a protected file replaced by a symlink is detected without following it', t => {
|
||||
const directory = temporaryRepository(t);
|
||||
const file = path.join(directory, 'scripts/lib/proxer_utils.py');
|
||||
fs.unlinkSync(file);
|
||||
fs.symlinkSync('/nonexistent/protected-test-target', file);
|
||||
const result = verifyProtectedTree(directory, manifest);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.errors.join('\n'), /entry type changed: scripts\/lib\/proxer_utils\.py/);
|
||||
});
|
||||
|
||||
test('a symlinked scripts directory is rejected', t => {
|
||||
const directory = temporaryRepository(t);
|
||||
fs.renameSync(path.join(directory, 'scripts'), path.join(directory, 'moved-scripts'));
|
||||
fs.symlinkSync('moved-scripts', path.join(directory, 'scripts'));
|
||||
const result = verifyProtectedTree(directory, manifest);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.errors.join('\n'), /scripts must be a real directory/);
|
||||
});
|
||||
|
||||
test('executable-bit changes are detected', t => {
|
||||
const directory = temporaryRepository(t);
|
||||
fs.chmodSync(path.join(directory, 'scripts/lib/proxer_utils.py'), 0o644);
|
||||
const result = verifyProtectedTree(directory, manifest);
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.errors.join('\n'), /executable bit changed/);
|
||||
});
|
||||
|
||||
test('an invalid manifest cannot redirect the checked path', t => {
|
||||
const directory = temporaryRepository(t);
|
||||
const result = verifyProtectedTree(directory, { ...manifest, protectedRoot: '../outside' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.match(result.errors.join('\n'), /Invalid protected-library manifest/);
|
||||
});
|
||||
@@ -0,0 +1,490 @@
|
||||
"""Offline regression checks for CLI boundaries; no production stream is invoked."""
|
||||
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPTS = ROOT / "scripts"
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
|
||||
|
||||
def load_script(name, path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
video = load_script("phase1_video", SCRIPTS / "proxer-dl-video.py")
|
||||
series = load_script("phase1_series", SCRIPTS / "proxer-dl-series.py")
|
||||
import request_validation as validation
|
||||
|
||||
|
||||
def protected_snapshot():
|
||||
return {str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in (SCRIPTS / "lib").rglob("*") if path.is_file()}
|
||||
|
||||
|
||||
class ValidationTests(unittest.TestCase):
|
||||
def test_cookie_preserves_equals_in_value(self):
|
||||
self.assertEqual(validation.parse_token("FixtureCookie=base64=="), ("FixtureCookie", "base64=="))
|
||||
|
||||
def test_stdin_cookie_preserves_equals_and_accepts_one_line(self):
|
||||
args = types.SimpleNamespace(token_stdin=True, token=None)
|
||||
for ending in ("", "\n", "\r\n"):
|
||||
with self.subTest(ending=ending):
|
||||
self.assertEqual(validation.token_from_args(args, io.StringIO("FixtureCookie=base64==" + ending)),
|
||||
("FixtureCookie", "base64=="))
|
||||
|
||||
def test_stdin_cookie_rejects_extra_lines_controls_and_overflow(self):
|
||||
args = types.SimpleNamespace(token_stdin=True, token=None)
|
||||
for value in ("FixtureCookie=abc\nsecond\n", "FixtureCookie=abc\n\n", "FixtureCookie=a\x00b\n",
|
||||
"FixtureCookie=a\x80b\n", "a=" + "b" * 8191 + "\n"):
|
||||
with self.subTest(length=len(value)), self.assertRaises(validation.ValidationError):
|
||||
validation.token_from_args(args, io.StringIO(value))
|
||||
|
||||
def test_token_length_boundary_and_invalid_utf8(self):
|
||||
args = types.SimpleNamespace(token_stdin=True, token=None)
|
||||
value = "a=" + "b" * 8190
|
||||
self.assertEqual(validation.token_from_args(args, io.StringIO(value + "\n")), ("a", "b" * 8190))
|
||||
with self.assertRaises(validation.ValidationError):
|
||||
validation.token_from_args(args, io.BytesIO(b"a=\xff\n"))
|
||||
with self.assertRaises(validation.ValidationError):
|
||||
validation.parse_token(value + "b")
|
||||
|
||||
def test_invalid_cookies_are_rejected(self):
|
||||
for token in ("", "name", "=value", "name=", "bad name=value", "name=a\nb", "name=a;b", "name=a b"):
|
||||
with self.subTest(token=token), self.assertRaises(validation.ValidationError):
|
||||
validation.parse_token(token)
|
||||
|
||||
def test_canonical_watch_url(self):
|
||||
self.assertEqual(validation.validate_watch_url("https://www.proxer.me:443/watch/123/9/engsub/#details"),
|
||||
"https://proxer.me/watch/123/9/engsub")
|
||||
|
||||
def test_watch_url_length_is_bounded(self):
|
||||
base = "https://proxer.me/watch/123/1/engsub#"
|
||||
self.assertEqual(validation.validate_watch_url(base + "x" * (2048 - len(base))),
|
||||
"https://proxer.me/watch/123/1/engsub")
|
||||
with self.assertRaises(validation.ValidationError):
|
||||
validation.validate_watch_url(base + "x" * (2049 - len(base)))
|
||||
|
||||
def test_unsupported_or_ambiguous_urls_are_rejected(self):
|
||||
for url in ("http://proxer.me/watch/123/1/engsub", "https://proxer.me.evil.invalid/watch/123/1/engsub",
|
||||
"https://user:password@proxer.me/watch/123/1/engsub", "https://proxer.me:8443/watch/123/1/engsub",
|
||||
"https://proxer.me/watch/123/1/engsub?cookie=secret", "https://proxer.me/watch/0/1/engsub",
|
||||
"https://proxer.me/watch/123/0/engsub", "https://proxer.me/watch/123/1/de",
|
||||
"https://proxer.me/watch/123/1/engsub\n", "https://proxer.me/watch/9007199254740992/1/engsub"):
|
||||
with self.subTest(url=url), self.assertRaises(validation.ValidationError):
|
||||
validation.validate_watch_url(url)
|
||||
|
||||
def test_unsafe_filenames_are_rejected(self):
|
||||
for filename in ("", ".", "..", "../outside", "nested/name", "nested\\name", "nul\x00name", "line\nname", " leading", "trailing "):
|
||||
with self.subTest(filename=filename), self.assertRaises(validation.ValidationError):
|
||||
validation.validate_filename(filename)
|
||||
self.assertEqual(validation.validate_filename("A safe 日本語 name S01E02"), "A safe 日本語 name S01E02")
|
||||
|
||||
def test_filename_limit_counts_utf8_bytes_and_extension(self):
|
||||
self.assertEqual(validation.validate_filename("a" * 251), "a" * 251)
|
||||
for filename in ("a" * 252, "日" * 84):
|
||||
with self.subTest(filename=filename), self.assertRaises(validation.ValidationError):
|
||||
validation.validate_filename(filename)
|
||||
|
||||
def test_ranges_are_inclusive_bounded_and_strict(self):
|
||||
with patch.dict(os.environ, {"MAX_SERIES_EPISODES": "2"}):
|
||||
self.assertEqual(validation.episode_range("9-10"), (9, 10))
|
||||
for value in ("1-3", "3-2", "0-2", "1.0-2", "1-2-3", "1-", "1e1-12", "1-9007199254740992"):
|
||||
with self.subTest(value=value), self.assertRaises(validation.ValidationError):
|
||||
validation.episode_range(value)
|
||||
|
||||
def test_default_range_limit_is_500(self):
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
self.assertEqual(validation.episode_range("1-500"), (1, 500))
|
||||
with self.assertRaises(validation.ValidationError):
|
||||
validation.episode_range("1-501")
|
||||
|
||||
def test_bad_range_configuration_is_a_validation_error(self):
|
||||
with patch.dict(os.environ, {"MAX_SERIES_EPISODES": "unlimited"}), self.assertRaises(validation.ValidationError):
|
||||
validation.episode_range("1-2")
|
||||
|
||||
def test_series_configuration_matches_shared_limit(self):
|
||||
for value in ("0", "10001", "9" * 5000):
|
||||
with self.subTest(length=len(value)), patch.dict(os.environ, {"MAX_SERIES_EPISODES": value}), self.assertRaises(validation.ValidationError):
|
||||
validation.episode_range("1-2")
|
||||
for value in ("10000", "00002", ""):
|
||||
with self.subTest(value=value), patch.dict(os.environ, {"MAX_SERIES_EPISODES": value}):
|
||||
self.assertEqual(validation.episode_range("1-2"), (1, 2))
|
||||
|
||||
def test_oversized_integer_is_rejected_without_conversion_failure(self):
|
||||
with self.assertRaises(validation.ValidationError):
|
||||
validation.positive_integer("9" * 5000, "Series ID")
|
||||
|
||||
def test_authentication_requires_status_evidence_not_message_keywords(self):
|
||||
error = RuntimeError("filename token-captcha-403-blocked.mp4")
|
||||
self.assertEqual(validation.error_result(error)["errorCategory"], "unknown")
|
||||
error.response = types.SimpleNamespace(status_code=403)
|
||||
self.assertEqual(validation.error_result(error)["errorCategory"], "authentication")
|
||||
|
||||
def test_chained_authentication_error_is_recognized_without_secret_output(self):
|
||||
cause = RuntimeError("https://signed.invalid/file?token=DO_NOT_LOG")
|
||||
cause.response = types.SimpleNamespace(status_code=401)
|
||||
outer = RuntimeError("wrapped DO_NOT_LOG")
|
||||
outer.__context__ = cause
|
||||
result = validation.error_result(outer)
|
||||
self.assertEqual(result["errorCategory"], "authentication")
|
||||
self.assertNotIn("DO_NOT_LOG", json.dumps(result))
|
||||
|
||||
def test_resolution_requires_exact_library_exception_metadata(self):
|
||||
unrelated_not_found = type("NotFoundError", (Exception,), {"__module__": "unrelated_library"})
|
||||
for error in (unrelated_not_found("DO_NOT_LOG"), RuntimeError("Embed code not found captcha DO_NOT_LOG")):
|
||||
with self.subTest(error_type=type(error)):
|
||||
result = validation.error_result(error)
|
||||
self.assertEqual(result["errorCategory"], "unknown")
|
||||
self.assertNotIn("DO_NOT_LOG", json.dumps(result))
|
||||
|
||||
|
||||
class DownloadTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.original_protected = protected_snapshot()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
if protected_snapshot() != cls.original_protected:
|
||||
raise AssertionError("The protected library tree changed during Python tests.")
|
||||
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory(prefix="proxer-phase1-")
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.output = Path(self.temporary.name)
|
||||
package = types.ModuleType("lib")
|
||||
package.__path__ = []
|
||||
self.library = types.ModuleType("lib.proxer_utils")
|
||||
self.library.NetworkError = type("NetworkError", (Exception,), {"__module__": "lib.proxer_utils"})
|
||||
self.library.NotFoundError = type("NotFoundError", (Exception,), {"__module__": "lib.proxer_utils"})
|
||||
self.library.get_embed_url = Mock(return_value="https://signed.invalid/embed?token=DO_NOT_LOG")
|
||||
self.library.get_mp4_url = Mock(return_value="https://signed.invalid/video?token=DO_NOT_LOG")
|
||||
self.library.download_mp4 = Mock(side_effect=lambda url, target, label: Path(target).write_bytes(b"synthetic media fixture"))
|
||||
self.module_patch = patch.dict(sys.modules, {"lib": package, "lib.proxer_utils": self.library})
|
||||
self.module_patch.start()
|
||||
self.addCleanup(self.module_patch.stop)
|
||||
self.sleep_patch = patch.object(series, "sleep")
|
||||
self.sleep_patch.start()
|
||||
self.addCleanup(self.sleep_patch.stop)
|
||||
self.env_patch = patch.dict(os.environ, {"MAX_SERIES_EPISODES": "500"})
|
||||
self.env_patch.start()
|
||||
self.addCleanup(self.env_patch.stop)
|
||||
|
||||
def video_args(self, **overrides):
|
||||
values = {"url": "https://proxer.me/watch/999999999/2/engsub", "filename": "Fixture Video S01E02",
|
||||
"token": "FixtureCookie=NOT_REAL==", "output": str(self.output)}
|
||||
values.update(overrides)
|
||||
return [part for key, value in values.items() for part in ("--" + key, value)]
|
||||
|
||||
def series_args(self, **overrides):
|
||||
values = {"id": "999999999", "name": "Fixture Series", "episodes": "1-2", "language": "engsub",
|
||||
"token": "FixtureCookie=NOT_REAL==", "output": str(self.output)}
|
||||
values.update(overrides)
|
||||
return [part for key, value in values.items() for part in ("--" + key, value)]
|
||||
|
||||
def invoke(self, entrypoint, args):
|
||||
stdout, stderr = io.StringIO(), io.StringIO()
|
||||
with redirect_stdout(stdout), redirect_stderr(stderr):
|
||||
code = entrypoint.main(args)
|
||||
records = [line[len(validation.RESULT_PREFIX):] for line in stdout.getvalue().splitlines()
|
||||
if line.startswith(validation.RESULT_PREFIX)]
|
||||
self.assertEqual(len(records), 1, stdout.getvalue())
|
||||
self.assertNotIn("DO_NOT_LOG", stdout.getvalue() + stderr.getvalue())
|
||||
self.assertNotIn("NOT_REAL", stdout.getvalue() + stderr.getvalue())
|
||||
return code, json.loads(records[0]), stdout.getvalue()
|
||||
|
||||
def test_video_success_has_one_result_and_preserves_stream_order(self):
|
||||
calls = Mock()
|
||||
calls.attach_mock(self.library.get_embed_url, "embed")
|
||||
calls.attach_mock(self.library.get_mp4_url, "media")
|
||||
calls.attach_mock(self.library.download_mp4, "download")
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(result, {"version": 1, "status": "completed"})
|
||||
self.assertEqual([item[0] for item in calls.mock_calls], ["embed", "media", "download"])
|
||||
self.assertEqual(self.library.get_embed_url.call_args.args[1], ("FixtureCookie", "NOT_REAL=="))
|
||||
self.assertTrue((self.output / "Fixture Video S01E02.mp4").is_file())
|
||||
|
||||
def test_resolver_failure_is_nonzero_and_requires_verification(self):
|
||||
for resolver in (self.library.get_embed_url, self.library.get_mp4_url):
|
||||
for wrapped in (False, True):
|
||||
with self.subTest(resolver=resolver, wrapped=wrapped):
|
||||
error = self.library.NotFoundError("https://signed.invalid/page?token=DO_NOT_LOG")
|
||||
if wrapped:
|
||||
outer = RuntimeError("wrapped DO_NOT_LOG")
|
||||
outer.__cause__ = error
|
||||
error = outer
|
||||
resolver.side_effect = error
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(result["status"], "failed")
|
||||
self.assertEqual(result["errorCategory"], "resolution")
|
||||
self.assertIn("verification", result["message"])
|
||||
self.assertNotIn("captcha", result["message"].lower())
|
||||
self.library.download_mp4.assert_not_called()
|
||||
resolver.side_effect = None
|
||||
|
||||
def test_wrapped_http_status_distinguishes_authentication_from_missing_source(self):
|
||||
http_error = type("HTTPError", (Exception,), {"__module__": "requests.exceptions"})
|
||||
for status, category in ((401, "authentication"), (403, "authentication"), (404, "source")):
|
||||
with self.subTest(status=status):
|
||||
cause = http_error("https://signed.invalid/page?token=DO_NOT_LOG")
|
||||
cause.response = types.SimpleNamespace(status_code=status)
|
||||
error = self.library.NetworkError("Failed to fetch episode page: DO_NOT_LOG")
|
||||
error.__context__ = cause
|
||||
self.library.get_embed_url.side_effect = error
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(result["errorCategory"], category)
|
||||
self.library.download_mp4.assert_not_called()
|
||||
|
||||
def test_network_failure_is_not_automatically_authentication(self):
|
||||
self.library.get_mp4_url.side_effect = self.library.NetworkError("captcha token 403 DO_NOT_LOG")
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual(result["errorCategory"], "network")
|
||||
|
||||
def test_transfer_failure_is_nonzero_even_when_an_old_file_exists(self):
|
||||
(self.output / "Fixture Video S01E02.mp4").write_bytes(b"old output")
|
||||
self.library.download_mp4.side_effect = RuntimeError("DO_NOT_LOG")
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual(result["status"], "failed")
|
||||
|
||||
def test_storage_failure_is_nonzero(self):
|
||||
self.library.download_mp4.side_effect = PermissionError("DO_NOT_LOG")
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual(result["errorCategory"], "storage")
|
||||
|
||||
def test_missing_stream_dependency_is_configuration_failure(self):
|
||||
for entrypoint, args in ((video, self.video_args()), (series, self.series_args())):
|
||||
with self.subTest(entrypoint=entrypoint.__name__), patch.dict(sys.modules, {"lib.proxer_utils": None}):
|
||||
code, result, _ = self.invoke(entrypoint, args)
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual(result["errorCategory"], "configuration")
|
||||
self.library.get_embed_url.assert_not_called()
|
||||
|
||||
def test_dependency_import_error_never_exposes_exception_text(self):
|
||||
self.library.get_embed_url.side_effect = ImportError("DO_NOT_LOG")
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual(result["errorCategory"], "configuration")
|
||||
|
||||
def test_missing_or_empty_output_is_not_success(self):
|
||||
for make_empty in (False, True):
|
||||
with self.subTest(make_empty=make_empty):
|
||||
self.library.download_mp4.side_effect = lambda url, target, label: Path(target).touch() if make_empty else None
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual(result["errorCategory"], "storage")
|
||||
|
||||
def test_invalid_url_never_calls_protected_library(self):
|
||||
code, result, _ = self.invoke(video, self.video_args(url="https://unrelated.invalid/watch/1/1/engsub"))
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(result["errorCategory"], "validation")
|
||||
self.library.get_embed_url.assert_not_called()
|
||||
|
||||
def test_path_traversal_never_calls_protected_library(self):
|
||||
code, result, _ = self.invoke(video, self.video_args(filename="../outside"))
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(result["errorCategory"], "validation")
|
||||
self.library.get_embed_url.assert_not_called()
|
||||
|
||||
def test_missing_output_directory_is_not_created(self):
|
||||
missing = self.output / "missing"
|
||||
code, result, _ = self.invoke(video, self.video_args(output=str(missing)))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(result["errorCategory"], "storage")
|
||||
self.assertFalse(missing.exists())
|
||||
|
||||
def test_symlink_output_is_rejected_and_target_untouched(self):
|
||||
outside = self.output / "other-file"
|
||||
outside.write_bytes(b"must not change")
|
||||
(self.output / "Fixture Video S01E02.mp4").symlink_to(outside)
|
||||
code, result, _ = self.invoke(video, self.video_args())
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(result["errorCategory"], "validation")
|
||||
self.assertEqual(outside.read_bytes(), b"must not change")
|
||||
self.library.download_mp4.assert_not_called()
|
||||
|
||||
def test_nonregular_output_is_rejected(self):
|
||||
(self.output / "Fixture Video S01E02.mp4").mkdir()
|
||||
code, _, _ = self.invoke(video, self.video_args())
|
||||
self.assertEqual(code, 2)
|
||||
self.library.download_mp4.assert_not_called()
|
||||
|
||||
def test_invalid_cli_arguments_emit_safe_failure(self):
|
||||
code, result, output = self.invoke(video, ["--unrecognized", "DO_NOT_LOG"])
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(result["errorCategory"], "validation")
|
||||
self.assertNotIn("DO_NOT_LOG", output)
|
||||
|
||||
def test_video_stdin_token_uses_same_pipeline(self):
|
||||
args = self.video_args()
|
||||
position = args.index("--token")
|
||||
args[position:position + 2] = ["--token-stdin"]
|
||||
with patch.object(sys, "stdin", io.StringIO("FixtureCookie=NOT_REAL==\n")):
|
||||
code, result, _ = self.invoke(video, args)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(result["status"], "completed")
|
||||
self.assertEqual(self.library.get_embed_url.call_args.args[1], ("FixtureCookie", "NOT_REAL=="))
|
||||
|
||||
def test_series_stdin_token_and_mutual_exclusion(self):
|
||||
args = self.series_args()
|
||||
position = args.index("--token")
|
||||
args[position:position + 2] = ["--token-stdin"]
|
||||
with patch.object(sys, "stdin", io.StringIO("FixtureCookie=NOT_REAL==\n")):
|
||||
code, _, _ = self.invoke(series, args)
|
||||
self.assertEqual(code, 0)
|
||||
code, result, _ = self.invoke(video, self.video_args() + ["--token-stdin"])
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(result["errorCategory"], "validation")
|
||||
|
||||
def test_series_preserves_legacy_filenames_and_cli_flags(self):
|
||||
fixtures = json.loads((ROOT / "tests/fixtures/legacy-contracts.json").read_text())
|
||||
sample = next(item for item in fixtures["namingCases"] if item["entrypoint"] == "cli-series")
|
||||
args = self.series_args(**sample["input"])
|
||||
code, result, _ = self.invoke(series, args)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(result["completed"], 2)
|
||||
self.assertEqual(sorted(path.name for path in self.output.iterdir()), sorted(sample["expectedFilenames"]))
|
||||
for mode, entrypoint, normal_args in (("video", video, self.video_args()), ("series", series, args)):
|
||||
replacements = {long: short for short, long in fixtures["cli"][mode]["requiredFlags"]}
|
||||
self.assertEqual(vars(entrypoint.parse_args(normal_args)),
|
||||
vars(entrypoint.parse_args([replacements.get(arg, arg) for arg in normal_args])))
|
||||
|
||||
def test_series_partial_failure_is_nonzero_with_counts(self):
|
||||
calls = 0
|
||||
|
||||
def transfer(url, target, label):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if calls == 1:
|
||||
raise self.library.NetworkError("DO_NOT_LOG")
|
||||
Path(target).write_bytes(b"synthetic media fixture")
|
||||
|
||||
self.library.download_mp4.side_effect = transfer
|
||||
code, result, _ = self.invoke(series, self.series_args())
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 0))
|
||||
self.assertEqual(result["failures"], [{"episode": 1, "errorCategory": "network"}])
|
||||
|
||||
def test_series_access_failure_stops_remaining_requests(self):
|
||||
error = self.library.NetworkError("DO_NOT_LOG")
|
||||
error.response = types.SimpleNamespace(status_code=403)
|
||||
self.library.get_embed_url.side_effect = error
|
||||
code, result, _ = self.invoke(series, self.series_args(episodes="1-3"))
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 1, 2))
|
||||
self.assertEqual(self.library.get_embed_url.call_count, 1)
|
||||
|
||||
def test_series_resolution_failure_stops_remaining_requests(self):
|
||||
self.library.get_embed_url.side_effect = ["synthetic-embed", self.library.NotFoundError("DO_NOT_LOG")]
|
||||
code, result, _ = self.invoke(series, self.series_args(episodes="1-4"))
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(result["errorCategory"], "resolution")
|
||||
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 2))
|
||||
self.assertEqual(result["failures"], [{"episode": 2, "errorCategory": "resolution"}])
|
||||
self.assertEqual(self.library.get_embed_url.call_count, 2)
|
||||
self.assertEqual(self.library.download_mp4.call_count, 1)
|
||||
|
||||
def test_series_confirmed_missing_source_does_not_pause_remaining_requests(self):
|
||||
cause = RuntimeError("DO_NOT_LOG")
|
||||
cause.response = types.SimpleNamespace(status_code=404)
|
||||
error = self.library.NetworkError("DO_NOT_LOG")
|
||||
error.__context__ = cause
|
||||
self.library.get_embed_url.side_effect = [error, "synthetic-embed"]
|
||||
code, result, _ = self.invoke(series, self.series_args())
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(result["errorCategory"], "source")
|
||||
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 0))
|
||||
self.assertEqual(self.library.get_embed_url.call_count, 2)
|
||||
self.assertEqual(self.library.download_mp4.call_count, 1)
|
||||
|
||||
def test_series_host_failures_stop_remaining_requests(self):
|
||||
for error, expected_category in ((PermissionError("DO_NOT_LOG"), "storage"),
|
||||
(ImportError("DO_NOT_LOG"), "configuration")):
|
||||
with self.subTest(category=expected_category):
|
||||
self.library.get_embed_url.reset_mock()
|
||||
self.library.get_embed_url.side_effect = error
|
||||
code, result, _ = self.invoke(series, self.series_args(episodes="1-3"))
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 1, 2))
|
||||
self.assertEqual(result["errorCategory"], expected_category)
|
||||
self.assertEqual(self.library.get_embed_url.call_count, 1)
|
||||
|
||||
def test_series_summary_reports_failure_that_stopped_the_batch(self):
|
||||
for error, category in ((PermissionError("DO_NOT_LOG"), "storage"),
|
||||
(self.library.NotFoundError("DO_NOT_LOG"), "resolution")):
|
||||
with self.subTest(category=category):
|
||||
self.library.get_embed_url.reset_mock()
|
||||
self.library.get_embed_url.side_effect = [self.library.NetworkError("DO_NOT_LOG"), error]
|
||||
code, result, _ = self.invoke(series, self.series_args(episodes="1-3"))
|
||||
self.assertNotEqual(code, 0)
|
||||
self.assertEqual(result["errorCategory"], category)
|
||||
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 2, 1))
|
||||
self.assertEqual(self.library.get_embed_url.call_count, 2)
|
||||
|
||||
def test_series_validates_every_destination_before_requests(self):
|
||||
(self.output / "Fixture Series_Episode_2_engsub.mp4").symlink_to(self.output / "missing")
|
||||
code, result, _ = self.invoke(series, self.series_args())
|
||||
self.assertEqual(code, 2)
|
||||
self.assertEqual(result["errorCategory"], "validation")
|
||||
self.library.get_embed_url.assert_not_called()
|
||||
|
||||
|
||||
class ProcessExitTests(unittest.TestCase):
|
||||
def test_real_cli_entrypoint_reports_process_exit(self):
|
||||
# Run __main__ in a separate process with an entirely synthetic imported library.
|
||||
driver = '''
|
||||
import pathlib, runpy, sys, types
|
||||
root, destination, mode = sys.argv[1:]
|
||||
sys.path.insert(0, str(pathlib.Path(root) / "scripts"))
|
||||
package = types.ModuleType("lib")
|
||||
package.__path__ = []
|
||||
library = types.ModuleType("lib.proxer_utils")
|
||||
library.get_embed_url = lambda *args: "synthetic-embed"
|
||||
library.get_mp4_url = lambda *args: "synthetic-media"
|
||||
def download(url, path, label):
|
||||
if mode == "fail":
|
||||
raise RuntimeError("PRIVATE_SIGNED_URL_DO_NOT_LOG")
|
||||
pathlib.Path(path).write_bytes(b"synthetic payload")
|
||||
library.download_mp4 = download
|
||||
sys.modules["lib"] = package
|
||||
sys.modules["lib.proxer_utils"] = library
|
||||
script = str(pathlib.Path(root) / "scripts/proxer-dl-video.py")
|
||||
sys.argv = [script, "-u", "https://proxer.me/watch/999999999/1/engsub", "-f", "Fixture", "-t", "FixtureCookie=synthetic==", "-o", destination]
|
||||
runpy.run_path(script, run_name="__main__")
|
||||
'''
|
||||
before = protected_snapshot()
|
||||
for mode, expected_code in (("ok", 0), ("fail", 1)):
|
||||
with self.subTest(mode=mode), tempfile.TemporaryDirectory(prefix="proxer-cli-") as destination:
|
||||
result = subprocess.run([sys.executable, "-B", "-c", driver, str(ROOT), destination, mode],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, expected_code, result.stderr)
|
||||
records = [line for line in result.stdout.splitlines() if line.startswith(validation.RESULT_PREFIX)]
|
||||
self.assertEqual(len(records), 1)
|
||||
self.assertNotIn("PRIVATE_SIGNED_URL", result.stdout + result.stderr)
|
||||
self.assertEqual(protected_snapshot(), before)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,411 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('node:path');
|
||||
const { createConfig } = require('../lib/config');
|
||||
const { createDbProvider } = require('../lib/mongo');
|
||||
const { LOG_LIMIT, sanitizeLog, createLineSanitizer } = require('../lib/logging');
|
||||
const { createPm2Controller, normalizeProcess } = require('../controllers/pm2Controller');
|
||||
|
||||
const settings = createConfig({
|
||||
MONGO_URI: 'mongodb://fixture-user:NOT_A_REAL_PASSWORD@database.invalid/fixture',
|
||||
MONGO_DB: 'phase1_fixture',
|
||||
});
|
||||
|
||||
function response() {
|
||||
return {
|
||||
statusCode: 200,
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
json(value) { this.body = value; return this; },
|
||||
render(view, value) { this.view = view; this.body = value; return this; },
|
||||
};
|
||||
}
|
||||
|
||||
function pm2Process(overrides = {}) {
|
||||
return {
|
||||
name: 'proxer-worker-1',
|
||||
pid: 1234,
|
||||
pm_id: 0,
|
||||
monit: { cpu: 2.5, memory: 8 * 1024 * 1024 },
|
||||
pm2_env: {
|
||||
name: 'proxer-worker-1',
|
||||
pm_id: 0,
|
||||
status: 'online',
|
||||
pm_uptime: Date.now() - 60_000,
|
||||
pm_exec_path: settings.workerScript,
|
||||
MONGO_URI: settings.mongoUri,
|
||||
TOKEN: 'NOT_A_REAL_PM2_TOKEN',
|
||||
env: { PASSWORD: 'NOT_A_REAL_PM2_PASSWORD' },
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function supervisor(processes = [], commandResult = {}) {
|
||||
const calls = [];
|
||||
const controller = createPm2Controller({
|
||||
settings,
|
||||
run: async args => {
|
||||
calls.push([...args]);
|
||||
if (args[0] === 'jlist') return { code: 0, stdout: JSON.stringify(processes), stderr: '' };
|
||||
return { code: 0, stdout: 'NOT_A_REAL_STDOUT_SECRET', stderr: 'NOT_A_REAL_STDERR_SECRET', ...commandResult };
|
||||
},
|
||||
});
|
||||
return { controller, calls };
|
||||
}
|
||||
|
||||
test('configuration defaults describe a portable home-directory installation', () => {
|
||||
const config = createConfig({});
|
||||
assert.equal(config.mongoDb, 'downloads');
|
||||
assert.equal(config.outputDir, '/mnt/media/WIP');
|
||||
assert.equal(config.pythonPath, 'python3');
|
||||
assert.equal(config.maxSeriesEpisodes, 500);
|
||||
assert.equal(config.port, 3000);
|
||||
assert.equal(config.mongoUri, '');
|
||||
assert.equal(config.tokenPrefix, '');
|
||||
assert.equal(config.workerScript, path.join(config.projectRoot, 'queue_worker.js'));
|
||||
assert.equal(config.videoScript, path.join(config.projectRoot, 'scripts/proxer-dl-video.py'));
|
||||
assert.equal(Object.isFrozen(config), true);
|
||||
});
|
||||
|
||||
test('web and worker configuration share explicit database and path overrides', () => {
|
||||
const config = createConfig({
|
||||
MONGO_URI: settings.mongoUri,
|
||||
MONGO_DB: 'private_download_queue',
|
||||
OUTPUT_DIR: '/mnt/media/fixture-output',
|
||||
VENV_PYTHON: '/home/fixture-download/Proxer-Downloader/.venv/bin/python',
|
||||
TOKEN_PREFIX: 'FIXTURE_COOKIE=',
|
||||
MAX_SERIES_EPISODES: '120',
|
||||
PORT: '3033',
|
||||
HOST: '127.0.0.1',
|
||||
});
|
||||
assert.equal(config.mongoUri, settings.mongoUri);
|
||||
assert.equal(config.mongoDb, 'private_download_queue');
|
||||
assert.equal(config.outputDir, '/mnt/media/fixture-output');
|
||||
assert.equal(config.pythonPath, '/home/fixture-download/Proxer-Downloader/.venv/bin/python');
|
||||
assert.equal(config.tokenPrefix, 'FIXTURE_COOKIE=');
|
||||
assert.equal(config.maxSeriesEpisodes, 120);
|
||||
assert.equal(config.port, 3033);
|
||||
assert.equal(config.host, '127.0.0.1');
|
||||
});
|
||||
|
||||
test('configuration rejects malformed, unsafe, and out-of-range positive integers', () => {
|
||||
for (const value of ['0', '-1', '1.5', 'Infinity', '12x', ' 12 ', '9007199254740993']) {
|
||||
assert.throws(() => createConfig({ PORT: value }), /PORT/);
|
||||
assert.throws(() => createConfig({ MAX_SERIES_EPISODES: value }), /MAX_SERIES_EPISODES/);
|
||||
}
|
||||
assert.throws(() => createConfig({ PORT: '65536' }), /PORT/);
|
||||
assert.throws(() => createConfig({ MAX_SERIES_EPISODES: '10001' }), /MAX_SERIES_EPISODES/);
|
||||
assert.equal(createConfig({ PORT: '', MAX_SERIES_EPISODES: '' }).port, 3000);
|
||||
});
|
||||
|
||||
test('concurrent database callers share one connection and the configured database', async () => {
|
||||
let instances = 0;
|
||||
let connections = 0;
|
||||
let closes = 0;
|
||||
const selectedNames = [];
|
||||
const selectedDb = { fixture: true };
|
||||
let release;
|
||||
const connected = new Promise(resolve => { release = resolve; });
|
||||
class FakeMongoClient {
|
||||
constructor(uri) { instances++; assert.equal(uri, settings.mongoUri); }
|
||||
async connect() { connections++; await connected; }
|
||||
db(name) { selectedNames.push(name); return selectedDb; }
|
||||
async close() { closes++; }
|
||||
}
|
||||
const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient });
|
||||
const resultsPromise = Promise.all([provider.getDb(), provider.getDb(), provider.getDb()]);
|
||||
await Promise.resolve();
|
||||
release();
|
||||
const results = await resultsPromise;
|
||||
assert.equal(instances, 1);
|
||||
assert.equal(connections, 1);
|
||||
assert.deepEqual(selectedNames, ['phase1_fixture']);
|
||||
assert.equal(results.every(value => value === selectedDb), true);
|
||||
assert.equal(await provider.getDb(), selectedDb);
|
||||
await provider.closeDb();
|
||||
assert.equal(closes, 1);
|
||||
});
|
||||
|
||||
test('a failed database connection is sanitized, closed, and retryable', async () => {
|
||||
let instances = 0;
|
||||
let closes = 0;
|
||||
const selectedDb = { recovered: true };
|
||||
class FakeMongoClient {
|
||||
constructor() { this.attempt = ++instances; }
|
||||
async connect() {
|
||||
if (this.attempt === 1) throw new Error(`connect failed: ${settings.mongoUri}`);
|
||||
}
|
||||
db() { return selectedDb; }
|
||||
async close() { closes++; }
|
||||
}
|
||||
const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient });
|
||||
await assert.rejects(provider.getDb(), error => {
|
||||
assert.match(error.message, /Database connection failed/);
|
||||
assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false);
|
||||
assert.equal(error.message.includes('mongodb://'), false);
|
||||
return true;
|
||||
});
|
||||
assert.equal(closes, 1);
|
||||
assert.equal(await provider.getDb(), selectedDb);
|
||||
assert.equal(instances, 2);
|
||||
await provider.closeDb();
|
||||
});
|
||||
|
||||
test('database client construction errors cannot reveal the connection URI', async () => {
|
||||
class ConstructorFailure {
|
||||
constructor() { throw new Error(`Invalid URI: ${settings.mongoUri}`); }
|
||||
}
|
||||
const provider = createDbProvider({ settings, MongoClientClass: ConstructorFailure });
|
||||
await assert.rejects(provider.getDb(), error => {
|
||||
assert.match(error.message, /Database connection failed/);
|
||||
assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false);
|
||||
return true;
|
||||
});
|
||||
await provider.closeDb();
|
||||
});
|
||||
|
||||
test('database selection errors are sanitized and do not poison later attempts', async () => {
|
||||
let instances = 0;
|
||||
let closes = 0;
|
||||
const selectedDb = { recovered: true };
|
||||
class SelectionFailure {
|
||||
constructor() { this.attempt = ++instances; }
|
||||
async connect() {}
|
||||
db() {
|
||||
if (this.attempt === 1) throw new Error(`database selection failed: ${settings.mongoUri}`);
|
||||
return selectedDb;
|
||||
}
|
||||
async close() { closes++; }
|
||||
}
|
||||
const provider = createDbProvider({ settings, MongoClientClass: SelectionFailure });
|
||||
await assert.rejects(provider.getDb(), error => {
|
||||
assert.match(error.message, /Database connection failed/);
|
||||
assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false);
|
||||
return true;
|
||||
});
|
||||
assert.equal(closes, 1);
|
||||
assert.equal(await provider.getDb(), selectedDb);
|
||||
assert.equal(instances, 2);
|
||||
await provider.closeDb();
|
||||
});
|
||||
|
||||
test('missing database configuration fails before constructing any client', async () => {
|
||||
class UnexpectedClient { constructor() { assert.fail('A client must not be created without MONGO_URI.'); } }
|
||||
const provider = createDbProvider({ settings: createConfig({}), MongoClientClass: UnexpectedClient });
|
||||
await assert.rejects(provider.getDb(), /MONGO_URI must be configured/);
|
||||
await provider.closeDb();
|
||||
});
|
||||
|
||||
test('database close is idempotent, waits for a pending connection, and allows reopening', async () => {
|
||||
let instances = 0;
|
||||
let closes = 0;
|
||||
let release;
|
||||
const connected = new Promise(resolve => { release = resolve; });
|
||||
class FakeMongoClient {
|
||||
constructor() { this.attempt = ++instances; }
|
||||
async connect() { if (this.attempt === 1) await connected; }
|
||||
db() { return { attempt: this.attempt }; }
|
||||
async close() { closes++; }
|
||||
}
|
||||
const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient });
|
||||
const pending = provider.getDb();
|
||||
const closing = provider.closeDb();
|
||||
release();
|
||||
await Promise.all([pending, closing]);
|
||||
assert.equal(closes, 1);
|
||||
await provider.closeDb();
|
||||
assert.equal(closes, 1);
|
||||
assert.deepEqual(await provider.getDb(), { attempt: 2 });
|
||||
await provider.closeDb();
|
||||
assert.equal(closes, 2);
|
||||
});
|
||||
|
||||
test('logs redact URLs, credential fields, explicit secrets, and terminal control characters', () => {
|
||||
const raw = [
|
||||
'Resolved https://stream.invalid/video.mp4?signature=NOT_A_REAL_SIGNATURE',
|
||||
'Database mongodb+srv://fixture:NOT_A_REAL_PASSWORD@database.invalid/',
|
||||
'Authorization: Bearer NOT_A_REAL_BEARER',
|
||||
'Cookie=FIXTURE_COOKIE=NOT_A_REAL_COOKIE',
|
||||
'Raw known value KNOWN_FIXTURE_SECRET==',
|
||||
'\x1b[31mReadable status\x1b[0m\x00',
|
||||
].join('\n');
|
||||
const sanitized = sanitizeLog(raw, ['KNOWN_FIXTURE_SECRET==']);
|
||||
assert.doesNotMatch(sanitized, /NOT_A_REAL_|KNOWN_FIXTURE_SECRET|https:\/\/|mongodb\+srv:\/\/|\x1b|\x00/);
|
||||
assert.match(sanitized, /Readable status/);
|
||||
assert.match(sanitized, /\[redacted URL\]/);
|
||||
});
|
||||
|
||||
test('streamed log redaction handles URLs and secrets split across pipe chunks', () => {
|
||||
const lines = [];
|
||||
const sanitizer = createLineSanitizer(line => lines.push(line), { secrets: ['KNOWN_FIXTURE_SECRET=='] });
|
||||
sanitizer.write(Buffer.from('Resolving https://stream.inv'));
|
||||
sanitizer.write(Buffer.from('alid/video?signature=NOT_A_REAL_SIGNATURE and KNOWN_FIX'));
|
||||
assert.deepEqual(lines, []);
|
||||
sanitizer.write(Buffer.from('TURE_SECRET==\n'));
|
||||
sanitizer.end();
|
||||
assert.equal(lines.length, 1);
|
||||
assert.doesNotMatch(lines.join(''), /NOT_A_REAL_|KNOWN_FIXTURE_SECRET|stream\.invalid|https:/);
|
||||
assert.match(lines.join(''), /\[redacted URL\]/);
|
||||
assert.match(lines.join(''), /\[redacted\]/);
|
||||
});
|
||||
|
||||
test('streamed log decoding preserves UTF-8 and sanitizes the unterminated final line', () => {
|
||||
const lines = [];
|
||||
const sanitizer = createLineSanitizer(line => lines.push(line));
|
||||
const input = Buffer.from('Grüße — fertig\nToken=NOT_A_REAL_TOKEN');
|
||||
const split = input.indexOf(Buffer.from('ü')) + 1;
|
||||
sanitizer.write(input.subarray(0, split));
|
||||
sanitizer.write(input.subarray(split));
|
||||
sanitizer.end();
|
||||
assert.equal(lines[0], 'Grüße — fertig\n');
|
||||
assert.doesNotMatch(lines.join(''), /NOT_A_REAL_TOKEN|�/);
|
||||
});
|
||||
|
||||
test('oversized streamed lines are discarded whole and subsequent lines recover', () => {
|
||||
const lines = [];
|
||||
const sanitizer = createLineSanitizer(line => lines.push(line), { maxLineLength: 32 });
|
||||
sanitizer.write('x'.repeat(100_000));
|
||||
sanitizer.write('NOT_A_REAL_TRAILING_SECRET\nNormal status\n');
|
||||
sanitizer.end();
|
||||
assert.deepEqual(lines, ['[oversized log line omitted]\n', 'Normal status\n']);
|
||||
});
|
||||
|
||||
test('large stored logs remain bounded after redaction', () => {
|
||||
const sanitized = sanitizeLog('x'.repeat(LOG_LIMIT * 4) + '\nToken=NOT_A_REAL_TOKEN');
|
||||
assert.ok(sanitized.length <= LOG_LIMIT + 64);
|
||||
assert.match(sanitized, /^\[earlier log output omitted\]/);
|
||||
assert.doesNotMatch(sanitized, /NOT_A_REAL_TOKEN/);
|
||||
});
|
||||
|
||||
test('normalized PM2 data retains process ID zero and excludes raw environments', () => {
|
||||
const normalized = normalizeProcess(pm2Process());
|
||||
assert.equal(normalized.pm_id, '0');
|
||||
assert.equal(normalized.cpu, '2.5%');
|
||||
assert.equal(normalized.memoryMB, '8 MB');
|
||||
assert.deepEqual(Object.keys(normalized).sort(), ['name', 'pid', 'pm_id', 'status', 'cpu', 'memoryMB', 'uptime', 'execPath'].sort());
|
||||
assert.doesNotMatch(JSON.stringify(normalized), /NOT_A_REAL_|MONGO_URI|pm2_env|"raw"/);
|
||||
});
|
||||
|
||||
test('worker lists and management pages include only the configured worker executable', async () => {
|
||||
const { controller, calls } = supervisor([
|
||||
pm2Process(),
|
||||
pm2Process({ name: 'unrelated-app', pm_id: 3, pm2_env: { pm_exec_path: '/srv/unrelated/queue_worker.js', status: 'online' } }),
|
||||
pm2Process({ name: 'same-prefix', pm_id: 4, pm2_env: { pm_exec_path: settings.workerScript + '.unrelated' } }),
|
||||
]);
|
||||
const json = response();
|
||||
await controller.listJson({}, json);
|
||||
assert.equal(json.statusCode, 200);
|
||||
assert.equal(json.body.processes.length, 1);
|
||||
assert.equal(json.body.processes[0].name, 'proxer-worker-1');
|
||||
assert.doesNotMatch(JSON.stringify(json.body), /NOT_A_REAL_|unrelated-app|same-prefix|pm2_env/);
|
||||
const page = response();
|
||||
await controller.getManage({}, page, error => { throw error; });
|
||||
assert.equal(page.view, 'pm2');
|
||||
assert.equal(page.body.processes.length, 1);
|
||||
assert.deepEqual(calls, [['jlist'], ['jlist']]);
|
||||
});
|
||||
|
||||
test('PM2 management rejects all and leading-option names before calling the supervisor', async () => {
|
||||
const { controller, calls } = supervisor([pm2Process()]);
|
||||
for (const name of ['all', 'ALL', '--help', '-worker']) {
|
||||
const res = response();
|
||||
await controller.postCommand({ body: { cmd: 'stop', name } }, res);
|
||||
assert.equal(res.statusCode, 400, name);
|
||||
assert.equal(res.body.ok, false);
|
||||
assert.equal(await controller.resolveManagedProcess(name), null);
|
||||
}
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test('worker creation rejects arbitrary script paths before invoking PM2', async () => {
|
||||
const { controller, calls } = supervisor([]);
|
||||
const res = response();
|
||||
await controller.postCommand({ body: { cmd: 'create', name: 'proxer-worker-2', scriptPath: '/tmp/unrelated-script.js' } }, res);
|
||||
assert.equal(res.statusCode, 400);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test('worker creation uses server-owned executable and cwd without returning PM2 output', async () => {
|
||||
const { controller, calls } = supervisor([]);
|
||||
const res = response();
|
||||
await controller.postCommand({ body: { cmd: 'create', name: 'proxer-worker-2' } }, res);
|
||||
assert.equal(res.statusCode, 200);
|
||||
assert.equal(res.body.ok, true);
|
||||
assert.deepEqual(calls[0], ['jlist']);
|
||||
const create = calls[1];
|
||||
assert.deepEqual(create.slice(0, 4), ['start', settings.workerScript, '--name', 'proxer-worker-2']);
|
||||
assert.equal(create[create.indexOf('--cwd') + 1], settings.projectRoot);
|
||||
assert.equal(create[create.indexOf('--interpreter') + 1], process.execPath);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr|pm2_env/);
|
||||
});
|
||||
|
||||
test('worker creation cannot reuse an unrelated PM2 process name', async () => {
|
||||
const unrelated = pm2Process({ name: 'existing-service', pm2_env: { pm_exec_path: '/srv/existing-service.js' } });
|
||||
const { controller, calls } = supervisor([unrelated]);
|
||||
const res = response();
|
||||
await controller.postCommand({ body: { cmd: 'create', name: 'existing-service' } }, res);
|
||||
assert.equal(res.statusCode, 409);
|
||||
assert.deepEqual(calls, [['jlist']]);
|
||||
});
|
||||
|
||||
test('worker commands target the resolved numeric PM2 ID, including zero', async () => {
|
||||
for (const cmd of ['start', 'stop', 'restart', 'delete']) {
|
||||
const { controller, calls } = supervisor([pm2Process()]);
|
||||
const res = response();
|
||||
await controller.postCommand({ body: { cmd, name: 'proxer-worker-1' } }, res);
|
||||
assert.equal(res.statusCode, 200, cmd);
|
||||
assert.deepEqual(calls, [['jlist'], [cmd, '0']]);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr/);
|
||||
}
|
||||
});
|
||||
|
||||
test('commands cannot target unrelated, ambiguous, or invalid-ID PM2 processes', async () => {
|
||||
const cases = [
|
||||
[pm2Process({ pm2_env: { pm_exec_path: '/srv/unrelated.js' } })],
|
||||
[pm2Process(), pm2Process({ pm_id: 1 })],
|
||||
[pm2Process({ pm_id: -1 })],
|
||||
[pm2Process({ pm_id: '0' })],
|
||||
];
|
||||
for (const processes of cases) {
|
||||
const { controller, calls } = supervisor(processes);
|
||||
const res = response();
|
||||
await controller.postCommand({ body: { cmd: 'stop', name: 'proxer-worker-1' } }, res);
|
||||
assert.equal(res.statusCode, 404);
|
||||
assert.deepEqual(calls, [['jlist']]);
|
||||
}
|
||||
});
|
||||
|
||||
test('PM2 command failures return a useful status without raw stderr', async () => {
|
||||
const { controller } = supervisor([pm2Process()], { code: 1 });
|
||||
const res = response();
|
||||
await controller.postCommand({ body: { cmd: 'restart', name: 'proxer-worker-1' } }, res);
|
||||
assert.equal(res.statusCode, 502);
|
||||
assert.equal(res.body.ok, false);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr/);
|
||||
});
|
||||
|
||||
test('PM2 availability and malformed-list errors are sanitized', async () => {
|
||||
for (const run of [
|
||||
async () => { throw new Error('NOT_A_REAL_SUPERVISOR_SECRET'); },
|
||||
async () => ({ code: 0, stdout: 'NOT_A_REAL_INVALID_JSON', stderr: '' }),
|
||||
async () => ({ code: 0, stdout: '{}', stderr: '' }),
|
||||
async () => ({ code: 2, stdout: '[]', stderr: 'NOT_A_REAL_STDERR_SECRET' }),
|
||||
]) {
|
||||
const controller = createPm2Controller({ settings, run });
|
||||
const res = response();
|
||||
await controller.listJson({}, res);
|
||||
assert.equal(res.statusCode, 503);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_/);
|
||||
}
|
||||
});
|
||||
|
||||
test('host-wide PM2 save returns409 without running a supervisor command', async () => {
|
||||
const { controller, calls } = supervisor([pm2Process()]);
|
||||
const res = response();
|
||||
await controller.postCommand({ body: { cmd: 'save' } }, res);
|
||||
assert.equal(res.statusCode, 409);
|
||||
assert.equal(res.body.ok, false);
|
||||
assert.deepEqual(calls, []);
|
||||
});
|
||||
@@ -0,0 +1,436 @@
|
||||
'use strict';
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const { Duplex } = require('node:stream');
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const express = require('express');
|
||||
const WebSocket = require('ws');
|
||||
const { config } = require('../lib/config');
|
||||
const { createApplication, createServer, attachLogConnection, handleHttpError, MAX_WS_PAYLOAD, MAX_WS_BUFFER } = require('../server');
|
||||
|
||||
class FakeSocket extends EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
this.readyState = WebSocket.OPEN;
|
||||
this.bufferedAmount = 0;
|
||||
this.sent = [];
|
||||
this.closeCalls = [];
|
||||
this.terminations = 0;
|
||||
this.pings = 0;
|
||||
}
|
||||
send(text, callback) {
|
||||
assert.equal(this.readyState, WebSocket.OPEN, 'Never send after a socket is closed.');
|
||||
if (this.sendFailure) throw new Error('NOT_A_REAL_SEND_SECRET');
|
||||
this.sent.push(JSON.parse(text));
|
||||
callback?.(this.sendCallbackFailure ? new Error('NOT_A_REAL_CALLBACK_SECRET') : undefined);
|
||||
}
|
||||
close(code, reason) {
|
||||
this.closeCalls.push({ code, reason });
|
||||
this.readyState = WebSocket.CLOSED;
|
||||
this.emit('close');
|
||||
}
|
||||
terminate() {
|
||||
this.terminations++;
|
||||
this.readyState = WebSocket.CLOSED;
|
||||
this.emit('close');
|
||||
}
|
||||
ping() { this.pings++; }
|
||||
}
|
||||
|
||||
function childProcess() {
|
||||
const child = new EventEmitter();
|
||||
child.stdout = new EventEmitter();
|
||||
child.stderr = new EventEmitter();
|
||||
child.killCalls = 0;
|
||||
child.kill = () => { child.killCalls++; return true; };
|
||||
return child;
|
||||
}
|
||||
|
||||
function logFixture(resolveWorker = async name => ({ name, pm_id: '0' })) {
|
||||
const socket = new FakeSocket();
|
||||
const children = [];
|
||||
const calls = [];
|
||||
const connection = attachLogConnection(socket, {
|
||||
settings: config,
|
||||
resolveWorker,
|
||||
spawnProcess: (...args) => {
|
||||
calls.push(args);
|
||||
const child = childProcess();
|
||||
children.push(child);
|
||||
return child;
|
||||
},
|
||||
});
|
||||
return { socket, children, calls, connection };
|
||||
}
|
||||
|
||||
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||||
async function message(socket, payload) {
|
||||
socket.emit('message', Buffer.from(JSON.stringify(payload)), false);
|
||||
await settle();
|
||||
}
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
let reject;
|
||||
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
test('log subscriptions resolve a registered worker and invoke its numeric PM2 ID', async () => {
|
||||
const names = [];
|
||||
const fixture = logFixture(async name => { names.push(name); return { name, pm_id: '0' }; });
|
||||
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
|
||||
assert.deepEqual(names, ['proxer-worker-1']);
|
||||
assert.deepEqual(fixture.calls[0], ['pm2', ['logs', '0', '--raw', '--lines', '200'], {
|
||||
cwd: config.projectRoot,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
}]);
|
||||
fixture.connection.dispose();
|
||||
});
|
||||
|
||||
test('log requests reject missing names, all, and option-like names without resolving or spawning', async () => {
|
||||
let lookups = 0;
|
||||
const fixture = logFixture(async () => { lookups++; return null; });
|
||||
for (const name of [undefined, null, '', 'all', 'ALL', '--help', '-worker']) {
|
||||
await message(fixture.socket, { type: 'logs', name });
|
||||
}
|
||||
assert.equal(lookups, 0);
|
||||
assert.equal(fixture.calls.length, 0);
|
||||
assert.equal(fixture.socket.sent.filter(item => item.type === 'error').length, 7);
|
||||
});
|
||||
|
||||
test('unknown workers and invalid resolved IDs cannot start log processes', async () => {
|
||||
for (const worker of [null, { pm_id: '-1' }, { pm_id: 'all' }, { pm_id: '9007199254740993' }]) {
|
||||
const fixture = logFixture(async () => worker);
|
||||
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
|
||||
assert.equal(fixture.calls.length, 0);
|
||||
assert.match(fixture.socket.sent.at(-1).error, /not found/);
|
||||
}
|
||||
});
|
||||
|
||||
test('null, arrays, primitives, malformed JSON, and binary requests are handled safely', async () => {
|
||||
const fixture = logFixture();
|
||||
for (const payload of [null, [], 'logs', 1, true]) await message(fixture.socket, payload);
|
||||
fixture.socket.emit('message', Buffer.from('{'), false);
|
||||
fixture.socket.emit('message', Buffer.from('{}'), true);
|
||||
await settle();
|
||||
assert.equal(fixture.calls.length, 0);
|
||||
assert.equal(fixture.socket.sent.filter(item => item.type === 'error').length, 7);
|
||||
});
|
||||
|
||||
test('oversized log requests close the connection with a bounded message', async () => {
|
||||
const fixture = logFixture();
|
||||
fixture.socket.emit('message', Buffer.from('x'.repeat(MAX_WS_PAYLOAD + 1)), false);
|
||||
await settle();
|
||||
assert.equal(fixture.socket.closeCalls[0].code, 1009);
|
||||
assert.equal(fixture.calls.length, 0);
|
||||
assert.ok(JSON.stringify(fixture.socket.sent).length < 1000);
|
||||
});
|
||||
|
||||
test('log streams redact split-chunk URLs and credential lines and bound oversized lines', async () => {
|
||||
const fixture = logFixture();
|
||||
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
|
||||
const child = fixture.children[0];
|
||||
child.stdout.emit('data', Buffer.from('Resolved https://stream.inv'));
|
||||
child.stdout.emit('data', Buffer.from('alid/video?signature=NOT_A_REAL_SIGNATURE\n'));
|
||||
child.stderr.emit('data', Buffer.from('Token=NOT_A_REAL_'));
|
||||
child.stderr.emit('data', Buffer.from('TOKEN\n'));
|
||||
child.stdout.emit('data', Buffer.from('x'.repeat(100_000) + '\n'));
|
||||
child.stdout.emit('data', Buffer.from('Completed a fixture'));
|
||||
child.emit('close', 0);
|
||||
const output = fixture.socket.sent.filter(item => ['stdout', 'stderr'].includes(item.type));
|
||||
assert.doesNotMatch(JSON.stringify(output), /NOT_A_REAL_|https:\/\/|stream\.invalid/);
|
||||
assert.match(JSON.stringify(output), /redacted URL/);
|
||||
assert.match(JSON.stringify(output), /oversized log line omitted/);
|
||||
assert.match(JSON.stringify(output), /Completed a fixture/);
|
||||
assert.ok(JSON.stringify(output).length < 1000);
|
||||
});
|
||||
|
||||
test('stop-logs kills the subscription and suppresses later child output', async () => {
|
||||
const fixture = logFixture();
|
||||
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
|
||||
const child = fixture.children[0];
|
||||
await message(fixture.socket, { type: 'stop-logs' });
|
||||
const count = fixture.socket.sent.length;
|
||||
child.stdout.emit('data', Buffer.from('stale output\n'));
|
||||
child.emit('close', 0);
|
||||
assert.equal(child.killCalls, 1);
|
||||
assert.equal(fixture.socket.sent.length, count);
|
||||
});
|
||||
|
||||
test('disconnect and socket errors clean up children without sending on a closed connection', async () => {
|
||||
for (const event of ['close', 'error']) {
|
||||
const fixture = logFixture();
|
||||
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
|
||||
fixture.socket.readyState = WebSocket.CLOSED;
|
||||
fixture.socket.emit(event, new Error('NOT_A_REAL_SOCKET_SECRET'));
|
||||
const count = fixture.socket.sent.length;
|
||||
fixture.children[0].stderr.emit('data', Buffer.from('late output\n'));
|
||||
fixture.children[0].emit('error', new Error('NOT_A_REAL_LATE_SECRET'));
|
||||
assert.equal(fixture.children[0].killCalls, 1);
|
||||
assert.equal(fixture.socket.sent.length, count);
|
||||
}
|
||||
});
|
||||
|
||||
test('stop and disconnect invalidate a pending worker lookup before it can spawn', async () => {
|
||||
for (const action of ['stop', 'disconnect']) {
|
||||
const pending = deferred();
|
||||
const fixture = logFixture(() => pending.promise);
|
||||
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
|
||||
if (action === 'stop') await message(fixture.socket, { type: 'stop-logs' });
|
||||
else fixture.socket.close(1000, 'fixture finished');
|
||||
pending.resolve({ pm_id: '0' });
|
||||
await settle();
|
||||
assert.equal(fixture.calls.length, 0, action);
|
||||
}
|
||||
});
|
||||
|
||||
test('a newer selection wins when an older worker lookup resolves later', async () => {
|
||||
const old = deferred();
|
||||
const fixture = logFixture(name => name === 'worker-old' ? old.promise : Promise.resolve({ pm_id: '2' }));
|
||||
await message(fixture.socket, { type: 'logs', name: 'worker-old' });
|
||||
await message(fixture.socket, { type: 'logs', name: 'worker-new' });
|
||||
old.resolve({ pm_id: '1' });
|
||||
await settle();
|
||||
assert.equal(fixture.calls.length, 1);
|
||||
assert.equal(fixture.calls[0][1][1], '2');
|
||||
fixture.connection.dispose();
|
||||
});
|
||||
|
||||
test('late close events from an old log process cannot clear a new subscription', async () => {
|
||||
const fixture = logFixture(async name => ({ pm_id: name === 'worker-old' ? '1' : '2' }));
|
||||
await message(fixture.socket, { type: 'logs', name: 'worker-old' });
|
||||
await message(fixture.socket, { type: 'logs', name: 'worker-new' });
|
||||
const old = fixture.children[0];
|
||||
const current = fixture.children[1];
|
||||
assert.equal(old.killCalls, 1);
|
||||
old.emit('close', 0);
|
||||
current.stdout.emit('data', Buffer.from('new subscription is active\n'));
|
||||
assert.match(fixture.socket.sent.at(-1).data, /new subscription is active/);
|
||||
assert.equal(fixture.socket.sent.some(item => item.type === 'close'), false);
|
||||
fixture.connection.dispose();
|
||||
assert.equal(current.killCalls, 1);
|
||||
});
|
||||
|
||||
test('lookup and spawn errors return generic messages without raw details', async () => {
|
||||
const fixture = logFixture(async () => { throw new Error('NOT_A_REAL_LOOKUP_SECRET'); });
|
||||
await message(fixture.socket, { type: 'logs', name: 'worker-one' });
|
||||
assert.doesNotMatch(JSON.stringify(fixture.socket.sent), /NOT_A_REAL_/);
|
||||
const socket = new FakeSocket();
|
||||
attachLogConnection(socket, {
|
||||
resolveWorker: async () => ({ pm_id: '0' }),
|
||||
spawnProcess: () => { throw new Error('NOT_A_REAL_SPAWN_SECRET'); },
|
||||
});
|
||||
await message(socket, { type: 'logs', name: 'worker-one' });
|
||||
assert.equal(socket.sent.at(-1).type, 'error');
|
||||
assert.doesNotMatch(JSON.stringify(socket.sent), /NOT_A_REAL_/);
|
||||
});
|
||||
|
||||
test('asynchronous child and pipe errors are handled and cleaned up', async () => {
|
||||
for (const source of ['child', 'stdout', 'stderr']) {
|
||||
const fixture = logFixture();
|
||||
await message(fixture.socket, { type: 'logs', name: 'worker-one' });
|
||||
const child = fixture.children[0];
|
||||
(source === 'child' ? child : child[source]).emit('error', new Error('NOT_A_REAL_PIPE_SECRET'));
|
||||
assert.equal(child.killCalls, 1);
|
||||
assert.equal(fixture.socket.sent.at(-1).type, 'error');
|
||||
assert.doesNotMatch(JSON.stringify(fixture.socket.sent), /NOT_A_REAL_/);
|
||||
}
|
||||
});
|
||||
|
||||
test('a slow WebSocket consumer is disconnected and its log child is stopped', async () => {
|
||||
const fixture = logFixture();
|
||||
await message(fixture.socket, { type: 'logs', name: 'worker-one' });
|
||||
fixture.socket.bufferedAmount = MAX_WS_BUFFER;
|
||||
fixture.children[0].stdout.emit('data', Buffer.from('next bounded line\n'));
|
||||
assert.equal(fixture.socket.closeCalls.at(-1).code, 1013);
|
||||
assert.equal(fixture.children[0].killCalls, 1);
|
||||
});
|
||||
|
||||
test('WebSocket send failures clean up the active subscription', async () => {
|
||||
for (const property of ['sendFailure', 'sendCallbackFailure']) {
|
||||
const fixture = logFixture();
|
||||
await message(fixture.socket, { type: 'logs', name: 'worker-one' });
|
||||
fixture.socket[property] = true;
|
||||
fixture.children[0].stdout.emit('data', Buffer.from('next line\n'));
|
||||
assert.equal(fixture.children[0].killCalls, 1);
|
||||
assert.equal(fixture.socket.closeCalls.at(-1).code, 1011);
|
||||
}
|
||||
});
|
||||
|
||||
test('HTTP error rendering and JSON responses exclude raw errors and stacks', () => {
|
||||
function response() {
|
||||
return {
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
json(body) { this.body = body; return this; },
|
||||
render(view, body) { this.view = view; this.body = body; return this; },
|
||||
};
|
||||
}
|
||||
for (const api of [false, true]) {
|
||||
const res = response();
|
||||
handleHttpError(new Error('NOT_A_REAL_DATABASE_SECRET'), { path: api ? '/pm2/list-json' : '/', is: () => false }, res, () => assert.fail('Unexpected next().'));
|
||||
assert.equal(res.statusCode, 500);
|
||||
assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stack|Error:/);
|
||||
if (!api) assert.equal(res.view, 'error');
|
||||
}
|
||||
let forwarded;
|
||||
handleHttpError(new Error('NOT_A_REAL_SECRET'), {}, { headersSent: true }, error => { forwarded = error; });
|
||||
assert.doesNotMatch(forwarded.message, /NOT_A_REAL_/);
|
||||
});
|
||||
|
||||
// Exercise Express body parsing using real HTTP message objects and no listening socket.
|
||||
function offlineRequest(app, body, contentType = 'application/json') {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new Duplex({ read() {}, write(chunk, encoding, callback) { callback(); } });
|
||||
const request = new http.IncomingMessage(socket);
|
||||
const bytes = Buffer.from(body);
|
||||
request.method = 'POST';
|
||||
request.url = '/pm2/fixture';
|
||||
request.headers = { 'content-type': contentType, 'content-length': String(bytes.length) };
|
||||
const response = new http.ServerResponse(request);
|
||||
const timeout = setTimeout(() => reject(new Error('Offline HTTP fixture did not complete.')), 2000);
|
||||
response.end = data => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ status: response.statusCode, text: String(data ?? '') });
|
||||
socket.destroy();
|
||||
return response;
|
||||
};
|
||||
app.handle(request, response, error => {
|
||||
clearTimeout(timeout);
|
||||
socket.destroy();
|
||||
reject(error || new Error('Offline HTTP fixture was not handled.'));
|
||||
});
|
||||
request.push(bytes);
|
||||
request.push(null);
|
||||
});
|
||||
}
|
||||
|
||||
test('application factory has safe shared locals and enforces32KiB JSON/form limits without listening', async () => {
|
||||
const router = express.Router();
|
||||
router.post('/pm2/fixture', (req, res) => res.json({ received: req.body }));
|
||||
const app = createApplication({ router });
|
||||
assert.deepEqual(app.locals.global, { captcha_blocked: false });
|
||||
const valid = await offlineRequest(app, JSON.stringify({ title: 'Fixture' }));
|
||||
assert.equal(valid.status, 200);
|
||||
assert.deepEqual(JSON.parse(valid.text), { received: { title: 'Fixture' } });
|
||||
const invalid = await offlineRequest(app, '{NOT_A_REAL_PARSE_SECRET');
|
||||
assert.equal(invalid.status, 400);
|
||||
assert.doesNotMatch(invalid.text, /NOT_A_REAL_/);
|
||||
const largeJson = await offlineRequest(app, JSON.stringify({ text: 'x'.repeat(33 * 1024) }));
|
||||
assert.equal(largeJson.status, 413);
|
||||
const largeForm = await offlineRequest(app, 'text=' + 'x'.repeat(33 * 1024), 'application/x-www-form-urlencoded');
|
||||
assert.equal(largeForm.status, 413);
|
||||
});
|
||||
|
||||
test('server construction does not listen and heartbeat/server close clean up log children and timer', async () => {
|
||||
const server = new EventEmitter();
|
||||
server.listening = false;
|
||||
server.listen = () => assert.fail('createServer must not listen automatically.');
|
||||
class FakeWebSocketServer extends EventEmitter {
|
||||
constructor(options) { super(); this.options = options; this.clients = new Set(); this.closed = false; }
|
||||
close() { if (!this.closed) { this.closed = true; this.emit('close'); } }
|
||||
}
|
||||
let tick;
|
||||
let cleared = 0;
|
||||
const interval = { unref() {} };
|
||||
const child = childProcess();
|
||||
const runtime = createServer({
|
||||
router: express.Router(),
|
||||
createHttpServer: () => server,
|
||||
WebSocketServer: FakeWebSocketServer,
|
||||
scheduleInterval: (callback, period) => { tick = callback; assert.equal(period, 30_000); return interval; },
|
||||
cancelInterval: actual => { assert.equal(actual, interval); cleared++; },
|
||||
resolveWorker: async () => ({ pm_id: '0' }),
|
||||
spawnProcess: () => child,
|
||||
});
|
||||
assert.equal(runtime.wss.options.maxPayload, 16 * 1024);
|
||||
const socket = new FakeSocket();
|
||||
runtime.wss.clients.add(socket);
|
||||
runtime.wss.emit('connection', socket);
|
||||
await message(socket, { type: 'logs', name: 'worker-one' });
|
||||
tick();
|
||||
assert.equal(socket.pings, 1);
|
||||
socket.emit('pong');
|
||||
tick();
|
||||
assert.equal(socket.pings, 2);
|
||||
tick();
|
||||
assert.equal(socket.terminations, 1);
|
||||
assert.equal(child.killCalls, 1);
|
||||
server.emit('close');
|
||||
assert.equal(cleared, 1);
|
||||
assert.equal(runtime.wss.closed, true);
|
||||
await runtime.close();
|
||||
assert.equal(cleared, 1);
|
||||
});
|
||||
|
||||
test('PM2 browser controls use safe DOM text, visible feedback, ready-state checks, and stop on deselect', async () => {
|
||||
class Element {
|
||||
constructor(tag = 'div') {
|
||||
this.tagName = tag;
|
||||
this.className = '';
|
||||
this.children = [];
|
||||
this.dataset = {};
|
||||
this.style = {};
|
||||
this.textContent = '';
|
||||
this.listeners = {};
|
||||
this.scrollTop = this.scrollHeight = this.clientHeight = 0;
|
||||
this.classList = {
|
||||
add: (...names) => { this.className = [...new Set([...this.className.split(' '), ...names])].join(' '); },
|
||||
remove: (...names) => { this.className = this.className.split(' ').filter(name => !names.includes(name)).join(' '); },
|
||||
};
|
||||
}
|
||||
set innerHTML(value) { assert.fail('Untrusted refreshed process fields must not use innerHTML.'); }
|
||||
addEventListener(name, callback) { (this.listeners[name] ||= []).push(callback); }
|
||||
append(...values) { this.children.push(...values); }
|
||||
appendChild(value) { this.children.push(value); return value; }
|
||||
replaceChildren(...values) { this.children = values; }
|
||||
async click() { for (const callback of this.listeners.click || []) await callback({ preventDefault() {}, currentTarget: this }); }
|
||||
}
|
||||
const elements = new Map();
|
||||
const get = id => { if (!elements.has(id)) elements.set(id, new Element()); return elements.get(id); };
|
||||
const document = {
|
||||
getElementById: get,
|
||||
createElement: tag => new Element(tag),
|
||||
querySelectorAll: () => get('process-list').children.filter(node => node.className?.split(' ').includes('pm2-row')),
|
||||
};
|
||||
let socket;
|
||||
class BrowserSocket {
|
||||
static OPEN = 1;
|
||||
constructor() { socket = this; this.readyState = 0; this.sent = []; this.listeners = {}; }
|
||||
addEventListener(name, callback) { this.listeners[name] = callback; }
|
||||
send(text) { assert.equal(this.readyState, 1); this.sent.push(JSON.parse(text)); }
|
||||
}
|
||||
const maliciousName = '<img src=x onerror=alert(1)>';
|
||||
const process = { name: maliciousName, pm_id: '0', pid: '12', status: '<script>fixture</script>', execPath: '<b>fixture</b>', uptime: '1m' };
|
||||
const context = vm.createContext({
|
||||
document,
|
||||
WebSocket: BrowserSocket,
|
||||
window: { addEventListener() {} },
|
||||
location: { protocol: 'http:', host: 'fixture.invalid' },
|
||||
fetch: async () => ({ ok: true, json: async () => ({ ok: true, processes: [process] }) }),
|
||||
});
|
||||
const template = fs.readFileSync(path.join(config.projectRoot, 'views/pm2.ejs'), 'utf8');
|
||||
assert.equal(template.includes('id="btn-save"'), false);
|
||||
assert.equal(template.includes('/home/pm2/'), false);
|
||||
assert.ok(template.indexOf('id="control-output"') < template.indexOf('id="control-centre"'));
|
||||
const script = template.match(/<script>([\s\S]*?)<\/script>/)[1];
|
||||
vm.runInContext(script + '\nglobalThis.fixture = { refreshList, sendLogRequest, appendLog };', context);
|
||||
assert.equal(context.fixture.sendLogRequest({ type: 'logs', name: 'worker-one' }, false), false);
|
||||
assert.equal(socket.sent.length, 0);
|
||||
await context.fixture.refreshList();
|
||||
const row = document.querySelectorAll()[0];
|
||||
assert.equal(row.children[0].children[0].textContent, maliciousName);
|
||||
assert.equal(row.dataset.name, maliciousName);
|
||||
socket.readyState = 1;
|
||||
await row.click();
|
||||
assert.equal(socket.sent.at(-1).type, 'logs');
|
||||
await row.click();
|
||||
assert.equal(socket.sent.at(-1).type, 'stop-logs');
|
||||
context.fixture.appendLog('x'.repeat(200_000));
|
||||
assert.ok(get('logs').textContent.length < 66 * 1024);
|
||||
});
|
||||
@@ -0,0 +1,357 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const ejs = require("ejs");
|
||||
const {
|
||||
ValidationError, normalizeWatchUrl, normalizeFilename, validateOutputTarget,
|
||||
cookieToken, buildQueueJobs, sanitizeLog, toPublicJob, MAX_LOG_BYTES,
|
||||
} = require("../lib/jobValidation");
|
||||
const { createQueueController } = require("../controllers/queueController");
|
||||
const fixtures = require("./fixtures/legacy-contracts.json");
|
||||
|
||||
const repository = path.resolve(__dirname, "..");
|
||||
const sourceUrl = "https://proxer.me/watch/42/2/engsub";
|
||||
|
||||
async function temporaryConfig(t, extra = {}) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), "proxer-web-"));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
return { outputDir, tokenPrefix: "fixture_cookie=", maxSeriesEpisodes: 500, ...extra };
|
||||
}
|
||||
|
||||
function response() {
|
||||
return {
|
||||
statusCode: 200, headers: {},
|
||||
status(code) { this.statusCode = code; return this; },
|
||||
set(name, value) { this.headers[name] = value; return this; },
|
||||
render(template, data) { this.template = template; this.data = data; return this; },
|
||||
json(data) { this.data = data; return this; },
|
||||
redirect(location) { this.location = location; return this; },
|
||||
};
|
||||
}
|
||||
|
||||
test("legacy web naming fixtures stay compatible", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
for (const fixture of fixtures.namingCases.filter(entry => entry.entrypoint.startsWith("web-"))) {
|
||||
const jobs = await buildQueueJobs({
|
||||
...fixture.input, mode: fixture.entrypoint.slice(4), token: "fixture-value==",
|
||||
}, config);
|
||||
assert.deepEqual(jobs.map(job => job.filename), fixture.expectedFilenames);
|
||||
assert.ok(jobs.every(job => job.token === "fixture_cookie=fixture-value=="));
|
||||
}
|
||||
});
|
||||
|
||||
test("video form title is honored and explicit legacy filename takes priority", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
const body = { mode: "video", url: sourceUrl, name: "My video title", token: "fixture" };
|
||||
assert.equal((await buildQueueJobs(body, config))[0].filename, "My video title");
|
||||
assert.equal((await buildQueueJobs({ ...body, filename: "Legacy filename" }, config))[0].filename, "Legacy filename");
|
||||
});
|
||||
|
||||
test("URL validation accepts only canonical Proxer episode sources", () => {
|
||||
assert.equal(normalizeWatchUrl("https://www.proxer.me:443/watch/42/2/engsub/#player").url, sourceUrl);
|
||||
const invalid = [
|
||||
"http://proxer.me/watch/42/2/engsub", "https://proxer.me.evil.test/watch/42/2/engsub",
|
||||
"https://127.0.0.1/watch/42/2/engsub", "file:///watch/42/2/engsub",
|
||||
"https://user:pass@proxer.me/watch/42/2/engsub", "https://@proxer.me/watch/42/2/engsub",
|
||||
"https://proxer.me:8443/watch/42/2/engsub", `${sourceUrl}?token=secret`,
|
||||
"https://proxer.me/watch/42/0/engsub", "https://proxer.me/watch/42/2/invalid",
|
||||
"https://proxer.me/watch/9007199254740992/2/engsub", "https://proxer.me/watch/42/2/engsub\n",
|
||||
"https://proxer.me\\watch\\42\\2\\engsub",
|
||||
];
|
||||
for (const value of invalid) assert.throws(() => normalizeWatchUrl(value), ValidationError, value);
|
||||
});
|
||||
|
||||
test("series requests reject partial integers, unsupported languages and oversized ranges", async t => {
|
||||
const config = await temporaryConfig(t, { maxSeriesEpisodes: 3 });
|
||||
const body = { mode: "series", id: "42", episode_from: "1", episode_to: "3", language: "gerdub", token: "fixture" };
|
||||
assert.equal((await buildQueueJobs(body, config)).length, 3);
|
||||
for (const change of [
|
||||
{ id: "42junk" }, { episode_from: "1.5" }, { episode_to: "4" },
|
||||
{ episode_from: "3", episode_to: "2" }, { language: "unsupported" },
|
||||
{ episode_to: "9007199254740992" }, { id: ["42"] },
|
||||
]) {
|
||||
await assert.rejects(buildQueueJobs({ ...body, ...change }, config), ValidationError);
|
||||
}
|
||||
});
|
||||
|
||||
test("filename containment rejects traversal, control characters and symlink destinations", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
for (const filename of ["../escape", "sub/name", "sub\\name", "..", ".", "", " name", "name ", "bad\u0000name", "bad\nname", "ü".repeat(126)]) {
|
||||
assert.throws(() => normalizeFilename(filename), ValidationError, filename);
|
||||
}
|
||||
await fs.writeFile(path.join(config.outputDir, "existing.mp4"), "fixture bytes");
|
||||
assert.equal(await validateOutputTarget(config.outputDir, "existing"), path.join(config.outputDir, "existing.mp4"));
|
||||
await fs.symlink(path.join(config.outputDir, "existing.mp4"), path.join(config.outputDir, "link.mp4"));
|
||||
await assert.rejects(validateOutputTarget(config.outputDir, "link"), ValidationError);
|
||||
await fs.mkdir(path.join(config.outputDir, "directory.mp4"));
|
||||
await assert.rejects(validateOutputTarget(config.outputDir, "directory"), ValidationError);
|
||||
});
|
||||
|
||||
test("cookie tokens preserve equals signs and reject injected cookie separators", () => {
|
||||
assert.equal(cookieToken("base64-like==", "session="), "session=base64-like==");
|
||||
for (const token of ["", "with space", "foo;other=bar", "foo\nbar", "a".repeat(8192), "ü".repeat(4096), ["array"]]) {
|
||||
assert.throws(() => cookieToken(token, "session="), ValidationError);
|
||||
}
|
||||
assert.throws(() => cookieToken("fixture", undefined), /TOKEN_PREFIX/);
|
||||
assert.throws(() => cookieToken("fixture", "invalid=prefix="), /TOKEN_PREFIX/);
|
||||
});
|
||||
|
||||
test("filename, source URL and cookie validation reject C1 controls consistently", () => {
|
||||
for (const control of ["\u0080", "\u0085"]) {
|
||||
assert.throws(() => normalizeFilename(`file${control}name`), ValidationError);
|
||||
assert.throws(() => normalizeWatchUrl(`${sourceUrl}#player${control}`), ValidationError);
|
||||
assert.throws(() => cookieToken(`value${control}padding==`, "session="), ValidationError);
|
||||
}
|
||||
});
|
||||
|
||||
test("malformed Unicode is rejected before queue serialization while valid surrogate pairs remain intact", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
for (const malformed of ["\uD800", "\uDC00", "\uD800x", "\uDC00\uD800"]) {
|
||||
assert.throws(() => normalizeFilename(`file${malformed}name`), ValidationError);
|
||||
assert.throws(() => normalizeWatchUrl(`${sourceUrl}#${malformed}`), ValidationError);
|
||||
assert.throws(() => cookieToken(`value${malformed}==`, "session="), ValidationError);
|
||||
await assert.rejects(buildQueueJobs({
|
||||
mode: "video", url: sourceUrl, name: malformed, token: "fixture",
|
||||
}, config), ValidationError);
|
||||
}
|
||||
const validName = "Episode \uD83C\uDFAC";
|
||||
assert.equal(normalizeFilename(validName), validName);
|
||||
assert.equal(normalizeWatchUrl(`${sourceUrl}#\uD83C\uDFAC`).url, sourceUrl);
|
||||
assert.equal(cookieToken("valid-\uD83C\uDFAC==", "session="), "session=valid-\uD83C\uDFAC==");
|
||||
assert.equal((await buildQueueJobs({ mode: "video", url: sourceUrl, name: validName, token: "fixture" }, config))[0].filename, validName);
|
||||
});
|
||||
|
||||
test("invalid submissions do not connect or insert, and failure responses never show stacks or tokens", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
let calls = 0;
|
||||
const controller = createQueueController({ config, getDb: async () => { calls += 1; throw new Error("database fixture secret"); } });
|
||||
const bad = response();
|
||||
await controller.enqueue({ body: { mode: "video", url: "https://evil.test/file", token: "fixture-secret" } }, bad);
|
||||
assert.equal(bad.statusCode, 400);
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(bad.data.details, null);
|
||||
assert.doesNotMatch(JSON.stringify(bad.data), /fixture-secret|Error:|stack/);
|
||||
|
||||
const unavailable = response();
|
||||
await controller.enqueue({ body: { mode: "video", url: sourceUrl, token: "fixture-secret" } }, unavailable);
|
||||
assert.equal(unavailable.statusCode, 500);
|
||||
assert.equal(calls, 1);
|
||||
assert.doesNotMatch(JSON.stringify(unavailable.data), /database fixture secret|fixture-secret|Error:/);
|
||||
});
|
||||
|
||||
test("enqueue inserts all validated episode jobs in one batch and redirects to existing status URL", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
let inserted;
|
||||
const controller = createQueueController({ config, getDb: async () => ({ collection(name) {
|
||||
assert.equal(name, "queue");
|
||||
return { bulkWrite: async operations => { inserted = operations; } };
|
||||
} }) });
|
||||
const result = response();
|
||||
await controller.enqueue({ body: { mode: "series", id: "42", episode_from: "9", episode_to: "10", language: "engdub", name: "Series", token: "fixture" } }, result);
|
||||
assert.equal(result.location, "/status");
|
||||
assert.deepEqual(inserted.map(operation => operation.insertOne.document.filename), ["SeriesE09_engdub", "SeriesE10_engdub"]);
|
||||
});
|
||||
|
||||
test("processing reset is rejected without reading or mutating the database", () => {
|
||||
const controller = createQueueController({ getDb: () => { throw new Error("must not be called"); } });
|
||||
const result = response();
|
||||
controller.clearProcessing({}, result);
|
||||
assert.equal(result.statusCode, 409);
|
||||
assert.match(result.data.message, /cannot be cleared safely/);
|
||||
});
|
||||
|
||||
test("public job DTOs and log tails remove credentials, private fields and signed URLs", () => {
|
||||
const result = toPublicJob({
|
||||
_id: "fixture-id", filename: "Example", token: "session=fixture-value==",
|
||||
url: `${sourceUrl}#token=fragment-secret`, raw: { env: { SECRET: "secret" } },
|
||||
created_at: "2026-01-01T00:00:00Z",
|
||||
output_log: "session=fixture-value== token=another-secret https://media.test/video.mp4?token=signed-secret\nCookie: private_session=value",
|
||||
});
|
||||
assert.equal(result.url, sourceUrl);
|
||||
assert.equal(result.created_at, "2026-01-01T00:00:00.000Z");
|
||||
assert.equal(result.token, undefined);
|
||||
assert.equal(result.raw, undefined);
|
||||
assert.doesNotMatch(JSON.stringify(result), /fixture-value|another-secret|signed-secret|fragment-secret|private_session/);
|
||||
const bounded = sanitizeLog("x".repeat(MAX_LOG_BYTES * 3) + "LAST LINE");
|
||||
assert.ok(Buffer.byteLength(bounded) < MAX_LOG_BYTES + 100);
|
||||
assert.ok(bounded.endsWith("LAST LINE"));
|
||||
});
|
||||
|
||||
test("status endpoints use projections, exclude secret settings and refuse symlink file-size reads", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
await fs.writeFile(path.join(config.outputDir, "target.mp4"), "fixture");
|
||||
await fs.symlink(path.join(config.outputDir, "target.mp4"), path.join(config.outputDir, "link.mp4"));
|
||||
const database = { collection(name) {
|
||||
if (name === "settings") return { findOne: async (_filter, options) => {
|
||||
assert.deepEqual(options.projection, { captcha_blocked: 1, pause_reason: 1 });
|
||||
return { captcha_blocked: true, secret: "settings-secret" };
|
||||
} };
|
||||
return { find(filter, options) {
|
||||
assert.equal(options.projection.token, 1, "tokens are internal inputs to exact-value log redaction");
|
||||
return { sort() { return this; }, async toArray() {
|
||||
return name === "queue" && filter.processing === true
|
||||
? [{ _id: "active", filename: "link", url: sourceUrl, token: "fixture-secret", private_field: true }]
|
||||
: [];
|
||||
} };
|
||||
} };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
const result = response();
|
||||
await controller.statusData({}, result, error => { throw error; });
|
||||
assert.equal(result.headers["Cache-Control"], "no-store");
|
||||
assert.deepEqual(result.data.global, { captcha_blocked: true, pause_reason: null });
|
||||
assert.equal(result.data.processing[0].fileSize, null);
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /fixture-secret|settings-secret|private_field/);
|
||||
});
|
||||
|
||||
test("projected queued and history logs redact known cookies without exposing them in JSON or view models", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
const groups = ["queued", "processing", "done", "failed"];
|
||||
const records = Object.fromEntries(groups.map(group => {
|
||||
const token = `custom_cookie=${group}-exact-credential==`;
|
||||
return [group, {
|
||||
_id: group, filename: `Fixture ${group}`, url: sourceUrl, token,
|
||||
output_log: `Captured ${token}\nUnlabelled ${group}-exact-credential==`,
|
||||
private_field: "must never reach the view",
|
||||
}];
|
||||
}));
|
||||
const database = { collection(name) {
|
||||
if (name === "settings") return { findOne: async () => ({ captcha_blocked: false }) };
|
||||
return { find(filter, { projection }) {
|
||||
const group = name === "queue" ? (filter.processing === true ? "processing" : "queued") : name;
|
||||
assert.equal(projection.token, 1);
|
||||
// Apply the real inclusion projection so this test cannot accidentally
|
||||
// redact a token which MongoDB would have omitted from the response.
|
||||
const projected = Object.fromEntries(Object.entries(records[group]).filter(([key]) => projection[key] === 1));
|
||||
return { sort() { return this; }, async toArray() { return [projected]; } };
|
||||
} };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
const jsonResponse = response();
|
||||
await controller.statusData({}, jsonResponse, error => { throw error; });
|
||||
const viewResponse = response();
|
||||
await controller.status({}, viewResponse, error => { throw error; });
|
||||
for (const snapshot of [jsonResponse.data, viewResponse.data]) {
|
||||
for (const group of groups) {
|
||||
const job = snapshot[group][0];
|
||||
assert.equal(Object.hasOwn(job, "token"), false);
|
||||
assert.equal(Object.hasOwn(job, "private_field"), false);
|
||||
assert.match(job.output_log, /\[redacted\]/);
|
||||
assert.ok(!job.output_log.includes(`${group}-exact-credential==`));
|
||||
assert.ok(!job.output_log.includes("custom_cookie="));
|
||||
}
|
||||
assert.doesNotMatch(JSON.stringify(snapshot), /exact-credential|must never reach the view/);
|
||||
}
|
||||
});
|
||||
|
||||
test("public global status exposes only allowlisted pause reasons and resolution job errors", async t => {
|
||||
const config = await temporaryConfig(t);
|
||||
for (const reason of ["resolution", "authentication", "<script>private reason</script>", undefined]) {
|
||||
const database = { collection(name) {
|
||||
if (name === "settings") return { findOne: async (_filter, { projection }) => {
|
||||
assert.deepEqual(projection, { captcha_blocked: 1, pause_reason: 1 });
|
||||
return { captcha_blocked: true, pause_reason: reason, token: "private-settings-token" };
|
||||
} };
|
||||
return { find() { return { sort() { return this; }, async toArray() { return []; } }; } };
|
||||
} };
|
||||
const controller = createQueueController({ config, getDb: async () => database });
|
||||
for (const method of ["statusData", "status"]) {
|
||||
const result = response();
|
||||
await controller[method]({}, result, error => { throw error; });
|
||||
assert.deepEqual(result.data.global, {
|
||||
captcha_blocked: true,
|
||||
pause_reason: ["resolution", "authentication"].includes(reason) ? reason : null,
|
||||
});
|
||||
assert.doesNotMatch(JSON.stringify(result.data), /private reason|private-settings-token/);
|
||||
}
|
||||
}
|
||||
const job = toPublicJob({ _id: "fixture", filename: "Episode", error_category: "resolution", token: "hidden" });
|
||||
assert.equal(job.error_category, "resolution");
|
||||
assert.equal(Object.hasOwn(job, "token"), false);
|
||||
});
|
||||
|
||||
test("resume clears both the existing global pause flag and its reason before redirecting", async () => {
|
||||
const operations = [];
|
||||
const controller = createQueueController({ getDb: async () => ({ collection(name) {
|
||||
assert.equal(name, "settings");
|
||||
return { updateOne: async (...args) => { operations.push(args); } };
|
||||
} }) });
|
||||
const result = response();
|
||||
await controller.clearCaptcha({}, result, error => { throw error; });
|
||||
assert.deepEqual(operations, [[
|
||||
{ _id: "global" }, { $set: { captcha_blocked: false }, $unset: { pause_reason: "" } },
|
||||
]]);
|
||||
assert.equal(result.location, "/status");
|
||||
});
|
||||
|
||||
test("verification banner distinguishes resolution failures without claiming a confirmed CAPTCHA", async () => {
|
||||
const header = path.join(repository, "views/partials/header.ejs");
|
||||
const rendered = await ejs.renderFile(header, { global: { captcha_blocked: true, pause_reason: "resolution" } });
|
||||
const message = rendered.match(/<span id="captcha-message">([\s\S]*?)<\/span>/)[1];
|
||||
assert.match(message, /video link could not be resolved/);
|
||||
assert.match(message, /Possible causes include CAPTCHA or login verification, an unavailable video, or a source change/);
|
||||
assert.match(rendered, /Resume after verification/);
|
||||
assert.doesNotMatch(message, /CAPTCHA triggered|CAPTCHA confirmed/);
|
||||
|
||||
const script = [...rendered.matchAll(/<script>([\s\S]*?)<\/script>/g)][0][1];
|
||||
const elements = { "captcha-alert": { style: {} }, "captcha-message": { textContent: "" } };
|
||||
let globalState = { captcha_blocked: true, pause_reason: "resolution" };
|
||||
const context = {
|
||||
document: { getElementById: id => elements[id] },
|
||||
fetch: async () => ({ json: async () => ({ global: globalState }) }),
|
||||
setInterval: () => {}, console,
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(script, context);
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.equal(elements["captcha-alert"].style.display, "block");
|
||||
assert.match(elements["captcha-message"].textContent, /unavailable video/);
|
||||
globalState = { captcha_blocked: true, pause_reason: "authentication" };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.match(elements["captcha-message"].textContent, /Authentication or access needs verification/);
|
||||
globalState = { captcha_blocked: true, pause_reason: "<img onerror=evil>" };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.doesNotMatch(elements["captcha-message"].textContent, /<img|evil/);
|
||||
globalState = { captcha_blocked: false, pause_reason: null };
|
||||
await vm.runInContext("updateCaptchaAlert()", context);
|
||||
assert.equal(elements["captcha-alert"].style.display, "none");
|
||||
});
|
||||
|
||||
test("server-rendered and refreshed status escape HTML-like filenames, IDs and logs", async () => {
|
||||
const attack = '<img src=x onerror="alert(1)">';
|
||||
const job = { _id: `id" onmouseover="alert(2)`, filename: attack, url: attack, output_log: attack, created_at: "2026-01-01T00:00:00Z" };
|
||||
const rendered = await ejs.renderFile(path.join(repository, "views/status.ejs"), {
|
||||
queued: [job], processing: [job], finished: [{ ...job, finished_at: job.created_at }],
|
||||
failed: [{ ...job, failed_at: job.created_at }], global: { captcha_blocked: false },
|
||||
});
|
||||
assert.ok(!rendered.includes(attack));
|
||||
assert.match(rendered, /<img src=x onerror="alert\(1\)">/);
|
||||
assert.doesNotMatch(rendered, /action="\/clear-processing"/);
|
||||
const scripts = [...rendered.matchAll(/<script>([\s\S]*?)<\/script>/g)];
|
||||
const statusScript = scripts.find(match => match[1].includes("function refreshStatus"))[1];
|
||||
const context = {
|
||||
document: { querySelectorAll: () => [] },
|
||||
fetch: async () => ({ json: async () => ({ queued: [job], processing: [job], done: [job], failed: [job] }) }),
|
||||
setInterval: () => {}, console,
|
||||
queuedList: {}, processingList: {}, doneList: {}, failedList: {},
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(statusScript, context);
|
||||
await vm.runInContext("refreshStatus()", context);
|
||||
for (const key of ["queuedList", "processingList", "doneList", "failedList"]) {
|
||||
assert.ok(!context[key].innerHTML.includes(attack));
|
||||
assert.match(context[key].innerHTML, /<img/);
|
||||
assert.doesNotMatch(context[key].innerHTML, /data-id="[^\n]*" onmouseover=/);
|
||||
}
|
||||
});
|
||||
|
||||
test("error view renders without a details local and never exposes a supplied stack", async () => {
|
||||
for (const data of [{ message: "A safe error" }, { message: "A safe error", details: "PRIVATE STACK" }]) {
|
||||
const rendered = await ejs.renderFile(path.join(repository, "views/error.ejs"), data);
|
||||
assert.match(rendered, /A safe error/);
|
||||
assert.doesNotMatch(rendered, /PRIVATE STACK/);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,586 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const { PassThrough } = require('node:stream');
|
||||
const fs = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { executeJob, processClaimedJob, claimNextJob, RESULT_PREFIX } = require('../queue_worker');
|
||||
const { LOG_LIMIT } = require('../lib/logging');
|
||||
|
||||
const now = new Date('2026-01-01T12:00:00.000Z');
|
||||
const successfulResult = `${RESULT_PREFIX}${JSON.stringify({ version: 1, status: 'completed' })}\n`;
|
||||
const makeJob = (changes = {}) => ({
|
||||
_id: 'fixture-job', filename: 'Fixture Episode', url: 'https://proxer.me/watch/42/1/engsub',
|
||||
token: 'fixture_cookie=fixture-secret==', created_at: now, processing: true, ...changes,
|
||||
});
|
||||
|
||||
async function temporarySettings(t) {
|
||||
const outputDir = await fs.mkdtemp(path.join(os.tmpdir(), 'proxer-worker-'));
|
||||
t.after(() => fs.rm(outputDir, { recursive: true, force: true }));
|
||||
return {
|
||||
outputDir, pythonPath: '/fixture/python', videoScript: '/fixture/proxer-dl-video.py',
|
||||
projectRoot: '/fixture/project',
|
||||
};
|
||||
}
|
||||
|
||||
function fakeSpawner({ run, synchronousError } = {}) {
|
||||
const calls = [];
|
||||
const backgroundErrors = [];
|
||||
function spawnFn(executable, args, options) {
|
||||
calls.push({ executable, args, options });
|
||||
if (synchronousError) throw synchronousError;
|
||||
const child = new EventEmitter();
|
||||
child.stdin = new PassThrough();
|
||||
child.stdout = new PassThrough();
|
||||
child.stderr = new PassThrough();
|
||||
child.input = '';
|
||||
child.stdin.on('data', chunk => { child.input += chunk.toString('utf8'); });
|
||||
calls.at(-1).child = child;
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await run(child);
|
||||
} catch (error) {
|
||||
backgroundErrors.push(error);
|
||||
child.emit('error', error);
|
||||
}
|
||||
});
|
||||
return child;
|
||||
}
|
||||
return { spawnFn, calls, backgroundErrors };
|
||||
}
|
||||
|
||||
async function executeFixture(t, {
|
||||
job = makeJob(), stdout = successfulResult, stderr = '', exitCode = 0, signal = null,
|
||||
output = 'synthetic video bytes', beforeClose, synchronousError,
|
||||
} = {}) {
|
||||
const settings = await temporarySettings(t);
|
||||
const destination = path.join(settings.outputDir, `${job.filename}.mp4`);
|
||||
const callbacks = [];
|
||||
const spawner = fakeSpawner({ synchronousError, run: async child => {
|
||||
if (output !== null) await fs.writeFile(destination, output);
|
||||
for (const chunk of Array.isArray(stdout) ? stdout : [stdout]) child.stdout.write(chunk);
|
||||
if (stderr) child.stderr.write(stderr);
|
||||
if (beforeClose) await beforeClose({ child, settings, destination });
|
||||
child.emit('close', exitCode, signal);
|
||||
} });
|
||||
const result = await executeJob(job, {
|
||||
settings, spawnFn: spawner.spawnFn, onChild: child => callbacks.push(child),
|
||||
});
|
||||
assert.deepEqual(spawner.backgroundErrors, [], 'fake child setup must not fail');
|
||||
return { result, settings, destination, callbacks, ...spawner };
|
||||
}
|
||||
|
||||
test('successful execution requires exit zero, one completed result, and a nonempty file', async t => {
|
||||
const run = await executeFixture(t);
|
||||
assert.equal(run.result.ok, true);
|
||||
assert.equal(run.result.exitCode, 0);
|
||||
assert.equal(run.calls.length, 1);
|
||||
assert.deepEqual(run.callbacks, [run.calls[0].child, null]);
|
||||
assert.equal(await fs.readFile(run.destination, 'utf8'), 'synthetic video bytes');
|
||||
});
|
||||
|
||||
test('worker sends credentials through stdin, enables bytecode protection, and uses configured paths', async t => {
|
||||
const job = makeJob({ url: 'https://www.proxer.me:443/watch/42/1/engsub/#player' });
|
||||
const run = await executeFixture(t, { job });
|
||||
const invocation = run.calls[0];
|
||||
assert.equal(invocation.executable, run.settings.pythonPath);
|
||||
assert.deepEqual(invocation.args, [
|
||||
'-B', run.settings.videoScript, '-u', 'https://proxer.me/watch/42/1/engsub',
|
||||
`--filename=${job.filename}`, '--token-stdin', `--output=${run.settings.outputDir}`,
|
||||
]);
|
||||
assert.ok(!invocation.args.join(' ').includes(job.token));
|
||||
assert.ok(!invocation.args.join(' ').includes('fixture-secret'));
|
||||
assert.equal(invocation.child.input, job.token + '\n');
|
||||
assert.equal(invocation.options.cwd, run.settings.projectRoot);
|
||||
assert.equal(invocation.options.env.PYTHONDONTWRITEBYTECODE, '1');
|
||||
assert.equal(invocation.options.env.PYTHONUNBUFFERED, '1');
|
||||
assert.deepEqual(invocation.options.stdio, ['pipe', 'pipe', 'pipe']);
|
||||
});
|
||||
|
||||
test('a nonzero exit cannot become success even with a completed result and output file', async t => {
|
||||
const { result } = await executeFixture(t, { exitCode: 1 });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.exitCode, 1);
|
||||
assert.equal(result.errorCategory, 'unknown');
|
||||
});
|
||||
|
||||
test('missing, failed, duplicate, malformed and unsupported results cannot become success', async t => {
|
||||
const cases = [
|
||||
['missing', 'ordinary progress output\n'],
|
||||
['failed', `${RESULT_PREFIX}{"version":1,"status":"failed","errorCategory":"network"}\n`],
|
||||
['duplicate', successfulResult + successfulResult],
|
||||
['malformed', `${RESULT_PREFIX}{not json}\n`],
|
||||
['unsupported version', `${RESULT_PREFIX}{"version":2,"status":"completed"}\n`],
|
||||
['unsupported state', `${RESULT_PREFIX}{"version":1,"status":"unknown"}\n`],
|
||||
['malformed duplicate', successfulResult + `${RESULT_PREFIX}{not json}\n`],
|
||||
];
|
||||
for (const [label, stdout] of cases) {
|
||||
const { result } = await executeFixture(t, { stdout });
|
||||
assert.equal(result.ok, false, label);
|
||||
}
|
||||
});
|
||||
|
||||
test('oversized result records invalidate a preceding completed result', async t => {
|
||||
const stdout = successfulResult + RESULT_PREFIX + JSON.stringify({
|
||||
version: 1, status: 'failed', message: 'x'.repeat(9000),
|
||||
}) + '\n';
|
||||
const { result } = await executeFixture(t, { stdout });
|
||||
assert.equal(result.ok, false);
|
||||
});
|
||||
|
||||
test('a completed result on stderr is only a log and does not count as successful execution', async t => {
|
||||
const { result } = await executeFixture(t, { stdout: '', stderr: successfulResult });
|
||||
assert.equal(result.ok, false);
|
||||
});
|
||||
|
||||
test('structured failure category is used without treating arbitrary log keywords as authentication', async t => {
|
||||
const failed = `${RESULT_PREFIX}{"version":1,"status":"failed","errorCategory":"network"}\n`;
|
||||
const { result } = await executeFixture(t, {
|
||||
stdout: 'Filename contains token 403 blocked captcha\n' + failed, exitCode: 1,
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'network');
|
||||
const authentication = await executeFixture(t, {
|
||||
stdout: `${RESULT_PREFIX}{"version":1,"status":"failed","errorCategory":"authentication"}\n`, exitCode: 1,
|
||||
});
|
||||
assert.equal(authentication.result.errorCategory, 'authentication');
|
||||
});
|
||||
|
||||
test('an unresolved-link result retains its resolution category', async t => {
|
||||
const { result } = await executeFixture(t, {
|
||||
stdout: `${RESULT_PREFIX}{"version":1,"status":"failed","errorCategory":"resolution"}\n`,
|
||||
exitCode: 1, output: null,
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'resolution');
|
||||
assert.equal(result.infrastructureFailure, false);
|
||||
});
|
||||
|
||||
test('missing, empty and symlink output files are rejected after otherwise successful child exit', async t => {
|
||||
for (const output of [null, '']) {
|
||||
const { result } = await executeFixture(t, { output });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'storage');
|
||||
assert.equal(result.infrastructureFailure, true);
|
||||
}
|
||||
const symlink = await executeFixture(t, { output: null, beforeClose: async ({ settings, destination }) => {
|
||||
const target = path.join(settings.outputDir, 'another-file.mp4');
|
||||
await fs.writeFile(target, 'synthetic bytes');
|
||||
await fs.symlink(target, destination);
|
||||
} });
|
||||
assert.equal(symlink.result.ok, false);
|
||||
assert.equal(symlink.result.errorCategory, 'storage');
|
||||
assert.equal(symlink.result.infrastructureFailure, true);
|
||||
});
|
||||
|
||||
test('a synchronous spawn exception is reported as a start failure', async t => {
|
||||
const { result } = await executeFixture(t, { synchronousError: new Error('fixture spawn failure') });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'spawn');
|
||||
assert.equal(result.infrastructureFailure, true);
|
||||
assert.equal(result.exitCode, null);
|
||||
});
|
||||
|
||||
test('an asynchronous child error settles once and is reported as a start failure', async t => {
|
||||
const settings = await temporarySettings(t);
|
||||
const callbacks = [];
|
||||
const spawner = fakeSpawner({ run: async child => {
|
||||
child.emit('error', Object.assign(new Error('fixture missing executable'), { code: 'ENOENT' }));
|
||||
child.emit('close', 0, null);
|
||||
} });
|
||||
const result = await executeJob(makeJob(), {
|
||||
settings, spawnFn: spawner.spawnFn, onChild: child => callbacks.push(child),
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'spawn');
|
||||
assert.equal(result.infrastructureFailure, true);
|
||||
assert.deepEqual(callbacks, [spawner.calls[0].child, null]);
|
||||
});
|
||||
|
||||
test('an error from a live child cannot complete execution or release its claim before close', async t => {
|
||||
const settings = await temporarySettings(t);
|
||||
const { db, operations } = recordingDatabase();
|
||||
const callbacks = [];
|
||||
let signalError, allowClose;
|
||||
const errorObserved = new Promise(resolve => { signalError = resolve; });
|
||||
const closeAllowed = new Promise(resolve => { allowClose = resolve; });
|
||||
const spawner = fakeSpawner({ run: async child => {
|
||||
child.pid = 12345;
|
||||
child.emit('spawn');
|
||||
child.emit('error', Object.assign(new Error('fixture kill denied'), { code: 'EPERM' }));
|
||||
signalError();
|
||||
await closeAllowed;
|
||||
child.emit('close', null, 'SIGTERM');
|
||||
} });
|
||||
let settled = false;
|
||||
const outcome = processClaimedJob(makeJob(), { db,
|
||||
execute: job => executeJob(job, { settings, spawnFn: spawner.spawnFn, onChild: child => callbacks.push(child) }),
|
||||
}).then(result => { settled = true; return { result }; }, error => { settled = true; return { error }; });
|
||||
await errorObserved;
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
try {
|
||||
assert.equal(settled, false);
|
||||
assert.deepEqual(operations, []);
|
||||
assert.deepEqual(callbacks, [spawner.calls[0].child]);
|
||||
} finally {
|
||||
allowClose();
|
||||
}
|
||||
const completed = await outcome;
|
||||
assert.match(completed.error.message, /infrastructure is unavailable.*remains queued/);
|
||||
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['queue.updateOne']);
|
||||
assert.deepEqual(callbacks, [spawner.calls[0].child, null]);
|
||||
});
|
||||
|
||||
test('signal termination cannot become success', async t => {
|
||||
const { result } = await executeFixture(t, { exitCode: null, signal: 'SIGTERM' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.exitCode, null);
|
||||
});
|
||||
|
||||
test('a stop requested during asynchronous output validation prevents spawning', async t => {
|
||||
const settings = await temporarySettings(t);
|
||||
let stopping = false;
|
||||
let spawns = 0;
|
||||
const execution = executeJob(makeJob(), {
|
||||
settings, shouldStop: () => stopping,
|
||||
spawnFn: () => { spawns += 1; throw new Error('must not spawn after stop'); },
|
||||
});
|
||||
// executeJob has reached its asynchronous path validation before the stop arrives.
|
||||
stopping = true;
|
||||
const result = await execution;
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'interrupted');
|
||||
assert.equal(spawns, 0);
|
||||
});
|
||||
|
||||
test('the final pause gate releases a never-started claim without history or deletion', async t => {
|
||||
const settings = await temporarySettings(t);
|
||||
const { db, operations } = recordingDatabase();
|
||||
let spawns = 0;
|
||||
const result = await processClaimedJob(makeJob(), { db,
|
||||
execute: job => executeJob(job, {
|
||||
settings, canStart: async () => false,
|
||||
spawnFn: () => { spawns += 1; throw new Error('must not start while paused'); },
|
||||
}),
|
||||
});
|
||||
assert.equal(result.errorCategory, 'paused');
|
||||
assert.equal(spawns, 0);
|
||||
assert.deepEqual(operations, [{ collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: 'fixture-job', processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
}]);
|
||||
});
|
||||
|
||||
test('a failed final pause read holds the claim and starts no subprocess', async t => {
|
||||
const settings = await temporarySettings(t);
|
||||
const { db, operations } = recordingDatabase();
|
||||
let spawns = 0;
|
||||
await assert.rejects(processClaimedJob(makeJob(), { db,
|
||||
execute: job => executeJob(job, {
|
||||
settings, canStart: async () => { throw new Error('synthetic pause read failure'); },
|
||||
spawnFn: () => { spawns += 1; throw new Error('must not start without pause state'); },
|
||||
}),
|
||||
}), /synthetic pause read failure/);
|
||||
assert.equal(spawns, 0);
|
||||
assert.deepEqual(operations, []);
|
||||
});
|
||||
|
||||
test('a terminated transfer during worker shutdown is interrupted rather than a failed download', async t => {
|
||||
const settings = await temporarySettings(t);
|
||||
let stopping = false;
|
||||
const spawner = fakeSpawner({ run: async child => {
|
||||
stopping = true;
|
||||
child.emit('close', null, 'SIGTERM');
|
||||
} });
|
||||
const result = await executeJob(makeJob(), {
|
||||
settings, spawnFn: spawner.spawnFn, shouldStop: () => stopping,
|
||||
});
|
||||
assert.equal(spawner.calls.length, 1);
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'interrupted');
|
||||
assert.equal(result.infrastructureFailure, undefined);
|
||||
});
|
||||
|
||||
test('a missing output directory is an infrastructure failure and does not spawn', async t => {
|
||||
const settings = await temporarySettings(t);
|
||||
settings.outputDir = path.join(settings.outputDir, 'missing-mount');
|
||||
let spawns = 0;
|
||||
const result = await executeJob(makeJob(), {
|
||||
settings, spawnFn: () => { spawns += 1; throw new Error('must not spawn without storage'); },
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'storage');
|
||||
assert.equal(result.infrastructureFailure, true);
|
||||
assert.equal(spawns, 0);
|
||||
});
|
||||
|
||||
test('configuration and storage failure markers identify unavailable worker infrastructure', async t => {
|
||||
for (const errorCategory of ['configuration', 'storage']) {
|
||||
const { result } = await executeFixture(t, {
|
||||
exitCode: 1,
|
||||
stdout: `${RESULT_PREFIX}${JSON.stringify({ version: 1, status: 'failed', errorCategory })}\n`,
|
||||
output: null,
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, errorCategory);
|
||||
assert.equal(result.infrastructureFailure, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('split output chunks preserve the result and redact complete secrets before bounding the log tail', async t => {
|
||||
const job = makeJob();
|
||||
const resultBytes = Buffer.from(successfulResult);
|
||||
const stdout = [
|
||||
('x'.repeat(1024) + '\n').repeat(48),
|
||||
'credential fixture_', 'cookie=fixture-', 'secret==\n',
|
||||
'https://media.example/file.mp4?sign', 'ature=hidden-signature\n',
|
||||
resultBytes.subarray(0, 7), resultBytes.subarray(7, 18), resultBytes.subarray(18),
|
||||
];
|
||||
const { result } = await executeFixture(t, { job, stdout });
|
||||
assert.equal(result.ok, true);
|
||||
assert.doesNotMatch(result.output, /fixture-secret|fixture_cookie|hidden-signature/);
|
||||
assert.ok(result.output.length <= LOG_LIMIT + 100);
|
||||
assert.match(result.output, /earlier log output omitted/);
|
||||
});
|
||||
|
||||
test('oversized raw tails cannot expose partial credentials after later URL redactions shrink logs', async t => {
|
||||
const job = makeJob({ token: 'fixture_cookie=private-prefix-' + 'Q'.repeat(4000) + '-KEEP_PRIVATE' });
|
||||
// Previously the raw 32 KiB tail began inside this cookie. Redacting the later
|
||||
// long URLs then exposed the unmatched cookie suffix in the final short log.
|
||||
const payload = 'x'.repeat(9000) + job.token + '\n'
|
||||
+ ('https://media.example/' + 'u'.repeat(6000) + '?signature=fixture\n').repeat(5);
|
||||
for (const channel of ['stdout', 'stderr']) {
|
||||
const options = channel === 'stdout'
|
||||
? { stdout: [payload.slice(0, LOG_LIMIT), payload.slice(LOG_LIMIT), successfulResult] }
|
||||
: { stdout: successfulResult, stderr: payload };
|
||||
const { result } = await executeFixture(t, { job, ...options });
|
||||
assert.equal(result.ok, true, channel);
|
||||
assert.doesNotMatch(result.output, /KEEP_PRIVATE|Q{32}|fixture_cookie|signature=fixture/, channel);
|
||||
assert.match(result.output, /oversized log line omitted/, channel);
|
||||
assert.ok(result.output.length <= LOG_LIMIT + 100, channel);
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid queued input and unsafe existing targets are rejected before spawning a child', async t => {
|
||||
const settings = await temporarySettings(t);
|
||||
let spawns = 0;
|
||||
const spawnFn = () => { spawns += 1; throw new Error('must not spawn'); };
|
||||
for (const change of [
|
||||
{ url: 'https://example.test/video' }, { filename: '../escape' },
|
||||
{ token: 'missing-separator' }, { token: 'session=' }, { token: 'session=bad;cookie=other' },
|
||||
]) {
|
||||
const result = await executeJob(makeJob(change), { settings, spawnFn });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'validation');
|
||||
}
|
||||
await fs.symlink(path.join(settings.outputDir, 'missing-target'), path.join(settings.outputDir, 'Fixture Episode.mp4'));
|
||||
const linked = await executeJob(makeJob(), { settings, spawnFn });
|
||||
assert.equal(linked.errorCategory, 'validation');
|
||||
assert.equal(spawns, 0);
|
||||
});
|
||||
|
||||
function recordingDatabase(failureAt) {
|
||||
const operations = [];
|
||||
const db = { collection(name) {
|
||||
return Object.fromEntries(['insertOne', 'deleteOne', 'updateOne'].map(method => [method, async (...args) => {
|
||||
operations.push({ collection: name, method, args });
|
||||
if (`${name}.${method}` === failureAt) throw new Error('synthetic persistence failure');
|
||||
return { acknowledged: true, deletedCount: 1, modifiedCount: 1 };
|
||||
}]));
|
||||
} };
|
||||
return { db, operations };
|
||||
}
|
||||
|
||||
test('successful claimed jobs persist history before deleting only their held queue record', async () => {
|
||||
const { db, operations } = recordingDatabase();
|
||||
const job = makeJob();
|
||||
let suppliedJob;
|
||||
const result = await processClaimedJob(job, { db, now: () => now, execute: async candidate => {
|
||||
suppliedJob = candidate;
|
||||
return { ok: true, exitCode: 0, output: 'Completed; credential fixture-secret==' };
|
||||
} });
|
||||
assert.equal(suppliedJob, job);
|
||||
assert.equal(result.ok, true);
|
||||
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['done.insertOne', 'queue.deleteOne']);
|
||||
const history = operations[0].args[0];
|
||||
assert.equal(history.job_id, job._id);
|
||||
assert.equal(history.finished_at, now);
|
||||
assert.equal(history.token, undefined);
|
||||
assert.doesNotMatch(history.output_log, /fixture-secret/);
|
||||
assert.deepEqual(operations[1].args, [{ _id: job._id, processing: true }]);
|
||||
});
|
||||
|
||||
test('history persistence failure leaves the claimed job held', async () => {
|
||||
for (const success of [true, false]) {
|
||||
const collection = success ? 'done' : 'failed';
|
||||
const { db, operations } = recordingDatabase(`${collection}.insertOne`);
|
||||
await assert.rejects(processClaimedJob(makeJob(), {
|
||||
db, execute: async () => ({ ok: success, exitCode: success ? 0 : 1, errorCategory: 'network', output: 'fixture' }),
|
||||
}), /synthetic persistence failure/);
|
||||
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), [`${collection}.insertOne`]);
|
||||
}
|
||||
});
|
||||
|
||||
test('ordinary failures move to failed history without globally blocking other jobs', async () => {
|
||||
const { db, operations } = recordingDatabase();
|
||||
await processClaimedJob(makeJob(), { db, now: () => now, execute: async () => ({
|
||||
ok: false, exitCode: 1, errorCategory: 'network', output: 'Network failed',
|
||||
}) });
|
||||
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['failed.insertOne', 'queue.deleteOne']);
|
||||
assert.equal(operations[0].args[0].error_category, 'network');
|
||||
assert.equal(operations[0].args[0].failed_at, now);
|
||||
assert.equal(operations[0].args[0].exit_code, 1);
|
||||
});
|
||||
|
||||
test('authentication and resolution pause the pool before history and preserve the queued request', async () => {
|
||||
for (const errorCategory of ['authentication', 'resolution']) {
|
||||
const { db, operations } = recordingDatabase();
|
||||
const job = makeJob();
|
||||
await processClaimedJob(job, { db, execute: async () => ({
|
||||
ok: false, exitCode: 1, errorCategory, output: 'Source needs verification fixture-secret==',
|
||||
}) });
|
||||
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), [
|
||||
'settings.updateOne', 'failed.insertOne', 'queue.updateOne',
|
||||
]);
|
||||
assert.deepEqual(operations[0].args, [
|
||||
{ _id: 'global' }, { $set: { captcha_blocked: true, pause_reason: errorCategory } }, { upsert: true },
|
||||
]);
|
||||
assert.equal(operations[1].args[0].error_category, errorCategory);
|
||||
assert.doesNotMatch(operations[1].args[0].output_log, /fixture-secret/);
|
||||
assert.equal(operations[1].args[0].token, undefined);
|
||||
assert.deepEqual(operations[2].args, [
|
||||
{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } },
|
||||
]);
|
||||
assert.equal(job.token, 'fixture_cookie=fixture-secret==');
|
||||
}
|
||||
});
|
||||
|
||||
test('failure to persist the authentication block does not release the job', async () => {
|
||||
const { db, operations } = recordingDatabase('settings.updateOne');
|
||||
await assert.rejects(processClaimedJob(makeJob(), { db, execute: async () => ({
|
||||
ok: false, exitCode: 1, errorCategory: 'authentication', output: 'Access requires attention',
|
||||
}) }), /synthetic persistence failure/);
|
||||
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['settings.updateOne']);
|
||||
});
|
||||
|
||||
test('history or claim-release failure after a resolution pause cannot delete the request', async () => {
|
||||
for (const failureAt of ['failed.insertOne', 'queue.updateOne']) {
|
||||
const { db, operations } = recordingDatabase(failureAt);
|
||||
await assert.rejects(processClaimedJob(makeJob(), { db, execute: async () => ({
|
||||
ok: false, exitCode: 1, errorCategory: 'resolution', output: 'Check the source',
|
||||
}) }), /synthetic persistence failure/);
|
||||
assert.equal(operations[0].collection, 'settings');
|
||||
assert.equal(operations[0].args[1].$set.captcha_blocked, true);
|
||||
assert.equal(operations.at(-1).collection + '.' + operations.at(-1).method, failureAt);
|
||||
assert.ok(operations.every(entry => entry.method !== 'deleteOne'));
|
||||
}
|
||||
});
|
||||
|
||||
test('unacknowledged attention writes halt without consuming the request', async () => {
|
||||
for (const unacknowledgedAt of ['settings.updateOne', 'failed.insertOne', 'queue.updateOne']) {
|
||||
const fixture = recordingDatabase();
|
||||
const db = { collection(name) {
|
||||
const original = fixture.db.collection(name);
|
||||
return Object.fromEntries(Object.entries(original).map(([method, operation]) => [method, async (...args) => {
|
||||
const result = await operation(...args);
|
||||
return name + '.' + method === unacknowledgedAt ? { acknowledged: false } : result;
|
||||
}]));
|
||||
} };
|
||||
await assert.rejects(processClaimedJob(makeJob(), { db, execute: async () => ({
|
||||
ok: false, exitCode: 1, errorCategory: 'resolution', output: 'Check the source',
|
||||
}) }), /could not be confirmed/);
|
||||
assert.equal(fixture.operations.at(-1).collection + '.' + fixture.operations.at(-1).method, unacknowledgedAt);
|
||||
assert.ok(fixture.operations.every(entry => entry.method !== 'deleteOne'));
|
||||
}
|
||||
});
|
||||
|
||||
function claimDatabase({ pauseReads = [false, false], readFailureAt = -1, afterClaim = () => {} } = {}) {
|
||||
const operations = [];
|
||||
let readCount = 0;
|
||||
const job = makeJob();
|
||||
const db = { collection(name) {
|
||||
if (name === 'settings') return { findOne: async () => {
|
||||
operations.push('pause.read');
|
||||
const current = readCount++;
|
||||
if (current === readFailureAt) throw new Error('synthetic pause read failure');
|
||||
return { captcha_blocked: pauseReads[current] ?? pauseReads.at(-1) };
|
||||
} };
|
||||
assert.equal(name, 'queue');
|
||||
return {
|
||||
findOneAndUpdate: async () => { operations.push('queue.claim'); afterClaim(); return job; },
|
||||
updateOne: async (filter, update) => {
|
||||
operations.push('queue.release');
|
||||
assert.deepEqual(filter, { _id: job._id, processing: true });
|
||||
assert.deepEqual(update, { $unset: { processing: '', started_at: '' } });
|
||||
return { acknowledged: true };
|
||||
},
|
||||
};
|
||||
} };
|
||||
return { db, operations, job };
|
||||
}
|
||||
|
||||
test('a paused pool does not claim a new job', async () => {
|
||||
const fixture = claimDatabase({ pauseReads: [true] });
|
||||
assert.equal(await claimNextJob(fixture.db), null);
|
||||
assert.deepEqual(fixture.operations, ['pause.read']);
|
||||
});
|
||||
|
||||
test('a pause arriving during claim acquisition releases only the never-started claim', async () => {
|
||||
const fixture = claimDatabase({ pauseReads: [false, true] });
|
||||
assert.equal(await claimNextJob(fixture.db), null);
|
||||
assert.deepEqual(fixture.operations, ['pause.read', 'queue.claim', 'pause.read', 'queue.release']);
|
||||
});
|
||||
|
||||
test('claim pause-read failure fails closed and leaves an acquired claim held', async () => {
|
||||
for (const readFailureAt of [0, 1]) {
|
||||
const fixture = claimDatabase({ readFailureAt });
|
||||
await assert.rejects(claimNextJob(fixture.db), /synthetic pause read failure/);
|
||||
assert.ok(!fixture.operations.includes('queue.release'));
|
||||
assert.equal(fixture.operations.includes('queue.claim'), readFailureAt === 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('a stop during claim acquisition releases it, while an open pool admits the job', async () => {
|
||||
let stopping = false;
|
||||
const stopped = claimDatabase({ afterClaim: () => { stopping = true; } });
|
||||
assert.equal(await claimNextJob(stopped.db, { shouldStop: () => stopping }), null);
|
||||
assert.equal(stopped.operations.at(-1), 'queue.release');
|
||||
const open = claimDatabase();
|
||||
assert.equal(await claimNextJob(open.db), open.job);
|
||||
assert.deepEqual(open.operations, ['pause.read', 'queue.claim', 'pause.read']);
|
||||
});
|
||||
|
||||
test('processClaimedJob uses its default executor when no execute override is supplied', async () => {
|
||||
const { db, operations } = recordingDatabase();
|
||||
const result = await processClaimedJob(makeJob({ url: 'invalid-source' }), { db });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.errorCategory, 'validation');
|
||||
assert.deepEqual(operations.map(entry => `${entry.collection}.${entry.method}`), ['failed.insertOne', 'queue.deleteOne']);
|
||||
});
|
||||
|
||||
test('interrupted jobs release only their own claim without creating history or blocking the pool', async () => {
|
||||
const { db, operations } = recordingDatabase();
|
||||
const job = makeJob();
|
||||
const result = await processClaimedJob(job, { db, execute: async () => ({
|
||||
ok: false, exitCode: null, errorCategory: 'interrupted', output: 'Worker is stopping',
|
||||
}) });
|
||||
assert.equal(result.errorCategory, 'interrupted');
|
||||
assert.deepEqual(operations, [{
|
||||
collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
}]);
|
||||
});
|
||||
|
||||
test('infrastructure failures preserve the request, release its claim, and reject to halt the worker', async () => {
|
||||
for (const errorCategory of ['spawn', 'storage', 'configuration']) {
|
||||
const { db, operations } = recordingDatabase();
|
||||
const job = makeJob();
|
||||
await assert.rejects(processClaimedJob(job, { db, execute: async () => ({
|
||||
ok: false, exitCode: null, errorCategory, infrastructureFailure: true, output: 'Unavailable',
|
||||
}) }), /infrastructure is unavailable.*remains queued/);
|
||||
assert.deepEqual(operations, [{
|
||||
collection: 'queue', method: 'updateOne',
|
||||
args: [{ _id: job._id, processing: true }, { $unset: { processing: '', started_at: '' } }],
|
||||
}]);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user