from __future__ import annotations import logging from dataclasses import dataclass, field import httpx import jwt logger = logging.getLogger(__name__) GRAPH_BASE_URL = "https://graph.microsoft.com/v1.0" GRAPH_TOKEN_URL = "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token" GRAPH_DEFAULT_SCOPE = "https://graph.microsoft.com/.default" @dataclass class ProbeGraphResult: ok: bool error: str | None = None roles: list[str] = field(default_factory=list) scopes: list[str] = field(default_factory=list) @dataclass class ProbeMSTeamsResult: ok: bool error: str | None = None app_id: str | None = None bot_token_ok: bool = False graph: ProbeGraphResult | None = None async def probe_bot_token(app_id: str, app_password: str) -> bool: token_url = "https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token" try: async with httpx.AsyncClient(timeout=15.0) as client: resp = await client.post( token_url, data={ "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_password, "scope": "https://api.botframework.com/.default", }, ) resp.raise_for_status() return "access_token" in resp.json() except Exception as e: logger.debug("Bot token probe failed: %s", e) return False async def probe_graph_token(tenant_id: str, app_id: str, app_password: str) -> ProbeGraphResult: token_url = GRAPH_TOKEN_URL.format(tenant_id=tenant_id) try: async with httpx.AsyncClient(timeout=15.0) as client: resp = await client.post( token_url, data={ "grant_type": "client_credentials", "client_id": app_id, "client_secret": app_password, "scope": GRAPH_DEFAULT_SCOPE, }, ) resp.raise_for_status() data = resp.json() access_token = data.get("access_token", "") if not access_token: return ProbeGraphResult(ok=False, error="No access_token in response") try: unverified = jwt.decode(access_token, options={"verify_signature": False}) roles = unverified.get("roles", []) or [] scopes_str = unverified.get("scp", "") or "" scopes = scopes_str.split(" ") if scopes_str else [] return ProbeGraphResult(ok=True, roles=list(roles), scopes=list(scopes)) except Exception as e: return ProbeGraphResult(ok=True, error=f"Token decode warning: {e}") except Exception as e: return ProbeGraphResult(ok=False, error=str(e)) async def probe_msteams(app_id: str, app_password: str, tenant_id: str) -> ProbeMSTeamsResult: bot_ok = await probe_bot_token(app_id, app_password) if not bot_ok: return ProbeMSTeamsResult( ok=False, error="Bot token probe failed", app_id=app_id, bot_token_ok=False, ) graph = None if tenant_id: graph = await probe_graph_token(tenant_id, app_id, app_password) if not graph.ok: logger.warning("Graph API probe failed: %s", graph.error) all_ok = bot_ok and (graph is None or graph.ok) return ProbeMSTeamsResult( ok=all_ok, app_id=app_id, bot_token_ok=bot_ok, graph=graph, )