Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8339e7b548 | ||
|
|
3275f06615 | ||
|
|
6a66c05f5e | ||
|
|
cf4d115475 | ||
|
|
ab18ca87ca |
No files matched your search
@@ -7,6 +7,29 @@ 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.
|
||||
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. 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`).
|
||||
|
||||
## [0.5.0] - 2026-11-26
|
||||
|
||||
### Added
|
||||
|
||||
@@ -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,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`: 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.
|
||||
@@ -139,6 +150,33 @@ 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` |
|
||||
| `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` |
|
||||
|
||||
- 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.
|
||||
- **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.
|
||||
|
||||
## Design notes
|
||||
|
||||
**One seam.** Every read goes through `Inventory.collect(type, paths)`, a
|
||||
|
||||
@@ -72,6 +72,19 @@ 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 []
|
||||
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
|
||||
) -> list[dict[str, Any]]:
|
||||
|
||||
@@ -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()
|
||||
@@ -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"
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""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 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
|
||||
|
||||
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 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 "provider").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]] | 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`, or None when it was refused: then
|
||||
:data:`FEDERATION_NOT_READ` takes the providers' place.
|
||||
"""
|
||||
if providers is None:
|
||||
return [FEDERATION_NOT_READ, *_domain_sources(domains, served=set())]
|
||||
federated = sorted(providers, key=lambda p: not p.get("is_default"))
|
||||
sources = [_provider_source(p) for p in federated]
|
||||
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:
|
||||
"""``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 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,
|
||||
self._port,
|
||||
self.username,
|
||||
self.password,
|
||||
PROVIDERS_PATH,
|
||||
verify_ssl=self._verify_ssl,
|
||||
timeout=self.timeout,
|
||||
)
|
||||
except PermissionError:
|
||||
providers = None
|
||||
else:
|
||||
providers = providers or []
|
||||
return {"sources": web_login_sources(domains=domains, providers=providers)}
|
||||
+2
-2
@@ -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"
|
||||
@@ -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",
|
||||
|
||||
@@ -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, [])
|
||||
|
||||
@@ -131,3 +131,29 @@ 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() == []
|
||||
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,298 @@
|
||||
"""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 FEDERATION_NOT_READ, 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", "provider", "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}
|
||||
|
||||
@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()
|
||||
with (
|
||||
patch.object(_session, "rest_get", side_effect=requests.HTTPError("500 Error")),
|
||||
pytest.raises(requests.HTTPError),
|
||||
):
|
||||
driver.get_web_login_auth()
|
||||
|
||||
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."""
|
||||
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