Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -350,10 +350,10 @@ control-agent-server api POST /api/canvas-extensions/installed/qa-headers/backen
`localhost:PORT` is the same server but not the ingress origin, so both
routes answer 421, and `X-Forwarded-Host` naming the ingress does not help;
the same cookie on the ingress host gets 200.
- **Forwarded proto (`F29.session-forwarded-proto`), known bug.** With
`trust_forwarded_headers` off (the default), the request's own scheme should
decide the origin (`bridge.py` `_request_origin`, `config.py`), so a
client-supplied `X-Forwarded-Proto: https` must not change it.
- **Forwarded proto (`F29.session-forwarded-proto`).** With
`trust_forwarded_headers` off (the default), the request's own scheme
decides the origin (`bridge.py` `_request_origin`, `config.py`), so a
client-supplied `X-Forwarded-Proto: https` does not change it.
```sh
FP=$(control-agent-server api POST /app-backends/qa-backend/session --header 'Origin: http://localhost:3000' --expect 200 \
--check ingress_url eq "$S/app-backends/qa-backend/" --print-header set-cookie | sed -n 's/^oh_app_backend_session=\([^;]*\);.*/\1/p')
Expand All @@ -362,21 +362,15 @@ control-agent-server api POST /api/canvas-extensions/installed/qa-headers/backen
--check app eq qa-backend
control-agent-server api POST /app-backends/qa-backend/session --header 'Origin: http://localhost:3000' \
--header 'X-Forwarded-Proto: https' --expect 200 --check ingress_url eq "$S/app-backends/qa-backend/" \
--save F29.session-forwarded-proto/session # bug: status eq 421 && response.body.detail contains 'must use the configured ingress origin'
--save F29.session-forwarded-proto/session
control-agent-server api GET /app-backends/qa-backend/echo --auth none --cookie "oh_app_backend_session=$FP" \
--header 'X-Forwarded-Proto: https' --expect 200 --check app eq qa-backend --save F29.session-forwarded-proto/proxy # bug: status eq 421 && response.body.detail contains 'must use the configured ingress origin'
--header 'X-Forwarded-Proto: https' --expect 200 --check app eq qa-backend --save F29.session-forwarded-proto/proxy
```
The same bootstrap and proxied GET without the header answer 200 first.
Expected: 200 for both with the header too. Actual: 421 `Canvas App
request must use the configured ingress origin`, because uvicorn's
`proxy_headers` (on by
default for loopback peers, `FORWARDED_ALLOW_IPS`) rewrites the scheme
before the bridge looks at it. The same header lets a loopback client
claim `https` against an HTTPS ingress. A run launched with
`--env FORWARDED_ALLOW_IPS=192.0.2.1` (uvicorn then trusts no loopback
peer) lets the same bootstrap past the host check, which pins the cause on
the server's uvicorn configuration (`__main__.py`), not on the client.
Only peers uvicorn trusts (loopback by default) can do this.
The same bootstrap and proxied GET without the header answer 200 first,
and both still answer 200 with the header: the server starts uvicorn with
`proxy_headers` only when `trust_forwarded_headers` is on (`__main__.py`),
so uvicorn does not rewrite the scheme from `X-Forwarded-Proto` for a
loopback peer (`FORWARDED_ALLOW_IPS`) behind the setting's back.
- **Origin rules (`F29.session-origin-rules`).** Only a control origin may
bootstrap, and it must differ from the ingress origin.
```sh
Expand Down Expand Up @@ -1069,10 +1063,11 @@ control-agent-server api POST /api/canvas-extensions/installed/qa-headers/backen
- HTTP clients normalize literal `.` and `..` segments before sending
(`/app-backends/<name>/./x` arrives as `/x`), so traversal recipes use
percent-encoded forms; the bridge decodes until the value stops changing.
- uvicorn trusts `X-Forwarded-Proto` (and `X-Forwarded-For`) from loopback
peers by default (`FORWARDED_ALLOW_IPS`), independently of
`trust_forwarded_headers`, which is why `F29.session-forwarded-proto`
fails; `X-Forwarded-Host` is honored only with `trust_forwarded_headers`.
- uvicorn's `proxy_headers` (which trusts `X-Forwarded-Proto` and
`X-Forwarded-For` from `FORWARDED_ALLOW_IPS` peers, loopback by default)
is on only when `trust_forwarded_headers` is; with it off, neither header
changes the request scheme or client address, and `X-Forwarded-Host` is
never honored either.
- Control origins from `allow_cors_origins` must match the listed origin
exactly after normalization (scheme, host and port; a default port may be
omitted), `allow_cors_origin_regex` must match the whole `Origin` value,
Expand Down
43 changes: 33 additions & 10 deletions openhands-agent-server/openhands/agent_server/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,47 @@
_LOOPBACK_HOST = "127.0.0.1"


def _auth_enabled() -> bool:
"""Return True when at least one session API key is configured.
def _load_server_config():
"""Resolve the effective agent-server config, or ``None`` if it fails.

Keys may come from the ``SESSION_API_KEY`` / ``OH_SESSION_API_KEYS_0``
environment variables or from the agent-server config file, so we resolve
the effective config rather than checking a single source.
Settings may come from environment variables or from the agent-server
config file, so we resolve the effective config rather than checking a
single source.
"""
from openhands.agent_server.config import load_config

try:
config = load_config()
return load_config()
except Exception:
logger.warning(
"Failed to load agent-server config while resolving default bind "
"host; assuming no session API key is configured.",
"Failed to load agent-server config while resolving server "
"startup options; using safe defaults.",
exc_info=True,
)
return False
return bool(config.session_api_keys)
return None


def _auth_enabled() -> bool:
"""Return True when at least one session API key is configured.

Keys may come from the ``SESSION_API_KEY`` / ``OH_SESSION_API_KEYS_0``
environment variables or from the agent-server config file.
"""
config = _load_server_config()
return bool(config and config.session_api_keys)


def _trust_forwarded_headers() -> bool:
"""Return True when the operator opted into trusting forwarded headers.

uvicorn's ``proxy_headers`` rewrites the request scheme and client address
from ``X-Forwarded-Proto``/``X-Forwarded-For`` sent by any peer in
``FORWARDED_ALLOW_IPS`` (loopback by default). Tying it to
``trust_forwarded_headers`` keeps a client from changing the origin the
server derives while that setting is off.
"""
config = _load_server_config()
return bool(config and config.trust_forwarded_headers)


def _get_internal_server_url(host: str, port: int) -> str:
Expand Down Expand Up @@ -323,6 +345,7 @@ def main() -> None:
log_level=log_level,
log_config=LOGGING_CONFIG,
ws="wsproto", # Use wsproto instead of deprecated websockets implementation
proxy_headers=_trust_forwarded_headers(),
)

# Use custom LoggingServer to capture signal handling events
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def __init__(
port: int | None = None,
ssl_certfile: Path | None = None,
ssl_keyfile: Path | None = None,
proxy_headers: bool = True,
) -> None:
self.port = port or _free_port()
self.server = uvicorn.Server(
Expand All @@ -67,6 +68,7 @@ def __init__(
log_level="warning",
ssl_certfile=str(ssl_certfile) if ssl_certfile else None,
ssl_keyfile=str(ssl_keyfile) if ssl_keyfile else None,
proxy_headers=proxy_headers,
)
)
self.thread = threading.Thread(target=self.server.run, daemon=True)
Expand Down Expand Up @@ -468,6 +470,81 @@ async def run(*, trust_forwarded: bool) -> int:
assert await run(trust_forwarded=True) == 200


@pytest.mark.asyncio
@pytest.mark.parametrize(
("public_scheme", "expected_status"),
[
# Plain-HTTP ingress: the header must not turn the origin into https.
("http", 200),
# HTTPS ingress reached over plain HTTP: the header must not claim it.
("https", 421),
],
)
async def test_untrusted_forwarded_proto_does_not_change_origin_on_launch_config(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
public_scheme: str,
expected_status: int,
) -> None:
"""With `trust_forwarded_headers` off, `X-Forwarded-Proto` from a loopback
client leaves the request origin alone under the server's real uvicorn
launch options.

Regression test: `__main__` left uvicorn's `proxy_headers` on, so uvicorn
rewrote the scheme from `X-Forwarded-Proto` for loopback peers before
`_request_origin` read it.
"""
from openhands.agent_server.__main__ import _trust_forwarded_headers

config_file = tmp_path / "config.json"
config_file.write_text('{"trust_forwarded_headers": false}')
monkeypatch.setenv("OPENHANDS_AGENT_SERVER_CONFIG_PATH", str(config_file))

backend = FastAPI()

@backend.get("/echo")
async def echo() -> JSONResponse:
return JSONResponse({"app": APP_NAME})

with _LiveServer(backend) as backend_server:
bridge_port = _free_port()
public_url = f"{public_scheme}://127.0.0.1:{bridge_port}"
app = FastAPI()
app.state.config = Config(
session_api_keys=[CONTROL_KEY],
allow_cors_origins=[CANVAS_ORIGIN],
app_backend_public_url=public_url,
)
app.state.app_backend_session_store = AppBackendSessionStore()
app.state.canvas_extension_backend_manager = _ReadyBackendManager(
("127.0.0.1", backend_server.port)
)
app.include_router(app_backend_bridge_router)
with _LiveServer(
app, port=bridge_port, proxy_headers=_trust_forwarded_headers()
):
root = f"http://127.0.0.1:{bridge_port}/app-backends/{APP_NAME}"
async with httpx.AsyncClient() as client:
bootstrap = await client.post(
f"{root}/session",
headers={**_bootstrap_headers(), "X-Forwarded-Proto": "https"},
)
assert bootstrap.status_code == expected_status
if expected_status != 200:
return
cookie = bootstrap.cookies.get(APP_BACKEND_SESSION_COOKIE_NAME)
assert cookie
proxied = await client.get(
f"{root}/echo",
headers={
"Cookie": f"{APP_BACKEND_SESSION_COOKIE_NAME}={cookie}",
"X-Forwarded-Proto": "https",
},
)
assert proxied.status_code == 200
assert proxied.json() == {"app": APP_NAME}


@pytest.mark.asyncio
async def test_backend_switch_invalidates_existing_session(live_bridge) -> None:
client: httpx.AsyncClient = live_bridge.client
Expand Down
41 changes: 41 additions & 0 deletions tests/agent_server/test_preload_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,3 +492,44 @@ def test_auth_enabled_ignores_empty_env_key(monkeypatch, tmp_path):
monkeypatch.delenv("SESSION_API_KEY", raising=False)
monkeypatch.setenv("OH_SESSION_API_KEYS_0", "")
assert _auth_enabled() is False


@pytest.mark.parametrize(
("config_json", "expected"),
[
("{}", False),
('{"trust_forwarded_headers": false}', False),
('{"trust_forwarded_headers": true}', True),
],
)
def test_main_ties_uvicorn_proxy_headers_to_trust_forwarded_headers(
monkeypatch, tmp_path, config_json, expected
):
"""uvicorn rewrites the request scheme from X-Forwarded-Proto only when
trust_forwarded_headers is on, so a client cannot change the origin the
Canvas bridge derives while it is off."""
cfg = tmp_path / "config.json"
cfg.write_text(config_json)
monkeypatch.setenv("OPENHANDS_AGENT_SERVER_CONFIG_PATH", str(cfg))
monkeypatch.delenv("SESSION_API_KEY", raising=False)
monkeypatch.delenv("OH_SESSION_API_KEYS_0", raising=False)
captured: dict = {}

def capture_config(app, **kwargs):
captured.update(kwargs)
return MagicMock()

with (
patch("sys.argv", ["prog", "--port", "4321"]),
patch("openhands.agent_server.__main__.preload_modules"),
patch("openhands.agent_server.__main__._setup_crash_diagnostics"),
patch("openhands.agent_server.__main__.LoggingServer") as mock_server,
patch("openhands.agent_server.__main__.Config", side_effect=capture_config),
):
mock_server.return_value.run.side_effect = SystemExit(0)
from openhands.agent_server.__main__ import main

with pytest.raises(SystemExit):
main()

assert captured["proxy_headers"] is expected
Loading