"""Channel accounts (owner) and the approval undo button (Phase 7). * ``GET /admin/channels`` / ``PUT /admin/channels/{channel}`` / ``DELETE ...``: per-tenant channel configuration. ``config`` takes NON-secret ids only; secrets are referenced by ``secret_ref`` and resolved from the secret store at delivery time (``core.channels.secrets``). Keys that look like secrets are rejected. * ``POST /approvals/{id}/undo``: if the approved call queued a message that is still inside its undo window, run the call's recorded undo (e.g. ``ecommerce.cancel_message``) through the gateway as the operator. ``200 {"status": "cancelled", ...}``; ``409`` if too late. """ from __future__ import annotations import uuid from datetime import UTC, datetime from typing import Any, Literal from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel, Field from sqlalchemy import select from core.api.routes.runs import services from core.approvals.models import Approval from core.auth.deps import Principal, require_role from core.channels.models import PROVIDERS, ChannelAccount from core.channels.secrets import valid_ref from core.gateway.gateway import ToolCall from core.services import Services from core.tenancy.models import Role router = APIRouter(tags=["channels"]) SECRET_LIKE = ("token", "secret", "password", "api_key", "apikey", "private_key", "access_key") def _secret_keys(value: Any, path: str = "") -> list[str]: found: list[str] = [] if isinstance(value, dict): for k, v in value.items(): key = str(k).lower() if any(s in key for s in SECRET_LIKE): found.append(f"{path}{k}") found.extend(_secret_keys(v, f"{path}{k}.")) elif isinstance(value, list): for i, v in enumerate(value): found.extend(_secret_keys(v, f"{path}{i}.")) return found class ChannelAccountIn(BaseModel): provider: str = Field(min_length=1, max_length=30) config: dict[str, Any] = Field(default_factory=dict) secret_ref: str | None = Field(default=None, max_length=120) enabled: bool = True def _out(a: ChannelAccount) -> dict[str, Any]: return { "id": str(a.id), "channel": a.channel, "provider": a.provider, "config": a.config, "secret_ref": a.secret_ref, "enabled": a.enabled, "cursor": a.cursor, "updated_at": a.updated_at, } @router.get("/admin/channels") async def list_channels( p: Principal = Depends(require_role(Role.OWNER)), svc: Services = Depends(services) ) -> list[dict[str, Any]]: async with svc.db.session(tenant_id=p.tenant_id) as s: rows = (await s.execute(select(ChannelAccount).order_by(ChannelAccount.channel))).scalars() return [_out(a) for a in rows] @router.put("/admin/channels/{channel}") async def put_channel( channel: Literal["whatsapp", "email", "webchat", "sms"], body: ChannelAccountIn, p: Principal = Depends(require_role(Role.OWNER)), svc: Services = Depends(services), ) -> dict[str, Any]: if body.provider not in PROVIDERS[channel]: raise HTTPException(422, f"provider for {channel} must be one of {PROVIDERS[channel]}") if body.secret_ref is not None and not valid_ref(body.secret_ref): raise HTTPException(422, "secret_ref must be a reference name, not a secret value") leaked = [k for k in _secret_keys(body.config) if not k.endswith("provider_config_key")] if leaked: raise HTTPException( 422, f"config must not hold secrets ({', '.join(leaked)}); use secret_ref" ) async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin(): acct = ( await s.execute(select(ChannelAccount).where(ChannelAccount.channel == channel)) ).scalar_one_or_none() if acct is None: acct = ChannelAccount(tenant_id=p.tenant_id, channel=channel, cursor={}) s.add(acct) acct.provider = body.provider acct.config = body.config acct.secret_ref = body.secret_ref acct.enabled = body.enabled acct.updated_at = datetime.now(UTC) await s.flush() return _out(acct) @router.delete("/admin/channels/{channel}", status_code=status.HTTP_204_NO_CONTENT) async def delete_channel( channel: str, p: Principal = Depends(require_role(Role.OWNER)), svc: Services = Depends(services), ) -> None: async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin(): acct = ( await s.execute(select(ChannelAccount).where(ChannelAccount.channel == channel)) ).scalar_one_or_none() if acct is None: raise HTTPException(404, "channel not configured") await s.delete(acct) @router.post("/approvals/{approval_id}/undo") async def undo_approved_send( approval_id: uuid.UUID, p: Principal = Depends(require_role(Role.AGENT_OPERATOR)), svc: Services = Depends(services), ) -> dict[str, Any]: async with svc.db.session(tenant_id=p.tenant_id) as s: a = await s.get(Approval, approval_id) if a is None: raise HTTPException(404, "approval not found") undo = a.undo or {} if not undo.get("tool"): raise HTTPException(409, "this approval has nothing to undo") outcome = await svc.gateway.execute( ToolCall( tenant_id=p.tenant_id, actor=p.actor, tool=str(undo["tool"]), args=dict(undo.get("args") or {}), ) ) if outcome.status != "executed" or outcome.result is None or not outcome.result.ok: reason = outcome.reason or (outcome.result.error if outcome.result else outcome.status) raise HTTPException(409, reason or "cannot undo") return {"status": "cancelled", "approval_id": str(approval_id), **(outcome.result.data or {})}