feat(proxy-hosts): support custom locations on create/update (#18)
* build(deps): sync uv.lock with pyproject dependencies * feat(proxy-hosts): support custom locations on create/update Extend ProxyHostLocation with forward_path and access_list_id, thread locations through create/update tools and client, preserve existing locations on updates that omit them (NPM replaces the list on PUT), and render full location records in host details. Adds 5 tests.
This commit is contained in:
1 parent
feae6dedfb
commit
e641c7b4ba
5 files changed
+1211
-23
No files matched your search
@@ -280,6 +280,7 @@ class NpmClient:
|
||||
access_list_id: int = 0,
|
||||
advanced_config: str = "",
|
||||
meta: dict | None = None,
|
||||
locations: list[dict] | None = None,
|
||||
) -> ProxyHost:
|
||||
"""Create a new proxy host.
|
||||
|
||||
@@ -299,6 +300,9 @@ class NpmClient:
|
||||
access_list_id: Access list ID (0 for none, use list_access_lists to find)
|
||||
advanced_config: Custom nginx configuration
|
||||
meta: Additional metadata
|
||||
locations: Custom location blocks. Each dict accepts path,
|
||||
forward_scheme, forward_host, forward_port, forward_path,
|
||||
advanced_config, and access_list_id. Omitted when None.
|
||||
|
||||
Returns:
|
||||
Created ProxyHost object
|
||||
@@ -320,6 +324,8 @@ class NpmClient:
|
||||
"advanced_config": advanced_config,
|
||||
"meta": meta or {},
|
||||
}
|
||||
if locations is not None:
|
||||
payload["locations"] = locations
|
||||
|
||||
response = await self._request("POST", "/nginx/proxy-hosts", json=payload)
|
||||
return ProxyHost(**response.json())
|
||||
@@ -357,6 +363,19 @@ class NpmClient:
|
||||
"advanced_config": existing.advanced_config,
|
||||
"meta": existing.meta,
|
||||
}
|
||||
# Preserve existing custom locations: NPM replaces the whole list
|
||||
# on PUT, so omitting the key would drop them. An explicit
|
||||
# ``locations`` kwarg replaces the list entirely.
|
||||
# Omit ``access_list_id`` unless explicitly set to a positive id.
|
||||
if existing.locations:
|
||||
payload["locations"] = [
|
||||
{
|
||||
k: v
|
||||
for k, v in loc.model_dump(exclude_none=True).items()
|
||||
if k != "access_list_id" or (v is not None and v > 0)
|
||||
}
|
||||
for loc in existing.locations
|
||||
]
|
||||
payload.update({k: v for k, v in kwargs.items() if v is not None})
|
||||
|
||||
response = await self._request("PUT", f"/nginx/proxy-hosts/{host_id}", json=payload)
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
"""Pydantic models for NPM API responses."""
|
||||
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ForwardScheme(StrEnum):
|
||||
"""Backend protocol for proxy forwarding."""
|
||||
|
||||
HTTP = "http"
|
||||
HTTPS = "https"
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
"""Response from the login/token endpoint."""
|
||||
|
||||
@@ -67,7 +75,9 @@ class ProxyHostLocation(BaseModel):
|
||||
forward_host: str | None = None
|
||||
forward_port: int | None = None
|
||||
forward_scheme: str | None = None
|
||||
forward_path: str | None = None
|
||||
advanced_config: str = ""
|
||||
access_list_id: int | None = None
|
||||
|
||||
|
||||
class ProxyHost(BaseModel):
|
||||
|
||||
@@ -6,11 +6,13 @@ from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
from fastmcp import FastMCP
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .client import NpmClient
|
||||
from .config import NpmInstance, settings
|
||||
from .exceptions import NpmApiError, NpmAuthenticationError, NpmConnectionError, NpmLogError
|
||||
from .logs import is_log_dir_configured, list_available_logs, read_log_lines
|
||||
from .models import ForwardScheme
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -72,6 +74,25 @@ def _check_destructive() -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
class ProxyHostLocationInput(BaseModel):
|
||||
"""Custom location block for create/update proxy host tools."""
|
||||
|
||||
path: str = Field(description="Location path (e.g. '/' or '/api')")
|
||||
forward_scheme: ForwardScheme = Field(description="Backend protocol")
|
||||
forward_host: str = Field(description="Backend host/IP to forward to")
|
||||
forward_port: int = Field(description="Backend port to forward to")
|
||||
forward_path: str | None = Field(
|
||||
default=None, description="Path prefix to forward to on the backend"
|
||||
)
|
||||
advanced_config: str | None = Field(
|
||||
default=None, description="Per-location custom nginx configuration"
|
||||
)
|
||||
access_list_id: int | None = Field(
|
||||
default=None,
|
||||
description="Per-location access list ID (omit to leave unset)",
|
||||
)
|
||||
|
||||
|
||||
def _format_error(e: Exception) -> str:
|
||||
if isinstance(e, NpmAuthenticationError):
|
||||
return f"Authentication failed: {e}"
|
||||
@@ -181,8 +202,12 @@ async def get_proxy_host_details(host_id: int, instance: str | None = None) -> s
|
||||
details["locations"] = [
|
||||
{
|
||||
"path": loc.path,
|
||||
"forward_scheme": loc.forward_scheme,
|
||||
"forward_host": loc.forward_host,
|
||||
"forward_port": loc.forward_port,
|
||||
"forward_path": loc.forward_path,
|
||||
"advanced_config": loc.advanced_config,
|
||||
"access_list_id": loc.access_list_id,
|
||||
}
|
||||
for loc in host.locations
|
||||
]
|
||||
@@ -336,6 +361,7 @@ async def create_proxy_host(
|
||||
allow_websocket_upgrade: bool | None = None,
|
||||
access_list_id: int | None = None,
|
||||
advanced_config: str | None = None,
|
||||
locations: list[ProxyHostLocationInput] | None = None,
|
||||
instance: str | None = None,
|
||||
) -> str:
|
||||
"""Create a new proxy host in Nginx Proxy Manager.
|
||||
@@ -351,6 +377,9 @@ async def create_proxy_host(
|
||||
allow_websocket_upgrade: Allow WebSocket connections (default from config)
|
||||
access_list_id: Access list ID (0 for no restrictions)
|
||||
advanced_config: Custom nginx configuration block
|
||||
locations: Custom location blocks. Each dict accepts path,
|
||||
forward_scheme, forward_host, forward_port, forward_path,
|
||||
advanced_config, and access_list_id.
|
||||
instance: NPM instance name (omit for default)
|
||||
"""
|
||||
if msg := _check_destructive():
|
||||
@@ -378,6 +407,11 @@ async def create_proxy_host(
|
||||
access_list_id=_or(access_list_id, "access_list_id"),
|
||||
advanced_config=_or(advanced_config, "advanced_config"),
|
||||
meta=defaults.get("meta", {}),
|
||||
locations=(
|
||||
[loc.model_dump(exclude_none=True) for loc in locations]
|
||||
if locations is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
domains = ", ".join(host.domain_names)
|
||||
@@ -405,11 +439,14 @@ async def update_proxy_host(
|
||||
allow_websocket_upgrade: bool | None = None,
|
||||
access_list_id: int | None = None,
|
||||
advanced_config: str | None = None,
|
||||
locations: list[ProxyHostLocationInput] | None = None,
|
||||
instance: str | None = None,
|
||||
) -> str:
|
||||
"""Update an existing proxy host in Nginx Proxy Manager.
|
||||
|
||||
Only provided fields will be updated; all others remain unchanged.
|
||||
Custom locations are preserved when omitted. Passing ``locations``
|
||||
replaces the entire locations list on the host.
|
||||
|
||||
Args:
|
||||
host_id: The ID of the proxy host to update
|
||||
@@ -422,6 +459,10 @@ async def update_proxy_host(
|
||||
allow_websocket_upgrade: Allow WebSocket connections
|
||||
access_list_id: Access list ID (0 for no restrictions)
|
||||
advanced_config: Custom nginx configuration block
|
||||
locations: Full replacement list of custom location blocks
|
||||
(each: path, forward_scheme, forward_host, forward_port,
|
||||
forward_path, advanced_config, access_list_id). Omit to
|
||||
leave existing locations unchanged.
|
||||
instance: NPM instance name (omit for default)
|
||||
"""
|
||||
if msg := _check_destructive():
|
||||
@@ -447,6 +488,8 @@ async def update_proxy_host(
|
||||
kwargs["access_list_id"] = access_list_id
|
||||
if advanced_config is not None:
|
||||
kwargs["advanced_config"] = advanced_config
|
||||
if locations is not None:
|
||||
kwargs["locations"] = [loc.model_dump(exclude_none=True) for loc in locations]
|
||||
|
||||
host = await client.update_proxy_host(host_id, **kwargs)
|
||||
|
||||
|
||||
@@ -256,6 +256,292 @@ class TestNpmClientEndpoints:
|
||||
assert msg.count("API error") == 0, f"Client should not prefix error: {msg}"
|
||||
|
||||
|
||||
MOCK_HOST_WITH_LOCATIONS = {
|
||||
"id": 7,
|
||||
"created_on": "2024-01-01T00:00:00Z",
|
||||
"modified_on": "2024-01-01T00:00:00Z",
|
||||
"owner_user_id": 1,
|
||||
"domain_names": ["app.example.com"],
|
||||
"forward_host": "192.168.1.100",
|
||||
"forward_port": 8080,
|
||||
"forward_scheme": "http",
|
||||
"enabled": True,
|
||||
"ssl_forced": False,
|
||||
"advanced_config": "",
|
||||
# No ``access_list_id`` on locations — the field is omitted when unset.
|
||||
"locations": [
|
||||
{
|
||||
"path": "/",
|
||||
"forward_scheme": "http",
|
||||
"forward_host": "192.168.1.100",
|
||||
"forward_port": 8080,
|
||||
"advanced_config": "auth_request /guard;\n",
|
||||
},
|
||||
{
|
||||
"path": "/api",
|
||||
"forward_scheme": "http",
|
||||
"forward_host": "192.168.1.100",
|
||||
"forward_port": 8080,
|
||||
"forward_path": "/api",
|
||||
"advanced_config": "",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _api_request_body(httpx_mock, method):
|
||||
"""Return the parsed JSON body of the last API request with a method.
|
||||
|
||||
Filters by method because the login POST is also recorded.
|
||||
"""
|
||||
|
||||
requests = httpx_mock.get_requests(method=method)
|
||||
api_requests = [r for r in requests if "/tokens" not in str(r.url)]
|
||||
assert api_requests, f"no {method} API request recorded"
|
||||
return json.loads(api_requests[-1].content)
|
||||
|
||||
|
||||
class TestProxyHostLocations:
|
||||
"""Test custom locations support on proxy hosts."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_location_model_parses_all_fields(self, httpx_mock, mock_token_response):
|
||||
"""Location model keeps forward_path and access_list_id."""
|
||||
from npm_mcp.models import ProxyHost
|
||||
|
||||
host = ProxyHost(**MOCK_HOST_WITH_LOCATIONS)
|
||||
assert host.locations is not None and len(host.locations) == 2
|
||||
assert host.locations[0].advanced_config == "auth_request /guard;\n"
|
||||
assert host.locations[1].forward_path == "/api"
|
||||
# Absent access_list_id defaults to None, not 0.
|
||||
assert host.locations[1].access_list_id is None
|
||||
|
||||
host_with_acl = ProxyHost(
|
||||
**{
|
||||
**MOCK_HOST_WITH_LOCATIONS,
|
||||
"locations": [{**MOCK_HOST_WITH_LOCATIONS["locations"][0], "access_list_id": 5}],
|
||||
}
|
||||
)
|
||||
assert host_with_acl.locations is not None
|
||||
assert host_with_acl.locations[0].access_list_id == 5
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_with_locations(
|
||||
self, httpx_mock, mock_token_response, mock_created_proxy_host
|
||||
):
|
||||
"""Create sends the locations list in the POST body."""
|
||||
|
||||
httpx_mock.add_response(
|
||||
method="POST",
|
||||
url="http://localhost:81/api/tokens",
|
||||
json=mock_token_response,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="POST",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts",
|
||||
json=mock_created_proxy_host,
|
||||
status_code=201,
|
||||
)
|
||||
|
||||
locations = [
|
||||
{
|
||||
"path": "/api",
|
||||
"forward_scheme": "http",
|
||||
"forward_host": "10.0.0.50",
|
||||
"forward_port": 3000,
|
||||
"forward_path": "/api",
|
||||
"advanced_config": "",
|
||||
"access_list_id": 0,
|
||||
}
|
||||
]
|
||||
|
||||
async with NpmClient(
|
||||
base_url="http://localhost:81/api",
|
||||
identity="test@test.com",
|
||||
secret="password",
|
||||
) as client:
|
||||
await client.create_proxy_host(
|
||||
domain_names=["newapp.example.com"],
|
||||
forward_host="10.0.0.50",
|
||||
forward_port=3000,
|
||||
locations=locations,
|
||||
)
|
||||
|
||||
assert _api_request_body(httpx_mock, "POST")["locations"] == locations
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_without_locations_omits_key(
|
||||
self, httpx_mock, mock_token_response, mock_created_proxy_host
|
||||
):
|
||||
"""Create without locations must not send the key at all."""
|
||||
|
||||
httpx_mock.add_response(
|
||||
method="POST",
|
||||
url="http://localhost:81/api/tokens",
|
||||
json=mock_token_response,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="POST",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts",
|
||||
json=mock_created_proxy_host,
|
||||
status_code=201,
|
||||
)
|
||||
|
||||
async with NpmClient(
|
||||
base_url="http://localhost:81/api",
|
||||
identity="test@test.com",
|
||||
secret="password",
|
||||
) as client:
|
||||
await client.create_proxy_host(
|
||||
domain_names=["newapp.example.com"],
|
||||
forward_host="10.0.0.50",
|
||||
forward_port=3000,
|
||||
)
|
||||
|
||||
assert "locations" not in _api_request_body(httpx_mock, "POST")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_preserves_locations_when_omitted(
|
||||
self, httpx_mock, mock_token_response
|
||||
):
|
||||
"""Update without locations must re-send the existing list (no drop)."""
|
||||
httpx_mock.add_response(
|
||||
method="POST",
|
||||
url="http://localhost:81/api/tokens",
|
||||
json=mock_token_response,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="GET",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts/7?expand=owner%2Ccertificate",
|
||||
json=MOCK_HOST_WITH_LOCATIONS,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="PUT",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts/7",
|
||||
json=MOCK_HOST_WITH_LOCATIONS,
|
||||
)
|
||||
|
||||
async with NpmClient(
|
||||
base_url="http://localhost:81/api",
|
||||
identity="test@test.com",
|
||||
secret="password",
|
||||
) as client:
|
||||
await client.update_proxy_host(7, forward_port=9090)
|
||||
|
||||
body = _api_request_body(httpx_mock, "PUT")
|
||||
assert body["forward_port"] == 9090
|
||||
assert body["locations"] == MOCK_HOST_WITH_LOCATIONS["locations"]
|
||||
# The preserved payload must not inject access_list_id when unset.
|
||||
for loc in body["locations"]:
|
||||
assert "access_list_id" not in loc
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_replaces_locations_when_provided(
|
||||
self, httpx_mock, mock_token_response
|
||||
):
|
||||
"""An explicit locations list replaces the existing one entirely."""
|
||||
httpx_mock.add_response(
|
||||
method="POST",
|
||||
url="http://localhost:81/api/tokens",
|
||||
json=mock_token_response,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="GET",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts/7?expand=owner%2Ccertificate",
|
||||
json=MOCK_HOST_WITH_LOCATIONS,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="PUT",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts/7",
|
||||
json=MOCK_HOST_WITH_LOCATIONS,
|
||||
)
|
||||
|
||||
replacement = [
|
||||
{
|
||||
"path": "/new",
|
||||
"forward_scheme": "http",
|
||||
"forward_host": "192.168.1.200",
|
||||
"forward_port": 9000,
|
||||
"advanced_config": "",
|
||||
"access_list_id": 0,
|
||||
}
|
||||
]
|
||||
|
||||
async with NpmClient(
|
||||
base_url="http://localhost:81/api",
|
||||
identity="test@test.com",
|
||||
secret="password",
|
||||
) as client:
|
||||
await client.update_proxy_host(7, locations=replacement)
|
||||
|
||||
body = _api_request_body(httpx_mock, "PUT")
|
||||
assert body["locations"] == replacement
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_preserves_access_list_id_when_set(self, httpx_mock, mock_token_response):
|
||||
"""Preserved locations keep an explicitly set access_list_id."""
|
||||
host_with_acl = {
|
||||
**MOCK_HOST_WITH_LOCATIONS,
|
||||
"locations": [
|
||||
{**MOCK_HOST_WITH_LOCATIONS["locations"][0], "access_list_id": 5}
|
||||
],
|
||||
}
|
||||
httpx_mock.add_response(
|
||||
method="POST",
|
||||
url="http://localhost:81/api/tokens",
|
||||
json=mock_token_response,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="GET",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts/7?expand=owner%2Ccertificate",
|
||||
json=host_with_acl,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="PUT",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts/7",
|
||||
json=host_with_acl,
|
||||
)
|
||||
|
||||
async with NpmClient(
|
||||
base_url="http://localhost:81/api",
|
||||
identity="test@test.com",
|
||||
secret="password",
|
||||
) as client:
|
||||
await client.update_proxy_host(7, forward_port=9090)
|
||||
|
||||
body = _api_request_body(httpx_mock, "PUT")
|
||||
assert body["locations"][0]["access_list_id"] == 5
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_empty_locations_clears_list(self, httpx_mock, mock_token_response):
|
||||
"""Passing locations=[] sends an empty list to clear existing ones."""
|
||||
httpx_mock.add_response(
|
||||
method="POST",
|
||||
url="http://localhost:81/api/tokens",
|
||||
json=mock_token_response,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="GET",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts/7?expand=owner%2Ccertificate",
|
||||
json=MOCK_HOST_WITH_LOCATIONS,
|
||||
)
|
||||
httpx_mock.add_response(
|
||||
method="PUT",
|
||||
url="http://localhost:81/api/nginx/proxy-hosts/7",
|
||||
json={**MOCK_HOST_WITH_LOCATIONS, "locations": []},
|
||||
)
|
||||
|
||||
async with NpmClient(
|
||||
base_url="http://localhost:81/api",
|
||||
identity="test@test.com",
|
||||
secret="password",
|
||||
) as client:
|
||||
await client.update_proxy_host(7, locations=[])
|
||||
|
||||
body = _api_request_body(httpx_mock, "PUT")
|
||||
assert body["locations"] == []
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_created_certificate():
|
||||
"""Mock response for created certificate."""
|
||||
|
||||
Reference in new issue
Block a user