feat(voice): add authenticated Phase 2 live lifecycle
Add cookie authentication, owned conversations, durable Live reservations, tool completion/replay fencing, revocation, and startup reconciliation. Introduce forward lifecycle/owner-chain migrations and the temporary Gemini adapter while preserving the existing OpenAI Realtime adapter. Include the executable audio client, regression coverage, configuration, API/database documentation, and recorded acceptance evidence. Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript syntax, and whitespace checks passed. Full PostgreSQL/provider-free results are recorded in the repair report; real-provider/browser acceptance is unrun. Follow-up work remains for configurable OpenAI/Gemini selection, transport admission, authority diagnostics, playback message bounds, and client replay identity after ambiguous creation responses.
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
"""A01-A03: opaque sessions, bounded login admission, and synchronizer CSRF."""
|
||||
from collections import deque
|
||||
import time
|
||||
from threading import Lock, BoundedSemaphore
|
||||
from typing import Annotated
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from app.api.v1.dependencies import get_auth_service, get_current_user, get_voice_settings, require_origin, error
|
||||
from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, generate_csrf_token, verify_csrf_token
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
|
||||
router = APIRouter(prefix='/auth', tags=['Authentication'])
|
||||
identity_router = APIRouter(tags=['Authentication'])
|
||||
_ATTEMPTS = deque(maxlen=120)
|
||||
_LOCK = Lock()
|
||||
_LOGINS = BoundedSemaphore(2)
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid', strict=True)
|
||||
username: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=1, max_length=1024)
|
||||
|
||||
class UserDTO(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
role: str
|
||||
organization_id: str
|
||||
|
||||
class AuthResponse(BaseModel):
|
||||
user: UserDTO
|
||||
csrf_token: str
|
||||
expires_at: str
|
||||
|
||||
@router.post('/login', response_model=AuthResponse)
|
||||
def login(req: LoginRequest, request: Request, response: Response,
|
||||
auth_service: Annotated[AuthService, Depends(get_auth_service)],
|
||||
config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
|
||||
require_origin(request, config)
|
||||
stamp = time.monotonic()
|
||||
with _LOCK:
|
||||
while _ATTEMPTS and stamp - _ATTEMPTS[0] >= 60:
|
||||
_ATTEMPTS.popleft()
|
||||
if len(_ATTEMPTS) >= config.login_attempts_per_minute:
|
||||
raise error('SERVICE_BUSY')
|
||||
_ATTEMPTS.append(stamp)
|
||||
if not _LOGINS.acquire(blocking=False):
|
||||
raise error('SERVICE_BUSY')
|
||||
try:
|
||||
user, token, csrf, expiry = auth_service.login(req.username, req.password)
|
||||
except ValueError as exc:
|
||||
raise error(str(exc)) from None
|
||||
finally:
|
||||
_LOGINS.release()
|
||||
response.set_cookie(COOKIE_NAME, token, httponly=True, secure=config.cookie_secure,
|
||||
samesite='lax', expires=expiry, path='/')
|
||||
return AuthResponse(user=UserDTO(**user), csrf_token=csrf, expires_at=expiry.isoformat())
|
||||
|
||||
@router.post('/logout', status_code=204)
|
||||
def logout(request: Request, response: Response,
|
||||
auth_service: Annotated[AuthService, Depends(get_auth_service)],
|
||||
config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
|
||||
require_origin(request, config)
|
||||
token = request.cookies.get(COOKIE_NAME)
|
||||
try:
|
||||
auth_service.get_current_user(token)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
if not verify_csrf_token(token, request.headers.get('x-csrf-token')):
|
||||
raise error('CSRF_TOKEN_INVALID')
|
||||
auth_service.logout(token)
|
||||
response.delete_cookie(COOKIE_NAME, path='/', secure=config.cookie_secure, httponly=True, samesite='lax')
|
||||
response.status_code = 204
|
||||
return response
|
||||
|
||||
@identity_router.get('/me', response_model=AuthResponse)
|
||||
@router.get('/me', response_model=AuthResponse, include_in_schema=False)
|
||||
def get_me(request: Request, user: Annotated[UserContext, Depends(get_current_user)]):
|
||||
return AuthResponse(user=UserDTO(id=str(user.id), organization_id=str(user.organization_id),
|
||||
username=user.username, role=user.role), csrf_token=generate_csrf_token(request.cookies.get(COOKIE_NAME)),
|
||||
expires_at=user.expires_at.isoformat())
|
||||
Reference in New Issue
Block a user