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.
246 lines
9.9 KiB
Python
246 lines
9.9 KiB
Python
"""Authentication, session lifecycle, CSRF tokens and access validation."""
|
|
from datetime import datetime, timezone, timedelta
|
|
import hashlib
|
|
import hmac
|
|
import os
|
|
import secrets
|
|
from uuid import UUID, uuid4
|
|
|
|
from argon2 import PasswordHasher
|
|
from argon2.exceptions import VerifyMismatchError, VerificationError
|
|
from pydantic import BaseModel, Field
|
|
from sqlalchemy import text
|
|
|
|
|
|
COOKIE_NAME = "rag_session"
|
|
DEFAULT_SESSION_LIFETIME = timedelta(hours=8)
|
|
|
|
|
|
|
|
class UserContext(BaseModel):
|
|
id: UUID
|
|
organization_id: UUID
|
|
username: str
|
|
role: str
|
|
is_enabled: bool
|
|
auth_session_id: UUID
|
|
access_epoch: int
|
|
expires_at: datetime | None = None
|
|
|
|
|
|
def hash_token(raw_token: str) -> str:
|
|
"""Computes SHA-256 hex digest of raw session token."""
|
|
if not valid_token(raw_token):
|
|
raise ValueError("AUTH_REQUIRED")
|
|
return hashlib.sha256(raw_token.encode("ascii")).hexdigest()
|
|
|
|
|
|
def valid_token(value):
|
|
return isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value)
|
|
|
|
|
|
def generate_csrf_token(raw_token: str) -> str:
|
|
if not valid_token(raw_token):
|
|
raise ValueError('AUTH_REQUIRED')
|
|
return hmac.new(raw_token.encode('ascii'), b'rag-session-csrf-v1', hashlib.sha256).hexdigest()
|
|
|
|
|
|
def verify_csrf_token(raw_token: str, client_csrf: str) -> bool:
|
|
return (valid_token(raw_token) and valid_token(client_csrf)
|
|
and hmac.compare_digest(generate_csrf_token(raw_token), client_csrf))
|
|
|
|
|
|
def check_origin(origin_header, host_header, allowed_origins=None, allowed_hosts=None, *, required=False):
|
|
from app.modules.voice.configuration import VoiceSettings
|
|
config = VoiceSettings()
|
|
origins = allowed_origins if allowed_origins is not None else config.trusted_origins
|
|
hosts = allowed_hosts if allowed_hosts is not None else config.trusted_hosts
|
|
if not isinstance(host_header, str) or len(host_header) > 255 or host_header not in hosts:
|
|
return False
|
|
if origin_header is None:
|
|
return not required
|
|
return isinstance(origin_header, str) and len(origin_header) <= 512 and origin_header in origins
|
|
|
|
|
|
class AuthService:
|
|
def __init__(self, engine, session_lifetime: timedelta | None = None, session_ttl: timedelta | None = None):
|
|
self.engine = engine
|
|
self.lifetime = session_ttl or session_lifetime or DEFAULT_SESSION_LIFETIME
|
|
self._hasher = PasswordHasher()
|
|
self._dummy_hash = self._hasher.hash(secrets.token_hex(32))
|
|
|
|
def login(self, username: str, password: str) -> tuple[dict, str, str, datetime]:
|
|
"""Authenticates user and issues a new opaque cookie session.
|
|
|
|
Returns: (user_dict, raw_token, csrf_token, expires_at)
|
|
Raises: ValueError("INVALID_CREDENTIALS") or ValueError("ACCOUNT_DISABLED")
|
|
"""
|
|
if (not isinstance(username, str) or not isinstance(password, str)
|
|
or not 1 <= len(username) <= 120 or not 1 <= len(password) <= 1024
|
|
or '\x00' in username or '\x00' in password):
|
|
raise ValueError('INVALID_CREDENTIALS')
|
|
clean_user = username.strip().lower()
|
|
now = datetime.now(timezone.utc)
|
|
expires_at = now + self.lifetime
|
|
|
|
from app.modules.knowledge.service import transaction
|
|
with transaction(self.engine) as conn:
|
|
row = conn.execute(
|
|
text("""
|
|
SELECT u.id, u.organization_id, u.username, u.password_hash, u.role, u.is_enabled,
|
|
s.access_epoch
|
|
FROM users u
|
|
JOIN organization_settings s ON s.organization_id = u.organization_id
|
|
WHERE u.username = :username
|
|
"""),
|
|
{"username": clean_user}
|
|
).mappings().first()
|
|
|
|
if not row:
|
|
try:
|
|
self._hasher.verify(self._dummy_hash, password)
|
|
except VerificationError:
|
|
pass
|
|
raise ValueError("INVALID_CREDENTIALS")
|
|
|
|
conn.execute(text('SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR SHARE'), {'org': row['organization_id']})
|
|
row = conn.execute(text('''SELECT u.id,u.organization_id,u.username,u.password_hash,u.role,u.is_enabled,s.access_epoch
|
|
FROM users u JOIN organization_settings s ON s.organization_id=u.organization_id
|
|
WHERE u.id=:id FOR SHARE OF u'''), {'id':row['id']}).mappings().first()
|
|
if row is None:
|
|
raise ValueError('INVALID_CREDENTIALS')
|
|
try:
|
|
self._hasher.verify(row["password_hash"], password)
|
|
except (VerifyMismatchError, VerificationError):
|
|
raise ValueError("INVALID_CREDENTIALS")
|
|
|
|
if not row["is_enabled"]:
|
|
raise ValueError("ACCOUNT_DISABLED")
|
|
|
|
session_id = uuid4()
|
|
raw_token = secrets.token_hex(32)
|
|
token_h = hash_token(raw_token)
|
|
csrf_token = generate_csrf_token(raw_token)
|
|
|
|
conn.execute(
|
|
text("""
|
|
INSERT INTO auth_sessions (id, organization_id, user_id, token_hash, created_at, expires_at, last_seen_at)
|
|
VALUES (:id, :org, :user, :token_hash, :created_at, :expires_at, :last_seen_at)
|
|
"""),
|
|
{
|
|
"id": session_id,
|
|
"org": row["organization_id"],
|
|
"user": row["id"],
|
|
"token_hash": token_h,
|
|
"created_at": now,
|
|
"expires_at": expires_at,
|
|
"last_seen_at": now,
|
|
}
|
|
)
|
|
|
|
user_dict = {
|
|
"id": str(row["id"]),
|
|
"username": row["username"],
|
|
"role": row["role"],
|
|
"organization_id": str(row["organization_id"]),
|
|
}
|
|
return user_dict, raw_token, csrf_token, expires_at
|
|
|
|
def get_current_user(self, raw_token: str) -> UserContext:
|
|
"""Validates session token and returns active UserContext."""
|
|
if not raw_token:
|
|
raise ValueError("AUTH_REQUIRED")
|
|
|
|
token_h = hash_token(raw_token)
|
|
now = datetime.now(timezone.utc)
|
|
|
|
from app.modules.knowledge.service import transaction
|
|
with transaction(self.engine) as conn:
|
|
row = conn.execute(
|
|
text("""
|
|
SELECT a.id AS auth_session_id, a.expires_at, a.revoked_at,
|
|
u.id AS user_id, u.organization_id, u.username, u.role, u.is_enabled,
|
|
s.access_epoch
|
|
FROM auth_sessions a
|
|
JOIN users u ON u.id = a.user_id AND u.organization_id = a.organization_id
|
|
JOIN organization_settings s ON s.organization_id = a.organization_id
|
|
WHERE a.token_hash = :token_hash
|
|
"""),
|
|
{"token_hash": token_h}
|
|
).mappings().first()
|
|
|
|
if not row:
|
|
raise ValueError("AUTH_REQUIRED")
|
|
|
|
if row["revoked_at"] is not None:
|
|
raise ValueError("SESSION_REVOKED")
|
|
|
|
if row["expires_at"] <= now:
|
|
raise ValueError("SESSION_EXPIRED")
|
|
|
|
if not row["is_enabled"]:
|
|
raise ValueError("ACCOUNT_DISABLED")
|
|
|
|
sess_id = row.get("auth_session_id") or row.get("id")
|
|
# Update last_seen_at
|
|
conn.execute(
|
|
text("UPDATE auth_sessions SET last_seen_at = :now WHERE id = :id"),
|
|
{"now": now, "id": sess_id}
|
|
)
|
|
|
|
return UserContext(
|
|
id=row["user_id"],
|
|
organization_id=row["organization_id"],
|
|
username=row["username"],
|
|
role=row["role"],
|
|
is_enabled=row["is_enabled"],
|
|
auth_session_id=sess_id,
|
|
access_epoch=row["access_epoch"],
|
|
expires_at=row["expires_at"],
|
|
)
|
|
|
|
def logout(self, raw_token: str | None) -> None:
|
|
"""Revokes the current auth session and closes owned live sessions."""
|
|
if not valid_token(raw_token):
|
|
return
|
|
|
|
token_h = hash_token(raw_token)
|
|
now = datetime.now(timezone.utc)
|
|
|
|
from app.modules.knowledge.service import transaction
|
|
with transaction(self.engine) as conn:
|
|
initial = conn.execute(text("SELECT organization_id FROM auth_sessions WHERE token_hash=:hash"), {"hash": token_h}).mappings().first()
|
|
if initial is None:
|
|
return
|
|
conn.execute(text("SELECT organization_id FROM organization_settings WHERE organization_id=:org FOR UPDATE"), {"org": initial["organization_id"]})
|
|
session = conn.execute(
|
|
text("SELECT id, user_id, organization_id FROM auth_sessions WHERE token_hash = :hash AND revoked_at IS NULL"),
|
|
{"hash": token_h}
|
|
).mappings().first()
|
|
|
|
if not session:
|
|
return
|
|
|
|
conn.execute(
|
|
text("UPDATE auth_sessions SET revoked_at = :now WHERE id = :id"),
|
|
{"now": now, "id": session["id"]}
|
|
)
|
|
|
|
# Close linked active live sessions
|
|
conn.execute(
|
|
text("""
|
|
UPDATE live_sessions
|
|
SET status = 'closed', closed_at = :now, close_reason = 'user_logout', updated_at = :now
|
|
WHERE auth_session_id = :session_id AND status IN ('creating', 'connecting', 'connected')
|
|
"""),
|
|
{"now": now, "session_id": session["id"]}
|
|
)
|
|
|
|
conn.execute(text("""
|
|
UPDATE tool_calls SET status='failed', completed_at=:now, error_code='SESSION_REVOKED'
|
|
WHERE status='running' AND live_session_id IN
|
|
(SELECT id FROM live_sessions WHERE auth_session_id=:auth)
|
|
"""), {'now': now, 'auth': session['id']})
|
|
from app.modules.voice.registry import notify
|
|
notify(auth_session_id=session['id'])
|