"""Bearer authentication storing only SHA-256 token digests.""" import hashlib, hmac from sqlalchemy import select from .models import Agent, Tenant def token_hash(token): return hashlib.sha256(token.encode()).hexdigest() def bootstrap(session, token): digest = token_hash(token); agent = session.scalar(select(Agent).where(Agent.token_hash == digest)) if agent: return agent tenant = session.scalar(select(Tenant).where(Tenant.name == "development")) or Tenant(name="development") session.add(tenant); session.flush(); agent = Agent(tenant_id=tenant.id, name="development-agent", token_hash=digest); session.add(agent); session.commit(); return agent def authenticate(session, token): digest = token_hash(token) for agent in session.scalars(select(Agent)).all(): if hmac.compare_digest(agent.token_hash, digest): return agent if agent.enabled else None # a disabled (revoked) Agent must not authenticate return None