feat(network): centralize proxy settings and add MCP routing (NAN-315) (#6372)
* feat(network): share proxy settings across features and MCP (NAN-315) * fix(network): address shared proxy review regressions * test(network): align rebased OAuth fixtures with runtime admission * fix(webui): configure shared proxy without leaving connection drafts * feat(webui): add optional shared proxy authentication editor * fix(webui): align proxy save tests and loading skeleton
This commit is contained in:
1 parent
872a83340d
commit
084b6bb394
181 files changed
+3740
-807
No files matched your search
@@ -34,7 +34,8 @@
|
||||
"tools.max_session_messages_per_minute",
|
||||
"tools.webui_allow_remote_package_install",
|
||||
"tools.web.enable",
|
||||
"tools.web.proxy",
|
||||
"network.proxy",
|
||||
"tools.web.use_proxy",
|
||||
"tools.web.user_agent",
|
||||
"tools.image_generation.save_dir",
|
||||
"api.host",
|
||||
|
||||
@@ -4,6 +4,7 @@ import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
from nanobot.runtime_admission import RuntimeAdmission, RuntimeBusyError, RuntimeMaintenanceError
|
||||
from nanobot.webui.mcp_oauth_api import (
|
||||
@@ -50,14 +51,19 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
|
||||
connection = _Connection()
|
||||
received: dict[str, object] = {}
|
||||
reload_calls = 0
|
||||
cfg = _config()
|
||||
cfg.use_proxy = True
|
||||
network_config = NetworkConfig(proxy="http://proxy-a.example:8080")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.mcp_oauth_api.validate_url_target",
|
||||
lambda _url: (True, ""),
|
||||
)
|
||||
|
||||
async def connect(servers, _registry, *, oauth_handlers):
|
||||
async def connect(servers, _registry, *, oauth_handlers, network):
|
||||
assert set(servers) == {"xmind"}
|
||||
received["cfg"] = servers["xmind"]
|
||||
received["network"] = network
|
||||
handlers = oauth_handlers["xmind"]
|
||||
await handlers.redirect_handler(
|
||||
"https://accounts.example.com/authorize?client_id=test&state=state-123"
|
||||
@@ -86,13 +92,20 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
|
||||
|
||||
started = await manager.start(
|
||||
"xmind",
|
||||
_config(),
|
||||
cfg,
|
||||
"https://agent.example.com/auth/mcp/callback",
|
||||
reload_mcp=reload_mcp,
|
||||
network=network_config,
|
||||
)
|
||||
|
||||
assert started["status"] == "authorization_required"
|
||||
assert started["authorization_url"].startswith("https://accounts.example.com/authorize?")
|
||||
cfg.use_proxy = False
|
||||
network_config.proxy = "http://proxy-b.example:8080"
|
||||
assert received["cfg"] is not cfg
|
||||
assert received["cfg"].use_proxy is True
|
||||
assert received["network"] is not network_config
|
||||
assert received["network"].proxy == "http://proxy-a.example:8080"
|
||||
manager.submit_callback(state="state-123", code="oauth-code", error=None)
|
||||
with pytest.raises(McpOAuthError, match="expired"):
|
||||
manager.submit_callback(state="state-123", code="replayed-code", error=None)
|
||||
@@ -135,7 +148,7 @@ async def test_browser_flow_activates_tools_before_probe_cleanup_completes(
|
||||
lambda _url: (True, ""),
|
||||
)
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
async def connect(_servers, _registry, *, oauth_handlers, network):
|
||||
handlers = oauth_handlers["linear"]
|
||||
await handlers.redirect_handler(
|
||||
"https://accounts.example.com/authorize?client_id=test&state=blocked-close"
|
||||
@@ -202,7 +215,7 @@ async def test_browser_flow_remains_busy_through_cancelled_or_expired_cleanup(
|
||||
if expire:
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api._FLOW_TTL_S", 0)
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
async def connect(_servers, _registry, *, oauth_handlers, network):
|
||||
handlers = oauth_handlers["linear"]
|
||||
await handlers.redirect_handler("https://accounts.example.com/auth?state=pending")
|
||||
try:
|
||||
@@ -256,7 +269,7 @@ async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
|
||||
lambda _url: (True, ""),
|
||||
)
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
async def connect(_servers, _registry, *, oauth_handlers, network):
|
||||
handlers = oauth_handlers["linear"]
|
||||
received["redirect_uri"] = handlers.redirect_uri
|
||||
await handlers.redirect_handler(
|
||||
@@ -329,7 +342,7 @@ async def test_browser_flow_surfaces_provider_denial_without_callback_descriptio
|
||||
lambda _url: (True, ""),
|
||||
)
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
async def connect(_servers, _registry, *, oauth_handlers, network):
|
||||
handlers = oauth_handlers["notion"]
|
||||
await handlers.redirect_handler("https://accounts.example.com/auth?state=deny-state")
|
||||
await handlers.callback_handler()
|
||||
@@ -375,7 +388,7 @@ async def test_browser_flow_blocks_unsafe_authorization_url(
|
||||
lambda _url: (url_is_safe, "private address"),
|
||||
)
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
async def connect(_servers, _registry, *, oauth_handlers, network):
|
||||
await oauth_handlers["linear"].redirect_handler(authorization_url)
|
||||
return {}
|
||||
|
||||
|
||||
@@ -359,11 +359,12 @@ def test_instance_oauth_setup_saves_endpoint_before_authorization(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_use_config(tmp_path, monkeypatch)
|
||||
name, cfg = ensure_mcp_oauth_server(
|
||||
name, cfg, network = ensure_mcp_oauth_server(
|
||||
{"name": ["metabase"], "mcp_url": ["https://analytics.example.com/api/metabase-mcp"]}
|
||||
)
|
||||
assert name == "metabase"
|
||||
assert cfg.auth == "oauth"
|
||||
assert network == load_config().network
|
||||
assert cfg.url == "https://analytics.example.com/api/metabase-mcp"
|
||||
row = next(item for item in mcp_presets_payload()["presets"] if item["name"] == name)
|
||||
assert row["installed"] is True
|
||||
@@ -372,7 +373,7 @@ def test_instance_oauth_setup_saves_endpoint_before_authorization(
|
||||
config = load_config()
|
||||
config.tools.mcp_servers[name].enabled_tools = ["search"]
|
||||
save_config(config)
|
||||
_, updated = ensure_mcp_oauth_server(
|
||||
_, updated, _network = ensure_mcp_oauth_server(
|
||||
{"name": [name], "mcp_url": ["https://other.example.com/api/metabase-mcp"]}
|
||||
)
|
||||
assert updated.url == "https://other.example.com/api/metabase-mcp"
|
||||
@@ -615,7 +616,7 @@ def test_test_mcp_preset_connects_and_reports_tools(
|
||||
async def aclose(self) -> None:
|
||||
return None
|
||||
|
||||
async def fake_connect(servers, registry):
|
||||
async def fake_connect(servers, registry, *, network):
|
||||
assert list(servers) == ["playwright"]
|
||||
|
||||
class FakeTool:
|
||||
@@ -652,7 +653,7 @@ def test_test_mcp_preset_inspects_tools_outside_the_enabled_allowlist(
|
||||
async def aclose(self) -> None:
|
||||
return None
|
||||
|
||||
async def fake_connect(servers, registry):
|
||||
async def fake_connect(servers, registry, *, network):
|
||||
assert servers["playwright"].enabled_tools == ["*"]
|
||||
|
||||
class FakeTool:
|
||||
@@ -689,7 +690,7 @@ def test_test_mcp_preset_scrubs_connection_errors(
|
||||
},
|
||||
)
|
||||
|
||||
async def fake_connect(_servers, _registry):
|
||||
async def fake_connect(_servers, _registry, *, network):
|
||||
raise RuntimeError("failed https://mcp.browserbase.com/mcp?browserbaseApiKey=bb_live_secret")
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.mcp.connect_mcp_servers", fake_connect)
|
||||
@@ -930,3 +931,146 @@ def test_normalize_mcp_mentions_uses_explicit_gateway_config(
|
||||
)
|
||||
|
||||
assert payload == [{"name": "gateway-docs", "display_name": "Gateway docs"}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("installed", [False, True], ids=["first-authorization", "existing-preset"])
|
||||
def test_oauth_setup_persists_proxy_choice_without_credential_fields(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
installed: bool,
|
||||
) -> None:
|
||||
_use_config(tmp_path, monkeypatch)
|
||||
config = load_config()
|
||||
config.network.proxy = "http://shared.example:8080"
|
||||
save_config(config)
|
||||
if installed:
|
||||
mcp_presets_action("enable", {"name": ["xmind"]})
|
||||
|
||||
name, cfg, network = ensure_mcp_oauth_server({
|
||||
"name": ["xmind"], "use_proxy": ["true"],
|
||||
})
|
||||
|
||||
assert name == "xmind"
|
||||
assert cfg.use_proxy is True
|
||||
assert cfg.auth == "oauth"
|
||||
assert network.proxy == "http://shared.example:8080"
|
||||
assert load_config().tools.mcp_servers[name].use_proxy is True
|
||||
payload = mcp_presets_payload()
|
||||
row = next(item for item in payload["presets"] if item["name"] == name)
|
||||
assert row["use_proxy"] is True
|
||||
assert row["status"] == "authorization_required"
|
||||
assert payload["proxy_configured"] is True
|
||||
assert "shared.example" not in json.dumps(payload)
|
||||
|
||||
_, updated, _ = ensure_mcp_oauth_server({"name": [name], "use_proxy": ["false"]})
|
||||
assert updated.use_proxy is False
|
||||
assert load_config().tools.mcp_servers[name].use_proxy is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["xmind", "custom-docs"])
|
||||
def test_proxy_action_preserves_existing_server_and_materializes_presets(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
name: str,
|
||||
) -> None:
|
||||
_use_config(tmp_path, monkeypatch)
|
||||
config = load_config()
|
||||
config.network.proxy = "http://shared.example:8080"
|
||||
save_config(config)
|
||||
if name == "custom-docs":
|
||||
custom_mcp_action("custom", {
|
||||
"name": [name], "url": ["https://docs.example.com/mcp"],
|
||||
"headers": ['{"Authorization": "Bearer preserved-secret"}'],
|
||||
"enabled_tools": ['["search"]'], "tool_timeout": ["90"],
|
||||
})
|
||||
|
||||
payload = mcp_presets_action("proxy", {"name": [name], "use_proxy": ["true"]})
|
||||
before = load_config().tools.mcp_servers[name]
|
||||
assert before.use_proxy is True
|
||||
assert payload["requires_restart"] is True
|
||||
assert next(row for row in payload["presets"] if row["name"] == name)["use_proxy"] is True
|
||||
|
||||
mcp_presets_action("proxy", {"name": [name], "use_proxy": ["false"]})
|
||||
after = load_config().tools.mcp_servers[name]
|
||||
assert after.use_proxy is False
|
||||
assert after.model_dump(exclude={"use_proxy"}) == before.model_dump(exclude={"use_proxy"})
|
||||
if name == "custom-docs":
|
||||
assert after.headers == {"Authorization": "Bearer preserved-secret"}
|
||||
assert after.enabled_tools == ["search"]
|
||||
assert after.tool_timeout == 90
|
||||
|
||||
|
||||
@pytest.mark.parametrize("transport", ["sse", "streamableHttp"])
|
||||
def test_custom_server_saves_explicit_proxy_flag(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
transport: str,
|
||||
) -> None:
|
||||
_use_config(tmp_path, monkeypatch)
|
||||
config = load_config()
|
||||
config.network.proxy = "http://shared.example:8080"
|
||||
save_config(config)
|
||||
payload = custom_mcp_action("custom", {
|
||||
"name": ["company-docs"], "transport": [transport],
|
||||
"url": ["https://docs.example.com/mcp"], "use_proxy": ["true"],
|
||||
})
|
||||
assert load_config().tools.mcp_servers["company-docs"].use_proxy is True
|
||||
assert next(row for row in payload["presets"] if row["name"] == "company-docs")["use_proxy"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_proxy", [False, True])
|
||||
def test_import_preserves_boolean_proxy_flag(tmp_path, monkeypatch, use_proxy: bool) -> None:
|
||||
_use_config(tmp_path, monkeypatch)
|
||||
config = load_config()
|
||||
config.network.proxy = "http://shared.example:8080"
|
||||
save_config(config)
|
||||
custom_mcp_action("import", {"config": [json.dumps({"mcpServers": {
|
||||
"company-docs": {"url": "https://docs.example.com/mcp", "useProxy": use_proxy},
|
||||
}})]})
|
||||
assert load_config().tools.mcp_servers["company-docs"].use_proxy is use_proxy
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid", ["true", "false", 1, None])
|
||||
def test_import_rejects_nonboolean_proxy_flag_without_saving(tmp_path, monkeypatch, invalid) -> None:
|
||||
_use_config(tmp_path, monkeypatch)
|
||||
with pytest.raises(McpPresetError, match="useProxy must be a boolean"):
|
||||
custom_mcp_action("import", {"config": [json.dumps({"mcpServers": {
|
||||
"valid-first": {"url": "https://docs.example.com/mcp"},
|
||||
"bad-flag": {"url": "https://docs.example.com/mcp", "useProxy": invalid},
|
||||
}})]})
|
||||
assert load_config().tools.mcp_servers == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "proxy", "oauth", "custom", "import"])
|
||||
def test_explicit_proxy_requires_shared_address_before_saving(tmp_path, monkeypatch, action) -> None:
|
||||
_use_config(tmp_path, monkeypatch)
|
||||
with pytest.raises(McpPresetError, match="Configure the shared proxy"):
|
||||
if action == "oauth":
|
||||
ensure_mcp_oauth_server({"name": ["xmind"], "use_proxy": ["true"]})
|
||||
elif action == "custom":
|
||||
custom_mcp_action("custom", {
|
||||
"name": ["company-docs"], "url": ["https://docs.example.com/mcp"],
|
||||
"use_proxy": ["true"],
|
||||
})
|
||||
elif action == "import":
|
||||
custom_mcp_action("import", {"config": [json.dumps({
|
||||
"company-docs": {"url": "https://docs.example.com/mcp", "useProxy": True},
|
||||
})]})
|
||||
else:
|
||||
mcp_presets_action(action, {"name": ["xmind"], "use_proxy": ["true"]})
|
||||
assert load_config().tools.mcp_servers == {}
|
||||
assert mcp_presets_payload()["proxy_configured"] is False
|
||||
|
||||
|
||||
def test_enable_preset_preserves_proxy_choice_on_later_enable(tmp_path, monkeypatch) -> None:
|
||||
_use_config(tmp_path, monkeypatch)
|
||||
config = load_config()
|
||||
config.network.proxy = "http://shared.example:8080"
|
||||
save_config(config)
|
||||
|
||||
mcp_presets_action("enable", {"name": ["xmind"], "use_proxy": ["true"]})
|
||||
assert load_config().tools.mcp_servers["xmind"].use_proxy is True
|
||||
mcp_presets_action("enable", {"name": ["xmind"]})
|
||||
assert load_config().tools.mcp_servers["xmind"].use_proxy is True
|
||||
mcp_presets_action("enable", {"name": ["xmind"], "use_proxy": ["false"]})
|
||||
assert load_config().tools.mcp_servers["xmind"].use_proxy is False
|
||||
@@ -906,7 +906,8 @@ def test_create_provider_settings_persists_custom_advanced_options(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
config = Config.model_validate({"network": {"proxy": "http://127.0.0.1:7890"}})
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
payload = create_provider_settings(
|
||||
@@ -914,7 +915,7 @@ def test_create_provider_settings_persists_custom_advanced_options(
|
||||
"name": ["Company Gateway"],
|
||||
"apiBase": ["https://gateway.example/v1"],
|
||||
"apiKey": ["sk-company"],
|
||||
"proxy": ["http://127.0.0.1:7890"],
|
||||
"use_proxy": ["true"],
|
||||
"extraHeaders": [json.dumps({"X-Tenant": "engineering"})],
|
||||
"extraBody": [json.dumps({"service_tier": "priority"})],
|
||||
"extraQuery": [json.dumps({"api-version": "2026-01-01"})],
|
||||
@@ -930,7 +931,7 @@ def test_create_provider_settings_persists_custom_advanced_options(
|
||||
"extra_headers",
|
||||
"extra_body",
|
||||
"extra_query",
|
||||
"proxy",
|
||||
"use_proxy",
|
||||
"thinking_style",
|
||||
]
|
||||
assert row["extra_headers"] == {"X-Tenant": "engineering"}
|
||||
@@ -941,7 +942,8 @@ def test_create_provider_settings_persists_custom_advanced_options(
|
||||
assert saved.display_name == "Company Gateway"
|
||||
assert saved.api_key == "sk-company"
|
||||
assert saved.api_base == "https://gateway.example/v1"
|
||||
assert saved.proxy == "http://127.0.0.1:7890"
|
||||
assert saved.use_proxy is True
|
||||
assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"
|
||||
assert saved.extra_headers == {"X-Tenant": "engineering"}
|
||||
assert saved.extra_body == {"service_tier": "priority"}
|
||||
assert saved.extra_query == {"api-version": "2026-01-01"}
|
||||
@@ -1023,6 +1025,7 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.providers.openai.api_key = "sk-openai"
|
||||
config.network.proxy = "http://127.0.0.1:7890"
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
@@ -1030,7 +1033,7 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(
|
||||
{
|
||||
"provider": ["openai"],
|
||||
"apiType": ["responses"],
|
||||
"proxy": ["http://127.0.0.1:7890"],
|
||||
"use_proxy": ["true"],
|
||||
"extraHeaders": [json.dumps({"X-Trace": "enabled"})],
|
||||
"extraBody": [json.dumps({"service_tier": "priority"})],
|
||||
"extraQuery": [json.dumps({"trace": "true"})],
|
||||
@@ -1047,7 +1050,8 @@ def test_update_provider_settings_persists_provider_specific_advanced_options(
|
||||
|
||||
saved = load_config(config_path)
|
||||
assert saved.providers.openai.api.to_capabilities().preferred_api == "responses"
|
||||
assert saved.providers.openai.proxy == "http://127.0.0.1:7890"
|
||||
assert saved.providers.openai.use_proxy is True
|
||||
assert saved.network.proxy == "http://127.0.0.1:7890"
|
||||
assert saved.providers.openai.extra_headers == {"X-Trace": "enabled"}
|
||||
assert saved.providers.openai.extra_body == {"service_tier": "priority"}
|
||||
assert saved.providers.openai.extra_query == {"trace": "true"}
|
||||
@@ -1071,7 +1075,7 @@ def test_update_provider_settings_updates_and_clears_oauth_proxy(
|
||||
) -> None:
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
getattr(config.providers, config_attr).proxy = "http://127.0.0.1:7000"
|
||||
config.network.proxy = "http://127.0.0.1:7890"
|
||||
save_config(config, config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
monkeypatch.setattr(
|
||||
@@ -1087,24 +1091,24 @@ def test_update_provider_settings_updates_and_clears_oauth_proxy(
|
||||
payload = update_provider_settings(
|
||||
{
|
||||
"provider": [provider_name],
|
||||
"proxy": [" http://127.0.0.1:7890 "],
|
||||
"use_proxy": ["true"],
|
||||
"extraBody": [json.dumps({"tools": []})],
|
||||
}
|
||||
)
|
||||
|
||||
providers = {row["name"]: row for row in payload["providers"]}
|
||||
assert providers[provider_name]["proxy"] == "http://127.0.0.1:7890"
|
||||
assert getattr(load_config(config_path).providers, config_attr).proxy == (
|
||||
"http://127.0.0.1:7890"
|
||||
)
|
||||
assert providers[provider_name]["use_proxy"] is True
|
||||
assert getattr(load_config(config_path).providers, config_attr).use_proxy is True
|
||||
assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"
|
||||
assert providers[provider_name]["extra_body"] == {"tools": []}
|
||||
assert getattr(load_config(config_path).providers, config_attr).extra_body == {"tools": []}
|
||||
|
||||
cleared = update_provider_settings({"provider": [provider_name], "proxy": [" "]})
|
||||
cleared = update_provider_settings({"provider": [provider_name], "use_proxy": ["false"]})
|
||||
|
||||
providers = {row["name"]: row for row in cleared["providers"]}
|
||||
assert providers[provider_name]["proxy"] is None
|
||||
assert getattr(load_config(config_path).providers, config_attr).proxy is None
|
||||
assert providers[provider_name]["use_proxy"] is False
|
||||
assert getattr(load_config(config_path).providers, config_attr).use_proxy is False
|
||||
assert load_config(config_path).network.proxy == "http://127.0.0.1:7890"
|
||||
|
||||
|
||||
def test_update_provider_settings_keeps_oauth_credentials_read_only(
|
||||
@@ -1115,7 +1119,7 @@ def test_update_provider_settings_keeps_oauth_credentials_read_only(
|
||||
save_config(Config(), config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
with pytest.raises(WebUISettingsError, match="only supports proxy and extra_body settings"):
|
||||
with pytest.raises(WebUISettingsError, match="only supports use_proxy and extra_body settings"):
|
||||
update_provider_settings({"provider": ["openai_codex"], "apiKey": ["not-allowed"]})
|
||||
|
||||
|
||||
@@ -1930,7 +1934,7 @@ def test_openai_codex_oauth_login_passes_configured_proxy(
|
||||
proxy = "http://127.0.0.1:23458"
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate({"providers": {"openaiCodex": {"proxy": "${CODEX_PROXY_TEST}"}}}),
|
||||
Config.model_validate({"network": {"proxy": "${CODEX_PROXY_TEST}"}, "providers": {"openaiCodex": {"useProxy": True}}}),
|
||||
config_path,
|
||||
)
|
||||
monkeypatch.setenv("CODEX_PROXY_TEST", proxy)
|
||||
@@ -2112,7 +2116,7 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy(
|
||||
) -> None:
|
||||
proxy = "http://127.0.0.1:23458"
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config.model_validate({"providers": {"xaiGrok": {"proxy": proxy}}}), config_path)
|
||||
save_config(Config.model_validate({"network": {"proxy": proxy}, "providers": {"xaiGrok": {"useProxy": True}}}), config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ from websockets.datastructures import Headers
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.loader import get_config_path
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
from nanobot.webui.http_utils import http_json_response
|
||||
@@ -413,12 +414,12 @@ async def test_settings_shutdown_joins_browser_authorization_and_releases_admiss
|
||||
config = MCPServerConfig(type="streamableHttp", auth="oauth", url="https://mcp.example/mcp")
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.ensure_mcp_oauth_server",
|
||||
lambda _query, *, config_path=None: ("linear", config),
|
||||
lambda _query, *, config_path=None: ("linear", config, NetworkConfig()),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.webui.mcp_oauth_api.validate_url_target", lambda _: (True, ""))
|
||||
cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def connect(_servers, _registry, *, oauth_handlers):
|
||||
async def connect(_servers, _registry, *, oauth_handlers, network):
|
||||
handlers = oauth_handlers["linear"]
|
||||
await handlers.redirect_handler("https://accounts.example/authorize?state=settings")
|
||||
try:
|
||||
@@ -457,9 +458,10 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke
|
||||
auth="oauth",
|
||||
url="https://app.xmind.com/api/mcp",
|
||||
)
|
||||
network = SimpleNamespace(proxy="http://shared.example:8080")
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_routes.ensure_mcp_oauth_server",
|
||||
lambda _query, *, config_path=None: ("xmind", config),
|
||||
lambda _query, *, config_path=None: ("xmind", config, network),
|
||||
)
|
||||
router = _router()
|
||||
start = AsyncMock(return_value={
|
||||
@@ -484,6 +486,7 @@ async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monke
|
||||
config,
|
||||
"https://gateway.example/auth/mcp/callback",
|
||||
reload_mcp=ANY,
|
||||
network=network,
|
||||
reset_credentials=False,
|
||||
)
|
||||
|
||||
@@ -1040,3 +1043,103 @@ async def test_image_switch_round_trip_clears_restart(tmp_path, enabled):
|
||||
reverted = await router.dispatch(None, _mutation_request(path, {"enabled": enabled}), path)
|
||||
assert json.loads(reverted.body)["requires_restart"] is False
|
||||
assert json.loads(reverted.body)["restart_required_sections"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_first_mcp_oauth_request_saves_proxy_flag_before_starting_flow(tmp_path) -> None:
|
||||
from nanobot.config.loader import load_config
|
||||
|
||||
config_path = tmp_path / "config.json"
|
||||
config_path.write_text(json.dumps({
|
||||
"network": {"proxy": "http://shared.example:8080"},
|
||||
"agents": {"defaults": {"workspace": str(tmp_path / "workspace")}},
|
||||
}), encoding="utf-8")
|
||||
router = _router(config_path=config_path)
|
||||
captured = {}
|
||||
|
||||
async def start(name, cfg, redirect_uri, *, reload_mcp, network, reset_credentials):
|
||||
saved = load_config(config_path)
|
||||
assert name == "xmind"
|
||||
assert cfg.auth == "oauth"
|
||||
assert cfg.use_proxy is True
|
||||
assert saved.tools.mcp_servers[name].use_proxy is True
|
||||
assert network == saved.network
|
||||
captured["network"] = network.proxy
|
||||
return {"status": "authorization_required", "name": name, "flow_id": "first-flow"}
|
||||
|
||||
router._mcp_oauth = SimpleNamespace(start=start)
|
||||
request = _mutation_request(
|
||||
"/api/settings/mcp-oauth/start",
|
||||
{"name": "xmind", "use_proxy": True},
|
||||
)
|
||||
response = await router.dispatch(None, request, "/api/settings/mcp-oauth/start")
|
||||
|
||||
assert response is not None
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body)["flow_id"] == "first-flow"
|
||||
assert captured == {"network": "http://shared.example:8080"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("use_proxy", [True, False])
|
||||
async def test_mcp_proxy_mutation_persists_reloads_and_keeps_oauth_credentials(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, use_proxy: bool,
|
||||
) -> None:
|
||||
from mcp.shared.auth import OAuthToken
|
||||
from websockets.http11 import Request
|
||||
|
||||
from nanobot.agent.tools.mcp_oauth import MCPOAuthStorage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.config.loader import load_config, save_config
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
monkeypatch.setattr("nanobot.agent.tools.mcp_oauth.get_data_dir", lambda: tmp_path)
|
||||
config_path = tmp_path / "config.json"
|
||||
config = Config.model_validate({
|
||||
"network": {"proxy": "http://proxy.example:8080"},
|
||||
"tools": {"mcpServers": {"team-docs": {
|
||||
"type": "streamableHttp", "auth": "oauth",
|
||||
"url": "https://mcp.example.com/mcp", "useProxy": not use_proxy,
|
||||
"headers": {"X-Organization": "team"}, "enabledTools": ["read"],
|
||||
}}},
|
||||
})
|
||||
save_config(config, config_path)
|
||||
original = config.tools.mcp_servers["team-docs"].model_copy(deep=True)
|
||||
storage = MCPOAuthStorage("team-docs", original.url)
|
||||
await storage.set_tokens(OAuthToken(access_token="synthetic-access", token_type="Bearer"))
|
||||
|
||||
async def reload_mcp() -> dict[str, object]:
|
||||
assert load_config(config_path).tools.mcp_servers["team-docs"].use_proxy is use_proxy
|
||||
return {"ok": True, "connected": ["team-docs"], "requires_restart": False}
|
||||
|
||||
reload = AsyncMock(side_effect=reload_mcp)
|
||||
gateway = build_gateway_services(
|
||||
config=WebSocketConfig(), bus=MessageBus(), session_manager=None,
|
||||
static_dist_path=None, workspace_path=tmp_path, config_path=config_path,
|
||||
default_restrict_to_workspace=True, runtime_model_name=None,
|
||||
runtime_surface="browser", runtime_capabilities_overrides=None, mcp_reload=reload,
|
||||
)
|
||||
connection = SimpleNamespace(
|
||||
remote_address=("127.0.0.1", 12345),
|
||||
request=Request("/", Headers({"Host": "127.0.0.1:8765"})),
|
||||
)
|
||||
path = "/api/settings/mcp-presets/proxy"
|
||||
try:
|
||||
http_response = await gateway.http.dispatch(connection, Request(path, Headers()))
|
||||
assert http_response.status_code == 405
|
||||
response = await gateway.http.dispatch_webui_mutation(
|
||||
connection, "settings.mcp.proxy", {"name": "team-docs", "use_proxy": str(use_proxy).lower()},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = json.loads(response.body)
|
||||
assert payload["hot_reload"]["ok"] is True
|
||||
assert payload["requires_restart"] is False
|
||||
row = next(row for row in payload["presets"] if row["name"] == "team-docs")
|
||||
assert row["use_proxy"] is use_proxy
|
||||
assert load_config(config_path).tools.mcp_servers["team-docs"] == original.model_copy(update={"use_proxy": use_proxy})
|
||||
assert storage.has_credentials() is True
|
||||
reload.assert_awaited_once()
|
||||
finally:
|
||||
await gateway.http.settings_routes.close()
|
||||
@@ -16,20 +16,32 @@ from nanobot.webui.settings_runtime import (
|
||||
from nanobot.webui.settings_services import WebUISettingsServices
|
||||
|
||||
|
||||
def test_web_proxy_roundtrip_while_disabled_preserves_model_proxy(tmp_path):
|
||||
def test_shared_proxy_roundtrip_preserves_independent_feature_switches(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
config = Config()
|
||||
config.tools.web.enable = False
|
||||
config.providers.openai.proxy = "http://model-proxy.example:8080"
|
||||
config.providers.openai.use_proxy = True
|
||||
save_config(config, path)
|
||||
for proxy in ("http://web-proxy.example:7890", None):
|
||||
payload = update_runtime_config_settings({"tools.web.proxy": proxy}, local_browser=True, config_path=path)
|
||||
assert payload["runtime_config"]["tools.web.proxy"] == proxy
|
||||
for proxy in ("http://shared-proxy.example:7890", "http://shared-proxy.example:7891"):
|
||||
payload = update_runtime_config_settings({"network.proxy": proxy}, local_browser=True, config_path=path)
|
||||
assert payload["runtime_config"]["network.proxy"] == proxy
|
||||
assert payload["requires_restart"]
|
||||
saved = load_config(path)
|
||||
assert saved.tools.web.proxy == proxy
|
||||
assert saved.network.proxy == proxy
|
||||
assert saved.tools.web.enable is False
|
||||
assert saved.providers.openai.proxy == "http://model-proxy.example:8080"
|
||||
assert saved.tools.web.use_proxy is False
|
||||
assert saved.providers.openai.use_proxy is True
|
||||
update_runtime_config_settings({"tools.web.use_proxy": True}, config_path=path)
|
||||
assert load_config(path).tools.web.use_proxy is True
|
||||
|
||||
|
||||
def test_enabling_web_proxy_without_an_address_preserves_config(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
save_config(Config(), path)
|
||||
before = path.read_bytes()
|
||||
with pytest.raises(WebUISettingsError, match="Advanced"):
|
||||
update_runtime_config_settings({"tools.web.use_proxy": True}, config_path=path)
|
||||
assert path.read_bytes() == before
|
||||
|
||||
|
||||
def test_runtime_patch_persists_and_preserves_other_domains(tmp_path):
|
||||
@@ -158,7 +170,7 @@ def test_timezone_auto_and_nullable_fields():
|
||||
}}})
|
||||
assert update_runtime_config(config, {
|
||||
"agents.defaults.timezone_mode": "auto",
|
||||
"tools.web.proxy": None,
|
||||
"network.proxy": None,
|
||||
}, local_browser=True)
|
||||
assert config.agents.defaults.timezone_mode == "auto"
|
||||
assert config.agents.defaults.dream.cron == "0 2 * * *"
|
||||
|
||||
Reference in new issue
Block a user