Files
ds-chat/backend/app/dependencies.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

75 lines
2.7 KiB
Python

import uuid
from fastapi import Depends, HTTPException, Request
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models import RoomMembership, RoomRole, User
from app.services.bot_service import resolve_token
_ROLE_RANK = {RoomRole.member: 0, RoomRole.admin: 1, RoomRole.owner: 2}
async def get_current_user(
request: Request, db: AsyncSession = Depends(get_db)
) -> User:
# Bearer token (bots) takes priority over the session cookie (humans) --
# a request either carries one or the other, never meaningfully both.
# Downstream, a token-authenticated bot is subject to the exact same
# room-membership/role checks as a session-authenticated human; the
# token additionally narrows what it can do via require_scope below.
auth_header = request.headers.get("authorization")
if auth_header and auth_header.lower().startswith("bearer "):
resolved = await resolve_token(db, auth_header[len("bearer ") :].strip())
if resolved is None:
raise HTTPException(status_code=401, detail="Invalid or revoked API token")
user, token = resolved
request.state.api_token = token
return user
user_id = request.session.get("user_id")
if not user_id:
raise HTTPException(status_code=401, detail="Not authenticated")
user = await db.get(User, uuid.UUID(user_id))
if user is None or not user.is_active:
request.session.clear()
raise HTTPException(status_code=401, detail="Not authenticated")
return user
def require_scope(request: Request, scope: str) -> None:
token = getattr(request.state, "api_token", None)
if token is not None and scope not in token.scopes:
raise HTTPException(status_code=403, detail=f"Token missing required scope: {scope}")
async def require_room_member(
room_id: uuid.UUID, user: User, db: AsyncSession
) -> RoomMembership:
result = await db.execute(
select(RoomMembership).where(
RoomMembership.room_id == room_id, RoomMembership.user_id == user.id
)
)
membership = result.scalar_one_or_none()
if membership is None:
raise HTTPException(status_code=403, detail="Not a member of this room")
return membership
async def require_room_role(
room_id: uuid.UUID, user: User, db: AsyncSession, minimum: RoomRole
) -> RoomMembership:
membership = await require_room_member(room_id, user, db)
if _ROLE_RANK[membership.role] < _ROLE_RANK[minimum]:
raise HTTPException(status_code=403, detail="Insufficient room role")
return membership
def require_site_admin(user: User) -> None:
if not user.is_site_admin:
raise HTTPException(status_code=403, detail="Site admin required")