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."""