Co-authored-by: b3nw <189466+b3nw@users.noreply.github.com>
This commit is contained in:
1 parent
725d323b96
commit
feae6dedfb
9 files changed
+178
-53
No files matched your search
@@ -41,3 +41,4 @@ select = ["E", "F", "I", "UP"]
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["src"]
|
||||
@@ -430,7 +430,7 @@ class NpmClient:
|
||||
async def create_certificate(
|
||||
self,
|
||||
domain_names: list[str],
|
||||
email: str,
|
||||
email: str = "",
|
||||
provider: str = "letsencrypt",
|
||||
dns_challenge: bool = False,
|
||||
) -> Certificate:
|
||||
@@ -438,7 +438,9 @@ class NpmClient:
|
||||
|
||||
Args:
|
||||
domain_names: List of domain names for the certificate
|
||||
email: Email address for Let's Encrypt notifications
|
||||
email: Deprecated and unused; kept for backward compatibility.
|
||||
NPM 2.x obtains the Let's Encrypt email from the authenticated
|
||||
user account and rejects it in the request meta.
|
||||
provider: Certificate provider (default: "letsencrypt")
|
||||
dns_challenge: Use DNS challenge instead of HTTP (default: False)
|
||||
|
||||
@@ -447,11 +449,7 @@ class NpmClient:
|
||||
"""
|
||||
payload = {
|
||||
"domain_names": domain_names,
|
||||
"meta": {
|
||||
"letsencrypt_email": email,
|
||||
"letsencrypt_agree": True,
|
||||
"dns_challenge": dns_challenge,
|
||||
},
|
||||
"meta": {"dns_challenge": dns_challenge},
|
||||
"provider": provider,
|
||||
}
|
||||
|
||||
|
||||
@@ -112,16 +112,12 @@ class Settings(BaseSettings):
|
||||
for name, cfg in self.instances.items():
|
||||
if not isinstance(cfg, dict):
|
||||
raise ValueError(
|
||||
f"NPM_INSTANCES['{name}'] must be an object, "
|
||||
f"got {type(cfg).__name__}"
|
||||
f"NPM_INSTANCES['{name}'] must be an object, got {type(cfg).__name__}"
|
||||
)
|
||||
missing = [
|
||||
k for k in ("api_url", "identity", "secret") if not cfg.get(k)
|
||||
]
|
||||
missing = [k for k in ("api_url", "identity", "secret") if not cfg.get(k)]
|
||||
if missing:
|
||||
raise ValueError(
|
||||
f"NPM_INSTANCES['{name}'] missing required field(s): "
|
||||
f"{missing}"
|
||||
f"NPM_INSTANCES['{name}'] missing required field(s): {missing}"
|
||||
)
|
||||
for field in ("api_url", "identity", "secret"):
|
||||
val = cfg[field]
|
||||
|
||||
+2
-1
@@ -57,11 +57,13 @@ def main() -> None:
|
||||
# Mount /health directly on the inner router
|
||||
from starlette.responses import PlainTextResponse
|
||||
from starlette.routing import Route
|
||||
|
||||
app.router.routes.insert(0, Route("/health", lambda r: PlainTextResponse("ok")))
|
||||
|
||||
if settings.mcp_auth_token:
|
||||
logger.info("Bearer token authentication enabled")
|
||||
from .auth import BearerAuthMiddleware
|
||||
|
||||
app.add_middleware(BearerAuthMiddleware, token=settings.mcp_auth_token)
|
||||
|
||||
import uvicorn
|
||||
@@ -71,4 +73,3 @@ def main() -> None:
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
+16
-18
@@ -61,8 +61,7 @@ mcp = FastMCP(
|
||||
|
||||
|
||||
DESTRUCTIVE_DISABLED_MSG = (
|
||||
"Destructive operations are disabled. "
|
||||
"Set NPM_MCP_ENABLE_DESTRUCTIVE_TOOLS=true to enable."
|
||||
"Destructive operations are disabled. Set NPM_MCP_ENABLE_DESTRUCTIVE_TOOLS=true to enable."
|
||||
)
|
||||
|
||||
|
||||
@@ -129,10 +128,7 @@ async def list_proxy_hosts(instance: str | None = None) -> str:
|
||||
ssl_status = "\U0001f512 SSL" if host.ssl_forced else "\U0001f513 HTTP"
|
||||
enabled_status = "\u2705" if host.enabled else "\u274c"
|
||||
fwd = f"{host.forward_scheme}://{host.forward_host}:{host.forward_port}"
|
||||
result.append(
|
||||
f"{enabled_status} [{host.id}] {domains}\n"
|
||||
f" \u2192 {fwd} {ssl_status}"
|
||||
)
|
||||
result.append(f"{enabled_status} [{host.id}] {domains}\n \u2192 {fwd} {ssl_status}")
|
||||
|
||||
return f"Found {len(hosts)} proxy host(s):\n\n" + "\n\n".join(result)
|
||||
|
||||
@@ -231,8 +227,7 @@ async def get_system_health(instance: str | None = None) -> str:
|
||||
result.append(f"Log directory: \u2705 ({len(logs)} log files found)")
|
||||
else:
|
||||
result.append(
|
||||
"Log directory: \u274c "
|
||||
"(not configured \u2014 set NPM_LOG_DIR or instance log_dir)"
|
||||
"Log directory: \u274c (not configured \u2014 set NPM_LOG_DIR or instance log_dir)"
|
||||
)
|
||||
|
||||
return "\n".join(result)
|
||||
@@ -242,9 +237,7 @@ async def get_system_health(instance: str | None = None) -> str:
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
async def search_audit_logs(
|
||||
limit: int = 50, offset: int = 0, instance: str | None = None
|
||||
) -> str:
|
||||
async def search_audit_logs(limit: int = 50, offset: int = 0, instance: str | None = None) -> str:
|
||||
"""Search the audit log for recent actions in Nginx Proxy Manager.
|
||||
|
||||
Args:
|
||||
@@ -381,9 +374,7 @@ async def create_proxy_host(
|
||||
http2_support=defaults.get("http2_support", True),
|
||||
block_exploits=_or(block_exploits, "block_exploits"),
|
||||
caching_enabled=defaults.get("caching_enabled", False),
|
||||
allow_websocket_upgrade=_or(
|
||||
allow_websocket_upgrade, "allow_websocket_upgrade"
|
||||
),
|
||||
allow_websocket_upgrade=_or(allow_websocket_upgrade, "allow_websocket_upgrade"),
|
||||
access_list_id=_or(access_list_id, "access_list_id"),
|
||||
advanced_config=_or(advanced_config, "advanced_config"),
|
||||
meta=defaults.get("meta", {}),
|
||||
@@ -581,7 +572,11 @@ async def get_proxy_host_logs(
|
||||
)
|
||||
|
||||
result = read_log_lines(
|
||||
host_id=host_id, log_type=log_type, lines=lines, search=search, log_dir=log_dir,
|
||||
host_id=host_id,
|
||||
log_type=log_type,
|
||||
lines=lines,
|
||||
search=search,
|
||||
log_dir=log_dir,
|
||||
)
|
||||
|
||||
header_parts = [
|
||||
@@ -607,7 +602,7 @@ async def get_proxy_host_logs(
|
||||
@mcp.tool()
|
||||
async def create_certificate(
|
||||
domain_names: list[str],
|
||||
email: str,
|
||||
email: str = "",
|
||||
dns_challenge: bool = False,
|
||||
instance: str | None = None,
|
||||
) -> str:
|
||||
@@ -615,7 +610,8 @@ async def create_certificate(
|
||||
|
||||
Args:
|
||||
domain_names: List of domain names for the certificate
|
||||
email: Email address for Let's Encrypt notifications
|
||||
email: Deprecated and optional; ignored. NPM 2.x manages certificate
|
||||
emails from the authenticated user account.
|
||||
dns_challenge: Use DNS challenge instead of HTTP (default: False)
|
||||
instance: NPM instance name (omit for default)
|
||||
"""
|
||||
@@ -624,7 +620,9 @@ async def create_certificate(
|
||||
try:
|
||||
client, _ = _resolve(instance)
|
||||
cert = await client.create_certificate(
|
||||
domain_names=domain_names, email=email, dns_challenge=dns_challenge,
|
||||
domain_names=domain_names,
|
||||
email=email,
|
||||
dns_challenge=dns_challenge,
|
||||
)
|
||||
|
||||
domains = ", ".join(cert.domain_names)
|
||||
|
||||
+108
-2
@@ -1,10 +1,11 @@
|
||||
"""Tests for NpmClient."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from httpx import Response
|
||||
|
||||
from npm_mcp.client import NpmClient
|
||||
from npm_mcp.exceptions import NpmApiError, NpmAuthenticationError, NpmConnectionError
|
||||
from npm_mcp.exceptions import NpmApiError, NpmAuthenticationError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -253,3 +254,108 @@ class TestNpmClientEndpoints:
|
||||
|
||||
msg = str(exc_info.value)
|
||||
assert msg.count("API error") == 0, f"Client should not prefix error: {msg}"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_created_certificate():
|
||||
"""Mock response for created certificate."""
|
||||
return {
|
||||
"id": 7,
|
||||
"created_on": "2024-01-15T10:00:00Z",
|
||||
"modified_on": "2024-01-15T10:00:00Z",
|
||||
"owner_user_id": 1,
|
||||
"provider": "letsencrypt",
|
||||
"nice_name": "app.example.com",
|
||||
"domain_names": ["app.example.com"],
|
||||
"expires_on": "2024-04-15T10:00:00Z",
|
||||
"meta": {"dns_challenge": False},
|
||||
}
|
||||
|
||||
|
||||
def _certificate_payload(httpx_mock) -> dict:
|
||||
"""Return the JSON payload sent to POST /nginx/certificates."""
|
||||
requests = [
|
||||
r for r in httpx_mock.get_requests(method="POST") if r.url.path == "/api/nginx/certificates"
|
||||
]
|
||||
assert len(requests) == 1
|
||||
return json.loads(requests[0].content)
|
||||
|
||||
|
||||
class TestNpmClientCertificates:
|
||||
"""Test certificate creation (issue #17: NPM 2.x meta schema)."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _mock_api(self, httpx_mock, mock_token_response, mock_created_certificate):
|
||||
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/certificates",
|
||||
json=mock_created_certificate,
|
||||
status_code=201,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _client() -> NpmClient:
|
||||
return NpmClient(
|
||||
base_url="http://localhost:81/api",
|
||||
identity="test@test.com",
|
||||
secret="password",
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_certificate_payload(self, httpx_mock):
|
||||
"""Payload must only contain meta keys accepted by NPM 2.x."""
|
||||
async with self._client() as client:
|
||||
await client.create_certificate(domain_names=["app.example.com"])
|
||||
|
||||
payload = _certificate_payload(httpx_mock)
|
||||
assert payload == {
|
||||
"domain_names": ["app.example.com"],
|
||||
"meta": {"dns_challenge": False},
|
||||
"provider": "letsencrypt",
|
||||
}
|
||||
assert "letsencrypt_email" not in payload["meta"]
|
||||
assert "letsencrypt_agree" not in payload["meta"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_certificate_with_deprecated_email(self, httpx_mock):
|
||||
"""Deprecated email argument is accepted but never sent."""
|
||||
async with self._client() as client:
|
||||
await client.create_certificate(
|
||||
domain_names=["app.example.com"], email="test@example.com"
|
||||
)
|
||||
|
||||
payload = _certificate_payload(httpx_mock)
|
||||
assert "letsencrypt_email" not in payload["meta"]
|
||||
assert "email" not in payload["meta"]
|
||||
assert "letsencrypt_email" not in payload
|
||||
assert "email" not in payload
|
||||
assert "test@example.com" not in json.dumps(payload)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_certificate_dns_challenge(self, httpx_mock):
|
||||
"""dns_challenge flag is forwarded in meta."""
|
||||
async with self._client() as client:
|
||||
await client.create_certificate(domain_names=["app.example.com"], dns_challenge=True)
|
||||
|
||||
payload = _certificate_payload(httpx_mock)
|
||||
assert payload["meta"] == {"dns_challenge": True}
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_certificate_response_parsing(self):
|
||||
"""Response is parsed into a Certificate model."""
|
||||
async with self._client() as client:
|
||||
cert = await client.create_certificate(domain_names=["app.example.com"])
|
||||
|
||||
assert cert.id == 7
|
||||
assert cert.domain_names == ["app.example.com"]
|
||||
assert cert.provider == "letsencrypt"
|
||||
assert cert.nice_name == "app.example.com"
|
||||
assert cert.owner_user_id == 1
|
||||
assert cert.expires_on is not None
|
||||
assert cert.expires_on.strftime("%Y-%m-%d") == "2024-04-15"
|
||||
assert cert.meta == {"dns_challenge": False}
|
||||
+5
-5
@@ -10,15 +10,15 @@ from npm_mcp.logs import (
|
||||
)
|
||||
|
||||
SAMPLE_ACCESS_LOG = (
|
||||
'[22/May/2025:10:00:01 +0000] - 200 200 - GET https app.example.com'
|
||||
"[22/May/2025:10:00:01 +0000] - 200 200 - GET https app.example.com"
|
||||
' "/" [Client 10.0.0.1] [Length 1542] "Mozilla/5.0" "-"\n'
|
||||
'[22/May/2025:10:00:02 +0000] - 301 301 - GET http app.example.com'
|
||||
"[22/May/2025:10:00:02 +0000] - 301 301 - GET http app.example.com"
|
||||
' "/old-path" [Client 10.0.0.2] [Length 0] "curl/7.88" "-"\n'
|
||||
'[22/May/2025:10:00:03 +0000] - 404 404 - GET https app.example.com'
|
||||
"[22/May/2025:10:00:03 +0000] - 404 404 - GET https app.example.com"
|
||||
' "/missing" [Client 10.0.0.1] [Length 548] "Mozilla/5.0" "-"\n'
|
||||
'[22/May/2025:10:00:04 +0000] - 200 200 - POST https app.example.com'
|
||||
"[22/May/2025:10:00:04 +0000] - 200 200 - POST https app.example.com"
|
||||
' "/api/data" [Client 10.0.0.3] [Length 256] "python-requests/2.31" "-"\n'
|
||||
'[22/May/2025:10:00:05 +0000] - 502 502 - GET https app.example.com'
|
||||
"[22/May/2025:10:00:05 +0000] - 502 502 - GET https app.example.com"
|
||||
' "/health" [Client 10.0.0.1] [Length 166] "kube-probe/1.28" "-"\n'
|
||||
)
|
||||
|
||||
|
||||
@@ -16,7 +16,8 @@ class TestMultiInstance:
|
||||
|
||||
def test_multi_instance_from_dict(self):
|
||||
s = Settings(
|
||||
identity="ignored", secret="ignored",
|
||||
identity="ignored",
|
||||
secret="ignored",
|
||||
instances={
|
||||
"prod": {"api_url": "http://prod:81/api", "identity": "a@b", "secret": "p"},
|
||||
"staging": {"api_url": "http://staging:81/api", "identity": "c@d", "secret": "s"},
|
||||
@@ -28,7 +29,8 @@ class TestMultiInstance:
|
||||
|
||||
def test_default_instance_is_first(self):
|
||||
s = Settings(
|
||||
identity="i", secret="s",
|
||||
identity="i",
|
||||
secret="s",
|
||||
instances={
|
||||
"alpha": {"api_url": "http://a:81/api", "identity": "x", "secret": "y"},
|
||||
"beta": {"api_url": "http://b:81/api", "identity": "x", "secret": "y"},
|
||||
@@ -49,7 +51,8 @@ class TestMultiInstance:
|
||||
|
||||
def test_instance_proxy_defaults(self):
|
||||
s = Settings(
|
||||
identity="i", secret="s",
|
||||
identity="i",
|
||||
secret="s",
|
||||
instances={
|
||||
"prod": {
|
||||
"api_url": "http://p:81/api",
|
||||
@@ -76,7 +79,8 @@ class TestMultiInstance:
|
||||
def test_missing_required_field_raises(self):
|
||||
with pytest.raises(ValueError, match="missing required field"):
|
||||
Settings(
|
||||
identity="i", secret="s",
|
||||
identity="i",
|
||||
secret="s",
|
||||
instances={"bad": {"identity": "a", "secret": "b"}},
|
||||
)
|
||||
|
||||
@@ -88,28 +92,46 @@ class TestMultiInstance:
|
||||
# Invalid api_url type (int)
|
||||
with pytest.raises(ValueError, match="must be a string"):
|
||||
Settings(
|
||||
identity="i", secret="s",
|
||||
instances={"site1": {"api_url": 123, "identity": "a", "secret": "b"}}
|
||||
identity="i",
|
||||
secret="s",
|
||||
instances={"site1": {"api_url": 123, "identity": "a", "secret": "b"}},
|
||||
)
|
||||
|
||||
# Invalid log_dir type (list)
|
||||
with pytest.raises(ValueError, match="must be a string"):
|
||||
Settings(
|
||||
identity="i", secret="s",
|
||||
instances={"site1": {"api_url": "http://npm:81/api", "identity": "a", "secret": "b", "log_dir": []}}
|
||||
identity="i",
|
||||
secret="s",
|
||||
instances={
|
||||
"site1": {
|
||||
"api_url": "http://npm:81/api",
|
||||
"identity": "a",
|
||||
"secret": "b",
|
||||
"log_dir": [],
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
# Invalid proxy_defaults type (str)
|
||||
with pytest.raises(ValueError, match="must be an object"):
|
||||
Settings(
|
||||
identity="i", secret="s",
|
||||
instances={"site1": {"api_url": "http://npm:81/api", "identity": "a", "secret": "b", "proxy_defaults": "invalid"}}
|
||||
identity="i",
|
||||
secret="s",
|
||||
instances={
|
||||
"site1": {
|
||||
"api_url": "http://npm:81/api",
|
||||
"identity": "a",
|
||||
"secret": "b",
|
||||
"proxy_defaults": "invalid",
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
def test_default_instance_selection(self):
|
||||
# Explicit default instance configuration
|
||||
s = Settings(
|
||||
identity="i", secret="s",
|
||||
identity="i",
|
||||
secret="s",
|
||||
default_instance="beta",
|
||||
instances={
|
||||
"alpha": {"api_url": "http://a:81/api", "identity": "x", "secret": "y"},
|
||||
@@ -123,7 +145,8 @@ class TestMultiInstance:
|
||||
# Explicit default instance configured but not present in instances list
|
||||
with pytest.raises(ValueError, match="is not in configured instances"):
|
||||
Settings(
|
||||
identity="i", secret="s",
|
||||
identity="i",
|
||||
secret="s",
|
||||
default_instance="gamma",
|
||||
instances={
|
||||
"alpha": {"api_url": "http://a:81/api", "identity": "x", "secret": "y"},
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
"""Tests for the server module and its FastMCP initialization."""
|
||||
|
||||
import pytest
|
||||
|
||||
def test_server_imports():
|
||||
"""Ensure that the server and mcp instance can be imported without errors."""
|
||||
from npm_mcp.server import mcp
|
||||
|
||||
assert mcp is not None
|
||||
assert mcp.name == "npm-mcp"
|
||||
|
||||
|
||||
def test_server_http_app():
|
||||
"""Ensure that the http_app can be retrieved without AttributeError."""
|
||||
from npm_mcp.server import mcp
|
||||
|
||||
app = mcp.http_app()
|
||||
assert app is not None
|
||||
Reference in new issue
Block a user