#!/usr/bin/env python3
"""Probe what an MCPProxy credential can reach, without running any upstream tool.

The credential is read from a file (--token-file) or from an environment
variable (default MCPPROXY_TOKEN), never from the command line, so it does not
land in shell history or `ps`.

  python3 verify_scope.py --url http://127.0.0.1:8080/mcp \
      --token-file ~/.config/mcpproxy/tokens/notes-agent \
      --allowed filesystem:read_text_file \
      --denied filesystem:write_file --denied everything:echo

Checks, in order. Each one must hold or the run fails:
  1. A request with no credential is refused with 401. Anything else means
     keyless callers are admitted, so the token is optional and this probe
     cannot tell whether the proxy honoured it: FAIL (WARN with
     --allow-anonymous, for a proxy that confines keyless callers on purpose).
  2. The credential is accepted on the MCP endpoint.
  3. tools/list succeeds and lists no administrator tool. Management tools
     (upstream_servers, quarantine_security, code_execution) are a FAIL too
     unless --allow-management is given.
  4. describe_tool returns a definition for every --allowed tool and an
     explicit not_found for every --denied tool. describe_tool never calls an
     upstream server. A hidden tool and a misspelled one both read not_found,
     so take the --denied names from `mcpproxy tools list --server <server>`.
  5. GET /api/v1/config answers 403 (it holds the admin API key; the response
     body is never read).

This probes the token. It does not prove that your client sends it: after the
client connects, check `mcpproxy activity list --token <name>`.

Use the base /mcp endpoint, not a profile URL. Plain http is accepted only for
a loopback address; use https for anything else. Redirects are not followed and
proxy environment variables are ignored. Exit code 0 when every check passed, 2
with a warning (the token is then not verified), 1 when a check failed.
Python 3.8+, standard library only.
"""
import argparse
import ipaddress
import json
import os
import sys
import urllib.error
import urllib.request
from urllib.parse import urlsplit

ADMIN_ONLY = {"credentials", "profiles"}
MANAGEMENT = {"upstream_servers", "quarantine_security", "code_execution"}


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):  # never forward the credential
        return None


# No redirects, and no environment proxies: the credential goes to the given host only.
OPENER = urllib.request.build_opener(NoRedirect, urllib.request.ProxyHandler({}))


def is_loopback(host):
    if host == "localhost":
        return True
    try:
        return ipaddress.ip_address(host).is_loopback
    except ValueError:
        return False


class Session:
    def __init__(self, url, token):
        self.url, self.token, self.sid, self.n = url, token, None, 0

    def post(self, method, params=None, notify=False):
        """Return (http status, JSON-RPC message or None)."""
        body = {"jsonrpc": "2.0", "method": method}
        if params is not None:
            body["params"] = params
        if not notify:
            self.n += 1
            body["id"] = self.n
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
        }
        if self.token:
            headers["X-API-Key"] = self.token
        if self.sid:
            headers["Mcp-Session-Id"] = self.sid
        req = urllib.request.Request(
            self.url, data=json.dumps(body).encode(), headers=headers, method="POST"
        )
        try:
            with OPENER.open(req, timeout=30) as resp:
                self.sid = resp.headers.get("Mcp-Session-Id") or self.sid
                raw = resp.read().decode()
                status = resp.status
        except urllib.error.HTTPError as err:
            return err.code, None
        except (urllib.error.URLError, OSError):
            return 0, None
        if notify or not raw.strip():
            return status, None
        message = None
        if raw.lstrip().startswith("{"):
            try:
                message = json.loads(raw)
            except ValueError:
                message = None
        else:
            for line in raw.splitlines():  # SSE framing
                if line.startswith("data:"):
                    try:
                        message = json.loads(line[5:].strip())
                    except ValueError:
                        pass
        return status, message

    def initialize(self):
        status, msg = self.post(
            "initialize",
            {
                "protocolVersion": "2025-06-18",
                "capabilities": {},
                "clientInfo": {"name": "verify-scope", "version": "1.1"},
            },
        )
        ok = status == 200 and isinstance(msg, dict) and isinstance(msg.get("result"), dict)
        if ok:
            self.post("notifications/initialized", notify=True)
        return status, ok


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--url", required=True, help="MCP endpoint, e.g. http://127.0.0.1:8080/mcp")
    ap.add_argument("--token-file", help="file holding the credential (mode 600)")
    ap.add_argument("--token-env", default="MCPPROXY_TOKEN", help="env var holding the credential")
    ap.add_argument("--allowed", action="append", default=[], metavar="SERVER:TOOL",
                    help="a tool the credential must be able to see (repeatable, at least one)")
    ap.add_argument("--denied", action="append", default=[], metavar="SERVER:TOOL",
                    help="a real tool the credential must not see (repeatable, at least one)")
    ap.add_argument("--no-denied-probe", action="store_true",
                    help="run without --denied: only when the proxy has no tool outside the scope")
    ap.add_argument("--allow-anonymous", action="store_true",
                    help="do not fail when keyless callers are admitted (anonymous_profile setups)")
    ap.add_argument("--allow-management", action="store_true",
                    help="do not fail when management tools or code_execution are listed")
    args = ap.parse_args()

    parts = urlsplit(args.url)
    if parts.scheme not in ("http", "https") or not parts.hostname:
        print("FAIL  --url must be an http(s) URL")
        return 1
    if parts.username or parts.password or parts.query or parts.fragment:
        print("FAIL  --url must not contain credentials, a query string or a fragment")
        return 1
    if parts.scheme == "http" and not is_loopback(parts.hostname):
        print("FAIL  refusing to send a credential over plain http to a non-loopback host; use https")
        return 1
    if parts.path.rstrip("/") != "/mcp":
        print("FAIL  --url must be the base /mcp endpoint: a profile URL (/mcp/p/<slug>) adds its "
              "own scope and would hide what the credential itself can reach")
        return 1
    if not args.allowed:
        print("FAIL  give at least one --allowed tool")
        return 1
    if not args.denied and not args.no_denied_probe:
        print("FAIL  give at least one --denied tool (or --no-denied-probe if the proxy has "
              "no tool outside the scope), or no denial is verified")
        return 1
    if set(args.allowed) & set(args.denied):
        print("FAIL  a tool is listed as both --allowed and --denied")
        return 1

    if args.token_file:
        try:
            with open(os.path.expanduser(args.token_file)) as fh:
                token = fh.read().strip()
        except OSError as err:
            print(f"FAIL  cannot read the token file: {err.strerror}")
            return 1
    else:
        token = os.environ.get(args.token_env, "").strip()
    if not token:
        print(f"FAIL  no credential: pass --token-file or export ${args.token_env}")
        return 1
    if any(ch.isspace() or ord(ch) < 0x21 or ord(ch) > 0x7E for ch in token):
        print("FAIL  the credential contains whitespace or control characters "
              "(more than one token in the file?)")
        return 1

    endpoint = f"{parts.scheme}://{parts.netloc}{parts.path}"
    results = []

    def report(level, text):
        results.append(level)
        print(f"{level:<5} {text}")

    # 1. no credential
    anonymous_admitted = False
    status, ok = Session(endpoint, None).initialize()
    if status == 401:
        report("PASS", "no credential -> 401 (a credential is required)")
    elif ok:
        anonymous_admitted = True
        report(
            "WARN" if args.allow_anonymous else "FAIL",
            "no credential -> accepted: keyless callers are admitted, so a client that "
            "omits the header is not confined by this token, and this probe cannot tell "
            "whether the proxy honoured the token",
        )
    else:
        report("FAIL", f"no credential -> unexpected HTTP {status}; is this an MCPProxy /mcp endpoint?")

    # 2. credential accepted
    s = Session(endpoint, token)
    status, ok = s.initialize()
    if not ok:
        report("FAIL", f"credential refused (HTTP {status})")
        print("RESULT FAILED")
        return 1
    if anonymous_admitted:
        report("WARN", "credential accepted, but so is no credential: this does not show "
                       "that the proxy recognised the token")
    else:
        report("PASS", "credential accepted")

    # 3. built-in tools
    status, listed = s.post("tools/list", {})
    tools = None
    if status == 200 and isinstance(listed, dict) and isinstance(listed.get("result"), dict):
        tools = listed["result"].get("tools")
    if not isinstance(tools, list) or not tools:
        report("FAIL", f"tools/list did not return a tool list (HTTP {status})")
        names = set()
    else:
        names = {t.get("name") for t in tools if isinstance(t, dict)}
        if names & ADMIN_ONLY:
            report("FAIL", f"administrator tools are listed: {sorted(names & ADMIN_ONLY)} (is this the admin key?)")
        elif "describe_tool" not in names or "retrieve_tools" not in names:
            report("FAIL", "the tool list lacks describe_tool/retrieve_tools; not the expected MCPProxy surface")
        else:
            report("PASS", f"{len(names)} built-in tools, no administrator tools")
        if names & MANAGEMENT:
            report(
                "NOTE" if args.allow_management else "FAIL",
                f"also listed: {sorted(names & MANAGEMENT)} (turn them off in the profile unless the agent needs them)",
            )

    # 4. describe_tool, one tool per call (the proxy caps ids per call, and a
    #    single definition stays under the response limit). No upstream call is made.
    def describe(tool):
        """Return 'visible', 'not_found' or 'unknown' for one server:tool id."""
        status, msg = s.post(
            "tools/call", {"name": "describe_tool", "arguments": {"tool_ids": [tool]}}
        )
        if status != 200 or not isinstance(msg, dict) or not isinstance(msg.get("result"), dict):
            return "unknown"
        result = msg["result"]
        if result.get("isError"):
            return "unknown"
        text = "".join(
            c.get("text", "") for c in result.get("content", [])
            if isinstance(c, dict) and c.get("type") == "text"
        )
        try:
            body = json.loads(text)
        except ValueError:
            return "unknown"
        if not isinstance(body, dict):
            return "unknown"
        if any(isinstance(d, dict) and d.get("name") == tool for d in body.get("definitions") or []):
            return "visible"
        if any(
            isinstance(e, dict) and e.get("id") == tool and e.get("error") == "not_found"
            for e in body.get("errors") or []
        ):
            return "not_found"
        return "unknown"

    for tool in args.allowed:
        answer = describe(tool)
        if answer == "visible":
            report("PASS", f"allowed  {tool} is visible")
        elif answer == "not_found":
            report("FAIL", f"allowed  {tool} is NOT visible to this credential")
        else:
            report("FAIL", f"allowed  {tool}: describe_tool gave no usable answer, cannot confirm")
    for tool in args.denied:
        answer = describe(tool)
        if answer == "not_found":
            report("PASS", f"denied   {tool} is not found for this credential")
        elif answer == "visible":
            report("FAIL", f"denied   {tool} IS visible to this credential")
        else:
            report("FAIL", f"denied   {tool}: describe_tool gave no usable answer, cannot confirm")

    # 5. REST config document (never read the body: for an admin key it holds the key)
    req = urllib.request.Request(
        f"{parts.scheme}://{parts.netloc}/api/v1/config", headers={"X-API-Key": token}
    )
    try:
        with OPENER.open(req, timeout=30) as resp:
            code = resp.status
    except urllib.error.HTTPError as err:
        code = err.code
    except (urllib.error.URLError, OSError):
        code = 0
    if code == 403:
        report("PASS", "GET /api/v1/config -> 403")
    elif code == 200:
        report("FAIL", "GET /api/v1/config -> 200: this credential can read the admin config")
    else:
        report("FAIL", f"GET /api/v1/config -> HTTP {code}, expected 403")

    if args.denied:
        print("note  a misspelled tool name also reads 'not found': check that each --denied "
              "name exists with `mcpproxy tools list --server <server>`")
    else:
        print("note  no --denied tool was probed: denial of upstream tools was NOT tested")
    if "FAIL" in results:
        print("RESULT FAILED")
        return 1
    if "WARN" in results:
        print("RESULT NOT VERIFIED (no check failed, but read the WARN lines)")
        return 2
    print("RESULT OK")
    return 0


if __name__ == "__main__":
    sys.exit(main())
