fix(webui): upload TUI and WebUI attachments over binary HTTP (#5980)
* feat(webui): add bounded binary attachment staging * feat(webui): bridge binary HTTP bodies alongside websocket listener * fix(webui): deliver attachments over authenticated binary HTTP * fix(webui): bound incomplete upload headers and preserve staging markers * test: reflect aiohttp runtime dependency for binary uploads * fix(webui): relay binary uploads and retain rejected drafts * refactor(webui): remove obsolete attachment transport errors * refactor(websocket): own binary attachment transport * fix(websocket): allow bounded uploads over slow connections * test(webui): restore upload timeout before retry * docs(websocket): focus attachment guide on client usage
This commit is contained in:
1 parent
5be1e589f2
commit
6646f5fbee
53 files changed
+1972
-847
No files matched your search
@@ -0,0 +1,79 @@
|
||||
"""Connection-scoped upload capabilities, issued only after the WS handshake."""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from urllib.parse import unquote
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
from aiohttp import web
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
from nanobot.channels.websocket.attachment_store import AttachmentStore, AttachmentUploadError
|
||||
|
||||
UPLOAD_PATH = "/api/attachments"
|
||||
|
||||
|
||||
class AttachmentHTTP:
|
||||
def __init__(self, store: AttachmentStore) -> None:
|
||||
self.store = store
|
||||
self._owners: WeakKeyDictionary[ServerConnection, str] = WeakKeyDictionary()
|
||||
self._tokens: set[str] = set()
|
||||
|
||||
def issue(self, connection: ServerConnection) -> dict[str, str]:
|
||||
self.revoke(connection)
|
||||
token = secrets.token_urlsafe(32)
|
||||
self._owners[connection] = token
|
||||
self._tokens.add(token)
|
||||
return {"path": UPLOAD_PATH, "token": token}
|
||||
|
||||
def owner(self, connection: ServerConnection) -> str:
|
||||
return self._owners.get(connection, "")
|
||||
|
||||
def revoke(self, connection: ServerConnection) -> None:
|
||||
owner = self._owners.pop(connection, "")
|
||||
self._tokens.discard(owner)
|
||||
if owner:
|
||||
self.store.discard_owner(owner)
|
||||
|
||||
async def handle(self, request: web.BaseRequest) -> web.StreamResponse:
|
||||
# Never reflect credentials, enable CORS, accept cookies, or reuse the
|
||||
# one-shot WS handshake token. The capability is valid on one live WS.
|
||||
if request.path != UPLOAD_PATH or request.method != "POST":
|
||||
response = web.json_response({"error": "not_found"}, status=404)
|
||||
else:
|
||||
authorization = request.headers.get("Authorization", "")
|
||||
owner = authorization.removeprefix("Bearer ")
|
||||
if not authorization.startswith("Bearer ") or owner not in self._tokens:
|
||||
response = web.json_response({"error": "unauthorized"}, status=401)
|
||||
elif request.headers.get("Content-Encoding") or request.headers.get("Transfer-Encoding"):
|
||||
response = web.json_response({"error": "unsupported_framing"}, status=400)
|
||||
elif request.headers.get("Expect", "").lower() not in {"", "100-continue"}:
|
||||
response = web.json_response({"error": "unsupported_expectation"}, status=417)
|
||||
else:
|
||||
async def body():
|
||||
# Iteration starts only after metadata and quota validation.
|
||||
if request.headers.get("Expect", "").lower() == "100-continue":
|
||||
await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n")
|
||||
async for chunk in request.content.iter_chunked(64 * 1024):
|
||||
yield chunk
|
||||
|
||||
try:
|
||||
reference = await self.store.upload(
|
||||
body(), owner=owner,
|
||||
mime=request.headers.get("Content-Type", ""),
|
||||
size=request.content_length or 0,
|
||||
filename=unquote(request.headers.get("X-Attachment-Name", "")),
|
||||
)
|
||||
if owner not in self._tokens:
|
||||
self.store.discard([reference], owner=owner)
|
||||
raise AttachmentUploadError("Connection closed during upload")
|
||||
response = web.json_response({"reference": reference}, status=201)
|
||||
except TimeoutError:
|
||||
response = web.json_response({"error": "Attachment upload timed out"}, status=400)
|
||||
except (AttachmentUploadError, OSError) as exc:
|
||||
response = web.json_response({"error": str(exc)}, status=400)
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
# A POST connection cannot later switch to the GET/WS parser. Closing
|
||||
# also avoids draining an unauthenticated or rejected large body.
|
||||
response.force_close()
|
||||
return response
|
||||
@@ -0,0 +1,41 @@
|
||||
"""File, MIME and batch policy for WebSocket channel binary uploads."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttachmentIngressLimits:
|
||||
max_count: int = 4
|
||||
max_file_bytes: int = 6 * 1024 * 1024
|
||||
max_total_bytes: int = 24 * 1024 * 1024
|
||||
|
||||
|
||||
MAX_VIDEOS_PER_MESSAGE = 1
|
||||
MAX_VIDEO_BYTES = 20 * 1024 * 1024
|
||||
|
||||
# A 20 MiB upload takes about 168 seconds at 1 Mbps. Keep a finite total
|
||||
# budget with room for contention, but release stalled uploads promptly.
|
||||
UPLOAD_TIMEOUT_SECONDS = 300.0
|
||||
UPLOAD_IDLE_TIMEOUT_SECONDS = 30.0
|
||||
UPLOAD_REQUEST_TIMEOUT_SECONDS = 315.0
|
||||
|
||||
IMAGE_MIME_ALLOWED: frozenset[str] = frozenset({
|
||||
"image/png", "image/jpeg", "image/webp", "image/gif",
|
||||
})
|
||||
VIDEO_MIME_ALLOWED: frozenset[str] = frozenset({
|
||||
"video/mp4", "video/webm", "video/quicktime",
|
||||
})
|
||||
DOCUMENT_MIME_ALLOWED: frozenset[str] = frozenset({
|
||||
"application/json",
|
||||
"application/pdf",
|
||||
"application/toml",
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/x-yaml",
|
||||
"application/xhtml+xml",
|
||||
"application/xml",
|
||||
"application/yaml",
|
||||
"text/csv", "text/html", "text/markdown", "text/plain", "text/xml", "text/yaml",
|
||||
})
|
||||
UPLOAD_MIME_ALLOWED = IMAGE_MIME_ALLOWED | VIDEO_MIME_ALLOWED | DOCUMENT_MIME_ALLOWED
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Bounded staging for binary uploads, independent of WebSocket frame limits.
|
||||
|
||||
The HTTP adapter must authenticate before calling ``upload``. ``owner`` must be
|
||||
server-authenticated identity, never a client-selected ID. References are only
|
||||
transport state; callers persist the paths returned by ``resolve`` as before.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import secrets
|
||||
import time
|
||||
from collections.abc import AsyncIterable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.channels.websocket.attachment_policy import (
|
||||
DOCUMENT_MIME_ALLOWED,
|
||||
MAX_VIDEO_BYTES,
|
||||
MAX_VIDEOS_PER_MESSAGE,
|
||||
UPLOAD_IDLE_TIMEOUT_SECONDS,
|
||||
UPLOAD_MIME_ALLOWED,
|
||||
UPLOAD_TIMEOUT_SECONDS,
|
||||
VIDEO_MIME_ALLOWED,
|
||||
AttachmentIngressLimits,
|
||||
)
|
||||
from nanobot.utils.media_decode import media_destination
|
||||
|
||||
|
||||
class AttachmentUploadError(ValueError):
|
||||
"""An upload or reference failed validation without consuming the draft."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Attachment:
|
||||
owner: str
|
||||
path: Path
|
||||
mime: str
|
||||
size: int
|
||||
expires: float
|
||||
|
||||
|
||||
class AttachmentStore:
|
||||
"""Single-event-loop staging store with disk, count, and lifetime bounds.
|
||||
|
||||
A whole file's declared size is reserved before awaiting its first chunk,
|
||||
so concurrent slow uploads cannot bypass the global disk quota. ``prune``
|
||||
should also be called periodically by the owning gateway. Committed files
|
||||
leave this store and are managed by the existing session media lifecycle.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
media_dir: Path,
|
||||
*,
|
||||
limits: AttachmentIngressLimits | None = None,
|
||||
max_pending: int = 128,
|
||||
max_pending_bytes: int = 128 * 1024 * 1024,
|
||||
ttl_seconds: float = 600,
|
||||
upload_timeout: float = UPLOAD_TIMEOUT_SECONDS,
|
||||
upload_idle_timeout: float = UPLOAD_IDLE_TIMEOUT_SECONDS,
|
||||
) -> None:
|
||||
if min(max_pending, max_pending_bytes, ttl_seconds, upload_timeout, upload_idle_timeout) <= 0:
|
||||
raise ValueError("Attachment store bounds must be positive")
|
||||
self.media_dir = media_dir
|
||||
self.limits = limits or AttachmentIngressLimits()
|
||||
self.max_pending = max_pending
|
||||
self.max_pending_bytes = max_pending_bytes
|
||||
self.ttl_seconds = ttl_seconds
|
||||
self.upload_timeout = upload_timeout
|
||||
self.upload_idle_timeout = upload_idle_timeout
|
||||
self._entries: dict[str, _Attachment] = {}
|
||||
self._reserved_bytes = 0
|
||||
self._active = 0
|
||||
self._journal = media_dir / ".pending-attachments"
|
||||
|
||||
async def upload(
|
||||
self,
|
||||
chunks: AsyncIterable[bytes],
|
||||
*,
|
||||
owner: str,
|
||||
mime: str,
|
||||
size: int,
|
||||
filename: str | None = None,
|
||||
) -> str:
|
||||
"""Stream a declared-length binary body and return an opaque reference.
|
||||
|
||||
No body bytes are requested until metadata and capacity are validated.
|
||||
The adapter must disable automatic request decompression and reject
|
||||
ambiguous framing, and must not buffer the complete body beforehand.
|
||||
"""
|
||||
self.prune()
|
||||
if not owner:
|
||||
raise AttachmentUploadError("Missing authenticated owner")
|
||||
if mime not in UPLOAD_MIME_ALLOWED:
|
||||
raise AttachmentUploadError("Unsupported attachment MIME")
|
||||
limit = MAX_VIDEO_BYTES if mime in VIDEO_MIME_ALLOWED else self.limits.max_file_bytes
|
||||
if isinstance(size, bool) or not 0 < size <= limit:
|
||||
raise AttachmentUploadError("Invalid attachment size")
|
||||
if self._active + len(self._entries) >= self.max_pending:
|
||||
raise AttachmentUploadError("Too many pending attachments")
|
||||
if self._reserved_bytes + size > self.max_pending_bytes:
|
||||
raise AttachmentUploadError("Pending attachment storage is full")
|
||||
self._active += 1
|
||||
self._reserved_bytes += size
|
||||
path: Path | None = None
|
||||
stored = False
|
||||
created = False
|
||||
marker_created = False
|
||||
try:
|
||||
self.media_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = media_destination(
|
||||
self.media_dir, mime,
|
||||
filename=filename if mime in DOCUMENT_MIME_ALLOWED else None,
|
||||
)
|
||||
self._journal.mkdir(parents=True, exist_ok=True)
|
||||
(self._journal / path.name).touch(exist_ok=False)
|
||||
marker_created = True
|
||||
received = 0
|
||||
# Exclusive creation prevents accidental overwrite or symlink following.
|
||||
with path.open("xb") as output:
|
||||
created = True
|
||||
async with asyncio.timeout(self.upload_timeout):
|
||||
iterator = aiter(chunks)
|
||||
while True:
|
||||
async with asyncio.timeout(self.upload_idle_timeout):
|
||||
try:
|
||||
chunk = await anext(iterator)
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
received += len(chunk)
|
||||
if received > size:
|
||||
raise AttachmentUploadError("Attachment exceeds declared size")
|
||||
output.write(chunk)
|
||||
if received != size:
|
||||
raise AttachmentUploadError("Incomplete attachment body")
|
||||
reference = secrets.token_urlsafe(32)
|
||||
self._entries[reference] = _Attachment(
|
||||
owner, path, mime, size, time.monotonic() + self.ttl_seconds,
|
||||
)
|
||||
stored = True
|
||||
return reference
|
||||
finally:
|
||||
self._active -= 1
|
||||
if not stored:
|
||||
self._reserved_bytes -= size
|
||||
if path is not None:
|
||||
if created:
|
||||
path.unlink(missing_ok=True)
|
||||
if marker_created:
|
||||
(self._journal / path.name).unlink(missing_ok=True)
|
||||
|
||||
def resolve(self, references: list[str], *, owner: str) -> list[str]:
|
||||
"""Validate a complete batch without consuming it, allowing send retries."""
|
||||
self.prune()
|
||||
if len(references) > self.limits.max_count + MAX_VIDEOS_PER_MESSAGE:
|
||||
raise AttachmentUploadError("Too many attachments")
|
||||
if len(set(references)) != len(references):
|
||||
raise AttachmentUploadError("Duplicate attachment reference")
|
||||
entries: list[_Attachment] = []
|
||||
for reference in references:
|
||||
entry = self._entries.get(reference)
|
||||
if entry is None or not owner or entry.owner != owner:
|
||||
raise AttachmentUploadError("Invalid attachment reference")
|
||||
entries.append(entry)
|
||||
videos = sum(entry.mime in VIDEO_MIME_ALLOWED for entry in entries)
|
||||
if videos > MAX_VIDEOS_PER_MESSAGE:
|
||||
raise AttachmentUploadError("Too many attachments")
|
||||
if len(entries) - videos > self.limits.max_count:
|
||||
raise AttachmentUploadError("Too many attachments")
|
||||
if sum(e.size for e in entries if e.mime not in VIDEO_MIME_ALLOWED) > self.limits.max_total_bytes:
|
||||
raise AttachmentUploadError("Attachment total exceeds limit")
|
||||
return [str(entry.path) for entry in entries]
|
||||
|
||||
def commit(self, references: list[str], *, owner: str) -> list[str]:
|
||||
"""Transfer validated files to session ownership after message acceptance.
|
||||
|
||||
The caller must not await between resolve, synchronous acceptance, and
|
||||
commit. A rejected message must leave references staged for retry.
|
||||
"""
|
||||
paths = self.resolve(references, owner=owner)
|
||||
for reference in references:
|
||||
entry = self._entries[reference]
|
||||
(self._journal / entry.path.name).unlink(missing_ok=True)
|
||||
self._reserved_bytes -= self._entries.pop(reference).size
|
||||
return paths
|
||||
|
||||
def discard_owner(self, owner: str) -> None:
|
||||
self.discard([ref for ref, entry in self._entries.items() if entry.owner == owner], owner=owner)
|
||||
|
||||
def discard(self, references: list[str], *, owner: str) -> None:
|
||||
for reference in references:
|
||||
entry = self._entries.get(reference)
|
||||
if entry is not None and entry.owner == owner:
|
||||
entry.path.unlink(missing_ok=True)
|
||||
(self._journal / entry.path.name).unlink(missing_ok=True)
|
||||
self._reserved_bytes -= entry.size
|
||||
del self._entries[reference]
|
||||
|
||||
def prune(self) -> None:
|
||||
"""Remove abandoned uploads; never delete committed session media."""
|
||||
now = time.monotonic()
|
||||
# Crash remnants retain a marker; committed historical files never do.
|
||||
cutoff = time.time() - self.ttl_seconds - self.upload_timeout
|
||||
for marker in self._journal.glob("*"):
|
||||
if marker.is_file() and marker.stat().st_mtime < cutoff:
|
||||
(self.media_dir / marker.name).unlink(missing_ok=True)
|
||||
marker.unlink(missing_ok=True)
|
||||
for reference, entry in list(self._entries.items()):
|
||||
if entry.expires <= now:
|
||||
entry.path.unlink(missing_ok=True)
|
||||
(self._journal / entry.path.name).unlink(missing_ok=True)
|
||||
self._reserved_bytes -= entry.size
|
||||
del self._entries[reference]
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clean staging after the gateway has stopped accepting uploads."""
|
||||
if self._active:
|
||||
raise RuntimeError("Stop active uploads before clearing attachment storage")
|
||||
for reference, entry in list(self._entries.items()):
|
||||
entry.path.unlink(missing_ok=True)
|
||||
(self._journal / entry.path.name).unlink(missing_ok=True)
|
||||
self._reserved_bytes -= entry.size
|
||||
del self._entries[reference]
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Body-capable HTTP bridge for the WebSocket channel listener.
|
||||
|
||||
GET (including WebSocket upgrades) remains on websockets' existing parser and
|
||||
handshake path. Other methods go directly to aiohttp's bounded streaming HTTP
|
||||
parser on the same socket, without proxying or changing the authenticated peer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any, cast
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.web_protocol import RequestHandler
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
from nanobot.channels.websocket.attachment_policy import UPLOAD_REQUEST_TIMEOUT_SECONDS
|
||||
|
||||
_HTTP_HEADER_TIMEOUT_S = 75.0
|
||||
_HTTP_CONNECTION_TIMEOUT_S = UPLOAD_REQUEST_TIMEOUT_SECONDS
|
||||
|
||||
|
||||
class BinaryHTTPBridge:
|
||||
"""Own HTTP connections alongside a websockets ``serve`` instance.
|
||||
|
||||
Pass ``connection_factory`` as ``create_connection`` to serve/unix_serve.
|
||||
After closing the listening server, await ``shutdown`` before disposing the
|
||||
upload store. Request decompression is deliberately disabled: declared body
|
||||
lengths must measure the exact bytes the upload store writes.
|
||||
"""
|
||||
|
||||
def __init__(self, handler: Callable[[web.BaseRequest], Awaitable[web.StreamResponse]]) -> None:
|
||||
async def request_started(request: web.BaseRequest) -> web.StreamResponse:
|
||||
if request.transport is not None:
|
||||
# This bridge remains the transport protocol while delegating
|
||||
# HTTP parsing to RequestHandler on the same transport.
|
||||
connection = cast(_BridgeConnection, request.transport.get_protocol())
|
||||
connection.request_started()
|
||||
return await handler(request)
|
||||
|
||||
self.http_server = web.Server(request_started, auto_decompress=False, keepalive_timeout=5)
|
||||
self.pending_connections: set[_BridgeConnection] = set()
|
||||
|
||||
bridge = self
|
||||
|
||||
class Connection(_BridgeConnection):
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, bridge=bridge, **kwargs)
|
||||
|
||||
self.connection_factory: type[ServerConnection] = Connection
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
for connection in tuple(self.pending_connections):
|
||||
connection.transport.close()
|
||||
await self.http_server.shutdown(timeout=1)
|
||||
|
||||
|
||||
class _BridgeConnection(ServerConnection):
|
||||
def __init__(self, *args: Any, bridge: BinaryHTTPBridge, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self._bridge = bridge
|
||||
self._prefix = bytearray()
|
||||
self._http_protocol: RequestHandler | None = None
|
||||
self._selected = False
|
||||
self._prefix_timeout: asyncio.TimerHandle | None = None
|
||||
|
||||
def connection_made(self, transport: asyncio.BaseTransport) -> None:
|
||||
# Delay websockets' handshake task until we know which parser owns this
|
||||
# connection. In particular, never feed a POST to Request.parse().
|
||||
self.transport = cast(asyncio.Transport, transport)
|
||||
self._bridge.pending_connections.add(self)
|
||||
self._prefix_timeout = asyncio.get_running_loop().call_later(10, self.transport.close)
|
||||
|
||||
def data_received(self, data: bytes) -> None:
|
||||
if not self._selected:
|
||||
needed = 4 - len(self._prefix)
|
||||
self._prefix.extend(data[:needed])
|
||||
if len(self._prefix) < 4:
|
||||
return
|
||||
data = bytes(self._prefix) + data[needed:]
|
||||
self._prefix.clear()
|
||||
self._selected = True
|
||||
self._bridge.pending_connections.discard(self)
|
||||
if self._prefix_timeout is not None:
|
||||
self._prefix_timeout.cancel()
|
||||
if data.startswith(b"GET "):
|
||||
super().connection_made(self.transport)
|
||||
else:
|
||||
# Incomplete headers retain their own short deadline. A parsed
|
||||
# request receives the longer bounded upload budget below.
|
||||
self._prefix_timeout = asyncio.get_running_loop().call_later(
|
||||
_HTTP_HEADER_TIMEOUT_S, self.transport.close,
|
||||
)
|
||||
self._http_protocol = self._bridge.http_server()
|
||||
self._http_protocol.connection_made(self.transport)
|
||||
if self._http_protocol is not None:
|
||||
self._http_protocol.data_received(data)
|
||||
else:
|
||||
super().data_received(data)
|
||||
|
||||
def request_started(self) -> None:
|
||||
if self._prefix_timeout is not None:
|
||||
self._prefix_timeout.cancel()
|
||||
self._prefix_timeout = asyncio.get_running_loop().call_later(
|
||||
_HTTP_CONNECTION_TIMEOUT_S, self.transport.close,
|
||||
)
|
||||
|
||||
def eof_received(self) -> None:
|
||||
if self._http_protocol is not None:
|
||||
return self._http_protocol.eof_received()
|
||||
if self._selected:
|
||||
return super().eof_received()
|
||||
return None
|
||||
|
||||
def connection_lost(self, exc: Exception | None) -> None:
|
||||
self._bridge.pending_connections.discard(self)
|
||||
if self._prefix_timeout is not None:
|
||||
self._prefix_timeout.cancel()
|
||||
if self._http_protocol is not None:
|
||||
self._http_protocol.connection_lost(exc)
|
||||
elif self._selected:
|
||||
super().connection_lost(exc)
|
||||
|
||||
def pause_writing(self) -> None:
|
||||
if self._http_protocol is not None:
|
||||
self._http_protocol.pause_writing()
|
||||
elif self._selected:
|
||||
super().pause_writing()
|
||||
|
||||
def resume_writing(self) -> None:
|
||||
if self._http_protocol is not None:
|
||||
self._http_protocol.resume_writing()
|
||||
elif self._selected:
|
||||
super().resume_writing()
|
||||
@@ -27,6 +27,7 @@ from nanobot.bus.events import (
|
||||
)
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
||||
from nanobot.config.schema import Base
|
||||
from nanobot.session.webui_turns import (
|
||||
clear_websocket_turn_if_current,
|
||||
@@ -207,10 +208,8 @@ class WebSocketConfig(Base):
|
||||
websocket_requires_token: bool = True
|
||||
allow_from: list[str] = Field(default_factory=lambda: ["*"])
|
||||
streaming: bool = True
|
||||
# Default 36 MB, upper 40 MB: supports up to 4 images at ~6 MB each after
|
||||
# client-side Worker normalization (see webui Composer). 4 × 6 MB × 1.37
|
||||
# (base64 overhead) + envelope framing stays under 36 MB; the 40 MB ceiling
|
||||
# leaves a small margin for sender slop without opening a DoS avenue.
|
||||
# Keep the existing configurable guard (also used for non-attachment
|
||||
# frames and older clients). HTTP attachments are outside this limit.
|
||||
max_message_bytes: int = Field(default=37_748_736, ge=1024, le=41_943_040)
|
||||
ping_interval_s: float = Field(default=20.0, ge=5.0, le=300.0)
|
||||
ping_timeout_s: float = Field(default=20.0, ge=5.0, le=300.0)
|
||||
@@ -394,6 +393,7 @@ class WebSocketChannel(BaseChannel):
|
||||
|
||||
self.gateway = gateway
|
||||
self._media = gateway.media
|
||||
self._uploads = gateway.uploads
|
||||
self._transcripts = gateway.transcripts
|
||||
self._temporary_chats = gateway.temporary_chats
|
||||
self._session_projection = gateway.session_projection
|
||||
@@ -509,6 +509,7 @@ class WebSocketChannel(BaseChannel):
|
||||
async def _cleanup_connection(self, connection: ServerConnection) -> None:
|
||||
"""Remove *connection* from every subscription set; safe to call multiple times."""
|
||||
self._retired_connections.add(connection)
|
||||
self._uploads.revoke(connection)
|
||||
state = self._connection_outbound.get(connection)
|
||||
if state is not None:
|
||||
state.closing = True
|
||||
@@ -697,6 +698,18 @@ class WebSocketChannel(BaseChannel):
|
||||
async def handler(connection: ServerConnection) -> None:
|
||||
await self._connection_loop(connection)
|
||||
|
||||
bridge = BinaryHTTPBridge(self._uploads.handle)
|
||||
|
||||
async def prune_uploads() -> None:
|
||||
while not stop_event.is_set():
|
||||
self._uploads.store.prune()
|
||||
try:
|
||||
await asyncio.wait_for(stop_event.wait(), timeout=30)
|
||||
except TimeoutError:
|
||||
pass
|
||||
|
||||
prune_task = asyncio.create_task(prune_uploads())
|
||||
|
||||
async def runner() -> None:
|
||||
socket_path = self.config.unix_socket_path
|
||||
failures = 0
|
||||
@@ -714,6 +727,7 @@ class WebSocketChannel(BaseChannel):
|
||||
handler,
|
||||
socket_path,
|
||||
process_request=process_request,
|
||||
create_connection=bridge.connection_factory,
|
||||
open_timeout=_WEBUI_HTTP_OPEN_TIMEOUT_S,
|
||||
max_size=self.config.max_message_bytes,
|
||||
ping_interval=self.config.ping_interval_s,
|
||||
@@ -728,6 +742,7 @@ class WebSocketChannel(BaseChannel):
|
||||
self.config.host,
|
||||
self.config.port,
|
||||
process_request=process_request,
|
||||
create_connection=bridge.connection_factory,
|
||||
open_timeout=_WEBUI_HTTP_OPEN_TIMEOUT_S,
|
||||
max_size=self.config.max_message_bytes,
|
||||
ping_interval=self.config.ping_interval_s,
|
||||
@@ -788,6 +803,10 @@ class WebSocketChannel(BaseChannel):
|
||||
try:
|
||||
await task
|
||||
finally:
|
||||
prune_task.cancel()
|
||||
await asyncio.gather(prune_task, return_exceptions=True)
|
||||
await bridge.shutdown()
|
||||
self._uploads.store.clear()
|
||||
self._running = False
|
||||
if self._server_task is task:
|
||||
self._server_task = None
|
||||
@@ -815,6 +834,8 @@ class WebSocketChannel(BaseChannel):
|
||||
"event": "ready",
|
||||
"chat_id": default_chat_id,
|
||||
"client_id": client_id,
|
||||
**({"upload": self._uploads.issue(connection)}
|
||||
if self.is_allowed(client_id) else {}),
|
||||
**({"terminal": gateway_identity(self.gateway.tokens.instance_id)}
|
||||
if _query_first(query, "terminal_protocol") == "1" else {}),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Production listener regressions for HTTP upload + small WS references."""
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import aiohttp
|
||||
import pytest
|
||||
from websockets.asyncio.client import connect
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def gateway(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
bus = MessageBus()
|
||||
config = WebSocketConfig(port=0, path="/ws", token="test-secret", max_message_bytes=1048576)
|
||||
services = build_gateway_services(
|
||||
config=config, bus=bus, session_manager=SessionManager(tmp_path),
|
||||
static_dist_path=None, workspace_path=tmp_path,
|
||||
default_restrict_to_workspace=True, runtime_model_name=None,
|
||||
runtime_surface="browser", runtime_capabilities_overrides=None,
|
||||
config_path=tmp_path / "config.json",
|
||||
)
|
||||
channel = WebSocketChannel(config, bus, gateway=services)
|
||||
task = asyncio.create_task(channel.start())
|
||||
try:
|
||||
async with asyncio.timeout(10):
|
||||
while channel._server is None:
|
||||
if task.done():
|
||||
await task
|
||||
await asyncio.sleep(.01)
|
||||
port = channel._server.sockets[0].getsockname()[1]
|
||||
yield channel, bus, f"http://127.0.0.1:{port}", f"ws://127.0.0.1:{port}/ws?token=test-secret"
|
||||
finally:
|
||||
await channel.stop()
|
||||
await task
|
||||
|
||||
|
||||
async def event(ws, name):
|
||||
async with asyncio.timeout(5):
|
||||
while True:
|
||||
payload = json.loads(await ws.recv())
|
||||
if payload["event"] == name:
|
||||
return payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime,name", [
|
||||
("image/png", "image.png"), ("text/csv", "report.csv"), ("video/webm", "clip.webm"),
|
||||
])
|
||||
async def test_real_listener_large_binary_and_reference_delivery(gateway, mime, name):
|
||||
channel, bus, http_url, ws_url = gateway
|
||||
raw = b"x" * 1_453_245
|
||||
async with connect(ws_url) as ws, aiohttp.ClientSession() as http:
|
||||
ready = await event(ws, "ready")
|
||||
capability = ready["upload"]
|
||||
headers = {"Authorization": f"Bearer {capability['token']}", "Content-Type": mime,
|
||||
"X-Attachment-Name": name}
|
||||
async with http.post(http_url + capability["path"], data=raw, headers=headers, expect100=True) as response:
|
||||
assert response.status == 201, await response.text()
|
||||
reference = (await response.json())["reference"]
|
||||
frame = {"type": "message", "chat_id": ready["chat_id"], "content": "look",
|
||||
"webui": True, "turn_id": "binary-turn",
|
||||
"media": [{"reference": reference, "name": name}]}
|
||||
assert len(json.dumps(frame)) < 1024
|
||||
await ws.send(json.dumps(frame))
|
||||
assert (await event(ws, "message_accepted"))["turn_id"] == "binary-turn"
|
||||
inbound = await asyncio.wait_for(bus.consume_inbound(), 2)
|
||||
path = Path(inbound.media[0])
|
||||
assert path.read_bytes() == raw
|
||||
assert path.parent == channel.gateway.uploads.store.media_dir
|
||||
# Lost ACK retry must not resolve a consumed reference or dispatch twice.
|
||||
await ws.send(json.dumps(frame))
|
||||
await event(ws, "message_accepted")
|
||||
with pytest.raises(TimeoutError):
|
||||
await asyncio.wait_for(bus.consume_inbound(), .03)
|
||||
channel.gateway.uploads.store.clear()
|
||||
assert path.exists()
|
||||
|
||||
|
||||
async def test_capability_is_required_owner_scoped_and_revoked(gateway):
|
||||
channel, _, http_url, ws_url = gateway
|
||||
async with aiohttp.ClientSession() as http:
|
||||
for token in ("", "test-secret", "client-selected-id"):
|
||||
async with http.post(http_url + "/api/attachments", data=b"secret",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "text/plain"}) as response:
|
||||
assert response.status == 401
|
||||
async with connect(ws_url) as owner, connect(ws_url) as other:
|
||||
capability = (await event(owner, "ready"))["upload"]
|
||||
other_ready = await event(other, "ready")
|
||||
headers = {"Authorization": f"Bearer {capability['token']}", "Content-Type": "image/png"}
|
||||
async with http.post(http_url + capability["path"], data=b"image", headers=headers) as response:
|
||||
reference = (await response.json())["reference"]
|
||||
await other.send(json.dumps({"type": "message", "chat_id": other_ready["chat_id"],
|
||||
"content": "steal", "media": [{"reference": reference}], "turn_id": "foreign"}))
|
||||
assert (await event(other, "error"))["detail"] == "attachment_rejected"
|
||||
async with asyncio.timeout(5):
|
||||
while capability["token"] in channel.gateway.uploads._tokens:
|
||||
await asyncio.sleep(.01)
|
||||
async with http.post(http_url + capability["path"], data=b"image", headers=headers) as response:
|
||||
assert response.status == 401
|
||||
|
||||
|
||||
async def test_inline_payload_rejected_and_failed_validation_keeps_upload(gateway):
|
||||
channel, bus, http_url, ws_url = gateway
|
||||
async with connect(ws_url) as ws, aiohttp.ClientSession() as http:
|
||||
ready = await event(ws, "ready")
|
||||
capability = ready["upload"]
|
||||
frame = {"type": "message", "chat_id": ready["chat_id"], "content": "look",
|
||||
"webui": True, "turn_id": "retry-turn", "media": [{"data_url": "data:image/png;base64,eA=="}]}
|
||||
await ws.send(json.dumps(frame))
|
||||
assert (await event(ws, "error"))["detail"] == "attachment_rejected"
|
||||
headers = {"Authorization": f"Bearer {capability['token']}", "Content-Type": "image/png"}
|
||||
async with http.post(http_url + capability["path"], data=b"image", headers=headers) as response:
|
||||
reference = (await response.json())["reference"]
|
||||
frame["media"] = [{"reference": reference}, {"reference": "invalid"}]
|
||||
await ws.send(json.dumps(frame))
|
||||
await event(ws, "error")
|
||||
frame["media"] = [{"reference": reference}]
|
||||
await ws.send(json.dumps(frame))
|
||||
await event(ws, "message_accepted")
|
||||
assert (await bus.consume_inbound()).media
|
||||
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime,body", [
|
||||
("image/svg+xml", b"<svg/>"), ("text/javascript", b"alert(1)"),
|
||||
("image/png", b""), ("image/png", b"x" * (6 * 1024 * 1024 + 1)),
|
||||
], ids=["svg", "javascript", "empty", "oversized"])
|
||||
async def test_http_policy_rejection_does_not_leave_files(gateway, mime, body):
|
||||
channel, _, http_url, ws_url = gateway
|
||||
async with connect(ws_url) as ws, aiohttp.ClientSession() as http:
|
||||
capability = (await event(ws, "ready"))["upload"]
|
||||
async with http.post(http_url + capability["path"], data=body,
|
||||
headers={"Authorization": f"Bearer {capability['token']}", "Content-Type": mime},
|
||||
expect100=True,
|
||||
) as response:
|
||||
assert response.status == 400
|
||||
assert not [p for p in channel.gateway.uploads.store.media_dir.rglob("*") if p.is_file()]
|
||||
|
||||
|
||||
async def test_one_shot_handshake_token_is_not_an_upload_credential(gateway):
|
||||
channel, _, http_url, _ = gateway
|
||||
# Use the same one-shot token registry as the bootstrap endpoint.
|
||||
issued = channel.gateway.tokens.issue_token(60, audience="webui")
|
||||
ws_url = http_url.replace("http://", "ws://") + "/ws?token=" + issued
|
||||
async with connect(ws_url) as ws, aiohttp.ClientSession() as http:
|
||||
capability = (await event(ws, "ready"))["upload"]
|
||||
assert issued not in channel.gateway.tokens.issued_tokens
|
||||
for token, expected in [(issued, 401), (capability["token"], 201)]:
|
||||
async with http.post(http_url + capability["path"], data=b"binary",
|
||||
headers={"Authorization": f"Bearer {token}", "Content-Type": "image/png"},
|
||||
) as response:
|
||||
assert response.status == expected
|
||||
|
||||
|
||||
async def test_stalled_upload_reports_timeout_and_keeps_connection_retryable(gateway):
|
||||
channel, _, http_url, ws_url = gateway
|
||||
channel.gateway.uploads.store.upload_idle_timeout = .05
|
||||
|
||||
async def stalled():
|
||||
yield b"x"
|
||||
await asyncio.sleep(.15)
|
||||
yield b"y"
|
||||
|
||||
async with connect(ws_url) as ws, aiohttp.ClientSession() as http:
|
||||
capability = (await event(ws, "ready"))["upload"]
|
||||
headers = {"Authorization": f"Bearer {capability['token']}",
|
||||
"Content-Type": "image/png", "Content-Length": "2"}
|
||||
async with http.post(http_url + capability["path"], data=stalled(), headers=headers) as response:
|
||||
assert response.status == 400
|
||||
assert (await response.json())["error"] == "Attachment upload timed out"
|
||||
assert not [p for p in channel.gateway.uploads.store.media_dir.rglob("*") if p.is_file()]
|
||||
async with http.post(http_url + capability["path"], data=b"xy", headers=headers) as response:
|
||||
assert response.status == 201
|
||||
@@ -0,0 +1,257 @@
|
||||
"""Binary staging regressions; these do not exercise the gateway HTTP listener."""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.channels.websocket.attachment_policy import AttachmentIngressLimits
|
||||
from nanobot.channels.websocket.attachment_store import AttachmentStore, AttachmentUploadError
|
||||
from nanobot.utils.media_decode import save_base64_data_url
|
||||
|
||||
|
||||
async def chunks(raw: bytes):
|
||||
for offset in range(0, len(raw), 65536):
|
||||
yield raw[offset:offset + 65536]
|
||||
|
||||
|
||||
async def upload(store, raw=b"attachment", owner="owner", mime="image/png", **kwargs):
|
||||
return await store.upload(chunks(raw), owner=owner, mime=mime, size=len(raw), **kwargs)
|
||||
|
||||
|
||||
async def test_binary_larger_than_websocket_limit_preserves_layout(tmp_path):
|
||||
raw = b"x" * (1024 * 1024 + 1)
|
||||
store = AttachmentStore(tmp_path)
|
||||
ref = await upload(store, raw)
|
||||
assert len(ref) < 100
|
||||
paths = store.resolve([ref], owner="owner")
|
||||
assert re.fullmatch(r"[0-9a-f]{12}\.png", Path(paths[0]).name)
|
||||
assert Path(paths[0]).read_bytes() == raw
|
||||
assert store.resolve([ref], owner="owner") == paths # a failed send is retryable
|
||||
assert store.commit([ref], owner="owner") == paths
|
||||
store.clear()
|
||||
assert Path(paths[0]).read_bytes() == raw # cleanup must not delete session media
|
||||
with pytest.raises(AttachmentUploadError):
|
||||
store.resolve([ref], owner="owner")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mime,filename,pattern", [
|
||||
("application/pdf", "../../report.pdf", r"[0-9a-f]{12}_.+\.pdf"),
|
||||
("video/webm", "ignored.webm", r"[0-9a-f]{12}\.webm"),
|
||||
("text/markdown", "notes.md", r"[0-9a-f]{12}_notes\.md"),
|
||||
])
|
||||
async def test_document_and_video_layout_matches_legacy(tmp_path, mime, filename, pattern):
|
||||
store = AttachmentStore(tmp_path)
|
||||
ref = await upload(store, mime=mime, filename=filename)
|
||||
path = Path(store.resolve([ref], owner="owner")[0])
|
||||
assert path.parent == tmp_path
|
||||
assert re.fullmatch(pattern, path.name)
|
||||
import base64
|
||||
legacy = save_base64_data_url(
|
||||
f"data:{mime};base64," + base64.b64encode(b"attachment").decode(), tmp_path,
|
||||
filename=filename if mime != "video/webm" else None,
|
||||
)
|
||||
assert legacy is not None
|
||||
assert path.name[12:] == Path(legacy).name[12:]
|
||||
|
||||
|
||||
async def test_ownership_invalid_and_duplicate_refs_are_atomic(tmp_path):
|
||||
store = AttachmentStore(tmp_path)
|
||||
ref = await upload(store)
|
||||
for references, owner in [([ref], "other"), ([ref, "unknown"], "owner"),
|
||||
([ref, ref], "owner"), (["../../file"], "owner")]:
|
||||
with pytest.raises(AttachmentUploadError):
|
||||
store.commit(references, owner=owner)
|
||||
assert len(store.resolve([ref], owner="owner")) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("size,raw", [(4, b"12345"), (6, b"12345")])
|
||||
async def test_body_length_failure_cleans_file_and_capacity(tmp_path, size, raw):
|
||||
store = AttachmentStore(tmp_path, max_pending=1, max_pending_bytes=6)
|
||||
with pytest.raises(AttachmentUploadError):
|
||||
await store.upload(chunks(raw), owner="owner", mime="image/png", size=size)
|
||||
assert not [path for path in tmp_path.rglob("*") if path.is_file()]
|
||||
assert await upload(store, b"123456")
|
||||
|
||||
|
||||
async def test_reject_metadata_before_reading_body(tmp_path):
|
||||
store = AttachmentStore(tmp_path)
|
||||
|
||||
async def unread():
|
||||
pytest.fail("Rejected request body was read")
|
||||
yield b""
|
||||
|
||||
for owner, mime, size in [("", "image/png", 1), ("owner", "text/javascript", 1),
|
||||
("owner", "image/png", 7 * 1024 * 1024),
|
||||
("owner", "image/png", 0)]:
|
||||
with pytest.raises(AttachmentUploadError):
|
||||
await store.upload(unread(), owner=owner, mime=mime, size=size)
|
||||
assert not [path for path in tmp_path.rglob("*") if path.is_file()]
|
||||
|
||||
|
||||
async def test_inflight_capacity_and_cancellation(tmp_path):
|
||||
store = AttachmentStore(tmp_path, max_pending_bytes=10)
|
||||
entered = asyncio.Event()
|
||||
|
||||
async def slow():
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
yield b"123456"
|
||||
|
||||
task = asyncio.create_task(store.upload(slow(), owner="owner", mime="image/png", size=6))
|
||||
await entered.wait()
|
||||
with pytest.raises(AttachmentUploadError, match="storage is full"):
|
||||
await upload(store, b"12345")
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert not [path for path in tmp_path.rglob("*") if path.is_file()]
|
||||
assert await upload(store, b"1234567890")
|
||||
|
||||
|
||||
async def test_timeout_cleans_partial_upload(tmp_path):
|
||||
store = AttachmentStore(tmp_path, upload_timeout=0.01)
|
||||
|
||||
async def slow():
|
||||
yield b"1"
|
||||
await asyncio.Event().wait()
|
||||
|
||||
with pytest.raises(TimeoutError):
|
||||
await store.upload(slow(), owner="owner", mime="image/png", size=2)
|
||||
assert not [path for path in tmp_path.rglob("*") if path.is_file()]
|
||||
|
||||
|
||||
async def test_progressing_upload_can_outlast_idle_timeout(tmp_path):
|
||||
store = AttachmentStore(tmp_path, upload_timeout=1, upload_idle_timeout=.1)
|
||||
|
||||
async def slow():
|
||||
for _ in range(3):
|
||||
await asyncio.sleep(.05)
|
||||
yield b"x"
|
||||
|
||||
ref = await store.upload(slow(), owner="owner", mime="image/png", size=3)
|
||||
assert Path(store.commit([ref], owner="owner")[0]).read_bytes() == b"xxx"
|
||||
|
||||
|
||||
async def test_stalled_upload_releases_file_and_capacity(tmp_path):
|
||||
store = AttachmentStore(
|
||||
tmp_path, upload_timeout=1, upload_idle_timeout=.01,
|
||||
max_pending=1, max_pending_bytes=2,
|
||||
)
|
||||
|
||||
async def stalled():
|
||||
yield b"x"
|
||||
await asyncio.Event().wait()
|
||||
|
||||
with pytest.raises(TimeoutError):
|
||||
await store.upload(stalled(), owner="owner", mime="image/png", size=2)
|
||||
assert not [path for path in tmp_path.rglob("*") if path.is_file()]
|
||||
assert await upload(store, b"xx")
|
||||
|
||||
|
||||
async def test_expiry_cleans_only_staged_files(tmp_path, monkeypatch):
|
||||
import nanobot.channels.websocket.attachment_store as module
|
||||
monkeypatch.setattr(module.time, "monotonic", lambda: 100)
|
||||
store = AttachmentStore(tmp_path, ttl_seconds=10)
|
||||
committed = await upload(store)
|
||||
staged = await upload(store)
|
||||
keep = Path(store.commit([committed], owner="owner")[0])
|
||||
remove = Path(store.resolve([staged], owner="owner")[0])
|
||||
monkeypatch.setattr(module.time, "monotonic", lambda: 111)
|
||||
store.prune()
|
||||
assert keep.exists()
|
||||
assert not remove.exists()
|
||||
with pytest.raises(AttachmentUploadError):
|
||||
store.resolve([staged], owner="owner")
|
||||
|
||||
|
||||
async def test_batch_limits_leave_all_references_retryable(tmp_path):
|
||||
store = AttachmentStore(tmp_path, limits=AttachmentIngressLimits(
|
||||
max_count=2, max_file_bytes=10, max_total_bytes=10,
|
||||
))
|
||||
refs = [await upload(store, b"123456") for _ in range(2)]
|
||||
with pytest.raises(AttachmentUploadError, match="total"):
|
||||
store.commit(refs, owner="owner")
|
||||
for ref in refs:
|
||||
assert store.resolve([ref], owner="owner")
|
||||
videos = [await upload(store, mime="video/mp4") for _ in range(2)]
|
||||
with pytest.raises(AttachmentUploadError, match="Too many"):
|
||||
store.resolve(videos, owner="owner")
|
||||
store.clear()
|
||||
assert not [path for path in tmp_path.rglob("*") if path.is_file()]
|
||||
|
||||
|
||||
async def test_filename_collision_never_unlinks_existing_file(tmp_path, monkeypatch):
|
||||
import nanobot.channels.websocket.attachment_store as module
|
||||
existing = tmp_path / "existing.png"
|
||||
existing.write_bytes(b"keep")
|
||||
monkeypatch.setattr(module, "media_destination", lambda *args, **kwargs: existing)
|
||||
with pytest.raises(FileExistsError):
|
||||
await upload(AttachmentStore(tmp_path))
|
||||
assert existing.read_bytes() == b"keep"
|
||||
|
||||
|
||||
async def test_committed_paths_persist_and_replay_without_reference_format(tmp_path):
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
store = AttachmentStore(tmp_path / "media")
|
||||
reference = await upload(store)
|
||||
paths = store.commit([reference], owner="owner")
|
||||
manager = SessionManager(tmp_path / "workspace")
|
||||
session = manager.get_or_create("websocket:binary-upload")
|
||||
session.add_message("user", "look", media=paths)
|
||||
manager.save(session)
|
||||
|
||||
replay_manager = SessionManager(tmp_path / "workspace")
|
||||
replay = replay_manager.get_or_create("websocket:binary-upload")
|
||||
assert replay.messages[0]["media"] == paths
|
||||
assert reference not in str(replay.messages)
|
||||
assert replay.get_history()[0] == {
|
||||
"role": "user", "content": f"look\n[image: {paths[0]}]",
|
||||
}
|
||||
store.clear()
|
||||
assert Path(paths[0]).exists()
|
||||
|
||||
|
||||
async def test_restart_prunes_crash_remnants_but_not_committed_media(tmp_path, monkeypatch):
|
||||
import os
|
||||
import time
|
||||
|
||||
first = AttachmentStore(tmp_path)
|
||||
committed = await upload(first)
|
||||
keep = Path(first.commit([committed], owner="owner")[0])
|
||||
abandoned = await upload(first)
|
||||
remove = Path(first.resolve([abandoned], owner="owner")[0])
|
||||
marker = tmp_path / ".pending-attachments" / remove.name
|
||||
old = time.time() - first.ttl_seconds - first.upload_timeout - 1
|
||||
os.utime(marker, (old, old))
|
||||
restarted = AttachmentStore(tmp_path)
|
||||
restarted.prune()
|
||||
assert not remove.exists()
|
||||
assert not marker.exists()
|
||||
assert keep.read_bytes() == b"attachment"
|
||||
|
||||
|
||||
async def test_disconnect_releases_staged_capacity_but_preserves_commits(tmp_path):
|
||||
store = AttachmentStore(tmp_path, max_pending=1)
|
||||
ref = await upload(store)
|
||||
keep = Path(store.commit([ref], owner="owner")[0])
|
||||
ref = await upload(store)
|
||||
remove = Path(store.resolve([ref], owner="owner")[0])
|
||||
store.discard_owner("owner")
|
||||
assert not remove.exists()
|
||||
assert keep.exists()
|
||||
assert await upload(store)
|
||||
|
||||
|
||||
async def test_filename_collision_preserves_another_uploads_crash_marker(tmp_path, monkeypatch):
|
||||
store = AttachmentStore(tmp_path)
|
||||
ref = await upload(store)
|
||||
path = Path(store.resolve([ref], owner="owner")[0])
|
||||
monkeypatch.setattr("nanobot.channels.websocket.attachment_store.media_destination", lambda *args, **kwargs: path)
|
||||
with pytest.raises(FileExistsError):
|
||||
await upload(store)
|
||||
assert (tmp_path / ".pending-attachments" / path.name).exists()
|
||||
assert path.read_bytes() == b"attachment"
|
||||
store.clear()
|
||||
@@ -0,0 +1,238 @@
|
||||
"""Real socket regressions for body-capable HTTP beside bounded WebSockets."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import aiohttp
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from websockets.asyncio.client import connect
|
||||
from websockets.asyncio.server import serve
|
||||
|
||||
from nanobot.channels.websocket.attachment_store import AttachmentStore
|
||||
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_binary_body_exceeds_ws_frame_limit_without_changing_ws(tmp_path):
|
||||
store = AttachmentStore(tmp_path)
|
||||
|
||||
async def upload(request):
|
||||
if request.headers.get("Authorization") != "Bearer isolated-test":
|
||||
return web.json_response({"error": "Unauthorized"}, status=401)
|
||||
if request.method != "POST" or request.path != "/api/attachments":
|
||||
return web.Response(status=404)
|
||||
if request.content_length is None or request.headers.get("Content-Encoding"):
|
||||
return web.Response(status=400)
|
||||
ref = await store.upload(
|
||||
request.content.iter_chunked(65536), owner="authenticated-owner",
|
||||
mime=request.content_type, size=request.content_length,
|
||||
)
|
||||
return web.json_response({"ref": ref})
|
||||
|
||||
async def echo(connection):
|
||||
async for message in connection:
|
||||
await connection.send(message)
|
||||
|
||||
bridge = BinaryHTTPBridge(upload)
|
||||
server = await serve(echo, "127.0.0.1", 0, max_size=1024 * 1024,
|
||||
create_connection=bridge.connection_factory)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
body = b"x" * 1_453_245
|
||||
try:
|
||||
async with aiohttp.ClientSession() as client:
|
||||
async with client.post(f"http://127.0.0.1:{port}/api/attachments", data=body,
|
||||
headers={"Content-Type": "image/png"}) as response:
|
||||
assert response.status == 401
|
||||
assert not list(tmp_path.iterdir())
|
||||
async with client.post(f"http://127.0.0.1:{port}/api/attachments", data=body,
|
||||
headers={"Content-Type": "image/png",
|
||||
"Authorization": "Bearer isolated-test"}) as response:
|
||||
assert response.status == 200
|
||||
ref = (await response.json())["ref"]
|
||||
paths = store.resolve([ref], owner="authenticated-owner")
|
||||
assert len(paths) == 1
|
||||
assert (tmp_path / paths[0]).read_bytes() == body
|
||||
async with connect(f"ws://127.0.0.1:{port}/") as ws:
|
||||
await ws.send(ref)
|
||||
assert await ws.recv() == ref
|
||||
await ws.send(body)
|
||||
await ws.wait_closed()
|
||||
assert ws.close_code == 1009
|
||||
finally:
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await bridge.shutdown()
|
||||
store.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fragmented_method_and_shutdown_of_undecided_connection():
|
||||
async def upload(request):
|
||||
return web.Response(body=await request.read())
|
||||
|
||||
async def echo(connection):
|
||||
async for message in connection:
|
||||
await connection.send(message)
|
||||
|
||||
bridge = BinaryHTTPBridge(upload)
|
||||
server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
try:
|
||||
for fragment in (b"P", b"O", b"S", b"T / HTTP/1.1\r\nHost: localhost\r\n",
|
||||
b"Content-Length: 4\r\nConnection: close\r\n\r\ntest"):
|
||||
writer.write(fragment)
|
||||
await writer.drain()
|
||||
await asyncio.sleep(0)
|
||||
response = await asyncio.wait_for(reader.read(), 2)
|
||||
assert b"200 OK" in response
|
||||
assert response.endswith(b"test")
|
||||
idle_reader, idle_writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
idle_writer.write(b"P")
|
||||
await idle_writer.drain()
|
||||
await asyncio.sleep(0.01)
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await bridge.shutdown()
|
||||
assert await asyncio.wait_for(idle_reader.read(), 2) == b""
|
||||
idle_writer.close()
|
||||
await idle_writer.wait_closed()
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await bridge.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("headers", [
|
||||
b"Content-Length: 4\r\nTransfer-Encoding: chunked\r\n",
|
||||
b"Content-Length: 4\r\nContent-Length: 5\r\n",
|
||||
b"Content-Length: -1\r\n",
|
||||
])
|
||||
async def test_ambiguous_http_framing_is_rejected_before_handler(headers):
|
||||
calls = []
|
||||
|
||||
async def upload(request):
|
||||
calls.append(request)
|
||||
return web.Response(status=200)
|
||||
|
||||
async def echo(connection):
|
||||
await connection.wait_closed()
|
||||
|
||||
bridge = BinaryHTTPBridge(upload)
|
||||
server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
try:
|
||||
writer.write(b"POST / HTTP/1.1\r\nHost: localhost\r\n" + headers
|
||||
+ b"Connection: close\r\n\r\ntest")
|
||||
await writer.drain()
|
||||
response = await asyncio.wait_for(reader.read(), 2)
|
||||
assert b"400 Bad Request" in response
|
||||
assert calls == []
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await bridge.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_body_is_not_automatically_decompressed():
|
||||
import gzip
|
||||
|
||||
body = gzip.compress(b"x" * 2_000_000)
|
||||
received = []
|
||||
|
||||
async def upload(request):
|
||||
received.append(await request.read())
|
||||
return web.Response(status=204)
|
||||
|
||||
async def echo(connection):
|
||||
await connection.wait_closed()
|
||||
|
||||
bridge = BinaryHTTPBridge(upload)
|
||||
server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
try:
|
||||
async with aiohttp.ClientSession() as client:
|
||||
async with client.post(f"http://127.0.0.1:{port}/", data=body,
|
||||
headers={"Content-Encoding": "gzip"}) as response:
|
||||
assert response.status == 204
|
||||
assert received == [body]
|
||||
finally:
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await bridge.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_incomplete_http_headers_have_a_deadline(monkeypatch):
|
||||
monkeypatch.setattr("nanobot.channels.websocket.binary_http._HTTP_HEADER_TIMEOUT_S", .05)
|
||||
|
||||
async def upload(request):
|
||||
pytest.fail("Incomplete headers must not invoke the upload handler")
|
||||
|
||||
async def echo(connection):
|
||||
await connection.wait_closed()
|
||||
|
||||
bridge = BinaryHTTPBridge(upload)
|
||||
server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
try:
|
||||
writer.write(b"POST /api/attachments HTTP/1.1\r\nHost: localhost\r\n")
|
||||
await writer.drain()
|
||||
assert await asyncio.wait_for(reader.read(), 2) == b""
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await bridge.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_parsed_request_outlasts_header_deadline(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.channels.websocket.binary_http._HTTP_HEADER_TIMEOUT_S", .1)
|
||||
monkeypatch.setattr("nanobot.channels.websocket.binary_http._HTTP_CONNECTION_TIMEOUT_S", 1)
|
||||
store = AttachmentStore(tmp_path, upload_timeout=1, upload_idle_timeout=.1)
|
||||
started = asyncio.Event()
|
||||
|
||||
async def upload(request):
|
||||
started.set()
|
||||
ref = await store.upload(
|
||||
request.content.iter_chunked(65536), owner="owner", mime="image/png", size=3,
|
||||
)
|
||||
response = web.json_response({"ref": ref})
|
||||
response.force_close()
|
||||
return response
|
||||
|
||||
async def echo(connection):
|
||||
await connection.wait_closed()
|
||||
|
||||
bridge = BinaryHTTPBridge(upload)
|
||||
server = await serve(echo, "127.0.0.1", 0, create_connection=bridge.connection_factory)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
try:
|
||||
writer.write(b"POST /api/attachments HTTP/1.1\r\nHost: localhost\r\nContent-Length: 3\r\n\r\n")
|
||||
await writer.drain()
|
||||
await asyncio.wait_for(started.wait(), 1)
|
||||
for _ in range(3):
|
||||
await asyncio.sleep(.05)
|
||||
writer.write(b"x")
|
||||
await writer.drain()
|
||||
response = await asyncio.wait_for(reader.read(), 1)
|
||||
assert b"200 OK" in response
|
||||
assert [p.read_bytes() for p in tmp_path.glob("*.png")] == [b"xxx"]
|
||||
finally:
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
server.close()
|
||||
await server.wait_closed()
|
||||
await bridge.shutdown()
|
||||
store.clear()
|
||||
@@ -418,9 +418,8 @@ async def test_temporary_chat_is_transient_and_discarded(bus, tmp_path) -> None:
|
||||
chat_id = await _new_temporary_chat(channel, connection)
|
||||
upload = tmp_path / "temporary-upload.txt"
|
||||
upload.write_text("private attachment", encoding="utf-8")
|
||||
channel.gateway.media.store_inbound_attachments = MagicMock(
|
||||
return_value=([str(upload)], None),
|
||||
)
|
||||
channel.gateway.uploads.store.resolve = MagicMock(return_value=[str(upload)])
|
||||
channel.gateway.uploads.store.commit = MagicMock(return_value=[str(upload)])
|
||||
|
||||
await channel._dispatch_envelope(
|
||||
connection,
|
||||
@@ -429,7 +428,7 @@ async def test_temporary_chat_is_transient_and_discarded(bus, tmp_path) -> None:
|
||||
"type": "message",
|
||||
"chat_id": chat_id,
|
||||
"content": "read this",
|
||||
"media": [{"data_url": "data:text/plain;base64,cHJpdmF0ZQ=="}],
|
||||
"media": [{"reference": "temporary-upload"}],
|
||||
"cli_apps": [{"name": "drawio"}],
|
||||
"workspace_scope": {
|
||||
"project_path": str(selected_project),
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
"""Tests for WS envelope media handling (client attachment upload path).
|
||||
|
||||
Exercises ``WebSocketChannel._dispatch_envelope`` for the ``message`` branch:
|
||||
decoding base64 data URLs, rejecting malformed / oversized / non-whitelisted
|
||||
payloads, preserving backward compatibility with media-less frames, and
|
||||
forwarding saved paths to ``_handle_message``.
|
||||
"""
|
||||
"""WS envelope regressions; binary ingress is tested through the HTTP listener."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
@@ -26,22 +19,6 @@ from nanobot.session.session_handles import SessionHandleResolver
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
|
||||
def _tiny_png_data_url() -> str:
|
||||
"""A 1-pixel PNG prefixed as a data URL — just enough for magic-bytes sniffing."""
|
||||
# 1x1 transparent PNG
|
||||
png = (
|
||||
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00"
|
||||
b"\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx"
|
||||
b"\x9cc\xf8\xcf\xc0\x00\x00\x00\x03\x00\x01\x00\x18\xdd\x8d\xb4\x00"
|
||||
b"\x00\x00\x00IEND\xaeB`\x82"
|
||||
)
|
||||
return f"data:image/png;base64,{base64.b64encode(png).decode()}"
|
||||
|
||||
|
||||
def _data_url(mime: str, payload: bytes) -> str:
|
||||
return f"data:{mime};base64,{base64.b64encode(payload).decode()}"
|
||||
|
||||
|
||||
def _make_channel(session_manager: SessionManager | None = None) -> WebSocketChannel:
|
||||
bus = MagicMock()
|
||||
bus.publish_inbound = AsyncMock()
|
||||
@@ -76,24 +53,18 @@ def isolate_websocket_turn_state() -> None:
|
||||
wth._WEBSOCKET_TURN_OWNERS.clear()
|
||||
|
||||
|
||||
# -- max_message_bytes bump ----------------------------------------------------
|
||||
|
||||
|
||||
def test_max_message_bytes_default_supports_multi_image_frame() -> None:
|
||||
"""Default 36 MB must comfortably hold 4 × 6 MB base64-encoded images."""
|
||||
def test_max_message_bytes_keeps_existing_transport_guard() -> None:
|
||||
"""Moving attachments to HTTP does not disable the configurable WS guard."""
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
|
||||
default = WebSocketConfig().max_message_bytes
|
||||
# 4 images × 6 MB × 1.37 base64 overhead ≈ 33 MB
|
||||
assert default >= 33 * 1024 * 1024
|
||||
# Upper bound 40 MB matches plan
|
||||
assert default == 36 * 1024 * 1024
|
||||
assert WebSocketConfig(max_message_bytes=1048576).max_message_bytes == 1048576
|
||||
# The existing upper bound remains 40 MB.
|
||||
with pytest.raises(Exception):
|
||||
WebSocketConfig(max_message_bytes=41_943_040 + 1)
|
||||
|
||||
|
||||
# -- _dispatch_envelope message branch + media --------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_without_media_backward_compatible() -> None:
|
||||
"""Existing clients that don't send ``media`` keep working unchanged."""
|
||||
@@ -136,41 +107,6 @@ async def test_webui_message_acceptance_echoes_turn_id() -> None:
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_webui_message_projects_attachments_to_other_clients(tmp_path: Path) -> None:
|
||||
channel = _make_channel()
|
||||
origin = AsyncMock()
|
||||
peer = AsyncMock()
|
||||
channel._attach(origin, "abc123")
|
||||
channel._attach(peer, "abc123")
|
||||
channel._webui_connections.add(origin)
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "please inspect @drawio",
|
||||
"webui": True,
|
||||
"turn_id": "turn-shared",
|
||||
"media": [{"data_url": _tiny_png_data_url(), "name": "shot.png"}],
|
||||
"cli_apps": [{"name": "DrawIO", "entry_point": "cli-anything-drawio"}],
|
||||
}
|
||||
|
||||
with patch("nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path):
|
||||
await channel._dispatch_envelope(origin, "client-1", envelope)
|
||||
|
||||
event = json.loads(peer.send.await_args.args[0])
|
||||
assert event["event"] == "user_message"
|
||||
assert event["turn_id"] == "turn-shared"
|
||||
assert event["text"] == "please inspect @drawio"
|
||||
assert event["cli_apps"] == [{
|
||||
"name": "drawio",
|
||||
"entry_point": "cli-anything-drawio",
|
||||
}]
|
||||
assert event["media_urls"][0]["kind"] == "image"
|
||||
assert event["media_urls"][0]["name"] == "shot.png"
|
||||
assert event["media_urls"][0]["url"].startswith("/api/media/")
|
||||
assert json.loads(origin.send.await_args.args[0])["event"] == "message_accepted"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_text_policy_is_independent_from_transport_limit() -> None:
|
||||
channel = _make_channel()
|
||||
@@ -270,281 +206,6 @@ async def test_webui_message_forwards_verified_session_mentions(tmp_path) -> Non
|
||||
assert "websocket:pricing" in block.content
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_with_single_image_forwards_saved_path(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "look at this",
|
||||
"media": [{"data_url": _tiny_png_data_url(), "name": "shot.png"}],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_awaited_once()
|
||||
paths = channel._handle_message.call_args.kwargs["media"]
|
||||
assert isinstance(paths, list) and len(paths) == 1
|
||||
saved = Path(paths[0])
|
||||
assert saved.exists()
|
||||
assert saved.suffix == ".png"
|
||||
assert saved.is_relative_to(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_with_multiple_images(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "a couple",
|
||||
"media": [
|
||||
{"data_url": _tiny_png_data_url()},
|
||||
{"data_url": _tiny_png_data_url()},
|
||||
{"data_url": _tiny_png_data_url()},
|
||||
],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
paths = channel._handle_message.call_args.kwargs["media"]
|
||||
assert len(paths) == 3
|
||||
# Saved filenames must be unique.
|
||||
assert len({Path(p).name for p in paths}) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_image_only_message_allows_empty_text(tmp_path) -> None:
|
||||
"""When media is attached, empty text is acceptable."""
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "",
|
||||
"media": [{"data_url": _tiny_png_data_url()}],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_awaited_once()
|
||||
# Error event NOT sent.
|
||||
mock_conn.send.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_rejected_when_more_than_four_images(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "hi",
|
||||
"media": [{"data_url": _tiny_png_data_url()}] * 5,
|
||||
"turn_id": "turn-attachments",
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_not_awaited()
|
||||
mock_conn.send.assert_awaited_once()
|
||||
err = json.loads(mock_conn.send.call_args[0][0])
|
||||
assert err["event"] == "error"
|
||||
assert err["chat_id"] == "abc123"
|
||||
assert err["detail"] == "attachment_rejected"
|
||||
assert err["reason"] == "too_many_images"
|
||||
assert err["turn_id"] == "turn-attachments"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_rejected_when_too_many_total_attachments(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "mixed",
|
||||
"media": [
|
||||
{"data_url": _tiny_png_data_url()},
|
||||
{"data_url": _tiny_png_data_url()},
|
||||
{"data_url": _tiny_png_data_url()},
|
||||
{"data_url": _tiny_png_data_url()},
|
||||
{"data_url": _data_url("application/pdf", b"%PDF-1.4"), "name": "report.pdf"},
|
||||
],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_not_awaited()
|
||||
err = json.loads(mock_conn.send.call_args[0][0])
|
||||
assert err["detail"] == "attachment_rejected"
|
||||
assert err["reason"] == "too_many_attachments"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_rejected_on_oversize_payload(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
oversized = b"x" * (9 * 1024 * 1024) # > 8 MB WS limit
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "big",
|
||||
"media": [{"data_url": _data_url("image/png", oversized)}],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_not_awaited()
|
||||
err = json.loads(mock_conn.send.call_args[0][0])
|
||||
assert err["detail"] == "attachment_rejected"
|
||||
assert err["reason"] == "size"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_with_pdf_forwards_saved_path(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "pdf?",
|
||||
"media": [{"data_url": _data_url("application/pdf", b"%PDF-1.4"), "name": "report.pdf"}],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_awaited_once()
|
||||
paths = channel._handle_message.call_args.kwargs["media"]
|
||||
assert isinstance(paths, list) and len(paths) == 1
|
||||
saved = Path(paths[0])
|
||||
assert saved.exists()
|
||||
assert saved.suffix == ".pdf"
|
||||
assert saved.name.endswith("_report.pdf")
|
||||
assert saved.read_bytes() == b"%PDF-1.4"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_with_csv_forwards_saved_path(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "summarize",
|
||||
"media": [
|
||||
{"data_url": _data_url("text/csv", b"name,value\nnanobot,1"), "name": "report.csv"}
|
||||
],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_awaited_once()
|
||||
paths = channel._handle_message.call_args.kwargs["media"]
|
||||
saved = Path(paths[0])
|
||||
assert saved.suffix == ".csv"
|
||||
assert saved.name.endswith("_report.csv")
|
||||
assert saved.read_bytes() == b"name,value\nnanobot,1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_rejected_on_unsupported_file_mime(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "zip?",
|
||||
"media": [{"data_url": _data_url("application/zip", b"PK")}],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_not_awaited()
|
||||
err = json.loads(mock_conn.send.call_args[0][0])
|
||||
assert err["detail"] == "attachment_rejected"
|
||||
assert err["reason"] == "mime"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_rejected_on_svg_mime(tmp_path) -> None:
|
||||
"""SVG is explicitly rejected — XSS surface inside embedded scripts."""
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "svg",
|
||||
"media": [{"data_url": _data_url("image/svg+xml", b"<svg/>")}],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_not_awaited()
|
||||
err = json.loads(mock_conn.send.call_args[0][0])
|
||||
assert err["reason"] == "mime"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"data_url",
|
||||
[
|
||||
pytest.param("http://evil.example/image.png", id="malformed_data_url"),
|
||||
pytest.param("data:image/png;base64,not-valid-base64!!!", id="broken_base64"),
|
||||
],
|
||||
)
|
||||
async def test_message_rejects_invalid_media_data_url(tmp_path, data_url) -> None:
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "nope",
|
||||
"media": [{"data_url": data_url}],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_not_awaited()
|
||||
err = json.loads(mock_conn.send.call_args[0][0])
|
||||
assert err["reason"] == "decode"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_message_rejected_when_media_item_shape_wrong(tmp_path) -> None:
|
||||
channel = _make_channel()
|
||||
@@ -586,38 +247,6 @@ async def test_message_rejected_when_media_field_is_not_list() -> None:
|
||||
assert err["reason"] == "malformed"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failed_media_does_not_partially_persist(tmp_path) -> None:
|
||||
"""If the second attachment is invalid, the first must not be forwarded.
|
||||
|
||||
Also: files already written in this call are cleaned up on failure, so
|
||||
a mixed-valid/invalid batch never leaves orphan files in the media dir.
|
||||
"""
|
||||
channel = _make_channel()
|
||||
mock_conn = AsyncMock()
|
||||
envelope = {
|
||||
"type": "message",
|
||||
"chat_id": "abc123",
|
||||
"content": "mixed",
|
||||
"media": [
|
||||
{"data_url": _tiny_png_data_url()},
|
||||
{"data_url": _data_url("image/svg+xml", b"<svg/>")},
|
||||
],
|
||||
}
|
||||
|
||||
with patch(
|
||||
"nanobot.webui.media_gateway.get_media_dir", return_value=tmp_path
|
||||
):
|
||||
await channel._dispatch_envelope(mock_conn, "client-1", envelope)
|
||||
|
||||
channel._handle_message.assert_not_awaited()
|
||||
err = json.loads(mock_conn.send.call_args[0][0])
|
||||
assert err["reason"] == "mime"
|
||||
# Partial-batch failures must not leak files to disk.
|
||||
leftover = [p for p in tmp_path.iterdir() if p.is_file()]
|
||||
assert leftover == [], f"orphan media after rejected batch: {leftover}"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rejects_empty_text_without_media() -> None:
|
||||
"""When no media is attached, whitespace-only content is still rejected
|
||||
@@ -652,3 +281,33 @@ async def test_non_string_content_still_rejected() -> None:
|
||||
channel._handle_message.assert_not_awaited()
|
||||
err = json.loads(mock_conn.send.call_args[0][0])
|
||||
assert err["detail"] == "missing content"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reference_attachments_are_projected_to_other_clients(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||
channel = _make_channel()
|
||||
origin, peer = AsyncMock(), AsyncMock()
|
||||
owner = channel.gateway.uploads.issue(origin)["token"]
|
||||
channel._attach(origin, "reference-chat")
|
||||
channel._attach(peer, "reference-chat")
|
||||
channel._webui_connections.add(origin)
|
||||
|
||||
async def body():
|
||||
yield b"image"
|
||||
|
||||
reference = await channel.gateway.uploads.store.upload(
|
||||
body(), owner=owner, mime="image/png", size=5,
|
||||
)
|
||||
await channel._dispatch_envelope(origin, "client", {
|
||||
"type": "message", "chat_id": "reference-chat", "content": "",
|
||||
"webui": True, "turn_id": "reference-turn",
|
||||
"media": [{"reference": reference, "name": "shot.png"}],
|
||||
})
|
||||
channel._handle_message.assert_awaited_once()
|
||||
assert Path(channel._handle_message.call_args.kwargs["media"][0]).read_bytes() == b"image"
|
||||
payload = json.loads(peer.send.await_args.args[0])
|
||||
assert payload["event"] == "user_message"
|
||||
assert payload["media_urls"][0]["name"] == "shot.png"
|
||||
assert payload["media_urls"][0]["url"].startswith("/api/media/")
|
||||
assert reference not in str(payload)
|
||||
@@ -224,7 +224,7 @@ def test_local_markdown_image_rejects_workspace_escape(
|
||||
with patch("nanobot.webui.media_gateway.get_media_dir", side_effect=_fake_media_dir(media)):
|
||||
assert channel.gateway.media.rewrite_local_markdown_images(text) == text
|
||||
|
||||
assert not (media / "websocket").exists()
|
||||
assert list((media / "websocket").iterdir()) == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user