diff --git a/.env.example b/.env.example index ce45f49..5553066 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,6 @@ -# Local development example only. Never commit real API keys or bearer tokens. -MAP_PANELS_JSON=[{"id":"panel-one","name":"Example Panel One","base_url":"https://panel-one.example.net","client_api_key":"REPLACE_WITH_CLIENT_API_KEY","application_api_key":"REPLACE_WITH_APPLICATION_API_KEY","admin_api_key":"REPLACE_WITH_ROOT_ADMIN_CLIENT_API_KEY"},{"id":"panel-two","name":"Example Panel Two","base_url":"https://panel-two.example.net","client_api_key":"REPLACE_WITH_CLIENT_API_KEY","application_api_key":"","admin_api_key":""}] +# Local development example only. Never commit real API keys, passwords, or bearer tokens. +# AMP uses username/password session login (not an API key); use HTTPS and a least-privilege account. +MAP_PANELS_JSON=[{"id":"legacy-ptero","name":"Pterodactyl 1.x example","provider":"pterodactyl","panel_version":"1.x","base_url":"https://ptero.example.net","client_api_key":"REPLACE_WITH_CLIENT_API_KEY","application_api_key":"REPLACE_WITH_APPLICATION_API_KEY"},{"id":"calagopus","name":"Calagopus example","provider":"calagopus","base_url":"https://calagopus.example.net","api_base_path":"/api","api_key":"REPLACE_WITH_CALAGOPUS_API_KEY","auth_type":"bearer"},{"id":"mcsm","name":"MCSManager 10 example","provider":"mcsmanager","panel_version":"10.x","base_url":"https://mcsm.example.net","api_base_path":"/api","api_key":"REPLACE_WITH_MCSMANAGER_API_KEY","auth_type":"query","auth_query_param":"apikey"},{"id":"amp","name":"CubeCoders AMP example","provider":"amp","base_url":"https://amp.example.net","api_base_path":"/API","auth_type":"amp_session","auth_username":"REPLACE_WITH_AMP_SERVICE_USER","auth_password":"REPLACE_WITH_AMP_PASSWORD"},{"id":"custom-rest","name":"Custom REST panel example","provider":"generic_rest","base_url":"https://api.example.net","api_base_path":"/api/v2","api_key":"REPLACE_WITH_PANEL_TOKEN","auth_type":"bearer"}] MAP_TRANSPORT=http MAP_SERVER_NAME=Model Access Panel (MAP) @@ -16,7 +17,7 @@ MAP_MAX_INLINE_FILE_BYTES=6000000 MAP_TRUSTED_WINGS_HOSTS= MAP_LOG_LEVEL=info -# Legacy single-panel compatibility (used only if multi-panel variables are empty): +# Legacy single-panel compatibility (used only if multi-panel variables are empty; supports Pterodactyl/Pelican): # PANEL_NAME=Example Panel # PANEL_BASE_URL=https://panel.example.net # PANEL_CLIENT_API_KEY=REPLACE_WITH_CLIENT_API_KEY diff --git a/.github/dependabot.yml b/.github/dependabot.yml index e9fccd3..95a2fca 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,6 +5,9 @@ updates: schedule: interval: weekly open-pull-requests-limit: 8 + ignore: + - dependency-name: "mcp" + update-types: ["version-update:semver-major"] - package-ecosystem: github-actions directory: / schedule: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c419d6..2205d6a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ jobs: python-version: ["3.11", "3.12", "3.13"] steps: - name: Check out source - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Set up Python uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 with: @@ -49,11 +49,11 @@ jobs: contents: read steps: - name: Check out full history - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.1 with: go-version: "1.25.x" - name: Install Gitleaks CLI diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 829b0a4..fd83f11 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -23,7 +23,7 @@ jobs: security-events: write steps: - name: Check out source - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Initialize CodeQL uses: github/codeql-action/init@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 50a5f10..ea219a1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: contents: write steps: - name: Check out tag - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - name: Set up Python uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 with: @@ -30,6 +30,9 @@ jobs: run: | python -m pip install --upgrade pip python -m pip install -e '.[dev]' + - name: Verify tag matches package version + run: | + python -c "import os, tomllib; v=tomllib.load(open('pyproject.toml','rb'))['project']['version']; t=os.environ['GITHUB_REF_NAME'].removeprefix('v'); print('release tag version:',t,'package version:',v); raise SystemExit(t!=v)" - name: Validate release run: | ruff check src tests deploy diff --git a/CHANGELOG.md b/CHANGELOG.md index ccca7d7..fbbc161 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ MAP is currently in beta. ## Unreleased +- Preserve Pterodactyl 1.x Client/Application compatibility and gate the 2.x-only Admin API when the host version is configured. +- Add provider-aware native REST adapters for Calagopus, MCSManager, Crafty Controller, PufferPanel, and configurable custom REST APIs. +- Add MCSManager-native instance listing, actions, command, and output-log tools plus PufferPanel OAuth2 client-credentials refresh. +- Add CubeCoders AMP session login with cached SESSIONID injection, and HTTP Basic authentication for custom REST panels. +- Add provider-specific auth configuration and tests for legacy routing, custom paths, query/header auth, and token caching. + - Split runtime into configuration, panel-client, transport-security, and MCP tool modules. - Add stdio alongside Streamable HTTP. - Expand configuration, architecture, deployment, security, and troubleshooting docs. diff --git a/README.md b/README.md index f00f514..3167be7 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Model Access Panel (MAP)

- One MCP gateway. Multiple Pterodactyl panels. Broad API control.
+ One MCP gateway. Multiple game-server panels. Broad API control.
A self-hosted, open-source administration gateway from RealmsNetwork.

@@ -12,18 +12,18 @@ MCP transports

-MAP is a self-hosted [Model Context Protocol](https://modelcontextprotocol.io/) server for administering one or many [Pterodactyl](https://pterodactyl.io/) panels from MCP-compatible clients. Configure each host once, choose it by ID in a tool call, and use dedicated server tools or the generic API gateway. +MAP is a self-hosted [Model Context Protocol](https://modelcontextprotocol.io/) gateway for administering multiple game-server and hosting panels. It preserves the familiar Pterodactyl API workflow for older 1.x and newer 2.x installations, and adds provider adapters for panels with different API conventions. Configure each host once, select it by ID, and use dedicated tools where a provider is supported or the native API gateway elsewhere. No universal adapter can infer vendor-specific endpoints or permissions automatically. **Heads up:** MAP is an administrative integration, not a read-only dashboard. Depending on configured API keys and panel permissions, it can stop servers, execute console commands, alter files, delete backups, and call destructive panel-wide endpoints. Only install it for systems you administer. ## Features -- **Multiple panels/hosts:** distinct IDs, labels, HTTPS origins, and credentials. -- **Broad API access:** generic Client, Application, and Admin request tool supporting GET, POST, PUT, PATCH, and DELETE. -- **Server operations:** list servers, inspect resources, start/stop/restart/kill, and send console commands. +- **Multiple providers:** each panel has its own ID, origin, provider type, endpoint prefix, and credentials. +- **Broad API access:** namespaced Client/Application/Admin requests for compatible panels and a generic native REST request tool supporting GET, POST, PUT, PATCH, and DELETE. +- **Server operations:** Pterodactyl/Pelican server power/resources/console/file/backup tools; native MCSManager instance list, power, console-command, and output-log tools; AMP session-based native calls. - **Files and backups:** browse/read/write, create directories, rename/delete files, manage backups, and transfer bounded binary files through trusted Wings hosts. - **Two MCP transports:** Streamable HTTP for hosted deployments and stdio for local MCP clients. -- **Customization:** configure the MCP display name, request/response limits, panel routing, timeout, and trusted Wings hosts. +- **Customization:** configure the MCP display name, request/response limits, native API prefix, auth scheme/header/query parameter, optional custom headers, panel routing, timeout, and trusted Wings hosts. - **Deployment options:** Docker, systemd, and interactive panel configuration. - **Maintainer automation:** Python test matrix, static checks, package build, secret scanning, CodeQL, dependency updates, and issue templates. @@ -78,11 +78,27 @@ Set `MAP_PANELS_JSON` to a JSON array. Each panel uses a unique `id`; pass that These are placeholders, not working credentials. Each host has its own base URL and keys. MAP will not reuse keys from another configured panel. For production, use the interactive configurator or a secret store. See [Configuration](docs/configuration.md). +## Supported panel providers + +| Provider | API mode | Support level | +| --- | --- | --- | +| [Pterodactyl](https://docs.pterodactyl.io/v1/api) 1.x | `client` / `application` | Dedicated server tools and generic API; Client server listing uses the older `GET /api/client` route. Admin API is unavailable in 1.x. | +| [Pterodactyl](https://docs.pterodactyl.io/v2/api) 2.x | `client` / `application` / `admin` | Dedicated server tools plus the 2.x Admin namespace when configured. | +| [Pelican Panel](https://pelican.dev/docs/panel/advanced/api-docs/) | `client` / `application` | Pterodactyl-compatible Client/Application APIs. | +| [Calagopus](https://calagopus.com/docs/) | `native` | Generic/native REST adapter with default prefix `/api`; its API and keys are not compatible with Pterodactyl. The native API reference is available on each Calagopus panel at `/api`. | +| [MCSManager](https://docs.mcsmanager.com/apis/api_instance.html) 10.x | `native` | Dedicated instance list, start/stop/restart/kill, command, and output-log tools; native REST access for other endpoints. MCSManager 9.x has API differences, so verify endpoints against your installed version. | +| [Crafty Controller](https://docs.craftycontrol.com/pages/developer-guide/api-reference/v2/) API v2 | `native` | Generic REST adapter, default prefix `/api/v2`, configurable auth header/scheme or other supported auth mode. | +| [PufferPanel](https://docs.pufferpanel.com/en/2.x/guides/common-problems.html) 2.x | `native` | Generic REST adapter with OAuth2 client-credentials token refresh, or a directly supplied bearer token. | +| [CubeCoders AMP](https://github-wiki-see.page/m/CubeCoders/AMP/wiki/Developers%3A-How-do-I-start-working-with-AMP%27s-API%3F) | `native` | Session-based native API: MAP logs in and caches SESSIONID for POST JSON calls. Requires a least-privilege AMP account; no API key is assumed. | +| Other HTTPS REST panels | `native` | Generic adapter with configurable API prefix and `bearer`, `header`, `query`, `basic`, `oauth2_client_credentials`, or `none` auth plus optional custom headers. Provider-specific actions need an adapter and tests before MAP claims native tool support. | + +Use `api="native"` for MCSManager, Crafty, PufferPanel, Calagopus, AMP, and generic REST requests. For Pterodactyl/Pelican, use the corresponding API namespace. Calagopus uses its own native API and its keys must be regenerated after migration. AMP uses session authentication, and generic REST profiles also support HTTP Basic authentication. See [provider configuration](docs/configuration.md) and [tool reference](docs/tools.md). + ## Deployment and security MAP binds to loopback by default. Never expose plaintext HTTP directly to the Internet. For remote access, use HTTPS termination, a strong random bearer token, firewall restrictions, and any additional access control required by your environment. Docker Compose binds to host loopback and requires a bearer token. -MAP is **not** an SSH server and does not grant root access to its host or Wings nodes. Its authority is limited to configured Pterodactyl API credentials and permissions. +MAP is **not** an SSH server and does not grant root access to its host or Wings nodes. Its authority is limited to the configured provider's API credentials and permissions. - [Security model](docs/security.md) - [Docker and systemd deployment](docs/deployment.md) @@ -96,7 +112,9 @@ MAP is **not** an SSH server and does not grant root access to its host or Wings ## API compatibility -Pterodactyl 1.x documents Client and Application APIs. Pterodactyl 2.x documents Client, Application, and Admin APIs, with different key requirements. MAP does not invent missing endpoints: consult docs for your installed panel version and use supported namespaces. See official [1.x API docs](https://docs.pterodactyl.io/v1/api) and [2.x API docs](https://docs.pterodactyl.io/v2/api). +MAP intentionally keeps Pterodactyl 1.x support. Both 1.x and 2.x expose Client and Application APIs; Admin is a 2.x API. Configure `panel_version: "1.x"` to reject Admin calls locally, or `auto` when the version is unknown. The generic API tool does not invent endpoints: check the documentation for the exact panel and version. + +Official references: [AMP API guide](https://github-wiki-see.page/m/CubeCoders/AMP/wiki/Developers%3A-How-do-I-start-working-with-AMP%27s-API%3F), [Calagopus migration notes](https://calagopus.com/docs/additional/migrations/pterodactyl/standalone), [Pterodactyl 1.x](https://docs.pterodactyl.io/v1/api), [Pterodactyl 2.x](https://docs.pterodactyl.io/v2/api), [MCSManager API](https://docs.mcsmanager.com/apis/api_instance.html), [Crafty API v2](https://docs.craftycontrol.com/pages/developer-guide/api-reference/v2/), and [PufferPanel OAuth2 guidance](https://docs.pufferpanel.com/en/2.x/guides/common-problems.html). ## Development diff --git a/deploy/configure_panels.py b/deploy/configure_panels.py index fa1f491..4a8dcf7 100644 --- a/deploy/configure_panels.py +++ b/deploy/configure_panels.py @@ -4,6 +4,7 @@ import base64 import getpass +import ipaddress import grp import json import os @@ -13,11 +14,6 @@ CONFIG = Path("/etc/realmsnetwork-map/map.env") PANEL_ID = re.compile(r"^[A-Za-z0-9_-]{1,48}$") -PANEL_KEYS = { - "MAP_HOST", "MAP_PORT", "MAP_MCP_BEARER_TOKEN", "MAP_MAX_RESPONSE_CHARS", - "MAP_MAX_INLINE_FILE_BYTES", "MAP_LOG_LEVEL", "MAP_TRUSTED_WINGS_HOSTS", -} - def read_settings() -> dict[str, str]: result: dict[str, str] = {} @@ -45,7 +41,7 @@ def main() -> int: print("Model Access Panel (MAP) panel setup") print("API keys are hidden as you type and are stored only in the root-owned server environment file.") while True: - raw_count = input("How many Pterodactyl panels should MAP configure? [1]: ").strip() + raw_count = input("How many panels should MAP configure? [1]: ").strip() if not raw_count: count = 1 break @@ -67,24 +63,140 @@ def main() -> int: name = input(f"Display name [{panel_id}]: ").strip() or panel_id base_url = input("Panel base URL (https://...): ").strip().rstrip("/") parsed = urlparse(base_url) - if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: - print("Invalid URL: use an HTTPS panel URL without embedded credentials, query, or fragment.") + try: + parsed.port + except ValueError: + print("Invalid panel URL port.") return 2 - client_key = getpass.getpass("Client API key (required for server power/files; leave blank only if not needed): ").strip() - application_key = getpass.getpass("Application API key (for panel-wide application endpoints; optional): ").strip() - admin_key = getpass.getpass("Root-admin Client API key (for Admin endpoints; optional): ").strip() - if not (client_key or application_key or admin_key): - print("At least one API key is required for each panel.") + try: + address = ipaddress.ip_address(parsed.hostname or "") + except ValueError: + address = None + if ( + not base_url + or len(base_url) > 2048 + or any(char.isspace() for char in base_url) + or parsed.scheme != "https" + or not parsed.hostname + or parsed.username + or parsed.password + or parsed.query + or parsed.fragment + or (address and not address.is_global) + ): + print("Invalid URL: use a public HTTPS panel URL without embedded credentials, query, or fragment.") return 2 - panels.append({ + provider_choices = { + "1": "pterodactyl", + "2": "pelican", + "3": "mcsmanager", + "4": "crafty", + "5": "pufferpanel", + "6": "generic_rest", + "7": "calagopus", + "8": "amp", + } + print("Panel provider: 1) Pterodactyl 2) Pelican 3) MCSManager 4) Crafty Controller 5) PufferPanel 6) Generic REST 7) Calagopus 8) CubeCoders AMP") + raw_provider = input("Choose provider [1]: ").strip() or "1" + provider = provider_choices.get(raw_provider, raw_provider.lower()) + if provider not in set(provider_choices.values()): + print("Unsupported provider. Choose one of the listed providers.") + return 2 + + record = { "id": panel_id, "name": name, "base_url": base_url, - "client_api_key": client_key, - "application_api_key": application_key, - "admin_api_key": admin_key, - }) + "provider": provider, + } + if provider == "pterodactyl": + panel_version = input("Pterodactyl API version (1.x / 2.x / auto) [auto]: ").strip().lower() or "auto" + if panel_version not in {"1", "1.x", "2", "2.x", "auto"}: + print("Enter 1.x, 2.x, or auto.") + return 2 + record["panel_version"] = "1.x" if panel_version in {"1", "1.x"} else "2.x" if panel_version in {"2", "2.x"} else "auto" + record["client_api_key"] = getpass.getpass("Client API key (required for server actions): ").strip() + record["application_api_key"] = getpass.getpass("Application API key (optional for panel-wide endpoints): ").strip() + if record["panel_version"] != "1.x": + record["admin_api_key"] = getpass.getpass("Root-admin Client API key (optional, Pterodactyl 2.x): ").strip() + else: + record["admin_api_key"] = "" + if not (record["client_api_key"] or record["application_api_key"]): + print("Configure at least a Client or Application API key.") + return 2 + elif provider == "pelican": + record["client_api_key"] = getpass.getpass("Client API key (required for server actions): ").strip() + record["application_api_key"] = getpass.getpass("Application API key (optional for panel-wide endpoints): ").strip() + if not (record["client_api_key"] or record["application_api_key"]): + print("Configure at least a Client or Application API key.") + return 2 + elif provider == "mcsmanager": + record["api_key"] = getpass.getpass("MCSManager API key (hidden input): ").strip() + version = input("MCSManager version [10.x]: ").strip() or "10.x" + if version not in {"9", "9.x", "10", "10.x"}: + print("Enter 9.x or 10.x.") + return 2 + record["panel_version"] = "9.x" if version in {"9", "9.x"} else "10.x" + record["api_base_path"] = "/api" + record["auth_type"] = "query" + record["auth_query_param"] = "apikey" + if not record["api_key"]: + print("MCSManager requires an API key for the native API.") + return 2 + elif provider == "amp": + record["api_base_path"] = input("AMP API base path [/API]: ").strip() or "/API" + record["auth_type"] = "amp_session" + record["auth_username"] = input("AMP username (create a least-privilege service account): ").strip() + record["auth_password"] = getpass.getpass("AMP password (hidden input): ") + record["amp_totp_token"] = getpass.getpass("AMP 2FA token (blank if not required; hidden input): ").strip() + if not record["auth_username"] or not record["auth_password"]: + print("AMP needs a username and password for its session API.") + return 2 + elif provider == "pufferpanel": + record["api_base_path"] = input("PufferPanel API base path [/api]: ").strip() or "/api" + oauth_id = input("OAuth client ID (blank to use a direct access token): ").strip() + oauth_secret = getpass.getpass("OAuth client secret (hidden; blank for direct token): ").strip() if oauth_id else "" + if oauth_id and oauth_secret: + record["oauth_client_id"] = oauth_id + record["oauth_client_secret"] = oauth_secret + record["auth_type"] = "oauth2_client_credentials" + record["oauth_token_path"] = "/oauth2/token" + else: + record["api_key"] = getpass.getpass("Bearer access token (hidden; expires and must be rotated): ").strip() + record["auth_type"] = "bearer" + if not record["api_key"]: + print("Configure OAuth client credentials or a bearer access token.") + return 2 + else: + default_path = "/api/v2" if provider == "crafty" else "/api" if provider == "calagopus" else "/API" if provider == "amp" else "" + record["api_base_path"] = input(f"Native API base path [{default_path or '/'}]: ").strip() or default_path + print("Authentication style: bearer / header / query / basic / none / oauth2_client_credentials") + auth_type = input("Auth style [bearer]: ").strip().lower() or "bearer" + if auth_type not in {"bearer", "header", "query", "basic", "none"}: + print("Unsupported auth style.") + return 2 + record["auth_type"] = auth_type + if auth_type == "basic": + record["auth_username"] = input("HTTP Basic auth username: ").strip() + record["auth_password"] = getpass.getpass("HTTP Basic auth password (hidden input): ") + if not record["auth_username"] or not record["auth_password"]: + print("Basic auth requires a username and password.") + return 2 + elif auth_type != "none": + record["api_key"] = getpass.getpass("API key/token (hidden input): ").strip() + if not record["api_key"]: + print("An API key/token is required for that auth style.") + return 2 + if auth_type == "header": + record["auth_header"] = input("HTTP auth header [X-API-Key]: ").strip() or "X-API-Key" + record["auth_scheme"] = input("Auth scheme/prefix (blank for raw key) []: ").strip() + elif auth_type == "query": + record["auth_query_param"] = input("Query parameter name [api_key]: ").strip() or "api_key" + elif auth_type == "bearer": + record["auth_header"] = "Authorization" + record["auth_scheme"] = "Bearer" + panels.append(record) previous_hosts = existing.get("MAP_TRUSTED_WINGS_HOSTS", "") prompt = "Exact Wings/node HTTPS hostnames for binary transfers, comma-separated" if previous_hosts: @@ -111,7 +223,10 @@ def main() -> int: settings = { "MAP_HOST": host, "MAP_PORT": existing.get("MAP_PORT", "8765"), + "MAP_SERVER_NAME": existing.get("MAP_SERVER_NAME", "Model Access Panel (MAP)"), "MAP_MAX_RESPONSE_CHARS": existing.get("MAP_MAX_RESPONSE_CHARS", "200000"), + "MAP_MAX_REQUEST_BODY_BYTES": existing.get("MAP_MAX_REQUEST_BODY_BYTES", "2000000"), + "MAP_MAX_RESPONSE_BYTES": existing.get("MAP_MAX_RESPONSE_BYTES", "5000000"), "MAP_MAX_INLINE_FILE_BYTES": existing.get("MAP_MAX_INLINE_FILE_BYTES", "6000000"), "MAP_LOG_LEVEL": existing.get("MAP_LOG_LEVEL", "info"), "MAP_TRUSTED_WINGS_HOSTS": trusted_hosts, diff --git a/docs/architecture.md b/docs/architecture.md index 16972b6..252605e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,7 +1,8 @@ # Architecture - `config.py` loads environment settings, validates panel identifiers/origins, and selects credentials by API namespace. -- `client.py` sends requests, redacts response content, and validates signed Wings transfer URLs. +- `client.py` sends provider-aware requests, applies configurable authentication, refreshes PufferPanel OAuth2 tokens, redacts responses, and validates signed Wings transfer URLs. +- `providers.py` maps provider types to API prefixes and version-compatibility rules. - `security.py` provides the ASGI bearer guard for HTTP transport. - `server.py` registers MCP tools and offers HTTP/stdio entry points. - `deploy/` contains systemd and interactive configuration files; `docs/` contains operator and contributor guides. diff --git a/docs/configuration.md b/docs/configuration.md index f38823e..75915da 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -15,7 +15,7 @@ Set `MAP_PANELS_JSON` to a JSON array. Each item has these fields: | `application_api_key` | Depends on use | Application API key for panel-wide endpoints. | | `admin_api_key` | Depends on use | Root-administrator Client API key for Admin API where supported. | -Every panel is independent. A missing key disables that namespace; MAP never falls back to credentials from another panel. +Every panel is independent; configuration supports at most 20 panel entries. A missing key disables that namespace, and MAP never falls back to credentials from another panel. Panel IDs and display names are limited to 48 and 128 characters respectively. ### Key selection @@ -25,6 +25,111 @@ Every panel is independent. A missing key disables that namespace; MAP never fal Pterodactyl 1.x documents Client and Application APIs. Pterodactyl 2.x documents Client, Application, and Admin APIs. Forks may differ. See official [1.x](https://docs.pterodactyl.io/v1/api) and [2.x](https://docs.pterodactyl.io/v2/api) docs. + +## Provider selection + +Each panel may set a `provider` (also accepted as `panel_type` or `type`). Unknown providers are rejected rather than silently routed to the wrong API. + +| Provider | Default API prefix | Auth defaults | Dedicated tools | +| --- | --- | --- | --- | +| `pterodactyl` | Namespace routes under `/api/client`, `/api/application`, or `/api/admin` | Separate Client/Application/Admin credentials | Server power, console, files, backups, resource state | +| `pelican` | Pterodactyl-compatible Client/Application routes | Client/Application credentials | Compatible server tools; no Admin namespace | +| `mcsmanager` | `/api` | API key in query parameter `apikey` | Instance list, power actions, command, output log | +| `crafty` | `/api/v2` | Bearer key by default; configurable | Generic/native REST | +| `pufferpanel` | `/api` | OAuth2 client credentials, automatically refreshed when configured | Generic/native REST | +| `calagopus` | `/api` | Bearer key by default; configurable | Generic/native REST; its API differs from Pterodactyl | +| `amp` | `/API` | Username/password login with optional TOTP; MAP caches the session ID | Generic/native AMP POST JSON API; no API key is used | +| `generic_rest` | Empty unless `api_base_path` is configured | Bearer by default; configurable | Generic/native REST | + +For Pterodactyl, set `panel_version: "1.x"` to reject the 2.x-only Admin namespace, or `panel_version: "2.x"` for a 2.x panel. The default is `auto` for existing configurations. Pterodactyl 1.x and 2.x both list the user's servers via `GET /api/client`. The Application API's full server list is `GET /api/application/servers`. + +Calagopus is a separate implementation, not an API-compatible Pterodactyl fork. Its API docs are available at the panel's `/api` path, and API keys must be regenerated after migrating from Pterodactyl. See the [official migration guide](https://calagopus.com/docs/additional/migrations/pterodactyl/standalone). MAP treats it as native REST instead of routing Pterodactyl tools to it. + +For non-Pterodactyl providers, call `panel_api_request` with `api="native"` and a relative `path` from the vendor's API documentation. The adapter prepends `api_base_path` and then applies the configured authentication. MAP does not assume endpoint equivalence across unrelated panels. + +### Native provider fields + +| Field | Meaning | +| --- | --- | +| `provider` | `pterodactyl` (default), `pelican`, `mcsmanager`, `crafty`, `pufferpanel`, `calagopus`, `amp`, or `generic_rest`. | +| `panel_version` | Pterodactyl compatibility gate; may also document the installed MCSManager version. | +| `api_base_path` | Prefix for native APIs. Defaults: MCSManager `/api`, Crafty `/api/v2`, PufferPanel `/api`, Calagopus `/api`, AMP `/API`, generic REST empty. | +| `status_path` | Optional native endpoint for `panel_status`; MCSManager defaults to `overview`. | +| `api_key` | Native provider key or bearer token. | +| `auth_type` | `bearer`, `header`, `query`, `basic`, `none`, `oauth2_client_credentials`, or `amp_session`. | +| `auth_header` | Header name for header/bearer/Basic auth; defaults to `Authorization`. | +| `auth_scheme` | Prefix such as `Bearer`. Use an empty value for raw API-key header auth. | +| `auth_query_param` | Query key used for query auth; MCSManager defaults to `apikey`. | +| `custom_headers` | Optional object of extra HTTP headers. Sensitive values are server-side only. Reserved routing and hop-by-hop headers are ignored. | +| `oauth_client_id` / `oauth_client_secret` | PufferPanel OAuth2 client-credentials pair. Preferred to manually supplied short-lived access tokens. | +| `oauth_token_path` | OAuth token endpoint path; defaults to `/oauth2/token` for PufferPanel. | +| `auth_username` / `auth_password` | HTTP Basic credentials or AMP session login credentials. Store server-side only. | +| `amp_totp_token` | Optional current AMP two-factor token for API login where required. | + +Example: CubeCoders AMP. MAP logs in through `/API/Core/Login`, caches the returned session ID, and injects it into native JSON POST calls. These are login credentials, not an API key. + +```json +{ + "id": "amp-main", + "name": "AMP Main", + "provider": "amp", + "base_url": "https://amp.example.net", + "api_base_path": "/API", + "auth_type": "amp_session", + "auth_username": "REPLACE_WITH_AMP_SERVICE_USER", + "auth_password": "REPLACE_WITH_AMP_PASSWORD", + "amp_totp_token": "" +} +``` + +Example: Calagopus. Its API differs from Pterodactyl, and API keys must be regenerated after migration. + +```json +{ + "id": "calagopus", + "name": "Calagopus", + "provider": "calagopus", + "base_url": "https://calagopus.example.net", + "api_base_path": "/api", + "api_key": "REPLACE_WITH_CALAGOPUS_API_KEY", + "auth_type": "bearer" +} +``` + +Example: MCSManager 10.x (use a real panel URL and keep the key secret). + +```json +{ + "id": "mcsm-eu", + "name": "MCSManager Europe", + "provider": "mcsmanager", + "panel_version": "10.x", + "base_url": "https://mcsm.example.net", + "api_base_path": "/api", + "api_key": "REPLACE_WITH_MCSMANAGER_API_KEY", + "auth_type": "query", + "auth_query_param": "apikey" +} +``` + +Example: PufferPanel with OAuth2 client credentials. + +```json +{ + "id": "puffer", + "name": "PufferPanel", + "provider": "pufferpanel", + "base_url": "https://puffer.example.net", + "api_base_path": "/api", + "oauth_client_id": "REPLACE_WITH_OAUTH_CLIENT_ID", + "oauth_client_secret": "REPLACE_WITH_OAUTH_CLIENT_SECRET", + "auth_type": "oauth2_client_credentials", + "oauth_token_path": "/oauth2/token" +} +``` + +MCSManager's documented API accepts its key as a query parameter. HTTPS encrypts the request in transit, but reverse-proxy access logs may record query strings. Restrict and redact such logs; never paste raw request URLs into issues. See the [MCSManager authentication guide](https://docs.mcsmanager.com/apis/get_apikey.html). + ## Environment variables | Variable | Default | Purpose | @@ -33,6 +138,8 @@ Pterodactyl 1.x documents Client and Application APIs. Pterodactyl 2.x documents | `MAP_PANELS_JSON_B64` | empty | Base64-encoded UTF-8 JSON, useful for systemd EnvironmentFile values. | | `PANEL_BASE_URL` | empty | Legacy single-panel URL when multi-panel variables are empty. | | `PANEL_NAME` | `Default Pterodactyl Panel` | Legacy display name. | +| `PANEL_PROVIDER` | `pterodactyl` | Legacy single-panel provider; supports Pterodactyl or Pelican. | +| `PANEL_VERSION` | `auto` | Legacy Pterodactyl API compatibility setting. | | `PANEL_CLIENT_API_KEY` | empty | Legacy Client key; `PANEL_API_KEY` remains a fallback. | | `PANEL_APPLICATION_API_KEY` | empty | Legacy Application key. | | `PANEL_ADMIN_API_KEY` | empty | Legacy root-admin Client key. | @@ -53,4 +160,4 @@ Pterodactyl 1.x documents Client and Application APIs. Pterodactyl 2.x documents Prefer `deploy/configure_panels.py` for systemd. It reads keys with hidden input and writes the panel array in base64 form to `/etc/realmsnetwork-map/map.env`. The file should remain root-owned, group-readable by the MAP account, and mode `0640`. -Base64 is encoding, not encryption. Filesystem permissions still matter. Never put secrets in command-line arguments, committed JSON, screenshots, bug reports, or prompts. +Base64 is encoding, not encryption. Filesystem permissions still matter. The helper preserves the server name and request/response/file-size limits and prompts for each provider's authentication type. Never put secrets in command-line arguments, committed JSON, screenshots, bug reports, or prompts. diff --git a/docs/roadmap.md b/docs/roadmap.md index a697397..52b9ec1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -7,7 +7,7 @@ This is a working direction, not a promise until implemented and tested. - Expand mocked coverage for API routing, authentication, redaction, and signed Wings transfers. - Add a low-permission health/diagnostics tool. - Improve compact summaries while preserving the generic endpoint escape hatch. -- Publish versioned releases and a supported panel/fork compatibility matrix. +- Publish versioned releases and a tested compatibility matrix for each native panel provider and version. - Add client configuration examples without credentials. ## Later diff --git a/docs/security.md b/docs/security.md index 592fd39..6893616 100644 --- a/docs/security.md +++ b/docs/security.md @@ -5,7 +5,7 @@ MAP is intended for administrators connecting trusted MCP clients to panels they ## Trust boundaries - **MAP host:** no arbitrary shell, SSH, or OS-root tool is provided. Run the service as an unprivileged account. -- **Panel API:** configured keys determine capabilities. Generic write requests and dedicated tools can be destructive. +- **Panel API:** configured keys/tokens determine capabilities. Generic REST writes and dedicated tools can be destructive. - **MCP client:** any client holding the bearer token can invoke all tools on that service; the token is not per-tool authorization. - **Wings transfers:** binary tools follow panel-generated signed URLs only after HTTPS and exact-host checks. @@ -15,6 +15,10 @@ MAP is intended for administrators connecting trusted MCP clients to panels they - Constant-time bearer comparison. - HTTPS-only panel URLs, no embedded user-info/query/fragment, and no arbitrary external request target. - Redirects disabled for authenticated API calls. +- Configured provider secrets, auth-header values, and cached PufferPanel access tokens are redacted from API responses. +- MCSManager sends its documented API key as an HTTPS query parameter, so reverse-proxy logs must be restricted and redacted. +- AMP credentials are used for session login; session IDs are cached server-side and redacted from API output. Use an AMP account with minimum required permissions. +- HTTP Basic credentials are encoded for the Authorization header, not encrypted by Basic auth itself; use them only over HTTPS. - Common credential fields, known configured key strings, and sensitive signed-URL query parameters are redacted. - Configurable response/file size limits. - Exact Wings hostname allowlist; redirects disabled. diff --git a/docs/tools.md b/docs/tools.md index 1a720e9..1f133e8 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -8,17 +8,39 @@ Tool schemas are exposed by the server. The chosen panel's API version and key d Lists panel IDs, names, base URLs, and which API namespaces have configured keys, without returning key values. -### `panel_status(panel_id, api="application")` +### `panel_status(panel_id, api="auto")` -Makes a request against the selected namespace. A 401/403 usually indicates key/permission problems; a 404 may mean an endpoint is absent for the panel version. +Checks the selected provider. `auto` uses the Client API for Pterodactyl/Pelican and a native status path for other providers; MCSManager defaults to `/api/overview`, while AMP uses its POST `Core/GetStatus` method. A 401/403 usually indicates authentication/permission problems; a 404 may mean the configured status endpoint is unavailable. ### `panel_api_request(panel_id, api, method, path, query_params=None, json_body=None, raw_body=None, content_type=None, timeout_seconds=30)` -General-purpose endpoint tool. Choose endpoints documented for your panel version. `path` is relative to the selected namespace; query parameters are separate. Supported methods: GET, POST, PUT, PATCH, DELETE. Supply at most one of JSON body and raw text body. +General-purpose endpoint tool. For Pterodactyl/Pelican, `api` is a supported namespace and `path` is relative to it. For MCSManager, Crafty, PufferPanel, Calagopus, AMP, or generic REST, use `api="native"`; `path` is relative to the configured `api_base_path`. Query parameters are passed separately. Supported methods: GET, POST, PUT, PATCH, DELETE. Supply at most one of JSON body and raw text body. This tool can make destructive changes when the key permits them. Review the method, endpoint, target object, and body before write requests. -## Dedicated server tools + +## CubeCoders AMP + +AMP's API differs from REST panels that use bearer keys. Set `provider` to `amp` and configure `auth_username`/`auth_password` (plus `amp_totp_token` when needed). MAP submits the login request, caches the returned `SESSIONID`, and injects it into native JSON POST requests. Use `panel_api_request` with `api="native"`, `method="POST"`, and the documented method path, such as `Core/GetStatus`. The request body must be a JSON object. `panel_status` uses AMP's `Core/GetStatus` POST path. + +Create a least-privilege AMP account. MAP does not expose the password/session token through `list_panels` and redacts session IDs from responses. The actual permissions granted by the AMP account still determine what it can do. + +## MCSManager-native tools + +These tools use MCSManager's native API rather than sending Pterodactyl routes to it. + +| Tool | Parameters | Purpose | +| --- | --- | --- | +| `mcsmanager_list_instances` | `panel_id, daemon_id, page=1, page_size=50` | List instances for a daemon. Page size is capped at 50. | +| `mcsmanager_instance_action` | `panel_id, daemon_id, instance_uuid, action` | Start, stop, restart, or kill an instance. | +| `mcsmanager_instance_command` | `panel_id, daemon_id, instance_uuid, command` | Send a command through the native HTTP API. | +| `mcsmanager_instance_output_log` | `panel_id, daemon_id, instance_uuid, size="10KB"` | Read the instance output log. | + +Calagopus uses its own API rather than Pterodactyl-compatible endpoints. Use the instance's `/api` documentation and `panel_api_request` with `api="native"`; configure `api_base_path` as `/api` and use a Calagopus API key. + +For other MCSManager endpoints, use `panel_api_request` with `api="native"` and the endpoint documented for the installed version. MCSManager 9.x and 10.x differ; verify endpoint semantics before making writes. + +## Pterodactyl/Pelican-compatible server tools | Tool | Parameters | Purpose | | --- | --- | --- | diff --git a/pyproject.toml b/pyproject.toml index 028e312..51a6af4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,11 +5,11 @@ build-backend = "hatchling.build" [project] name = "realmsnetwork-map" version = "0.3.0" -description = "A multi-panel Pterodactyl administration gateway over Model Context Protocol." +description = "A multi-provider game-server panel administration gateway over Model Context Protocol." readme = "README.md" requires-python = ">=3.11" license = "MIT" -keywords = ["mcp", "model-context-protocol", "pterodactyl", "game-server", "panel", "administration"] +keywords = ["mcp", "model-context-protocol", "pterodactyl", "pelican", "mcsmanager", "crafty-controller", "pufferpanel", "calagopus", "cube-coders-amp", "amp", "rest-api", "game-server", "panel", "administration"] classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", diff --git a/src/map_server/client.py b/src/map_server/client.py index 3c122d9..e75bbe5 100644 --- a/src/map_server/client.py +++ b/src/map_server/client.py @@ -1,14 +1,21 @@ """HTTP client for authorized panel APIs and trusted Wings file transfers.""" from __future__ import annotations +import base64 +import hashlib import ipaddress import json import os +import re +import threading +import time from typing import Any -from urllib.parse import parse_qsl, unquote, urlencode, urlparse, urlunsplit +from urllib.parse import parse_qsl, urlencode, urlparse, urlunsplit from curl_cffi import requests +from .providers import PTERODACTYL_COMPATIBLE, normalize_provider, route_request + from .config import ( IMPERSONATE, MAX_REQUEST_BODY_BYTES, @@ -16,7 +23,6 @@ MAX_RESPONSE_CHARS, MCP_BEARER_TOKEN, SERVER_ID_RE, - SUPPORTED_APIS, SUPPORTED_METHODS, _panel, _panels, @@ -26,8 +32,49 @@ SENSITIVE_KEYS = ( "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", ) + + +def _redact_url(value: str) -> str: + """Redact credentials in URLs, including URLs embedded in text responses.""" + parsed = urlparse(value) + if parsed.scheme not in {"http", "https"} or not parsed.netloc: + return value + query = parse_qsl(parsed.query, keep_blank_values=True) + def sensitive(key: str) -> bool: + normalized = key.lower().replace("-", "_") + return any(part.replace("-", "_") in normalized for part in SENSITIVE_KEYS) + if any(sensitive(key) for key, _ in query): + query = [(key, "[REDACTED]" if sensitive(key) else item) for key, item in query] + # Never pass through user-info returned inside a URL. + netloc = parsed.netloc.rsplit("@", 1)[-1] + return urlunsplit((parsed.scheme, netloc, parsed.path, urlencode(query), parsed.fragment)) + + +def _redact_text(value: str, token: str = "") -> str: + """Redact configured secrets and credentials in any signed URLs contained in text.""" + for panel in _panels().values(): + for secret in _panel_secrets(panel): + value = value.replace(secret, "[REDACTED]") + for secret in (token, MCP_BEARER_TOKEN, *(item[0] for item in _OAUTH_CACHE.values()), *(item[0] for item in _AMP_SESSION_CACHE.values())): + if secret: + value = value.replace(secret, "[REDACTED]") + + url_pattern = re.compile(r'https?://[^\s<>"]+') + def clean_match(match: re.Match[str]) -> str: + url = match.group(0) + suffix = "" + while url and url[-1] in ".,);": + suffix = url[-1] + suffix + url = url[:-1] + return _redact_url(url) + suffix + + return url_pattern.sub(clean_match, value) + + + def _safe_json(value: Any) -> Any: """Redact common credential fields while preserving useful API output.""" if isinstance(value, dict): @@ -42,21 +89,253 @@ def _safe_json(value: Any) -> Any: if isinstance(value, list): return [_safe_json(item) for item in value] if isinstance(value, str): - parsed_value = urlparse(value) - if parsed_value.scheme in {"http", "https"} and parsed_value.netloc and parsed_value.query: - query = parse_qsl(parsed_value.query, keep_blank_values=True) - if any(any(part in key.lower() for part in SENSITIVE_KEYS) for key, _ in query): - query = [(key, "[REDACTED]" if any(part in key.lower() for part in SENSITIVE_KEYS) else item) for key, item in query] - value = urlunsplit((parsed_value.scheme, parsed_value.netloc, parsed_value.path, urlencode(query), parsed_value.fragment)) - for panel in _panels().values(): - for key in ("client_api_key", "application_api_key", "admin_api_key"): - secret = panel.get(key, "") - if secret: - value = value.replace(secret, "[REDACTED]") + value = _redact_text(value) + value = _redact_url(value) return value[:MAX_RESPONSE_CHARS] + "…[truncated]" if len(value) > MAX_RESPONSE_CHARS else value return value + +_OAUTH_CACHE: dict[str, tuple[str, float]] = {} +_OAUTH_LOCK = threading.Lock() +_AMP_SESSION_CACHE: dict[str, tuple[str, float]] = {} +_AMP_SESSION_LOCK = threading.Lock() + + +def _oauth_access_token(panel: dict[str, Any]) -> str: + """Fetch and cache a OAuth22 client-credentials token.""" + client_id = panel.get("oauth_client_id", "") + client_secret = panel.get("oauth_client_secret", "") + if not client_id or not client_secret: + token = panel.get("api_key", "") + if token: + return token + raise RuntimeError( + f"Panel '{panel['id']}' needs oauth_client_id/oauth_client_secret or a bearer api_key." + ) + panel_id = str(panel["id"]) + cache_key = "|".join(( + panel_id, + str(panel.get("base_url", "")), + str(panel.get("oauth_client_id", "")), + hashlib.sha256(str(panel.get("oauth_client_secret", "")).encode("utf-8")).hexdigest(), + str(panel.get("oauth_token_path", "/oauth2/token")), + )) + now = time.monotonic() + cached = _OAUTH_CACHE.get(cache_key) + if cached and cached[1] > now + 30: + return cached[0] + with _OAUTH_LOCK: + now = time.monotonic() + cached = _OAUTH_CACHE.get(cache_key) + if cached and cached[1] > now + 30: + return cached[0] + url = str(panel["base_url"]).rstrip("/") + str(panel.get("oauth_token_path", "/oauth2/token")) + try: + response = requests.post( + url, + data={ + "grant_type": "client_credentials", + "client_id": client_id, + "client_secret": client_secret, + }, + headers={"Accept": "application/json"}, + impersonate=IMPERSONATE, + timeout=20, + allow_redirects=False, + stream=True, + ) + try: + if 300 <= response.status_code < 400: + raise RuntimeError("OAuth2 endpoint redirected; redirect following is disabled.") + if not 200 <= response.status_code < 300: + raise RuntimeError( + f"OAuth2 token request failed with HTTP {response.status_code}." + ) + length = response.headers.get("content-length", "") + if length.isdigit() and int(length) > 65536: + raise RuntimeError("OAuth2 response was larger than 64 KB.") + chunks: list[bytes] = [] + total = 0 + for chunk in response.iter_content(chunk_size=8192): + if not chunk: + continue + total += len(chunk) + if total > 65536: + raise RuntimeError("OAuth2 response was larger than 64 KB.") + chunks.append(chunk) + payload = json.loads(b"".join(chunks).decode("utf-8")) + finally: + response.close() + except RuntimeError: + raise + except Exception as exc: + raise RuntimeError(f"OAuth2 request failed ({type(exc).__name__}).") from None + token = payload.get("access_token") if isinstance(payload, dict) else None + if not isinstance(token, str) or not token: + raise RuntimeError("OAuth2 response did not contain an access_token.") + try: + lifetime = max(10, int(payload.get("expires_in", 300)) - 30) + except (TypeError, ValueError): + lifetime = 270 + _OAUTH_CACHE[cache_key] = (token, time.monotonic() + lifetime) + return token + + + +def _amp_session(panel: dict[str, Any]) -> str: + """Authenticate against CubeCoders AMP and cache its session ID.""" + panel_id = str(panel["id"]) + base_url = str(panel["base_url"]).rstrip("/") + username = str(panel.get("auth_username", "")) + password = str(panel.get("auth_password", "")) + if not username or not password: + raise RuntimeError(f"AMP panel '{panel_id}' requires auth_username and auth_password.") + password_fingerprint = hashlib.sha256(password.encode("utf-8")).hexdigest() + cache_key = "|".join((panel_id, base_url, username, password_fingerprint)) + now = time.monotonic() + cached = _AMP_SESSION_CACHE.get(cache_key) + if cached and cached[1] > now + 30: + return cached[0] + with _AMP_SESSION_LOCK: + now = time.monotonic() + cached = _AMP_SESSION_CACHE.get(cache_key) + if cached and cached[1] > now + 30: + return cached[0] + payload = { + "username": username, + "password": password, + "token": str(panel.get("amp_totp_token", "")), + "rememberMe": False, + } + try: + response = requests.post( + base_url + "/API/Core/Login", + headers={"Accept": "application/json", "Content-Type": "application/json"}, + data=json.dumps(payload, separators=(",", ":")).encode("utf-8"), + impersonate=IMPERSONATE, + timeout=20, + allow_redirects=False, + stream=True, + ) + try: + if 300 <= response.status_code < 400: + raise RuntimeError("AMP login redirected; redirect following is disabled.") + if not 200 <= response.status_code < 300: + raise RuntimeError(f"AMP login failed with HTTP {response.status_code}.") + length = response.headers.get("content-length", "") + if length.isdigit() and int(length) > 65536: + raise RuntimeError("AMP login response was larger than 64 KB.") + chunks: list[bytes] = [] + total = 0 + for chunk in response.iter_content(chunk_size=8192): + if not chunk: + continue + total += len(chunk) + if total > 65536: + raise RuntimeError("AMP login response was larger than 64 KB.") + chunks.append(chunk) + payload_result = json.loads(b"".join(chunks).decode("utf-8")) + finally: + response.close() + except RuntimeError: + raise + except Exception as exc: + raise RuntimeError( + f"AMP login request failed ({type(exc).__name__}). Check credentials and panel reachability." + ) from None + + session_id = "" + if isinstance(payload_result, dict): + for key, value in payload_result.items(): + if key.lower() in {"sessionid", "session_id"} and isinstance(value, str): + session_id = value + break + if not session_id: + raise RuntimeError( + "AMP login did not return a sessionID. Verify credentials, permissions, and any required 2FA token." + ) + _AMP_SESSION_CACHE[cache_key] = (session_id, time.monotonic() + 1200) + return session_id + + +def _panel_secrets(panel: dict[str, Any]) -> list[str]: + """Collect configured secret values for response redaction without exposing them.""" + keys = { + "client_api_key", "application_api_key", "admin_api_key", "api_key", "auth_token", + "oauth_client_secret", "auth_password", "amp_totp_token", + } + secrets = [str(panel[key]) for key in keys if panel.get(key)] + if panel.get("auth_type") == "basic" and panel.get("auth_username") and panel.get("auth_password"): + pair = f"{panel['auth_username']}:{panel['auth_password']}".encode("utf-8") + secrets.append("Basic " + base64.b64encode(pair).decode("ascii")) + custom = panel.get("custom_headers", {}) + if isinstance(custom, dict): + for name, value in custom.items(): + if any(word in str(name).lower().replace("-", "_") for word in SENSITIVE_KEYS): + if isinstance(value, str) and value: + secrets.append(value) + secrets.extend(value[0] for value in _OAUTH_CACHE.values()) + secrets.extend(value[0] for value in _AMP_SESSION_CACHE.values()) + return list(dict.fromkeys(secret for secret in secrets if secret)) + + +def _apply_panel_auth( + panel: dict[str, Any], + api_kind: str, + headers: dict[str, str], + params: dict[str, Any], +) -> str: + """Apply provider-specific auth and return the active token for response redaction.""" + provider = normalize_provider(panel.get("provider")) + if provider in PTERODACTYL_COMPATIBLE: + token = _token_for(panel, api_kind) + headers["Authorization"] = f"Bearer {token}" + return token + + auth_type = str(panel.get("auth_type", "bearer")).lower() + token = "" + if auth_type == "amp_session": + token = _amp_session(panel) + elif auth_type == "basic": + username = str(panel.get("auth_username", "")) + password = str(panel.get("auth_password", "")) + if not username or not password: + raise RuntimeError(f"Panel '{panel['id']}' requires auth_username and auth_password for Basic auth.") + token = password + encoded = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii") + headers[str(panel.get("auth_header") or "Authorization")] = f"Basic {encoded}" + elif auth_type == "oauth2_client_credentials": + token = _oauth_access_token(panel) + headers[str(panel.get("auth_header") or "Authorization")] = f"Bearer {token}" + elif auth_type == "bearer": + token = str(panel.get("api_key", "") or panel.get("auth_token", "")) + if not token: + raise RuntimeError(f"Panel '{panel['id']}' has no bearer API key configured.") + header = str(panel.get("auth_header") or "Authorization") + scheme = str(panel.get("auth_scheme") or "Bearer").strip() + headers[header] = f"{scheme} {token}".strip() + elif auth_type == "header": + token = str(panel.get("api_key", "") or panel.get("auth_token", "")) + if not token: + raise RuntimeError(f"Panel '{panel['id']}' has no API key configured for header authentication.") + header = str(panel.get("auth_header") or "X-API-Key") + scheme = str(panel.get("auth_scheme") or "").strip() + headers[header] = f"{scheme} {token}".strip() if scheme else token + elif auth_type == "query": + token = str(panel.get("api_key", "") or panel.get("auth_token", "")) + if not token: + raise RuntimeError(f"Panel '{panel['id']}' has no API key configured for query authentication.") + params[str(panel.get("auth_query_param") or "api_key")] = token + elif auth_type != "none": + raise RuntimeError(f"Panel '{panel['id']}' has unsupported auth_type '{auth_type}'.") + + if provider == "mcsmanager": + headers.setdefault("X-Requested-With", "XMLHttpRequest") + headers.setdefault("Content-Type", "application/json; charset=utf-8") + return token + + def _api_request( panel_id: str, api: str, @@ -69,9 +348,7 @@ def _api_request( timeout_seconds: int = 30, ) -> dict[str, Any]: panel = _panel(panel_id) - api = api.lower().strip() - if api not in SUPPORTED_APIS: - raise ValueError("api must be client, application, or admin.") + provider = normalize_provider(panel.get("provider")) method = method.upper().strip() if method not in SUPPORTED_METHODS: raise ValueError("method must be GET, POST, PUT, PATCH, or DELETE.") @@ -79,34 +356,30 @@ def _api_request( raise ValueError("Pass json_body or raw_body, not both.") if raw_body is not None and method in {"GET", "DELETE"}: raise ValueError("raw_body is only supported for POST, PUT, and PATCH.") - if not isinstance(path, str): - raise ValueError("path must be a relative API path.") - input_path = path.strip() - if input_path.startswith("//"): - raise ValueError("Absolute network-path URLs are not allowed.") - relative = input_path.lstrip("/") - prefix = f"api/{api}" - if relative == prefix: - relative = "" - elif relative.startswith(prefix + "/"): - relative = relative[len(prefix) + 1:] - if "://" in relative or relative.startswith("//") or "?" in relative or "#" in relative or "%" in relative or "\\" in relative: - raise ValueError("path must be relative to the selected API namespace; pass query parameters separately.") - decoded = unquote(relative) - if any(segment in {".", ".."} for segment in decoded.split("/")) or "\\" in decoded: - raise ValueError("path cannot contain traversal segments.") - if len(relative) > 2048: - raise ValueError("path is too long.") - - if query_params is not None: - if not isinstance(query_params, dict): - raise ValueError("query_params must be an object.") - try: - query_size = len(json.dumps(query_params, ensure_ascii=False, separators=(",", ":")).encode("utf-8")) - except (TypeError, ValueError): - raise ValueError("query_params must be JSON-serializable.") from None - if query_size > 65536: - raise ValueError("query_params exceeds the 64 KB input limit.") + + url, api_kind, accept_header, relative = route_request(panel, api, path) + if provider == "amp": + if method != "POST": + raise ValueError("AMP API operations use POST requests.") + if raw_body is not None: + raise ValueError("AMP API calls require JSON so MAP can inject the authenticated SESSIONID.") + if json_body is None: + json_body = {} + if not isinstance(json_body, dict): + raise ValueError("AMP json_body must be an object.") + if relative.lower() == "core/login": + raise ValueError("AMP login is managed automatically by MAP; call the desired native API method.") + json_body = dict(json_body) + json_body["SESSIONID"] = _amp_session(panel) + if query_params is not None and not isinstance(query_params, dict): + raise ValueError("query_params must be an object.") + params = dict(query_params or {}) + try: + 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 query_size > 65536: + raise ValueError("query_params exceeds the 64 KB input limit.") encoded_json: bytes | None = None raw_bytes: bytes | None = None @@ -124,31 +397,38 @@ def _api_request( if len(raw_bytes) > MAX_REQUEST_BODY_BYTES: raise ValueError(f"Request body exceeds MAP_MAX_REQUEST_BODY_BYTES ({MAX_REQUEST_BODY_BYTES} bytes).") - token = _token_for(panel, api) - url = f"{panel['base_url']}/api/{api}" + (f"/{relative}" if relative else "") - headers = { - "Authorization": f"Bearer {token}", - "Accept": "Application/vnd.pterodactyl.v1+json", - } - kwargs: dict[str, Any] = { - "headers": headers, - "params": query_params or {}, - "impersonate": IMPERSONATE, - "timeout": max(1, min(int(timeout_seconds), 120)), - "allow_redirects": False, - "stream": True, - } + headers: dict[str, str] = {"Accept": accept_header} + if provider in PTERODACTYL_COMPATIBLE: + headers["Content-Type"] = "application/json" + custom_headers = panel.get("custom_headers", {}) + if isinstance(custom_headers, dict): + # These hop-by-hop/routing headers are never user-overridable. + for name, value in custom_headers.items(): + lower = str(name).lower() + if lower in {"host", "content-length", "connection", "transfer-encoding", "proxy-authorization", "authorization"}: + continue + headers[str(name)] = str(value) + + token = _apply_panel_auth(panel, api_kind, headers, params) if encoded_json is not None: - kwargs["data"] = encoded_json headers["Content-Type"] = "application/json" elif raw_bytes is not None: - kwargs["data"] = raw_bytes headers["Content-Type"] = content_type or "text/plain; charset=utf-8" elif content_type: headers["Content-Type"] = content_type try: - response = requests.request(method, url, **kwargs) + response = requests.request( + method, + url, + headers=headers, + params=params, + data=encoded_json if encoded_json is not None else raw_bytes, + impersonate=IMPERSONATE, + timeout=max(1, min(int(timeout_seconds), 120)), + allow_redirects=False, + stream=True, + ) except Exception as exc: raise RuntimeError( f"Panel API transport failed ({type(exc).__name__}). Check DNS, TLS, and panel connectivity." @@ -159,7 +439,7 @@ def _api_request( return { "ok": False, "status_code": response.status_code, - "error": "Panel redirected the request; redirect following is disabled to protect API credentials.", + "error": "Panel redirected the request; redirect following is disabled to protect credentials.", } response_type = response.headers.get("content-type", "") @@ -169,7 +449,7 @@ def _api_request( "ok": False, "status_code": 413, "method": method, - "api": api, + "api": api_kind, "path": "/" + relative, "error": f"Panel API response exceeds MAP_MAX_RESPONSE_BYTES ({MAX_RESPONSE_BYTES} bytes).", } @@ -186,7 +466,7 @@ def _api_request( "ok": False, "status_code": 413, "method": method, - "api": api, + "api": api_kind, "path": "/" + relative, "error": f"Panel API response exceeds MAP_MAX_RESPONSE_BYTES ({MAX_RESPONSE_BYTES} bytes).", } @@ -205,10 +485,7 @@ def _api_request( except (ValueError, UnicodeDecodeError): data = "[Panel returned invalid JSON]" elif "text/" in response_type.lower() or "xml" in response_type.lower(): - text_value = body.decode("utf-8", errors="replace") - for secret in (token, MCP_BEARER_TOKEN): - if secret: - text_value = text_value.replace(secret, "[REDACTED]") + text_value = _redact_text(body.decode("utf-8", errors="replace"), token=token) data = text_value[:MAX_RESPONSE_CHARS] + "…[truncated]" if len(text_value) > MAX_RESPONSE_CHARS else text_value else: data = { @@ -217,11 +494,18 @@ def _api_request( "note": "Binary response omitted. Use a purpose-built file transfer tool for downloads.", } + # MCSManager reports application-level status in JSON, even when HTTP status is 200. + ok = 200 <= response.status_code < 300 + if provider == "mcsmanager" and isinstance(data, dict) and isinstance(data.get("status"), int): + ok = ok and data["status"] == 200 + if provider == "amp" and isinstance(data, dict) and "result" in data: + ok = ok and str(data.get("result", "")).lower() in {"success", "ok"} return { - "ok": 200 <= response.status_code < 300, + "ok": ok, "status_code": response.status_code, "method": method, - "api": api, + "api": api_kind, + "provider": provider, "path": "/" + relative, "data": data, } @@ -231,6 +515,10 @@ def _signed_wings_url(panel_id: str, server_id: str, operation: str, query: dict if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") panel = _panel(panel_id) + if normalize_provider(panel.get("provider")) not in PTERODACTYL_COMPATIBLE: + raise ValueError( + "The signed Wings upload/download tools require Pterodactyl or Pelican; use the provider's native API for other panels." + ) token = _token_for(panel, "client") try: response = requests.get( @@ -240,18 +528,35 @@ def _signed_wings_url(panel_id: str, server_id: str, operation: str, query: dict impersonate=IMPERSONATE, timeout=30, allow_redirects=False, + stream=True, ) except Exception as exc: raise RuntimeError(f"Panel file-transfer request failed ({type(exc).__name__}).") from None if 300 <= response.status_code < 400: + response.close() return None, {"ok": False, "status_code": response.status_code, "error": "Panel redirected the request; redirects are disabled."} if response.status_code < 200 or response.status_code >= 300: + response.close() return None, {"ok": False, "status_code": response.status_code, "error": "Panel refused the file-transfer request."} try: - payload = response.json() + length = response.headers.get("content-length", "") + if length.isdigit() and int(length) > 65536: + return None, {"ok": False, "status_code": response.status_code, "error": "Panel file-transfer metadata exceeded 64 KB."} + chunks: list[bytes] = [] + total = 0 + for chunk in response.iter_content(chunk_size=8192): + if not chunk: + continue + total += len(chunk) + if total > 65536: + return None, {"ok": False, "status_code": response.status_code, "error": "Panel file-transfer metadata exceeded 64 KB."} + chunks.append(chunk) + payload = json.loads(b"".join(chunks).decode("utf-8")) url = payload.get("attributes", {}).get("url") - except (ValueError, AttributeError): + except (ValueError, AttributeError, UnicodeDecodeError): url = None + finally: + response.close() if not isinstance(url, str) or not url: return None, {"ok": False, "status_code": response.status_code, "error": "Panel did not return a signed file-transfer URL."} parsed = urlparse(url) diff --git a/src/map_server/config.py b/src/map_server/config.py index b1e17f9..e6f6381 100644 --- a/src/map_server/config.py +++ b/src/map_server/config.py @@ -7,6 +7,9 @@ import os import re from urllib.parse import urlparse +from typing import Any + +from .providers import normalize_api_base_path, normalize_provider from dotenv import load_dotenv @@ -21,14 +24,42 @@ MAX_REQUEST_BODY_BYTES = int(os.getenv("MAP_MAX_REQUEST_BODY_BYTES", "2000000")) MAX_RESPONSE_BYTES = int(os.getenv("MAP_MAX_RESPONSE_BYTES", "5000000")) MAX_INLINE_FILE_BYTES = int(os.getenv("MAP_MAX_INLINE_FILE_BYTES", "6000000")) +MAX_REQUEST_BODY_BYTES = int(os.getenv("MAP_MAX_REQUEST_BODY_BYTES", "2000000")) +MAX_RESPONSE_BYTES = int(os.getenv("MAP_MAX_RESPONSE_BYTES", "5000000")) +MAX_CONFIGURED_PANELS = 20 PANEL_IDS_RE = re.compile(r"^[A-Za-z0-9_-]{1,48}$") SERVER_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,80}$") -SUPPORTED_APIS = {"client", "application", "admin"} +SUPPORTED_APIS = {"client", "application", "admin", "native"} SUPPORTED_METHODS = {"GET", "POST", "PUT", "PATCH", "DELETE"} -def _read_panels() -> dict[str, dict[str, str]]: +if not 1 <= PORT <= 65535: + raise RuntimeError("MAP_PORT must be between 1 and 65535.") +if min(MAX_RESPONSE_CHARS, MAX_REQUEST_BODY_BYTES, MAX_RESPONSE_BYTES, MAX_INLINE_FILE_BYTES) < 1: + raise RuntimeError("MAP response and file size limits must all be positive integers.") + + +def _validate_base_url(panel_id: str, base_url: str) -> None: + """Validate a panel origin before it can be used for authenticated requests.""" + if not base_url or len(base_url) > 2048 or any(char.isspace() for char in base_url): + raise RuntimeError(f"Panel '{panel_id}' must have a base_url between 1 and 2048 characters.") + parsed = urlparse(base_url) + if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment: + raise RuntimeError(f"Panel '{panel_id}' must have a valid HTTPS base_url without embedded credentials, query, or fragment.") + try: + parsed.port + except ValueError: + raise RuntimeError(f"Panel '{panel_id}' base_url has an invalid port.") from None + try: + address = ipaddress.ip_address(parsed.hostname) + except ValueError: + address = None + if address and not address.is_global: + raise RuntimeError(f"Panel '{panel_id}' cannot use a non-public IP address as its base_url.") + + +def _read_panels() -> dict[str, dict[str, Any]]: """Load panel URLs and API keys from server-side environment only.""" - panels: dict[str, dict[str, str]] = {} + panels: dict[str, dict[str, Any]] = {} raw = os.getenv("MAP_PANELS_JSON", "").strip() if not raw: encoded = os.getenv("MAP_PANELS_JSON_B64", "").strip() @@ -44,16 +75,113 @@ def _read_panels() -> dict[str, dict[str, str]]: raise RuntimeError("MAP_PANELS_JSON must be valid JSON.") from exc if not isinstance(entries, list): raise RuntimeError("MAP_PANELS_JSON must be a JSON array.") + if len(entries) > MAX_CONFIGURED_PANELS: + raise RuntimeError(f"MAP_PANELS_JSON supports at most {MAX_CONFIGURED_PANELS} panels.") for entry in entries: if not isinstance(entry, dict): raise RuntimeError("Each MAP_PANELS_JSON entry must be an object.") panel_id = str(entry.get("id", "")).strip() if not PANEL_IDS_RE.fullmatch(panel_id) or panel_id in panels: raise RuntimeError("Panel IDs must be unique and use letters, numbers, underscores, or hyphens.") + base_url = str(entry.get("base_url") or "").strip().rstrip("/") + _validate_base_url(panel_id, base_url) + name = str(entry.get("name") or panel_id).strip() + if not name or len(name) > 128: + raise RuntimeError("Panel display name must be between 1 and 128 characters.") + provider = normalize_provider( + entry.get("provider", entry.get("panel_type", entry.get("type", "pterodactyl"))) + ) + panel_version = str(entry.get("panel_version", entry.get("version", "auto")) or "auto").strip().lower() + if provider == "pterodactyl" and panel_version not in {"auto", "1", "1.x", "v1", "2", "2.x", "v2"}: + raise RuntimeError(f"Panel '{panel_id}' panel_version must be auto, 1.x, or 2.x.") + default_auth = { + "pterodactyl": "bearer", + "pelican": "bearer", + "mcsmanager": "query", + "crafty": "bearer", + "pufferpanel": "oauth2_client_credentials", + "calagopus": "bearer", + "amp": "amp_session", + "generic_rest": "bearer", + }[provider] + auth_type = str(entry.get("auth_type") or default_auth).strip().lower() + if auth_type not in {"bearer", "header", "query", "basic", "none", "oauth2_client_credentials", "amp_session"}: + raise RuntimeError( + f"Panel '{panel_id}' auth_type must be bearer, header, query, basic, none, oauth2_client_credentials, or amp_session." + ) + api_key = str(entry.get("api_key") or entry.get("auth_token") or "").strip() + oauth_client_id = str(entry.get("oauth_client_id") or "").strip() + oauth_client_secret = str(entry.get("oauth_client_secret") or "").strip() + auth_username = str(entry.get("auth_username") or "").strip() + auth_password = str(entry.get("auth_password") or "") + amp_totp_token = str(entry.get("amp_totp_token") or "").strip() + if provider == "amp": + if not (auth_username and auth_password): + raise RuntimeError("AMP panels require auth_username and auth_password.") + auth_type = "amp_session" + if provider == "pufferpanel": + if bool(oauth_client_id) != bool(oauth_client_secret): + raise RuntimeError("PufferPanel OAuth requires both oauth_client_id and oauth_client_secret.") + if oauth_client_id and oauth_client_secret: + auth_type = "oauth2_client_credentials" + elif api_key: + auth_type = "bearer" + else: + raise RuntimeError("PufferPanel requires OAuth client credentials or a bearer api_key.") + auth_header = str(entry.get("auth_header") or "Authorization").strip() + 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() + 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.") + custom_headers = entry.get("custom_headers") or {} + if not isinstance(custom_headers, dict) or len(custom_headers) > 32: + raise RuntimeError(f"Panel '{panel_id}' custom_headers must be an object with at most 32 entries.") + for header_name, header_value in custom_headers.items(): + if ( + not isinstance(header_name, str) + or not re.fullmatch(r"[!#$%&'*+._|~0-9A-Za-z-]{1,128}", header_name) + or header_name.lower() in {"host", "content-length", "connection", "transfer-encoding", "proxy-authorization", "authorization"} + or not isinstance(header_value, str) + or len(header_value) > 8192 + or "\r" in header_value + or "\n" in header_value + ): + raise RuntimeError(f"Panel '{panel_id}' has an invalid custom HTTP header.") + api_base_path = normalize_api_base_path(entry, provider) + oauth_token_path = str(entry.get("oauth_token_path") or "/oauth2/token").strip() + if ( + not oauth_token_path.startswith("/") + or oauth_token_path.startswith("//") + 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 "\\" in oauth_token_path + or any(part in {".", ".."} for part in oauth_token_path.strip("/").split("/")) + ): + raise RuntimeError(f"Panel '{panel_id}' oauth_token_path must be an absolute path on its configured host.") panels[panel_id] = { "id": panel_id, - "name": str(entry.get("name") or panel_id), - "base_url": str(entry.get("base_url") or "").strip().rstrip("/"), + "name": name, + "base_url": base_url, + "provider": provider, + "panel_version": panel_version, + "api_base_path": api_base_path, + "status_path": str(entry.get("status_path") or ("overview" if provider == "mcsmanager" else "")).strip(), + "auth_type": auth_type, + "api_key": api_key, + "auth_header": auth_header, + "auth_scheme": auth_scheme, + "auth_query_param": auth_query_param, + "oauth_client_id": oauth_client_id, + "oauth_client_secret": oauth_client_secret, + "auth_username": auth_username, + "auth_password": auth_password, + "amp_totp_token": amp_totp_token, + "oauth_token_path": oauth_token_path, + "custom_headers": dict(custom_headers), "client_api_key": str(entry.get("client_api_key") or "").strip(), "application_api_key": str(entry.get("application_api_key") or "").strip(), "admin_api_key": str(entry.get("admin_api_key") or "").strip(), @@ -61,10 +189,33 @@ def _read_panels() -> dict[str, dict[str, str]]: else: base_url = os.getenv("PANEL_BASE_URL", "").strip().rstrip("/") if base_url: + _validate_base_url("default", base_url) + legacy_name = os.getenv("PANEL_NAME", "Default Pterodactyl Panel").strip() + if not legacy_name or len(legacy_name) > 128: + raise RuntimeError("PANEL_NAME must be between 1 and 128 characters.") + provider = normalize_provider(os.getenv("PANEL_PROVIDER", "pterodactyl")) + if provider not in {"pterodactyl", "pelican"}: + raise RuntimeError("Legacy single-panel variables support Pterodactyl/Pelican; use MAP_PANELS_JSON for other providers.") panels["default"] = { "id": "default", - "name": os.getenv("PANEL_NAME", "Default Pterodactyl Panel").strip(), + "name": legacy_name, "base_url": base_url, + "provider": provider, + "panel_version": os.getenv("PANEL_VERSION", "auto").strip().lower(), + "api_base_path": "", + "status_path": "", + "auth_type": "bearer", + "api_key": "", + "auth_header": "Authorization", + "auth_scheme": "Bearer", + "auth_query_param": "api_key", + "oauth_client_id": "", + "oauth_client_secret": "", + "auth_username": "", + "auth_password": "", + "amp_totp_token": "", + "oauth_token_path": "/oauth2/token", + "custom_headers": {}, "client_api_key": os.getenv("PANEL_CLIENT_API_KEY", os.getenv("PANEL_API_KEY", "")).strip(), "application_api_key": os.getenv("PANEL_APPLICATION_API_KEY", "").strip(), "admin_api_key": os.getenv("PANEL_ADMIN_API_KEY", "").strip(), @@ -72,11 +223,11 @@ def _read_panels() -> dict[str, dict[str, str]]: return panels -def _panels() -> dict[str, dict[str, str]]: +def _panels() -> dict[str, dict[str, Any]]: return _read_panels() -def _panel(panel_id: str) -> dict[str, str]: +def _panel(panel_id: str) -> dict[str, Any]: if not PANEL_IDS_RE.fullmatch(panel_id or ""): raise ValueError("panel_id must be a configured panel ID.") panel = _panels().get(panel_id) diff --git a/src/map_server/providers.py b/src/map_server/providers.py new file mode 100644 index 0000000..b60f353 --- /dev/null +++ b/src/map_server/providers.py @@ -0,0 +1,136 @@ +"""Panel provider routing and API compatibility rules.""" +from __future__ import annotations + +from typing import Any + +PTERODACTYL_COMPATIBLE = {"pterodactyl", "pelican"} +SUPPORTED_PROVIDERS = { + "pterodactyl", + "pelican", + "mcsmanager", + "crafty", + "pufferpanel", + "calagopus", + "amp", + "generic_rest", +} +PROVIDER_ALIASES = { + "ptero": "pterodactyl", + "pterodactyl1": "pterodactyl", + "pterodactyl2": "pterodactyl", + "pterodactyl-1.x": "pterodactyl", + "pterodactyl-2.x": "pterodactyl", + "mcsmanager9": "mcsmanager", + "mcsmanager10": "mcsmanager", + "mcs-manager": "mcsmanager", + "crafty-controller": "crafty", + "craftycontroller": "crafty", + "puffer-panel": "pufferpanel", + "cube-coders-amp": "amp", + "cubecoders_amp": "amp", + "cagolqupus": "calagopus", + "generic": "generic_rest", + "rest": "generic_rest", +} + +DEFAULT_API_BASE_PATH = { + "pterodactyl": "", + "pelican": "", + "mcsmanager": "/api", + "crafty": "/api/v2", + "pufferpanel": "/api", + "calagopus": "/api", + "amp": "/API", + "generic_rest": "", +} + +PANEL_API_NAMESPACES = { + "pterodactyl": {"client", "application", "admin"}, + "pelican": {"client", "application"}, +} +PTERODACTYL_ACCEPT = "Application/vnd.pterodactyl.v1+json" +JSON_ACCEPT = "application/json" + + +def normalize_provider(value: Any) -> str: + provider = str(value or "pterodactyl").strip().lower().replace(" ", "_") + provider = PROVIDER_ALIASES.get(provider, provider) + if provider not in SUPPORTED_PROVIDERS: + supported = ", ".join(sorted(SUPPORTED_PROVIDERS)) + raise RuntimeError(f"Unsupported panel provider '{provider}'. Supported providers: {supported}.") + return provider + + +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.") + 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.") + if len(raw) > 256: + raise RuntimeError(f"Panel '{panel.get('id', '?')}' api_base_path is too long.") + return "/" + "/".join(part for part in parts if part) if raw.strip("/") else "" + + +def _validate_relative_path(path: str) -> str: + if not isinstance(path, str): + raise ValueError("path must be a relative API path.") + raw = path.strip() + if raw.startswith("//"): + raise ValueError("Absolute network-path URLs are not allowed.") + relative = raw.lstrip("/") + if ( + "://" in relative + or "?" in relative + or "#" in relative + or "%" in relative + or "\\" in relative + or any(ord(char) < 32 for char in relative) + ): + raise ValueError("path must be relative; pass query parameters separately.") + if any(segment in {".", ".."} for segment in relative.split("/")): + raise ValueError("path cannot contain traversal segments.") + if len(relative) > 2048: + raise ValueError("path is too long.") + return relative + + +def route_request(panel: dict[str, Any], api: str, path: str) -> tuple[str, str, str, str]: + """Resolve provider, API namespace, and relative path into a trusted URL. + + Returns (url, api_kind, accept_header, normalized_relative_path). + """ + provider = normalize_provider(panel.get("provider")) + api = str(api or "").strip().lower() + relative = _validate_relative_path(path) + base_url = str(panel["base_url"]).rstrip("/") + + if provider in PTERODACTYL_COMPATIBLE: + if api not in PANEL_API_NAMESPACES[provider]: + allowed = ", ".join(sorted(PANEL_API_NAMESPACES[provider])) + raise ValueError(f"Provider '{provider}' supports the API namespaces: {allowed}.") + version = str(panel.get("panel_version", "auto")).lower() + if provider == "pterodactyl" and api == "admin" and version in {"1", "1.x", "v1"}: + raise ValueError("Pterodactyl Admin API is only available in 2.x. Use Client/Application for 1.x.") + prefix = f"api/{api}" + if relative == prefix: + relative = "" + elif relative.startswith(prefix + "/"): + relative = relative[len(prefix) + 1:] + url = f"{base_url}/{prefix}" + (f"/{relative}" if relative else "") + return url, api, PTERODACTYL_ACCEPT, relative + + if api not in {"native", "custom"}: + raise ValueError( + f"Provider '{provider}' uses its native API. Set api='native' and pass a path from that panel's API docs." + ) + + api_base_path = normalize_api_base_path(panel, provider) + # Accept an already-prefixed path without producing /api/api/... by accident. + if api_base_path and (relative == api_base_path.strip("/") or relative.startswith(api_base_path.strip("/") + "/")): + relative = relative[len(api_base_path.strip("/")):].lstrip("/") + url = base_url + api_base_path + (f"/{relative}" if relative else "") + return url, "native", JSON_ACCEPT, relative diff --git a/src/map_server/server.py b/src/map_server/server.py index c4b4cd5..6e3bcdc 100644 --- a/src/map_server/server.py +++ b/src/map_server/server.py @@ -4,6 +4,7 @@ import argparse import base64 import os +import re from typing import Any from urllib.parse import urlparse @@ -27,6 +28,7 @@ _token_for, ) from .security import BearerGuard +from .providers import PTERODACTYL_COMPATIBLE, normalize_provider mcp = FastMCP(MAP_SERVER_NAME, host=HOST, port=PORT) @@ -34,29 +36,78 @@ @mcp.tool() def list_panels() -> dict[str, Any]: - """List configured panels and available API-key types without revealing secret values.""" + """List configured panel providers and auth readiness without revealing credentials.""" result = [] for panel in _panels().values(): - parsed = urlparse(panel["base_url"]) + provider = normalize_provider(panel.get("provider")) + ptero_compatible = provider in PTERODACTYL_COMPATIBLE + if ptero_compatible: + apis_available = { + "client": bool(panel.get("client_api_key")), + "application": bool(panel.get("application_api_key") or panel.get("admin_api_key")), + "admin": provider == "pterodactyl" and bool(panel.get("admin_api_key")), + } + api_mode = "pterodactyl_compatible" + else: + apis_available = {"native": bool( + panel.get("api_key") + or (panel.get("oauth_client_id") and panel.get("oauth_client_secret")) + or (panel.get("auth_type") == "basic" and panel.get("auth_username") and panel.get("auth_password")) + or (provider == "amp" and panel.get("auth_username") and panel.get("auth_password")) + or panel.get("auth_type") == "none" + )} + api_mode = "native" result.append({ "id": panel["id"], "name": panel["name"], "base_url": panel["base_url"], + "provider": provider, + "panel_version": panel.get("panel_version", "auto"), + "api_base_path": panel.get("api_base_path", ""), + "api_mode": api_mode, "configured": bool(panel["base_url"]), - "https": parsed.scheme == "https", - "apis_available": { - "client": bool(panel.get("client_api_key")), - "application": bool(panel.get("application_api_key") or panel.get("admin_api_key")), - "admin": bool(panel.get("admin_api_key")), - }, + "https": urlparse(panel["base_url"]).scheme == "https", + "auth_type": panel.get("auth_type", "bearer"), + "apis_available": apis_available, + "dedicated_server_tools": ptero_compatible or provider == "mcsmanager", }) return {"panels": result, "count": len(result)} +def _require_panel_provider(panel_id: str, allowed: set[str], operation: str) -> dict[str, Any]: + panel = _panel(panel_id) + provider = normalize_provider(panel.get("provider")) + if provider not in allowed: + expected = ", ".join(sorted(allowed)) + raise ValueError( + f"{operation} is not implemented for provider '{provider}'. " + f"Supported providers for this tool: {expected}. Use panel_api_request with api='native' for other panels." + ) + return panel + + @mcp.tool() -def panel_status(panel_id: str, api: str = "application") -> dict[str, Any]: - """Check panel API connectivity by requesting the selected API namespace root.""" - return _api_request(panel_id, api, "GET", "") +def panel_status(panel_id: str, api: str = "auto") -> dict[str, Any]: + """Check connectivity to the configured panel's API.""" + panel = _panel(panel_id) + provider = normalize_provider(panel.get("provider")) + if api == "auto": + if provider in PTERODACTYL_COMPATIBLE: + if panel.get("client_api_key"): + api = "client" + elif panel.get("application_api_key") or panel.get("admin_api_key"): + api = "application" + else: + api = "client" + path = "" + else: + api = "native" + path = str(panel.get("status_path") or ("Core/GetStatus" if provider == "amp" else "")) + else: + path = "" + if provider == "amp": + return _api_request(panel_id, api, "POST", path, json_body={}) + return _api_request(panel_id, api, "GET", path) @mcp.tool() @@ -71,10 +122,11 @@ def panel_api_request( content_type: str | None = None, timeout_seconds: int = 30, ) -> dict[str, Any]: - """Request any relative Pterodactyl Client, Application, or Admin API endpoint. + """Request a relative endpoint from any supported panel API. - Supports read and write methods. Use the panel-version API docs to choose namespace, - endpoint, method, query parameters, and request body. Arbitrary external URLs are rejected. + Pterodactyl/Pelican use client/application (and Pterodactyl 2.x admin) namespaces. + MCSManager, Crafty, PufferPanel, and generic REST profiles use api='native'. + Arbitrary external URLs are rejected; writes can be destructive. """ return _api_request(panel_id, api, method, path, query_params, json_body, raw_body, content_type, timeout_seconds) @@ -84,12 +136,92 @@ def list_servers(panel_id: str, page: int = 1, api: str = "application") -> dict """List servers using the Application API, or the Client API when api='client'.""" if page < 1 or page > 1000: raise ValueError("page must be between 1 and 1000.") - return _api_request(panel_id, api, "GET", "servers" if api != "client" else "", {"page": page}) + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "list_servers") + if api == "client": + # Pterodactyl 1.x and 2.x list the user's servers at GET /api/client. + return _api_request(panel_id, api, "GET", "", {"page": page}) + if api == "application": + return _api_request(panel_id, api, "GET", "servers", {"page": page}) + raise ValueError("api must be client or application for list_servers.") + + + +@mcp.tool() +def mcsmanager_list_instances( + panel_id: str, daemon_id: str, page: int = 1, page_size: int = 50 +) -> dict[str, Any]: + """List MCSManager instances for a daemon using the native MCSManager API.""" + _require_panel_provider(panel_id, {"mcsmanager"}, "mcsmanager_list_instances") + if not daemon_id or len(daemon_id) > 256: + raise ValueError("daemon_id must be between 1 and 256 characters.") + if page < 1 or page > 1000 or page_size < 1 or page_size > 50: + raise ValueError("page must be 1–1000 and page_size must be 1–50.") + return _api_request( + panel_id, "native", "GET", "service/remote_service_instances", + {"daemonId": daemon_id, "page": page, "page_size": page_size}, + ) + + +@mcp.tool() +def mcsmanager_instance_action( + panel_id: str, daemon_id: str, instance_uuid: str, action: str +) -> dict[str, Any]: + """Start, stop, restart, or kill an MCSManager instance using its native API.""" + _require_panel_provider(panel_id, {"mcsmanager"}, "mcsmanager_instance_action") + if not daemon_id or len(daemon_id) > 256: + raise ValueError("daemon_id must be between 1 and 256 characters.") + if not SERVER_ID_RE.fullmatch(instance_uuid or ""): + raise ValueError("instance_uuid contains unsupported characters.") + action = action.strip().lower() + routes = {"start": "open", "stop": "stop", "restart": "restart", "kill": "kill"} + if action not in routes: + raise ValueError("action must be start, stop, restart, or kill.") + return _api_request( + panel_id, "native", "GET", f"protected_instance/{routes[action]}", + {"uuid": instance_uuid, "daemonId": daemon_id}, + ) + + +@mcp.tool() +def mcsmanager_instance_command( + panel_id: str, daemon_id: str, instance_uuid: str, command: str +) -> dict[str, Any]: + """Send a command to an MCSManager instance through its native HTTP API.""" + _require_panel_provider(panel_id, {"mcsmanager"}, "mcsmanager_instance_command") + if not daemon_id or len(daemon_id) > 256: + raise ValueError("daemon_id must be between 1 and 256 characters.") + if not SERVER_ID_RE.fullmatch(instance_uuid or ""): + raise ValueError("instance_uuid contains unsupported characters.") + if not command or len(command) > 10000: + raise ValueError("command must be between 1 and 10000 characters.") + return _api_request( + panel_id, "native", "GET", "protected_instance/command", + {"uuid": instance_uuid, "daemonId": daemon_id, "command": command}, + ) + + +@mcp.tool() +def mcsmanager_instance_output_log( + panel_id: str, daemon_id: str, instance_uuid: str, size: str = "10KB" +) -> dict[str, Any]: + """Read the recent output log for an MCSManager instance.""" + _require_panel_provider(panel_id, {"mcsmanager"}, "mcsmanager_instance_output_log") + if not daemon_id or len(daemon_id) > 256: + raise ValueError("daemon_id must be between 1 and 256 characters.") + if not SERVER_ID_RE.fullmatch(instance_uuid or ""): + raise ValueError("instance_uuid contains unsupported characters.") + if not re.fullmatch(r"\d+(?:KB)?", size.strip().upper()): + raise ValueError("size must be a byte count or a value such as 10KB.") + return _api_request( + panel_id, "native", "GET", "protected_instance/outputlog", + {"uuid": instance_uuid, "daemonId": daemon_id, "size": size.strip().upper()}, + ) @mcp.tool() def server_resources(panel_id: str, server_id: str) -> dict[str, Any]: """Read live resource usage and running state for a server.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_resources") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") return _api_request(panel_id, "client", "GET", f"servers/{server_id}/resources") @@ -98,6 +230,7 @@ def server_resources(panel_id: str, server_id: str) -> dict[str, Any]: @mcp.tool() def server_power(panel_id: str, server_id: str, signal: str) -> dict[str, Any]: """Start, stop, restart, or force-kill a server through the Pterodactyl Client API.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_power") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") signal = signal.lower().strip() @@ -109,6 +242,7 @@ def server_power(panel_id: str, server_id: str, signal: str) -> dict[str, Any]: @mcp.tool() def server_console_command(panel_id: str, server_id: str, command: str) -> dict[str, Any]: """Send a console command to a server. Server state and API permissions still apply.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_console_command") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") if not command or len(command) > 10000: @@ -119,6 +253,7 @@ def server_console_command(panel_id: str, server_id: str, command: str) -> dict[ @mcp.tool() def server_list_files(panel_id: str, server_id: str, directory: str = "/") -> dict[str, Any]: """List files and folders in a server directory.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_list_files") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") return _api_request(panel_id, "client", "GET", f"servers/{server_id}/files/list", {"directory": directory}) @@ -127,6 +262,7 @@ def server_list_files(panel_id: str, server_id: str, directory: str = "/") -> di @mcp.tool() def server_read_file(panel_id: str, server_id: str, file: str) -> dict[str, Any]: """Read a text file from the server filesystem.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_read_file") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") return _api_request(panel_id, "client", "GET", f"servers/{server_id}/files/contents", {"file": file}) @@ -135,6 +271,7 @@ def server_read_file(panel_id: str, server_id: str, file: str) -> dict[str, Any] @mcp.tool() def server_write_file(panel_id: str, server_id: str, file: str, content: str) -> dict[str, Any]: """Create or overwrite a text file on a server. Panel permissions apply.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_write_file") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") if len(content.encode("utf-8")) > 2_000_000: @@ -148,6 +285,7 @@ def server_write_file(panel_id: str, server_id: str, file: str, content: str) -> @mcp.tool() def server_create_directory(panel_id: str, server_id: str, name: str, root: str = "/") -> dict[str, Any]: """Create a directory in the server filesystem.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_create_directory") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") return _api_request(panel_id, "client", "POST", f"servers/{server_id}/files/create-folder", @@ -157,6 +295,7 @@ def server_create_directory(panel_id: str, server_id: str, name: str, root: str @mcp.tool() def server_delete_files(panel_id: str, server_id: str, files: list[str], root: str = "/") -> dict[str, Any]: """Delete selected server files or folders permanently.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_delete_files") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") if not files or len(files) > 500: @@ -168,6 +307,7 @@ def server_delete_files(panel_id: str, server_id: str, files: list[str], root: s @mcp.tool() def server_rename_files(panel_id: str, server_id: str, root: str, files: list[dict[str, str]]) -> dict[str, Any]: """Rename or move files using a list of from/to pairs.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_rename_files") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") if not files or len(files) > 200: @@ -182,6 +322,7 @@ def server_rename_files(panel_id: str, server_id: str, root: str, files: list[di @mcp.tool() def server_create_backup(panel_id: str, server_id: str, name: str | None = None, ignored: list[str] | None = None) -> dict[str, Any]: """Start a backup for a server.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_create_backup") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") body: dict[str, Any] = {} @@ -195,6 +336,7 @@ def server_create_backup(panel_id: str, server_id: str, name: str | None = None, @mcp.tool() def server_list_backups(panel_id: str, server_id: str) -> dict[str, Any]: """List backups registered for a server.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_list_backups") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") return _api_request(panel_id, "client", "GET", f"servers/{server_id}/backups") @@ -203,6 +345,7 @@ def server_list_backups(panel_id: str, server_id: str) -> dict[str, Any]: @mcp.tool() def server_delete_backup(panel_id: str, server_id: str, backup_id: str) -> dict[str, Any]: """Delete a server backup by UUID. This is destructive.""" + _require_panel_provider(panel_id, PTERODACTYL_COMPATIBLE, "server_delete_backup") if not SERVER_ID_RE.fullmatch(server_id or ""): raise ValueError("server_id contains unsupported characters.") if not SERVER_ID_RE.fullmatch(backup_id or ""): @@ -322,7 +465,8 @@ def server_download_file_base64( "server_resources", "server_power", "server_console_command", "server_list_files", "server_read_file", "server_write_file", "server_create_directory", "server_delete_files", "server_rename_files", "server_create_backup", "server_list_backups", "server_delete_backup", - "server_upload_file_base64", "server_download_file_base64", "BearerGuard", + "mcsmanager_list_instances", "mcsmanager_instance_action", "mcsmanager_instance_command", + "mcsmanager_instance_output_log", "server_upload_file_base64", "server_download_file_base64", "BearerGuard", "_safe_json", "_panel", "_panels", "_token_for", "SUPPORTED_APIS", "SUPPORTED_METHODS", ] diff --git a/tests/test_safety.py b/tests/test_safety.py index 0a84489..877eeb0 100644 --- a/tests/test_safety.py +++ b/tests/test_safety.py @@ -110,7 +110,7 @@ async def check(): def test_admin_methods_and_full_access_tools_are_available(): assert server.SUPPORTED_METHODS == {"GET", "POST", "PUT", "PATCH", "DELETE"} - assert server.SUPPORTED_APIS == {"client", "application", "admin"} + assert server.SUPPORTED_APIS == {"client", "application", "admin", "native"} for name in ( "panel_api_request", "server_power", "server_console_command", "server_write_file", "server_upload_file_base64", "server_download_file_base64", @@ -175,3 +175,503 @@ def test_api_request_caps_streamed_response(monkeypatch): assert result["status_code"] == 413 assert "MAP_MAX_RESPONSE_BYTES" in result["error"] assert response.closed is True + + +def test_list_servers_uses_servers_endpoint_for_client_api(monkeypatch): + configured_panel(monkeypatch) + calls = [] + response = FakeResponse(body=b'{"data":[]}') + def fake_request(method, url, **kwargs): + calls.append((method, url, kwargs)) + return response + + monkeypatch.setattr(client.requests, "request", fake_request) + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "bp", + "name": "ByteProject", + "base_url": "https://panel.example.test", + "panel_version": "1.x", + "client_api_key": "client-secret-value", + "application_api_key": "application-secret-value", + }]), + ) + result = server.list_servers("bp", api="client") + + assert result["ok"] is True + assert calls[0][1] == "https://panel.example.test/api/client" + assert calls[0][2]["params"] == {"page": 1} + + +def test_text_response_redacts_signed_urls_and_configured_keys(monkeypatch): + configured_panel(monkeypatch) + body = ( + "Signed URL: https://node.example.test/upload?token=signed-value&file=world.zip " + "leaked=client-secret-value" + ).encode("utf-8") + response = FakeResponse( + body=body, + headers={"content-type": "text/plain; charset=utf-8"}, + ) + monkeypatch.setattr(client.requests, "request", lambda *args, **kwargs: response) + + result = client._api_request("bp", "client", "GET", "servers") + + assert result["ok"] is True + assert "signed-value" not in result["data"] + assert "[REDACTED]" in result["data"] + assert "world.zip" in result["data"] + assert "client-secret-value" not in result["data"] + + +@pytest.mark.parametrize( + "base_url", + [ + "http://panel.example.test", + "https://user:password@panel.example.test", + "https://panel.example.test/path?token=secret", + "https://127.0.0.1", + "https://panel.example.test:invalid", + ], +) +def test_panel_config_rejects_unsafe_origins(monkeypatch, base_url): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([ + { + "id": "bp", + "base_url": base_url, + "client_api_key": "client-secret-value", + } + ]), + ) + with pytest.raises(RuntimeError): + server.list_panels() + + +def test_panel_config_caps_number_of_panels(monkeypatch): + panels = [ + { + "id": f"p{index}", + "base_url": f"https://panel-{index}.example.test", + "client_api_key": "dummy-key", + } + for index in range(21) + ] + monkeypatch.setenv("MAP_PANELS_JSON", json.dumps(panels)) + with pytest.raises(RuntimeError, match="at most 20 panels"): + server.list_panels() + + + +def configured_mcsmanager(monkeypatch, **extra): + panel = { + "id": "mcsm", + "name": "MCSManager", + "provider": "mcsmanager", + "base_url": "https://mcsm.example.test", + "api_key": "mcsm-secret-key", + } + panel.update(extra) + monkeypatch.setenv("MAP_PANELS_JSON", json.dumps([panel])) + monkeypatch.delenv("MAP_PANELS_JSON_B64", raising=False) + + +def test_provider_config_defaults_to_legacy_pterodactyl(monkeypatch): + configured_panel(monkeypatch) + panel = server._panel("bp") + assert panel["provider"] == "pterodactyl" + assert server.list_panels()["panels"][0]["api_mode"] == "pterodactyl_compatible" + + +def test_pterodactyl_v1_blocks_admin_namespace(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "p1", + "provider": "pterodactyl", + "panel_version": "1.x", + "base_url": "https://panel.example.test", + "client_api_key": "client-key", + "admin_api_key": "admin-key", + }]), + ) + with pytest.raises(ValueError, match="only available in 2.x"): + client._api_request("p1", "admin", "GET", "eggs") + + +def test_mcsmanager_native_route_and_query_auth(monkeypatch): + configured_mcsmanager(monkeypatch) + calls = [] + response = FakeResponse(body=b'{"status":200,"data":[],"time":123}') + def fake_request(method, url, **kwargs): + calls.append((method, url, kwargs)) + return response + + monkeypatch.setattr(client.requests, "request", fake_request) + result = server.mcsmanager_list_instances("mcsm", "daemon-123", page=2, page_size=20) + + assert result["ok"] is True + assert result["provider"] == "mcsmanager" + assert calls[0][1] == "https://mcsm.example.test/api/service/remote_service_instances" + assert calls[0][2]["params"] == { + "daemonId": "daemon-123", + "page": 2, + "page_size": 20, + "apikey": "mcsm-secret-key", + } + assert calls[0][2]["headers"]["X-Requested-With"] == "XMLHttpRequest" + assert "mcsm-secret-key" not in json.dumps(result) + + +def test_mcsmanager_action_uses_native_endpoint(monkeypatch): + configured_mcsmanager(monkeypatch) + calls = [] + response = FakeResponse(body=b'{"status":200,"data":true}') + def fake_request(method, url, **kwargs): + calls.append((method, url, kwargs)) + return response + + monkeypatch.setattr(client.requests, "request", fake_request) + result = server.mcsmanager_instance_action("mcsm", "daemon-123", "abc12345", "start") + + assert result["ok"] is True + assert calls[0][0] == "GET" + assert calls[0][1] == "https://mcsm.example.test/api/protected_instance/open" + assert calls[0][2]["params"]["uuid"] == "abc12345" + assert calls[0][2]["params"]["daemonId"] == "daemon-123" + + +def test_mcsmanager_application_error_is_not_reported_as_success(monkeypatch): + configured_mcsmanager(monkeypatch) + response = FakeResponse(body=b'{"status":403,"data":null,"time":123}') + monkeypatch.setattr(client.requests, "request", lambda *args, **kwargs: response) + result = client._api_request("mcsm", "native", "GET", "overview") + + assert result["ok"] is False + assert result["status_code"] == 200 + + +def test_custom_rest_provider_uses_configured_prefix_and_auth(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "crafty", + "provider": "crafty", + "base_url": "https://crafty.example.test", + "api_key": "crafty-token", + "auth_type": "bearer", + }]), + ) + calls = [] + response = FakeResponse(body=b'{"servers":[]}') + def fake_request(method, url, **kwargs): + calls.append((method, url, kwargs)) + return response + + monkeypatch.setattr(client.requests, "request", fake_request) + result = client._api_request("crafty", "native", "GET", "servers") + + assert result["ok"] is True + assert calls[0][1] == "https://crafty.example.test/api/v2/servers" + assert calls[0][2]["headers"]["Authorization"] == "Bearer crafty-token" + + +def test_generic_rest_provider_supports_custom_api_path_and_header_auth(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "custom", + "provider": "generic_rest", + "base_url": "https://api.example.test/root", + "api_base_path": "/v9/control", + "api_key": "custom-key", + "auth_type": "header", + "auth_header": "X-API-Key", + "auth_scheme": "", + }]), + ) + calls = [] + response = FakeResponse(body=b'{"ok":true}') + def fake_request(method, url, **kwargs): + calls.append((method, url, kwargs)) + return response + + monkeypatch.setattr(client.requests, "request", fake_request) + result = client._api_request("custom", "native", "GET", "status") + + assert result["ok"] is True + assert calls[0][1] == "https://api.example.test/root/v9/control/status" + assert calls[0][2]["headers"]["X-API-Key"] == "custom-key" + + +def test_pufferpanel_oauth_token_is_cached_and_used(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "puffer", + "provider": "pufferpanel", + "base_url": "https://puffer.example.test", + "oauth_client_id": "oauth-client-id", + "oauth_client_secret": "oauth-client-secret", + }]), + ) + token_calls = [] + api_calls = [] + + class JsonResponse(FakeResponse): + def json(self): + return {"access_token": "cached-access-token", "expires_in": 3600} + + token_response = JsonResponse(body=b'{"access_token":"cached-access-token"}') + def fake_post(url, **kwargs): + token_calls.append((url, kwargs)) + return token_response + def fake_request(method, url, **kwargs): + api_calls.append((method, url, kwargs)) + return FakeResponse(body=b'{"data":[]}') + monkeypatch.setattr(client.requests, "post", fake_post) + monkeypatch.setattr(client.requests, "request", fake_request) + client._OAUTH_CACHE.clear() + + client._api_request("puffer", "native", "GET", "servers") + client._api_request("puffer", "native", "GET", "servers") + + assert len(token_calls) == 1 + assert token_calls[0][0] == "https://puffer.example.test/oauth2/token" + assert token_calls[0][1]["data"]["grant_type"] == "client_credentials" + assert api_calls[0][1] == "https://puffer.example.test/api/servers" + assert api_calls[0][2]["headers"]["Authorization"] == "Bearer cached-access-token" + assert "oauth-client-secret" not in json.dumps(server.list_panels()) + + +def test_pterodactyl_style_tools_reject_unrelated_panel_types(monkeypatch): + configured_mcsmanager(monkeypatch) + with pytest.raises(ValueError, match="not implemented for provider"): + server.server_power("mcsm", "abc12345", "start") + + +def test_calagopus_alias_uses_native_api_and_non_pterodactyl_auth(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "cal", + "name": "Calagopus", + "provider": "cagolqupus", + "base_url": "https://calagopus.example.test", + "api_key": "calagopus-secret-token", + }]), + ) + calls = [] + response = FakeResponse(body=b'{"servers":[]}') + def fake_request(method, url, **kwargs): + calls.append((method, url, kwargs)) + return response + + monkeypatch.setattr(client.requests, "request", fake_request) + result = client._api_request("cal", "native", "GET", "client/servers") + + assert result["ok"] is True + assert result["provider"] == "calagopus" + assert calls[0][1] == "https://calagopus.example.test/api/client/servers" + assert calls[0][2]["headers"]["Authorization"] == "Bearer calagopus-secret-token" + assert "calagopus-secret-token" not in json.dumps(server.list_panels()) + with pytest.raises(ValueError, match="not implemented for provider"): + server.server_power("cal", "abcd1234", "start") + + +def test_calagopus_default_path_and_auth_configuration(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "cal", + "provider": "calagopus", + "base_url": "https://calagopus.example.test", + "api_key": "calagopus-key", + }]), + ) + panel = server._panel("cal") + assert panel["api_base_path"] == "/api" + assert panel["auth_type"] == "bearer" + assert server.list_panels()["panels"][0]["dedicated_server_tools"] is False + + +def test_calagopus_provider_alias_is_available_in_registry(): + from map_server.providers import normalize_provider + + assert normalize_provider("cagolqupus") == "calagopus" + + + +def test_basic_auth_provider_header_and_redaction(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "basic", + "provider": "generic_rest", + "base_url": "https://basic.example.test", + "api_base_path": "/v1", + "auth_type": "basic", + "auth_username": "operator", + "auth_password": "hidden-basic-password", + }]), + ) + calls = [] + response = FakeResponse( + body=b'{"ok":true,"password":"hidden-basic-password"}', + ) + def fake_request(method, url, **kwargs): + calls.append((method, url, kwargs)) + return response + + monkeypatch.setattr(client.requests, "request", fake_request) + result = client._api_request("basic", "native", "GET", "status") + + assert result["ok"] is True + assert calls[0][2]["headers"]["Authorization"] == "Basic " + base64.b64encode( + b"operator:hidden-basic-password" + ).decode("ascii") + assert "hidden-basic-password" not in json.dumps(result) + assert result["data"]["password"] == "[REDACTED]" + + +def test_amp_session_authenticates_once_and_injects_session_id(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "amp", + "provider": "amp", + "base_url": "https://amp.example.test", + "auth_type": "amp_session", + "auth_username": "service-user", + "auth_password": "hidden-amp-password", + }]), + ) + login_calls = [] + api_calls = [] + + login_response = FakeResponse( + body=b'{"sessionID":"amp-session-secret","result":"Success"}', + headers={"content-type": "application/json"}, + ) + api_response = FakeResponse( + body=b'{"result":"Success","SESSIONID":"amp-session-secret","state":"running"}', + headers={"content-type": "application/json"}, + ) + + def fake_post(url, **kwargs): + login_calls.append((url, kwargs)) + return login_response + + def fake_request(method, url, **kwargs): + api_calls.append((method, url, kwargs)) + return api_response + + monkeypatch.setattr(client.requests, "post", fake_post) + monkeypatch.setattr(client.requests, "request", fake_request) + client._AMP_SESSION_CACHE.clear() + + first = client._api_request("amp", "native", "POST", "Core/GetStatus", json_body={"verbose": True}) + second = client._api_request("amp", "native", "POST", "Core/GetStatus", json_body={"verbose": False}) + + assert first["ok"] is True + assert second["ok"] is True + assert len(login_calls) == 1 + assert login_calls[0][0] == "https://amp.example.test/API/Core/Login" + assert json.loads(login_calls[0][1]["data"])["username"] == "service-user" + assert json.loads(login_calls[0][1]["data"].decode())["password"] == "hidden-amp-password" + assert api_calls[0][0] == "POST" + assert api_calls[0][1] == "https://amp.example.test/API/Core/GetStatus" + assert json.loads(api_calls[0][2]["data"])["SESSIONID"] == "amp-session-secret" + assert first["data"]["SESSIONID"] == "[REDACTED]" + assert "amp-session-secret" not in json.dumps(first) + assert "hidden-amp-password" not in json.dumps(server.list_panels()) + + +def test_amp_native_api_requires_post_and_json_object(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "amp", + "provider": "amp", + "base_url": "https://amp.example.test", + "auth_username": "service-user", + "auth_password": "hidden-amp-password", + }]), + ) + with pytest.raises(ValueError, match="use POST"): + client._api_request("amp", "native", "GET", "Core/GetStatus") + monkeypatch.setattr( + client.requests, "post", + lambda *args, **kwargs: FakeResponse(body=b'{"sessionID":"amp-session","result":"Success"}'), + ) + with pytest.raises(ValueError, match="must be an object"): + client._api_request("amp", "native", "POST", "Core/GetStatus", json_body=["not", "an", "object"]) + + +def test_amp_panel_credentials_are_required_and_never_exposed(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "amp", + "provider": "amp", + "base_url": "https://amp.example.test", + "auth_username": "operator", + }]), + ) + with pytest.raises(RuntimeError, match="require auth_username and auth_password"): + server.list_panels() + + +def test_pufferpanel_rejects_partial_oauth_credentials(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "puffer", + "provider": "pufferpanel", + "base_url": "https://puffer.example.test", + "oauth_client_id": "only-id", + }]), + ) + with pytest.raises(RuntimeError, match="both oauth_client_id and oauth_client_secret"): + server.list_panels() + + +def test_pufferpanel_rejects_missing_auth_credentials(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "puffer", + "provider": "pufferpanel", + "base_url": "https://puffer.example.test", + }]), + ) + with pytest.raises(RuntimeError, match="requires OAuth client credentials or a bearer api_key"): + server.list_panels() + + +def test_amp_status_uses_native_post_endpoint(monkeypatch): + monkeypatch.setenv( + "MAP_PANELS_JSON", + json.dumps([{ + "id": "amp", + "provider": "amp", + "base_url": "https://amp.example.test", + "auth_username": "service-user", + "auth_password": "hidden-amp-password", + }]), + ) + calls = [] + login_response = FakeResponse(body=b'{"sessionID":"amp-session-secret","result":"Success"}') + api_response = FakeResponse(body=b'{"result":"Success","state":"Running"}') + monkeypatch.setattr(client.requests, "post", lambda url, **kwargs: (calls.append(("login", url, kwargs)) or login_response)) + monkeypatch.setattr(client.requests, "request", lambda method, url, **kwargs: (calls.append((method, url, kwargs)) or api_response)) + client._AMP_SESSION_CACHE.clear() + + result = server.panel_status("amp") + + assert result["ok"] is True + assert calls[0][0] == "login" + assert calls[1][0] == "POST" + assert calls[1][1] == "https://amp.example.test/API/Core/GetStatus" diff --git a/wiki/Deployment.md b/wiki/Deployment.md deleted file mode 100644 index 7b477de..0000000 --- a/wiki/Deployment.md +++ /dev/null @@ -1,7 +0,0 @@ -# Deployment - -Supported modes are HTTP for hosted services and stdio for local MCP clients. Docker Compose publishes HTTP only on host loopback and requires a bearer token. The systemd example uses an unprivileged service account and root-owned environment file. - -Remote use requires HTTPS ingress and access controls. Never expose unauthenticated plaintext HTTP. - -See the [deployment guide](https://github.com/RealmsNetwork/MAP/blob/main/docs/deployment.md). diff --git a/wiki/Development-and-Contributing.md b/wiki/Development-and-Contributing.md deleted file mode 100644 index c64e62a..0000000 --- a/wiki/Development-and-Contributing.md +++ /dev/null @@ -1,5 +0,0 @@ -# Development and Contributing - -Install with `python -m pip install -e '.[dev]'`. Run `ruff check src tests deploy`, `pytest -q`, and `python -m build`. Tests should use mocks and never require production credentials. - -Read [CONTRIBUTING.md](https://github.com/RealmsNetwork/MAP/blob/main/CONTRIBUTING.md). diff --git a/wiki/Home.md b/wiki/Home.md deleted file mode 100644 index c53c509..0000000 --- a/wiki/Home.md +++ /dev/null @@ -1,11 +0,0 @@ -# Model Access Panel Wiki - -Welcome to the MAP handbook. The canonical operator guide is versioned in `docs/`. - -- [Quick Start](Quick-Start) -- [Multi-Panel Configuration](Multi-Panel-Configuration) -- [Tool Reference](Tool-Reference) -- [Deployment](Deployment) -- [Security](Security) -- [Troubleshooting](Troubleshooting) -- [Development and Contributing](Development-and-Contributing) diff --git a/wiki/Multi-Panel-Configuration.md b/wiki/Multi-Panel-Configuration.md deleted file mode 100644 index 97e7e7b..0000000 --- a/wiki/Multi-Panel-Configuration.md +++ /dev/null @@ -1,5 +0,0 @@ -# Multi-Panel Configuration - -MAP routes calls by `panel_id`. Configure `MAP_PANELS_JSON` with one object per panel or use `MAP_PANELS_JSON_B64` for systemd. Every panel needs a unique ID and HTTPS base URL; add only the key types required for the tasks you intend to perform. Do not commit credentials. - -Read the [configuration reference](https://github.com/RealmsNetwork/MAP/blob/main/docs/configuration.md). diff --git a/wiki/Quick-Start.md b/wiki/Quick-Start.md deleted file mode 100644 index 9573b42..0000000 --- a/wiki/Quick-Start.md +++ /dev/null @@ -1,15 +0,0 @@ -# Quick Start - -Requires Python 3.11+. - -```bash -git clone https://github.com/RealmsNetwork/MAP.git -cd MAP -python -m venv .venv -. .venv/bin/activate -python -m pip install -e '.[dev]' -cp .env.example .env -map-server --transport http -``` - -The default URL is `http://127.0.0.1:8765/mcp`. Read the [configuration guide](https://github.com/RealmsNetwork/MAP/blob/main/docs/configuration.md) before adding a panel. diff --git a/wiki/Security.md b/wiki/Security.md deleted file mode 100644 index 93bb087..0000000 --- a/wiki/Security.md +++ /dev/null @@ -1,5 +0,0 @@ -# Security - -MAP can make destructive changes when configured API keys allow them. Use least-privilege panel tokens, keep secrets server-side, protect remote transport with HTTPS/authentication, and verify the selected panel before writes. - -MAP provides no host shell or root access. Report vulnerabilities privately according to [SECURITY.md](https://github.com/RealmsNetwork/MAP/blob/main/SECURITY.md). diff --git a/wiki/Tool-Reference.md b/wiki/Tool-Reference.md deleted file mode 100644 index d7ad95d..0000000 --- a/wiki/Tool-Reference.md +++ /dev/null @@ -1,5 +0,0 @@ -# Tool Reference - -MAP offers panel discovery, generic Client/Application/Admin API requests, server resource/power/console controls, file operations, bounded binary transfers, and backup tools. Generic requests support GET, POST, PUT, PATCH, and DELETE. - -Read the [tool reference](https://github.com/RealmsNetwork/MAP/blob/main/docs/tools.md). Review destructive methods before use. diff --git a/wiki/Troubleshooting.md b/wiki/Troubleshooting.md deleted file mode 100644 index 7081d53..0000000 --- a/wiki/Troubleshooting.md +++ /dev/null @@ -1,10 +0,0 @@ -# Troubleshooting - -- Empty `list_panels`: configure panels and restart. -- 401/403: verify key type, namespace, and permissions. -- 404: check panel version and relative endpoint path. -- Transfer refused: trust the exact Wings hostname and verify connectivity. -- Remote HTTP blocked: use HTTPS and bearer token. -- Non-loopback startup blocked: set a random 32+ character token. - -See the [full troubleshooting guide](https://github.com/RealmsNetwork/MAP/blob/main/docs/troubleshooting.md).