Skip to content
47 changes: 44 additions & 3 deletions openhands-agent-server/openhands/agent_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,18 @@
import logging
import os
from pathlib import Path
from typing import Any, ClassVar, Final, Literal

from pydantic import BaseModel, ConfigDict, Field, SecretStr, field_validator
from typing import Any, ClassVar, Final, Literal, Self

from pydantic import (
BaseModel,
ConfigDict,
Field,
ModelWrapValidatorHandler,
PrivateAttr,
SecretStr,
field_validator,
model_validator,
)

from openhands.agent_server.conversation_lease import DEFAULT_LEASE_TTL_SECONDS
from openhands.agent_server.env_parser import (
Expand Down Expand Up @@ -61,6 +70,12 @@ def _default_secret_key() -> SecretStr | None:
return None


def _is_blank_secret(value: object) -> bool:
if isinstance(value, SecretStr):
value = value.get_secret_value()
return isinstance(value, str) and not value.strip()


def _default_web_url() -> str | None:
web_url = os.getenv("OH_WEB_URL")
if web_url:
Expand Down Expand Up @@ -484,6 +499,7 @@ class Config(BaseModel):
),
)
model_config: ClassVar[ConfigDict] = {"frozen": True}
_secret_key_was_blank: bool = PrivateAttr(default=False)

@field_validator("session_api_keys")
@classmethod
Expand All @@ -492,6 +508,31 @@ def _drop_empty_session_api_keys(cls, value: list[str]) -> list[str]:
# credential; keeping it would make an empty string authenticate.
return [key for key in value if key]

@field_validator("secret_key")
@classmethod
def _empty_secret_key_is_unset(cls, value: SecretStr | None) -> SecretStr | None:
"""Treat a blank secret key (e.g. ``OH_SECRET_KEY=`` or whitespace only)
as unset, so the session-key fallback applies instead of encrypting with
a key anyone can guess."""
if _is_blank_secret(value):
return _default_secret_key()
return value

@model_validator(mode="wrap")
@classmethod
def _remember_blank_secret_key(
cls, data: Any, handler: ModelWrapValidatorHandler[Self]
) -> Self:
config = handler(data)
if isinstance(data, dict) and _is_blank_secret(data.get("secret_key")):
config._secret_key_was_blank = True
return config

@property
def secret_key_was_blank(self) -> bool:
"""Whether a blank secret key was configured (and so treated as unset)."""
return self._secret_key_was_blank

@property
def cipher(self) -> Cipher | None:
cipher = getattr(self, "_cipher", None)
Expand Down
7 changes: 6 additions & 1 deletion openhands-agent-server/openhands/agent_server/init_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ def _build_initialized_config(base: Config, req: InitRequest) -> Config:
updates: dict[str, Any] = {"deferred_init": False}
if req.session_api_keys is not None:
updates["session_api_keys"] = req.session_api_keys
if req.secret_key is not None:
# A blank secret_key is treated as unset, like a blank OH_SECRET_KEY.
if req.secret_key is not None and req.secret_key.get_secret_value().strip():
updates["secret_key"] = req.secret_key
elif req.session_api_keys and base.secret_key is None:
# Match the Config default: fall back to first session key when no
Expand Down Expand Up @@ -353,6 +354,10 @@ def check_init_api_key(
per-user runtime config."""
config: Config | None = getattr(request.app.state, "config", None)
if config is None or config.secret_key is None:
if config is not None and config.secret_key_was_blank:
# A blank key was configured but no usable key remains → fail
# closed, since no client can present a blank key.
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
# No key configured → endpoint is open. Acceptable for dev.
return
expected = config.secret_key.get_secret_value()
Expand Down
85 changes: 84 additions & 1 deletion tests/agent_server/test_config.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import json
import logging

import pytest
from pydantic import ValidationError
from pydantic import SecretStr, ValidationError

from openhands.agent_server.config import (
CONFIG_PATH_ENV,
DEFAULT_CONVERSATION_IDLE_TTL_SECONDS,
V0_SESSION_API_KEY_ENV,
V1_SESSION_API_KEY_ENV,
Config,
load_config,
)
from openhands.agent_server.init_router import InitRequest, _build_initialized_config


def test_load_config_reads_registered_marketplaces_from_env(monkeypatch, tmp_path):
Expand Down Expand Up @@ -80,3 +84,82 @@ def test_load_config_ignores_empty_session_api_key_slots(monkeypatch, tmp_path):
monkeypatch.setenv("OH_SESSION_API_KEYS_1", "")

assert load_config().session_api_keys == ["sk-oh-real"]


@pytest.fixture
def no_session_keys(monkeypatch, tmp_path):
monkeypatch.setenv(CONFIG_PATH_ENV, str(tmp_path / "missing.json"))
monkeypatch.delenv(V0_SESSION_API_KEY_ENV, raising=False)
monkeypatch.delenv(V1_SESSION_API_KEY_ENV, raising=False)


@pytest.mark.parametrize("blank", ["", " ", "\n"])
def test_empty_secret_key_env_is_treated_as_unset(
monkeypatch, caplog, no_session_keys, blank
):
monkeypatch.setenv("OH_SECRET_KEY", blank)

config = load_config()

assert config.secret_key is None
with caplog.at_level(logging.WARNING, logger="openhands.agent_server.config"):
assert config.cipher is None
assert "OH_SECRET_KEY was not defined" in caplog.text


@pytest.mark.parametrize("blank", ["", " "])
def test_empty_secret_key_env_falls_back_to_session_key(
monkeypatch, no_session_keys, blank
):
monkeypatch.setenv("OH_SECRET_KEY", blank)
monkeypatch.setenv(V1_SESSION_API_KEY_ENV, "session-key")

config = load_config()

assert config.secret_key is not None
assert config.secret_key.get_secret_value() == "session-key"
assert config.cipher is not None
assert config.cipher.secret_key == "session-key"


def test_blank_secret_key_in_config_file_is_treated_as_unset(
monkeypatch, tmp_path, no_session_keys
):
config_file = tmp_path / "config.json"
config_file.write_text(json.dumps({"secret_key": " "}))
monkeypatch.setenv(CONFIG_PATH_ENV, str(config_file))
monkeypatch.delenv("OH_SECRET_KEY", raising=False)

config = load_config()

assert config.secret_key is None
assert config.cipher is None


def test_blank_secret_key_in_constructor_is_treated_as_unset(no_session_keys):
assert Config(secret_key=SecretStr(" ")).secret_key is None
secret_key = Config(secret_key=SecretStr("real")).secret_key
assert secret_key is not None
assert secret_key.get_secret_value() == "real"


def test_secret_key_env_with_surrounding_whitespace_is_kept_verbatim(
monkeypatch, no_session_keys
):
monkeypatch.setenv("OH_SECRET_KEY", " mykey ")

cipher = load_config().cipher

assert cipher is not None
assert cipher.secret_key == " mykey "


def test_init_secret_key_with_surrounding_whitespace_is_kept_verbatim(
no_session_keys,
):
merged = _build_initialized_config(
Config(deferred_init=True), InitRequest(secret_key=SecretStr(" mykey "))
)

assert merged.secret_key is not None
assert merged.secret_key.get_secret_value() == " mykey "
50 changes: 49 additions & 1 deletion tests/agent_server/test_init_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from pydantic import SecretStr

from openhands.agent_server.api import api_lifespan, create_app
from openhands.agent_server.config import Config
from openhands.agent_server.config import CONFIG_PATH_ENV, Config, load_config
from openhands.agent_server.init_router import (
InitRequest,
InitService,
Expand Down Expand Up @@ -155,6 +155,15 @@ def test_explicit_secret_key_wins(self):
assert merged.secret_key is not None
assert merged.secret_key.get_secret_value() == "explicit-secret"

@pytest.mark.parametrize("blank", ["", " "])
def test_empty_secret_key_is_treated_as_unset(self, blank):
base = Config(deferred_init=True)
merged = _build_initialized_config(
base, InitRequest(session_api_keys=["s1"], secret_key=SecretStr(blank))
)
assert merged.secret_key is not None
assert merged.secret_key.get_secret_value() == "s1"


class TestRouterMounting:
"""Behavior of the /api/init endpoint outside the lifespan."""
Expand Down Expand Up @@ -403,6 +412,45 @@ async def test_init_without_session_keys_keeps_vscode_token(
class TestEndToEndOverLifespan:
"""Drive the whole flow through the FastAPI lifespan + TestClient."""

def test_blank_init_secret_falls_back_to_session_key(self, tmp_path):
_reset_conversation_singleton()
cfg = Config(
deferred_init=True,
conversations_path=tmp_path / "convs",
bash_events_dir=tmp_path / "bash",
)
app = create_app(cfg)
with TestClient(app) as client:
try:
response = client.post(
"/api/init",
json={
"secret_key": "",
"session_api_keys": ["user-session-key"],
},
)
assert response.status_code == 200
assert app.state.config.cipher.secret_key == "user-session-key"
finally:
_reset_conversation_singleton()

@pytest.mark.parametrize("blank", ["", " "])
def test_blank_secret_key_env_keeps_init_closed(self, tmp_path, monkeypatch, blank):
_reset_conversation_singleton()
monkeypatch.setenv(CONFIG_PATH_ENV, str(tmp_path / "missing.json"))
monkeypatch.setenv("OH_SECRET_KEY", blank)
monkeypatch.setenv("OH_DEFERRED_INIT", "true")
monkeypatch.setenv("OH_CONVERSATIONS_PATH", str(tmp_path / "convs"))
monkeypatch.setenv("OH_BASH_EVENTS_DIR", str(tmp_path / "bash"))
cfg = load_config()
assert cfg.deferred_init and cfg.secret_key is None
with TestClient(create_app(cfg)) as client:
try:
assert client.post("/api/init", json={}).status_code == 401
assert client.get("/api/init").json()["state"] == "dormant"
finally:
_reset_conversation_singleton()

@pytest.mark.parametrize("session_api_keys", [[""], ["", "user-session-key"]])
def test_init_rejects_empty_session_keys(self, tmp_path, session_api_keys):
_reset_conversation_singleton()
Expand Down
Loading