File size: 3,481 Bytes
e6a43c8
624c7c9
01e0bb5
624c7c9
01e0bb5
 
 
 
 
 
e6a43c8
01e0bb5
e6a43c8
 
 
 
 
 
 
 
 
 
 
 
73c7f92
e6a43c8
73c7f92
e6a43c8
 
 
 
 
 
 
01e0bb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""
Tests de `app/integrations/core_auth.py`: mapeo de roles del Core al rol
interno de M6, y el fallback de resolución de roles vía `GET /roles`.

La verificación de JWT del Core vía JWKS (`verify_core_token`/`get_signing_key`)
sigue eliminada: la sesión de M6 es siempre un JWT HS256 propio. El rol se
resuelve en el canje SSO (ver `tests/test_sso.py`), primero desde
`user.roles[]` y, si viene vacío, vía `resolve_user_roles`/`_fetch_roles_index`
— reintroducidos porque el Core real no siempre puebla `user.roles[]` en el
canje (ver `M6_DISEÑO.md` §14.11).
"""
import httpx
import pytest

from app.integrations import core_auth


@pytest.mark.parametrize(
    "role_names,expected",
    [
        (["admin_internacion"], "ADMINISTRATIVO"),
        (["Medico"], "MEDICO"),
        (["limpieza"], "LIMPIEZA"),
        (["admin"], "ADMINISTRATIVO"),
        (["app"], "ADMINISTRATIVO"),
        (["Enfermero"], None),
        (["app", "role_manager"], "ADMINISTRATIVO"),
        ([], None),
        (["limpieza", "admin_internacion"], "ADMINISTRATIVO"),  # precedencia
        (["limpieza", "Medico"], "MEDICO"),
    ],
)
def test_map_core_roles_to_internal(role_names, expected):
    assert core_auth.map_core_roles_to_internal(role_names) == expected


# ─── Fallback de roles: GET /roles con la cuenta de servicio ───────────────


def _roles_list_response(payload: dict) -> httpx.Response:
    return httpx.Response(200, json=payload, request=httpx.Request("GET", "http://core/roles"))


def test_fetch_roles_index_arma_indice_desde_users_embebidos(monkeypatch):
    monkeypatch.setattr(core_auth, "get_service_token", lambda: "service-token")

    payload = {
        "data": [
            {"id": 1, "name": "admin_internacion", "users": [{"id": 42}, {"id": 43}]},
            {"id": 2, "name": "Medico", "users": [{"id": 43}]},
            {"id": 3, "name": "sin_usuarios", "users": []},
        ]
    }
    monkeypatch.setattr(httpx, "get", lambda *a, **k: _roles_list_response(payload))

    index = core_auth._fetch_roles_index()

    assert index == {42: ["admin_internacion"], 43: ["admin_internacion", "Medico"]}


def test_fetch_roles_index_usa_el_token_de_servicio(monkeypatch):
    monkeypatch.setattr(core_auth, "get_service_token", lambda: "mi-token")
    received = {}

    def _fake_get(url, headers=None, params=None, timeout=None):
        received["url"] = url
        received["headers"] = headers
        received["params"] = params
        return _roles_list_response({"data": []})

    monkeypatch.setattr(httpx, "get", _fake_get)

    core_auth._fetch_roles_index()

    assert received["headers"] == {"Authorization": "Bearer mi-token"}
    assert received["url"].endswith("/roles")
    assert received["params"] == {"pageSize": 200}


def test_resolve_user_roles_devuelve_vacio_si_no_esta_en_el_indice(monkeypatch):
    monkeypatch.setattr(core_auth, "_fetch_roles_index", lambda: {42: ["Medico"]})

    assert core_auth.resolve_user_roles(999) == []
    assert core_auth.resolve_user_roles(42) == ["Medico"]


def test_fetch_roles_index_propaga_error_http(monkeypatch):
    monkeypatch.setattr(core_auth, "get_service_token", lambda: "service-token")

    def _fake_get(*a, **k):
        return httpx.Response(500, request=httpx.Request("GET", "http://core/roles"))

    monkeypatch.setattr(httpx, "get", _fake_get)

    with pytest.raises(httpx.HTTPStatusError):
        core_auth._fetch_roles_index()