|
| 1 | +"""Coupler connections API — ConnectedAccount vault and token delegation.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import uuid |
| 7 | +from datetime import datetime |
| 8 | +from typing import Any, Optional |
| 9 | + |
| 10 | +from fastapi import APIRouter, Depends, Header, HTTPException |
| 11 | +from pydantic import BaseModel, Field |
| 12 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 13 | + |
| 14 | +from app.config import settings |
| 15 | +from app.database import get_db |
| 16 | +from app.dependencies import get_current_user |
| 17 | +from app.models import ActivityLog, User |
| 18 | +from app.services.connected_account_service import ConnectedAccountService |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | +router = APIRouter(prefix="/connections", tags=["Connections"]) |
| 23 | + |
| 24 | + |
| 25 | +class ConnectionSummary(BaseModel): |
| 26 | + id: str |
| 27 | + provider_type: str |
| 28 | + provider_name: str |
| 29 | + provider_id: Optional[str] = None |
| 30 | + scopes: list[str] = Field(default_factory=list) |
| 31 | + status: str |
| 32 | + expires_at: Optional[datetime] = None |
| 33 | + last_used_at: Optional[datetime] = None |
| 34 | + created_at: Optional[datetime] = None |
| 35 | + |
| 36 | + |
| 37 | +class ConnectionListResponse(BaseModel): |
| 38 | + connections: list[ConnectionSummary] |
| 39 | + count: int |
| 40 | + |
| 41 | + |
| 42 | +class TokenDelegationRequest(BaseModel): |
| 43 | + purpose: str = "tool_execute" |
| 44 | + ttl_seconds: int = Field(default=300, ge=60, le=900) |
| 45 | + |
| 46 | + |
| 47 | +class TokenDelegationResponse(BaseModel): |
| 48 | + access_token: str |
| 49 | + token_type: str = "Bearer" |
| 50 | + expires_at: str |
| 51 | + purpose: str |
| 52 | + provider_type: str |
| 53 | + scopes: list[str] = Field(default_factory=list) |
| 54 | + |
| 55 | + |
| 56 | +def _require_atp_service( |
| 57 | + x_service_token: Optional[str] = Header(None, alias="X-Service-Token"), |
| 58 | + authorization: Optional[str] = Header(None), |
| 59 | +) -> None: |
| 60 | + expected = getattr(settings, "JANUA_SERVICE_TOKEN", None) or "" |
| 61 | + if not expected: |
| 62 | + raise HTTPException(status_code=404, detail="not found") |
| 63 | + candidate = x_service_token |
| 64 | + if not candidate and authorization and authorization.lower().startswith("bearer "): |
| 65 | + candidate = authorization[7:].strip() |
| 66 | + if not candidate or candidate != expected: |
| 67 | + raise HTTPException(status_code=401, detail="invalid_service_credentials") |
| 68 | + |
| 69 | + |
| 70 | +def _to_summary(conn) -> ConnectionSummary: |
| 71 | + return ConnectionSummary( |
| 72 | + id=str(conn.id), |
| 73 | + provider_type=conn.provider_type, |
| 74 | + provider_name=conn.provider_name, |
| 75 | + provider_id=conn.provider_id, |
| 76 | + scopes=list(conn.oauth_scopes or []), |
| 77 | + status=conn.status, |
| 78 | + expires_at=conn.oauth_expires_at, |
| 79 | + last_used_at=conn.last_used_at, |
| 80 | + created_at=conn.created_at, |
| 81 | + ) |
| 82 | + |
| 83 | + |
| 84 | +@router.get("", response_model=ConnectionListResponse) |
| 85 | +async def list_connections( |
| 86 | + db: AsyncSession = Depends(get_db), |
| 87 | + current_user: User = Depends(get_current_user), |
| 88 | +): |
| 89 | + """List delegated SaaS connections for the authenticated user (no secrets).""" |
| 90 | + svc = ConnectedAccountService(db) |
| 91 | + connections = await svc.list_for_user(current_user, sync_oauth=True) |
| 92 | + summaries = [_to_summary(c) for c in connections] |
| 93 | + return ConnectionListResponse(connections=summaries, count=len(summaries)) |
| 94 | + |
| 95 | + |
| 96 | +@router.delete("/{connection_id}") |
| 97 | +async def revoke_connection( |
| 98 | + connection_id: str, |
| 99 | + db: AsyncSession = Depends(get_db), |
| 100 | + current_user: User = Depends(get_current_user), |
| 101 | +): |
| 102 | + svc = ConnectedAccountService(db) |
| 103 | + try: |
| 104 | + cid = uuid.UUID(connection_id) |
| 105 | + except ValueError: |
| 106 | + raise HTTPException(status_code=400, detail="invalid_connection_id") |
| 107 | + if not await svc.revoke(current_user, cid): |
| 108 | + raise HTTPException(status_code=404, detail="connection_not_found") |
| 109 | + activity = ActivityLog( |
| 110 | + user_id=current_user.id, |
| 111 | + action="connection.revoked", |
| 112 | + resource_type="connected_account", |
| 113 | + resource_id=connection_id, |
| 114 | + activity_metadata={"source": "user"}, |
| 115 | + ) |
| 116 | + db.add(activity) |
| 117 | + await db.commit() |
| 118 | + return {"revoked": True, "id": connection_id} |
| 119 | + |
| 120 | + |
| 121 | +@router.post("/{connection_id}/token", response_model=TokenDelegationResponse) |
| 122 | +async def delegate_connection_token( |
| 123 | + connection_id: str, |
| 124 | + body: TokenDelegationRequest, |
| 125 | + db: AsyncSession = Depends(get_db), |
| 126 | + x_acting_user_id: str = Header(..., alias="X-Acting-User-Id"), |
| 127 | + _: None = Depends(_require_atp_service), |
| 128 | +): |
| 129 | + """Issue a short-lived access token for Coupler tool execute (ATP service only).""" |
| 130 | + svc = ConnectedAccountService(db) |
| 131 | + try: |
| 132 | + cid = uuid.UUID(connection_id) |
| 133 | + acting_uid = uuid.UUID(x_acting_user_id) |
| 134 | + except ValueError: |
| 135 | + raise HTTPException(status_code=400, detail="invalid_id") |
| 136 | + |
| 137 | + connection = await svc.get_by_id(cid) |
| 138 | + if not connection: |
| 139 | + raise HTTPException(status_code=404, detail="connection_not_found") |
| 140 | + |
| 141 | + try: |
| 142 | + payload = await svc.delegate_token( |
| 143 | + connection, |
| 144 | + acting_user_id=acting_uid, |
| 145 | + purpose=body.purpose, |
| 146 | + ttl_seconds=body.ttl_seconds, |
| 147 | + ) |
| 148 | + except PermissionError: |
| 149 | + raise HTTPException(status_code=403, detail="acting_user_mismatch") |
| 150 | + except ValueError as e: |
| 151 | + raise HTTPException(status_code=404, detail=str(e)) |
| 152 | + |
| 153 | + activity = ActivityLog( |
| 154 | + user_id=acting_uid, |
| 155 | + action="tool.delegation.issued", |
| 156 | + resource_type="connected_account", |
| 157 | + resource_id=connection_id, |
| 158 | + activity_metadata={ |
| 159 | + "purpose": body.purpose, |
| 160 | + "provider_type": connection.provider_type, |
| 161 | + "ttl_seconds": body.ttl_seconds, |
| 162 | + }, |
| 163 | + ) |
| 164 | + db.add(activity) |
| 165 | + await db.commit() |
| 166 | + |
| 167 | + return TokenDelegationResponse(**payload) |
| 168 | + |
| 169 | + |
| 170 | +@router.post("/sync/{provider}") |
| 171 | +async def sync_provider_connection( |
| 172 | + provider: str, |
| 173 | + db: AsyncSession = Depends(get_db), |
| 174 | + current_user: User = Depends(get_current_user), |
| 175 | +): |
| 176 | + """Explicitly sync a provider connection from linked OAuthAccount.""" |
| 177 | + if provider not in ("github", "slack"): |
| 178 | + raise HTTPException(status_code=400, detail="unsupported_provider") |
| 179 | + svc = ConnectedAccountService(db) |
| 180 | + await svc.list_for_user(current_user, sync_oauth=True) |
| 181 | + connections = await svc.list_for_user(current_user, sync_oauth=False) |
| 182 | + matched = [c for c in connections if c.provider_type == provider] |
| 183 | + if not matched: |
| 184 | + raise HTTPException( |
| 185 | + status_code=404, |
| 186 | + detail=f"No {provider} connection. Link {provider} via OAuth first.", |
| 187 | + ) |
| 188 | + return {"synced": True, "connection": _to_summary(matched[0])} |
0 commit comments