Download tests/test_sso.py from Modulo-6/api: direct link, hf CLI and curl.
- Browser
- Download file 9.37 kB
-
https://huggingface.co/spaces/Modulo-6/api/resolve/main/tests/test_sso.py
- Command line
-
hf download hf://spaces/Modulo-6/api/tests/test_sso.py
-
curl -L -o test_sso.py https://huggingface.co/spaces/Modulo-6/api/resolve/main/tests/test_sso.py
9.37 kB
| """ | |
| Tests de `POST /api/v1/auth/sso-exchange` (SSO entrante) y `POST /api/v1/auth/sso-ticket` | |
| (SSO saliente): canje de ticket del Core por una sesión propia de M6, y el camino | |
| inverso — pedirle al Core un ticket para navegar hacia otro módulo, usando el | |
| `core_token` embebido en la sesión (ver `app/routers/auth.py`). | |
| No golpean el Core real: se stubean `core_auth.exchange_sso_ticket`/`request_sso_ticket`. | |
| """ | |
| import pytest | |
| from app.config import settings | |
| from app.dependencies import create_access_token, decode_token | |
| from app.integrations import core_auth | |
| def _core_user(roles: list[str], user_id: int = 42) -> dict: | |
| return { | |
| "id": user_id, | |
| "first_name": "Ana", | |
| "last_name": "Pérez", | |
| "email": "ana@example.com", | |
| "roles": [{"id": i, "name": name} for i, name in enumerate(roles)], | |
| } | |
| def sso_enabled(monkeypatch): | |
| monkeypatch.setattr(settings, "sso_enabled", True) | |
| def test_sso_exchange_ok(client, monkeypatch, sso_enabled): | |
| monkeypatch.setattr( | |
| core_auth, | |
| "exchange_sso_ticket", | |
| lambda ticket: {"user": _core_user(["admin_internacion"]), "token": "core-jwt"}, | |
| ) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "un-ticket-valido"}) | |
| assert resp.status_code == 200 | |
| body = resp.json() | |
| assert body["rol"] == "ADMINISTRATIVO" | |
| assert body["user"]["id"] == 42 | |
| assert body["user"]["email"] == "ana@example.com" | |
| payload = decode_token(body["token"]) | |
| assert payload["sub"] == "42" | |
| assert payload["rol"] == "ADMINISTRATIVO" | |
| # El JWT del Core queda embebido — necesario para pedir tickets SSO salientes | |
| # más adelante (POST /auth/sso-ticket), sin volver a tocar el Core en cada request. | |
| assert payload["core_token"] == "core-jwt" | |
| def test_sso_exchange_medico(client, monkeypatch, sso_enabled): | |
| monkeypatch.setattr( | |
| core_auth, | |
| "exchange_sso_ticket", | |
| lambda ticket: {"user": _core_user(["Medico"], user_id=9), "token": "core-jwt"}, | |
| ) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "otro-ticket"}) | |
| assert resp.status_code == 200 | |
| assert resp.json()["rol"] == "MEDICO" | |
| def test_sso_exchange_ticket_invalido_401(client, monkeypatch, sso_enabled): | |
| def _raise(ticket): | |
| raise core_auth.SSOTicketInvalid("expirado") | |
| monkeypatch.setattr(core_auth, "exchange_sso_ticket", _raise) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "usado-o-expirado"}) | |
| assert resp.status_code == 401 | |
| assert resp.json()["detail"]["codigo"] == "NO_AUTENTICADO" | |
| def test_sso_exchange_core_inalcanzable_502(client, monkeypatch, sso_enabled): | |
| def _raise(ticket): | |
| raise core_auth.SSOExchangeError("timeout") | |
| monkeypatch.setattr(core_auth, "exchange_sso_ticket", _raise) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "cualquiera"}) | |
| assert resp.status_code == 502 | |
| assert resp.json()["detail"]["codigo"] == "SERVICIO_EXTERNO_NO_DISPONIBLE" | |
| def test_sso_exchange_rol_no_mapeado_403(client, monkeypatch, sso_enabled): | |
| monkeypatch.setattr( | |
| core_auth, | |
| "exchange_sso_ticket", | |
| lambda ticket: {"user": _core_user(["Enfermero"], user_id=10), "token": "core-jwt"}, | |
| ) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "un-ticket"}) | |
| assert resp.status_code == 403 | |
| assert resp.json()["detail"]["codigo"] == "NO_AUTORIZADO" | |
| # ─── Fallback de roles (GET /roles) cuando `user.roles[]` viene vacío ────── | |
| # El Core real no siempre puebla `user.roles[]` en la respuesta del canje SSO | |
| # (ver changelog #48 en M6_DISEÑO.md §14.11) — `sso_exchange` cae entonces a | |
| # `core_auth.resolve_user_roles`, que resuelve vía `GET /roles`. | |
| def test_sso_exchange_roles_vacio_usa_fallback(client, monkeypatch, sso_enabled): | |
| monkeypatch.setattr( | |
| core_auth, | |
| "exchange_sso_ticket", | |
| lambda ticket: {"user": _core_user([], user_id=7), "token": "core-jwt"}, | |
| ) | |
| monkeypatch.setattr(core_auth, "resolve_user_roles", lambda user_id: ["Medico"]) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "un-ticket"}) | |
| assert resp.status_code == 200 | |
| assert resp.json()["rol"] == "MEDICO" | |
| def test_sso_exchange_roles_vacio_fallback_tambien_vacio_403(client, monkeypatch, sso_enabled): | |
| monkeypatch.setattr( | |
| core_auth, | |
| "exchange_sso_ticket", | |
| lambda ticket: {"user": _core_user([], user_id=8), "token": "core-jwt"}, | |
| ) | |
| monkeypatch.setattr(core_auth, "resolve_user_roles", lambda user_id: []) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "un-ticket"}) | |
| assert resp.status_code == 403 | |
| assert resp.json()["detail"]["codigo"] == "NO_AUTORIZADO" | |
| def test_sso_exchange_roles_no_vacio_no_usa_fallback(client, monkeypatch, sso_enabled): | |
| """Si el canje ya trae roles, no se llama al fallback (camino feliz sin tocar el Core de nuevo).""" | |
| monkeypatch.setattr( | |
| core_auth, | |
| "exchange_sso_ticket", | |
| lambda ticket: {"user": _core_user(["admin_internacion"]), "token": "core-jwt"}, | |
| ) | |
| def _fail(user_id): | |
| raise AssertionError("no debería llamarse: user.roles[] ya vino poblado") | |
| monkeypatch.setattr(core_auth, "resolve_user_roles", _fail) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "un-ticket"}) | |
| assert resp.status_code == 200 | |
| assert resp.json()["rol"] == "ADMINISTRATIVO" | |
| def test_sso_exchange_fallback_de_roles_falla_502(client, monkeypatch, sso_enabled): | |
| monkeypatch.setattr( | |
| core_auth, | |
| "exchange_sso_ticket", | |
| lambda ticket: {"user": _core_user([], user_id=11), "token": "core-jwt"}, | |
| ) | |
| def _raise(user_id): | |
| raise core_auth.SSOExchangeError("timeout en GET /roles") | |
| monkeypatch.setattr(core_auth, "resolve_user_roles", _raise) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "un-ticket"}) | |
| assert resp.status_code == 502 | |
| assert resp.json()["detail"]["codigo"] == "SERVICIO_EXTERNO_NO_DISPONIBLE" | |
| def test_sso_exchange_ticket_vacio_422(client, sso_enabled): | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": ""}) | |
| assert resp.status_code == 422 | |
| def test_sso_exchange_deshabilitado_404(client, monkeypatch): | |
| monkeypatch.setattr(settings, "sso_enabled", False) | |
| resp = client.post("/api/v1/auth/sso-exchange", json={"ticket": "cualquiera"}) | |
| assert resp.status_code == 404 | |
| # ─── POST /auth/sso-ticket (SSO saliente) ────────────────────────────────── | |
| def _headers_con_core_token(core_token: str = "core-jwt-vigente") -> dict: | |
| token = create_access_token(sub="1", rol="ADMINISTRATIVO", extra={"core_token": core_token}) | |
| return {"Authorization": f"Bearer {token}"} | |
| def test_sso_ticket_ok(client, monkeypatch, sso_enabled): | |
| monkeypatch.setattr( | |
| core_auth, "request_sso_ticket", lambda core_token: {"ticket": "un-ticket-nuevo", "expires_in": 60} | |
| ) | |
| resp = client.post("/api/v1/auth/sso-ticket", headers=_headers_con_core_token()) | |
| assert resp.status_code == 200 | |
| assert resp.json() == {"ticket": "un-ticket-nuevo", "expires_in": 60} | |
| def test_sso_ticket_pasa_el_core_token_correcto(client, monkeypatch, sso_enabled): | |
| received = [] | |
| monkeypatch.setattr( | |
| core_auth, | |
| "request_sso_ticket", | |
| lambda core_token: received.append(core_token) or {"ticket": "t", "expires_in": 60}, | |
| ) | |
| client.post("/api/v1/auth/sso-ticket", headers=_headers_con_core_token("mi-core-token")) | |
| assert received == ["mi-core-token"] | |
| def test_sso_ticket_sin_core_token_401(client, admin_headers, sso_enabled): | |
| """Sesiones que no vinieron de un SSO real (p.ej. el endpoint de dev, admin_headers | |
| de conftest.py) no tienen core_token embebido — no pueden pedir un ticket saliente.""" | |
| resp = client.post("/api/v1/auth/sso-ticket", headers=admin_headers) | |
| assert resp.status_code == 401 | |
| assert resp.json()["detail"]["codigo"] == "SIN_SESION_CORE" | |
| def test_sso_ticket_core_token_vencido_401(client, monkeypatch, sso_enabled): | |
| def _raise(core_token): | |
| raise core_auth.CoreTokenInvalid("vencido") | |
| monkeypatch.setattr(core_auth, "request_sso_ticket", _raise) | |
| resp = client.post("/api/v1/auth/sso-ticket", headers=_headers_con_core_token()) | |
| assert resp.status_code == 401 | |
| assert resp.json()["detail"]["codigo"] == "NO_AUTENTICADO" | |
| def test_sso_ticket_core_inalcanzable_502(client, monkeypatch, sso_enabled): | |
| def _raise(core_token): | |
| raise core_auth.SSOExchangeError("timeout") | |
| monkeypatch.setattr(core_auth, "request_sso_ticket", _raise) | |
| resp = client.post("/api/v1/auth/sso-ticket", headers=_headers_con_core_token()) | |
| assert resp.status_code == 502 | |
| assert resp.json()["detail"]["codigo"] == "SERVICIO_EXTERNO_NO_DISPONIBLE" | |
| def test_sso_ticket_sin_sesion_401(client, sso_enabled): | |
| resp = client.post("/api/v1/auth/sso-ticket") | |
| assert resp.status_code == 401 | |
| def test_sso_ticket_deshabilitado_404(client, monkeypatch): | |
| monkeypatch.setattr(settings, "sso_enabled", False) | |
| resp = client.post("/api/v1/auth/sso-ticket", headers=_headers_con_core_token()) | |
| assert resp.status_code == 404 | |