Files
ServiceMap-Public/backend/tests/test_v163_security.py
NuklearRabbit adc2c70c21 ServiceMap: update tests and backend/app (+7 areas)
Public changes compared with the previous published export:
89 files changed.

Affected areas:
- backend/app: 21 files
- dependencies: 5 files
- deployment and CI: 6 files
- documentation: 2 files
- frontend: 3 files
- frontend/src: 20 files
- project files: 1 file
- tests: 30 files
- unraid: 1 file

Changed files:
- Updated: ".env.example"
- Updated: "Dockerfile.unraid"
- Updated: "README.md"
- Updated: "backend/Dockerfile"
- Added: "backend/app/alerts.py"
- Updated: "backend/app/auth.py"
- Added: "backend/app/backups.py"
- Updated: "backend/app/config_io.py"
- Updated: "backend/app/demo.py"
- Updated: "backend/app/discovery.py"
- Updated: "backend/app/discovery_store.py"
- Updated: "backend/app/docker_discovery.py"
- Updated: "backend/app/events.py"
- Updated: "backend/app/evidence.py"
- Updated: "backend/app/health.py"
- Updated: "backend/app/incidents.py"
- Added: "backend/app/loops.py"
- Updated: "backend/app/main.py"
- Updated: "backend/app/models.py"
- Updated: "backend/app/observation.py"
- Updated: "backend/app/probes.py"
- Added: "backend/app/response_cache.py"
- Updated: "backend/app/scheduler.py"
- Updated: "backend/app/semantic.py"
- Updated: "backend/app/store.py"
- Updated: "backend/pyproject.toml"
- Updated: "backend/tests/test_api.py"
- Updated: "backend/tests/test_config_io.py"
- Updated: "backend/tests/test_demo.py"
- Updated: "backend/tests/test_discovery_v120.py"
- Updated: "backend/tests/test_health.py"
- Updated: "backend/tests/test_probes.py"
- Updated: "backend/tests/test_scheduler.py"
- Updated: "backend/tests/test_v130_probe_reachability.py"
- Updated: "backend/tests/test_v160_evidence_changes.py"
- Added: "backend/tests/test_v163_alerts.py"
- Added: "backend/tests/test_v163_backups.py"
- Added: "backend/tests/test_v163_data_integrity.py"
- Added: "backend/tests/test_v163_efficiency.py"
- Added: "backend/tests/test_v163_health_performance.py"
- Added: "backend/tests/test_v163_loops.py"
- Added: "backend/tests/test_v163_management.py"
- Added: "backend/tests/test_v163_realtime.py"
- Added: "backend/tests/test_v163_security.py"
- Added: "backend/tests/test_v163_semantic_etag.py"
- Added: "compose.demo.yaml"
- Updated: "compose.yaml"
- Added: "docker-compose.broker.yml"
- Updated: "docker-compose.yml"
- Updated: "docs/ARCHITECTURE.md"
- Added: "frontend/e2e/a11y.spec.ts"
- Updated: "frontend/e2e/demo.spec.ts"
- Updated: "frontend/index.html"
- Updated: "frontend/nginx.conf"
- Updated: "frontend/package-lock.json"
- Updated: "frontend/package.json"
- Updated: "frontend/playwright.config.ts"
- Updated: "frontend/src/App.tsx"
- Updated: "frontend/src/LivingEdge.tsx"
- Added: "frontend/src/activityView.test.ts"
- Added: "frontend/src/activityView.ts"
- Updated: "frontend/src/api.ts"
- Added: "frontend/src/apiAuth.test.ts"
- Added: "frontend/src/components/ActionsMenu.tsx"
- Added: "frontend/src/components/ConfirmDialog.test.tsx"
- Added: "frontend/src/components/ConfirmDialog.tsx"
- Added: "frontend/src/components/StatusIcon.tsx"
- Updated: "frontend/src/demo/DemoWalkthrough.test.ts"
- Updated: "frontend/src/demo/DemoWalkthrough.tsx"
- Added: "frontend/src/elk-worker-url.d.ts"
- Added: "frontend/src/labels.ts"
- Updated: "frontend/src/main.tsx"
- Added: "frontend/src/realtime/refreshPlan.test.ts"
- Added: "frontend/src/realtime/refreshPlan.ts"
- Updated: "frontend/src/realtime/useRealtimeEvents.ts"
- Added: "frontend/src/routing/urlState.test.ts"
- Added: "frontend/src/routing/urlState.ts"
- Updated: "frontend/src/styles.css"
- Added: "frontend/src/topology/GraphListView.test.tsx"
- Added: "frontend/src/topology/GraphListView.tsx"
- Updated: "frontend/src/topology/ServiceNode.tsx"
- Updated: "frontend/src/topology/TopologyCommandBar.tsx"
- Added: "frontend/src/topology/semanticGraph.test.ts"
- Updated: "frontend/src/topology/semanticGraph.ts"
- Added: "frontend/src/topologyLayout.test.ts"
- Updated: "frontend/src/topologyLayout.ts"
- Updated: "package-lock.json"
- Updated: "package.json"
- Updated: "unraid/my-servicemap.xml"

Export provenance/manifests refreshed; excluded from the change summary.

Publish curated ServiceMap source from af46f684e468dffd3a5190e28d3b572d4c26bfd7
2026-11-20 13:51:46 +01:00

157 lines
6.9 KiB
Python

"""v1.6.3 security baseline: admin token for writes, origin/host checks, limits."""
from __future__ import annotations
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from starlette.requests import Request
from app import auth
from app import main as main_module
from app.config_io import parse_document
from app.discovery import DiscoveryManager
from app.discovery_store import DiscoveryStore
from app.store import Store
SERVICE = {"name": "API", "kind": "http", "url": "https://api.test"}
@pytest.fixture()
def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
main_module.store = Store(str(tmp_path / "servicemap.db"))
main_module.discovery_store = DiscoveryStore(main_module.store)
main_module.discovery_manager = DiscoveryManager(main_module.store, main_module.discovery_store)
monkeypatch.setenv("SERVICEMAP_DB", str(tmp_path / "servicemap.db"))
monkeypatch.delenv("SERVICEMAP_ADMIN_TOKEN_FILE", raising=False)
monkeypatch.delenv("SERVICEMAP_ALLOWED_HOSTS", raising=False)
auth.reset_token_cache()
yield TestClient(main_module.app)
auth.reset_token_cache()
def test_token_mode_keeps_reads_open_and_requires_the_token_for_writes(
client: TestClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("SERVICEMAP_AUTH_MODE", "token")
assert client.get("/api/v1/services").status_code == 200
assert client.get("/api/v1/topology/semantic").status_code == 200
refused = client.post("/api/v1/services", json=SERVICE)
assert refused.status_code == 401
assert refused.headers["www-authenticate"] == "Bearer"
assert client.post(
"/api/v1/services", json=SERVICE, headers={"Authorization": "Bearer wrong-token-value-123456789"}
).status_code == 401
token_file = tmp_path / "admin-token"
assert token_file.exists() # generated on first use, next to the database
token = token_file.read_text(encoding="utf-8").strip()
assert len(token) >= 24
headers = {"Authorization": f"Bearer {token}"}
assert client.post("/api/v1/services", json=SERVICE, headers=headers).status_code == 201
assert client.post("/api/v1/auth/verify", headers=headers).json() == {"ok": True}
assert client.get("/api/v1/meta").json()["write_auth"] == "admin_token"
# The token is stable across reads and never regenerated over a file.
auth.reset_token_cache()
assert auth.admin_token() == token
def test_too_short_admin_token_file_refuses_writes(
client: TestClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("SERVICEMAP_AUTH_MODE", "token")
short = tmp_path / "short-token"
short.write_text("too-short\n", encoding="utf-8")
monkeypatch.setenv("SERVICEMAP_ADMIN_TOKEN_FILE", str(short))
response = client.post("/api/v1/services", json=SERVICE, headers={"Authorization": "Bearer too-short"})
assert response.status_code == 503
def test_cross_site_mutations_are_refused_even_without_authentication(client: TestClient) -> None:
# disabled mode: no token, but a browser on another site cannot write.
assert client.post(
"/api/v1/services", json=SERVICE, headers={"Origin": "https://evil.example"}
).status_code == 403
assert client.post(
"/api/v1/maintenance/prune", headers={"Sec-Fetch-Site": "cross-site"}
).status_code == 403
assert client.post("/api/v1/services", json=SERVICE, headers={"Origin": "null"}).status_code == 403
# Same origin and header-less clients (curl, integrations) still work.
assert client.post(
"/api/v1/services", json=SERVICE, headers={"Origin": "http://testserver"}
).status_code == 201
assert client.post(
"/api/v1/services", json={**SERVICE, "name": "Worker"}
).status_code == 201
# Behind nginx/NPM the Host may lose the port while Origin keeps it, or
# the public name arrives as X-Forwarded-Host.
assert client.post(
"/api/v1/services",
json={**SERVICE, "name": "Proxied"},
headers={"Host": "192.0.2.10", "Origin": "http://192.0.2.10:1253"},
).status_code == 201
assert client.post(
"/api/v1/services",
json={**SERVICE, "name": "Forwarded"},
headers={"Host": "backend:8000", "X-Forwarded-Host": "servicemap.lan", "Origin": "https://servicemap.lan"},
).status_code == 201
assert client.post(
"/api/v1/services",
json={**SERVICE, "name": "Spoofed"},
headers={"Host": "192.0.2.10:1253", "Origin": "http://192.0.2.11:1253"},
).status_code == 403
# Reads are not affected by the Origin rule.
assert client.get("/api/v1/services", headers={"Origin": "https://evil.example"}).status_code == 200
def test_optional_host_allowlist_blocks_rebinding_but_keeps_loopback(
client: TestClient, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("SERVICEMAP_ALLOWED_HOSTS", "servicemap.lan,192.0.2.10")
assert client.get("/api/v1/services", headers={"Host": "attacker.example"}).status_code == 400
assert client.get("/api/v1/services", headers={"Host": "192.0.2.10:1253"}).status_code == 200
assert client.get("/health", headers={"Host": "127.0.0.1:8000"}).status_code == 200
def test_security_headers_body_limit_and_yaml_aliases(client: TestClient) -> None:
response = client.get("/health")
assert response.headers["x-content-type-options"] == "nosniff"
assert response.headers["x-frame-options"] == "DENY"
assert "frame-ancestors 'none'" in response.headers["content-security-policy"]
oversized = client.post(
"/api/v1/config/import",
content=b"x",
headers={"Content-Length": str(5 * 1024 * 1024), "Content-Type": "application/json"},
)
assert oversized.status_code == 413
bomb = "a: &a [x, x]\nb: &b [*a, *a]\nc: [*b, *b]\n"
with pytest.raises(ValueError, match="anchors of -aliassen"):
parse_document(bomb, "yaml")
def _request(method: str, path: str) -> Request:
return Request({"type": "http", "method": method, "path": path, "headers": [], "query_string": b""})
def test_oidc_role_requirements_cover_export_and_demo() -> None:
assert auth.required_role(_request("GET", "/api/v1/services")) == "viewer"
assert auth.required_role(_request("GET", "/api/v1/config")) == "admin"
assert auth.required_role(_request("POST", "/api/v1/demo")) == "admin"
assert auth.required_role(_request("POST", "/api/v1/demo/reset")) == "admin"
assert auth.required_role(_request("PUT", "/api/v1/services/x")) == "operator"
def test_cache_headers_keep_the_ui_current_after_a_deploy(client: TestClient) -> None:
# index.html (served by the SPA fallback / static mount) must revalidate.
response = client.get("/", follow_redirects=True)
if response.status_code == 200:
assert response.headers.get("cache-control") == "no-cache"
api = client.get("/api/v1/services")
assert "immutable" not in api.headers.get("cache-control", "")