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>
136 lines
4.4 KiB
Python
136 lines
4.4 KiB
Python
"""Delegation persistence — shares the GSAP async engine.
|
|
|
|
The DelegationDB SQLModel is registered against the same SQLModel.metadata
|
|
as the rest of GSAP, so init_db() in gsap_broker.db creates this table
|
|
alongside the AuthorizationContextDB and friends.
|
|
"""
|
|
|
|
from datetime import datetime
|
|
from typing import Optional
|
|
|
|
from sqlmodel import SQLModel, Field, select
|
|
from sqlmodel.ext.asyncio.session import AsyncSession
|
|
|
|
from gsap_broker.db import engine
|
|
|
|
|
|
class DelegationDB(SQLModel, table=True):
|
|
__tablename__ = "delegations"
|
|
|
|
delegation_id: str = Field(primary_key=True)
|
|
status: str = Field(default="active", index=True)
|
|
agent_type: str
|
|
agent_model: Optional[str] = None
|
|
agent_did: str
|
|
agent_keycloak_client_id: Optional[str] = None
|
|
delegator_did: str
|
|
delegator_ac_id: str
|
|
delegated_ac_id: Optional[str] = None
|
|
capability_ceiling: str = "CAP_MUTATE"
|
|
ceremony_required_for: str = ""
|
|
max_commands: int = 500
|
|
commands_executed: int = 0
|
|
created_at: datetime = Field(default_factory=lambda: datetime.utcnow())
|
|
expires_at: datetime = Field(default_factory=lambda: datetime.utcnow())
|
|
revoked_at: Optional[datetime] = None
|
|
revoke_reason: Optional[str] = None
|
|
chronicle_cid: Optional[str] = None
|
|
|
|
|
|
async def create_delegation(delegation: DelegationDB) -> None:
|
|
async with AsyncSession(engine) as session:
|
|
session.add(delegation)
|
|
await session.commit()
|
|
|
|
|
|
async def get_delegation(delegation_id: str) -> Optional[DelegationDB]:
|
|
async with AsyncSession(engine) as session:
|
|
result = await session.exec(
|
|
select(DelegationDB).where(DelegationDB.delegation_id == delegation_id)
|
|
)
|
|
return result.first()
|
|
|
|
|
|
async def revoke_delegation(delegation_id: str, reason: str) -> bool:
|
|
async with AsyncSession(engine) as session:
|
|
result = await session.exec(
|
|
select(DelegationDB).where(
|
|
DelegationDB.delegation_id == delegation_id,
|
|
DelegationDB.status == "active",
|
|
)
|
|
)
|
|
d = result.first()
|
|
if not d:
|
|
return False
|
|
d.status = "revoked"
|
|
d.revoked_at = datetime.utcnow()
|
|
d.revoke_reason = reason
|
|
session.add(d)
|
|
await session.commit()
|
|
return True
|
|
|
|
|
|
async def get_active_delegations() -> list[DelegationDB]:
|
|
async with AsyncSession(engine) as session:
|
|
result = await session.exec(
|
|
select(DelegationDB).where(DelegationDB.status == "active")
|
|
)
|
|
return list(result.all())
|
|
|
|
|
|
async def increment_commands(delegation_id: str) -> int:
|
|
async with AsyncSession(engine) as session:
|
|
result = await session.exec(
|
|
select(DelegationDB).where(DelegationDB.delegation_id == delegation_id)
|
|
)
|
|
d = result.first()
|
|
if not d:
|
|
return 0
|
|
d.commands_executed += 1
|
|
session.add(d)
|
|
await session.commit()
|
|
return d.commands_executed
|
|
|
|
|
|
async def expire_stale() -> list[DelegationDB]:
|
|
"""Find and expire delegations past TTL or command limit."""
|
|
now = datetime.utcnow()
|
|
async with AsyncSession(engine) as session:
|
|
result = await session.exec(
|
|
select(DelegationDB).where(DelegationDB.status == "active")
|
|
)
|
|
expired = []
|
|
for d in result.all():
|
|
if now > d.expires_at or d.commands_executed >= d.max_commands:
|
|
d.status = "expired"
|
|
d.revoke_reason = (
|
|
"command_limit"
|
|
if d.commands_executed >= d.max_commands
|
|
else "ttl_elapsed"
|
|
)
|
|
d.revoked_at = now
|
|
session.add(d)
|
|
expired.append(d)
|
|
await session.commit()
|
|
return expired
|
|
|
|
|
|
async def revoke_by_delegator_ac(delegator_ac_id: str) -> int:
|
|
"""Cascading revocation — all delegations from a specific AC."""
|
|
now = datetime.utcnow()
|
|
async with AsyncSession(engine) as session:
|
|
result = await session.exec(
|
|
select(DelegationDB).where(
|
|
DelegationDB.status == "active",
|
|
DelegationDB.delegator_ac_id == delegator_ac_id,
|
|
)
|
|
)
|
|
count = 0
|
|
for d in result.all():
|
|
d.status = "revoked"
|
|
d.revoked_at = now
|
|
d.revoke_reason = "delegator_ac_revoked"
|
|
session.add(d)
|
|
count += 1
|
|
await session.commit()
|
|
return count
|