"""受限工作目录与远程输入输出字节校验。""" from __future__ import annotations import asyncio import hashlib import json import os from pathlib import PurePosixPath import stat import uuid import httpx from app.adapters.media import confined from app.domain.errors import MediaError as ProviderError from .contracts import _invalid, _int from .transport import _url from typing import TYPE_CHECKING if TYPE_CHECKING: from .client import Provider _REMOTE_INPUT_SUFFIXES = { ".json", ".png", ".jpg", ".jpeg", ".webp", ".bmp", ".wav", ".mp3", ".flac", ".m4a", ".ogg", ".aac", ".mp4", ".webm", ".mov", } _REMOTE_INPUT_LIMIT = 512 * 1024 * 1024 def _work(provider: Provider, path): work = confined(path, provider.settings, exists=False, root=provider.settings.job_work_root) if not work.is_dir(): raise _invalid("任务工作目录不可用。") return work def _asset(provider: Provider, asset_id, assets): # assets 由上游按用户权限解析;这里只接受映射内 ID,不能把输入当作路径。 if not isinstance(asset_id, str) or asset_id not in assets: raise _invalid("请选择可访问的素材。") return confined(assets[asset_id], provider.settings) async def _upload_input(provider: Provider, source): source = confined(source, provider.settings) suffix = source.suffix.lower() if suffix == ".jfif": # 参考图已按内容解码校验;JFIF使用JPEG编码,远端沿用标准.jpg名称。 # 只规范传输文件名,原素材字节、摘要和本地存储位置保持不变。 suffix = ".jpg" if suffix not in _REMOTE_INPUT_SUFFIXES: raise _invalid("模型输入文件类型不受支持。") limit = min( _REMOTE_INPUT_LIMIT, int(getattr(provider.settings, "max_upload_bytes", _REMOTE_INPUT_LIMIT)), ) try: with source.open("rb") as stream: # 同一描述符完成摘要与上传,回执必须匹配字节数、摘要和目标名。 info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_size <= 0: raise _invalid("模型输入文件为空或不可读取。") if info.st_size > limit: raise ProviderError("input_too_large", "模型输入文件超出大小限制。") digest, size = hashlib.sha256(), 0 while chunk := await asyncio.to_thread(stream.read, 1024 * 1024): size += len(chunk) if size > limit or size > info.st_size: raise ProviderError("input_too_large", "模型输入文件超出大小限制。") digest.update(chunk) if size != info.st_size: raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True) digest = digest.hexdigest() name = digest + suffix stream.seek(0) async def chunks(): count = 0 while data := await asyncio.to_thread(stream.read, 1024 * 1024): count += len(data) if count > size: raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True) yield data if count != size: raise ProviderError("invalid_asset", "模型输入文件在读取时发生变化。", True) headers = { **provider._headers(), "Content-Type": "application/octet-stream", "Content-Length": str(size), } async with asyncio.timeout( max(30, min(600, float(provider.settings.request_timeout_seconds) * 4)) ): async with provider.client.stream( "POST", _url(provider.settings.inference_base_url, "/inputs/" + name), headers=headers, content=chunks(), ) as response: if not 200 <= response.status_code < 300: raise provider._http_error(response.status_code) parts, count = [], 0 async for chunk in response.aiter_bytes(): count += len(chunk) if count > 16384: raise ValueError parts.append(chunk) receipt = json.loads(b"".join(parts)) path = receipt["path"] candidate = PurePosixPath(path) if ( not isinstance(path, str) or not path.startswith("/") or path.startswith("//") or "\\" in path or ":" in path or "\x00" in path or not candidate.is_absolute() or str(candidate) != path or any(part in {".", ".."} for part in candidate.parts) or candidate.name != name or candidate.parent.parts[-2:] != ("inputs", "llm-services") or receipt["sha256"] != digest or type(receipt["size_bytes"]) is not int or receipt["size_bytes"] != size ): raise ValueError return path except (httpx.HTTPError, asyncio.TimeoutError): raise ProviderError( "upstream_unavailable", "模型输入文件传输失败,请稍后重试。", True ) from None except OSError: raise ProviderError("invalid_asset", "模型输入文件不存在或不可读取。", True) from None except (ValueError, TypeError, KeyError, UnicodeError, RecursionError): raise ProviderError( "invalid_upstream_response", "模型服务返回了无效文件接收结果。", True ) from None async def _download_url( provider: Provider, url, destination, headers, *, payload=None, timeout=None, total_timeout=None ): target = confined(destination, provider.settings, exists=False) target.parent.mkdir(parents=True, exist_ok=True) temporary = target.with_name(target.name + ".part-" + uuid.uuid4().hex) try: async with asyncio.timeout( total_timeout if total_timeout is not None else max(30, min(600, float(provider.settings.request_timeout_seconds) * 4)) ): options = {} if timeout is None else {"timeout": timeout} async with provider.client.stream( "POST" if payload is not None else "GET", url, headers=headers, json=payload, **options, ) as response: if not 200 <= response.status_code < 300: raise provider._http_error(response.status_code) limit = int(provider.settings.max_output_bytes) declared = response.headers.get("Content-Length") if declared is not None and (not declared.isdigit() or int(declared) > limit): raise ProviderError("output_too_large", "输出文件超出大小限制。") count = 0 with temporary.open("xb") as stream: async for chunk in response.aiter_bytes(): count += len(chunk) if count > limit: raise ProviderError("output_too_large", "输出文件超出大小限制。") stream.write(chunk) if not count or (declared is not None and count != int(declared)): raise ProviderError( "invalid_upstream_response", "输出文件为空或未传输完整。", True ) os.replace(temporary, target) except (httpx.HTTPError, asyncio.TimeoutError): raise ProviderError( "upstream_unavailable", "输出文件传输失败,请稍后重试。", True ) from None except OSError: raise ProviderError("output_unavailable", "无法保存输出文件。", True) from None finally: temporary.unlink(missing_ok=True) async def download(provider: Provider, upstream_id, index, destination): _int(index, 0, 1000) await provider._download_url( _url( provider.settings.inference_base_url, "/jobs/" + provider._job_id(upstream_id) + "/outputs/" + str(index), ), destination, provider._headers(), ) def _json_file(work, name, value): target = work / name temporary = work / (name + ".part-" + uuid.uuid4().hex) try: temporary.write_text( json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2), encoding="utf-8" ) os.replace(temporary, target) finally: temporary.unlink(missing_ok=True) return target