feat(admin): migrate admin routes to group authorization and enforce negative Remote-User barrier
- Migrate all admin endpoints in routes/admin.py to consume group authorization dependency (AdminDep / require_admin). - Purge legacy Remote-User header dependency from admin routes and OpenAPI documentation. - Add negative security barrier tests strictly rejecting Remote-User header injection with HTTP 401 when unauthenticated and HTTP 403 when authenticated without admin group. - Update admin test suites, fixtures (admin_client, guest_client, login_client), and configuration/preview tests to authenticate via signed session cookies.
This commit is contained in:
1 parent
f20fb0fc98
commit
b0dea63c3f
6 files changed
+228
-95
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 de sesió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 autenticación y grupo administrativo.",
|
||||
},
|
||||
],
|
||||
lifespan=lifespan,
|
||||
|
||||
+34
-34
@@ -3,9 +3,10 @@ import io
|
||||
from datetime import UTC, datetime
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Response, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..auth import Identity, require_admin
|
||||
from ..config import settings
|
||||
from ..database import get_db
|
||||
from ..schemas import (
|
||||
@@ -18,39 +19,23 @@ from ..schemas import (
|
||||
RSVPUpdate,
|
||||
)
|
||||
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.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"])
|
||||
|
||||
|
||||
def require_admin(
|
||||
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."""
|
||||
if not remote_user:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail="Not authenticated",
|
||||
)
|
||||
return remote_user
|
||||
|
||||
|
||||
AdminDep = Annotated[str, Depends(require_admin)]
|
||||
AdminDep = Annotated[Identity, Depends(require_admin)]
|
||||
DbDep = Annotated[Session, Depends(get_db)]
|
||||
|
||||
ADMIN_401 = {
|
||||
401: {
|
||||
"description": "No autenticado. Se requiere la cabecera `Remote-User` provista por Authelia ForwardAuth."
|
||||
}
|
||||
ADMIN_RESPONSES = {
|
||||
401: {"description": "No autenticado. Se requiere sesión activa de usuario."},
|
||||
403: {"description": "Acceso denegado. Se requiere pertenecer al grupo 'bdinvite_admins'."},
|
||||
}
|
||||
ADMIN_401 = ADMIN_RESPONSES
|
||||
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -63,7 +48,7 @@ ADMIN_401 = {
|
||||
),
|
||||
responses={
|
||||
200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."},
|
||||
**ADMIN_401,
|
||||
**ADMIN_RESPONSES,
|
||||
},
|
||||
)
|
||||
def list_rsvps(
|
||||
@@ -92,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(
|
||||
@@ -119,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(
|
||||
@@ -157,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(
|
||||
@@ -192,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(
|
||||
@@ -217,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=(
|
||||
"Reemplaza 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(
|
||||
@@ -263,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,53 @@ def client(db_session):
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def create_test_session(
|
||||
subject: str = "admin-001",
|
||||
email: str = "admin@example.com",
|
||||
groups: list[str] | None = None,
|
||||
) -> tuple[str, str]:
|
||||
"""Helper to create a valid signed session cookie for testing."""
|
||||
from app.auth import Identity, get_auth_adapter, sign_session_cookie
|
||||
|
||||
if groups is None:
|
||||
groups = ["bdinvite_admins"]
|
||||
adapter = get_auth_adapter()
|
||||
identity = Identity(
|
||||
subject=subject,
|
||||
email=email,
|
||||
groups=groups,
|
||||
)
|
||||
session = adapter.session_store.create_session(identity=identity)
|
||||
signed_cookie = sign_session_cookie(session.session_id, adapter.secret_key)
|
||||
return adapter.session_cookie_name, signed_cookie
|
||||
|
||||
|
||||
def login_client(
|
||||
client: TestClient,
|
||||
subject: str = "admin-001",
|
||||
email: str = "admin@example.com",
|
||||
groups: list[str] | None = None,
|
||||
) -> TestClient:
|
||||
"""Sets a valid session cookie on client for an identity with the given groups."""
|
||||
cookie_name, cookie_value = create_test_session(
|
||||
subject=subject,
|
||||
email=email,
|
||||
groups=groups,
|
||||
)
|
||||
client.cookies.set(cookie_name, cookie_value)
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def admin_client(client: TestClient) -> TestClient:
|
||||
login_client(client, groups=["bdinvite_admins"])
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def guest_client(client: TestClient) -> TestClient:
|
||||
login_client(client, subject="guest-001", email="guest@example.com", groups=["guests"])
|
||||
return client
|
||||
|
||||
+122
-38
@@ -1,65 +1,133 @@
|
||||
def test_admin_endpoints_require_remote_user(client):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.conftest import login_client
|
||||
|
||||
|
||||
def test_admin_endpoints_require_authentication(client: TestClient):
|
||||
"""Anonymous requests to all admin endpoints must receive HTTP 401 Unauthorized."""
|
||||
endpoints = [
|
||||
"/birthday/api/admin/rsvps",
|
||||
"/birthday/api/admin/export",
|
||||
"/birthday/api/admin/config",
|
||||
("GET", "/birthday/api/admin/rsvps"),
|
||||
("DELETE", "/birthday/api/admin/rsvps/1"),
|
||||
("PATCH", "/birthday/api/admin/rsvps/1"),
|
||||
("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"),
|
||||
]
|
||||
for path in endpoints:
|
||||
res = client.get(path)
|
||||
assert res.status_code == 401, f"GET {path} should require Remote-User header"
|
||||
for method, path in endpoints:
|
||||
res = client.request(method, path)
|
||||
assert res.status_code == 401, f"{method} {path} should require authentication"
|
||||
assert res.json() == {"detail": "Not authenticated"}
|
||||
|
||||
|
||||
def test_admin_list_and_search_rsvps(client):
|
||||
headers = {"Remote-User": "kiskaadee"}
|
||||
def test_remote_user_header_strictly_ignored(client: TestClient):
|
||||
"""Legacy Remote-User header without valid authenticated session must be strictly rejected with HTTP 401."""
|
||||
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
|
||||
assert res.status_code == 401
|
||||
assert res.json() == {"detail": "Not authenticated"}
|
||||
|
||||
# Also verify across other admin routes
|
||||
assert client.get("/birthday/api/admin/export", headers={"Remote-User": "kiskaadee"}).status_code == 401
|
||||
assert client.get("/birthday/api/admin/config", headers={"Remote-User": "kiskaadee"}).status_code == 401
|
||||
assert (
|
||||
client.post(
|
||||
"/birthday/api/admin/map-preview/generate",
|
||||
headers={"Remote-User": "kiskaadee"},
|
||||
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
|
||||
).status_code
|
||||
== 401
|
||||
)
|
||||
|
||||
|
||||
def test_admin_endpoints_authenticated_non_admin_forbidden(guest_client: TestClient):
|
||||
"""Authenticated non-admin users (e.g. guest@example.com with groups: ['guests']) must receive HTTP 403 Forbidden."""
|
||||
endpoints = [
|
||||
("GET", "/birthday/api/admin/rsvps"),
|
||||
("DELETE", "/birthday/api/admin/rsvps/1"),
|
||||
("PATCH", "/birthday/api/admin/rsvps/1"),
|
||||
("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"),
|
||||
]
|
||||
for method, path in endpoints:
|
||||
res = guest_client.request(method, path)
|
||||
assert res.status_code == 403, f"{method} {path} should reject non-admin with 403"
|
||||
assert "Forbidden" in res.json()["detail"]
|
||||
|
||||
|
||||
def test_remote_user_header_with_non_admin_session_cannot_elevate_privileges(
|
||||
guest_client: TestClient,
|
||||
):
|
||||
"""An attacker passing Remote-User: admin with a non-admin session cookie must still receive HTTP 403."""
|
||||
res = guest_client.get(
|
||||
"/birthday/api/admin/rsvps",
|
||||
headers={"Remote-User": "admin@example.com", "X-Remote-User": "admin"},
|
||||
)
|
||||
assert res.status_code == 403
|
||||
assert "Forbidden" in res.json()["detail"]
|
||||
|
||||
|
||||
def test_admin_endpoints_authenticated_admin_allowed(admin_client: TestClient):
|
||||
"""Authenticated admin user (admin@example.com with groups: ['bdinvite_admins']) succeeds."""
|
||||
res_rsvps = admin_client.get("/birthday/api/admin/rsvps")
|
||||
assert res_rsvps.status_code == 200
|
||||
|
||||
res_export = admin_client.get("/birthday/api/admin/export")
|
||||
assert res_export.status_code == 200
|
||||
|
||||
res_config = admin_client.get("/birthday/api/admin/config")
|
||||
assert res_config.status_code == 200
|
||||
|
||||
|
||||
def test_admin_list_and_search_rsvps(admin_client: TestClient):
|
||||
# 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):
|
||||
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,15 +138,16 @@ 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):
|
||||
# Unauthorized without session
|
||||
res_unauth = client.delete("/birthday/api/admin/rsvps/1")
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
# Login as admin
|
||||
login_client(client)
|
||||
|
||||
# 404 for non-existent RSVP
|
||||
res_404 = client.delete("/birthday/api/admin/rsvps/9999", headers=headers)
|
||||
res_404 = client.delete("/birthday/api/admin/rsvps/9999")
|
||||
assert res_404.status_code == 404
|
||||
|
||||
# Create an RSVP
|
||||
@@ -86,33 +155,33 @@ def test_admin_delete_rsvp(client):
|
||||
"/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 = 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 = 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 = 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):
|
||||
# Unauthorized without session
|
||||
res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"})
|
||||
assert res_unauth.status_code == 401
|
||||
|
||||
# Login as admin
|
||||
login_client(client)
|
||||
|
||||
# 404 for non-existent RSVP
|
||||
res_404 = client.patch(
|
||||
"/birthday/api/admin/rsvps/9999",
|
||||
json={"name": "New Name"},
|
||||
headers=headers,
|
||||
)
|
||||
assert res_404.status_code == 404
|
||||
|
||||
@@ -126,16 +195,16 @@ def test_admin_update_rsvp(client):
|
||||
json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"},
|
||||
)
|
||||
|
||||
list_res = client.get("/birthday/api/admin/rsvps", headers=headers)
|
||||
list_res = 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")
|
||||
assert id_two is not None
|
||||
|
||||
# Update Person One with valid new name and phone
|
||||
patch_res = 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()
|
||||
@@ -147,7 +216,6 @@ def test_admin_update_rsvp(client):
|
||||
dup_res = client.patch(
|
||||
f"/birthday/api/admin/rsvps/{id_one}",
|
||||
json={"phone": "300 333 4444"},
|
||||
headers=headers,
|
||||
)
|
||||
assert dup_res.status_code == 409
|
||||
|
||||
@@ -155,7 +223,23 @@ def test_admin_update_rsvp(client):
|
||||
val_res = 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_put_and_patch(admin_client: TestClient):
|
||||
"""Both PUT and PATCH /birthday/api/admin/config succeed for authorized admins."""
|
||||
current = admin_client.get("/birthday/api/admin/config").json()
|
||||
assert current["honoree_name"] == "Isabelle Snow"
|
||||
|
||||
# Test PUT
|
||||
payload_put = {**current, "honoree_name": "Isabelle PUT"}
|
||||
res_put = admin_client.put("/birthday/api/admin/config", json=payload_put)
|
||||
assert res_put.status_code == 200
|
||||
assert res_put.json()["honoree_name"] == "Isabelle PUT"
|
||||
|
||||
# Test PATCH
|
||||
payload_patch = {**current, "honoree_name": "Isabelle PATCH"}
|
||||
res_patch = admin_client.patch("/birthday/api/admin/config", json=payload_patch)
|
||||
assert res_patch.status_code == 200
|
||||
assert res_patch.json()["honoree_name"] == "Isabelle PATCH"
|
||||
@@ -1,3 +1,6 @@
|
||||
from tests.conftest import login_client
|
||||
|
||||
|
||||
def test_get_config_public(client):
|
||||
response = client.get("/birthday/api/config")
|
||||
assert response.status_code == 200
|
||||
@@ -14,10 +17,8 @@ def test_get_config_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"},
|
||||
)
|
||||
login_client(client)
|
||||
res_auth = client.get("/birthday/api/admin/config")
|
||||
assert res_auth.status_code == 200
|
||||
assert res_auth.json()["honoree_name"] == "Isabelle Snow"
|
||||
|
||||
@@ -46,15 +47,15 @@ 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
|
||||
# With admin session -> 200
|
||||
login_client(client)
|
||||
res_auth = 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 +69,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 +93,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
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from unittest.mock import ANY, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import settings
|
||||
from app.services.map_preview import (
|
||||
deg2num,
|
||||
@@ -10,7 +9,7 @@ from app.services.map_preview import (
|
||||
validate_google_maps_url_format,
|
||||
)
|
||||
|
||||
ADMIN_HEADERS = {"Remote-User": "kiskaadee"}
|
||||
from tests.conftest import login_client
|
||||
|
||||
|
||||
def test_is_google_maps_host():
|
||||
@@ -81,9 +80,9 @@ def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client
|
||||
assert resp.status_code == 401
|
||||
|
||||
# Test with auth -> 200
|
||||
login_client(client)
|
||||
resp = 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 +96,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 +116,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 +124,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