Files
SnapOtter/packages/ai/python/offline_guard.py
T
SnapOtterandGitHub d10d0f544f fix: release QA hardening across processing, media, security, and CI gates (#649)
A release-readiness QA pass over the whole product. The commits split into
defects a user would hit and gates that were reporting green while measuring
nothing.

## Fixes that change behaviour

Rate limiting was bypassable on every install: TRUST_PROXY defaulted to true, so
request.ip came from a client-set header and a forged X-Forwarded-For got past
the login limiter. The default is now a private-network trust list.

A transient Postgres outage stranded in-flight jobs, leaving finished output on
disk with no row pointing at it. A reconciler now resolves those rows and adopts
the bytes rather than dropping the work.

A Redis connection that moved to a new address wedged every read-blocked
consumer, so completions stopped signalling while health still answered 200.
Socket timeouts plus subscriber pings recover it.

Installing more than one AI bundle left the shared venv multi-versioned and
silently broke three tools. The installer now reconciles distributions to one
version each.

Converting an image to JXL at quality 1 through 4 returned a 500, because
libjxl 0.7 rejects the distance those values compute. The quality is floored at
what the encoder honours. A missing ffmpeg was also reported to the user as a
corrupt upload; it now says the engine is unavailable.

RAW uploads reached an unpatched LibRaw on arm64, so it is built from source at
0.22.2, and the release scan was split so it can fail on an unfixed critical
instead of hiding it behind ignore-unfixed.

## Gates that could not fail

Two mutation lanes ran zero mutants because Stryker crawled the gitignored docs
build; coverage discarded its whole report on any failing test; the lint gate
skipped root tests, scripts, and two workspaces; and several generated matrices
counted a host missing ffmpeg as a passing tool. Each now measures what it
claims.

Full evidence and the outstanding release items are tracked locally and are not
part of this branch.
2026-07-27 15:37:30 +08:00

102 lines
4.3 KiB
Python

"""Gate runtime model downloads behind an explicit opt-in.
Models normally arrive through user-initiated feature bundle installs
(install_feature.py), and the resolvers in the AI scripts always prefer those
bundled files. If a model is missing, the runtime fails closed instead of
fetching mutable content. Operators may explicitly opt into public model
fallback downloads with SNAPOTTER_ALLOW_MODEL_DOWNLOAD=1.
"""
import os
def downloads_allowed():
"""Return True only when runtime downloads are explicitly enabled.
Unknown values remain fail-closed to avoid enabling network access through
a typo or an inherited environment setting.
"""
return os.environ.get("SNAPOTTER_ALLOW_MODEL_DOWNLOAD", "0").lower() in ("1", "true")
def ensure_download_allowed(what):
"""Raise a clear, actionable error when runtime downloads are disabled."""
if downloads_allowed():
return
raise RuntimeError(
f"{what} is missing and automatic downloads are disabled. Reinstall "
"the feature bundle from Settings, or explicitly set "
"SNAPOTTER_ALLOW_MODEL_DOWNLOAD=1 to permit runtime downloads."
)
def link_bundled_weight(link_path, target_path):
"""Best-effort: make link_path resolve to an installed bundle file.
gfpgan and codeformer-pip hardcode weight paths relative to the process
cwd, while the feature bundles install those weights under MODELS_PATH.
Symlinking the expected path to the bundled file lets the libraries find
the weight without downloading. Returns True when link_path exists
afterwards (already present, or successfully linked).
"""
if os.path.exists(link_path):
return True
if not os.path.exists(target_path):
return False
try:
parent = os.path.dirname(link_path)
if parent:
os.makedirs(parent, exist_ok=True)
os.symlink(target_path, link_path)
except OSError:
return os.path.exists(link_path)
return True
GFPGAN_HELPER_WEIGHTS = ("detection_Resnet50_Final.pth", "parsing_parsenet.pth")
def prepare_gfpgan_helper_weights(models_base):
"""Resolve GFPGAN's cwd-relative facexlib helper weights offline.
gfpgan 1.3.x hardcodes FaceRestoreHelper(model_rootpath="gfpgan/weights"),
a path relative to the process cwd, and facexlib downloads any file
missing from it (GitHub release URLs). The feature bundles install those
weights under <models>/gfpgan/facelib, so link them into the expected
location; when a weight cannot be resolved locally, strict offline mode
errors instead of downloading.
"""
for fname in GFPGAN_HELPER_WEIGHTS:
link = os.path.join("gfpgan", "weights", fname)
target = os.path.join(models_base, "gfpgan", "facelib", fname)
if not link_bundled_weight(link, target):
ensure_download_allowed(f"GFPGAN helper weight {fname}")
def prepare_codeformer_weights(models_base):
"""Resolve codeformer-pip's cwd-relative weights offline.
codeformer-pip 0.0.4 downloads four weights into a cwd-relative
CodeFormer/weights/ tree at import time of codeformer.app -- unconditionally,
even though this app calls inference_app with background_enhance=False and so
never uses the RealESRGAN background upsampler (RealESRGAN_x2plus.pth). All
four ship in the upscale-enhance bundle and are linked here from models_base
so the import never triggers a download; strict offline mode then works.
"""
expected = {
os.path.join("CodeFormer", "weights", "CodeFormer", "codeformer.pth"): os.path.join(
models_base, "codeformer", "codeformer.pth"
),
os.path.join("CodeFormer", "weights", "facelib", "detection_Resnet50_Final.pth"): os.path.join(
models_base, "gfpgan", "facelib", "detection_Resnet50_Final.pth"
),
os.path.join("CodeFormer", "weights", "facelib", "parsing_parsenet.pth"): os.path.join(
models_base, "gfpgan", "facelib", "parsing_parsenet.pth"
),
os.path.join("CodeFormer", "weights", "realesrgan", "RealESRGAN_x2plus.pth"): os.path.join(
models_base, "realesrgan", "RealESRGAN_x2plus.pth"
),
}
for link, target in expected.items():
if not link_bundled_weight(link, target):
ensure_download_allowed(f"CodeFormer weight {os.path.basename(link)}")