feat: get_web_login_auth on the vCenter, a source per provider and SSO domain (NetOrk/netork#662)
The vCenter driver reads how people log in to the vSphere Client, in napalm-device-types' WebLoginAuthDict: each identity provider of identity federation (GET /api/vcenter/identity/providers) is a source that decides itself (external), the default first; each SSO domain the vSphere API names (UserDirectory.domainList) is a source whose second factor cannot be read (unknown), since smart card and RSA SecurID live in SSO's authentication policy, which neither API exposes. Listing the providers needs VcIdentityProviders.Read and .Manage; without them the vCenter answers 403 and the driver raises PermissionError naming them. The REST read logs in to /api/session with the same account and logs out after. The ESXi driver has no reader.
This commit is contained in:
1 parent
e1677bebb2
commit
ab18ca87ca
10 files changed
+529
-6
No files matched your search
@@ -0,0 +1,274 @@
|
||||
"""get_web_login_auth: how people log in to vCenter's web interface (NetOrk/netork#662).
|
||||
|
||||
A vCenter login goes to vCenter Single Sign-On. Every SSO domain the vSphere API
|
||||
names (``UserDirectory.domainList``: the system domain, ``localos``, each AD or
|
||||
LDAP identity source) is a source, and so is every identity provider of identity
|
||||
federation (``GET /api/vcenter/identity/providers``). Whether SSO asks a domain's
|
||||
users for a smart card or an RSA SecurID code is in its authentication policy,
|
||||
which neither API exposes: those sources are ``unknown``, never guessed. A
|
||||
federated provider decides itself: ``external``.
|
||||
|
||||
The provider shapes follow the vSphere Automation API reference
|
||||
(``Providers.Summary``: ``provider``, ``name``, ``config_tag``, ``is_default``,
|
||||
``domain_names``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from napalm_vmware import VmwareEsxiDriver, VmwareVcenterDriver, _session
|
||||
from napalm_vmware.web_login import PROVIDERS_PATH, web_login_sources
|
||||
from tests.conftest import FakeInventory, load
|
||||
|
||||
|
||||
def _source(name: str, kind: str, factors: str) -> dict[str, str]:
|
||||
return {"name": name, "kind": kind, "factors": factors}
|
||||
|
||||
|
||||
def _provider(name: str, *, tag: str = "Oidc", default: bool = False, domains=()) -> dict:
|
||||
return {
|
||||
"provider": f"id-{name}",
|
||||
"name": name,
|
||||
"config_tag": tag,
|
||||
"is_default": default,
|
||||
"domain_names": list(domains),
|
||||
}
|
||||
|
||||
|
||||
class TestSources:
|
||||
def test_every_sso_domain_is_a_source_whose_second_factor_cannot_be_read(self):
|
||||
assert web_login_sources(domains=["vsphere.local", "CORP"], providers=[]) == [
|
||||
_source("vsphere.local", "sso", "unknown"),
|
||||
_source("CORP", "sso", "unknown"),
|
||||
]
|
||||
|
||||
def test_the_local_os_source_is_named_as_such(self):
|
||||
assert web_login_sources(domains=["localos"], providers=[]) == [
|
||||
_source("localos", "localos", "unknown")
|
||||
]
|
||||
|
||||
def test_a_federated_identity_provider_decides_itself(self):
|
||||
sources = web_login_sources(
|
||||
domains=["vsphere.local"], providers=[_provider("Microsoft ADFS", tag="Oauth2")]
|
||||
)
|
||||
|
||||
assert sources == [
|
||||
_source("Microsoft ADFS", "oauth2", "external"),
|
||||
_source("vsphere.local", "sso", "unknown"),
|
||||
]
|
||||
|
||||
def test_federation_does_not_switch_the_local_domain_off(self):
|
||||
"""administrator@vsphere.local still logs in beside the provider: both are ways in."""
|
||||
sources = web_login_sources(
|
||||
domains=["vsphere.local"], providers=[_provider("Okta", default=True)]
|
||||
)
|
||||
|
||||
assert [s["name"] for s in sources] == ["Okta", "vsphere.local"]
|
||||
|
||||
def test_the_default_provider_comes_first(self):
|
||||
providers = [_provider("ADFS"), _provider("Entra ID", default=True)]
|
||||
|
||||
assert [s["name"] for s in web_login_sources(domains=[], providers=providers)] == [
|
||||
"Entra ID",
|
||||
"ADFS",
|
||||
]
|
||||
|
||||
def test_a_domain_a_provider_serves_is_not_listed_twice(self):
|
||||
providers = [_provider("ADFS", domains=["corp.example.com"])]
|
||||
|
||||
sources = web_login_sources(
|
||||
domains=["vsphere.local", "CORP.example.com"], providers=providers
|
||||
)
|
||||
|
||||
assert [s["name"] for s in sources] == ["ADFS", "vsphere.local"]
|
||||
|
||||
def test_a_provider_without_a_name_or_tag_is_named_by_its_id(self):
|
||||
provider = {"provider": "b7d3", "is_default": False}
|
||||
|
||||
assert web_login_sources(domains=[], providers=[provider]) == [
|
||||
_source("b7d3", "federation", "external")
|
||||
]
|
||||
|
||||
def test_no_reading_ever_passes(self):
|
||||
"""Nothing either API says proves a second factor; the verdict can only be
|
||||
not met (never produced here) or not assessed."""
|
||||
sources = web_login_sources(
|
||||
domains=["vsphere.local", "localos", "CORP"], providers=[_provider("Okta")]
|
||||
)
|
||||
|
||||
assert {s["factors"] for s in sources} <= {"unknown", "external"}
|
||||
|
||||
def test_nothing_named_is_no_source(self):
|
||||
assert web_login_sources(domains=[], providers=[]) == []
|
||||
|
||||
|
||||
def _vcenter(domains=("vsphere.local",)) -> VmwareVcenterDriver:
|
||||
data = load("vcsim-vcenter")
|
||||
data["sso_domains"] = list(domains)
|
||||
driver = VmwareVcenterDriver("vc01.example.lan", "netork@vsphere.local", "secret")
|
||||
driver._si = MagicMock()
|
||||
driver._inventory = FakeInventory(data)
|
||||
return driver
|
||||
|
||||
|
||||
class TestDriver:
|
||||
def test_the_vcenter_reads_both_apis(self):
|
||||
driver = _vcenter(domains=["vsphere.local", "localos"])
|
||||
with patch.object(
|
||||
_session, "rest_get", return_value=[_provider("ADFS", tag="Oauth2")]
|
||||
) as get:
|
||||
reading = driver.get_web_login_auth()
|
||||
|
||||
assert reading == {
|
||||
"sources": [
|
||||
_source("ADFS", "oauth2", "external"),
|
||||
_source("vsphere.local", "sso", "unknown"),
|
||||
_source("localos", "localos", "unknown"),
|
||||
]
|
||||
}
|
||||
args, kwargs = get.call_args
|
||||
assert args == (
|
||||
"vc01.example.lan",
|
||||
443,
|
||||
"netork@vsphere.local",
|
||||
"secret",
|
||||
PROVIDERS_PATH,
|
||||
)
|
||||
assert kwargs == {"verify_ssl": True, "timeout": 60}
|
||||
|
||||
def test_a_missing_privilege_is_raised_and_names_it(self):
|
||||
"""Without VcIdentityProviders.Read and .Manage the vCenter answers 403; the
|
||||
reading is refused rather than judged without its providers."""
|
||||
driver = _vcenter()
|
||||
refused = PermissionError("GET /api/vcenter/identity/providers was refused (403)")
|
||||
with (
|
||||
patch.object(_session, "rest_get", side_effect=refused),
|
||||
pytest.raises(PermissionError) as exc,
|
||||
):
|
||||
driver.get_web_login_auth()
|
||||
|
||||
assert "VcIdentityProviders.Read" in str(exc.value)
|
||||
assert "VcIdentityProviders.Manage" in str(exc.value)
|
||||
|
||||
def test_esxi_has_no_reader(self):
|
||||
"""The host client's logins are not read; hasattr stays a truthful answer."""
|
||||
assert not hasattr(VmwareEsxiDriver, "get_web_login_auth")
|
||||
|
||||
|
||||
class _Response:
|
||||
def __init__(self, status: int, body: Any = None) -> None:
|
||||
self.status_code = status
|
||||
self._body = body
|
||||
|
||||
def json(self) -> Any:
|
||||
return self._body
|
||||
|
||||
def raise_for_status(self) -> None:
|
||||
if self.status_code >= 400:
|
||||
raise requests.HTTPError(f"{self.status_code} Error", response=self) # type: ignore[arg-type]
|
||||
|
||||
|
||||
class _Http:
|
||||
"""A ``requests.Session`` stand-in that records the calls."""
|
||||
|
||||
def __init__(self, *, login: _Response, get: _Response) -> None:
|
||||
self.headers: dict[str, str] = {}
|
||||
self.verify: bool | str = True
|
||||
self.calls: list[tuple[str, str, dict]] = []
|
||||
self._login, self._get = login, get
|
||||
|
||||
def __enter__(self) -> _Http:
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc: object) -> None:
|
||||
return None
|
||||
|
||||
def post(self, url: str, **kwargs: Any) -> _Response:
|
||||
self.calls.append(("POST", url, kwargs))
|
||||
return self._login
|
||||
|
||||
def get(self, url: str, **kwargs: Any) -> _Response:
|
||||
self.calls.append(
|
||||
("GET", url, dict(kwargs, session=self.headers.get("vmware-api-session-id")))
|
||||
)
|
||||
return self._get
|
||||
|
||||
def delete(self, url: str, **kwargs: Any) -> _Response:
|
||||
self.calls.append(("DELETE", url, kwargs))
|
||||
return _Response(204)
|
||||
|
||||
|
||||
def _rest_get(http: _Http, path: str = PROVIDERS_PATH) -> Any:
|
||||
with patch.object(_session.requests, "Session", return_value=http):
|
||||
return _session.rest_get(
|
||||
"vc01.example.lan",
|
||||
443,
|
||||
"netork@vsphere.local",
|
||||
"secret",
|
||||
path,
|
||||
verify_ssl=False,
|
||||
timeout=7,
|
||||
)
|
||||
|
||||
|
||||
class TestRestSession:
|
||||
def test_it_logs_in_reads_and_logs_out(self):
|
||||
http = _Http(login=_Response(201, "token-1"), get=_Response(200, [{"provider": "p"}]))
|
||||
|
||||
assert _rest_get(http) == [{"provider": "p"}]
|
||||
assert http.verify is False
|
||||
assert [(m, u) for m, u, _ in http.calls] == [
|
||||
("POST", "https://vc01.example.lan:443/api/session"),
|
||||
("GET", f"https://vc01.example.lan:443{PROVIDERS_PATH}"),
|
||||
("DELETE", "https://vc01.example.lan:443/api/session"),
|
||||
]
|
||||
assert http.calls[0][2]["auth"] == ("netork@vsphere.local", "secret")
|
||||
assert http.calls[1][2] == {"timeout": 7, "session": "token-1"}
|
||||
|
||||
@pytest.mark.parametrize("status", [401, 403])
|
||||
def test_a_refused_read_is_a_permission_error(self, status):
|
||||
http = _Http(
|
||||
login=_Response(201, "token-1"), get=_Response(status, {"error_type": "UNAUTHORIZED"})
|
||||
)
|
||||
|
||||
with pytest.raises(PermissionError, match=f"refused \\({status}\\)"):
|
||||
_rest_get(http)
|
||||
assert http.calls[-1][0] == "DELETE"
|
||||
|
||||
def test_a_refused_login_is_a_permission_error(self):
|
||||
http = _Http(
|
||||
login=_Response(401, {"error_type": "UNAUTHENTICATED"}), get=_Response(200, [])
|
||||
)
|
||||
|
||||
with pytest.raises(PermissionError, match="POST /api/session"):
|
||||
_rest_get(http)
|
||||
assert [m for m, _, _ in http.calls] == ["POST"]
|
||||
|
||||
def test_a_vcenter_without_the_api_raises(self):
|
||||
"""Before vCenter 7.0 U2 there is no /api: not a permission matter, still an error."""
|
||||
http = _Http(login=_Response(404), get=_Response(200, []))
|
||||
|
||||
with pytest.raises(requests.HTTPError):
|
||||
_rest_get(http)
|
||||
|
||||
def test_an_ipv6_address_is_bracketed(self):
|
||||
http = _Http(login=_Response(201, "t"), get=_Response(200, []))
|
||||
with patch.object(_session.requests, "Session", return_value=http):
|
||||
_session.rest_get("fd00::5", 443, "u", "p", PROVIDERS_PATH, verify_ssl=True, timeout=1)
|
||||
|
||||
assert http.calls[0][1] == "https://[fd00::5]:443/api/session"
|
||||
|
||||
|
||||
def test_a_failed_logout_does_not_hide_the_reading():
|
||||
class _Flaky(_Http):
|
||||
def delete(self, url: str, **kwargs: Any) -> _Response:
|
||||
raise requests.ConnectionError("gone")
|
||||
|
||||
http = _Flaky(login=_Response(201, "t"), get=_Response(200, [{"provider": "p"}]))
|
||||
|
||||
assert _rest_get(http) == [{"provider": "p"}]
|
||||
Reference in new issue
Block a user