Merges the standalone llm-principal-broker (1,132 LOC) into fastapi-gsap
as an in-process module. The previous architecture had two FastAPI
processes where the broker called GSAP over HTTP on every delegation
creation; now the lifecycle code uses GSAP's own async DB engine
directly and inserts AuthorizationContextDB rows in the same
transaction context.
New module: gsap_broker/delegations/
models.py Pydantic request/response shapes
storage.py DelegationDB SQLModel sharing the GSAP engine
lifecycle.py DelegationManager — in-process AC issuance via
AuthorizationContextDB.insert (no HTTP self-call)
cleanup.py 30s background task for stale delegations
router.py /delegations/* FastAPI router (4 endpoints)
registrars/
base.py AgentRegistrar Protocol + AgentCredentials
stub.py dev-mode no-op
keycloak.py Keycloak Admin REST API
entra.py Microsoft Entra Agent ID via Graph (lazy import)
factory.py driver selection (auto/stub/keycloak/entra)
Wiring:
app.py mounts the delegations router and starts the cleanup task in
the existing lifespan context manager.
settings.py absorbs the keycloak_admin_*, entra_*, and
agent_registrar fields from the old broker's settings.
pyproject.toml adds an optional `entra` extra for the msal dep.
Behaviour preservation:
- Endpoints kept identical: POST /, POST /{id}/revoke, GET /{id}, GET /
- Chronicle event codes preserved: 0x3001 / 0x3003 / 0x3004
- DelegationScope defaults unchanged (max_ttl_minutes=60, max_commands=500)
- Capability ceiling -> capability_mask conversion documented inline
Smoke test: `python -c "from gsap_broker.app import app"` loads cleanly
with 26 routes including the four /delegations/ endpoints.
The standalone llm-principal-broker repo is archived to
~/projects/archive/llm-principal-broker.
Signed-off-by: Tyler King <tking@guildhouse.dev>
150 lines
5 KiB
Python
150 lines
5 KiB
Python
"""Entra Agent ID registrar — registers agent identities via Microsoft Graph.
|
|
|
|
Implements AgentRegistrar for GCAP-SPEC-LLM-PRINCIPAL-BROKER-0001 §4.2.
|
|
|
|
Uses standard Graph application registration with agent metadata tags.
|
|
When Entra Agent ID Blueprint APIs reach GA, this driver should be updated
|
|
to use the dedicated /agentIdentityBlueprints and /agentIdentities endpoints.
|
|
"""
|
|
|
|
import logging
|
|
|
|
import httpx
|
|
import msal
|
|
|
|
from .base import AgentCredentials
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
GRAPH_API = "https://graph.microsoft.com/v1.0"
|
|
|
|
|
|
class EntraRegistrar:
|
|
"""AgentRegistrar implementation using Microsoft Entra + Graph API."""
|
|
|
|
def __init__(
|
|
self,
|
|
tenant_id: str,
|
|
client_id: str,
|
|
client_secret: str,
|
|
agent_blueprint_id: str = "",
|
|
):
|
|
self.tenant_id = tenant_id
|
|
self.client_id = client_id
|
|
self.client_secret = client_secret
|
|
self.agent_blueprint_id = agent_blueprint_id
|
|
self._app = msal.ConfidentialClientApplication(
|
|
client_id=self.client_id,
|
|
client_credential=self.client_secret,
|
|
authority=f"https://login.microsoftonline.com/{self.tenant_id}",
|
|
)
|
|
|
|
async def _get_token(self) -> str:
|
|
result = self._app.acquire_token_for_client(
|
|
scopes=["https://graph.microsoft.com/.default"]
|
|
)
|
|
if "access_token" in result:
|
|
return result["access_token"]
|
|
raise RuntimeError(
|
|
f"Entra token error: {result.get('error_description', result.get('error', 'unknown'))}"
|
|
)
|
|
|
|
async def _headers(self) -> dict:
|
|
token = await self._get_token()
|
|
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
|
|
|
async def register_agent(
|
|
self,
|
|
delegation_id: str,
|
|
agent_type: str,
|
|
delegator_id: str,
|
|
display_name: str,
|
|
expires_at: str,
|
|
metadata: dict | None = None,
|
|
) -> AgentCredentials:
|
|
headers = await self._headers()
|
|
|
|
tags = [
|
|
f"agent_type:{agent_type}",
|
|
f"delegation_id:{delegation_id}",
|
|
f"delegator:{delegator_id}",
|
|
"governed:true",
|
|
"HideApp",
|
|
]
|
|
if self.agent_blueprint_id:
|
|
tags.append(f"blueprint:{self.agent_blueprint_id}")
|
|
|
|
app_body = {
|
|
"displayName": display_name,
|
|
"signInAudience": "AzureADMyOrg",
|
|
"tags": tags,
|
|
"notes": f"Governed AI agent. Delegator: {delegator_id}. Expires: {expires_at}",
|
|
"passwordCredentials": [],
|
|
}
|
|
|
|
async with httpx.AsyncClient(timeout=15.0) as http:
|
|
resp = await http.post(f"{GRAPH_API}/applications", json=app_body, headers=headers)
|
|
if resp.status_code == 401:
|
|
headers = await self._headers()
|
|
resp = await http.post(f"{GRAPH_API}/applications", json=app_body, headers=headers)
|
|
resp.raise_for_status()
|
|
|
|
app_data = resp.json()
|
|
app_id = app_data["appId"]
|
|
object_id = app_data["id"]
|
|
|
|
secret_resp = await http.post(
|
|
f"{GRAPH_API}/applications/{object_id}/addPassword",
|
|
json={
|
|
"passwordCredential": {
|
|
"displayName": f"delegation-{delegation_id}",
|
|
"endDateTime": expires_at,
|
|
}
|
|
},
|
|
headers=headers,
|
|
)
|
|
secret_resp.raise_for_status()
|
|
client_secret = secret_resp.json().get("secretText", "")
|
|
|
|
sp_resp = await http.post(
|
|
f"{GRAPH_API}/servicePrincipals",
|
|
json={"appId": app_id, "displayName": display_name, "tags": tags},
|
|
headers=headers,
|
|
)
|
|
if sp_resp.status_code not in (200, 201, 409):
|
|
sp_resp.raise_for_status()
|
|
|
|
logger.info("Entra: registered agent %s (appId=%s)", display_name, app_id)
|
|
return AgentCredentials(
|
|
client_id=app_id,
|
|
client_secret=client_secret,
|
|
agent_display_name=display_name,
|
|
idp_backend="entra",
|
|
)
|
|
|
|
async def delete_agent(self, client_id: str) -> bool:
|
|
headers = await self._headers()
|
|
|
|
async with httpx.AsyncClient(timeout=10.0) as http:
|
|
resp = await http.get(
|
|
f"{GRAPH_API}/applications",
|
|
params={"$filter": f"appId eq '{client_id}'"},
|
|
headers=headers,
|
|
)
|
|
resp.raise_for_status()
|
|
apps = resp.json().get("value", [])
|
|
if not apps:
|
|
return False
|
|
|
|
object_id = apps[0]["id"]
|
|
del_resp = await http.delete(
|
|
f"{GRAPH_API}/applications/{object_id}",
|
|
headers=headers,
|
|
)
|
|
deleted = del_resp.status_code in (200, 204)
|
|
if deleted:
|
|
logger.info("Entra: deleted agent app %s", client_id)
|
|
return deleted
|
|
|
|
async def get_agent_token(self, client_id: str) -> str | None:
|
|
return None
|