Files
ds-chat/backend/app/services/bot_service.py
T
ksmithandClaude Sonnet 5 0ab23c44a7 Phase 7: Bot/extension system
Bot accounts (User rows with is_bot=True), scoped API tokens (read:messages,
write:messages, manage:rooms) authenticated via Authorization: Bearer on both
REST and the WS handshake, live bot WebSocket access on the same /ws/chat
endpoint humans use, message editing (WS "edit" envelope -> message_update
broadcast, fans out cross-instance for free via the existing broadcaster),
incoming webhooks (room-scoped, no auth beyond the URL token), and outgoing
webhooks/event subscriptions (HMAC-SHA256 signed, backgrounded delivery,
creation-time SSRF validation against private/loopback/link-local targets).

Token auth is additive, not a parallel system: a bearer-token-authenticated
bot goes through the exact same room-membership/role checks a session-
authenticated human does everywhere; only read:messages/write:messages are
separately scope-gated (the two message endpoints). manage:rooms scope
enforcement, full per-delivery SSRF re-validation, and bot API rate limiting
were explicitly scoped out (confirmed with the repo owner) as disproportionate
to this phase -- documented as known gaps in backend/README.md rather than
silently skipped.

Admin portal gains a Bots tab (create bots, issue/revoke scoped tokens,
cross-room webhook visibility); RoomInfoPanel gains room-scoped webhook/
subscription management, mirroring how invites already work there. The chat
UI also gets a minimal "edit your own message" affordance -- not asked for
by the issue, but the only practical way to exercise the edit pipeline by
hand instead of only via a scripted bot client.

Along the way: fixed a real bug caught while writing the incoming-webhook
test -- offline-push notification relied on the sender being "connected" to
exclude themselves, true for WS-originated messages but not for the new
webhook path, which has no WS connection for the attributed sender at all.
Now explicitly excluded. Also discovered the REST-only test fixture never
triggered ASGI lifespan, so app.state.broadcaster/presence didn't exist for
it; moved their construction out of the lifespan into create_app() itself
(Redis client construction is synchronous/lazy) so both the WS and
REST-only paths always have them.

New tests/test_bots.py, test_message_edit.py, test_webhooks.py (full suite
now 78/78, stable across repeated runs) plus a scripted end-to-end smoke
test (bot WS join/post/edit, incoming webhook, SSRF rejection, outgoing
delivery) and a full browser walkthrough of the new admin/room UI.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 08:12:41 -06:00

120 lines
3.6 KiB
Python

import uuid
from datetime import datetime, timezone
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.models import ApiToken, User
from app.security import generate_token, hash_password, hash_token
from app.services.audit import record_audit_log
VALID_SCOPES = {"read:messages", "write:messages", "manage:rooms"}
class DuplicateBotError(Exception):
pass
class BotNotFoundError(Exception):
pass
class InvalidScopeError(Exception):
pass
class TokenNotFoundError(Exception):
pass
async def create_bot(db: AsyncSession, actor: User, username: str) -> User:
# Bots never authenticate with a password -- generate one and discard
# it. email is NOT NULL/unique today; a placeholder avoids widening the
# schema just for accounts that will never receive real mail.
# bots.example.com (not e.g. bots.local/.invalid) deliberately, since
# pydantic's EmailStr rejects addresses whose *top-level* domain is one
# of the IANA special-use TLDs (.local, .invalid, .test, ...) -- a
# subdomain of the real (if reserved-for-docs) .com TLD isn't affected.
bot = User(
username=username,
email=f"{username}@bots.example.com",
password_hash=hash_password(generate_token()),
is_bot=True,
)
db.add(bot)
try:
await db.flush()
except IntegrityError as exc:
await db.rollback()
raise DuplicateBotError() from exc
record_audit_log(db, actor, "bot.create", "user", bot.id)
await db.commit()
await db.refresh(bot)
return bot
async def list_bots(db: AsyncSession) -> list[User]:
result = await db.execute(
select(User).where(User.is_bot.is_(True)).order_by(User.created_at)
)
return list(result.scalars().all())
async def _get_bot(db: AsyncSession, bot_id: uuid.UUID) -> User:
bot = await db.get(User, bot_id)
if bot is None or not bot.is_bot:
raise BotNotFoundError()
return bot
async def create_api_token(
db: AsyncSession, actor: User, bot_id: uuid.UUID, scopes: list[str]
) -> tuple[ApiToken, str]:
bot = await _get_bot(db, bot_id)
if not set(scopes) <= VALID_SCOPES:
raise InvalidScopeError()
plaintext = generate_token()
token = ApiToken(owner_id=bot.id, token_hash=hash_token(plaintext), scopes=scopes)
db.add(token)
record_audit_log(
db, actor, "bot.issue_token", "user", bot.id, {"scopes": scopes}
)
await db.commit()
await db.refresh(token)
return token, plaintext
async def list_api_tokens(db: AsyncSession, bot_id: uuid.UUID) -> list[ApiToken]:
result = await db.execute(
select(ApiToken).where(ApiToken.owner_id == bot_id).order_by(ApiToken.created_at)
)
return list(result.scalars().all())
async def revoke_api_token(db: AsyncSession, actor: User, token_id: uuid.UUID) -> None:
token = await db.get(ApiToken, token_id)
if token is None:
raise TokenNotFoundError()
await db.delete(token)
record_audit_log(db, actor, "bot.revoke_token", "user", token.owner_id)
await db.commit()
async def resolve_token(db: AsyncSession, plaintext: str) -> tuple[User, ApiToken] | None:
result = await db.execute(
select(ApiToken)
.where(ApiToken.token_hash == hash_token(plaintext))
.options(selectinload(ApiToken.owner))
)
token = result.scalar_one_or_none()
if token is None or not token.owner.is_active:
return None
token.last_used_at = datetime.now(timezone.utc)
await db.commit()
return token.owner, token