234 lines
11 KiB
Python
234 lines
11 KiB
Python
"""The lab tools' host half (tools.py): a library per caller (never a path
|
|
the caller names), a source that is a URL or one of its own uploads, the
|
|
allowlisted flags — and the run scope's ``tools`` key, which becomes the
|
|
run's AIA_TOOLS_URL / AIA_TOOLS_TOKEN."""
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import struct
|
|
|
|
import pytest
|
|
from fastapi import FastAPI, HTTPException
|
|
from fastapi.testclient import TestClient
|
|
|
|
import egress
|
|
import launch
|
|
import claude_launch
|
|
import tools
|
|
|
|
|
|
@pytest.fixture
|
|
def libs(tmp_path, monkeypatch):
|
|
owner = tmp_path / "vx"
|
|
(owner / "models").mkdir(parents=True)
|
|
monkeypatch.setattr(tools, "VX_OWNER", owner)
|
|
monkeypatch.setattr(tools, "VX_GUESTS", tmp_path / "vx-guests")
|
|
return tmp_path
|
|
|
|
|
|
def test_a_library_per_caller(libs):
|
|
assert tools.library_dir("owner") == libs / "vx"
|
|
d = tools.library_dir("guest-ana")
|
|
assert d == libs / "vx-guests" / "ana"
|
|
# the search model is the owner's, linked — not rebuilt per guest
|
|
assert (d / "models").is_symlink()
|
|
for bad in ("guest-../x", "ana", "guest-", "/etc", "guest-a/b"):
|
|
with pytest.raises(HTTPException):
|
|
tools.library_dir(bad)
|
|
|
|
|
|
def test_a_source_is_a_url_or_an_upload_of_that_library(libs, monkeypatch):
|
|
monkeypatch.setattr(egress, "resolve_public", lambda host, port: [(2, "93.184.216.34")])
|
|
assert tools._source("guest-ana", "https://youtu.be/x") == "https://youtu.be/x"
|
|
up = tools.library_dir("guest-ana") / "_uploads"
|
|
up.mkdir()
|
|
(up / "0123456789abcdef-clip.mp4").write_bytes(b"x")
|
|
assert tools._source("guest-ana", "0123456789abcdef-clip.mp4").endswith("clip.mp4")
|
|
for bad in ("/home/me/homelab/.env", "file:///etc/passwd", "../vx/v1/source.mp4",
|
|
"0123456789abcdef-missing.mp4"):
|
|
with pytest.raises(HTTPException):
|
|
tools._source("guest-ana", bad)
|
|
# another guest's upload is not this one's
|
|
with pytest.raises(HTTPException):
|
|
tools._source("guest-bo", "0123456789abcdef-clip.mp4")
|
|
|
|
|
|
def test_video_dirs_stay_inside(libs):
|
|
lib = tools.library_dir("guest-ana")
|
|
(lib / "v1-abc").mkdir()
|
|
(lib / "v1-abc" / "report.md").write_text("# v1")
|
|
assert tools.video_dir("guest-ana", "v1-abc") == lib / "v1-abc"
|
|
for bad in ("../ana", "models", "_uploads", "v1-abc/../../x", "nope"):
|
|
with pytest.raises(HTTPException):
|
|
tools.video_dir("guest-ana", bad)
|
|
|
|
|
|
def test_run_flags_are_allowlisted():
|
|
body = tools.VxJob(library="owner", source="https://x.test/v", fps=99, asr="whisper-turbo",
|
|
lang="fr", describe=False, title="a\nb", force=True)
|
|
args = tools._args(body, "https://x.test/v")
|
|
assert args[:4] == ["run", "https://x.test/v", "--on", "auto"]
|
|
assert "--fps" in args and args[args.index("--fps") + 1] == "4.0"
|
|
assert "--no-describe" in args and "--force" in args
|
|
assert args[args.index("--title") + 1] == "a b"
|
|
with pytest.raises(HTTPException):
|
|
tools._args(tools.VxJob(library="owner", source="x", asr="rm -rf"), "x")
|
|
with pytest.raises(HTTPException):
|
|
tools._args(tools.VxJob(library="owner", source="x", lang="--exec"), "x")
|
|
|
|
|
|
def test_paths_in_replies_are_made_relative(libs):
|
|
lib = tools.library_dir("guest-ana")
|
|
out = tools._relative("guest-ana", {"report": f"{lib}/v1/report.md",
|
|
"hits": [{"frame": f"{lib}/v1/frames/f1.jpg"}]})
|
|
assert out == {"report": "v1/report.md", "hits": [{"frame": "v1/frames/f1.jpg"}]}
|
|
|
|
|
|
def test_the_tools_scope_becomes_the_runs_env():
|
|
scope = {"tools": {"url": "https://claude.example.test/proxy/tools", "token": "aiat1.ana.1.x" * 2}}
|
|
assert launch.valid_scope(scope) is scope
|
|
env = claude_launch._scope_settings(scope)["env"]
|
|
assert env["AIA_TOOLS_URL"] == "https://claude.example.test/proxy/tools"
|
|
assert env["AIA_TOOLS_TOKEN"] == "aiat1.ana.1.x" * 2
|
|
for bad in ({"url": "http://plain", "token": "x" * 20}, {"url": "https://x"},
|
|
{"url": "https://x", "token": "short"}, "nope"):
|
|
with pytest.raises(HTTPException):
|
|
launch.valid_scope({"tools": bad})
|
|
|
|
|
|
# ── a guest's URL is fetched from the lab: public addresses only ─────────────
|
|
def test_a_guests_url_must_be_on_the_public_internet(libs, monkeypatch):
|
|
table = {"video.example": ["93.184.216.34"], "hub.lab.example": ["100.64.1.7"],
|
|
"both.example": ["93.184.216.34", "10.0.0.5"], "v6.example": ["fd00::1"]}
|
|
|
|
def getaddrinfo(host, port, **kw):
|
|
if host in table:
|
|
return [(2, 1, 6, "", (a, port or 0)) for a in table[host]]
|
|
return [(2, 1, 6, "", (host, port or 0))] # an IP literal resolves to itself
|
|
monkeypatch.setattr(egress.socket, "getaddrinfo", getaddrinfo)
|
|
monkeypatch.setattr(egress, "_own_addresses", lambda: (frozenset(), ()))
|
|
assert tools._source("guest-ana", "https://video.example/v.mp4")
|
|
for bad in ("http://127.0.0.1:8096/api/users", "http://localhost:8096/x",
|
|
"http://172.17.0.1:8790/health", "http://192.168.1.254/",
|
|
"http://169.254.169.254/latest", "http://100.95.133.7/", "http://[::1]:8096/",
|
|
"http://[fd00::1]/", "http://[::ffff:127.0.0.1]/", "http://0.0.0.0:8096/",
|
|
"https://hub.lab.example/x", "https://both.example/v.mp4",
|
|
"https://v6.example/v", "http://video.example\\@127.0.0.1/",
|
|
"http://127.0.0.1\\@video.example/", "http://u:p@video.example/v"):
|
|
with pytest.raises(HTTPException) as e:
|
|
tools._source("guest-ana", bad)
|
|
assert e.value.status_code == 400, bad
|
|
# the owner's library is the owner's: a lab URL is his to name
|
|
assert tools._source("owner", "http://hub.lab.example/v.mp4")
|
|
|
|
|
|
def test_this_hosts_own_addresses_and_ipv6_neighbours_are_not_public(monkeypatch):
|
|
import ipaddress
|
|
own = ipaddress.ip_address("2a01:e0a:1:2:aaaa:bbbb:cccc:dddd")
|
|
monkeypatch.setattr(egress, "_own_addresses", lambda: (
|
|
frozenset({own, ipaddress.ip_address("82.64.1.2")}),
|
|
(ipaddress.ip_network("2a01:e0a:1:2::/64"),)))
|
|
assert not egress.is_public_ip(str(own))
|
|
assert not egress.is_public_ip("2a01:e0a:1:2::1") # the router, a LAN device
|
|
assert not egress.is_public_ip("82.64.1.2")
|
|
assert egress.is_public_ip("2a01:e0a:9:9::1") and egress.is_public_ip("93.184.216.34")
|
|
assert not egress.is_public_ip("64:ff9b::7f00:1") # NAT64 of 127.0.0.1
|
|
assert not egress.is_public_ip("224.0.0.1") and not egress.is_public_ip("nonsense")
|
|
|
|
|
|
def test_a_guests_job_downloads_through_the_proxy_and_reads_no_fetch_error(libs, monkeypatch, tmp_path):
|
|
real = tmp_path / "bin" / "yt-dlp"
|
|
real.parent.mkdir()
|
|
real.write_text("#!/bin/sh\necho \"$@\"\n")
|
|
real.chmod(0o755)
|
|
monkeypatch.setenv("PATH", f"{real.parent}:/usr/bin:/bin")
|
|
monkeypatch.setattr(egress, "SHIM_DIR", str(tmp_path / "shim"))
|
|
monkeypatch.setenv("HTTPS_PROXY", "http://corp:3128")
|
|
env = tools._env("guest-ana")
|
|
assert env["PATH"].startswith(str(tmp_path / "shim") + ":")
|
|
assert env["VX_REAL_YTDLP"] == str(real) and env["VX_EGRESS_PROXY"].startswith("http://127.0.0.1:")
|
|
assert "HTTPS_PROXY" not in env
|
|
import subprocess
|
|
out = subprocess.run(["yt-dlp", "https://x.example/v"], env=env, capture_output=True, text=True)
|
|
assert out.stdout.split() == ["--proxy", env["VX_EGRESS_PROXY"], "https://x.example/v"]
|
|
# without its two variables the shim refuses rather than download directly
|
|
bare = {k: v for k, v in env.items() if not k.startswith("VX_")}
|
|
assert subprocess.run(["yt-dlp", "x"], env=bare, capture_output=True).returncode == 1
|
|
# the owner's own jobs are not proxied
|
|
assert "VX_EGRESS_PROXY" not in tools._env("owner")
|
|
# what a failed download said never reaches a guest; the owner reads it
|
|
line = "yt-dlp failed: ERROR: [generic] Unable to download webpage: HTTP Error 401: Unauthorized"
|
|
assert tools._job_error("guest-ana", line) == tools.VX_FETCH_ERROR
|
|
assert tools._job_error("owner", line) == line
|
|
lib = tools.library_dir("guest-ana")
|
|
assert tools._job_error("guest-ana", f"no audio in {lib}/v1/source.mp4") == "no audio in v1/source.mp4"
|
|
|
|
|
|
# ── 3d-render: a model is self-contained or refused ──────────────────────────
|
|
def _glb(doc: dict | str, binary: bytes = b"") -> bytes:
|
|
js = (doc if isinstance(doc, str) else json.dumps(doc)).encode()
|
|
js += b" " * (-len(js) % 4)
|
|
chunks = struct.pack("<II", len(js), 0x4E4F534A) + js
|
|
if binary:
|
|
chunks += struct.pack("<II", len(binary), 0x004E4942) + binary
|
|
return b"glTF" + struct.pack("<II", 2, 12 + len(chunks)) + chunks
|
|
|
|
|
|
_DATA = "data:application/octet-stream;base64," + base64.b64encode(b"\0" * 12).decode()
|
|
|
|
|
|
def test_a_model_naming_a_file_is_refused(tmp_path):
|
|
f = tmp_path / "model.glb"
|
|
ok = [_glb({"asset": {"version": "2.0"}, "buffers": [{"byteLength": 12}]}, b"\0" * 12),
|
|
_glb({"buffers": [{"uri": _DATA, "byteLength": 12}], "images": [{"uri": _DATA}]}),
|
|
json.dumps({"buffers": [{"uri": _DATA}]}).encode(),
|
|
b"\xef\xbb\xbf" + json.dumps({"asset": {}}).encode()]
|
|
for body in ok:
|
|
f.write_bytes(body)
|
|
tools.self_contained(f)
|
|
bad = [_glb({"images": [{"uri": "/mnt/nvme/PRIVATE/x.jpg"}]}),
|
|
_glb({"buffers": [{"uri": "/home/me/.ssh/id_ed25519", "byteLength": 400}]}),
|
|
_glb({"buffers": [{"uri": "../../.env"}]}),
|
|
_glb({"images": [{"uri": "file:///etc/passwd"}]}),
|
|
_glb({"images": [{"uri": "DATA:image/png;base64,AAAA"}]}), # the renderer is case-sensitive
|
|
_glb({"images": [{"uri": 7}]}),
|
|
_glb({"extensions": {"X": {"sources": [{"uri": "tex.png"}]}}}), # anywhere in the document
|
|
# a repeated key: whichever one a parser keeps, the model is refused
|
|
_glb('{"images": [{"uri": "/etc/passwd", "uri": "' + _DATA + '"}]}'),
|
|
_glb('{"images": [{"uri": "' + _DATA + '", "uri": "/etc/passwd"}]}'),
|
|
json.dumps({"buffers": [{"uri": "scene.bin"}]}).encode(),
|
|
b"glTF" + struct.pack("<II", 2, 20) + struct.pack("<II", 4, 0x004E4942) + b"\0" * 4,
|
|
_glb("[1, 2]"), _glb("{not json"), b"PK\x03\x04 not a model at all"]
|
|
for body in bad:
|
|
f.write_bytes(body)
|
|
with pytest.raises(HTTPException) as e:
|
|
tools.self_contained(f)
|
|
assert e.value.status_code == 422
|
|
assert "/" not in str(e.value.detail).replace("glTF/glb", "") # no path echoed
|
|
|
|
|
|
def test_render_refuses_before_running_and_scrubs_its_errors(tmp_path, monkeypatch):
|
|
ran = []
|
|
|
|
class P:
|
|
returncode, stdout = 1, ""
|
|
stderr = ""
|
|
|
|
def run(args, **kw):
|
|
ran.append(args)
|
|
P.stderr = f"error: {args[2]} has no triangle meshes"
|
|
return P()
|
|
monkeypatch.setattr(tools, "_auth", lambda a: None)
|
|
monkeypatch.setattr(tools, "IS_WORKER", False)
|
|
monkeypatch.setattr(tools.subprocess, "run", run)
|
|
app = FastAPI()
|
|
app.include_router(tools.router)
|
|
c = TestClient(app)
|
|
r = c.post("/tools/3d-render", content=_glb({"images": [{"uri": "/etc/hostname"}]}))
|
|
assert r.status_code == 422 and "self-contained" in r.json()["detail"] and not ran
|
|
r = c.post("/tools/3d-render", content=_glb({"asset": {"version": "2.0"}}))
|
|
assert r.status_code == 422 and len(ran) == 1
|
|
assert r.json()["detail"] == "error: model.glb has no triangle meshes"
|