From ab18ca87ca44e5a51f4d5617df4320e15c9875a3 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 29 Nov 2026 20:09:55 +0100 Subject: [PATCH 1/4] 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. --- CHANGELOG.md | 15 ++ README.md | 32 +++++ napalm_vmware/_inventory.py | 7 + napalm_vmware/_session.py | 49 ++++++- napalm_vmware/vcenter.py | 8 +- napalm_vmware/web_login.py | 128 +++++++++++++++++ pyproject.toml | 2 +- tests/conftest.py | 3 + tests/test_inventory.py | 17 +++ tests/test_web_login.py | 274 ++++++++++++++++++++++++++++++++++++ 10 files changed, 529 insertions(+), 6 deletions(-) create mode 100644 napalm_vmware/web_login.py create mode 100644 tests/test_web_login.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e15e52..4cf1110 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- `get_web_login_auth()` on the vCenter driver (napalm-device-types 4.50.0's + `WebLoginAuthDict`, NetOrk/netork#662): how people log in to the vSphere Client. + Each identity provider of identity federation (`GET /api/vcenter/identity/providers`) + is a source that decides itself (`external`), the default one first; each SSO domain + the vSphere API names (`UserDirectory.domainList`: the system domain, `localos`, each + AD or LDAP identity source) is a source whose second factor cannot be read + (`unknown`): smart card and RSA SecurID live in SSO's authentication policy, which + neither API exposes. Needs `VcIdentityProviders.Read` and `VcIdentityProviders.Manage` + (the Read-only role has neither); without them the driver raises `PermissionError` + naming them. The ESXi driver has no reader. + +### Changed +- Requires napalm-device-types 4.50.0 or later (`WebLoginAuthDict`). + ## [0.5.0] - 2026-11-26 ### Added diff --git a/README.md b/README.md index 56068fc..2511bbd 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ hardware**: see [Harvesting fixtures](#harvesting-fixtures). | `reboot_host` | ✅ (maintenance mode only) | — | `RebootHost_Task` | | `create_vm_from_cloud_init`, `destroy_vm`, `get_vm_status` | ✅ | ✅ | see [Provisioning](#provisioning) | | `get_network_targets`, `get_image_storages` | ✅ | ✅ | port groups, datastores | +| `get_web_login_auth` | — | ✅ | identity providers (REST) and SSO domains, see [Web interface logins](#web-interface-logins) | | VIBs, updates | — | — | not yet | Unverified assumptions, to be checked against real hardware: @@ -42,6 +43,8 @@ Unverified assumptions, to be checked against real hardware: - the HTTP fingerprints (`vmware esxi` on the Host Client page, `vcenter` on the vSphere Client page) - the free vSphere Hypervisor license reporting `editionKey` `esxBasic` +- a vCenter's `UserDirectory.domainList` naming its SSO domains (vcsim leaves it + empty) ## Requirements @@ -49,6 +52,12 @@ Unverified assumptions, to be checked against real hardware: - An account that may read the inventory. For power and snapshot actions it also needs *Virtual machine → Interaction → Power on/off/Reset/Suspend* and *Virtual machine → Snapshot management*. +- For `get_web_login_auth` (vCenter 7.0 U2 or later, for the `/api` REST + endpoints): `VcIdentityProviders.Read` **and** `VcIdentityProviders.Manage`, + which the REST API asks for to list the identity providers. The built-in + *Read-only* role has neither; a custom role with both on the vCenter root is + enough. Without them the vCenter answers 403 and the driver raises + `PermissionError` naming them. - For provisioning: `qemu-img` (package `qemu-utils`) where the driver runs, and HTTPS from there to every ESXi host that may receive a VM -- through a vCenter the disk upload goes straight to the host, not via the vCenter. @@ -139,6 +148,29 @@ Linux guests are provisioned; `guest_os` other than `"linux"` is refused Unverified until #305: that each distribution's cloud kernel carries the PVSCSI and VMXNET3 drivers. +## Web interface logins + +`get_web_login_auth()` (vCenter only, NetOrk/netork#662) returns +napalm-device-types' `WebLoginAuthDict`: the sources a vSphere Client login can go +to, each with what it asks for. + +| Source | `kind` | `factors` | Read from | +|---|---|---|---| +| an identity provider of identity federation (ADFS, Entra ID, Okta, PingFederate), the default first | its `config_tag`, lowercased (`oauth2`, `oidc`) | `external`: the provider decides | `GET /api/vcenter/identity/providers` | +| `localos` | `localos` | `unknown` | `UserDirectory.domainList` | +| every other SSO domain: the system domain, each AD or LDAP identity source | `sso` | `unknown` | `UserDirectory.domainList` | + +- An SSO domain a provider serves (its `domain_names`) is listed once, as the + provider. Federation does not switch the local domain off, so the SSO domains + stay sources beside it. +- **Why `unknown`:** whether vCenter Single Sign-On asks for a smart card (with + password login switched off) or an RSA SecurID code is its authentication + policy (`sso-config.sh`), which neither the vSphere API nor the vCenter REST API + exposes. The driver does not guess `password` or `password_otp`. No reading + therefore proves a second factor. +- The vSphere API session cannot be reused for the REST API, so the driver logs + in to `/api/session` with the same account, reads, and logs out again. + ## Design notes **One seam.** Every read goes through `Inventory.collect(type, paths)`, a diff --git a/napalm_vmware/_inventory.py b/napalm_vmware/_inventory.py index 5b4577e..18ec505 100644 --- a/napalm_vmware/_inventory.py +++ b/napalm_vmware/_inventory.py @@ -72,6 +72,13 @@ class Inventory: return [] return self.properties(manager, ["licenses"]).get("licenses", []) + def sso_domains(self) -> list[str]: + """The SSO domains a login can name (``UserDirectory.domainList``, vCenter).""" + directory = getattr(self._content, "userDirectory", None) + if directory is None: + return [] + return list(self.properties(directory, ["domainList"]).get("domainList") or []) + def _retrieve( self, obj_spec: Any, vim_type: Any, paths: Sequence[str], *, raw: bool = False ) -> list[dict[str, Any]]: diff --git a/napalm_vmware/_session.py b/napalm_vmware/_session.py index 1879049..558f978 100644 --- a/napalm_vmware/_session.py +++ b/napalm_vmware/_session.py @@ -1,7 +1,7 @@ -"""Opening and closing a vSphere API session. +"""Opening and closing a vSphere API session, and one read of the vCenter REST API. -Kept apart from everything else because it is the only code that opens a -socket; the tests replace it wholesale. +Kept apart from everything else because it is the only code that opens an API +session; the tests replace it wholesale. """ from __future__ import annotations @@ -9,8 +9,12 @@ from __future__ import annotations import ssl from typing import Any +import requests from pyVim.connect import Disconnect, SmartConnect +#: The vCenter REST API's session resource (vCenter 7.0 U2 or later). +_REST_SESSION = "/api/session" + def _ssl_context(verify: bool) -> ssl.SSLContext: context = ssl.create_default_context() @@ -45,3 +49,42 @@ def alive(si: Any) -> bool: # pragma: no cover - talks to a live session except Exception: return False return True + + +def rest_get( + host: str, port: int, user: str, password: str, path: str, *, verify_ssl: bool, timeout: int +) -> Any: + """``GET path`` on the vCenter REST API, in a session of its own that is closed after. + + The vSphere API session cannot be handed to the REST API, so this logs in + again with the same account. + + :raises PermissionError: when the login or the read is refused (401, 403). + :raises requests.HTTPError: for any other error, e.g. 404 before vCenter 7.0 U2. + """ + base = f"https://{f'[{host}]' if ':' in host else host}:{port}" + with requests.Session() as http: + http.verify = verify_ssl + login = http.post(f"{base}{_REST_SESSION}", auth=(user, password), timeout=timeout) + _raise_for(login, f"POST {_REST_SESSION}") + http.headers["vmware-api-session-id"] = login.json() + try: + response = http.get(f"{base}{path}", timeout=timeout) + _raise_for(response, f"GET {path}") + return response.json() + finally: + _logout(http, f"{base}{_REST_SESSION}", timeout) + + +def _logout(http: Any, url: str, timeout: int) -> None: + """End the REST session; a failure here must not hide the read's own result.""" + try: + http.delete(url, timeout=timeout) + except requests.RequestException: + pass + + +def _raise_for(response: Any, what: str) -> None: + if response.status_code in (401, 403): + raise PermissionError(f"{what} was refused ({response.status_code})") + response.raise_for_status() diff --git a/napalm_vmware/vcenter.py b/napalm_vmware/vcenter.py index 8de0ef0..ed34353 100644 --- a/napalm_vmware/vcenter.py +++ b/napalm_vmware/vcenter.py @@ -15,10 +15,14 @@ from napalm_vmware.actions import VmwareActionsMixin from napalm_vmware.base import VmwareBaseDriver from napalm_vmware.parse.facts import vcenter_facts from napalm_vmware.provisioning import VmwareProvisioningMixin +from napalm_vmware.web_login import VcenterWebLoginMixin -class VmwareVcenterDriver(VmwareProvisioningMixin, VmwareActionsMixin, VmwareBaseDriver): - """A vCenter and every VM, datastore and port group it manages.""" +class VmwareVcenterDriver( + VcenterWebLoginMixin, VmwareProvisioningMixin, VmwareActionsMixin, VmwareBaseDriver +): + """A vCenter and every VM, datastore and port group it manages, and how people + log in to its web interface (``web_login``).""" DRIVER_NAME = "vmware_vcenter" API_TYPE = "VirtualCenter" diff --git a/napalm_vmware/web_login.py b/napalm_vmware/web_login.py new file mode 100644 index 0000000..d31f785 --- /dev/null +++ b/napalm_vmware/web_login.py @@ -0,0 +1,128 @@ +"""How people log in to vCenter's web interface (NetOrk/netork#662). + +napalm-device-types' ``WebLoginAuthDict``: the sources a login is checked against, +each with what it asks for. Read only. vCenter only: the ESXi host client's +logins are not read, so the ESXi driver has no ``get_web_login_auth``. + +**What a source is.** The vSphere Client hands every login to vCenter Single +Sign-On, so the sources are SSO's: + +- **each SSO domain** the vSphere API names (``UserDirectory.domainList``): the + system domain (``vsphere.local`` unless renamed at install), ``localos`` (the + appliance's own accounts) and each Active Directory or LDAP identity source. + ``{"name": "vsphere.local", "kind": "sso", "factors": "unknown"}``; ``localos`` + has the kind ``localos``. The API names a domain, not its type, so an AD and an + OpenLDAP source are both ``sso``; +- **each identity provider of identity federation** (``GET + /api/vcenter/identity/providers``, vCenter 7.0 U2 or later): ADFS, Entra ID, + Okta, PingFederate. ``{"name": "Microsoft ADFS", "kind": "oauth2", "factors": + "external"}``, the kind its ``config_tag``. The default provider comes first. An + SSO domain that a provider serves (its ``domain_names``) is the provider's and is + not listed again. Federation does not switch the local domain off: + ``administrator@vsphere.local`` still logs in, so the SSO domains stay sources. + +**What a source asks for.** + +- A federated provider is ``external``: the provider decides whether it asks for + a second factor, and vCenter cannot say. +- An SSO domain is ``unknown``. Whether SSO asks for a smart card (with password + login switched off) or an RSA SecurID code is in SSO's authentication policy + (``sso-config.sh``), which neither the vSphere API nor the vCenter REST API + exposes. Saying ``password`` would be a guess, and so would ``password_otp``. + +So no reading of a vCenter proves a second factor: its web interface is judged +*not assessed*, with the sources named, until an API shows the policy. + +**The privilege the reading needs.** ``GET /api/vcenter/identity/providers`` +needs ``VcIdentityProviders.Read`` and ``VcIdentityProviders.Manage`` (vSphere +Automation API reference). The built-in *Read-only* role has neither, the +*Administrator* role has both; a custom role with the two, granted on the vCenter +root, is enough. Without them the vCenter answers 403, and the driver raises +``PermissionError`` naming them instead of reading the SSO domains alone. +``domainList`` is read with ``System.View``, which every role has. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from typing import Any + +from napalm_device_types import LoginSourceDict, WebLoginAuthDict + +from napalm_vmware import _session + +#: The vCenter REST endpoint listing identity federation's providers. +PROVIDERS_PATH = "/api/vcenter/identity/providers" +#: The privileges that endpoint asks for, all of them. +PROVIDERS_PRIVILEGES = ("VcIdentityProviders.Read", "VcIdentityProviders.Manage") +#: The SSO identity source of the appliance's own operating system accounts. +LOCAL_OS = "localos" + + +def _provider_source(provider: Mapping[str, Any]) -> LoginSourceDict: + name = str(provider.get("name") or provider.get("provider") or "") + kind = str(provider.get("config_tag") or "federation").lower() + return {"name": name, "kind": kind, "factors": "external"} + + +def _domain_source(domain: str) -> LoginSourceDict: + kind = LOCAL_OS if domain.lower() == LOCAL_OS else "sso" + return {"name": domain, "kind": kind, "factors": "unknown"} + + +def web_login_sources( + *, domains: Iterable[str], providers: Iterable[Mapping[str, Any]] +) -> list[LoginSourceDict]: + """The providers (the default first), then the SSO domains in the API's order. + + *domains* is ``UserDirectory.domainList``, *providers* the answer of + :data:`PROVIDERS_PATH`. + """ + federated = sorted(providers, key=lambda p: not p.get("is_default")) + served = {str(d).lower() for p in federated for d in p.get("domain_names") or ()} + sources = [_provider_source(p) for p in federated] + sources += [_domain_source(d) for d in domains if d and d.lower() not in served] + return sources + + +class VcenterWebLoginMixin: + """``get_web_login_auth`` for the vCenter driver.""" + + hostname: str + username: str + password: str + timeout: int + _port: int + _verify_ssl: bool + _inventory: Any + + def get_web_login_auth(self) -> WebLoginAuthDict: + """The sources a vSphere Client login can go to, each with what it asks for. + + Example:: + + {"sources": [{"name": "vsphere.local", "kind": "sso", "factors": "unknown"}]} + + :raises PermissionError: when the API login lacks the privileges that list + the identity providers (see the module docstring). + """ + try: + providers = _session.rest_get( + self.hostname, + self._port, + self.username, + self.password, + PROVIDERS_PATH, + verify_ssl=self._verify_ssl, + timeout=self.timeout, + ) + except PermissionError as exc: + raise PermissionError( + f"the API login lacks {' and '.join(PROVIDERS_PRIVILEGES)} on the vCenter, " + f"which list the identity providers: {exc}" + ) from exc + return { + "sources": web_login_sources( + domains=self._inventory.sso_domains(), providers=providers or [] + ) + } diff --git a/pyproject.toml b/pyproject.toml index 326dab1..a2fca87 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,7 +27,7 @@ classifiers = [ ] dependencies = [ "napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks - "napalm-device-types>=4.21.1", + "napalm-device-types>=4.50.0", "pyvmomi>=8.0.1", # Provisioning: download the image, write the NoCloud seed ISO and its YAML. "requests>=2.31", diff --git a/tests/conftest.py b/tests/conftest.py index 92dff03..5441763 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -42,6 +42,9 @@ class FakeInventory: def licenses(self) -> list[dict[str, Any]]: return self.data.get("licenses", []) + def sso_domains(self) -> list[str]: + return self.data.get("sso_domains", []) + def collect(self, type_name: str, paths: Sequence[str]) -> list[dict[str, Any]]: self.calls.append((type_name, tuple(paths))) rows = self.data["objects"].get(type_name, []) diff --git a/tests/test_inventory.py b/tests/test_inventory.py index 7834175..825a47b 100644 --- a/tests/test_inventory.py +++ b/tests/test_inventory.py @@ -131,3 +131,20 @@ def test_raw_properties_keep_the_pyvmomi_objects(content): vim.VirtualMachine("vm-1", None), ["config.hardware.device"], raw=True ) assert props["config.hardware.device"][0] is disk + + +def test_sso_domains_are_read_from_the_user_directory(content): + """The SSO domains a vCenter login can name (NetOrk/netork#662).""" + content.userDirectory = vim.UserDirectory("UserDirectory", None) + content.propertyCollector.RetrievePropertiesEx.return_value = SimpleNamespace( + objects=[ + _content(vim.UserDirectory("UserDirectory", None), {"domainList": ["vsphere.local"]}) + ], + token=None, + ) + assert Inventory(content).sso_domains() == ["vsphere.local"] + + +def test_sso_domains_empty_without_a_user_directory(content): + content.userDirectory = None + assert Inventory(content).sso_domains() == [] diff --git a/tests/test_web_login.py b/tests/test_web_login.py new file mode 100644 index 0000000..22aff12 --- /dev/null +++ b/tests/test_web_login.py @@ -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"}] From cf4d115475a4e044de397e0b2b28b0b154743e81 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 29 Nov 2026 20:10:03 +0100 Subject: [PATCH 2/4] chore(release): 0.6.0 --- CHANGELOG.md | 2 ++ pyproject.toml | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cf1110..c35f0b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.6.0] - 2026-11-29 + ### Added - `get_web_login_auth()` on the vCenter driver (napalm-device-types 4.50.0's `WebLoginAuthDict`, NetOrk/netork#662): how people log in to the vSphere Client. diff --git a/pyproject.toml b/pyproject.toml index a2fca87..f573b5d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-vmware" -version = "0.5.0" +version = "0.6.0" description = "NAPALM drivers for VMware ESXi hosts and vCenter Server (vSphere API via pyVmomi)" readme = "README.md" requires-python = ">=3.12" From 6a66c05f5ec0c696215891331b0ef819eeb53b75 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 29 Nov 2026 22:41:02 +0100 Subject: [PATCH 3/4] feat: read the identity providers best effort; a refused list is federation not read (NetOrk/netork#662) Listing the providers needs VcIdentityProviders.Manage besides .Read, which allows changing the identity provider configuration. The verdict is not assessed either way, so the driver no longer needs it: a 401/403 on GET /api/vcenter/identity/providers yields the SSO domains plus one source, "identity federation (not read)" (federation, unknown), instead of an error. PermissionError stays for a refused domainList; any other error of the REST read is raised as before. Part of 0.6.0, not yet tagged. --- CHANGELOG.md | 12 ++++++-- README.md | 18 ++++++++---- napalm_vmware/_inventory.py | 8 +++++- napalm_vmware/web_login.py | 57 +++++++++++++++++++++---------------- tests/test_inventory.py | 9 ++++++ tests/test_web_login.py | 44 +++++++++++++++++++++------- 6 files changed, 104 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c35f0b1..33bd0bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,9 +17,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 the vSphere API names (`UserDirectory.domainList`: the system domain, `localos`, each AD or LDAP identity source) is a source whose second factor cannot be read (`unknown`): smart card and RSA SecurID live in SSO's authentication policy, which - neither API exposes. Needs `VcIdentityProviders.Read` and `VcIdentityProviders.Manage` - (the Read-only role has neither); without them the driver raises `PermissionError` - naming them. The ESXi driver has no reader. + neither API exposes. Reading the providers is best effort: the vCenter lists them only + to an account with `VcIdentityProviders.Read` **and** `VcIdentityProviders.Manage`. + *Manage* allows changing the identity provider configuration, and the verdict is "not + assessed" either way, so it is not required, and granting it is not advised. When the + list is refused (401/403), the reading is the SSO domains plus one source, `identity + federation (not read)` (`federation`, `unknown`). With both privileges the providers + are named instead. `PermissionError` is raised only when `domainList` itself is + refused; any other error of the REST read is raised as it is. The ESXi driver has no + reader. ### Changed - Requires napalm-device-types 4.50.0 or later (`WebLoginAuthDict`). diff --git a/README.md b/README.md index 2511bbd..f2435d6 100644 --- a/README.md +++ b/README.md @@ -52,12 +52,14 @@ Unverified assumptions, to be checked against real hardware: - An account that may read the inventory. For power and snapshot actions it also needs *Virtual machine → Interaction → Power on/off/Reset/Suspend* and *Virtual machine → Snapshot management*. -- For `get_web_login_auth` (vCenter 7.0 U2 or later, for the `/api` REST - endpoints): `VcIdentityProviders.Read` **and** `VcIdentityProviders.Manage`, - which the REST API asks for to list the identity providers. The built-in - *Read-only* role has neither; a custom role with both on the vCenter root is - enough. Without them the vCenter answers 403 and the driver raises - `PermissionError` naming them. +- For `get_web_login_auth`: nothing beyond reading the inventory + (`System.View`, for the SSO domains). The identity providers are read best + effort (vCenter 7.0 U2 or later, for the `/api` REST endpoints): the vCenter + lists them only to an account with `VcIdentityProviders.Read` **and** + `VcIdentityProviders.Manage`. **Granting *Manage* is not advised:** it allows + changing the identity provider configuration, and the verdict is "not + assessed" either way. Without it the reading names the SSO domains and + `identity federation (not read)`; with both privileges it names the providers. - For provisioning: `qemu-img` (package `qemu-utils`) where the driver runs, and HTTPS from there to every ESXi host that may receive a VM -- through a vCenter the disk upload goes straight to the host, not via the vCenter. @@ -157,6 +159,7 @@ to, each with what it asks for. | Source | `kind` | `factors` | Read from | |---|---|---|---| | an identity provider of identity federation (ADFS, Entra ID, Okta, PingFederate), the default first | its `config_tag`, lowercased (`oauth2`, `oidc`) | `external`: the provider decides | `GET /api/vcenter/identity/providers` | +| `identity federation (not read)`, in the providers' place when the vCenter refused to list them (401/403) | `federation` | `unknown` | — | | `localos` | `localos` | `unknown` | `UserDirectory.domainList` | | every other SSO domain: the system domain, each AD or LDAP identity source | `sso` | `unknown` | `UserDirectory.domainList` | @@ -168,6 +171,9 @@ to, each with what it asks for. policy (`sso-config.sh`), which neither the vSphere API nor the vCenter REST API exposes. The driver does not guess `password` or `password_otp`. No reading therefore proves a second factor. +- **Errors:** a refused provider list is not one (see the table). A refused + `domainList` raises `PermissionError`; any other error of the REST read + (e.g. 404 before vCenter 7.0 U2) is raised as it is. - The vSphere API session cannot be reused for the REST API, so the driver logs in to `/api/session` with the same account, reads, and logs out again. diff --git a/napalm_vmware/_inventory.py b/napalm_vmware/_inventory.py index 18ec505..a005e8d 100644 --- a/napalm_vmware/_inventory.py +++ b/napalm_vmware/_inventory.py @@ -77,7 +77,13 @@ class Inventory: directory = getattr(self._content, "userDirectory", None) if directory is None: return [] - return list(self.properties(directory, ["domainList"]).get("domainList") or []) + try: + props = self.properties(directory, ["domainList"]) + except vim.fault.NoPermission as exc: + raise PermissionError( + f"reading the SSO domains (domainList) was refused: {exc.privilegeId}" + ) from exc + return list(props.get("domainList") or []) def _retrieve( self, obj_spec: Any, vim_type: Any, paths: Sequence[str], *, raw: bool = False diff --git a/napalm_vmware/web_login.py b/napalm_vmware/web_login.py index d31f785..2b4e7ab 100644 --- a/napalm_vmware/web_login.py +++ b/napalm_vmware/web_login.py @@ -33,13 +33,17 @@ Sign-On, so the sources are SSO's: So no reading of a vCenter proves a second factor: its web interface is judged *not assessed*, with the sources named, until an API shows the policy. -**The privilege the reading needs.** ``GET /api/vcenter/identity/providers`` -needs ``VcIdentityProviders.Read`` and ``VcIdentityProviders.Manage`` (vSphere -Automation API reference). The built-in *Read-only* role has neither, the -*Administrator* role has both; a custom role with the two, granted on the vCenter -root, is enough. Without them the vCenter answers 403, and the driver raises -``PermissionError`` naming them instead of reading the SSO domains alone. -``domainList`` is read with ``System.View``, which every role has. +**The privileges, and why federation is best effort.** ``domainList`` is read +with ``System.View``, which every role has; if even that is refused, the driver +raises ``PermissionError``. ``GET /api/vcenter/identity/providers`` needs +``VcIdentityProviders.Read`` **and** ``VcIdentityProviders.Manage`` (vSphere +Automation API reference). *Manage* lets an account change the identity provider +configuration, a lot to grant for a reading whose verdict is *not assessed* +either way, so the driver does not need it: when the vCenter refuses the list +(401 or 403), the reading is the SSO domains plus :data:`FEDERATION_NOT_READ`, a +source that stands for the providers that could not be read (``unknown``, never +a pass). With both privileges the providers are named instead. Any other error +of that read is raised as it is. """ from __future__ import annotations @@ -53,15 +57,20 @@ from napalm_vmware import _session #: The vCenter REST endpoint listing identity federation's providers. PROVIDERS_PATH = "/api/vcenter/identity/providers" -#: The privileges that endpoint asks for, all of them. -PROVIDERS_PRIVILEGES = ("VcIdentityProviders.Read", "VcIdentityProviders.Manage") +#: The source that stands for identity federation when the vCenter refused to list +#: its providers: there may be some, and what they ask for cannot be read. +FEDERATION_NOT_READ: LoginSourceDict = { + "name": "identity federation (not read)", + "kind": "federation", + "factors": "unknown", +} #: The SSO identity source of the appliance's own operating system accounts. LOCAL_OS = "localos" def _provider_source(provider: Mapping[str, Any]) -> LoginSourceDict: name = str(provider.get("name") or provider.get("provider") or "") - kind = str(provider.get("config_tag") or "federation").lower() + kind = str(provider.get("config_tag") or "provider").lower() return {"name": name, "kind": kind, "factors": "external"} @@ -71,13 +80,16 @@ def _domain_source(domain: str) -> LoginSourceDict: def web_login_sources( - *, domains: Iterable[str], providers: Iterable[Mapping[str, Any]] + *, domains: Iterable[str], providers: Iterable[Mapping[str, Any]] | None ) -> list[LoginSourceDict]: """The providers (the default first), then the SSO domains in the API's order. *domains* is ``UserDirectory.domainList``, *providers* the answer of - :data:`PROVIDERS_PATH`. + :data:`PROVIDERS_PATH`, or None when it was refused: then + :data:`FEDERATION_NOT_READ` takes the providers' place. """ + if providers is None: + return [FEDERATION_NOT_READ, *(_domain_source(d) for d in domains if d)] federated = sorted(providers, key=lambda p: not p.get("is_default")) served = {str(d).lower() for p in federated for d in p.get("domain_names") or ()} sources = [_provider_source(p) for p in federated] @@ -103,9 +115,11 @@ class VcenterWebLoginMixin: {"sources": [{"name": "vsphere.local", "kind": "sso", "factors": "unknown"}]} - :raises PermissionError: when the API login lacks the privileges that list - the identity providers (see the module docstring). + :raises PermissionError: when the API login may not read the SSO domains. + A refused list of identity providers is not an error (see the module + docstring). """ + domains = self._inventory.sso_domains() try: providers = _session.rest_get( self.hostname, @@ -116,13 +130,8 @@ class VcenterWebLoginMixin: verify_ssl=self._verify_ssl, timeout=self.timeout, ) - except PermissionError as exc: - raise PermissionError( - f"the API login lacks {' and '.join(PROVIDERS_PRIVILEGES)} on the vCenter, " - f"which list the identity providers: {exc}" - ) from exc - return { - "sources": web_login_sources( - domains=self._inventory.sso_domains(), providers=providers or [] - ) - } + except PermissionError: + providers = None + else: + providers = providers or [] + return {"sources": web_login_sources(domains=domains, providers=providers)} diff --git a/tests/test_inventory.py b/tests/test_inventory.py index 825a47b..bdd6bc2 100644 --- a/tests/test_inventory.py +++ b/tests/test_inventory.py @@ -148,3 +148,12 @@ def test_sso_domains_are_read_from_the_user_directory(content): def test_sso_domains_empty_without_a_user_directory(content): content.userDirectory = None assert Inventory(content).sso_domains() == [] + + +def test_sso_domains_refused_is_a_permission_error(content): + content.userDirectory = vim.UserDirectory("UserDirectory", None) + content.propertyCollector.RetrievePropertiesEx.side_effect = vim.fault.NoPermission( + privilegeId="System.View" + ) + with pytest.raises(PermissionError, match="System.View"): + Inventory(content).sso_domains() diff --git a/tests/test_web_login.py b/tests/test_web_login.py index 22aff12..f2c8e76 100644 --- a/tests/test_web_login.py +++ b/tests/test_web_login.py @@ -22,7 +22,7 @@ import pytest import requests from napalm_vmware import VmwareEsxiDriver, VmwareVcenterDriver, _session -from napalm_vmware.web_login import PROVIDERS_PATH, web_login_sources +from napalm_vmware.web_login import FEDERATION_NOT_READ, PROVIDERS_PATH, web_login_sources from tests.conftest import FakeInventory, load @@ -91,7 +91,7 @@ class TestSources: provider = {"provider": "b7d3", "is_default": False} assert web_login_sources(domains=[], providers=[provider]) == [ - _source("b7d3", "federation", "external") + _source("b7d3", "provider", "external") ] def test_no_reading_ever_passes(self): @@ -141,19 +141,43 @@ class TestDriver: ) 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.""" + @pytest.mark.parametrize("status", [401, 403]) + def test_providers_refused_still_names_the_sso_domains_and_federation_not_read(self, status): + """Listing the providers needs VcIdentityProviders.Manage, which netOrk does not + ask for: refused, the reading is the SSO domains plus federation as not read.""" + driver = _vcenter(domains=["vsphere.local"]) + refused = PermissionError(f"GET {PROVIDERS_PATH} was refused ({status})") + with patch.object(_session, "rest_get", side_effect=refused): + reading = driver.get_web_login_auth() + + assert reading == { + "sources": [ + FEDERATION_NOT_READ, + _source("vsphere.local", "sso", "unknown"), + ] + } + + def test_federation_not_read_is_never_a_pass(self): + assert FEDERATION_NOT_READ["factors"] == "unknown" + + def test_any_other_api_error_still_raises(self): 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, + patch.object(_session, "rest_get", side_effect=requests.HTTPError("500 Error")), + pytest.raises(requests.HTTPError), ): driver.get_web_login_auth() - assert "VcIdentityProviders.Read" in str(exc.value) - assert "VcIdentityProviders.Manage" in str(exc.value) + def test_sso_domains_refused_is_a_permission_error(self): + """Without domainList there is nothing to name: not judged by the providers alone.""" + driver = _vcenter() + driver._inventory = MagicMock() + driver._inventory.sso_domains.side_effect = PermissionError("domainList: NoPermission") + with ( + patch.object(_session, "rest_get", return_value=[_provider("ADFS")]), + pytest.raises(PermissionError, match="domainList"), + ): + driver.get_web_login_auth() def test_esxi_has_no_reader(self): """The host client's logins are not read; hasattr stays a truthful answer.""" From 3275f066156e15aa7dd39f026510848cae1d38a9 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 29 Nov 2026 23:30:19 +0100 Subject: [PATCH 4/4] refactor: split web_login_sources so it stays within the complexity ratchet (NetOrk/netork#662) --- napalm_vmware/web_login.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/napalm_vmware/web_login.py b/napalm_vmware/web_login.py index 2b4e7ab..7afbc05 100644 --- a/napalm_vmware/web_login.py +++ b/napalm_vmware/web_login.py @@ -89,12 +89,20 @@ def web_login_sources( :data:`FEDERATION_NOT_READ` takes the providers' place. """ if providers is None: - return [FEDERATION_NOT_READ, *(_domain_source(d) for d in domains if d)] + return [FEDERATION_NOT_READ, *_domain_sources(domains, served=set())] federated = sorted(providers, key=lambda p: not p.get("is_default")) - served = {str(d).lower() for p in federated for d in p.get("domain_names") or ()} sources = [_provider_source(p) for p in federated] - sources += [_domain_source(d) for d in domains if d and d.lower() not in served] - return sources + return sources + _domain_sources(domains, served=_served_domains(federated)) + + +def _served_domains(providers: Iterable[Mapping[str, Any]]) -> set[str]: + """The SSO domains the providers serve (``domain_names``), lowercased.""" + return {str(d).lower() for p in providers for d in p.get("domain_names") or ()} + + +def _domain_sources(domains: Iterable[str], *, served: set[str]) -> list[LoginSourceDict]: + """A source per named SSO domain that no provider serves, in the API's order.""" + return [_domain_source(d) for d in domains if d and d.lower() not in served] class VcenterWebLoginMixin: