Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(show): contain admission and keep runtime transport local

Maxf3fc595019dd
diff --git a/core/show_api.py b/core/show_api.py
index f722d164b..7634bc180 100644
--- a/core/show_api.py
+++ b/core/show_api.py
@@ -131,21 +131,31 @@ def _declarations(workspace: Path) -> list[dict]:
return payload["server_to_server"]
+def is_server_api_path(raw_path: bytes, method: str, query: bytes = b"") -> bool:
+ """Identify only a possible declaration path, without granting admission."""
+ if method != "POST" or query or len(raw_path) > 512:
+ return False
+ match = _PUBLIC_PATH.fullmatch(raw_path)
+ return match is not None and _ROUTE.fullmatch(match[2].decode("ascii")) is not None
+
+
def resolve_server_api(raw_path: bytes, method: str, query: bytes = b"") -> ServerAPIRegistration | None:
"""Resolve admission from current page state and files, with no lifecycle writes."""
- if method != "POST" or query or len(raw_path) > 512:
+ if not is_server_api_path(raw_path, method, query):
return None
match = _PUBLIC_PATH.fullmatch(raw_path)
- if match is None:
- return None
share_id, route_path = (part.decode("ascii") for part in match.groups())
- if not _ROUTE.fullmatch(route_path):
- return None
- store = ShowPageStore()
try:
- page = store.get_by_share_id(share_id)
- finally:
- store.close()
+ store = ShowPageStore(read_only=True)
+ try:
+ page = store.get_by_share_id(share_id)
+ finally:
+ store.close()
+ except Exception as exc:
+ # Datastore failures are not an absent registration. Do not fall through
+ # to browser admission or expose exception detail through the UI handler.
+ logger.warning("Show server API datastore unavailable (%s)", type(exc).__name__)
+ raise ServerAPIRequestError(503) from exc
if page is None or page.share_id != share_id or page.visibility != "public":
return None
try:
diff --git a/core/show_pages.py b/core/show_pages.py
index 66c688e38..653b49ab1 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -721,15 +721,18 @@ def public_url(share_id: str | None, *, config: V2Config | None = None) -> str |
class ShowPageStore:
- def __init__(self, db_path: Path | None = None):
+ def __init__(self, db_path: Path | None = None, *, read_only: bool = False):
self.db_path = db_path or paths.get_sqlite_state_path()
- if db_path is None:
- ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
- else:
- from storage.migrations import run_migrations
+ if not read_only:
+ if db_path is None:
+ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
+ else:
+ from storage.migrations import run_migrations
- run_migrations(self.db_path)
- self.engine = create_sqlite_engine(self.db_path)
+ run_migrations(self.db_path)
+ self.engine = (
+ create_sqlite_engine(self.db_path, read_only=True) if read_only else create_sqlite_engine(self.db_path)
+ )
def close(self) -> None:
self.engine.dispose()
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 6edb467fd..86f841d6e 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -1246,7 +1246,7 @@ class ShowRuntimeManager:
) -> httpx.Response:
"""Own transport failures and publish their recovery evidence."""
try:
- async with httpx.AsyncClient(timeout=httpx.Timeout(phase_timeout_seconds, connect=5.0)) as client:
+ async with httpx.AsyncClient(timeout=httpx.Timeout(phase_timeout_seconds, connect=5.0), trust_env=False) as client:
async def bounded_response() -> httpx.Response:
bounded_headers = {**headers, "accept-encoding": "identity"}
async with client.stream(method, f"{base_url}{path}", headers=bounded_headers, content=body) as response:
@@ -1518,7 +1518,7 @@ class ShowRuntimeManager:
async def _probe_capabilities_payload(self, base_url: str) -> dict[str, Any] | object | None:
try:
- async with httpx.AsyncClient(timeout=httpx.Timeout(2.0, connect=0.5)) as client:
+ async with httpx.AsyncClient(timeout=httpx.Timeout(2.0, connect=0.5), trust_env=False) as client:
response = await client.get(f"{base_url}/capabilities")
except (httpx.TimeoutException, httpx.TransportError):
return None
@@ -1569,7 +1569,7 @@ class ShowRuntimeManager:
async def _healthy(self, base_url: str) -> bool:
try:
- async with httpx.AsyncClient(timeout=httpx.Timeout(2.0, connect=0.5)) as client:
+ async with httpx.AsyncClient(timeout=httpx.Timeout(2.0, connect=0.5), trust_env=False) as client:
response = await client.get(f"{base_url}/health")
return response.status_code == 200
except Exception:
diff --git a/docs/plans/show-server-api-ingress.md b/docs/plans/show-server-api-ingress.md
index 92c5f1dbd..8e20868d0 100644
--- a/docs/plans/show-server-api-ingress.md
+++ b/docs/plans/show-server-api-ingress.md
@@ -49,7 +49,9 @@ Same external inbox + sole remotePM seszbebbz6fwq. One managed forever Harness d
- new `core/show_api.py`
- `core/show_runtime.py`: PM-approved extension on 2026-09-18 to the existing request and transport options only; see implementation mechanics below
- `core/show_pages.py` only where required to reuse page/workspace lifecycle
+- `storage/db.py`: PM-approved shared factory `read_only=False` option on 2026-09-18; no migration/importer/lock changes
- `tests/test_ui_show_pages.py`, `tests/test_ui_server_mutation_protection.py`, new `tests/test_show_api.py`, new `tests/test_show_api_integration.py`
+- `tests/test_show_runtime_protocol.py`: PM-approved strict client factory adaptation to assert the local transport's `trust_env=False`, preserving existing timeout assertions
- `scripts/check_show_router.mjs` only for reusing its pinned real Runtime integration path
- `skills/use-show-pages/SKILL.md`, optional new `skills/use-show-pages/references/server-api.md` if it keeps entry concise
- this `docs/plans/show-server-api-ingress.md`
@@ -80,8 +82,15 @@ Prepare a pinned installable artifact and rollback/state-preservation/health pla
Raw URI aliases and queries do not acquire admission. Manifest parsing rejects
duplicate keys; invalid optional declarations disable admission.
- Body limits are 1 MiB hard maximum, 10 seconds for upload and 30 seconds for
- the complete registered operation, including capability negotiation and
- response streaming. Requests allow at most 64 header fields / 16 KiB in total,
+ the complete admission and registered operation, including the first storage
+ lookup, earlier request hooks, capability negotiation and response streaming.
+ A syntactic candidate never grants admission: the current declaration still
+ controls the exception. Once an unregistered browser request passes its normal
+ admission hooks, its established handler timeout is preserved. Datastore
+ construction, lookup and close failures produce fixed 503/no-store receipts
+ without exception details or browser cookies. Request cancellation prevents
+ subsequent forwarding; it does not forcibly terminate a synchronous worker.
+ Requests allow at most 64 header fields / 16 KiB in total,
with 16 declared metadata names of at most 64 characters and values of at most
2048 bytes. Names are case-insensitive `x-` metadata under a fixed exclusion
policy for credentials, hop/proxy/internal protocol and browser identity.
@@ -98,6 +107,26 @@ Prepare a pinned installable artifact and rollback/state-preservation/health pla
before capability probes or lifecycle operations. The existing transport owns
streaming and process-fenced failure invalidation; oversized/encoded handler
responses close their stream without invalidating a healthy Runtime.
+- The first reviewed head `44666dc8594fb3e13e83bb35970e58a5c36279b5` had three
+ findings in two root-cause classes: incomplete pre-handler public boundaries
+ (deadline and datastore error containment), and environment-owned loopback
+ egress. PM approved closing these classes together. All three Runtime HTTPX
+ clients (transport, capabilities and health) now set `trust_env=False`.
+ Artifact downloads and other external HTTP clients retain their own policy.
+- The resolver uses `ShowPageStore(read_only=True)` through the existing shared
+ SQLite factory's keyword-only `read_only=False` option. PM approved this narrow
+ follow-through after inspecting the cold-store migration lock: `mode=ro` opens
+ an existing database without directory/file creation, migration/bootstrap or
+ journal-mode changes. It preserves hidden SQL parameters and a 5-second busy
+ wait. Missing/unreadable/corrupt/schema-incomplete state fails with the fixed
+ public 503 boundary; healthy absent declarations still fall back normally.
+ Default stores and cached engines retain their existing lifecycle. SQLite WAL
+ and SHM bookkeeping may still occur; this is not an immutable-file guarantee.
+ Authorized startup owns initialization. Pre-existing UI config/startup hooks
+ are not redesigned, and timeout does not claim to kill synchronous workers.
+ Tests hold a real migration lock while resolving, prohibit both bootstrap
+ entrypoints, delete a database between engine creation and connection, and
+ verify URI encoding, unchanged journal mode and ordinary default Store writes.
- Bounded Runtime response materialization recalculates content length and
removes transfer/encoding framing. The ingress exposes only a generic no-store
receipt and accepted 2xx/4xx/5xx status, never handler output, redirect headers,
@@ -110,9 +139,13 @@ Prepare a pinned installable artifact and rollback/state-preservation/health pla
row, SHARED identity and revocation. HOME/XDG/config and representative child
Vault-path writes are test-owned; credentials are synthetic. The existing
`check_show_router.mjs` invokes this test using its already-built pinned
- Runtime, so mocks are not the only CI boundary evidence.
-- Local validation: 594 existing Show/mutation tests passed. Focused new
- registration/admission/transport tests and the pinned real integration passed;
+ Runtime, so mocks are not the only CI boundary evidence. The real chain also
+ sets upper/lower HTTP/HTTPS/ALL proxy variables to a test-owned poison proxy
+ with empty upper/lower NO_PROXY. Health, capabilities and exact signed payload
+ delivery succeed; the proxy receives no traffic.
+- Local validation after the first correction: 706 focused tests passed
+ (78 new boundary, 30 Runtime protocol, 594 Show/mutation, four legacy guards),
+ plus 69 selected Store/access tests and the pinned real integration;
final PR/CI evidence is recorded in the delivery report. No service deployment,
signing key commissioning, hook registration or external delivery is claimed.
diff --git a/storage/db.py b/storage/db.py
index 22b2d1220..9c28be208 100644
--- a/storage/db.py
+++ b/storage/db.py
@@ -29,9 +29,11 @@ def sqlite_url(db_path: Path | None = None) -> str:
return URL.create("sqlite", database=str(path)).render_as_string(hide_password=False)
-def create_sqlite_engine(db_path: Path | None = None) -> Engine:
+def create_sqlite_engine(db_path: Path | None = None, *, read_only: bool = False) -> Engine:
+ """Open normal state, or existing state without creation or journal changes."""
path = _resolve_sqlite_path(db_path)
- path.parent.mkdir(parents=True, exist_ok=True)
+ if not read_only:
+ path.parent.mkdir(parents=True, exist_ok=True)
# ``hide_parameters`` keeps bound values out of ``str(exc)`` on every
# SQLAlchemy error. Those values are the user's identity and access-control
# data -- emails, subjects, instance and scope ids, serialized authorization
@@ -41,12 +43,17 @@ def create_sqlite_engine(db_path: Path | None = None) -> Engine:
# this is the only ``create_engine`` in the codebase, so every engine
# inherits it. The statement text, the traceback, and the underlying sqlite3
# error all survive, which is what a diagnostic actually needs.
- engine = create_engine(sqlite_url(path), future=True, hide_parameters=True)
+ url = (
+ URL.create("sqlite", database=path.as_uri(), query={"mode": "ro", "uri": "true"})
+ if read_only else sqlite_url(path)
+ )
+ engine = create_engine(url, future=True, hide_parameters=True)
@event.listens_for(engine, "connect")
def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
cursor = dbapi_connection.cursor()
- cursor.execute("PRAGMA journal_mode = WAL")
+ if not read_only:
+ cursor.execute("PRAGMA journal_mode = WAL")
cursor.execute("PRAGMA foreign_keys = ON")
cursor.execute("PRAGMA busy_timeout = 5000")
cursor.close()
diff --git a/tests/test_show_api.py b/tests/test_show_api.py
index 688fbd588..4d87d285b 100644
--- a/tests/test_show_api.py
+++ b/tests/test_show_api.py
@@ -357,3 +357,209 @@ async def test_handler_responses_are_secret_free_and_never_redirect(ingress, mon
assert response.json() == ({"ok": True} if status == 202 else {"error": "show_server_api_rejected"})
assert "location" not in response.headers and "set-cookie" not in response.headers
assert response.headers["cache-control"] == "no-store"
+
+
[email protected]("failure_site", ["init", "lookup", "close"])
+async def test_admission_datastore_failures_never_escape_public_boundary(ingress, monkeypatch, failure_site):
+ manager = fake_manager(monkeypatch)
+ closed = []
+
+ class FailedStore:
+ def __init__(self, *, read_only):
+ assert read_only
+ if failure_site == "init":
+ raise OSError("fixture private constructor database path and credential")
+
+ def get_by_share_id(self, share_id):
+ if failure_site == "lookup":
+ raise OSError("fixture private lookup database path and credential")
+ return ingress.page
+
+ def close(self):
+ closed.append(True)
+ if failure_site == "close":
+ raise OSError("fixture private close database path and credential")
+
+ monkeypatch.setattr(show_api, "ShowPageStore", FailedStore)
+ response = await post(ingress)
+ assert response.status_code == 503
+ assert response.json() == {"error": "show_server_api_rejected"}
+ assert response.headers["cache-control"] == "no-store"
+ assert "set-cookie" not in response.headers
+ assert len(closed) == (0 if failure_site == "init" else 1)
+ manager.request.assert_not_called()
+
+
[email protected]("failure_site", ["resolver", "earlier_hook"])
+async def test_total_deadline_interrupts_initial_admission(ingress, monkeypatch, failure_site):
+ import threading
+ import time
+
+ manager = fake_manager(monkeypatch)
+ entered = threading.Event()
+ release = threading.Event()
+ finished = threading.Event()
+ original = show_api.resolve_server_api
+
+ def stalled(*args, **kwargs):
+ entered.set()
+ try:
+ assert release.wait(2), "test failed to release storage worker"
+ return original(*args, **kwargs) if failure_site == "resolver" else None
+ finally:
+ finished.set()
+
+ if failure_site == "resolver":
+ monkeypatch.setattr(show_api, "resolve_server_api", stalled)
+ else:
+ monkeypatch.setattr(ui_server.app, "_before_request_handlers", [stalled, *ui_server.app._before_request_handlers])
+ monkeypatch.setattr(show_api, "TOTAL_TIMEOUT_SECONDS", 0.05)
+ started = time.monotonic()
+ try:
+ response = await post(ingress)
+ assert entered.is_set()
+ assert response.status_code == 504
+ assert response.headers["cache-control"] == "no-store"
+ assert "set-cookie" not in response.headers
+ assert time.monotonic() - started < 0.75
+ manager.request.assert_not_called()
+ finally:
+ release.set()
+ assert await asyncio.to_thread(finished.wait, 2)
+ await asyncio.sleep(0)
+ manager.request.assert_not_called()
+
+
+async def test_earlier_admission_error_has_generic_receipt(ingress, monkeypatch):
+ def failed_hook():
+ raise RuntimeError("fixture private diagnostic")
+ monkeypatch.setattr(ui_server.app, "_before_request_handlers", [failed_hook, *ui_server.app._before_request_handlers])
+ response = await post(ingress)
+ assert response.status_code == 503
+ assert response.json() == {"error": "show_server_api_rejected"}
+ assert response.headers["cache-control"] == "no-store"
+ assert "set-cookie" not in response.headers
+
+
+async def test_unregistered_browser_keeps_its_existing_handler_deadline(ingress, monkeypatch):
+ (ingress.workspace / show_api.MANIFEST_NAME).unlink()
+ monkeypatch.setattr(show_api, "TOTAL_TIMEOUT_SECONDS", 0.05)
+ manager = fake_manager(monkeypatch)
+ async def browser_handler(*args, **kwargs):
+ await asyncio.sleep(0.1)
+ return httpx.Response(200, content=b"browser result")
+ manager.request.side_effect = browser_handler
+ response = await post(ingress, headers={"Origin": "https://alex.avibe.bot"})
+ assert response.status_code == 200 and response.content == b"browser result"
+
+
[email protected]("status", [503, 504])
+def test_admission_receipt_does_not_require_dispatch_context(status):
+ response = ui_server._show_server_api_result(status)
+ assert response.status_code == status
+ assert json.loads(response.body) == {"error": "show_server_api_rejected"}
+ assert response.headers["cache-control"] == "no-store"
+ assert "set-cookie" not in response.headers
+
+
+def test_read_only_store_reuses_wal_rows_without_migration_lock(ingress, monkeypatch, hold_migration_lock_elsewhere):
+ from core import show_pages
+ from storage import migrations
+ from storage.lock import migration_lock_path_for
+
+ def forbidden(*args, **kwargs):
+ raise AssertionError("read-only admission cannot initialize or migrate")
+
+ monkeypatch.setattr(show_pages, "ensure_sqlite_state", forbidden)
+ monkeypatch.setattr(migrations, "run_migrations", forbidden)
+ with hold_migration_lock_elsewhere(migration_lock_path_for(paths.get_sqlite_state_path())):
+ assert resolve(ingress).session_id == ingress.page.session_id
+ # Explicit paths must also skip the separate run_migrations branch.
+ store = ShowPageStore(paths.get_sqlite_state_path(), read_only=True)
+ try:
+ assert store.get_by_share_id(ingress.page.share_id) == ingress.page
+ with store.engine.connect() as connection:
+ assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal"
+ assert connection.exec_driver_sql("PRAGMA busy_timeout").scalar() == 5000
+ assert store.engine.hide_parameters
+ with pytest.raises(Exception, match="readonly"):
+ connection.exec_driver_sql("CREATE TABLE forbidden_write (id integer)")
+ finally:
+ store.close()
+
+
[email protected]("kind", ["missing", "missing-parent", "directory", "schema", "corrupt"])
+async def test_unavailable_read_only_store_returns_controlled_receipt(ingress, monkeypatch, tmp_path, kind):
+ import sqlite3
+
+ db_path = tmp_path / "absent-parent" / "state.sqlite" if kind == "missing-parent" else tmp_path / "isolated.sqlite"
+ if kind == "directory":
+ db_path.mkdir()
+ elif kind == "schema":
+ with sqlite3.connect(db_path) as db:
+ db.execute("CREATE TABLE unrelated (id integer)")
+ elif kind == "corrupt":
+ db_path.write_bytes(b"fixture invalid database")
+ real_store = ShowPageStore
+ monkeypatch.setattr(show_api, "ShowPageStore", lambda *, read_only: real_store(db_path, read_only=read_only))
+ manager = fake_manager(monkeypatch)
+ response = await post(ingress)
+ assert response.status_code == 503
+ assert response.json() == {"error": "show_server_api_rejected"}
+ assert response.headers["cache-control"] == "no-store"
+ assert "set-cookie" not in response.headers
+ manager.request.assert_not_called()
+ if kind in {"missing", "missing-parent"}:
+ assert not db_path.exists()
+ if kind == "missing-parent":
+ assert not db_path.parent.exists()
+
+
+def test_read_only_factory_never_recreates_deleted_database(tmp_path):
+ import sqlite3
+ from storage.db import create_sqlite_engine
+
+ db_path = tmp_path / "deleted.sqlite"
+ with sqlite3.connect(db_path) as db:
+ db.execute("CREATE TABLE marker (id integer)")
+ engine = create_sqlite_engine(db_path, read_only=True)
+ db_path.unlink() # after factory construction, before actual SQLite connect
+ try:
+ with pytest.raises(Exception, match="unable to open"):
+ with engine.connect():
+ pytest.fail("read-only open recreated deleted state")
+ assert not db_path.exists()
+ finally:
+ engine.dispose()
+
+
+def test_read_only_uri_preserves_encoded_path_and_journal_mode(tmp_path):
+ import sqlite3
+ from storage.db import create_sqlite_engine
+
+ db_path = tmp_path / "中文 space ? mode=rw#%.sqlite"
+ with sqlite3.connect(db_path) as db:
+ db.execute("CREATE TABLE marker (value text)")
+ db.execute("INSERT INTO marker VALUES ('exact path')")
+ assert db.execute("PRAGMA journal_mode").fetchone()[0] == "delete"
+ engine = create_sqlite_engine(db_path, read_only=True)
+ try:
+ with engine.connect() as connection:
+ assert connection.exec_driver_sql("SELECT value FROM marker").scalar() == "exact path"
+ assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "delete"
+ finally:
+ engine.dispose()
+ with sqlite3.connect(db_path) as db:
+ assert db.execute("PRAGMA journal_mode").fetchone()[0] == "delete"
+
+
+def test_default_store_still_initializes_and_writes(tmp_path):
+ db_path = tmp_path / "ordinary" / "state.sqlite"
+ assert not db_path.exists()
+ store = ShowPageStore(db_path)
+ try:
+ page = store.ensure("sesdefault")
+ assert store.get(page.session_id) == page
+ assert db_path.is_file()
+ finally:
+ store.close()
diff --git a/tests/test_show_api_integration.py b/tests/test_show_api_integration.py
index cfc0cc9e8..3bfc6d922 100644
--- a/tests/test_show_api_integration.py
+++ b/tests/test_show_api_integration.py
@@ -89,6 +89,21 @@ async def test_real_ui_runtime_signed_handler_inbox(tmp_path, monkeypatch):
monkeypatch.setenv("SHOW_API_FIXTURE_ROOT", str(tmp_path))
monkeypatch.setenv("SHOW_API_FIXTURE_INBOX", str(inbox))
monkeypatch.setenv("AVIBE_ALLOW_DEV_STATE_MIGRATION", "1")
+ proxy_requests = []
+
+ async def proxy_trap(reader, writer):
+ proxy_requests.append(await reader.read(65536))
+ writer.write(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+ await writer.drain()
+ writer.close()
+ await writer.wait_closed()
+
+ proxy = await asyncio.start_server(proxy_trap, "127.0.0.1", 0)
+ proxy_url = f"http://127.0.0.1:{proxy.sockets[0].getsockname()[1]}"
+ for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
+ monkeypatch.setenv(name, proxy_url)
+ monkeypatch.setenv("NO_PROXY", "")
+ monkeypatch.setenv("no_proxy", "")
node = shutil.which("node")
assert node
manager = show_runtime.ShowRuntimeManager(
@@ -142,9 +157,12 @@ async def test_real_ui_runtime_signed_handler_inbox(tmp_path, monkeypatch):
revoked = await client.post(ingress.path, headers=headers, content=body)
assert revoked.status_code == 403
assert (paths.get_vibe_remote_dir() / "vault/fixture-write").read_text() == "synthetic"
+ assert proxy_requests == [], "Runtime loopback traffic must ignore environment proxies"
finally:
server.should_exit = True
if task is not None:
await asyncio.wait_for(task, 10)
listener.close()
manager.stop()
+ proxy.close()
+ await proxy.wait_closed()
diff --git a/tests/test_show_runtime_protocol.py b/tests/test_show_runtime_protocol.py
index a78f81e99..6b7a62864 100644
--- a/tests/test_show_runtime_protocol.py
+++ b/tests/test_show_runtime_protocol.py
@@ -263,7 +263,8 @@ def test_show_runtime_request_accepts_per_call_timeout_without_changing_connect_
async def request(self, _method, _url, *, headers, content):
return httpx.Response(200, content=b"ready")
- def client_factory(*, timeout):
+ def client_factory(*, timeout, trust_env):
+ assert trust_env is False
captured_timeouts.append(timeout)
return _AppClient()
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index a494d5a57..36d8f9c71 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -678,7 +678,10 @@ def _is_show_api_mutation() -> bool:
def _ensure_csrf_cookie(response: Response) -> Response:
- if getattr(request._request.state, "show_server_api_registration", None) is not None:
+ if (
+ getattr(request._request.state, "show_server_api_pending", False)
+ or getattr(request._request.state, "show_server_api_registration", None) is not None
+ ):
return response
if _is_current_immutable_static_asset_request():
return response
@@ -2958,6 +2961,7 @@ async def resolve_public_show_server_api():
resolve_server_api, incoming.scope.get("raw_path", b""), incoming.method,
incoming.scope.get("query_string", b""),
)
+ incoming.state.show_server_api_pending = False
return None
@@ -3199,6 +3203,12 @@ def _resolve_log_sources() -> list[dict[str, Any]]:
@app.errorhandler(Exception)
def handle_exception(e):
"""Global exception handler - ensures all errors return JSON."""
+ if (
+ getattr(request._request.state, "show_server_api_pending", False)
+ or getattr(request._request.state, "show_server_api_registration", None) is not None
+ ):
+ logger.warning("Show server API admission failed (%s)", type(e).__name__)
+ return _show_server_api_result(503)
from vibe.authorization import InstanceAuthorizationError
if isinstance(e, InstanceAuthorizationError):
@@ -15993,28 +16003,46 @@ async def _serve_show_server_api(starlette_request: FastAPIRequest, registration
@app.post("/p/{share_id}/{asset_path:path}", include_in_schema=False)
async def public_show_post(starlette_request: FastAPIRequest, share_id: str, asset_path: str):
- from core.show_api import TOTAL_TIMEOUT_SECONDS
+ from core.show_api import TOTAL_TIMEOUT_SECONDS, is_server_api_path
- starlette_request.state.show_server_api_candidate = True
- started = time.monotonic()
+ candidate = is_server_api_path(
+ starlette_request.scope.get("raw_path", b""), "POST", starlette_request.scope.get("query_string", b""),
+ )
+ starlette_request.state.show_server_api_candidate = candidate
+ starlette_request.state.show_server_api_pending = candidate
+ browser_admitted = asyncio.Event()
async def handler():
registration = getattr(starlette_request.state, "show_server_api_registration", None)
if registration is not None:
- try:
- return await asyncio.wait_for(
- _serve_show_server_api(starlette_request, registration),
- timeout=max(0, TOTAL_TIMEOUT_SECONDS - (time.monotonic() - started)),
- )
- except asyncio.TimeoutError:
- return _show_server_api_result(504)
+ return await _serve_show_server_api(starlette_request, registration)
+ browser_admitted.set()
# Preserve legacy JSON validation for non-opted-in browser POSTs, after
- # the normal Origin/CSRF/visibility hooks have made their decisions.
+ # the normal request protection hooks have made their decisions.
request._body_present = bool(await starlette_request.body())
await request.load_json()
return await serve_public_show_page(share_id, asset_path)
- return await app.dispatch_native_request(starlette_request, handler, parse_json=False)
+ dispatch = app.dispatch_native_request(starlette_request, handler, parse_json=False)
+ if not candidate:
+ return await dispatch
+ # Bound the entire admission, including the first storage lookup and all
+ # preceding hooks. Once normal browser admission is established, preserve
+ # that route's existing configured timeout instead of imposing ingress's.
+ dispatch_task = asyncio.create_task(dispatch)
+ browser_task = asyncio.create_task(browser_admitted.wait())
+ try:
+ done, _ = await asyncio.wait(
+ (dispatch_task, browser_task), timeout=TOTAL_TIMEOUT_SECONDS, return_when=asyncio.FIRST_COMPLETED,
+ )
+ if not done:
+ return _show_server_api_result(504)
+ return await dispatch_task
+ finally:
+ for task in (dispatch_task, browser_task):
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(dispatch_task, browser_task, return_exceptions=True)
@app.route(