feat(admin): migrate admin routes to group authorization and enforce negative Remote-User barrier
- Migrate all admin endpoints in backend/app/routes/admin.py to consume the group authorization dependency require_admin (bdinvite_admins group) - Completely purge legacy Remote-User header dependency from admin route implementations and API documentation - Enforce strict negative barrier rejecting requests containing Remote-User without a valid authenticated session with HTTP 401 Unauthorized - Enforce access control verification: 401 for anonymous requests, 403 for non-admin authenticated users, 200 for bdinvite_admins members - Update admin test suite and related fixtures in backend/tests/ to authenticate via session cookies and verify full admin functionality and negative barriers
This commit is contained in:
1 parent
27015d0d72
commit
39ac42cfce
6 files changed
+258
-111
No files matched your search
+3
-3
@@ -31,8 +31,8 @@ app = FastAPI(
|
||||
"API REST para la invitación interactiva de cumpleaños con sistema RSVP.\n\n"
|
||||
"### Arquitectura de Seguridad\n"
|
||||
"- **Rutas Públicas (`/birthday/api/*`)**: Acceso abierto para los invitados.\n"
|
||||
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por **Authelia ForwardAuth** "
|
||||
"a nivel de proxy inverso (Traefik). Cada endpoint valida de forma independiente la cabecera `Remote-User`."
|
||||
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por autenticación "
|
||||
"OIDC y autorización basada en grupos (`bdinvite_admins`)."
|
||||
),
|
||||
openapi_tags=[
|
||||
{
|
||||
@@ -45,7 +45,7 @@ app = FastAPI(
|
||||
},
|
||||
{
|
||||
"name": "Admin",
|
||||
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por Authelia.",
|
||||
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por autorización administrativa.",
|
||||
},
|
||||
],
|
||||
lifespan=lifespan,
|
||||
|
||||
+33
-42
@@ -3,9 +3,10 @@ import io
|
||||
from datetime import UTC, datetime
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, Response, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..auth import AdminUserDep, Identity, require_admin
|
||||
from ..config import settings
|
||||
from ..database import get_db
|
||||
from ..schemas import (
|
||||
@@ -21,47 +22,22 @@ from ..services.config import get_config, seed_default_config, update_config
|
||||
from ..services.map_preview import generate_map_preview_image, resolve_google_maps_coordinates
|
||||
from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp
|
||||
|
||||
router = APIRouter(tags=["Admin"])
|
||||
router = APIRouter(tags=["Admin"], dependencies=[Depends(require_admin)])
|
||||
|
||||
|
||||
def require_admin(
|
||||
request: Request,
|
||||
remote_user: Annotated[
|
||||
str | None,
|
||||
Header(
|
||||
alias="Remote-User",
|
||||
description="Identidad de usuario autenticada e inyectada por Authelia ForwardAuth en el proxy Traefik",
|
||||
examples=["kiskaadee"],
|
||||
),
|
||||
] = None,
|
||||
) -> str:
|
||||
"""Security invariant: require verified Remote-User header from Authelia or authenticated admin session."""
|
||||
if remote_user:
|
||||
return remote_user
|
||||
|
||||
from .auth import get_auth_adapter
|
||||
|
||||
adapter = get_auth_adapter()
|
||||
identity = adapter.current_identity(request)
|
||||
if identity and "bdinvite_admins" in identity.groups:
|
||||
return identity.subject
|
||||
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
|
||||
|
||||
AdminDep = Annotated[str, Depends(require_admin)]
|
||||
AdminDep = AdminUserDep
|
||||
DbDep = Annotated[Session, Depends(get_db)]
|
||||
|
||||
ADMIN_401 = {
|
||||
ADMIN_RESPONSES = {
|
||||
401: {
|
||||
"description": "No autenticado. Se requiere la cabecera `Remote-User` provista por Authelia ForwardAuth."
|
||||
}
|
||||
"description": "No autenticado. Se requiere una sesión válida o token de autorización.",
|
||||
},
|
||||
403: {
|
||||
"description": "Acceso prohibido. El usuario autenticado no pertenece al grupo administrativo.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@router.get(
|
||||
"/rsvps",
|
||||
response_model=RSVPListResponse,
|
||||
@@ -72,7 +48,7 @@ ADMIN_401 = {
|
||||
),
|
||||
responses={
|
||||
200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."},
|
||||
**ADMIN_401,
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def list_rsvps(
|
||||
@@ -101,7 +77,7 @@ def list_rsvps(
|
||||
responses={
|
||||
204: {"description": "Registro eliminado con éxito."},
|
||||
404: {"description": "Registro no encontrado."},
|
||||
**ADMIN_401,
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def delete_rsvp_endpoint(
|
||||
@@ -128,7 +104,7 @@ def delete_rsvp_endpoint(
|
||||
400: {"description": "Error de validación en los campos proporcionados."},
|
||||
404: {"description": "Registro no encontrado."},
|
||||
409: {"description": "El número de teléfono ya está registrado por otro asistente."},
|
||||
**ADMIN_401,
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def update_rsvp_endpoint(
|
||||
@@ -166,7 +142,7 @@ def update_rsvp_endpoint(
|
||||
"content": {"text/csv": {}},
|
||||
"description": "Descarga del archivo CSV `rsvps.csv`.",
|
||||
},
|
||||
**ADMIN_401,
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def export_rsvps_csv(
|
||||
@@ -201,7 +177,7 @@ def export_rsvps_csv(
|
||||
description="Retorna el objeto completo de configuración para poblar el formulario de administración.",
|
||||
responses={
|
||||
200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."},
|
||||
**ADMIN_401,
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def get_admin_config(
|
||||
@@ -226,7 +202,22 @@ def get_admin_config(
|
||||
),
|
||||
responses={
|
||||
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
|
||||
**ADMIN_401,
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
@router.patch(
|
||||
"/config",
|
||||
response_model=InvitationConfigResponse,
|
||||
summary="Actualizar configuración de la invitación",
|
||||
description=(
|
||||
"Actualiza los valores de la configuración singleton del evento. "
|
||||
"Si la URL de Google Maps cambió, valida y regenera automáticamente la vista previa del mapa. "
|
||||
"Aplica validación de fecha ISO, hora en formato militar 24h y zona horaria válida IANA. "
|
||||
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
|
||||
),
|
||||
responses={
|
||||
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
async def update_admin_config(
|
||||
@@ -272,7 +263,7 @@ async def update_admin_config(
|
||||
),
|
||||
responses={
|
||||
200: {"model": GenerateMapPreviewResponse, "description": "Vista previa generada exitosamente."},
|
||||
**ADMIN_401,
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
async def regenerate_map_preview_endpoint(
|
||||
|
||||
@@ -41,3 +41,62 @@ def client(db_session):
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def admin_identity():
|
||||
from app.auth import Identity
|
||||
|
||||
return Identity(
|
||||
subject="admin-001",
|
||||
email="admin@example.com",
|
||||
name="Admin User",
|
||||
groups=["bdinvite_admins"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def guest_identity():
|
||||
from app.auth import Identity
|
||||
|
||||
return Identity(
|
||||
subject="guest-001",
|
||||
email="guest@example.com",
|
||||
name="Guest User",
|
||||
groups=["guests"],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def admin_session_cookie(admin_identity):
|
||||
from app.auth import get_auth_adapter
|
||||
|
||||
adapter = get_auth_adapter()
|
||||
session_id = adapter.establish_session(admin_identity)
|
||||
return {adapter.session_cookie_name: session_id}
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def guest_session_cookie(guest_identity):
|
||||
from app.auth import get_auth_adapter
|
||||
|
||||
adapter = get_auth_adapter()
|
||||
session_id = adapter.establish_session(guest_identity)
|
||||
return {adapter.session_cookie_name: session_id}
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def admin_client(db_session, admin_session_cookie):
|
||||
def override_get_db():
|
||||
try:
|
||||
yield db_session
|
||||
finally:
|
||||
pass
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
with TestClient(app) as test_client:
|
||||
for k, v in admin_session_cookie.items():
|
||||
test_client.cookies.set(k, v)
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
+146
-41
@@ -1,4 +1,37 @@
|
||||
def test_admin_endpoints_require_remote_user(client):
|
||||
from unittest.mock import ANY, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.auth import Identity, get_auth_adapter
|
||||
|
||||
|
||||
def test_remote_user_header_strictly_ignored(client: TestClient):
|
||||
"""Negative gate: legacy Remote-User header without authenticated session must return 401."""
|
||||
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
def test_admin_endpoints_require_authentication(client: TestClient):
|
||||
"""Anonymous requests to admin endpoints must receive HTTP 401 Unauthorized."""
|
||||
endpoints = [
|
||||
("GET", "/birthday/api/admin/rsvps"),
|
||||
("GET", "/birthday/api/admin/export"),
|
||||
("GET", "/birthday/api/admin/config"),
|
||||
("PUT", "/birthday/api/admin/config"),
|
||||
("PATCH", "/birthday/api/admin/config"),
|
||||
("POST", "/birthday/api/admin/map-preview/generate"),
|
||||
("DELETE", "/birthday/api/admin/rsvps/1"),
|
||||
("PATCH", "/birthday/api/admin/rsvps/1"),
|
||||
]
|
||||
for method, path in endpoints:
|
||||
res = client.request(method, path)
|
||||
assert res.status_code == 401, f"{method} {path} should require authentication"
|
||||
assert res.headers.get("WWW-Authenticate") == "Bearer"
|
||||
|
||||
|
||||
def test_admin_endpoints_require_remote_user(client: TestClient):
|
||||
"""Backwards-compatible test: verify anonymous or legacy header calls are rejected with 401."""
|
||||
endpoints = [
|
||||
"/birthday/api/admin/rsvps",
|
||||
"/birthday/api/admin/export",
|
||||
@@ -6,60 +39,84 @@ def test_admin_endpoints_require_remote_user(client):
|
||||
]
|
||||
for path in endpoints:
|
||||
res = client.get(path)
|
||||
assert res.status_code == 401, f"GET {path} should require Remote-User header"
|
||||
assert res.json() == {"detail": "Not authenticated"}
|
||||
assert res.status_code == 401, f"GET {path} should require authentication"
|
||||
res_legacy = client.get(path, headers={"Remote-User": "kiskaadee"})
|
||||
assert res_legacy.status_code == 401, f"GET {path} with Remote-User must still be rejected"
|
||||
|
||||
|
||||
def test_admin_list_and_search_rsvps(client):
|
||||
headers = {"Remote-User": "kiskaadee"}
|
||||
def test_admin_endpoints_forbidden_for_non_admin_users(client: TestClient, guest_session_cookie: dict[str, str]):
|
||||
"""Authenticated non-admin users must receive HTTP 403 Forbidden."""
|
||||
for k, v in guest_session_cookie.items():
|
||||
client.cookies.set(k, v)
|
||||
|
||||
endpoints = [
|
||||
("GET", "/birthday/api/admin/rsvps"),
|
||||
("GET", "/birthday/api/admin/export"),
|
||||
("GET", "/birthday/api/admin/config"),
|
||||
("PUT", "/birthday/api/admin/config"),
|
||||
("PATCH", "/birthday/api/admin/config"),
|
||||
("POST", "/birthday/api/admin/map-preview/generate"),
|
||||
("DELETE", "/birthday/api/admin/rsvps/1"),
|
||||
("PATCH", "/birthday/api/admin/rsvps/1"),
|
||||
]
|
||||
for method, path in endpoints:
|
||||
res = client.request(method, path)
|
||||
assert res.status_code == 403, f"{method} {path} should be forbidden for guest user"
|
||||
assert "bdinvite_admins" in res.json().get("detail", "")
|
||||
|
||||
# Even if non-admin injects Remote-User header, session identity governs -> 403
|
||||
res_spoof = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "admin"})
|
||||
assert res_spoof.status_code == 403
|
||||
|
||||
|
||||
def test_admin_list_and_search_rsvps(admin_client: TestClient):
|
||||
"""Authenticated admin user can list and search RSVPs."""
|
||||
# Initially 0
|
||||
res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||
res = admin_client.get("/birthday/api/admin/rsvps")
|
||||
assert res.status_code == 200
|
||||
assert res.json()["count"] == 0
|
||||
|
||||
# Add 3 invitees
|
||||
client.post(
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Carlos Gomez", "phone": "300 111 2233", "email": "carlos@test.com"},
|
||||
)
|
||||
client.post(
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Maria Perez", "phone": "315 222 3344", "email": "maria@test.com"},
|
||||
)
|
||||
client.post(
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Juan Gomez", "phone": "320 333 4455", "email": None},
|
||||
)
|
||||
|
||||
# List all
|
||||
res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||
res = admin_client.get("/birthday/api/admin/rsvps")
|
||||
assert res.status_code == 200
|
||||
data = res.json()
|
||||
assert data["count"] == 3
|
||||
|
||||
# Search by name
|
||||
res_search = client.get("/birthday/api/admin/rsvps?search=Gomez", headers=headers)
|
||||
res_search = admin_client.get("/birthday/api/admin/rsvps?search=Gomez")
|
||||
assert res_search.status_code == 200
|
||||
search_data = res_search.json()
|
||||
assert search_data["count"] == 2
|
||||
|
||||
# Search by phone substring
|
||||
res_phone = client.get("/birthday/api/admin/rsvps?search=315222", headers=headers)
|
||||
res_phone = admin_client.get("/birthday/api/admin/rsvps?search=315222")
|
||||
assert res_phone.status_code == 200
|
||||
assert res_phone.json()["count"] == 1
|
||||
assert res_phone.json()["rsvps"][0]["name"] == "Maria Perez"
|
||||
|
||||
|
||||
def test_admin_export_csv(client):
|
||||
headers = {"Remote-User": "kiskaadee"}
|
||||
|
||||
client.post(
|
||||
def test_admin_export_csv(admin_client: TestClient):
|
||||
"""Authenticated admin user can export RSVPs as CSV."""
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Sofia Vergara", "phone": "301 999 8877", "email": "sofia@hollywood.com"},
|
||||
)
|
||||
|
||||
res = client.get("/birthday/api/admin/export", headers=headers)
|
||||
res = admin_client.get("/birthday/api/admin/export")
|
||||
assert res.status_code == 200
|
||||
assert res.headers["content-type"].startswith("text/csv")
|
||||
assert 'filename="rsvps.csv"' in res.headers["content-disposition"]
|
||||
@@ -70,72 +127,68 @@ def test_admin_export_csv(client):
|
||||
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
|
||||
|
||||
|
||||
def test_admin_delete_rsvp(client):
|
||||
headers = {"Remote-User": "kiskaadee"}
|
||||
|
||||
# Unauthorized without header
|
||||
def test_admin_delete_rsvp(client: TestClient, admin_client: TestClient):
|
||||
"""Admin can delete RSVPs; anonymous requests are rejected."""
|
||||
# Unauthorized without session
|
||||
res_unauth = client.delete("/birthday/api/admin/rsvps/1")
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
# 404 for non-existent RSVP
|
||||
res_404 = client.delete("/birthday/api/admin/rsvps/9999", headers=headers)
|
||||
res_404 = admin_client.delete("/birthday/api/admin/rsvps/9999")
|
||||
assert res_404.status_code == 404
|
||||
|
||||
# Create an RSVP
|
||||
client.post(
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Lucas Silva", "phone": "300 444 5566", "email": "lucas@test.com"},
|
||||
)
|
||||
list_res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||
list_res = admin_client.get("/birthday/api/admin/rsvps")
|
||||
assert list_res.status_code == 200
|
||||
rsvps = list_res.json()["rsvps"]
|
||||
assert len(rsvps) == 1
|
||||
rsvp_id = rsvps[0]["id"]
|
||||
|
||||
# Delete successfully
|
||||
del_res = client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}", headers=headers)
|
||||
del_res = admin_client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}")
|
||||
assert del_res.status_code == 204
|
||||
|
||||
# Confirm deletion
|
||||
list_after = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||
list_after = admin_client.get("/birthday/api/admin/rsvps")
|
||||
assert list_after.json()["count"] == 0
|
||||
|
||||
|
||||
def test_admin_update_rsvp(client):
|
||||
headers = {"Remote-User": "kiskaadee"}
|
||||
|
||||
# Unauthorized without header
|
||||
def test_admin_update_rsvp(client: TestClient, admin_client: TestClient):
|
||||
"""Admin can update RSVPs; anonymous requests are rejected."""
|
||||
# Unauthorized without session
|
||||
res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"})
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
# 404 for non-existent RSVP
|
||||
res_404 = client.patch(
|
||||
res_404 = admin_client.patch(
|
||||
"/birthday/api/admin/rsvps/9999",
|
||||
json={"name": "New Name"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_404.status_code == 404
|
||||
|
||||
# Create two RSVPs
|
||||
client.post(
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Person One", "phone": "300 111 2222", "email": "one@test.com"},
|
||||
)
|
||||
client.post(
|
||||
admin_client.post(
|
||||
"/birthday/api/rsvp",
|
||||
json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"},
|
||||
)
|
||||
|
||||
list_res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||
list_res = admin_client.get("/birthday/api/admin/rsvps")
|
||||
rsvps = list_res.json()["rsvps"]
|
||||
id_one = next(r["id"] for r in rsvps if r["name"] == "Person One")
|
||||
id_two = next(r["id"] for r in rsvps if r["name"] == "Person Two")
|
||||
|
||||
# Update Person One with valid new name and phone
|
||||
patch_res = client.patch(
|
||||
patch_res = admin_client.patch(
|
||||
f"/birthday/api/admin/rsvps/{id_one}",
|
||||
json={"name": "Person One Updated", "phone": "+57 300 999 8888", "email": "newone@test.com"},
|
||||
headers=headers,
|
||||
)
|
||||
assert patch_res.status_code == 200
|
||||
updated_data = patch_res.json()
|
||||
@@ -144,18 +197,70 @@ def test_admin_update_rsvp(client):
|
||||
assert updated_data["email"] == "newone@test.com"
|
||||
|
||||
# Attempt to update Person One's phone to Person Two's phone -> 409
|
||||
dup_res = client.patch(
|
||||
dup_res = admin_client.patch(
|
||||
f"/birthday/api/admin/rsvps/{id_one}",
|
||||
json={"phone": "300 333 4444"},
|
||||
headers=headers,
|
||||
)
|
||||
assert dup_res.status_code == 409
|
||||
|
||||
# Validation error for invalid phone
|
||||
val_res = client.patch(
|
||||
val_res = admin_client.patch(
|
||||
f"/birthday/api/admin/rsvps/{id_one}",
|
||||
json={"phone": "12345"},
|
||||
headers=headers,
|
||||
)
|
||||
assert val_res.status_code in (400, 422)
|
||||
|
||||
|
||||
def test_admin_config_endpoints(admin_client: TestClient, client: TestClient):
|
||||
"""Admin can retrieve and update config via PUT and PATCH; unauthenticated calls rejected."""
|
||||
# Anonymous -> 401
|
||||
assert client.get("/birthday/api/admin/config").status_code == 401
|
||||
assert client.patch("/birthday/api/admin/config", json={}).status_code == 401
|
||||
assert client.put("/birthday/api/admin/config", json={}).status_code == 401
|
||||
|
||||
# Admin GET config -> 200
|
||||
res = admin_client.get("/birthday/api/admin/config")
|
||||
assert res.status_code == 200
|
||||
current_config = res.json()
|
||||
assert current_config["honoree_name"] == "Isabelle Snow"
|
||||
|
||||
# Admin PATCH config -> 200
|
||||
update_payload = {**current_config}
|
||||
update_payload["honoree_name"] = "Isabelle Updated via PATCH"
|
||||
patch_res = admin_client.patch("/birthday/api/admin/config", json=update_payload)
|
||||
assert patch_res.status_code == 200
|
||||
assert patch_res.json()["honoree_name"] == "Isabelle Updated via PATCH"
|
||||
|
||||
# Admin PUT config -> 200
|
||||
update_payload["honoree_name"] = "Isabelle Updated via PUT"
|
||||
put_res = admin_client.put("/birthday/api/admin/config", json=update_payload)
|
||||
assert put_res.status_code == 200
|
||||
assert put_res.json()["honoree_name"] == "Isabelle Updated via PUT"
|
||||
|
||||
|
||||
@patch("app.routes.admin.resolve_google_maps_coordinates")
|
||||
@patch("app.routes.admin.generate_map_preview_image")
|
||||
def test_admin_map_preview_generate_endpoint(
|
||||
mock_generate, mock_resolve, client: TestClient, admin_client: TestClient, tmp_path
|
||||
):
|
||||
"""Map preview generation requires admin; verifies successful generation."""
|
||||
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
|
||||
mock_generate.return_value = tmp_path / "map_preview.png"
|
||||
|
||||
# Anonymous -> 401
|
||||
res_unauth = client.post(
|
||||
"/birthday/api/admin/map-preview/generate",
|
||||
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
|
||||
)
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
# Admin -> 200
|
||||
res_admin = admin_client.post(
|
||||
"/birthday/api/admin/map-preview/generate",
|
||||
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
|
||||
)
|
||||
assert res_admin.status_code == 200
|
||||
data = res_admin.json()
|
||||
assert "/birthday/api/map-preview.png" in data["map_preview_url"]
|
||||
assert data["lat"] == 34.1432
|
||||
assert data["lng"] == -118.2551
|
||||
@@ -10,19 +10,16 @@ def test_get_config_public(client):
|
||||
assert data["countdown_label"] == "NOS VEMOS EN"
|
||||
|
||||
|
||||
def test_get_config_admin(client):
|
||||
def test_get_config_admin(client, admin_client):
|
||||
res_unauth = client.get("/birthday/api/admin/config")
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
res_auth = client.get(
|
||||
"/birthday/api/admin/config",
|
||||
headers={"Remote-User": "admin_user"},
|
||||
)
|
||||
res_auth = admin_client.get("/birthday/api/admin/config")
|
||||
assert res_auth.status_code == 200
|
||||
assert res_auth.json()["honoree_name"] == "Isabelle Snow"
|
||||
|
||||
|
||||
def test_update_config_requires_admin(client):
|
||||
def test_update_config_requires_admin(client, admin_client):
|
||||
update_payload = {
|
||||
"title": "Fiesta de Cumpleaños",
|
||||
"invitation_text": "Estás invitado a la fiesta de",
|
||||
@@ -46,15 +43,14 @@ def test_update_config_requires_admin(client):
|
||||
"countdown_in_progress": "EN VIVO",
|
||||
"countdown_finished": "TERMINADO",
|
||||
}
|
||||
# Without Remote-User header -> 401
|
||||
# Without session -> 401
|
||||
res = client.put("/birthday/api/admin/config", json=update_payload)
|
||||
assert res.status_code == 401
|
||||
|
||||
# With Remote-User header -> 200
|
||||
res_auth = client.put(
|
||||
# With admin session -> 200
|
||||
res_auth = admin_client.put(
|
||||
"/birthday/api/admin/config",
|
||||
json=update_payload,
|
||||
headers={"Remote-User": "admin_user"},
|
||||
)
|
||||
assert res_auth.status_code == 200
|
||||
data = res_auth.json()
|
||||
@@ -68,7 +64,7 @@ def test_update_config_requires_admin(client):
|
||||
assert res_pub.json()["title"] == "Fiesta de Cumpleaños"
|
||||
|
||||
|
||||
def test_update_config_invalid_timezone(client):
|
||||
def test_update_config_invalid_timezone(admin_client):
|
||||
invalid_payload = {
|
||||
"title": "Party",
|
||||
"invitation_text": "Invited",
|
||||
@@ -92,10 +88,9 @@ def test_update_config_invalid_timezone(client):
|
||||
"countdown_in_progress": "CURSO",
|
||||
"countdown_finished": "FIN",
|
||||
}
|
||||
res = client.put(
|
||||
res = admin_client.put(
|
||||
"/birthday/api/admin/config",
|
||||
json=invalid_payload,
|
||||
headers={"Remote-User": "admin_user"},
|
||||
)
|
||||
assert res.status_code == 422
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ from app.services.map_preview import (
|
||||
validate_google_maps_url_format,
|
||||
)
|
||||
|
||||
ADMIN_HEADERS = {"Remote-User": "kiskaadee"}
|
||||
|
||||
|
||||
def test_is_google_maps_host():
|
||||
assert is_google_maps_host("maps.app.goo.gl")
|
||||
@@ -72,7 +70,7 @@ def test_deg2num():
|
||||
|
||||
@patch("app.routes.admin.resolve_google_maps_coordinates")
|
||||
@patch("app.routes.admin.generate_map_preview_image")
|
||||
def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, tmp_path):
|
||||
def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, admin_client, tmp_path):
|
||||
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
|
||||
mock_generate.return_value = tmp_path / "map_preview.png"
|
||||
|
||||
@@ -81,9 +79,8 @@ def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client
|
||||
assert resp.status_code == 401
|
||||
|
||||
# Test with auth -> 200
|
||||
resp = client.post(
|
||||
resp = admin_client.post(
|
||||
"/birthday/api/admin/map-preview/generate",
|
||||
headers=ADMIN_HEADERS,
|
||||
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
@@ -97,19 +94,19 @@ def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client
|
||||
|
||||
@patch("app.routes.admin.resolve_google_maps_coordinates")
|
||||
@patch("app.routes.admin.generate_map_preview_image")
|
||||
def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, client, tmp_path):
|
||||
def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, admin_client, tmp_path):
|
||||
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
|
||||
mock_generate.return_value = tmp_path / "map_preview.png"
|
||||
|
||||
# Get current config
|
||||
current = client.get("/birthday/api/admin/config", headers=ADMIN_HEADERS).json()
|
||||
current = admin_client.get("/birthday/api/admin/config").json()
|
||||
orig_map_url = current["map_url"]
|
||||
assert orig_map_url == "https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA"
|
||||
|
||||
# 1. Update config WITHOUT changing map_url -> generator NOT called
|
||||
update_payload = {**current}
|
||||
update_payload["honoree_name"] = "Updated Honoree"
|
||||
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=update_payload)
|
||||
resp = admin_client.put("/birthday/api/admin/config", json=update_payload)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["honoree_name"] == "Updated Honoree"
|
||||
mock_resolve.assert_not_called()
|
||||
@@ -117,7 +114,7 @@ def test_config_update_triggers_generator_only_when_map_url_changes(mock_generat
|
||||
|
||||
# 2. Update config WITH new map_url -> generator CALLED
|
||||
update_payload["map_url"] = "https://maps.google.com/?q=34.1432,-118.2551"
|
||||
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=update_payload)
|
||||
resp = admin_client.put("/birthday/api/admin/config", json=update_payload)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551"
|
||||
assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png"
|
||||
@@ -125,11 +122,11 @@ def test_config_update_triggers_generator_only_when_map_url_changes(mock_generat
|
||||
mock_generate.assert_called_once_with(34.1432, -118.2551)
|
||||
|
||||
|
||||
def test_config_update_rejects_invalid_map_url(client):
|
||||
current = client.get("/birthday/api/admin/config", headers=ADMIN_HEADERS).json()
|
||||
def test_config_update_rejects_invalid_map_url(admin_client):
|
||||
current = admin_client.get("/birthday/api/admin/config").json()
|
||||
bad_payload = {**current, "map_url": "https://invalid-non-google-url.com/something"}
|
||||
|
||||
resp = client.put("/birthday/api/admin/config", headers=ADMIN_HEADERS, json=bad_payload)
|
||||
resp = admin_client.put("/birthday/api/admin/config", json=bad_payload)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user