Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/map_server/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,19 @@
"authorization", "password", "secret", "api_key", "apikey", "access_token",
"refresh_token", "private_key", "client_secret", "bearer", "cookie", "token", "signature",
"credential", "session_id", "sessionid", "x_amz_security_token",
"access_key", "auth_key", "api_secret", "jwt",
)



def _redact_url(value: str) -> str:
"""Redact credentials in URLs, including URLs embedded in text responses."""
parsed = urlparse(value)
try:
parsed = urlparse(value)
except ValueError:
# A malformed URL should not turn a harmless upstream response into a tool failure.
# Known configured secrets are redacted before this function is called.
return value
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
return value
query = parse_qsl(parsed.query, keep_blank_values=True)
Expand Down Expand Up @@ -410,6 +416,16 @@ def _api_request(
headers[str(name)] = str(value)

token = _apply_panel_auth(panel, api_kind, headers, params)
# Query-based authentication appends its secret only during auth application, so enforce
# the limit again after that token has been included.
try:
authenticated_query_size = len(
json.dumps(params, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
)
except (TypeError, ValueError):
raise ValueError("query_params must be JSON-serializable.") from None
if authenticated_query_size > 65536:
raise ValueError("query_params including authentication exceeds the 64 KB input limit.")
if encoded_json is not None:
headers["Content-Type"] = "application/json"
elif raw_bytes is not None:
Expand Down Expand Up @@ -514,6 +530,16 @@ def _api_request(
def _signed_wings_url(panel_id: str, server_id: str, operation: str, query: dict[str, Any]) -> tuple[str | None, dict[str, Any] | None]:
if not SERVER_ID_RE.fullmatch(server_id or ""):
raise ValueError("server_id contains unsupported characters.")
if operation not in {"upload", "download"}:
raise ValueError("operation must be upload or download.")
if not isinstance(query, dict):
raise ValueError("File-transfer query must be an object.")
try:
query_size = len(json.dumps(query, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
except (TypeError, ValueError):
raise ValueError("File-transfer query must be JSON-serializable.") from None
if query_size > 65536:
raise ValueError("File-transfer query exceeds the 64 KB input limit.")
panel = _panel(panel_id)
if normalize_provider(panel.get("provider")) not in PTERODACTYL_COMPATIBLE:
raise ValueError(
Expand Down
4 changes: 4 additions & 0 deletions src/map_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ def _read_panels() -> dict[str, dict[str, Any]]:
if not re.fullmatch(r"[!#$%&'*+.^_|~0-9A-Za-z-]{1,128}", auth_header):
raise RuntimeError(f"Panel '{panel_id}' auth_header is not a valid HTTP header name.")
auth_scheme = str(entry.get("auth_scheme", "Bearer" if auth_type == "bearer" else "")).strip()
if len(auth_scheme) > 128 or any(ord(char) < 32 or ord(char) == 127 for char in auth_scheme):
raise RuntimeError(f"Panel '{panel_id}' auth_scheme cannot contain control characters and must be at most 128 characters.")
auth_query_param = str(entry.get("auth_query_param") or ("apikey" if provider == "mcsmanager" else "api_key")).strip()
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", auth_query_param):
raise RuntimeError(f"Panel '{panel_id}' auth_query_param contains unsupported characters.")
Expand All @@ -157,6 +159,8 @@ def _read_panels() -> dict[str, dict[str, Any]]:
or any(char.isspace() for char in oauth_token_path)
or "?" in oauth_token_path
or "#" in oauth_token_path
or "%" in oauth_token_path
or any(ord(char) < 32 or ord(char) == 127 for char in oauth_token_path)
or "://" in oauth_token_path
or "\\" in oauth_token_path
or any(part in {".", ".."} for part in oauth_token_path.strip("/").split("/"))
Expand Down
13 changes: 11 additions & 2 deletions src/map_server/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,17 @@ def normalize_api_base_path(panel: dict[str, Any], provider: str) -> str:
raw = str(panel.get("api_base_path", DEFAULT_API_BASE_PATH[provider]) or "").strip()
if not raw:
return ""
if any(char.isspace() for char in raw) or "?" in raw or "#" in raw or "://" in raw or "\\" in raw:
raise RuntimeError(f"Panel '{panel.get('id', '?')}' api_base_path must be a relative URL path.")
if (
any(char.isspace() or ord(char) < 32 or ord(char) == 127 for char in raw)
or "?" in raw
or "#" in raw
or "%" in raw
or "://" in raw
or "\\" in raw
):
raise RuntimeError(
f"Panel '{panel.get('id', '?')}' api_base_path must be a relative URL path without encoded characters."
)
parts = raw.strip("/").split("/")
if any(part in {".", ".."} for part in parts):
raise RuntimeError(f"Panel '{panel.get('id', '?')}' api_base_path cannot contain traversal segments.")
Expand Down
10 changes: 8 additions & 2 deletions src/map_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,12 +408,18 @@ def server_upload_file_base64(
impersonate=IMPERSONATE,
timeout=90,
allow_redirects=False,
stream=True,
)
except Exception as exc:
raise RuntimeError(f"Wings upload failed ({type(exc).__name__}). Signed URL and credentials were not logged.") from None
try:
status_code = response.status_code
finally:
# The upload result body is deliberately unused. Do not buffer an untrusted node response.
response.close()
return {
"ok": 200 <= response.status_code < 300,
"status_code": response.status_code,
"ok": 200 <= status_code < 300,
"status_code": status_code,
"filename": filename,
"directory": directory,
"bytes_uploaded": len(contents),
Expand Down
102 changes: 102 additions & 0 deletions tests/test_safety.py
Original file line number Diff line number Diff line change
Expand Up @@ -770,3 +770,105 @@ def test_oauth_token_with_60_second_lifetime_is_cached_until_refresh_window(monk
assert first == "short-lived-token"
assert second == first
assert len(calls) == 1


def test_redaction_handles_malformed_url_in_upstream_text(monkeypatch):
configured_panel(monkeypatch)
result = client._safe_json({"message": "bad URL https://[broken and access_key=known-secret"})
assert "bad URL" in result["message"]
assert "https://[broken" in result["message"]


@pytest.mark.parametrize("api_base_path", ["/api/%2e%2e/internal", "/api/../internal", "/api/\x01bad"])
def test_api_base_path_rejects_encoded_or_control_path_segments(monkeypatch, api_base_path):
monkeypatch.setenv(
"MAP_PANELS_JSON",
json.dumps([{
"id": "custom",
"provider": "generic_rest",
"base_url": "https://api.example.test",
"api_base_path": api_base_path,
"auth_type": "none",
}]),
)
with pytest.raises(RuntimeError, match="api_base_path"):
server.list_panels()


def test_query_auth_token_is_included_in_size_limit(monkeypatch):
configured_mcsmanager(monkeypatch)
called = []
monkeypatch.setattr(client.requests, "request", lambda *args, **kwargs: called.append(args))
with pytest.raises(ValueError, match="including authentication"):
client._api_request(
"mcsm", "native", "GET", "overview",
query_params={"x": "a" * 65510},
)
assert called == []


def test_signed_wings_query_is_bounded(monkeypatch):
configured_panel(monkeypatch)
called = []
monkeypatch.setattr(client.requests, "get", lambda *args, **kwargs: called.append(args))
with pytest.raises(ValueError, match="64 KB"):
client._signed_wings_url("bp", "abc12345", "download", {"file": "x" * 65540})
assert called == []


def test_file_upload_does_not_buffer_node_response(monkeypatch):
import base64

configured_panel(monkeypatch)
monkeypatch.setattr(server, "_signed_wings_url", lambda *args, **kwargs: ("https://node.example.test/upload?token=signed", None))
response = FakeResponse(status_code=201, body=b"x" * 100000)
calls = []

def fake_post(url, **kwargs):
calls.append((url, kwargs))
return response

monkeypatch.setattr(server.requests, "post", fake_post)
result = server.server_upload_file_base64("bp", "abc12345", "test.bin", base64.b64encode(b"hello").decode())

assert result["ok"] is True
assert result["status_code"] == 201
assert calls[0][1]["stream"] is True
assert response.closed is True


def test_custom_access_key_header_and_response_values_are_redacted(monkeypatch):
monkeypatch.setenv(
"MAP_PANELS_JSON",
json.dumps([{
"id": "custom",
"provider": "generic_rest",
"base_url": "https://api.example.test",
"auth_type": "none",
"custom_headers": {"X-Access-Key": "custom-access-secret"},
}]),
)
result = client._safe_json({
"access_key": "custom-access-secret",
"message": "server echoed custom-access-secret",
"url": "https://api.example.test/status?access_key=custom-access-secret&ok=1",
})
assert result["access_key"] == "[REDACTED]"
assert "custom-access-secret" not in json.dumps(result)
assert "ok=1" in result["url"]


def test_auth_scheme_rejects_header_control_characters(monkeypatch):
monkeypatch.setenv(
"MAP_PANELS_JSON",
json.dumps([{
"id": "custom",
"provider": "generic_rest",
"base_url": "https://api.example.test",
"api_key": "test-key",
"auth_type": "bearer",
"auth_scheme": "Bearer\r\nX-Injected: yes",
}]),
)
with pytest.raises(RuntimeError, match="auth_scheme"):
server.list_panels()
Loading