#!/usr/bin/env python3
"""Delegated vs application permissions for an MCP server identity in Microsoft Entra: lab setup and the MCP server.

Every test in the lab is an az or curl command shown in the article. This file does only the two jobs that need code:

  python3 entra_lab.py setup          # three apps, one user, one group, a broad admin consent; writes $LAB_SECRETS/lab.env
  python3 entra_lab.py serve naive    # MCP-shaped server on 127.0.0.1:9300 that runs every tool with its own Graph app token
  python3 entra_lab.py serve fixed    # the same server with a scope or app-role check per tool and OBO for user calls

Needs Python 3.10+, `pip install "pyjwt[crypto]"`, openssl and the Azure CLI signed in to a THROWAWAY tenant
where you are Global Administrator. Set TENANT_ID and LAB_SECRETS (default ~/.lab-mcp-perm).
Secrets (the server's client secret, the test user's password, the agent's private key) stay in 0600 files in
$LAB_SECRETS and are never printed. lab.env holds only IDs.
"""
import base64, json, os, secrets, subprocess, sys, time, urllib.error, urllib.parse, urllib.request, uuid
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

import jwt  # PyJWT, crypto extra

TENANT = os.environ.get("TENANT_ID", "")
LAB = Path(os.environ.get("LAB_SECRETS", "~/.lab-mcp-perm")).expanduser()
STATE = LAB / "state.json"
GRAPH = "https://graph.microsoft.com/v1.0"
GRAPH_APP = "00000003-0000-0000-c000-000000000000"
AUTH = f"https://login.microsoftonline.com/{TENANT}"
PORT = 9300


# ---------- helpers ----------
def az_rest(method, path, body=None):
    cmd = ["az", "rest", "--method", method, "--uri", GRAPH + path, "-o", "json"]
    if body is not None:
        cmd += ["--body", json.dumps(body), "--headers", "Content-Type=application/json"]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode:
        raise SystemExit(f"Graph {method} {path} failed: {r.stderr.strip()[-300:]}")
    return json.loads(r.stdout) if r.stdout.strip() else {}


def need_tenant():
    if not TENANT:
        raise SystemExit("set TENANT_ID first")
    cur = subprocess.run(["az", "account", "show", "--query", "tenantId", "-o", "tsv"], capture_output=True, text=True).stdout.strip()
    if cur != TENANT:
        raise SystemExit("az is signed in to a different tenant; run: az login --tenant $TENANT_ID --allow-no-subscriptions")


def load():
    return json.loads(STATE.read_text())


def write_secret(name, value):
    fd = os.open(LAB / name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        f.write(value)  # no trailing newline: curl reads it with --data-urlencode name@file


def save(s):
    LAB.mkdir(parents=True, exist_ok=True)
    STATE.write_text(json.dumps(s, indent=1))
    STATE.chmod(0o600)


def post_form(url, data):
    try:
        r = urllib.request.urlopen(urllib.request.Request(url, urllib.parse.urlencode(data).encode()))
        return r.status, json.loads(r.read())
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read())


def err(j):
    d = j.get("error_description", "")
    return f"{j.get('error')}: {d.split(':')[0]}"


def server_graph_app_token(s):
    return post_form(f"{AUTH}/oauth2/v2.0/token", {"grant_type": "client_credentials", "client_id": s["server_app"],
                     "client_secret": s["server_secret"], "scope": "https://graph.microsoft.com/.default"})


def obo(s, user_access_token, scope):
    return post_form(f"{AUTH}/oauth2/v2.0/token", {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "client_id": s["server_app"],
                     "client_secret": s["server_secret"], "assertion": user_access_token, "requested_token_use": "on_behalf_of", "scope": scope})


def graph_call(token, method, path, body=None):
    req = urllib.request.Request(GRAPH + path, method=method, data=json.dumps(body).encode() if body is not None else None,
                                 headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"})
    try:
        r = urllib.request.urlopen(req)
        return r.status, (json.loads(r.read() or b"{}"))
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read())
        except Exception:
            return e.code, {}


def gerr(j):
    return (j.get("error") or {}).get("code", "") if isinstance(j, dict) else ""


def graph_ids(names_roles, names_scopes):
    sp = az_rest("GET", f"/servicePrincipals?$filter=appId eq '{GRAPH_APP}'&$select=id,appRoles,oauth2PermissionScopes")["value"][0]
    roles = {r["value"]: r["id"] for r in sp["appRoles"] if r["value"] in names_roles}
    scopes = {x["value"]: x["id"] for x in sp["oauth2PermissionScopes"] if x["value"] in names_scopes}
    return sp["id"], roles, scopes


# ---------- steps ----------
def setup():
    need_tenant()
    if STATE.exists():
        raise SystemExit("state already exists; run the cleanup commands first")
    LAB.mkdir(parents=True, exist_ok=True)
    LAB.chmod(0o700)
    s = {"made_apps": [], "made_users": [], "made_groups": []}
    domain = [d["id"] for d in az_rest("GET", "/domains?$select=id,isDefault")["value"] if d["isDefault"]][0]
    graph_sp, g_roles, g_scopes = graph_ids({"User.Read.All", "Group.ReadWrite.All", "Application.Read.All", "Group.Read.All"},
                                            {"User.Read", "Group.ReadWrite.All", "Group.Read.All"})
    s.update(graph_sp=graph_sp, g_roles=g_roles, g_scopes=g_scopes)
    # MCP server: three delegated scopes, two app roles
    sc = [{"id": str(uuid.uuid4()), "value": v, "type": "User", "isEnabled": True, "adminConsentDisplayName": v,
           "adminConsentDescription": f"Lab scope {v}", "userConsentDisplayName": v, "userConsentDescription": f"Lab scope {v}"}
          for v in ("Mcp.Tools.Read", "Mcp.Tools.Write", "Mcp.Admin")]
    ar = [{"id": str(uuid.uuid4()), "value": v, "displayName": v, "description": f"Lab role {v}", "isEnabled": True,
           "allowedMemberTypes": ["Application"]} for v in ("Mcp.Tools.Read.All", "Mcp.Tools.Write.All")]
    srv = az_rest("POST", "/applications", {"displayName": "lab-mcp-perm-server", "signInAudience": "AzureADMyOrg"})
    s["made_apps"].append(srv["id"])
    az_rest("PATCH", f"/applications/{srv['id']}", {"identifierUris": [f"api://{srv['appId']}"], "appRoles": ar,
            "api": {"oauth2PermissionScopes": sc, "requestedAccessTokenVersion": 2},
            "requiredResourceAccess": [{"resourceAppId": GRAPH_APP, "resourceAccess": [
                {"id": g_roles["User.Read.All"], "type": "Role"}, {"id": g_roles["Group.ReadWrite.All"], "type": "Role"},
                {"id": g_roles["Application.Read.All"], "type": "Role"},
                {"id": g_scopes["User.Read"], "type": "Scope"}, {"id": g_scopes["Group.ReadWrite.All"], "type": "Scope"}]}]})
    pw = az_rest("POST", f"/applications/{srv['id']}/addPassword", {"passwordCredential": {"displayName": "lab", "endDateTime": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + 7 * 86400))}})
    s.update(server_app=srv["appId"], server_obj=srv["id"], server_secret=pw["secretText"])
    s["scope_ids"] = {x["value"]: x["id"] for x in sc}
    s["role_ids"] = {x["value"]: x["id"] for x in ar}
    # public client (the user's tool) and the autonomous agent with a certificate
    cli = az_rest("POST", "/applications", {"displayName": "lab-mcp-perm-client", "signInAudience": "AzureADMyOrg", "isFallbackPublicClient": True,
                  "requiredResourceAccess": [{"resourceAppId": srv["appId"], "resourceAccess": [
                      {"id": s["scope_ids"]["Mcp.Tools.Read"], "type": "Scope"}, {"id": s["scope_ids"]["Mcp.Tools.Write"], "type": "Scope"}]}]})
    s["made_apps"].append(cli["id"]); s.update(client_app=cli["appId"], client_obj=cli["id"])
    key, crt = LAB / "agent.key", LAB / "agent.crt"
    subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(key), "-out", str(crt), "-days", "7", "-subj", "/CN=lab-mcp-perm-agent"], check=True, capture_output=True)
    key.chmod(0o600)
    der = subprocess.run(["openssl", "x509", "-in", str(crt), "-outform", "DER"], check=True, capture_output=True).stdout
    sha1 = subprocess.run(["openssl", "x509", "-in", str(crt), "-noout", "-fingerprint", "-sha1"], check=True, capture_output=True, text=True).stdout
    s["thumbprint"] = sha1.split("=")[1].strip().replace(":", "")
    agt = az_rest("POST", "/applications", {"displayName": "lab-mcp-perm-agent", "signInAudience": "AzureADMyOrg",
                  "keyCredentials": [{"type": "AsymmetricX509Cert", "usage": "Verify", "key": base64.b64encode(der).decode(), "displayName": "lab"}],
                  "requiredResourceAccess": [{"resourceAppId": srv["appId"], "resourceAccess": [
                      {"id": s["role_ids"]["Mcp.Tools.Read.All"], "type": "Role"}, {"id": s["role_ids"]["Mcp.Tools.Write.All"], "type": "Role"}]}]})
    s["made_apps"].append(agt["id"]); s.update(agent_app=agt["appId"], agent_obj=agt["id"])
    for a in ("server", "client", "agent"):
        s[f"{a}_sp"] = az_rest("POST", "/servicePrincipals", {"appId": s[f"{a}_app"]})["id"]
    # user and group: the user does not own the group
    s["password"] = secrets.token_urlsafe(18) + "aA1!"
    s["upn"] = f"lab-mcp-perm@{domain}"
    u = az_rest("POST", "/users", {"accountEnabled": True, "displayName": "lab-mcp-perm user", "mailNickname": "lab-mcp-perm", "userPrincipalName": s["upn"],
                "passwordProfile": {"password": s["password"], "forceChangePasswordNextSignIn": False}})
    s["made_users"].append(u["id"])
    g = az_rest("POST", "/groups", {"displayName": "lab-mcp-perm-group", "mailNickname": "lab-mcp-perm-group", "mailEnabled": False, "securityEnabled": True, "description": "lab group"})
    s["made_groups"].append(g["id"]); s["group"] = g["id"]
    # the admin consent a team would click through
    az_rest("POST", "/oauth2PermissionGrants", {"clientId": s["client_sp"], "consentType": "AllPrincipals", "resourceId": s["server_sp"], "scope": "Mcp.Tools.Read Mcp.Tools.Write"})
    s["agent_assign"] = {}
    for v in ("Mcp.Tools.Read.All", "Mcp.Tools.Write.All"):
        a = az_rest("POST", f"/servicePrincipals/{s['agent_sp']}/appRoleAssignments", {"principalId": s["agent_sp"], "resourceId": s["server_sp"], "appRoleId": s["role_ids"][v]})
        s["agent_assign"][v] = a["id"]
    s["server_assign"] = {}
    for v in ("User.Read.All", "Group.ReadWrite.All", "Application.Read.All"):
        a = az_rest("POST", f"/servicePrincipals/{s['server_sp']}/appRoleAssignments", {"principalId": s["server_sp"], "resourceId": graph_sp, "appRoleId": g_roles[v]})
        s["server_assign"][v] = a["id"]
    s["server_graph_delegated"] = az_rest("POST", "/oauth2PermissionGrants", {"clientId": s["server_sp"], "consentType": "AllPrincipals", "resourceId": graph_sp, "scope": "User.Read Group.ReadWrite.All"})["id"]
    s["client_grant"] = az_rest("GET", f"/oauth2PermissionGrants?$filter=clientId eq '{s['client_sp']}' and resourceId eq '{s['server_sp']}'")["value"][0]["id"]
    save(s)
    write_secret("server.secret", s["server_secret"])
    write_secret("user.password", s["password"])
    env = {"GRAPH_APP_ID": GRAPH_APP, "SERVER_APP": s["server_app"], "CLIENT_APP": s["client_app"], "AGENT_APP": s["agent_app"],
           "SERVER_OBJ": s["server_obj"], "CLIENT_OBJ": s["client_obj"], "AGENT_OBJ": s["agent_obj"],
           "SERVER_SP": s["server_sp"], "CLIENT_SP": s["client_sp"], "AGENT_SP": s["agent_sp"], "GRAPH_SP": graph_sp,
           "LAB_UPN": s["upn"], "USER_ID": s["made_users"][0], "GROUP_ID": s["group"],
           "CLIENT_GRANT": s["client_grant"], "SERVER_GRAPH_GRANT": s["server_graph_delegated"],
           "AGENT_WRITE_ASSIGN": s["agent_assign"]["Mcp.Tools.Write.All"],
           "SERVER_APPREAD_ASSIGN": s["server_assign"]["Application.Read.All"],
           "SERVER_GROUPRW_ASSIGN": s["server_assign"]["Group.ReadWrite.All"],
           "MCP_READ_SCOPE": s["scope_ids"]["Mcp.Tools.Read"], "MCP_READ_ROLE": s["role_ids"]["Mcp.Tools.Read.All"],
           "GRAPH_USER_READ_ALL_ROLE": g_roles["User.Read.All"], "GRAPH_GROUP_READ_ALL_ROLE": g_roles["Group.Read.All"],
           "GRAPH_USER_READ_SCOPE": g_scopes["User.Read"], "GRAPH_GROUP_READ_ALL_SCOPE": g_scopes["Group.Read.All"]}
    (LAB / "lab.env").write_text("".join(f"export {k}={v}\n" for k, v in env.items()))
    print("created: lab-mcp-perm-server, lab-mcp-perm-client, lab-mcp-perm-agent, lab-mcp-perm user, lab-mcp-perm-group")
    print("server Graph app roles granted: User.Read.All, Group.ReadWrite.All, Application.Read.All")
    print("client delegated grant on the server: Mcp.Tools.Read Mcp.Tools.Write (Mcp.Admin not consented)")
    print("agent app roles on the server: Mcp.Tools.Read.All, Mcp.Tools.Write.All")
    print(f"IDs written to {LAB / 'lab.env'}; run: source \"$LAB_SECRETS/lab.env\"")


# ---------- the MCP-shaped server ----------
class Handler(BaseHTTPRequestHandler):
    S = {}; MODE = "naive"

    def log_message(self, *a):
        pass

    def _send(self, code, obj):
        b = json.dumps(obj).encode(); self.send_response(code); self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)

    def do_POST(self):
        s = self.S; body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
        tok = (self.headers.get("Authorization") or "").removeprefix("Bearer ").strip()
        try:
            key = jwt.PyJWKClient(f"https://login.microsoftonline.com/{TENANT}/discovery/v2.0/keys").get_signing_key_from_jwt(tok).key
            c = jwt.decode(tok, key, algorithms=["RS256"], audience=s["server_app"], issuer=f"{AUTH}/v2.0")
        except Exception as e:
            return self._send(401, {"error": f"invalid token: {type(e).__name__}"})
        tool = body["params"]["name"]; user_call = "scp" in c
        need = {"get_profile": ("Mcp.Tools.Read", "Mcp.Tools.Read.All"), "list_groups": ("Mcp.Tools.Read", "Mcp.Tools.Read.All"),
                "update_group_description": ("Mcp.Tools.Write", "Mcp.Tools.Write.All")}[tool]
        if self.MODE == "fixed":
            have = c.get("scp", "").split() if user_call else c.get("roles", [])
            if need[0 if user_call else 1] not in have:
                return self._send(403, {"error": f"{tool} needs {need[0 if user_call else 1]}; the token has {' '.join(have) or 'nothing'}"})
            if user_call:
                st, j = obo(s, tok, "https://graph.microsoft.com/.default")
            else:
                st, j = server_graph_app_token(s)
        else:
            st, j = server_graph_app_token(s)  # naive: every tool runs as the server
        if st != 200:
            return self._send(502, {"error": err(j)})
        gtok = j["access_token"]
        path, method, payload = {"get_profile": ("/me", "GET", None), "list_groups": ("/groups?$top=3&$select=displayName", "GET", None),
                                 "update_group_description": (f"/groups/{s['group']}", "PATCH", {"description": f"set by the {self.MODE} server"})}[tool]
        code, resp = graph_call(gtok, method, path, payload)
        self._send(200 if code < 300 else 403 if code == 403 else 400, {"graph_status": code, "graph_error": gerr(resp), "token_type": "user" if user_call else "app"})


def serve(mode):
    if mode not in ("naive", "fixed"):
        raise SystemExit("usage: python3 entra_lab.py serve naive|fixed")
    Handler.S = load(); Handler.MODE = mode
    print(f"{mode} MCP server on http://127.0.0.1:{PORT}/mcp; Ctrl+C or kill to stop", flush=True)
    HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()


if __name__ == "__main__":
    if sys.argv[1:] == ["setup"]:
        setup()
    elif len(sys.argv) == 3 and sys.argv[1] == "serve":
        serve(sys.argv[2])
    else:
        raise SystemExit(__doc__)
