From 5fb8ea445dd9b5bad3f12205c3fb3b5564f240b5 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 19 Oct 2026 00:12:40 -0500 Subject: [PATCH] feat(auth): implement Google OAuth2 flow, HMAC session guard, and Turso admin_allowlist audit log - Add /auth/google/login, /auth/google/callback, /auth/me, /auth/logout, /auth/allowlist, and /auth/audit-log endpoints. - Verify authenticated operator sessions against Turso admin_allowlist (is_active = 1) on every protected request. - Record all administrative mutations in admin_audit_log. Refs: #3 --- app/core/auth.py | 172 ++++++++++++++++++++++++ app/core/config.py | 29 ++-- app/routers/auth.py | 320 ++++++++++++++++++++++++++++++++++++++++++++ app/schemas/auth.py | 38 ++++++ 4 files changed, 551 insertions(+), 8 deletions(-) create mode 100644 app/core/auth.py create mode 100644 app/routers/auth.py create mode 100644 app/schemas/auth.py diff --git a/app/core/auth.py b/app/core/auth.py new file mode 100644 index 0000000..8662fc7 --- /dev/null +++ b/app/core/auth.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import time +import uuid +from datetime import UTC, datetime +from typing import Any + +import libsql_client +from fastapi import HTTPException, Request, status + +from app.core.config import settings +from app.db.database import get_db, row_to_dict +from app.schemas.auth import AdminPrincipal + +SESSION_COOKIE_NAME = "armonia_session" +OAUTH_STATE_COOKIE_NAME = "armonia_oauth_state" + + +def _b64url_encode(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def _b64url_decode(s: str) -> bytes: + padding = "=" * (-len(s) % 4) + return base64.urlsafe_b64decode(s + padding) + + +def create_session_token(email: str, ttl_seconds: int | None = None) -> str: + """Create an HMAC-SHA256 signed session token for an authenticated admin email.""" + ttl = ttl_seconds if ttl_seconds is not None else settings.session_ttl_seconds + payload = { + "sub": email.strip().lower(), + "iat": int(time.time()), + "exp": int(time.time()) + ttl, + } + payload_b64 = _b64url_encode(json.dumps(payload, separators=(",", ":")).encode("utf-8")) + sig = hmac.new( + settings.session_secret_key.encode("utf-8"), + payload_b64.encode("ascii"), + hashlib.sha256, + ).digest() + sig_b64 = _b64url_encode(sig) + return f"{payload_b64}.{sig_b64}" + + +def verify_session_token(token: str) -> str: + """Verify HMAC-SHA256 signature and expiration, returning the normalized admin email.""" + parts = token.split(".") + if len(parts) != 2: + raise ValueError("Invalid token format") + payload_b64, sig_b64 = parts + expected_sig = hmac.new( + settings.session_secret_key.encode("utf-8"), + payload_b64.encode("ascii"), + hashlib.sha256, + ).digest() + try: + actual_sig = _b64url_decode(sig_b64) + except Exception as exc: + raise ValueError("Invalid token signature encoding") from exc + + if not hmac.compare_digest(expected_sig, actual_sig): + raise ValueError("Token signature mismatch") + + try: + payload = json.loads(_b64url_decode(payload_b64).decode("utf-8")) + except Exception as exc: + raise ValueError("Invalid token payload") from exc + + exp = int(payload.get("exp", 0)) + if time.time() >= exp: + raise ValueError("Session token has expired") + + email = str(payload.get("sub", "")).strip().lower() + if not email: + raise ValueError("Token missing subject email") + return email + + +async def get_allowlisted_admin(client: libsql_client.Client, email: str) -> AdminPrincipal | None: + """Look up an email in Turso's admin_allowlist table and return AdminPrincipal if active.""" + normalized = email.strip().lower() + res = await client.execute( + "SELECT email, full_name, role, is_active, last_login_at FROM admin_allowlist WHERE lower(email) = ? LIMIT 1;", + [normalized], + ) + if not res.rows: + return None + row = row_to_dict(res, res.rows[0]) + if not bool(row.get("is_active", 0)): + return None + return AdminPrincipal( + email=str(row["email"]), + full_name=str(row["full_name"]), + role=row["role"], + is_active=True, + last_login_at=row.get("last_login_at"), + ) + + +async def record_admin_audit( + client: libsql_client.Client, + admin_email: str, + action_type: str, + entity_type: str, + entity_id: str, + details: dict[str, Any] | None = None, +) -> None: + """Write an immutable audit entry to admin_audit_log.""" + audit_id = str(uuid.uuid4()) + now = datetime.now(UTC).isoformat() + details_json = json.dumps(details, ensure_ascii=False) if details else None + await client.execute( + """ + INSERT INTO admin_audit_log (id, admin_email, action_type, entity_type, entity_id, details_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?); + """, + [audit_id, admin_email, action_type, entity_type, entity_id, details_json, now], + ) + + +async def require_admin(request: Request) -> AdminPrincipal: + """ + FastAPI dependency enforcing Google OAuth session token OR dev/service key fallback, + always verified against an active row in Turso's admin_allowlist table. + """ + candidate_email: str | None = None + + # 1. Check Authorization: Bearer or HttpOnly session cookie + auth_header = request.headers.get("Authorization", "") + token: str | None = None + if auth_header.startswith("Bearer "): + token = auth_header.removeprefix("Bearer ").strip() + elif SESSION_COOKIE_NAME in request.cookies: + token = request.cookies.get(SESSION_COOKIE_NAME) + + if token: + try: + candidate_email = verify_session_token(token) + except ValueError as exc: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail=f"Sesión inválida o expirada: {exc}", + ) from exc + else: + # 2. Check X-Admin-Key + X-Admin-Email fallback for automated tests / CLI + admin_key = request.headers.get("X-Admin-Key") + admin_email_hdr = request.headers.get("X-Admin-Email") + if admin_key and hmac.compare_digest(admin_key, settings.admin_api_key): + if admin_email_hdr: + candidate_email = admin_email_hdr.strip().lower() + elif settings.admin_bootstrap_emails: + candidate_email = settings.admin_bootstrap_emails[0].strip().lower() + + if not candidate_email: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Autenticación de administrador requerida (Google OAuth).", + ) + + async with get_db() as client: + principal = await get_allowlisted_admin(client, candidate_email) + if not principal: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"El correo '{candidate_email}' no está autorizado en la lista de administradores activos.", + ) + return principal diff --git a/app/core/config.py b/app/core/config.py index 0c83d58..c650117 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -7,16 +7,16 @@ from pydantic import BeforeValidator from pydantic_settings import BaseSettings, SettingsConfigDict -def _parse_origins(v: str | list[str]) -> list[str]: +def _parse_str_list(v: str | list[str]) -> list[str]: if isinstance(v, str): try: parsed = json.loads(v) if isinstance(parsed, list): - return [str(x) for x in parsed] + return [str(x).strip() for x in parsed if str(x).strip()] except Exception: pass return [x.strip() for x in v.split(",") if x.strip()] - return list(v) + return [str(x).strip() for x in v if str(x).strip()] class Settings(BaseSettings): @@ -34,21 +34,34 @@ class Settings(BaseSettings): environment: str = "development" port: int = 8000 host: str = "0.0.0.0" - cors_origins: Annotated[list[str], BeforeValidator(_parse_origins)] = [ + cors_origins: Annotated[list[str], BeforeValidator(_parse_str_list)] = [ "http://localhost:5173", "http://localhost:3000", ] - # Security + # Security & Google OAuth + Turso Allowlist admin_api_key: str = "dev-secret-key-change-in-production" + session_secret_key: str = "dev-session-secret-change-in-production" + session_ttl_seconds: int = 86400 * 7 # 7 days + google_oauth_client_id: str | None = None + google_oauth_client_secret: str | None = None + google_oauth_redirect_uri: str = "http://localhost:8000/auth/google/callback" + dashboard_origin_url: str = "http://localhost:5173" + admin_bootstrap_emails: Annotated[list[str], BeforeValidator(_parse_str_list)] = [ + "jasmin@armoniadelser.mx", + "asistente@armoniadelser.mx", + ] + + # Operational rules + payment_followup_threshold_hours: int = 48 # Business profile (Armonía del Ser) - therapist_name: str = "Jazmín" + therapist_name: str = "Jasmin" business_name: str = "Armonía del Ser" - whatsapp_phone: str = "521XXXXXXXXXX" + whatsapp_phone: str = "527751487912" spei_clabe: str = "012345678901234567" spei_bank: str = "BBVA" - spei_beneficiary: str = "Jazmín" + spei_beneficiary: str = "Jasmin" # Google Calendar gcal_calendar_id: str = "primary" diff --git a/app/routers/auth.py b/app/routers/auth.py new file mode 100644 index 0000000..30d1e7a --- /dev/null +++ b/app/routers/auth.py @@ -0,0 +1,320 @@ +from __future__ import annotations + +import hmac +import secrets +import urllib.parse +from datetime import UTC, datetime + +import httpx +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status +from fastapi.responses import RedirectResponse + +from app.core.auth import ( + OAUTH_STATE_COOKIE_NAME, + SESSION_COOKIE_NAME, + create_session_token, + get_allowlisted_admin, + record_admin_audit, + require_admin, +) +from app.core.config import settings +from app.db.database import get_db, result_to_dicts, row_to_dict +from app.schemas.auth import ( + AdminAllowlistCreate, + AdminAllowlistUpdate, + AdminPrincipal, + AuditLogRead, +) + +router = APIRouter(prefix="/auth", tags=["Authentication & Admin Allowlist"]) + +GOOGLE_AUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth" +GOOGLE_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" +GOOGLE_USERINFO_ENDPOINT = "https://openidconnect.googleapis.com/v1/userinfo" + + +@router.get("/google/login") +async def google_oauth_login(): + """ + Initiate backend-driven Google OAuth2 Authorization Code flow. + Redirects the administrator to Google's consent screen with a signed CSRF state cookie. + """ + if not settings.google_oauth_client_id or not settings.google_oauth_client_secret: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="Google OAuth credentials are not configured on the backend.", + ) + + state = secrets.token_urlsafe(32) + params = { + "client_id": settings.google_oauth_client_id, + "redirect_uri": settings.google_oauth_redirect_uri, + "response_type": "code", + "scope": "openid email profile", + "state": state, + "prompt": "select_account", + } + url = f"{GOOGLE_AUTH_ENDPOINT}?{urllib.parse.urlencode(params)}" + response = RedirectResponse(url=url, status_code=status.HTTP_302_FOUND) + response.set_cookie( + key=OAUTH_STATE_COOKIE_NAME, + value=state, + httponly=True, + secure=settings.environment == "production", + samesite="lax", + max_age=600, + ) + return response + + +@router.get("/google/callback") +async def google_oauth_callback( + request: Request, + code: str | None = None, + state: str | None = None, +): + """ + Google OAuth2 callback: + 1. Validates CSRF state cookie. + 2. Exchanges authorization code for tokens on the server. + 3. Verifies Google userinfo (email_verified == True). + 4. Checks email against Turso's admin_allowlist table. + 5. Issues an HttpOnly signed session cookie and redirects to armonia-dashboard. + """ + if not code or not state: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Missing code or state parameter in OAuth callback.", + ) + + expected_state = request.cookies.get(OAUTH_STATE_COOKIE_NAME) + if not expected_state or not hmac.compare_digest(expected_state, state): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="Invalid or expired OAuth state parameter.", + ) + + if not settings.google_oauth_client_id or not settings.google_oauth_client_secret: + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="Google OAuth credentials are not configured.", + ) + + async with httpx.AsyncClient(timeout=10.0) as http_client: + token_res = await http_client.post( + GOOGLE_TOKEN_ENDPOINT, + data={ + "code": code, + "client_id": settings.google_oauth_client_id, + "client_secret": settings.google_oauth_client_secret, + "redirect_uri": settings.google_oauth_redirect_uri, + "grant_type": "authorization_code", + }, + ) + if token_res.status_code != 200: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Failed to exchange Google OAuth authorization code.", + ) + token_data = token_res.json() + access_token = token_data.get("access_token") + if not access_token: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Google OAuth response did not include an access token.", + ) + + userinfo_res = await http_client.get( + GOOGLE_USERINFO_ENDPOINT, + headers={"Authorization": f"Bearer {access_token}"}, + ) + if userinfo_res.status_code != 200: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Failed to fetch verified user profile from Google.", + ) + userinfo = userinfo_res.json() + + email = str(userinfo.get("email", "")).strip().lower() + email_verified = bool(userinfo.get("email_verified", False)) + if not email or not email_verified: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Google account email is missing or not verified.", + ) + + async with get_db() as client: + principal = await get_allowlisted_admin(client, email) + if not principal: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail=f"El correo '{email}' no está en la lista de administradores autorizados.", + ) + now = datetime.now(UTC).isoformat() + await client.execute( + "UPDATE admin_allowlist SET last_login_at = ? WHERE lower(email) = ?;", + [now, email], + ) + + session_token = create_session_token(principal.email) + redirect = RedirectResponse( + url=settings.dashboard_origin_url, status_code=status.HTTP_302_FOUND + ) + redirect.delete_cookie(OAUTH_STATE_COOKIE_NAME) + redirect.set_cookie( + key=SESSION_COOKIE_NAME, + value=session_token, + httponly=True, + secure=settings.environment == "production", + samesite="lax", + max_age=settings.session_ttl_seconds, + ) + return redirect + + +@router.get("/me", response_model=AdminPrincipal) +async def get_current_admin(admin: AdminPrincipal = Depends(require_admin)): + """Return the currently authenticated and allowlisted administrator.""" + return admin + + +@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT) +async def logout(response: Response): + """Clear the administrator session cookie.""" + response.delete_cookie(SESSION_COOKIE_NAME) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@router.get("/allowlist", response_model=list[AdminPrincipal]) +async def list_allowlist(admin: AdminPrincipal = Depends(require_admin)): + """List all administrator entries in Turso's admin_allowlist table.""" + async with get_db() as client: + res = await client.execute( + "SELECT email, full_name, role, is_active, last_login_at FROM admin_allowlist ORDER BY created_at ASC;" + ) + rows = result_to_dicts(res) + return [ + AdminPrincipal( + email=str(r["email"]), + full_name=str(r["full_name"]), + role=r["role"], + is_active=bool(r.get("is_active", 0)), + last_login_at=r.get("last_login_at"), + ) + for r in rows + ] + + +@router.post("/allowlist", response_model=AdminPrincipal, status_code=status.HTTP_201_CREATED) +async def add_to_allowlist( + payload: AdminAllowlistCreate, + admin: AdminPrincipal = Depends(require_admin), +): + """Add or reactivate an administrator in Turso's admin_allowlist table.""" + normalized_email = payload.email.strip().lower() + async with get_db() as client: + await client.execute( + """ + INSERT INTO admin_allowlist (email, full_name, role, is_active) + VALUES (?, ?, ?, ?) + ON CONFLICT(email) DO UPDATE SET + full_name = excluded.full_name, + role = excluded.role, + is_active = excluded.is_active; + """, + [normalized_email, payload.full_name, payload.role, 1 if payload.is_active else 0], + ) + await record_admin_audit( + client, + admin_email=admin.email, + action_type="UPSERT_ALLOWLIST", + entity_type="admin_allowlist", + entity_id=normalized_email, + details={"role": payload.role, "is_active": payload.is_active}, + ) + res = await client.execute( + "SELECT email, full_name, role, is_active, last_login_at FROM admin_allowlist WHERE email = ? LIMIT 1;", + [normalized_email], + ) + r = row_to_dict(res, res.rows[0]) + return AdminPrincipal( + email=str(r["email"]), + full_name=str(r["full_name"]), + role=r["role"], + is_active=bool(r.get("is_active", 0)), + last_login_at=r.get("last_login_at"), + ) + + +@router.patch("/allowlist/{email}", response_model=AdminPrincipal) +async def update_allowlist_entry( + email: str, + payload: AdminAllowlistUpdate, + admin: AdminPrincipal = Depends(require_admin), +): + """Update role, name, or active status for an administrator in Turso.""" + normalized_email = email.strip().lower() + async with get_db() as client: + res = await client.execute( + "SELECT * FROM admin_allowlist WHERE lower(email) = ? LIMIT 1;", + [normalized_email], + ) + if not res.rows: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Administrator email not found in allowlist.", + ) + current = row_to_dict(res, res.rows[0]) + new_name = payload.full_name if payload.full_name is not None else current["full_name"] + new_role = payload.role if payload.role is not None else current["role"] + new_active = ( + (1 if payload.is_active else 0) + if payload.is_active is not None + else int(current["is_active"]) + ) + + await client.execute( + "UPDATE admin_allowlist SET full_name = ?, role = ?, is_active = ? WHERE lower(email) = ?;", + [new_name, new_role, new_active, normalized_email], + ) + await record_admin_audit( + client, + admin_email=admin.email, + action_type="UPDATE_ALLOWLIST", + entity_type="admin_allowlist", + entity_id=normalized_email, + details={"full_name": new_name, "role": new_role, "is_active": bool(new_active)}, + ) + updated_res = await client.execute( + "SELECT email, full_name, role, is_active, last_login_at FROM admin_allowlist WHERE lower(email) = ? LIMIT 1;", + [normalized_email], + ) + r = row_to_dict(updated_res, updated_res.rows[0]) + return AdminPrincipal( + email=str(r["email"]), + full_name=str(r["full_name"]), + role=r["role"], + is_active=bool(r.get("is_active", 0)), + last_login_at=r.get("last_login_at"), + ) + + +@router.get("/audit-log", response_model=list[AuditLogRead]) +async def list_audit_log( + entity_id: str | None = None, + limit: int = 50, + admin: AdminPrincipal = Depends(require_admin), +): + """Retrieve recent administrative actions recorded in admin_audit_log.""" + async with get_db() as client: + if entity_id: + res = await client.execute( + "SELECT * FROM admin_audit_log WHERE entity_id = ? ORDER BY created_at DESC LIMIT ?;", + [entity_id, limit], + ) + else: + res = await client.execute( + "SELECT * FROM admin_audit_log ORDER BY created_at DESC LIMIT ?;", + [limit], + ) + return [AuditLogRead(**r) for r in result_to_dicts(res)] diff --git a/app/schemas/auth.py b/app/schemas/auth.py new file mode 100644 index 0000000..7512aa7 --- /dev/null +++ b/app/schemas/auth.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import Literal + +from pydantic import BaseModel, Field + +AdminRole = Literal["OWNER", "ASSISTANT", "ADMIN"] + + +class AdminPrincipal(BaseModel): + email: str + full_name: str + role: AdminRole + is_active: bool = True + last_login_at: str | None = None + + +class AdminAllowlistCreate(BaseModel): + email: str = Field(..., min_length=5) + full_name: str = Field(..., min_length=2) + role: AdminRole = "ASSISTANT" + is_active: bool = True + + +class AdminAllowlistUpdate(BaseModel): + full_name: str | None = None + role: AdminRole | None = None + is_active: bool | None = None + + +class AuditLogRead(BaseModel): + id: str + admin_email: str + action_type: str + entity_type: str + entity_id: str + details_json: str | None = None + created_at: str