Files
SnapOtter/tests/unit/security/dockerfile-build-args.test.ts
T
SnapOtterandGitHub 60d01ab2dd fix: release-acceptance QA follow-ups (upload crash, scipy ABI conflict, rate limit, OCR fallback) (#458)
* fix(api): prevent a crash when an over-limit upload stream has no consumer yet

busboy's "limit" handler destroyed the file stream with an error but never
attached its own error listener, relying entirely on whatever consumes
part.file downstream to do so. On a fast enough connection (or a fully
buffered body, e.g. Fastify inject()), busboy can process enough bytes to
hit the size limit before the route handler's receiveUpload() call has
attached its own stream listener, leaving the resulting "error" event with
zero listeners -- which crashes the whole process by default in Node.

Surfaced by tonight's FULL_MATRIX+FUZZ integration run (880 uncaught
exceptions, all the same root cause). Reproduces deterministically in
isolation; unrelated to this release's actual code delta (file untouched
since PR #413, well before the baseline QA pass).

Fix: attach a baseline no-op error listener the moment the stream is
created, guaranteeing at least one listener always exists. EventEmitter
delivers "error" to every registered listener, so the real consumer's own
error handling is unaffected.

* fix(ai-bundles): rebuild upscale-enhance and photo-restoration to reconcile scipy ABI

upscale-enhance and photo-restoration both depend on codeformer-pip, whose
transitive closure (basicsr -> realesrgan -> gfpgan) pulls in an unpinned
scipy. Both bundles were last built ~June 18-19, before PR #437 added the
manifest's `constraints` array (numpy==1.26.4, scipy==1.12.0, etc.) to pin
exactly this kind of dependency during bundle builds. Only the ocr bundle
was rebuilt after that fix landed.

install_feature.py has no pip install step -- it's a raw tarfile extraction
with no cross-bundle conflict resolution, so installing OCR alongside either
stale bundle left three incompatible scipy versions' files mixed in the same
site-packages directory (a compiled _rotation.*.so from one release next to
Python files expecting a different release's API), breaking the `upscale`
tool and OCR's higher-quality tiers with an ImportError.

Rebuilt both bundles for amd64-gpu and arm64-cpu from the current manifest,
verified scipy/scikit-learn/scikit-image/pandas all resolve to the pinned
versions in the tarballs themselves, then verified end-to-end on real
hardware (Mac arm64 CPU and ubuntu_gpu .248 RTX 4070): installing all
affected bundles together now yields exactly one version of each constrained
package, `upscale` produces correct output, and OCR's balanced/best tiers
correctly use PaddleOCR-GPU instead of erroring out.

Published the rebuilt tarballs to the public deepsafe/feature-bundles
HuggingFace repo and updated this manifest's sha256/sizes to match.

Also adds verify-bundle-compatibility.sh: verify-bundle.sh checks each
bundle in isolation (a fresh venv per bundle), which is exactly why this
shipped twice -- nothing ever checked that bundles built at different times
agree once layered into the one shared venv real installs use. The new
script installs every bundle for an arch into one venv and asserts each
constrained package has exactly one, correct version.

Known follow-up (not fixed here, needs separate discussion): uninstalling a
bundle only removes its downloaded model weights, never the site-packages
it added, so existing installations that already hit this bug have no clean
self-service fix via uninstall+reinstall -- they need a full AI-venv wipe.

* fix(docker): bake a real rate limit default for the all-in-one one-liner

The documented single-container `docker run` install had RATE_LIMIT_PER_MIN=0
(effectively unlimited, ~50k/min) baked in, since only docker-compose.yml
carried a hardened override. A self-hoster following the one-liner path got
no meaningful throttling anywhere, including auth-adjacent routes with no
dedicated per-route limit. Bakes a generous-but-real 1000/min default into
the Dockerfile, raises both compose files' fallback to match so the two
documented install paths converge on the same posture, and updates the Zod
schema default plus docs that quoted the old value.

* fix(api): boot log undercounted tool routes by the conversion-preset total

The "Tool routes: N active" line logged before registerConversionPresets(app)
ran, so it only ever reported the base 158 tools, 83 short of the real
241-tool total. Presets have to register after the base loop (they delegate
to each base tool's own processV2), so the fix moves the log line to after
that call and has registerConversionPresets return its count instead of
reordering the dependency.

* fix(ai): forward {info}/{warning} stderr JSON instead of dropping it

The dispatcher stderr parser only recognized {ready} and {progress,stage}
shaped JSON lines; anything else that parsed as valid JSON (like ocr.py's
GPU-to-tesseract downgrade notice, an {"info": ...} line) matched neither
branch and fell through silently, never reaching docker logs. Adds explicit
{info}/{warning} handling that forwards to console.log/console.warn, same as
the existing [prefix]-tagged non-JSON path.

* fix(api): fall back to a lower OCR tier when PaddleOCR itself is unusable

ocr.ts already retries lower quality tiers on a crashed dispatcher, but the
condition only matched crash-style messages (segfault, exited unexpectedly).
ocr.py's own ImportError/exception handlers already produce messages telling
the caller to use a lower tier (e.g. on the scipy ABI conflict class of bug),
but nothing ever acted on them, so a broken PaddleOCR hard-failed with 422
instead of degrading to Tesseract like ocr-pdf effectively does. Broadens the
retry condition to also catch PaddleOCR-engine-unusable messages.

Note: ocr-pdf's tesseract-only behavior turned out to be an unrelated,
pre-existing, deliberate design choice (PaddleOCR segfaults on rasterized PDF
pages on arm64), not a graceful-fallback mechanism to copy -- the two tools
weren't actually solving the same problem, so this fixes ocr.ts's own gap
rather than trying to mirror ocr-pdf.
2026-07-07 12:18:28 +08:00

154 lines
6.9 KiB
TypeScript

import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const here = dirname(fileURLToPath(import.meta.url));
const dockerfile = readFileSync(resolve(here, "../../../docker/Dockerfile"), "utf8");
const snapotterRun = readFileSync(
resolve(here, "../../../docker/s6/s6-rc.d/snapotter/run"),
"utf8",
);
const postgresReady = readFileSync(
resolve(here, "../../../docker/s6/s6-rc.d/postgres-ready/up"),
"utf8",
);
const composeCpu = readFileSync(resolve(here, "../../../docker/docker-compose.yml"), "utf8");
const composeGpu = readFileSync(resolve(here, "../../../docker/docker-compose-gpu.yml"), "utf8");
function stageBody(stageName: string): string {
const lines = dockerfile.split(/\r?\n/);
const start = lines.findIndex((line) =>
new RegExp(`^FROM\\s+.*\\s+AS\\s+${stageName}$`).test(line),
);
expect(start).toBeGreaterThanOrEqual(0);
const next = lines.findIndex((line, index) => index > start && /^FROM\s+/.test(line));
return lines.slice(start, next === -1 ? undefined : next).join("\n");
}
describe("Dockerfile build args", () => {
it("keeps the Pandoc version default in the production stage", () => {
const production = stageBody("production");
const argMatch = production.match(/^ARG PANDOC_VERSION=(.+)$/m);
expect(argMatch?.[1]).toMatch(/^\d+\.\d+(?:\.\d+)?$/);
expect(production.indexOf("ARG PANDOC_VERSION=")).toBeLessThan(
production.indexOf("pandoc-${PANDOC_VERSION}"),
);
});
it("keeps the amd64 CUDA base on the cu126 runtime family", () => {
const baseLine = dockerfile
.split(/\r?\n/)
.find((line) => line.includes(" AS base-linux-amd64"));
expect(baseLine).toContain("nvidia/cuda:12.6.");
expect(baseLine).toContain("cudnn-runtime-ubuntu24.04");
expect(baseLine).not.toContain("nvidia/cuda:12.9.");
});
it("avoids secret-scanner build arg names for public PostHog browser config", () => {
const dockerArgOrEnvNames = [...dockerfile.matchAll(/^(?:ARG|ENV)\s+([A-Za-z0-9_]+)/gm)].map(
(match) => match[1],
);
expect(dockerArgOrEnvNames).not.toContain("SNAPOTTER_POSTHOG_KEY");
expect(dockerfile).toContain("SNAPOTTER_POSTHOG_PROJECT_ID");
});
it("removes distro-generated snakeoil TLS material after embedded database install", () => {
const production = stageBody("production");
const installIndex = production.indexOf("postgresql-17 postgresql-client-17 redis-server");
const removeIndex = production.indexOf("/etc/ssl/private/ssl-cert-snakeoil.key");
expect(installIndex).toBeGreaterThanOrEqual(0);
expect(removeIndex).toBeGreaterThan(installIndex);
expect(production).toContain("/etc/ssl/certs/ssl-cert-snakeoil.pem");
});
it("purges build-only compiler and header packages before the final image", () => {
const production = stageBody("production");
const venvIndex = production.indexOf("python3 -m venv /opt/venv");
const purgeIndex = production.indexOf("apt-get purge -y --auto-remove");
expect(venvIndex).toBeGreaterThanOrEqual(0);
expect(purgeIndex).toBeGreaterThan(venvIndex);
expect(production.slice(purgeIndex)).toContain("python3-dev");
expect(production.slice(purgeIndex)).toContain("gcc");
expect(production.slice(purgeIndex)).toContain("g++");
expect(production.slice(purgeIndex)).toContain("libraw-dev");
expect(production.slice(purgeIndex)).toContain("libopenexr-dev");
expect(production.slice(purgeIndex)).toContain("libcurl4-openssl-dev");
expect(production.slice(purgeIndex)).toContain("libffi-dev");
expect(production.slice(purgeIndex)).toContain("libgcc-12-dev");
expect(production.slice(purgeIndex)).toContain("libwebp-dev");
expect(production.slice(purgeIndex)).toContain("dpkg-dev");
expect(production.slice(purgeIndex)).toContain("libc6-dev");
expect(production.slice(purgeIndex)).toContain("linux-libc-dev");
expect(production.slice(purgeIndex)).toContain("libpq-dev");
});
it("pins the Python venv setuptools package to the fixed CVE version", () => {
const production = stageBody("production");
expect(production).toContain('"setuptools==78.1.1"');
expect(production).toContain('"wheel==0.47.0"');
expect(production).toContain('"jaraco.context==6.1.0"');
expect(production).toContain("setuptools/_vendor/wheel-*.dist-info");
expect(production).toContain("jaraco_context-6.1.0.dist-info");
expect(production).not.toContain("pip install wheel setuptools");
});
it("does not require pnpm or a root HOME at production runtime", () => {
const production = stageBody("production");
expect(production).toContain("corepack disable pnpm");
expect(production).not.toContain('CMD ["pnpm"');
expect(production).toContain('CMD ["./node_modules/.bin/tsx"');
expect(snapotterRun).not.toContain("pnpm");
expect(snapotterRun).toContain("exec s6-setuidgid snapotter ./node_modules/.bin/tsx");
});
it("checks embedded Postgres readiness with the app database role", () => {
expect(postgresReady).toContain("pg_isready");
expect(postgresReady).toContain("-U snapotter");
expect(postgresReady).toContain("-d snapotter");
});
it("bakes a real, non-zero rate limit default for the one-liner all-in-one install", () => {
// The one-liner `docker run` path has no compose file to override this, so
// whatever ships here is what a self-hoster following the documented
// single-container install actually gets. RATE_LIMIT_PER_MIN=0 means
// "unlimited" (see apps/api/src/index.ts), which left every route
// (including auth) without meaningful throttling.
const production = stageBody("production");
const match = production.match(/^\s*RATE_LIMIT_PER_MIN=(\d+)/m);
expect(match).not.toBeNull();
const value = Number(match?.[1]);
expect(value).toBeGreaterThan(0);
// Generous on purpose (self-hosted, single-user/small-team usage
// shouldn't ever brush up against it) but a real, finite ceiling.
expect(value).toBeGreaterThanOrEqual(1000);
});
it("keeps the compose files' rate limit fallback at least as generous as the Dockerfile default", () => {
// Compose previously hardened this to 300/min while the raw one-liner
// shipped 0 (unlimited) -- a real gap between two equally-documented
// install paths' default security posture. Both should converge on the
// same non-zero floor rather than leaving the one-liner as the outlier.
const production = stageBody("production");
const dockerfileDefault = Number(production.match(/^\s*RATE_LIMIT_PER_MIN=(\d+)/m)?.[1] ?? 0);
for (const [name, compose] of [
["docker-compose.yml", composeCpu],
["docker-compose-gpu.yml", composeGpu],
] as const) {
const fallback = compose.match(/RATE_LIMIT_PER_MIN:-(\d+)/);
expect(fallback, `${name} should set a RATE_LIMIT_PER_MIN fallback`).not.toBeNull();
expect(Number(fallback?.[1])).toBeGreaterThanOrEqual(dockerfileDefault);
}
});
});