Skip to content

Commit d75a44b

Browse files
rustyconoverclaude
andcommitted
hosted: refuse stdio and granian; cap what waitress buffers before auth
Orchard hosted mode (VGI_ORCHARD_HOSTED=1), two fixes found by the SDK-neutral conformance harness (vgi test/hosted/): - stdio is refused like --unix and --tcp: Worker.main without --http and vgi-serve without --http both exit with "only --http is allowed". - Waitress reads a whole request body before the WSGI app (and so the Pass check) runs, up to its 1 GiB default. In hosted mode its max_request_body_size is now the worker's request cap: the explicit VGI_RPC_MAX_REQUEST_BYTES, or HOSTED_DEFAULT_MAX_REQUEST_BYTES (32 MiB) when unset, which is also advertised (VGI-Max-Request-Bytes) and enforced, so larger requests take upload URLs. A Content-Length over the cap gets 413 before any body is read. Both waitress paths (vgi-serve and Worker.main) apply it. - granian has no body cap, so --server granian is refused in hosted mode. The remaining exposure, at most one capped body per open connection before the 401, is documented in docs/authentication.md. Tests cover stdio on both entry points, granian, the advertised default, 413 for over-cap bodies on both waitress paths, and the cap resolution. scripts/hosted_conformance.sh adds stdio and granian to the must-refuse commands, and CI pins the updated harness. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 834021a commit d75a44b

7 files changed

Lines changed: 160 additions & 17 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ jobs:
189189
name: Orchard hosted-mode conformance
190190
runs-on: ubuntu-latest
191191
env:
192-
VGI_HOSTED_REF: 2957674e1167abf884fbd0d7e159472afa31291c
192+
VGI_HOSTED_REF: fce57984a7e8ea35f9dcd4a034b5ed37c85ca5c5
193193
steps:
194194
- uses: actions/checkout@v7
195195

‎docs/authentication.md‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,10 @@ is refused. It also refuses to start when any other way in is configured:
112112
- `VGI_OAUTH_RESOURCE` (a Field Worker never advertises `resource_metadata`);
113113
- `VGI_PROXY_PROOF_MODE` other than `off`, or Iroh / peer identity;
114114
- a custom `authenticate` callback passed to `create_app`;
115-
- `--tcp`, `--unix` or `--iroh-raw-upstream`, which carry no Pass;
115+
- stdio (no `--http`, for both `vgi-serve` and `Worker.main`), `--tcp`, `--unix`
116+
or `--iroh-raw-upstream`, which carry no Pass;
117+
- `--server granian`, which cannot cap a request body before authentication
118+
(see below);
116119
- a `VGI_ORCHARD_HOSTED` value other than `1`/`0`/`true`/`false`/`yes`/`no`/`on`/`off`.
117120

118121
**Verification:**
@@ -146,7 +149,17 @@ VGI-Supported-Encodings: ... (and the other VGI capability headers)
146149
There is no `resource_metadata` in the challenge. If the JWKS cannot be
147150
fetched, the answer is 503 with `Retry-After` instead: the worker cannot tell
148151
whether the Pass is valid, so it does not claim that it isn't. Authentication
149-
runs before the request body is read, size-checked or decompressed. CORS is
152+
runs before the app reads, size-checks or decompresses the request body.
153+
154+
**Request-body cap.** Waitress receives a whole request body before it calls
155+
the app, so before the Pass is checked. In hosted mode its buffer limit is the
156+
worker's request cap: `VGI_RPC_MAX_REQUEST_BYTES`, or 32 MiB when that is
157+
unset. The cap is advertised as `VGI-Max-Request-Bytes`, and larger requests
158+
go through upload URLs. A request whose `Content-Length` is over the cap gets
159+
waitress's 413 before any of the body is read. What remains is bounded: a
160+
caller without a Pass can make the worker hold at most one capped body per
161+
open connection (waitress accepts up to 100 connections by default) until
162+
the 401. granian has no such cap, so hosted mode refuses `--server granian`. CORS is
150163
open (`Access-Control-Allow-Origin: *`), because the only credential is the
151164
bearer Pass. The `Authorization` header is never logged, including under
152165
`--debug`.

‎scripts/hosted_conformance.sh‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
# --streaming-body, --only 'jwks.*'). Runs from the project env
1111
# (`uv sync --all-extras`), which has the client, joserfc and cryptography.
1212
#
13-
# No stdio --refuse-cmd: Worker.main refuses --unix and --tcp in hosted mode
14-
# but still serves stdio (see the harness README).
13+
# Must-refuse commands: stdio (Worker.main and vgi-serve without --http),
14+
# --unix, --tcp, --iroh-raw-upstream, and --server granian (no body cap).
1515
set -euo pipefail
1616

1717
cd "$(dirname "$0")/.."
@@ -30,6 +30,9 @@ FIXTURE="$(printf '%q' "$PY") -m vgi._test_fixtures.orchard_hosted"
3030
exec "$PY" "$HARNESS" \
3131
--worker-cwd "$PWD" \
3232
--worker-cmd "$WORKER --http --host 127.0.0.1 --port 0 --debug" \
33+
--refuse-cmd "$FIXTURE" \
34+
--refuse-cmd "$WORKER" \
35+
--refuse-cmd "$WORKER --http --server granian --host 127.0.0.1 --port 0" \
3336
--refuse-cmd "$FIXTURE --unix /tmp/vgi-hosted-refuse-{port}.sock" \
3437
--refuse-cmd "$FIXTURE --tcp 127.0.0.1:{port}" \
3538
--refuse-cmd "$WORKER --iroh-raw-upstream 0" \

‎tests/test_orchard_hosted.py‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import base64
2121
import json
2222
import os
23+
import socket
2324
import subprocess
2425
import sys
2526
import threading
@@ -370,6 +371,21 @@ def test_zz_authorization_never_logged(self, worker: _Worker) -> None:
370371
assert token.split(".")[2] not in text
371372
assert "Bearer " not in text
372373

374+
def test_body_cap_advertised(self, worker: _Worker) -> None:
375+
"""With VGI_RPC_MAX_REQUEST_BYTES unset, hosted mode advertises its 32 MiB default."""
376+
from vgi.hosted import HOSTED_DEFAULT_MAX_REQUEST_BYTES
377+
378+
status, headers, _ = _request(worker, "HEAD", "/health")
379+
assert status == 200
380+
assert headers.get("vgi-max-request-bytes") == str(HOSTED_DEFAULT_MAX_REQUEST_BYTES)
381+
382+
@pytest.mark.parametrize("excess", [1, 64 * 1024**3])
383+
def test_body_over_cap_refused_unread(self, worker: _Worker, excess: int) -> None:
384+
"""A body declared over the cap gets 413 at once, before any of it is read or buffered."""
385+
from vgi.hosted import HOSTED_DEFAULT_MAX_REQUEST_BYTES
386+
387+
assert _declared_body_status(worker.url, HOSTED_DEFAULT_MAX_REQUEST_BYTES + excess) == 413
388+
373389
@staticmethod
374390
def _assert_401(status: int, headers: dict[str, str]) -> None:
375391
assert status == 401
@@ -379,6 +395,29 @@ def _assert_401(status: int, headers: dict[str, str]) -> None:
379395
assert "vgi-accept-max-response-bytes-support" in headers or "vgi-externalization-enabled" in headers
380396

381397

398+
def _declared_body_status(url: str, length: int) -> int:
399+
"""Declare a body of *length* bytes, send none of it, and return the status.
400+
401+
Nothing follows the headers, so a server that waits for the body before
402+
answering times out here (and the test fails) instead of answering.
403+
"""
404+
port = int(url.rsplit(":", 1)[1])
405+
head = (
406+
f"POST /vgi.v3/catalog_attach HTTP/1.1\r\nHost: 127.0.0.1\r\n"
407+
f"Content-Type: application/vnd.apache.arrow.stream\r\nContent-Length: {length}\r\n"
408+
"Connection: close\r\n\r\n"
409+
)
410+
with socket.create_connection(("127.0.0.1", port), timeout=10) as sock:
411+
sock.sendall(head.encode())
412+
data = b""
413+
while b"\r\n" not in data:
414+
chunk = sock.recv(4096)
415+
if not chunk:
416+
break
417+
data += chunk
418+
return int(data.split(b" ", 2)[1])
419+
420+
382421
# ---------------------------------------------------------------------------
383422
# Startup refusals
384423
# ---------------------------------------------------------------------------
@@ -467,9 +506,13 @@ def test_unrecognised_flag_value(self) -> None:
467506
"""A typo in VGI_ORCHARD_HOSTED refuses instead of meaning 'off'."""
468507
assert "VGI_ORCHARD_HOSTED" in _refused(_env(_JWKS, VGI_ORCHARD_HOSTED="yes please"))
469508

470-
@pytest.mark.parametrize("flag", [["--tcp", "127.0.0.1:0"], ["--unix", "/tmp/vgi-orchard-hosted-refuse.sock"]])
509+
@pytest.mark.parametrize(
510+
"flag",
511+
[[], ["--tcp", "127.0.0.1:0"], ["--unix", "/tmp/vgi-orchard-hosted-refuse.sock"]],
512+
ids=["stdio", "tcp", "unix"],
513+
)
471514
def test_unauthenticated_transports(self, flag: list[str]) -> None:
472-
"""Worker.main refuses --tcp and --unix: they carry no Pass."""
515+
"""Worker.main refuses stdio (the default), --tcp and --unix: they carry no Pass."""
473516
proc = subprocess.run(
474517
[sys.executable, "-m", FIXTURE, *flag],
475518
cwd=_REPO,
@@ -481,6 +524,19 @@ def test_unauthenticated_transports(self, flag: list[str]) -> None:
481524
assert proc.returncode != 0
482525
assert "only --http" in proc.stderr
483526

527+
def test_vgi_serve_stdio(self) -> None:
528+
"""vgi-serve without --http (stdio) refuses in hosted mode."""
529+
argv = [sys.executable, "-m", "vgi.serve", f"{FIXTURE}:OrchardHostedWorker"]
530+
proc = subprocess.run(
531+
argv, cwd=_REPO, env=_env(_JWKS), stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60
532+
)
533+
assert proc.returncode != 0
534+
assert "only --http" in proc.stderr
535+
536+
def test_granian_refused(self) -> None:
537+
"""--server granian refuses: it cannot cap a body before authentication runs."""
538+
assert "granian" in _refused(_env(_JWKS), "--server", "granian")
539+
484540
def test_iroh_raw_upstream(self) -> None:
485541
"""vgi-serve refuses --iroh-raw-upstream in hosted mode."""
486542
argv = [sys.executable, "-m", "vgi.serve", f"{FIXTURE}:OrchardHostedWorker", "--iroh-raw-upstream", "0"]
@@ -522,6 +578,10 @@ def test_worker_main_http_serves(self, jwks_uri: str) -> None:
522578
with pytest.raises(urllib.error.HTTPError) as info:
523579
urllib.request.urlopen(urllib.request.Request(url + "/health"), timeout=30)
524580
assert info.value.code == 401
581+
# Worker.main's waitress is capped too.
582+
from vgi.hosted import HOSTED_DEFAULT_MAX_REQUEST_BYTES
583+
584+
assert _declared_body_status(url, HOSTED_DEFAULT_MAX_REQUEST_BYTES + 1) == 413
525585
finally:
526586
proc.terminate()
527587
proc.wait(timeout=15)
@@ -571,6 +631,19 @@ def test_jwt_algorithms_outside_hosted_mode(self, monkeypatch: pytest.MonkeyPatc
571631
with pytest.raises(SystemExit):
572632
_resolve_jwt_authenticate()
573633

634+
def test_request_cap_defaults(self, monkeypatch: pytest.MonkeyPatch) -> None:
635+
"""Hosted mode always has a request cap; an explicit one wins; outside it, none by default."""
636+
from vgi.hosted import HOSTED_DEFAULT_MAX_REQUEST_BYTES, hosted_waitress_limits
637+
from vgi.serve import resolve_blob_vendor_http_config
638+
639+
assert resolve_blob_vendor_http_config({}).max_request_bytes is None
640+
hosted = {"VGI_ORCHARD_HOSTED": "1"}
641+
assert resolve_blob_vendor_http_config(hosted).max_request_bytes == HOSTED_DEFAULT_MAX_REQUEST_BYTES
642+
explicit = {**hosted, "VGI_RPC_MAX_REQUEST_BYTES": "65536"}
643+
assert resolve_blob_vendor_http_config(explicit).max_request_bytes == 65536
644+
assert hosted_waitress_limits(65536) == {"max_request_body_size": 65536}
645+
assert hosted_waitress_limits(None) == {"max_request_body_size": HOSTED_DEFAULT_MAX_REQUEST_BYTES}
646+
574647
@pytest.mark.parametrize("value", ["0", "false", "", "off"])
575648
def test_off_values(self, monkeypatch: pytest.MonkeyPatch, value: str) -> None:
576649
"""Hosted mode is off for the usual false values."""

‎vgi/hosted.py‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828

2929
import os
3030
import sys
31-
from collections.abc import Callable, Sequence
31+
from collections.abc import Callable, Mapping, Sequence
3232
from dataclasses import dataclass
3333
from typing import TYPE_CHECKING, Any, NoReturn
3434

@@ -38,6 +38,7 @@
3838

3939
__all__ = [
4040
"HOSTED_CHALLENGE",
41+
"HOSTED_DEFAULT_MAX_REQUEST_BYTES",
4142
"HOSTED_ENV",
4243
"HostedConfig",
4344
"hosted_authenticate",
@@ -67,6 +68,12 @@
6768
#: Timeout for each JWKS request.
6869
JWKS_FETCH_TIMEOUT_SECONDS = 10.0
6970

71+
#: Request-body cap in hosted mode when ``VGI_RPC_MAX_REQUEST_BYTES`` is unset.
72+
#: It is advertised (``VGI-Max-Request-Bytes``), enforced by the app, and is
73+
#: also the most the HTTP server buffers before authentication runs. Larger
74+
#: requests go through upload URLs.
75+
HOSTED_DEFAULT_MAX_REQUEST_BYTES = 32 * 1024 * 1024
76+
7077
_TRUE = frozenset({"1", "true", "yes", "on"})
7178
_FALSE = frozenset({"", "0", "false", "no", "off"})
7279

@@ -87,9 +94,12 @@ def refuse_in_hosted_mode(reason: str) -> NoReturn:
8794
sys.exit(1)
8895

8996

90-
def hosted_mode_enabled() -> bool:
97+
def hosted_mode_enabled(env: Mapping[str, str] | None = None) -> bool:
9198
"""Return whether ``VGI_ORCHARD_HOSTED`` turns hosted mode on.
9299
100+
Args:
101+
env: Environment mapping (defaults to ``os.environ``).
102+
93103
Returns:
94104
True for ``1``/``true``/``yes``/``on`` (any case), False when unset
95105
or ``0``/``false``/``no``/``off``.
@@ -100,7 +110,7 @@ def hosted_mode_enabled() -> bool:
100110
start a worker without authentication.
101111
102112
"""
103-
raw = os.environ.get(HOSTED_ENV)
113+
raw = (os.environ if env is None else env).get(HOSTED_ENV)
104114
if raw is None:
105115
return False
106116
value = raw.strip().lower()
@@ -245,6 +255,25 @@ def check_environment_conflicts() -> None:
245255
refuse_in_hosted_mode("VGI_PROXY_PROOF_MODE must be off; hosted workers authenticate by Pass only.")
246256

247257

258+
def hosted_waitress_limits(max_request_bytes: int | None) -> dict[str, int]:
259+
"""Waitress settings that cap what it buffers before the app runs.
260+
261+
Waitress reads a whole request body before it calls the WSGI app, so
262+
before the Pass is checked. Its own default cap is 1 GiB; in hosted mode
263+
it is the worker's request cap instead, so a caller without a Pass can
264+
make the worker hold at most one capped body per connection. A larger
265+
``Content-Length`` gets waitress's 413 before any of the body is read.
266+
267+
Args:
268+
max_request_bytes: The effective request cap (hosted mode always has one).
269+
270+
Returns:
271+
Keyword arguments to splat into ``waitress.serve`` / ``create_server``.
272+
273+
"""
274+
return {"max_request_body_size": max_request_bytes or HOSTED_DEFAULT_MAX_REQUEST_BYTES}
275+
276+
248277
#: The shortest VGI_SIGNING_KEY a hosted worker accepts.
249278
MIN_SIGNING_KEY_BYTES = 32
250279

‎vgi/serve.py‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
from typing import TYPE_CHECKING, Any, Literal
3939

4040
from vgi import idle_exit as _idle_exit
41-
from vgi.hosted import HOSTED_CHALLENGE, hosted_mode_enabled
41+
from vgi.hosted import HOSTED_CHALLENGE, HOSTED_DEFAULT_MAX_REQUEST_BYTES, hosted_mode_enabled
4242
from vgi.logging_config import LogFormat, LogLevel
4343
from vgi.profiling import maybe_start_profile
4444

@@ -233,7 +233,9 @@ def resolve_blob_vendor_http_config(env: Mapping[str, str] | None = None) -> Blo
233233
(``VGI_RPC_EXTERNALIZE_THRESHOLD_BYTES``, default 1 MiB;
234234
``VGI_RPC_EXTERNAL_COMPRESSION``) and client upload URLs
235235
(``VGI_RPC_MAX_UPLOAD_BYTES``). ``VGI_RPC_MAX_REQUEST_BYTES`` is read
236-
either way: it is an explicit operator setting.
236+
either way: it is an explicit operator setting. In Orchard hosted mode it
237+
defaults to ``HOSTED_DEFAULT_MAX_REQUEST_BYTES`` (32 MiB), because the
238+
HTTP server buffers that much before authentication runs.
237239
238240
Args:
239241
env: Environment mapping (defaults to ``os.environ``).
@@ -248,6 +250,8 @@ def resolve_blob_vendor_http_config(env: Mapping[str, str] | None = None) -> Blo
248250
"""
249251
environ = os.environ if env is None else env
250252
max_request_bytes = _positive_int_env(environ, "VGI_RPC_MAX_REQUEST_BYTES")
253+
if max_request_bytes is None and hosted_mode_enabled(environ):
254+
max_request_bytes = HOSTED_DEFAULT_MAX_REQUEST_BYTES
251255
if not environ.get("VGI_BLOB_VENDOR_URL", "").strip():
252256
return BlobVendorHttpConfig(max_request_bytes=max_request_bytes)
253257
from vgi_rpc.vendor import external_config_from_env, max_upload_bytes_from_env
@@ -690,6 +694,10 @@ def serve(
690694
from vgi.hosted import refuse_in_hosted_mode
691695

692696
refuse_in_hosted_mode("only --http is allowed; --iroh-raw-upstream carries no Pass.")
697+
if not http and iroh_raw_upstream is None and hosted_mode_enabled():
698+
from vgi.hosted import refuse_in_hosted_mode
699+
700+
refuse_in_hosted_mode("only --http is allowed; stdio carries no Pass.")
693701
if (iroh_raw_upstream is not None or iroh_trusted_proxy) and iroh_issuer is None:
694702
sys.exit("Iroh bridge options require --iroh-issuer")
695703
trusted_iroh_proxies = tuple(iroh_trusted_proxy or ["127.0.0.1"])
@@ -1623,6 +1631,13 @@ def _serve_http(
16231631
iroh_bridge_issuer=iroh_bridge_issuer,
16241632
)
16251633
_hosted.resolve_hosted_config()
1634+
if server == "granian":
1635+
# granian hands the app a fully read body and has no body-size
1636+
# cap, so a caller without a Pass could make it buffer anything.
1637+
_hosted.refuse_in_hosted_mode(
1638+
"--server granian cannot cap request bodies before authentication; "
1639+
"hosted workers serve with waitress (the default)."
1640+
)
16261641
port = _resolve_http_port(host, port)
16271642

16281643
# Republished as environment rather than threaded through as arguments, so
@@ -1692,7 +1707,12 @@ def _serve_http(
16921707

16931708
_tame_queue_depth_logger()
16941709
serve_kwargs: dict[str, Any] = {"host": host, "port": port, "_quiet": True}
1695-
serve_kwargs.update(waitress_arrow_tuning(resolve_blob_vendor_http_config().max_request_bytes))
1710+
max_request_bytes = resolve_blob_vendor_http_config().max_request_bytes
1711+
serve_kwargs.update(waitress_arrow_tuning(max_request_bytes))
1712+
if hosted_mode_enabled():
1713+
from vgi.hosted import hosted_waitress_limits
1714+
1715+
serve_kwargs.update(hosted_waitress_limits(max_request_bytes))
16961716
if http_threads is not None:
16971717
serve_kwargs["threads"] = http_threads
16981718
serve_kwargs.pop("_quiet")

‎vgi/worker.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1897,12 +1897,12 @@ def _run(
18971897
if sum(x for x in (http, unix is not None, tcp is not None)) > 1:
18981898
raise typer.BadParameter("--http, --unix, and --tcp are mutually exclusive")
18991899

1900-
if (unix is not None or tcp is not None) and _hosted_mode_enabled():
1901-
# TCP and AF_UNIX carry no authentication: a hosted worker
1902-
# serves Passes over HTTP only.
1900+
if not http and _hosted_mode_enabled():
1901+
# stdio, TCP and AF_UNIX carry no authentication: a hosted
1902+
# worker serves Passes over HTTP only.
19031903
from vgi.hosted import refuse_in_hosted_mode
19041904

1905-
refuse_in_hosted_mode("only --http is allowed; --unix and --tcp carry no authentication.")
1905+
refuse_in_hosted_mode("only --http is allowed; stdio, --unix and --tcp carry no authentication.")
19061906

19071907
if http:
19081908
from vgi.serve import (
@@ -2155,6 +2155,11 @@ def _run_http(
21552155
}
21562156
if http_threads is not None:
21572157
serve_kwargs["threads"] = http_threads
2158+
if _hosted_mode_enabled():
2159+
from vgi.hosted import hosted_waitress_limits
2160+
from vgi.serve import resolve_blob_vendor_http_config
2161+
2162+
serve_kwargs.update(hosted_waitress_limits(resolve_blob_vendor_http_config().max_request_bytes))
21582163
# Same reasoning as vgi_rpc.http.server.serve_http: waitress warns per
21592164
# request whenever its queue is non-empty, which for VGI-length
21602165
# requests is the steady state rather than an exception, and costs

0 commit comments

Comments
 (0)