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:
11linear11
2026-10-09 07:59:02 -04:00
parent 07245cd5ca
commit 996435d2ae
42 changed files with 4551 additions and 88 deletions
+81
View File
@@ -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())
+71
View File
@@ -0,0 +1,71 @@
"""Conversation management endpoints (C01)."""
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Response, status
from pydantic import BaseModel, ConfigDict, Field
from app.api.v1.dependencies import (
get_current_user,
get_lifecycle_service,
require_csrf,
)
from app.modules.auth.service import UserContext
from app.modules.voice.lifecycle import LiveLifecycleService
router = APIRouter(prefix="/conversations", tags=["Conversations"])
class CreateConversationRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
client_request_id: UUID
mode: str = Field(default="voice", description="Must be 'voice' in MVP")
title: str | None = Field(default=None, max_length=120)
class ConversationResponse(BaseModel):
id: str
mode: str
title: str | None = None
status: str
access_epoch: int
created_at: str
@router.post(
"",
response_model=ConversationResponse,
status_code=status.HTTP_201_CREATED,
summary="C01: Create Conversation",
description="Creates an owned voice conversation container with idempotency protection.",
)
def create_conversation(
req: CreateConversationRequest,
response: Response,
user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
_csrf: Annotated[None, Depends(require_csrf)] = None,
) -> ConversationResponse:
try:
result = lifecycle.create_conversation(
user=user,
client_request_id=req.client_request_id,
mode=req.mode,
title=req.title,
)
except ValueError as exc:
from app.api.v1.dependencies import error
raise error(str(exc)) from None
if result.get("replayed"):
response.headers["Idempotency-Replayed"] = "true"
return ConversationResponse(
id=result["id"],
mode=result["mode"],
title=result["title"],
status=result["status"],
access_epoch=result["access_epoch"],
created_at=result["created_at"],
)
+104
View File
@@ -0,0 +1,104 @@
"""Cookie-only identity and shared backend services, lazily constructed."""
from datetime import timedelta
import json
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Request
from sqlalchemy.engine import Engine
from app.infrastructure.database import create_database
from app.modules.documents.settings import IngestionSettings
from app.modules.auth.service import AuthService, COOKIE_NAME, UserContext, check_origin, verify_csrf_token
from app.modules.voice.lifecycle import LiveLifecycleService
from app.modules.voice.configuration import VoiceSettings
from app.modules.knowledge.service import SearchService
from app.modules.knowledge.langchain_tool import SearchToolRunner
from app.modules.knowledge.calibration import load_cutoff
_ENGINE = _AUTH_SERVICE = _LIFECYCLE_SERVICE = _TOOL_RUNNER = _SEARCH_SERVICE = None
def get_voice_settings():
return VoiceSettings()
def error(code):
code = {'SESSION_NOT_FOUND':'NOT_FOUND','CONVERSATION_NOT_FOUND':'NOT_FOUND',
'SESSION_REVOKED':'AUTH_REQUIRED','SESSION_EXPIRED':'AUTH_REQUIRED','ACCOUNT_DISABLED':'AUTH_REQUIRED',
'CSRF_TOKEN_INVALID':'CSRF_INVALID','FORBIDDEN_ORIGIN':'FORBIDDEN','SERVICE_BUSY':'RATE_LIMITED',
'SERVICE_UNAVAILABLE':'DEPENDENCY_UNAVAILABLE'}.get(code,code)
codes = {
'AUTH_REQUIRED': 401, 'INVALID_CREDENTIALS': 401, 'ACCOUNT_DISABLED': 401,
'SESSION_REVOKED': 401, 'SESSION_EXPIRED': 401, 'CSRF_TOKEN_INVALID': 403,
'FORBIDDEN_ORIGIN': 403, 'CONVERSATION_NOT_FOUND': 404, 'SESSION_NOT_FOUND': 404,
'CALIBRATION_REQUIRED': 503, 'LIVE_PROVIDER_UNAVAILABLE': 503, 'SERVICE_BUSY': 429,
'MODE_MISMATCH': 409, 'CONVERSATION_CLOSED': 409, 'CONVERSATION_STALE': 409,
'LIVE_SESSION_BUSY': 409, 'LIVE_SESSION_UNUSABLE': 409, 'IDEMPOTENCY_CONFLICT': 409,
'CONTEXT_REVOKED': 409, 'LIVE_SESSION_EXPIRED':409, 'NOT_FOUND':404,'CSRF_INVALID':403,'FORBIDDEN':403,'RATE_LIMITED':429,'DEPENDENCY_UNAVAILABLE':503,
}
if code not in codes:
code = 'DEPENDENCY_UNAVAILABLE'
return HTTPException(codes.get(code, 503), detail={'code': code, 'message': 'Request could not be completed.'})
def get_engine():
global _ENGINE
if _ENGINE is None:
_ENGINE = create_database(IngestionSettings().database_url.get_secret_value())
return _ENGINE
def get_auth_service(engine: Annotated[Engine, Depends(get_engine)]):
global _AUTH_SERVICE
if _AUTH_SERVICE is None or _AUTH_SERVICE.engine is not engine:
_AUTH_SERVICE = AuthService(engine, session_lifetime=timedelta(seconds=VoiceSettings().auth_session_seconds))
return _AUTH_SERVICE
def get_lifecycle_service(engine: Annotated[Engine, Depends(get_engine)]):
global _LIFECYCLE_SERVICE
if _LIFECYCLE_SERVICE is None or _LIFECYCLE_SERVICE.engine is not engine:
_LIFECYCLE_SERVICE = LiveLifecycleService(engine, session_ttl=timedelta(seconds=VoiceSettings().live_session_seconds))
return _LIFECYCLE_SERVICE
def get_tool_runner():
global _TOOL_RUNNER
if _TOOL_RUNNER is None:
_TOOL_RUNNER = SearchToolRunner()
return _TOOL_RUNNER
def get_search_service(engine: Annotated[Engine, Depends(get_engine)]):
global _SEARCH_SERVICE
if _SEARCH_SERVICE is None or _SEARCH_SERVICE.engine is not engine:
settings = IngestionSettings()
path = VoiceSettings().search_calibration_report
cutoff = None
if path is not None:
try:
cutoff = load_cutoff(json.loads(path.read_text(encoding='utf-8')))
except (ValueError, OSError, KeyError, TypeError, AttributeError):
raise error('CALIBRATION_REQUIRED') from None
from app.worker import factories
_, provider_factory = factories(settings)
provider, counter = provider_factory(settings.processing_profile())
_SEARCH_SERVICE = SearchService(engine, settings, provider, counter, cutoff=cutoff)
return _SEARCH_SERVICE
def get_current_user(request: Request, auth_service: Annotated[AuthService, Depends(get_auth_service)]) -> UserContext:
try:
return auth_service.get_current_user(request.cookies.get(COOKIE_NAME))
except ValueError:
raise error('AUTH_REQUIRED') from None
def require_origin(request: Request, config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
if not check_origin(request.headers.get('origin'), request.headers.get('host'), config.trusted_origins, config.trusted_hosts, required=True):
raise error('FORBIDDEN_ORIGIN')
def require_csrf(request: Request, config: Annotated[VoiceSettings, Depends(get_voice_settings)],
x_csrf_token: Annotated[str | None, Header()] = None):
require_origin(request, config)
if not verify_csrf_token(request.cookies.get(COOKIE_NAME), x_csrf_token):
raise error('CSRF_TOKEN_INVALID')
+283
View File
@@ -0,0 +1,283 @@
"""V01-V04 and supervised, cookie-authenticated Gemini stream."""
import asyncio
from dataclasses import asdict
import json
import logging
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, Response, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, ConfigDict
from app.api.v1.dependencies import (get_auth_service, get_current_user, get_engine,
get_lifecycle_service, get_search_service, get_tool_runner, get_voice_settings, require_csrf, error)
from app.infrastructure.blocking import blocking
from app.modules.auth.service import COOKIE_NAME, UserContext, check_origin
from app.modules.voice.lifecycle import LiveLifecycleService
from app.modules.voice.configuration import VoiceSettings
from app.modules.voice.runtime import VoiceRuntime
from app.modules.voice.settings import RuntimeSettings
from app.modules.voice.durable_tools import DurableTools
from app.modules.voice import registry
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
from app.modules.knowledge.calibration import load_cutoff
from app.modules.knowledge.evidence import RETRIEVAL_POLICY
from app.modules.documents.settings import IngestionSettings
logger = logging.getLogger(__name__)
router = APIRouter(prefix='/voice/sessions', tags=['Voice Sessions'])
ACTIVE_MEDIA_SESSIONS = set()
# Event-loop-local guard mutation has no await between membership check and insertion.
def close_affected_runtimes(organization_id, new_epoch=0):
return registry.notify(organization_id=organization_id, new_epoch=new_epoch)
class CreateLiveSessionRequest(BaseModel):
model_config = ConfigDict(extra='forbid')
conversation_id: UUID
client_request_id: UUID
class LiveSessionResponse(BaseModel):
session_id: str
conversation_id: str
status: str
stream_path: str | None
expires_at: str
poll_url: str
class CloseLiveSessionResponse(BaseModel):
session_id: str
status: str
close_reason: str | None = None
def capability(config):
config.require_voice()
try:
if config.search_calibration_report is None:
raise ValueError('CALIBRATION_REQUIRED')
cutoff = load_cutoff(json.loads(config.search_calibration_report.read_text(encoding='utf-8')))
if (cutoff.profile != asdict(IngestionSettings().embedding_profile)
or cutoff.retrieval_policy != RETRIEVAL_POLICY):
raise ValueError('CALIBRATION_REQUIRED')
except (OSError, ValueError, KeyError, TypeError, AttributeError):
raise ValueError('CALIBRATION_REQUIRED') from None
return cutoff
@router.post('', response_model=LiveSessionResponse, status_code=201)
def create_voice_session(req: CreateLiveSessionRequest, response: Response,
user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)],
_csrf: Annotated[None, Depends(require_csrf)] = None):
try:
# Recover replay before capability checks: a configuration change cannot alter identity.
try:
result = lifecycle.recover_live_session(user, req.client_request_id)
except ValueError as exc:
if str(exc) != 'SESSION_NOT_FOUND':
raise
else:
if result['conversation_id'] != str(req.conversation_id):
raise ValueError('IDEMPOTENCY_CONFLICT')
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id)
response.status_code = 201 if result['status'] == 'connected' else 202
response.headers['Idempotency-Replayed'] = 'true'
return result
cutoff = capability(config)
profile = config.profile()
profile["search"] = {"embedding": cutoff.profile, "calibration_id": cutoff.calibration_id,
"retrieval_policy": cutoff.retrieval_policy, "distance": cutoff.distance}
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id,
provider=config.provider, model=config.gemini_model, execution_profile=profile)
except ValueError as exc:
raise error(str(exc)) from None
if result['replayed']:
response.status_code = 201 if result['status'] == 'connected' else 202
response.headers['Idempotency-Replayed'] = 'true'
return result
@router.get('/by-request/{client_request_id}', response_model=LiveSessionResponse)
def recover(client_request_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)]):
try:
return lifecycle.recover_live_session(user, client_request_id)
except ValueError as exc:
raise error(str(exc)) from None
@router.get('/{session_id}')
def poll(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)]):
try:
return lifecycle.get_live_session(user, session_id)
except ValueError as exc:
raise error(str(exc)) from None
@router.post('/{session_id}/close', response_model=CloseLiveSessionResponse)
def close(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
_csrf: Annotated[None, Depends(require_csrf)] = None):
try:
return lifecycle.close_live_session(user, session_id)
except ValueError as exc:
raise error(str(exc)) from None
async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle_service,
engine, search_service, tool_runner, config=None):
config = config or VoiceSettings()
if (websocket.query_params or not check_origin(websocket.headers.get('origin'), websocket.headers.get('host'),
config.trusted_origins, config.trusted_hosts, required=True)):
await websocket.close(code=1008, reason='Stream unavailable')
return
try:
user = await blocking(auth_service.get_current_user, websocket.cookies.get(COOKIE_NAME))
info = await blocking(lifecycle_service.validate_stream, user, session_id, initial=True)
config.require_voice()
if search_service.cutoff is None:
raise ValueError('CALIBRATION_REQUIRED')
if (info['provider'] != 'gemini' or info['model'] != config.gemini_model
or any(info['execution_profile'].get(k) != v for k,v in config.profile().items())
or info['execution_profile'].get('search') != {
'embedding': search_service.cutoff.profile, 'calibration_id': search_service.cutoff.calibration_id,
'retrieval_policy': search_service.cutoff.retrieval_policy, 'distance': search_service.cutoff.distance}):
raise ValueError('LIVE_SESSION_UNUSABLE')
except Exception as exc:
logger.info('Stream admission rejected: %s', type(exc).__name__)
await websocket.close(code=1008, reason='Stream unavailable')
return
if session_id in ACTIVE_MEDIA_SESSIONS or len(ACTIVE_MEDIA_SESSIONS) >= config.max_provider_sessions:
await websocket.close(code=1008, reason='Stream unavailable')
return
ACTIVE_MEDIA_SESSIONS.add(session_id)
runtime = adapter = None
children = []
outcome, failed = 'LIVE_TRANSPORT_FAILED', True
client_closed = False
ready_sent = asyncio.Event()
async def close_client(code=1000):
nonlocal client_closed
if not client_closed:
client_closed = True
try:
await websocket.close(code=code, reason='Voice session stopped')
except (RuntimeError, WebSocketDisconnect):
pass
try:
# Guard is released even if accept fails.
await websocket.accept()
limits = RuntimeSettings()
transport = await asyncio.wait_for(connect_gemini(config.gemini_api_key.get_secret_value(),
config.gemini_model, config.gemini_proxy, limits), limits.connect_timeout_seconds)
adapter = GeminiLiveAdapter(transport, model=config.gemini_model, voice=config.gemini_voice, settings=limits)
async def authority_check(execution):
nonlocal outcome
try:
await blocking(lifecycle_service.validate_stream, user, session_id, runtime.session_execution)
await blocking(lifecycle_service.validate_stream, user, session_id, execution)
except ValueError as exc:
outcome = str(exc)
raise
return True
store = DurableTools(lifecycle_service, user, session_id)
async def emit(event):
if isinstance(event,bytes):
await websocket.send_bytes(event)
else:
if event['type'] == 'sources':
for response, call in runtime.calls.values():
if call['ref'] == event['tool_call_id']:
await store.delivery(call, response.turn.execution)
if event['type'] == 'turn_interrupted':
await blocking(lifecycle_service.cancel_tools, user, session_id, event['cancelled_tool_call_ids'])
await websocket.send_text(json.dumps(event,ensure_ascii=False))
if event['type'] == 'session_ready':
ready_sent.set()
await blocking(lifecycle_service.mark_connected, user, session_id)
runtime = VoiceRuntime(adapter, search_service, tool_runner, user.id, emit,
authority_check=authority_check, session_id=str(session_id), settings=limits,
close_client=close_client, tool_store=store)
registry.register(session_id, user.organization_id, info['access_epoch'], user.auth_session_id, runtime)
await runtime.start()
async def browser():
while runtime.usable:
message = await websocket.receive()
if message['type'] == 'websocket.disconnect':
return
if not runtime.ready and ready_sent.is_set():
await asyncio.wait_for(runtime.ready_signal.wait(), limits.send_timeout_seconds)
if message.get('bytes') is not None:
await runtime.input_audio(message['bytes'])
elif message.get('text') is not None:
await runtime.client_control(message['text'].encode('utf-8'))
async def monitor():
nonlocal outcome
while runtime.usable:
await asyncio.sleep(.25)
try:
await blocking(lifecycle_service.validate_stream, user, session_id)
except ValueError as exc:
outcome = str(exc)
async with runtime.lock:
runtime.fail('CONTEXT_REVOKED')
return
children = [asyncio.create_task(browser()), asyncio.create_task(runtime.receive_loop()),
asyncio.create_task(monitor()), asyncio.create_task(runtime.failure_signal.wait())]
done, pending = await asyncio.wait(children, return_when=asyncio.FIRST_COMPLETED)
for task in done:
if not task.cancelled():
exc = task.exception()
if exc:
raise exc
if runtime.failure:
# Give its terminal-error delivery its bounded opportunity before cancellation.
try:
await asyncio.wait_for(runtime.error_delivered.wait(), limits.send_timeout_seconds)
except TimeoutError:
pass
outcome = outcome if outcome not in ('connection_closed', 'LIVE_TRANSPORT_FAILED') else runtime.failure
failed = outcome.startswith('LIVE_') or outcome in ('SEARCH_TIMEOUT','SEARCH_SATURATED','DEPENDENCY_UNAVAILABLE','SEARCH_CANCELLED')
except WebSocketDisconnect:
outcome = 'LIVE_TRANSPORT_FAILED'
failed = True
except Exception:
if runtime and runtime.failure:
outcome = runtime.failure
else:
outcome = 'LIVE_SETUP_FAILED' if runtime is None or not runtime.ready else 'LIVE_TRANSPORT_FAILED'
failed = True
finally:
async def cleanup():
try:
for task in children:
task.cancel()
await asyncio.gather(*children, return_exceptions=True)
try:
if runtime:
await asyncio.wait_for(runtime.close(), 6)
elif adapter:
await asyncio.wait_for(adapter.close(), 6)
except Exception:
logger.warning('Bounded provider cleanup incomplete')
try:
await blocking(lifecycle_service.finish_session, user, session_id, outcome, failed=failed)
except Exception:
logger.warning('Live terminal persistence unavailable')
await asyncio.wait_for(close_client(runtime.close_code or 1000 if runtime else 1011), 5)
finally:
registry.unregister(session_id)
ACTIVE_MEDIA_SESSIONS.discard(session_id)
# An ASGI disconnect can cancel its route after close was delivered. Cleanup
# owns a separate task so cancellation cannot strand the media guard.
cleaning = asyncio.create_task(cleanup())
try:
await asyncio.shield(cleaning)
except asyncio.CancelledError:
# Owning-loop registry/shutdown tracks this independent completion.
raise
@router.websocket('/{session_id}/stream')
async def stream(websocket: WebSocket, session_id: UUID,
engine=Depends(get_engine), auth_service=Depends(get_auth_service), lifecycle=Depends(get_lifecycle_service),
runner=Depends(get_tool_runner), search=Depends(get_search_service), config=Depends(get_voice_settings)):
if not websocket.app.state.ready:
await websocket.close(code=1013,reason='Service unavailable')
return
await handle_stream_websocket(websocket,session_id,auth_service,lifecycle,engine,search,runner,config)