Discord: check bot permissions before handing a token to a node (server-26#225 S3)
start_stream now asks Discord (cached REST snapshots, S2) whether each bot
it could pick may View, Connect and Speak in the voice channel, before the
lease. Covers all four entry points: bot POST /discord/streams, web picker,
nodes discord_join, and the reconciler's re-place.
- pick_token: denied bots skipped; confirmed-ok sorts before unknown;
unknown is allowed (fail open); all denied -> missing_permissions naming
each bot, missing permission, trace reason and fix. The reuse branch
falls through when its token is denied.
- Bounded: discord_perm_check_concurrency at once, within
discord_perm_check_budget_seconds; unanswered = unknown.
- Non-voice channel -> 400 bad_channel (not missing_permissions).
- systems/{id}.preferred_token_id is now read (plan finding 1), as a hint.
- Pool bots at discord_pool_bot_guild_cap are never offered as invites;
pool_full when nothing else is left (owner Q3).
- handle_actual drops cached access on missing_permissions, channel_full,
not_in_guild, bad_channel.
- New GET /discord/nodes/{node_id}/guilds/{guild_id}/voice-check (org
member, names only) and GET /discord/guilds/{guild_id}/voice-check
(service key or admin).
- PUT /tokens/{id}/prefer/{system_id}: org owners for their own systems
and own BYO bots; shared systems and pool bots stay admin-only (owner Q2).
Keeps both pointers single-valued; audited.
- Kill switch: DISCORD_PERM_CHECK_ENABLED=false.
- tests/conftest.py: autouse fixture so no test ever reaches discord.com.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a75149b2eb
commit
2c2cf9d9be
@@ -5,7 +5,14 @@ from typing import Optional
|
||||
from app.internal import firestore as fstore
|
||||
from app.internal import discord_leases as leases
|
||||
from app.internal import discord_rest
|
||||
from app.internal.auth import require_admin_token
|
||||
from app.internal.audit import write_audit
|
||||
from app.internal.auth import (
|
||||
describe_actor,
|
||||
get_org_role,
|
||||
get_role,
|
||||
require_admin_token,
|
||||
require_firebase_token,
|
||||
)
|
||||
from app.internal.logger import logger
|
||||
|
||||
router = APIRouter(prefix="/tokens", tags=["tokens"])
|
||||
@@ -94,35 +101,99 @@ async def flush_tokens(_: dict = Depends(require_admin_token)):
|
||||
return {"released": released}
|
||||
|
||||
|
||||
def _may_edit_system(decoded: dict, system: Optional[dict]) -> bool:
|
||||
"""Platform admin: any system. Org owner: only their own org's systems —
|
||||
a shared system (no org_id) serves every org, so a preference there is
|
||||
platform-admin only (owner decision Q2, 2026-10-05)."""
|
||||
if get_role(decoded) == "admin":
|
||||
return True
|
||||
return bool(system and system.get("org_id") and system.get("org_id") == decoded.get("org_id"))
|
||||
|
||||
|
||||
def _check_prefer_access(decoded: dict, token: Optional[dict], system: Optional[dict],
|
||||
system_id: Optional[str]) -> None:
|
||||
"""Raise unless the caller may point ``system`` at ``token``. Another
|
||||
org's bot or system is a 404, never a 403 (no existence leak)."""
|
||||
if get_role(decoded) == "admin":
|
||||
if not token:
|
||||
raise HTTPException(404, "Token not found.")
|
||||
if system_id is not None and not system:
|
||||
raise HTTPException(404, "System not found.")
|
||||
return
|
||||
org_id = decoded.get("org_id")
|
||||
if not org_id or get_org_role(decoded) != "owner":
|
||||
raise HTTPException(403, "Only the organization owner or a platform admin can choose a system's radio bot.")
|
||||
if not token or (token.get("org_id") is not None and token.get("org_id") != org_id):
|
||||
raise HTTPException(404, "Token not found.")
|
||||
if token.get("org_id") is None:
|
||||
raise HTTPException(403, "Only a platform admin can make a shared DRB radio bot preferred. "
|
||||
"Organization owners can choose their own organization's radio bots.")
|
||||
if system_id is None:
|
||||
return
|
||||
if not system or (system.get("org_id") and system.get("org_id") != org_id):
|
||||
raise HTTPException(404, "System not found.")
|
||||
if not system.get("org_id"):
|
||||
raise HTTPException(403, "That system is shared by every organization; only a platform admin can "
|
||||
"choose its radio bot.")
|
||||
|
||||
|
||||
@router.put("/{token_id}/prefer/{system_id}", status_code=200)
|
||||
async def set_preferred_system(
|
||||
token_id: str,
|
||||
system_id: str,
|
||||
_: dict = Depends(require_admin_token),
|
||||
decoded: dict = Depends(require_firebase_token),
|
||||
):
|
||||
"""
|
||||
Mark this token as the preferred bot for a system.
|
||||
When a discord_join is issued for any node in that system, this token
|
||||
is tried first before falling back to the general pool.
|
||||
Mark this token as the preferred bot for a system: ``start_stream`` tries
|
||||
it first for that system's radio channels when nobody named a bot
|
||||
(server-26#225 S3), and uses another bot when it can't take the stream.
|
||||
Pass system_id="_none" to clear the preference.
|
||||
|
||||
Who (owner decision Q2, 2026-10-05): a platform admin for any bot and any
|
||||
system; an org owner for their OWN org's systems and their OWN
|
||||
bring-your-own bots. Shared systems (no org_id) and pool bots stay
|
||||
platform-admin only.
|
||||
"""
|
||||
if "/" in token_id or "/" in system_id:
|
||||
raise HTTPException(400, "Bad id.")
|
||||
existing = await fstore.doc_get("bot_tokens", token_id)
|
||||
if not existing:
|
||||
raise HTTPException(404, "Token not found.")
|
||||
uid, email = describe_actor(decoded)
|
||||
if system_id == "_none":
|
||||
# Clear any existing preference on the system that pointed to this token.
|
||||
system_doc = await fstore.doc_get("systems", existing.get("preferred_for_system_id", ""))
|
||||
if system_doc:
|
||||
await fstore.doc_set("systems", existing["preferred_for_system_id"], {"preferred_token_id": None})
|
||||
_check_prefer_access(decoded, existing, None, None)
|
||||
old_id = existing.get("preferred_for_system_id") or ""
|
||||
system_doc = await fstore.doc_get("systems", old_id) if old_id else None
|
||||
if system_doc and system_doc.get("preferred_token_id") == token_id:
|
||||
if not _may_edit_system(decoded, system_doc):
|
||||
raise HTTPException(403, "That system is shared by every organization; only a platform admin "
|
||||
"can change its radio bot.")
|
||||
await fstore.doc_set("systems", old_id, {"preferred_token_id": None})
|
||||
await fstore.doc_set("bot_tokens", token_id, {"preferred_for_system_id": None})
|
||||
await write_audit(uid, email, "discord.token.prefer", details={
|
||||
"token_id": token_id, "system_id": None, "previous_system_id": old_id or None})
|
||||
return {"ok": True, "preferred_for_system_id": None}
|
||||
|
||||
system_doc = await fstore.doc_get("systems", system_id)
|
||||
if not system_doc:
|
||||
raise HTTPException(404, "System not found.")
|
||||
# Set preference on both sides for easy lookup in either direction.
|
||||
_check_prefer_access(decoded, existing, system_doc, system_id)
|
||||
|
||||
# Keep both pointers single-valued: this bot stops being preferred for the
|
||||
# system it was preferred for (when the caller may edit that system), and
|
||||
# the bot this system preferred before loses its back-pointer.
|
||||
old_sys_id = existing.get("preferred_for_system_id")
|
||||
if old_sys_id and old_sys_id != system_id:
|
||||
old_sys = await fstore.doc_get("systems", old_sys_id)
|
||||
if old_sys and old_sys.get("preferred_token_id") == token_id and _may_edit_system(decoded, old_sys):
|
||||
await fstore.doc_set("systems", old_sys_id, {"preferred_token_id": None})
|
||||
old_tok_id = system_doc.get("preferred_token_id")
|
||||
if old_tok_id and old_tok_id != token_id:
|
||||
old_tok = await fstore.doc_get("bot_tokens", old_tok_id)
|
||||
if old_tok and old_tok.get("preferred_for_system_id") == system_id:
|
||||
await fstore.doc_set("bot_tokens", old_tok_id, {"preferred_for_system_id": None})
|
||||
|
||||
await fstore.doc_set("systems", system_id, {"preferred_token_id": token_id})
|
||||
await fstore.doc_set("bot_tokens", token_id, {"preferred_for_system_id": system_id})
|
||||
await write_audit(uid, email, "discord.token.prefer", details={
|
||||
"token_id": token_id, "system_id": system_id, "previous_token_id": old_tok_id,
|
||||
"org_id": system_doc.get("org_id")})
|
||||
return {"ok": True, "preferred_for_system_id": system_id}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user