feat(auth): decouple auth adapters with proxy-headers forward-auth and JIT mirror

- Introduce AuthProvider strategy (proxy_headers, google_oauth, dev_key) in Settings
- Implement ProxyHeaderAdapter parsing Remote-Email, Remote-Name, and Remote-Groups
- Map LLDAP groups to RoleEnum with highest-privilege precedence
- Mirror proxy-authenticated actors into admin_allowlist on mutating actions to satisfy DB foreign keys (ADR-0006)
- Provide uniform AdminPrincipal injection via require_admin
- Add unit tests for role resolution and integration tests for auth adapter matrix

Refs: #6
This commit is contained in:
kiskaadee committed 2026-10-19 14:12:51 -05:00
1 parent 4652a22b0d
commit 7987fdfa5d
6 files changed
+477 -30

No files matched your search

+136 -29
View File
@@ -7,13 +7,16 @@ import json
import time import time
import uuid import uuid
from datetime import UTC, datetime from datetime import UTC, datetime
from typing import Any from typing import Any, Protocol
import libsql_client import libsql_client
from fastapi import HTTPException, Request, status from fastapi import HTTPException, Request, status
from sqlmodel import Session
from app.core.config import settings from app.core.config import AuthProvider, settings
from app.db.database import get_db, row_to_dict from app.db.database import get_db, get_engine, row_to_dict
from app.models.admin import RoleEnum
from app.repositories.admin import mirror_admin_actor
from app.schemas.auth import AdminPrincipal from app.schemas.auth import AdminPrincipal
SESSION_COOKIE_NAME = "armonia_session" SESSION_COOKIE_NAME = "armonia_session"
@@ -123,50 +126,154 @@ async def record_admin_audit(
) )
async def require_admin(request: Request) -> AdminPrincipal: # --- Pluggable authentication strategy (ADR-0006) ---------------------------------------
""" #
FastAPI dependency enforcing Google OAuth session token OR dev/service key fallback, # Each adapter inspects only its own credentials and returns:
always verified against an active row in Turso's admin_allowlist table. # * AdminPrincipal -> authenticated and authorized
""" # * None -> its credentials are absent (lets require_admin try a fallback / 401)
candidate_email: str | None = None # and raises HTTPException when credentials are present but invalid or unauthorized.
# 1. Check Authorization: Bearer <session_token> or HttpOnly session cookie # Highest privilege first; exact (case-insensitive) LLDAP group names.
PROXY_GROUP_ROLES: tuple[tuple[str, RoleEnum], ...] = (
("armonia-owner", RoleEnum.OWNER),
("armonia-admin", RoleEnum.ADMIN),
("armonia-assistant", RoleEnum.ASSISTANT),
)
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
def resolve_role_from_groups(raw_groups: str | None) -> RoleEnum | None:
"""Map Authelia's comma-separated `Remote-Groups` to the highest-privilege RoleEnum."""
if not raw_groups:
return None
groups = {g.strip().lower() for g in raw_groups.split(",") if g.strip()}
for group_name, role in PROXY_GROUP_ROLES:
if group_name in groups:
return role
return None
class AuthAdapter(Protocol):
async def authenticate(self, request: Request) -> AdminPrincipal | None: ...
async def _require_allowlisted(email: str) -> AdminPrincipal:
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á autorizado en la lista de administradores activos.",
)
return principal
class ProxyHeaderAdapter:
"""
Authelia/LLDAP forward-auth. Identity and role come exclusively from Remote-* headers;
reads perform zero database queries. On unsafe methods the principal is mirrored into
`admin_allowlist` so audited writes keep FK integrity (ADR-0006).
SECURITY: only enable when the API is reachable exclusively through the proxy, which must
strip client-supplied Remote-* headers.
"""
async def authenticate(self, request: Request) -> AdminPrincipal | None:
raw_identity = request.headers.get("Remote-Email") or request.headers.get("Remote-User")
email = (raw_identity or "").strip().lower()
if not email:
return None
role = resolve_role_from_groups(request.headers.get("Remote-Groups"))
if role is None:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"El usuario '{email}' no pertenece a ningún grupo armonia-* autorizado.",
)
full_name = (request.headers.get("Remote-Name") or "").strip() or email
principal = AdminPrincipal(email=email, full_name=full_name, role=role.value)
if request.method.upper() not in SAFE_METHODS:
with Session(get_engine()) as session:
mirror_admin_actor(session, email=email, full_name=full_name, role=role.value)
return principal
class GoogleOAuthAdapter:
"""HMAC session token (Bearer header or HttpOnly cookie) verified against the allowlist."""
async def authenticate(self, request: Request) -> AdminPrincipal | None:
auth_header = request.headers.get("Authorization", "") auth_header = request.headers.get("Authorization", "")
token: str | None = None token: str | None = None
if auth_header.startswith("Bearer "): if auth_header.startswith("Bearer "):
token = auth_header.removeprefix("Bearer ").strip() token = auth_header.removeprefix("Bearer ").strip()
elif SESSION_COOKIE_NAME in request.cookies: elif SESSION_COOKIE_NAME in request.cookies:
token = request.cookies.get(SESSION_COOKIE_NAME) token = request.cookies.get(SESSION_COOKIE_NAME)
if not token:
return None
if token:
try: try:
candidate_email = verify_session_token(token) email = verify_session_token(token)
except ValueError as exc: except ValueError as exc:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Sesión inválida o expirada: {exc}", detail=f"Sesión inválida o expirada: {exc}",
) from exc ) from exc
else: return await _require_allowlisted(email)
# 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:
class DevKeyAdapter:
"""X-Admin-Key (+ optional X-Admin-Email) for tests, CLI, and local dashboard development."""
async def authenticate(self, request: Request) -> AdminPrincipal | None:
admin_key = request.headers.get("X-Admin-Key")
if not admin_key:
return None
if not hmac.compare_digest(admin_key, settings.admin_api_key):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Autenticación de administrador requerida (Google OAuth).", detail="Clave de administrador inválida.",
) )
async with get_db() as client: admin_email_hdr = (request.headers.get("X-Admin-Email") or "").strip().lower()
principal = await get_allowlisted_admin(client, candidate_email) email = admin_email_hdr or (
if not principal: settings.admin_bootstrap_emails[0].strip().lower()
raise HTTPException( if settings.admin_bootstrap_emails
status_code=status.HTTP_403_FORBIDDEN, else ""
detail=f"El correo '{candidate_email}' no está autorizado en la lista de administradores activos.",
) )
if not email:
return None
return await _require_allowlisted(email)
AUTH_ADAPTERS: dict[AuthProvider, AuthAdapter] = {
AuthProvider.PROXY_HEADERS: ProxyHeaderAdapter(),
AuthProvider.GOOGLE_OAUTH: GoogleOAuthAdapter(),
AuthProvider.DEV_KEY: DevKeyAdapter(),
}
def resolve_adapter_chain() -> list[AuthAdapter]:
"""Configured provider first; dev_key fallback only outside production."""
primary = AuthProvider(settings.auth_provider)
chain = [AUTH_ADAPTERS[primary]]
if primary is not AuthProvider.DEV_KEY and settings.environment != "production":
chain.append(AUTH_ADAPTERS[AuthProvider.DEV_KEY])
return chain
async def require_admin(request: Request) -> AdminPrincipal:
"""
FastAPI dependency yielding a uniform AdminPrincipal regardless of identity provider
(`settings.auth_provider`). Routers and services never inspect credentials themselves.
"""
for adapter in resolve_adapter_chain():
principal = await adapter.authenticate(request)
if principal is not None:
return principal return principal
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Autenticación de administrador requerida.",
)
+41 -1
View File
@@ -1,12 +1,21 @@
from __future__ import annotations from __future__ import annotations
import json import json
from enum import StrEnum
from typing import Annotated from typing import Annotated
from pydantic import BeforeValidator from pydantic import BeforeValidator
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
class AuthProvider(StrEnum):
"""Identity source strategy consumed by `app.core.auth.require_admin`."""
PROXY_HEADERS = "proxy_headers"
GOOGLE_OAUTH = "google_oauth"
DEV_KEY = "dev_key"
def _parse_str_list(v: str | list[str]) -> list[str]: def _parse_str_list(v: str | list[str]) -> list[str]:
if isinstance(v, str): if isinstance(v, str):
try: try:
@@ -19,6 +28,18 @@ def _parse_str_list(v: str | list[str]) -> list[str]:
return [str(x).strip() for x in v if str(x).strip()] return [str(x).strip() for x in v if str(x).strip()]
def _parse_int_list(v: str | list[int]) -> list[int]:
if isinstance(v, str):
try:
parsed = json.loads(v)
if isinstance(parsed, list):
return [int(x) for x in parsed]
except Exception:
pass
return [int(x.strip()) for x in v.split(",") if x.strip()]
return [int(x) for x in v]
class Settings(BaseSettings): class Settings(BaseSettings):
model_config = SettingsConfigDict( model_config = SettingsConfigDict(
env_file=".env", env_file=".env",
@@ -39,7 +60,12 @@ class Settings(BaseSettings):
"http://localhost:3000", "http://localhost:3000",
] ]
# Security & Google OAuth + Turso Allowlist # Security & Pluggable Authentication (ADR-0005, ADR-0006)
# proxy_headers: trust Authelia Remote-* headers (API must only be reachable via the proxy)
# google_oauth: HMAC session token/cookie verified against Turso admin_allowlist
# dev_key: X-Admin-Key (+ X-Admin-Email) verified against admin_allowlist
# Outside production, dev_key is also tried as a fallback when the primary finds no credentials.
auth_provider: AuthProvider = AuthProvider.GOOGLE_OAUTH
admin_api_key: str = "dev-secret-key-change-in-production" admin_api_key: str = "dev-secret-key-change-in-production"
session_secret_key: str = "dev-session-secret-change-in-production" session_secret_key: str = "dev-session-secret-change-in-production"
session_ttl_seconds: int = 86400 * 7 # 7 days session_ttl_seconds: int = 86400 * 7 # 7 days
@@ -63,6 +89,20 @@ class Settings(BaseSettings):
spei_bank: str = "BBVA" spei_bank: str = "BBVA"
spei_beneficiary: str = "Jasmin" spei_beneficiary: str = "Jasmin"
# Business hours & availability engine (ADR-0003)
business_timezone: str = "America/Mexico_City"
availability_open_time: str = "09:00"
availability_close_time: str = "19:00"
availability_slot_step_minutes: int = 30
availability_working_weekdays: Annotated[list[int], BeforeValidator(_parse_int_list)] = [
0,
1,
2,
3,
4,
] # Mon-Fri
availability_max_range_days: int = 60
# Google Calendar # Google Calendar
gcal_calendar_id: str = "primary" gcal_calendar_id: str = "primary"
google_service_account_json: str | None = None google_service_account_json: str | None = None
+1
View File
@@ -0,0 +1 @@
"""Persistence boundary for repositories built on SQLModel sessions."""
+35
View File
@@ -0,0 +1,35 @@
from __future__ import annotations
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlmodel import Session
from app.models.admin import AdminAllowlist
from app.services.timestamps import utc_now_iso
def mirror_admin_actor(session: Session, *, email: str, full_name: str, role: str) -> None:
"""
Upsert an externally-authenticated actor (e.g. Authelia proxy user) into `admin_allowlist`
so that actor columns (`admin_audit_log.admin_email`, `payments.acknowledged_by`, ...) keep
referential integrity (ADR-0006).
The identity provider is authoritative for name and role, so both are refreshed on every
write. `is_active` is deliberately left untouched on conflict: mirroring records who acted,
it never re-enables a row an operator disabled.
"""
now = utc_now_iso()
table = AdminAllowlist.__table__ # pyright: ignore[reportAttributeAccessIssue]
stmt = sqlite_insert(table).values(
email=email,
full_name=full_name,
role=role,
is_active=True,
created_at=now,
last_login_at=now,
)
stmt = stmt.on_conflict_do_update(
index_elements=[table.c.email],
set_={"full_name": full_name, "role": role, "last_login_at": now},
)
session.exec(stmt) # pyright: ignore[reportCallIssue, reportArgumentType]
session.commit()
+218
View File
@@ -0,0 +1,218 @@
from __future__ import annotations
import pytest
from sqlmodel import Session, select
from app.core.auth import create_session_token
from app.core.config import AuthProvider, settings
from app.db.database import get_engine
from app.models.admin import AdminAllowlist
OWNER_EMAIL = "jasmin@armoniadelser.mx"
def _proxy_headers(
email: str | None = "operadora@homelab.lan",
groups: str | None = "users,armonia-assistant",
name: str | None = "Operadora Homelab",
*,
user: str | None = None,
) -> dict[str, str]:
headers: dict[str, str] = {}
if email is not None:
headers["Remote-Email"] = email
if user is not None:
headers["Remote-User"] = user
if groups is not None:
headers["Remote-Groups"] = groups
if name is not None:
headers["Remote-Name"] = name
return headers
def _bearer(email: str = OWNER_EMAIL) -> dict[str, str]:
return {"Authorization": f"Bearer {create_session_token(email)}"}
def _dev_key(email: str | None = OWNER_EMAIL, key: str | None = None) -> dict[str, str]:
headers = {"X-Admin-Key": key if key is not None else settings.admin_api_key}
if email is not None:
headers["X-Admin-Email"] = email
return headers
def _allowlist_row(email: str) -> AdminAllowlist | None:
with Session(get_engine()) as session:
return session.exec(select(AdminAllowlist).where(AdminAllowlist.email == email)).first()
@pytest.fixture
def proxy_mode(monkeypatch):
monkeypatch.setattr(settings, "auth_provider", AuthProvider.PROXY_HEADERS)
@pytest.fixture
def production(monkeypatch):
monkeypatch.setattr(settings, "environment", "production")
# --- proxy_headers (Authelia + LLDAP) -------------------------------------------------
def test_proxy_headers_build_principal_from_authelia_headers(client, proxy_mode):
res = client.get("/auth/me", headers=_proxy_headers())
assert res.status_code == 200
body = res.json()
assert body["email"] == "operadora@homelab.lan"
assert body["full_name"] == "Operadora Homelab"
assert body["role"] == "ASSISTANT"
def test_proxy_headers_normalize_email_and_fall_back_to_remote_user(client, proxy_mode):
res = client.get(
"/auth/me",
headers=_proxy_headers(email=None, user=" Owner@Homelab.LAN ", groups="armonia-owner"),
)
assert res.status_code == 200
assert res.json()["email"] == "owner@homelab.lan"
assert res.json()["role"] == "OWNER"
def test_proxy_headers_fall_back_to_email_when_remote_name_missing(client, proxy_mode):
res = client.get("/auth/me", headers=_proxy_headers(name=None))
assert res.status_code == 200
assert res.json()["full_name"] == "operadora@homelab.lan"
def test_proxy_headers_without_identity_are_unauthenticated(client, proxy_mode):
res = client.get("/auth/me", headers=_proxy_headers(email=None, user=None))
assert res.status_code == 401
def test_proxy_headers_without_armonia_group_are_forbidden(client, proxy_mode):
res = client.get("/auth/me", headers=_proxy_headers(groups="users,family"))
assert res.status_code == 403
def test_proxy_headers_reads_never_touch_the_allowlist(client, proxy_mode):
email = "lector.solo@homelab.lan"
res = client.get("/bookings/follow-up-queue", headers=_proxy_headers(email=email))
assert res.status_code == 200
assert _allowlist_row(email) is None
def test_proxy_headers_mirror_principal_into_allowlist_on_first_write(client, proxy_mode):
email = "escritora@homelab.lan"
assert _allowlist_row(email) is None
res = client.post(
"/auth/allowlist",
headers=_proxy_headers(email=email, groups="armonia-owner", name="Escritora"),
json={"email": "nueva.asistente@armoniadelser.mx", "full_name": "Nueva Asistente"},
)
assert res.status_code == 201
mirrored = _allowlist_row(email)
assert mirrored is not None
assert mirrored.role == "OWNER"
assert mirrored.full_name == "Escritora"
assert mirrored.last_login_at is not None
# Audit trail references the mirrored actor (FK target exists)
audit = client.get(
"/auth/audit-log?entity_id=nueva.asistente@armoniadelser.mx",
headers=_proxy_headers(email=email, groups="armonia-owner"),
).json()
assert audit[0]["admin_email"] == email
def test_proxy_mirror_tracks_role_changes_from_lldap(client, proxy_mode):
email = "promovida@homelab.lan"
for groups in ("armonia-assistant", "armonia-admin"):
res = client.patch(
f"/auth/allowlist/{OWNER_EMAIL}",
headers=_proxy_headers(email=email, groups=groups),
json={},
)
assert res.status_code == 200
mirrored = _allowlist_row(email)
assert mirrored is not None
assert mirrored.role == "ADMIN"
def test_proxy_mode_ignores_bearer_tokens_in_production(client, proxy_mode, production):
assert client.get("/auth/me", headers=_bearer()).status_code == 401
def test_proxy_mode_rejects_dev_key_in_production(client, proxy_mode, production):
assert client.get("/auth/me", headers=_dev_key()).status_code == 401
def test_proxy_mode_allows_dev_key_fallback_outside_production(client, proxy_mode):
res = client.get("/auth/me", headers=_dev_key())
assert res.status_code == 200
assert res.json()["email"] == OWNER_EMAIL
# --- google_oauth -------------------------------------------------------------------
def test_google_oauth_ignores_spoofed_proxy_headers(client):
assert settings.auth_provider == AuthProvider.GOOGLE_OAUTH
res = client.get("/auth/me", headers=_proxy_headers(groups="armonia-owner"))
assert res.status_code == 401
def test_google_oauth_rejects_invalid_session_token(client):
res = client.get("/auth/me", headers={"Authorization": "Bearer not.a-valid-token"})
assert res.status_code == 401
def test_google_oauth_accepts_session_cookie(client):
client.cookies.set("armonia_session", create_session_token(OWNER_EMAIL))
try:
res = client.get("/auth/me")
finally:
client.cookies.clear()
assert res.status_code == 200
assert res.json()["role"] == "OWNER"
def test_google_oauth_rejects_dev_key_in_production(client, production):
assert client.get("/auth/me", headers=_dev_key()).status_code == 401
def test_google_oauth_session_still_works_in_production(client, production):
assert client.get("/auth/me", headers=_bearer()).status_code == 200
# --- dev_key ------------------------------------------------------------------------
@pytest.fixture
def dev_key_mode(monkeypatch):
monkeypatch.setattr(settings, "auth_provider", AuthProvider.DEV_KEY)
def test_dev_key_resolves_allowlisted_email(client, dev_key_mode):
res = client.get("/auth/me", headers=_dev_key("asistente@armoniadelser.mx"))
assert res.status_code == 200
assert res.json()["role"] == "ASSISTANT"
def test_dev_key_without_email_uses_first_bootstrap_admin(client, dev_key_mode):
res = client.get("/auth/me", headers=_dev_key(email=None))
assert res.status_code == 200
assert res.json()["email"] == settings.admin_bootstrap_emails[0]
def test_dev_key_with_wrong_key_is_unauthenticated(client, dev_key_mode):
assert client.get("/auth/me", headers=_dev_key(key="wrong-key")).status_code == 401
def test_dev_key_with_non_allowlisted_email_is_forbidden(client, dev_key_mode):
assert client.get("/auth/me", headers=_dev_key("intruder@example.com")).status_code == 403
def test_dev_key_mode_ignores_bearer_tokens(client, dev_key_mode):
assert client.get("/auth/me", headers=_bearer()).status_code == 401
+46
View File
@@ -0,0 +1,46 @@
from __future__ import annotations
import pytest
from app.core.auth import resolve_role_from_groups
from app.models.admin import RoleEnum
@pytest.mark.parametrize(
("raw_groups", "expected"),
[
("armonia-owner", RoleEnum.OWNER),
("armonia-assistant", RoleEnum.ASSISTANT),
("armonia-admin", RoleEnum.ADMIN),
# Authelia emits comma-separated groups; unrelated LLDAP groups are ignored
("users,armonia-assistant,family", RoleEnum.ASSISTANT),
# Whitespace and case from the proxy must not break matching
(" Users , ARMONIA-Owner ", RoleEnum.OWNER),
],
)
def test_resolve_role_maps_lldap_groups_to_roles(raw_groups: str, expected: RoleEnum):
assert resolve_role_from_groups(raw_groups) is expected
@pytest.mark.parametrize(
"raw_groups",
[
"armonia-owner,armonia-assistant",
"armonia-assistant,armonia-owner",
"armonia-admin,armonia-owner,armonia-assistant",
],
)
def test_resolve_role_picks_highest_privilege_regardless_of_order(raw_groups: str):
assert resolve_role_from_groups(raw_groups) is RoleEnum.OWNER
def test_resolve_role_prefers_admin_over_assistant():
assert resolve_role_from_groups("armonia-assistant,armonia-admin") is RoleEnum.ADMIN
@pytest.mark.parametrize(
"raw_groups",
[None, "", " ", "users,admins", "armonia", "armonia-owners", "not-armonia-owner"],
)
def test_resolve_role_returns_none_without_an_exact_armonia_group(raw_groups: str | None):
assert resolve_role_from_groups(raw_groups) is None