diff --git a/.vale/styles/spelling-exceptions.txt b/.vale/styles/spelling-exceptions.txt index 3cc7598f6..f22059401 100644 --- a/.vale/styles/spelling-exceptions.txt +++ b/.vale/styles/spelling-exceptions.txt @@ -161,3 +161,5 @@ ty formatters Entra OData +vManage +onboarded diff --git a/AGENTS.md b/AGENTS.md index 0157b3101..57dedcada 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ infrahub-sync/ └─ .github/workflows/ # CI ``` -Available adapters (`infrahub_sync/adapters/`): `infrahub`, `netbox`, `nautobot`, `aci`, `prometheus`, `peeringmanager`, `ipfabricsync`, `slurpitsync`, `webex`, `genericrestapi`, `msgraphsync`. +Available adapters (`infrahub_sync/adapters/`): `infrahub`, `netbox`, `nautobot`, `aci`, `prometheus`, `peeringmanager`, `ipfabricsync`, `slurpitsync`, `webex`, `ciscosdwan`, `genericrestapi`, `msgraphsync`. ## CLI Commands diff --git a/README.md b/README.md index ab18cb263..b6c2ee728 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,7 @@ After the sync completes, every NetBox device, interface, VLAN, prefix, and rela | Nautobot | Nautobot → Infrahub | | IP Fabric | IP Fabric → Infrahub | | Cisco ACI | Cisco ACI → Infrahub | +| Cisco Catalyst SD-WAN | SD-WAN Manager → Infrahub | | Peering Manager | Peering Manager → Infrahub · Infrahub → Peering Manager | | Prometheus | Prometheus → Infrahub | | Slurp'it | Slurp'it → Infrahub | diff --git a/changelog/+cisco-sdwan-adapter.added.md b/changelog/+cisco-sdwan-adapter.added.md new file mode 100644 index 000000000..5e1e98420 --- /dev/null +++ b/changelog/+cisco-sdwan-adapter.added.md @@ -0,0 +1 @@ +Added a Cisco Catalyst SD-WAN Manager source adapter (`ciscosdwan`) and an example that syncs the Manager, its sites, configuration groups and WAN edge routers into the `Sdwan` schema. The adapter logs in with a username and password read from environment variables, follows `pageInfo` pagination and logs out at the end of the run. diff --git a/docs/docs/adapters/choosing-an-adapter.mdx b/docs/docs/adapters/choosing-an-adapter.mdx index 1a40c454b..73927b221 100644 --- a/docs/docs/adapters/choosing-an-adapter.mdx +++ b/docs/docs/adapters/choosing-an-adapter.mdx @@ -20,6 +20,7 @@ Each adapter handles two responsibilities for its target system: **communication | IP Fabric | IP Fabric → Infrahub | Building Infrahub inventory from IP Fabric network discovery data | | Slurp'it | Slurp'it → Infrahub | Building Infrahub inventory from Slurp'it network discovery data | | Cisco ACI | Cisco ACI → Infrahub | Syncing data from Cisco ACI fabrics into Infrahub | +| Cisco Catalyst SD-WAN | SD-WAN Manager → Infrahub | Syncing SD-WAN sites, configuration groups and WAN edge routers from SD-WAN Manager into Infrahub | | Peering Manager | Peering Manager → Infrahub · Infrahub → Peering Manager | Bi-directional sync between Peering Manager and Infrahub | | PeeringDB | PeeringDB → Infrahub | Pulling autonomous system and internet exchange data from PeeringDB into Infrahub | | Prometheus | Prometheus → Infrahub | Pulling target or metric metadata from Prometheus into Infrahub | diff --git a/docs/docs/adapters/cisco-sdwan.mdx b/docs/docs/adapters/cisco-sdwan.mdx new file mode 100644 index 000000000..6d1371f27 --- /dev/null +++ b/docs/docs/adapters/cisco-sdwan.mdx @@ -0,0 +1,110 @@ +--- +title: Cisco Catalyst SD-WAN adapter +--- + +The Cisco Catalyst SD-WAN adapter reads inventory from Cisco Catalyst SD-WAN Manager (formerly vManage) into a sync project: the Manager itself, its sites, its configuration groups and its WAN edge routers, or any other JSON resource under `/dataservice/`. Run it to record in Infrahub which routers the Manager has onboarded, with the site and configuration group of each one, and review the differences before you sync them. + +SD-WAN Manager is supported as a **source only**. The adapter reads data with GET requests. The only other requests it sends are the form login to `/j_security_check` and the logout from `/logout`; it never changes configuration in the Manager. The example on this page was tested against SD-WAN Manager 20.18.2.1. + +## Authentication and permissions + +The adapter logs in with a username and password, the same way the Manager web interface does: it posts the credentials to `/j_security_check`, requests the session's XSRF token from `/dataservice/client/token`, and sends that token with every later request. The [Cisco SD-WAN authentication documentation](https://developer.cisco.com/docs/sdwan/authentication/) describes this flow. + +The adapter uses one session for the whole run. After the last mapping loads, or as soon as a request fails, the adapter logs out with `POST /logout`, and falls back to `GET /logout` when the Manager responds with HTTP 405. Logging out matters because the Manager limits the number of concurrent sessions and, at that limit, invalidates the least recently used one. If the logout request fails, the adapter logs a warning and the session expires after the Manager's inactivity timeout, 30 minutes by default according to the same Cisco page. + +The adapter reads the credentials from environment variables only. The two settings contain variable names, not values: + +| Setting | Default variable name | The variable contains | +| --- | --- | --- | +| `username_env` | `CISCO_SDWAN_USERNAME` | The Manager user name | +| `password_env` | `CISCO_SDWAN_PASSWORD` | The password of that user | + +Change the variable names when you run projects against several Managers from one environment. Give the account read access to every resource the project maps; for a resource the account cannot read, the adapter stops with HTTP 403. + +The adapter sends no tenant selection (`VSessionId`), so on a multi-tenant Manager it reads the data the Manager returns for the logged-in user. + +## Sync the Manager, sites, configuration groups and routers + +The [example project](https://github.com/opsmill/infrahub-sync/blob/main/examples/cisco_sdwan_to_infrahub/config.yml) maps four Manager resources to the `Sdwan` kinds in the accompanying [example schema](https://github.com/opsmill/infrahub-sync/blob/main/examples/cisco_sdwan_to_infrahub/schema.yml). An SD-WAN instance contains its sites and configuration groups, and each site contains its routers. + +| Infrahub kind | Manager endpoint | Identifier | Peer | +| --- | --- | --- | --- | +| `SdwanInstance` | `client/about` | `name`, set in the configuration | None | +| `SdwanSite` | `v1/network-hierarchy`, nodes labelled `SITE` | `id_value` from `data.hierarchyId.siteId` | `instance` | +| `SdwanConfigurationGroup` | `v1/config-group` | `name` | `instance` | +| `SdwanRouter` | `system/device/vedges`, routers with a configured site ID | `chassis_id` from `chasisNumber` | `site` from `configuredSiteId`, referencing `SdwanSite` | + +`chasisNumber` is spelled that way by the API. The other mapped values come from these fields and transforms: + +- **Instance name.** `client/about` returns the Manager version, but no name for the deployment. The example sets the name `sdwan-manager` as a static value, and every `instance` reference uses the same value. Replace all of them with the name you use for this Manager. +- **Routers that are not onboarded.** `system/device/vedges` also lists the chassis numbers in the WAN edge list that are not assigned to a site. On the Manager used to test the example, it returned 30 chassis numbers, 4 of them assigned. The filter on `configuredSiteId` keeps the assigned ones. +- **Router model.** The API reports models such as `vedge-C8000V`. A transform removes the `vedge-` prefix, so the value matches a choice of the `model` dropdown, such as `C8000V`. When the result is not one of the choices, Infrahub rejects the router node. +- **Configuration group of a router.** For a router deployed with a configuration group, the Manager reports `managed-by: Config-Group edge_basic`. A transform keeps the group name, `edge_basic`; for a router managed another way, the field stays empty. +- **Feature profiles of a configuration group.** `v1/config-group` lists the profiles of each group with their type. One transform per type selects the profile name for `system_profile`, `transport_profile`, `service_profile`, `cli_profile` and `policy_object_profile`. The schema makes the system and transport profiles mandatory, so Infrahub rejects a group without one of them. + +Infrahub Sync orders the loads from the references: the instance first, then sites and configuration groups, then routers. + +Load the schema into Infrahub, then list, generate and compare: + +```bash +infrahubctl schema load examples/cisco_sdwan_to_infrahub/schema.yml +infrahub-sync list --directory examples/ +infrahub-sync generate --name from-cisco-sdwan --directory examples/ +infrahub-sync diff --name from-cisco-sdwan --directory examples/ +``` + +Set `CISCO_SDWAN_URL`, `CISCO_SDWAN_USERNAME`, `CISCO_SDWAN_PASSWORD` and the destination's `INFRAHUB_API_TOKEN` through your secret manager or shell, and configure the destination address for your environment. Review the diff before you run `sync` with the same configuration. + +The example sets no `diffsync_flags`, so Infrahub Sync ignores nodes that exist only in Infrahub. A router removed from the Manager stays in Infrahub, and the diff does not list it. + +## Connection settings + +Set `source.name: ciscosdwan` and configure the connection under `source.settings`. + +| Setting | Default | Meaning | +| --- | --- | --- | +| `url` | Unset | HTTPS origin of the Manager, such as `https://sdwan-manager.example.com`, with no path, query, fragment or embedded credentials. `CISCO_SDWAN_URL` replaces it when set. | +| `username_env` | `CISCO_SDWAN_USERNAME` | Name of the variable that contains the user name. | +| `password_env` | `CISCO_SDWAN_PASSWORD` | Name of the variable that contains the password. | +| `verify_ssl` | `true` | Verify the Manager's TLS certificate. | +| `timeout` | `30` | Timeout in seconds for each request. | +| `retries` | `3` | Retries per request after a rate limit, a server error, a timeout or a connection failure. | +| `max_retry_delay` | `60` | Maximum wait in seconds between retries. A `Retry-After` longer than this value stops the run. | + +A lab Manager can present a self-signed certificate, which fails verification. Set `verify_ssl: false` only for such a lab. To trust a private certificate authority instead, set the `REQUESTS_CA_BUNDLE` environment variable to its certificate bundle. + +## Map other resources + +The `mapping` of each schema mapping is a GET path under `/dataservice/`. Write it with or without that prefix, and add query parameters after `?`, for example `data/device/state/CEdgeInterface?count=1000`. Configure fields, filters, Jinja2 transforms, identifiers and references as described in the [schema-mapping configuration](../reference/config.mdx). + +The adapter accepts the response shapes the Manager uses: + +- an object with a `data` list, as returned by `device` and `system/device/vedges`; +- an object with a `data` object, as returned by `client/about`, which becomes one record; +- a bare list, as returned by `v1/config-group` and `v1/network-hierarchy`. + +**Paged endpoints.** When a response includes `pageInfo` with `moreEntries: true`, the adapter requests the next page with `startId` set to the `endId` it received, and continues until `moreEntries` is false. The Manager pages device state endpoints, such as `data/device/state/CEdgeInterface`, this way. A response whose `pageInfo` reports `hasMoreData` uses scroll pagination, which the adapter does not support; it stops rather than load part of the data. + +**Field names with hyphens.** Many Manager fields contain hyphens, such as `host-name` and `system-ip`. A Jinja2 expression cannot name those as variables, so the adapter adds a copy of each such field with underscores: write `{{ host_name }}` in a transform. `mapping` and `filters` accept either name. + +**Several kinds from one endpoint.** When several mappings use the same endpoint, the adapter requests it once per run and gives each mapping its own copy of the records, so the transforms of one mapping do not change the records of another. + +**Repeated identifiers.** When several records of a mapping have the same identifier and the same values, for example sites taken from a device list, the adapter loads one node. When the values differ, it stops and names the identifier; add a filter or change the identifiers. + +**Source identifiers.** The adapter gives each record a source identifier, and Infrahub Sync matches a reference written as an `id` object to the peer with that identifier. The adapter uses the record's `id`, then `uuid`, `deviceId`, `recordId` or `vdevice-dataKey`. A record with none of them, such as the one from `client/about`, receives an identifier calculated from its endpoint and position. + +## Failure handling + +| Failure | Result and action | +| --- | --- | +| Login rejected | The Manager responds to a rejected login with HTTP 200 and an error body or its login page. The adapter stops and names the two credential variables; check their values. | +| Session rejected during the run | When a data request returns the login page, HTTP 401 or HTTP 403, the adapter logs in once more and repeats the request. If the Manager still rejects it, the adapter stops with HTTP 401, or with HTTP 403 for a resource the account cannot read. | +| HTTP 404 | Stops; check the mapping path and whether your Manager version provides the endpoint. | +| HTTP 400 and other rejected responses | Stops with the status and the first 200 characters of the Manager's error message. Other response fields and the raw body are left out. | +| HTTP 429 or 5xx | Waits for `Retry-After`, or 1, 2, 4… seconds up to `max_retry_delay`, then retries up to `retries` times. | +| Timeout or connection failure | Retries the same way, then stops and names the endpoint. | +| Certificate verification failure | Stops; trust the Manager's certificate authority, or set `verify_ssl: false` for a lab Manager. | +| Redirect | Stops; the adapter does not follow redirects. | +| Invalid JSON, records that are not objects, or a page without a new `endId` | Stops rather than treat the resource as empty or complete. | + +Errors and logs never contain the password, the session cookie or the XSRF token. The adapter logs a debug event for each request, with a running request count, and an info event for each endpoint, with the number of records and requests. Incremental change tracking is not implemented for SD-WAN Manager; the adapter reads every mapped resource in full on each run. diff --git a/docs/docs/readme.mdx b/docs/docs/readme.mdx index 4c192fc69..bfcb6b74d 100644 --- a/docs/docs/readme.mdx +++ b/docs/docs/readme.mdx @@ -85,6 +85,7 @@ Infrahub is populated from what is actually deployed in the network rather than | Nautobot | Nautobot → Infrahub | | IP Fabric | IP Fabric → Infrahub | | Cisco ACI | Cisco ACI → Infrahub | +| Cisco Catalyst SD-WAN | SD-WAN Manager → Infrahub | | Peering Manager | Peering Manager → Infrahub · Infrahub → Peering Manager | | Prometheus | Prometheus → Infrahub | | Slurp’it | Slurp’it → Infrahub | diff --git a/docs/sidebars.ts b/docs/sidebars.ts index 76d566eb7..48101a8e8 100644 --- a/docs/sidebars.ts +++ b/docs/sidebars.ts @@ -35,6 +35,7 @@ const sidebars: SidebarsConfig = { items: [ 'adapters/choosing-an-adapter', 'adapters/aci', + 'adapters/cisco-sdwan', 'adapters/device42', 'adapters/msgraphsync', 'adapters/genericrestapi', diff --git a/examples/cisco_sdwan_to_infrahub/ciscosdwan/__init__.py b/examples/cisco_sdwan_to_infrahub/ciscosdwan/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/examples/cisco_sdwan_to_infrahub/ciscosdwan/sync_adapter.py b/examples/cisco_sdwan_to_infrahub/ciscosdwan/sync_adapter.py new file mode 100644 index 000000000..40b42c81b --- /dev/null +++ b/examples/cisco_sdwan_to_infrahub/ciscosdwan/sync_adapter.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from infrahub_sync.plugin_loader import PluginLoader + +from .sync_models import ( + SdwanConfigurationGroup, + SdwanInstance, + SdwanRouter, + SdwanSite, +) + +# Load adapter class dynamically at runtime + +_AdapterBaseClass = PluginLoader().resolve("ciscosdwan") + + +# ------------------------------------------------------- +# AUTO-GENERATED FILE, DO NOT MODIFY +# This file has been generated with the command `infrahub-sync generate` +# All modifications will be lost the next time you reexecute this command +# ------------------------------------------------------- +class CiscosdwanSync(_AdapterBaseClass): + SdwanConfigurationGroup = SdwanConfigurationGroup + SdwanInstance = SdwanInstance + SdwanRouter = SdwanRouter + SdwanSite = SdwanSite diff --git a/examples/cisco_sdwan_to_infrahub/ciscosdwan/sync_models.py b/examples/cisco_sdwan_to_infrahub/ciscosdwan/sync_models.py new file mode 100644 index 000000000..cf2b188e8 --- /dev/null +++ b/examples/cisco_sdwan_to_infrahub/ciscosdwan/sync_models.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import Any, List + +from infrahub_sync.plugin_loader import PluginLoader +# Load model class dynamically at runtime (honor adapters_path, safe fallback) +try: + + _loader = PluginLoader.from_env_and_args() + + + _spec = "ciscosdwan" + + _ModelBaseClass = _loader.resolve(_spec, default_class_candidates=("Model",)) +except Exception: + # Fallback: use DiffSyncModel to avoid import-time failure + from diffsync import DiffSyncModel as _FallbackModel + _ModelBaseClass = _FallbackModel + +# ------------------------------------------------------- +# AUTO-GENERATED FILE, DO NOT MODIFY +# This file has been generated with the command `infrahub-sync generate` +# All modifications will be lost the next time you reexecute this command +# ------------------------------------------------------- +class SdwanConfigurationGroup(_ModelBaseClass): + _modelname = "SdwanConfigurationGroup" + _identifiers = ("name",) + _attributes = ("instance", "transport_profile", "description", "cli_profile", "policy_object_profile", "system_profile", "service_profile") + transport_profile: str + description: str | None = None + cli_profile: str | None = None + policy_object_profile: str | None = None + system_profile: str + name: str + service_profile: str | None = None + instance: str + + local_id: str | None = None + local_data: Any | None = None + +class SdwanInstance(_ModelBaseClass): + _modelname = "SdwanInstance" + _identifiers = ("name",) + _attributes = ("manager_version",) + manager_version: str | None = None + name: str + + local_id: str | None = None + local_data: Any | None = None + +class SdwanRouter(_ModelBaseClass): + _modelname = "SdwanRouter" + _identifiers = ("chassis_id",) + _attributes = ("site", "configuration_group", "model") + configuration_group: str | None = None + model: str | None = None + chassis_id: str + site: str + + local_id: str | None = None + local_data: Any | None = None + +class SdwanSite(_ModelBaseClass): + _modelname = "SdwanSite" + _identifiers = ("id_value",) + _attributes = ("instance",) + id_value: int + instance: str + + local_id: str | None = None + local_data: Any | None = None diff --git a/examples/cisco_sdwan_to_infrahub/config.yml b/examples/cisco_sdwan_to_infrahub/config.yml new file mode 100644 index 000000000..0c39d4a5a --- /dev/null +++ b/examples/cisco_sdwan_to_infrahub/config.yml @@ -0,0 +1,106 @@ +--- +name: from-cisco-sdwan + +# Credentials come from CISCO_SDWAN_USERNAME and CISCO_SDWAN_PASSWORD. +# CISCO_SDWAN_URL, when set, replaces the url below. +source: + name: ciscosdwan + settings: + url: "https://sdwan-manager.example.com" + # A lab Manager often presents a self-signed certificate. Keep verification on in production. + verify_ssl: true + +destination: + name: infrahub + settings: + url: "http://localhost:8000" + +# order: omitted — infrahub-sync computes it from the references below: +# SdwanInstance, then SdwanSite and SdwanConfigurationGroup, then SdwanRouter. + +schema_mapping: + # One record describing the Manager. Its name is not reported by the API, so set it here + # and use the same value in every `instance` reference below. + - name: SdwanInstance + mapping: client/about + identifiers: ["name"] + fields: + - name: name + static: "sdwan-manager" + - name: manager_version + mapping: version + + # Sites from the network hierarchy; the global node that contains them is left out. + - name: SdwanSite + mapping: v1/network-hierarchy + identifiers: ["id_value"] + filters: + - field: data.label + operation: "==" + value: "SITE" + fields: + - name: id_value + mapping: data.hierarchyId.siteId + - name: instance + static: "sdwan-manager" + reference: SdwanInstance + + # Configuration groups with the name of the feature profile assigned for each type. + - name: SdwanConfigurationGroup + mapping: v1/config-group + identifiers: ["name"] + transforms: + - field: system_profile + expression: "{{ profiles | default([]) | selectattr('type', 'equalto', 'system') | map(attribute='name') | first | default(None) }}" + - field: transport_profile + expression: "{{ profiles | default([]) | selectattr('type', 'equalto', 'transport') | map(attribute='name') | first | default(None) }}" + - field: service_profile + expression: "{{ profiles | default([]) | selectattr('type', 'equalto', 'service') | map(attribute='name') | first | default(None) }}" + - field: cli_profile + expression: "{{ profiles | default([]) | selectattr('type', 'equalto', 'cli') | map(attribute='name') | first | default(None) }}" + - field: policy_object_profile + expression: "{{ profiles | default([]) | selectattr('type', 'equalto', 'policy-object') | map(attribute='name') | first | default(None) }}" + fields: + - name: name + mapping: name + - name: description + mapping: description + - name: system_profile + mapping: system_profile + - name: transport_profile + mapping: transport_profile + - name: service_profile + mapping: service_profile + - name: cli_profile + mapping: cli_profile + - name: policy_object_profile + mapping: policy_object_profile + - name: instance + static: "sdwan-manager" + reference: SdwanInstance + + # WAN edge routers that are assigned to a site. The inventory also lists unassigned + # chassis numbers from the device list; the filter leaves those out. + - name: SdwanRouter + mapping: system/device/vedges + identifiers: ["chassis_id"] + filters: + - field: configuredSiteId + operation: is_not_empty + transforms: + # "vedge-C8000V" becomes "C8000V", one of the router model choices. + - field: model + expression: "{{ deviceModel | replace('vedge-', '', 1) }}" + # "Config-Group edge_basic" becomes "edge_basic"; devices managed another way have none. + - field: configuration_group + expression: "{{ managed_by[13:] if managed_by is string and managed_by.startswith('Config-Group ') else None }}" + fields: + - name: chassis_id + mapping: chasisNumber # spelled this way by the API + - name: model + mapping: model + - name: configuration_group + mapping: configuration_group + - name: site + mapping: configuredSiteId + reference: SdwanSite diff --git a/examples/cisco_sdwan_to_infrahub/infrahub/__init__.py b/examples/cisco_sdwan_to_infrahub/infrahub/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/examples/cisco_sdwan_to_infrahub/infrahub/sync_adapter.py b/examples/cisco_sdwan_to_infrahub/infrahub/sync_adapter.py new file mode 100644 index 000000000..d1fb9d910 --- /dev/null +++ b/examples/cisco_sdwan_to_infrahub/infrahub/sync_adapter.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from infrahub_sync.plugin_loader import PluginLoader + +from .sync_models import ( + SdwanConfigurationGroup, + SdwanInstance, + SdwanRouter, + SdwanSite, +) + +# Load adapter class dynamically at runtime + +_AdapterBaseClass = PluginLoader().resolve("infrahub") + + +# ------------------------------------------------------- +# AUTO-GENERATED FILE, DO NOT MODIFY +# This file has been generated with the command `infrahub-sync generate` +# All modifications will be lost the next time you reexecute this command +# ------------------------------------------------------- +class InfrahubSync(_AdapterBaseClass): + SdwanConfigurationGroup = SdwanConfigurationGroup + SdwanInstance = SdwanInstance + SdwanRouter = SdwanRouter + SdwanSite = SdwanSite diff --git a/examples/cisco_sdwan_to_infrahub/infrahub/sync_models.py b/examples/cisco_sdwan_to_infrahub/infrahub/sync_models.py new file mode 100644 index 000000000..6d2a081fa --- /dev/null +++ b/examples/cisco_sdwan_to_infrahub/infrahub/sync_models.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import Any, List + +from infrahub_sync.plugin_loader import PluginLoader +# Load model class dynamically at runtime (honor adapters_path, safe fallback) +try: + + _loader = PluginLoader.from_env_and_args() + + + _spec = "infrahub" + + _ModelBaseClass = _loader.resolve(_spec, default_class_candidates=("Model",)) +except Exception: + # Fallback: use DiffSyncModel to avoid import-time failure + from diffsync import DiffSyncModel as _FallbackModel + _ModelBaseClass = _FallbackModel + +# ------------------------------------------------------- +# AUTO-GENERATED FILE, DO NOT MODIFY +# This file has been generated with the command `infrahub-sync generate` +# All modifications will be lost the next time you reexecute this command +# ------------------------------------------------------- +class SdwanConfigurationGroup(_ModelBaseClass): + _modelname = "SdwanConfigurationGroup" + _identifiers = ("name",) + _attributes = ("instance", "transport_profile", "description", "cli_profile", "policy_object_profile", "system_profile", "service_profile") + transport_profile: str + description: str | None = None + cli_profile: str | None = None + policy_object_profile: str | None = None + system_profile: str + name: str + service_profile: str | None = None + instance: str + + local_id: str | None = None + local_data: Any | None = None + +class SdwanInstance(_ModelBaseClass): + _modelname = "SdwanInstance" + _identifiers = ("name",) + _attributes = ("manager_version",) + manager_version: str | None = None + name: str + + local_id: str | None = None + local_data: Any | None = None + +class SdwanRouter(_ModelBaseClass): + _modelname = "SdwanRouter" + _identifiers = ("chassis_id",) + _attributes = ("site", "configuration_group", "model") + configuration_group: str | None = None + model: str | None = None + chassis_id: str + site: str + + local_id: str | None = None + local_data: Any | None = None + +class SdwanSite(_ModelBaseClass): + _modelname = "SdwanSite" + _identifiers = ("id_value",) + _attributes = ("instance",) + id_value: int + instance: str + + local_id: str | None = None + local_data: Any | None = None diff --git a/examples/cisco_sdwan_to_infrahub/schema.yml b/examples/cisco_sdwan_to_infrahub/schema.yml new file mode 100644 index 000000000..53eea63ca --- /dev/null +++ b/examples/cisco_sdwan_to_infrahub/schema.yml @@ -0,0 +1,432 @@ +# yaml-language-server: $schema=https://schema.infrahub.app/infrahub/schema/latest.json +# The four Sdwan nodes this example writes: instance, site, router and configuration group. +# Their definitions match a complete SD-WAN schema that also models feature templates and +# policies; relationships to those other nodes are left out, so this file loads on its own. +--- +version: '1.0' +nodes: +- name: Instance + namespace: Sdwan + label: Instances + display_label: name__value + human_friendly_id: + - name__value + order_by: + - name__value + uniqueness_constraints: + - - name__value + inherit_from: + - CoreArtifactTarget + include_in_menu: false + attributes: + - name: name + kind: Text + optional: false + - name: manager_version + kind: Text + optional: true + parameters: + regex: ^\d+(\.\d+)+$ + - name: management_ip_variable + kind: Text + label: Management IP Variable + optional: true + parameters: + regex: ^[^"~`$&+,]{1,255}$ + - name: multi_region_fabric_enabled + kind: Boolean + optional: true + relationships: + - name: sites + label: Sites + peer: SdwanSite + kind: Component + cardinality: many + identifier: sdwan__sites + optional: true + - name: configuration_groups + label: Configuration Groups + peer: SdwanConfigurationGroup + kind: Component + cardinality: many + identifier: sdwan__configuration_groups + optional: true +- name: Site + namespace: Sdwan + label: Site + display_label: id_value__value + human_friendly_id: + - id_value__value + order_by: + - id_value__value + uniqueness_constraints: + - - id_value__value + - instance + include_in_menu: false + attributes: + - name: id_value + kind: Number + optional: false + parameters: + min_value: 1 + max_value: 4294967295 + relationships: + - name: instance + label: Instance + peer: SdwanInstance + kind: Parent + cardinality: one + identifier: sdwan__sites + optional: false + - name: routers + label: Routers + peer: SdwanRouter + kind: Component + cardinality: many + identifier: sites__routers + optional: true +- name: Router + namespace: Sdwan + label: Router + display_label: chassis_id__value + human_friendly_id: + - chassis_id__value + order_by: + - chassis_id__value + uniqueness_constraints: + - - chassis_id__value + - site + include_in_menu: false + attributes: + - name: chassis_id + kind: Text + optional: false + - name: management_ip_variable + kind: Text + label: Management IP Variable + optional: true + parameters: + regex: ^[^"~`$&+,]{1,255}$ + - name: configuration_group + kind: Text + optional: true + parameters: + regex: ^[^<>!&" ]{1,128}$ + - name: configuration_group_deploy + kind: Boolean + optional: true + - name: policy_group + kind: Text + optional: true + parameters: + regex: ^[^<>!&" ]{1,128}$ + - name: policy_group_deploy + kind: Boolean + optional: true + - name: tags + kind: List + optional: true + - name: topology_label + kind: Text + optional: true + - name: model + kind: Dropdown + choices: + - name: ASR-1001-HX + label: Asr 1001 Hx + - name: ASR-1001-X + label: Asr 1001 X + - name: ASR-1002-HX + label: Asr 1002 Hx + - name: ASR-1002-X + label: Asr 1002 X + - name: ASR-1006-X + label: Asr 1006 X + - name: C1101-4P + label: C1101 4 P + - name: C1101-4PLTEP + label: C1101 4 Pltep + - name: C1101-4PLTEPW + label: C1101 4 Pltepw + - name: C1109-2PLTEGB + label: C1109 2 Pltegb + - name: C1109-2PLTEUS + label: C1109 2 Plteus + - name: C1109-2PLTEVZ + label: C1109 2 Pltevz + - name: C1109-4PLTE2P + label: C1109 4 Plte2 P + - name: C1109-4PLTE2PW + label: C1109 4 Plte2 Pw + - name: C1111-4P + label: C1111 4 P + - name: C1111-4PLTEEA + label: C1111 4 Plteea + - name: C1111-4PLTELA + label: C1111 4 Pltela + - name: C1111-4PW + label: C1111 4 Pw + - name: C1111-8P + label: C1111 8 P + - name: C1111-8PLTEEA + label: C1111 8 Plteea + - name: C1111-8PLTEEAW + label: C1111 8 Plteeaw + - name: C1111-8PLTELA + label: C1111 8 Pltela + - name: C1111-8PLTELAW + label: C1111 8 Pltelaw + - name: C1111-8PW + label: C1111 8 Pw + - name: C1111X-8P + label: C1111 X 8 P + - name: C1112-8P + label: C1112 8 P + - name: C1112-8PLTEEA + label: C1112 8 Plteea + - name: C1112-8PLTEEAWE + label: C1112 8 Plteeawe + - name: C1112-8PWE + label: C1112 8 Pwe + - name: C1113-8P + label: C1113 8 P + - name: C1113-8PLTEEA + label: C1113 8 Plteea + - name: C1113-8PLTEEAW + label: C1113 8 Plteeaw + - name: C1113-8PLTELA + label: C1113 8 Pltela + - name: C1113-8PLTELAWZ + label: C1113 8 Pltelawz + - name: C1113-8PLTEW + label: C1113 8 Pltew + - name: C1113-8PM + label: C1113 8 Pm + - name: C1113-8PMLTEEA + label: C1113 8 Pmlteea + - name: C1113-8PMWE + label: C1113 8 Pmwe + - name: C1113-8PW + label: C1113 8 Pw + - name: C1116-4P + label: C1116 4 P + - name: C1116-4PLTEEA + label: C1116 4 Plteea + - name: C1116-4PLTEEAWE + label: C1116 4 Plteeawe + - name: C1116-4PWE + label: C1116 4 Pwe + - name: C1117-4P + label: C1117 4 P + - name: C1117-4PLTEEA + label: C1117 4 Plteea + - name: C1117-4PLTEEAW + label: C1117 4 Plteeaw + - name: C1117-4PLTELA + label: C1117 4 Pltela + - name: C1117-4PLTELAWZ + label: C1117 4 Pltelawz + - name: C1117-4PM + label: C1117 4 Pm + - name: C1117-4PMLTEEA + label: C1117 4 Pmlteea + - name: C1117-4PMLTEEAWE + label: C1117 4 Pmlteeawe + - name: C1117-4PMWE + label: C1117 4 Pmwe + - name: C1117-4PW + label: C1117 4 Pw + - name: C1118-8P + label: C1118 8 P + - name: C1121-4P + label: C1121 4 P + - name: C1121-4PLTEP + label: C1121 4 Pltep + - name: C1121-8P + label: C1121 8 P + - name: C1121-8PLTEP + label: C1121 8 Pltep + - name: C1121-8PLTEPW + label: C1121 8 Pltepw + - name: C1121X-8P + label: C1121 X 8 P + - name: C1121X-8PLTEP + label: C1121 X 8 Pltep + - name: C1121X-8PLTEPW + label: C1121 X 8 Pltepw + - name: C1126-8PLTEP + label: C1126 8 Pltep + - name: C1126X-8PLTEP + label: C1126 X 8 Pltep + - name: C1127-8PLTEP + label: C1127 8 Pltep + - name: C1127-8PMLTEP + label: C1127 8 Pmltep + - name: C1127X-8PLTEP + label: C1127 X 8 Pltep + - name: C1127X-8PMLTEP + label: C1127 X 8 Pmltep + - name: C1128-8PLTEP + label: C1128 8 Pltep + - name: C1131-8PLTEPW + label: C1131 8 Pltepw + - name: C1131-8PW + label: C1131 8 Pw + - name: C1131X-8PLTEPW + label: C1131 X 8 Pltepw + - name: C1131X-8PW + label: C1131 X 8 Pw + - name: C1161-8P + label: C1161 8 P + - name: C1161-8PLTEP + label: C1161 8 Pltep + - name: C1161X-8P + label: C1161 X 8 P + - name: C1161X-8PLTEP + label: C1161 X 8 Pltep + - name: C8000V + label: C8000 V + - name: C8200-1N-4T + label: C8200 1 N 4 T + - name: C8200L-1N-4T + label: C8200 L 1 N 4 T + - name: C8300-1N1S-4T2X + label: C8300 1 N1 S 4 T2 X + - name: C8300-1N1S-6T + label: C8300 1 N1 S 6 T + - name: C8300-2N2S-4T2X + label: C8300 2 N2 S 4 T2 X + - name: C8300-2N2S-6T + label: C8300 2 N2 S 6 T + - name: C8500-12X + label: C8500 12 X + - name: C8500-12X4QC + label: C8500 12 X4 Qc + - name: C8500-20X6C + label: C8500 20 X6 C + - name: C8500L-8S4X + label: C8500 L 8 S4 X + - name: IR-1101 + label: Ir 1101 + - name: IR-1821 + label: Ir 1821 + - name: IR-1831 + label: Ir 1831 + - name: IR-1833 + label: Ir 1833 + - name: IR-1835 + label: Ir 1835 + - name: IR-8140H + label: Ir 8140 H + - name: IR-8140H-P + label: Ir 8140 H P + - name: IR-8340 + label: Ir 8340 + - name: ISR-4221 + label: Isr 4221 + - name: ISR-4221X + label: Isr 4221 X + - name: ISR-4321 + label: Isr 4321 + - name: ISR-4331 + label: Isr 4331 + - name: ISR-4351 + label: Isr 4351 + - name: ISR-4431 + label: Isr 4431 + - name: ISR-4451-X + label: Isr 4451 X + - name: ISR-4461 + label: Isr 4461 + - name: ISR1100-4G-XE + label: Isr1100 4 G Xe + - name: ISR1100-4GLTEGB-XE + label: Isr1100 4 Gltegb Xe + - name: ISR1100-4GLTENA-XE + label: Isr1100 4 Gltena Xe + - name: ISR1100-6G-XE + label: Isr1100 6 G Xe + - name: ISR1100X-4G-XE + label: Isr1100 X 4 G Xe + - name: ISR1100X-6G-XE + label: Isr1100 X 6 G Xe + optional: true + - name: device_template + kind: Text + optional: true + parameters: + regex: ^[^<>!&" ]{1,128}$ + - name: device_variables + kind: JSON + optional: true + - name: policy_variables + kind: JSON + optional: true + relationships: + - name: site + label: Sites + peer: SdwanSite + kind: Parent + cardinality: one + identifier: sites__routers + optional: false +- name: ConfigurationGroup + namespace: Sdwan + label: Configuration Group + display_label: name__value + human_friendly_id: + - name__value + order_by: + - name__value + uniqueness_constraints: + - - name__value + - instance + include_in_menu: false + attributes: + - name: name + kind: Text + optional: false + parameters: + regex: ^[^&<>! "]{1,128}$ + - name: description + kind: Text + optional: true + - name: cli_profile + kind: Text + label: CLI Profile + optional: true + parameters: + regex: ^[^&<>! "]{1,128}$ + - name: other_profile + kind: Text + optional: true + parameters: + regex: ^[^&<>! "]{1,128}$ + - name: policy_object_profile + kind: Text + optional: true + parameters: + regex: ^[^&<>! "]{1,128}$ + - name: service_profile + kind: Text + optional: true + parameters: + regex: ^[^&<>! "]{1,128}$ + - name: system_profile + kind: Text + optional: false + parameters: + regex: ^[^&<>! "]{1,128}$ + - name: transport_profile + kind: Text + optional: false + parameters: + regex: ^[^&<>! "]{1,128}$ + relationships: + - name: instance + label: Instance + peer: SdwanInstance + kind: Parent + cardinality: one + identifier: sdwan__configuration_groups + optional: false diff --git a/infrahub_sync/adapters/ciscosdwan.py b/infrahub_sync/adapters/ciscosdwan.py new file mode 100644 index 000000000..d2d3691f7 --- /dev/null +++ b/infrahub_sync/adapters/ciscosdwan.py @@ -0,0 +1,117 @@ +"""Read-only Cisco Catalyst SD-WAN Manager source built on the shared REST mapping contract.""" + +from __future__ import annotations + +import hashlib +import json +import re +from typing import TYPE_CHECKING, Any + +import structlog + +from infrahub_sync.adapters.ciscosdwan_client import CiscosdwanClient +from infrahub_sync.adapters.genericrestapi import GenericrestapiAdapter, GenericrestapiModel + +if TYPE_CHECKING: + from infrahub_sync import SyncAdapter, SyncConfig + +logger = structlog.get_logger(__name__) + +LOCAL_ID_KEY = "_sdwan_id" +LOCAL_ID_FIELDS = ("uuid", "deviceId", "recordId", "vdevice-dataKey") + + +class CiscosdwanAdapter(GenericrestapiAdapter): + """Load configured `/dataservice/` GET resources from SD-WAN Manager, as a source only.""" + + client: CiscosdwanClient + + def __init__(self, target: str, adapter: SyncAdapter, config: SyncConfig, *args: Any, **kwargs: Any) -> None: + if target != "source": + msg = "Cisco SD-WAN: this adapter can only be used as a source" + raise ValueError(msg) + super().__init__(target, adapter, config, "CiscoSdwan", *args, **kwargs) + self._responses: dict[str, list[dict[str, Any]]] = {} + + def _create_rest_client(self, settings: dict) -> CiscosdwanClient: + return CiscosdwanClient(settings) + + @staticmethod + def _prepare(record: dict[str, Any], endpoint: str, index: int) -> dict[str, Any]: + """Add a source identifier when the record has no `id`, and underscore aliases for hyphenated keys. + + Jinja2 transforms cannot name a variable such as `host-name`, so each such key is also + available as `host_name`. The original keys are kept for `mapping` and `filters`. + """ + prepared = dict(record) + if prepared.get("id") is None: + local_id = next((prepared[key] for key in LOCAL_ID_FIELDS if prepared.get(key)), None) + if local_id is None: + local_id = hashlib.sha256(json.dumps([endpoint, index]).encode()).hexdigest() + prepared = {LOCAL_ID_KEY: str(local_id), **prepared} + for key in list(prepared): + alias = re.sub(r"\W", "_", key) + if alias != key and alias not in prepared: + prepared[alias] = prepared[key] + return prepared + + def _records(self, endpoint: str) -> list[dict[str, Any]]: + """Fetch an endpoint once per run; each mapping receives its own copies of the records.""" + if endpoint not in self._responses: + self._responses[endpoint] = [ + self._prepare(record, endpoint, index) for index, record in enumerate(self.client.records(endpoint)) + ] + return [dict(record) for record in self._responses[endpoint]] + + def model_loader(self, model_name: str, model: type[GenericrestapiModel]) -> None: + """Fetch, filter and transform records, then add one model per distinct identifier.""" + element = next((item for item in self.config.schema_mapping if item.name == model_name), None) + if element is None: + msg = f"Cisco SD-WAN: {model_name}: no schema mapping is configured for this model" + raise ValueError(msg) + if not element.mapping: + msg = f"Cisco SD-WAN: {model_name}: mapping must name a GET endpoint under /dataservice/" + raise ValueError(msg) + fetched = False + try: + records = self._records(element.mapping) + fetched = True + finally: + # One session serves every mapping; log out after the last one, or as soon as a fetch fails. + if not fetched or not self.top_level or model_name == self.top_level[-1]: + self.client.close() + filtered = model.filter_records(records=records, schema_mapping=element) + transformed = model.transform_records(records=filtered, schema_mapping=element) + duplicates = 0 + for obj in transformed: + data = self.obj_to_diffsync(obj=obj, mapping=element, model=model) + for field in element.fields: + if field.static is not None: + data[field.name] = field.static + missing = [key for key in model._identifiers if data.get(key) in (None, "")] + if missing: + msg = f"Cisco SD-WAN: {model_name}: a record has no value for identifier {', '.join(missing)}" + raise ValueError(msg) + item = model(**data) + existing = self.get_or_none(model, item.get_unique_id()) + if existing is None: + self.add(item) + continue + if existing.get_attrs() != item.get_attrs(): + msg = ( + f"Cisco SD-WAN: {model_name}: several records share the identifier " + f"'{item.get_unique_id()}' with different values; add a filter or change the identifiers" + ) + raise ValueError(msg) + duplicates += 1 + logger.info( + "Cisco SD-WAN models loaded", + model=model_name, + fetched=len(records), + loaded=len(transformed) - duplicates, + duplicates=duplicates, + ) + + +class CiscosdwanModel(GenericrestapiModel): + """Source models share the REST field, filter and transform behavior.""" diff --git a/infrahub_sync/adapters/ciscosdwan_client.py b/infrahub_sync/adapters/ciscosdwan_client.py new file mode 100644 index 000000000..a5b079f76 --- /dev/null +++ b/infrahub_sync/adapters/ciscosdwan_client.py @@ -0,0 +1,343 @@ +"""Read-only Cisco Catalyst SD-WAN Manager session client and validated source settings.""" + +from __future__ import annotations + +import math +import os +import time +from datetime import datetime, timezone +from email.utils import parsedate_to_datetime +from typing import Any, Literal +from urllib.parse import parse_qsl, urlsplit + +import requests +import structlog +from pydantic import BaseModel, ConfigDict, Field, ValidationError + +from infrahub_sync.adapters.rest_api_client import RestApiClient + +logger = structlog.get_logger(__name__) + +URL_ENV = "CISCO_SDWAN_URL" +DATA_PREFIX = "/dataservice/" + + +class CiscosdwanSettings(BaseModel): + """Connection settings; credential fields contain environment variable names.""" + + model_config = ConfigDict(extra="forbid", hide_input_in_errors=True) + url: str | None = None + username_env: str = "CISCO_SDWAN_USERNAME" + password_env: str = "CISCO_SDWAN_PASSWORD" + verify_ssl: bool = True + timeout: float = Field(default=30, gt=0, allow_inf_nan=False) + retries: int = Field(default=3, ge=0) + max_retry_delay: float = Field(default=60, gt=0, allow_inf_nan=False) + + +class CiscosdwanError(ValueError): + """A Cisco SD-WAN Manager failure whose message excludes credentials and response bodies.""" + + +class CiscosdwanHTTPError(CiscosdwanError): + """An HTTP failure with a status code usable by callers.""" + + def __init__(self, status: int, resource: str, reason: str) -> None: + self.status = status + super().__init__(f"Cisco SD-WAN: {resource}: HTTP {status}: {reason}") + + +def environment_value(name: str) -> str: + """Read a required variable without including its value in failures.""" + value = os.environ.get(name) + if not value: + msg = f"Cisco SD-WAN: required environment variable {name} is not set" + raise CiscosdwanError(msg) + return value + + +def _is_html(response: requests.Response) -> bool: + """SD-WAN Manager answers an unauthenticated data request with its HTML login page.""" + return "text/html" in response.headers.get("Content-Type", "").lower() + + +class CiscosdwanClient(RestApiClient): + """GET-only client with session login, XSRF token handling and pageInfo pagination.""" + + def __init__(self, settings: dict[str, Any]) -> None: # pylint: disable=super-init-not-called + try: + self.options = CiscosdwanSettings.model_validate(settings) + except ValidationError as exc: + names = ", ".join(sorted({".".join(str(part) for part in error["loc"]) for error in exc.errors()})) + msg = f"Cisco SD-WAN: invalid source settings: {names}" + raise CiscosdwanError(msg) from None + url = os.environ.get(URL_ENV) or self.options.url + if not url: + msg = f"Cisco SD-WAN: set the url setting or the {URL_ENV} environment variable" + raise CiscosdwanError(msg) + origin = urlsplit(url.strip().rstrip("/")) + extra_components = any((origin.username, origin.password, origin.path, origin.query, origin.fragment)) + if origin.scheme != "https" or not origin.hostname or extra_components: + msg = "Cisco SD-WAN: url must be an HTTPS origin without credentials, path, query or fragment" + raise CiscosdwanError(msg) + self.base_url = f"{origin.scheme}://{origin.netloc}" + self.timeout = self.options.timeout + self._username = environment_value(self.options.username_env) + self._password = environment_value(self.options.password_env) + self._session: requests.Session | None = None + self.request_count = 0 + + @staticmethod + def resource_path(endpoint: str) -> tuple[str, dict[str, str]]: + """Split a mapping into an absolute `/dataservice/` path and its query parameters.""" + parts = urlsplit(endpoint.strip()) + path = parts.path.lstrip("/") + path = path.removeprefix(DATA_PREFIX.strip("/") + "/") + if parts.scheme or parts.netloc or parts.fragment or not path or ".." in path.split("/"): + msg = f"Cisco SD-WAN: mapping '{endpoint}' must be a path under {DATA_PREFIX}, such as 'device'" + raise CiscosdwanError(msg) + return DATA_PREFIX + path, dict(parse_qsl(parts.query, keep_blank_values=True)) + + @staticmethod + def _retry_after(response: requests.Response) -> float | None: + """Return a valid server-requested delay, or None for default backoff.""" + value = response.headers.get("Retry-After", "") + try: + delay = float(value) + except ValueError: + try: + delay = (parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds() + except (ValueError, TypeError, OverflowError): + return None + return max(0.0, delay) if math.isfinite(delay) else None + + def _perform( + self, session: requests.Session, method: str, path: str, params: dict[str, Any] | None, *, login: bool + ) -> requests.Response: + # The login form is built only in this frame. Errors raised from `_send` and its callers then + # never hold the password in a local variable that a traceback with locals would print. + form = {"j_username": self._username, "j_password": self._password} if login else None + return session.request( + method, self.base_url + path, params=params, data=form, timeout=self.timeout, allow_redirects=False + ) + + def _send( + self, + session: requests.Session, + method: Literal["GET", "POST"], + path: str, + *, + params: dict[str, Any] | None = None, + login: bool = False, + ) -> requests.Response: + """Send one request with bounded retries for timeouts, rate limits and server errors.""" + for attempt in range(self.options.retries + 1): + self.request_count += 1 + logger.debug("Cisco SD-WAN request", method=method, resource=path, requests=self.request_count) + try: + response = self._perform(session, method, path, params, login=login) + except requests.exceptions.SSLError: + msg = ( + f"Cisco SD-WAN: {path}: TLS certificate verification failed; trust the Manager certificate " + "authority or set verify_ssl: false for a lab Manager" + ) + raise CiscosdwanError(msg) from None + except (requests.Timeout, requests.ConnectionError): + if attempt == self.options.retries: + msg = f"Cisco SD-WAN: {path}: timeout or connection failure after {attempt + 1} attempts" + raise CiscosdwanError(msg) from None + time.sleep(min(2**attempt, self.options.max_retry_delay)) + continue + except requests.RequestException: + msg = f"Cisco SD-WAN: {path}: request failed" + raise CiscosdwanError(msg) from None + status = response.status_code + if not isinstance(status, int): + msg = f"Cisco SD-WAN: {path}: response lacks an HTTP status" + raise CiscosdwanError(msg) + if status == 429 or status >= 500: + if attempt == self.options.retries: + reason = "rate limit retry budget exhausted" if status == 429 else "server retries exhausted" + raise CiscosdwanHTTPError(status, path, reason) + delay = self._retry_after(response) + if delay is not None and delay > self.options.max_retry_delay: + reason = ( + f"Retry-After of {delay:.0f}s exceeds max_retry_delay of {self.options.max_retry_delay:.0f}s" + ) + raise CiscosdwanHTTPError(status, path, reason) + if delay is None: + delay = min(2**attempt, self.options.max_retry_delay) + logger.warning("Cisco SD-WAN retry", resource=path, status=status, delay=delay) + time.sleep(delay) + continue + return response + msg = f"Cisco SD-WAN: {path}: retry budget exhausted" + raise CiscosdwanError(msg) + + @staticmethod + def _login_rejected(response: requests.Response) -> bool: + """A rejected login still answers HTTP 200, with an HTML page or a JSON error body.""" + body = response.text.strip() + if not body: + return False + if " requests.Session: + """Open a session with form login, then attach the XSRF token the Manager issues for it.""" + session = requests.Session() + session.verify = self.options.verify_ssl + session.headers["Accept"] = "application/json" + response = self._send(session, "POST", "/j_security_check", login=True) + if response.status_code != 200 or self._login_rejected(response): + session.close() + status = "" if response.status_code == 200 else f" (HTTP {response.status_code})" + msg = ( + f"Cisco SD-WAN: the Manager rejected the login{status}; check the " + f"{self.options.username_env} and {self.options.password_env} environment variables" + ) + raise CiscosdwanError(msg) + token = self._send(session, "GET", DATA_PREFIX + "client/token") + if token.status_code == 200 and not _is_html(token) and token.text.strip(): + session.headers["X-XSRF-TOKEN"] = token.text.strip() + elif token.status_code == 404: + logger.info("Cisco SD-WAN Manager issues no XSRF token; continuing without one") + else: + session.close() + msg = f"Cisco SD-WAN: login failed; the Manager rejected the new session (HTTP {token.status_code})" + raise CiscosdwanError(msg) + self._session = session + logger.info("Cisco SD-WAN session opened", manager=urlsplit(self.base_url).hostname) + return session + + def close(self) -> None: + """Log out so the session does not count against the Manager session limit.""" + session, self._session = self._session, None + if session is None: + return + try: + self.request_count += 1 + response = session.post(self.base_url + "/logout", timeout=self.timeout, allow_redirects=False) + if response.status_code == 405: + self.request_count += 1 + response = session.get( + self.base_url + "/logout", + params={"nocache": str(int(time.time()))}, + timeout=self.timeout, + allow_redirects=False, + ) + logger.info("Cisco SD-WAN session closed", status=response.status_code) + except requests.RequestException: + logger.warning("Cisco SD-WAN logout failed; the Manager expires the session after its idle timeout") + finally: + session.close() + + @staticmethod + def _error_reason(response: requests.Response) -> str: + """Return the Manager's short error message, never the raw body.""" + try: + payload = response.json() + except ValueError: + return "request rejected; check the mapping path and query parameters" + error = payload.get("error") if isinstance(payload, dict) else None + message = error.get("message") if isinstance(error, dict) else None + if isinstance(message, str) and message.strip(): + return " ".join(message.split())[:200] + return "request rejected; check the mapping path and query parameters" + + def _get(self, path: str, params: dict[str, Any]) -> requests.Response: + session = self._session or self.login() + response = self._send(session, "GET", path, params=params) + if response.status_code in {401, 403} or (response.status_code == 200 and _is_html(response)): + logger.info("Cisco SD-WAN session rejected; logging in again", resource=path) + session.close() + self._session = None + response = self._send(self.login(), "GET", path, params=params) + status = response.status_code + if not isinstance(status, int): + msg = f"Cisco SD-WAN: {path}: response lacks an HTTP status" + raise CiscosdwanError(msg) + if status == 401 or (status == 200 and _is_html(response)): + raise CiscosdwanHTTPError(401, path, "the Manager rejected the session after a new login") + if status == 403: + raise CiscosdwanHTTPError(403, path, "the user lacks permission for this resource") + if status == 404: + raise CiscosdwanHTTPError(404, path, "endpoint not found; check the mapping path and Manager version") + if 300 <= status < 400: + raise CiscosdwanHTTPError(status, path, "redirect refused") + if not 200 <= status < 300: + raise CiscosdwanHTTPError(status, path, self._error_reason(response)) + return response + + @staticmethod + def _json(response: requests.Response, path: str) -> Any: + try: + return response.json() + except ValueError: + msg = f"Cisco SD-WAN: {path}: response is not valid JSON" + raise CiscosdwanError(msg) from None + + @staticmethod + def _extract(payload: Any, path: str) -> tuple[list[dict[str, Any]], Any]: + """Return the records and the pageInfo block of one response.""" + page_info = None + records = payload + if isinstance(payload, dict) and "data" in payload: + records = payload["data"] + page_info = payload.get("pageInfo") + if isinstance(records, dict): + records = [records] + if not isinstance(records, list) or any(not isinstance(item, dict) for item in records): + msg = f"Cisco SD-WAN: {path}: response must contain JSON objects" + raise CiscosdwanError(msg) + return records, page_info + + def request( + self, + method: str, + endpoint: str, + params: dict[str, Any] | None = None, + data: dict[str, Any] | None = None, + ) -> Any: + """Read one JSON response; reject the inherited REST mutation helpers unconditionally.""" + if method != "GET" or data is not None: + msg = "Cisco SD-WAN: this adapter permits only GET data requests" + raise CiscosdwanError(msg) + path, query = self.resource_path(endpoint) + return self._json(self._get(path, {**query, **(params or {})}), path) + + def records(self, endpoint: str) -> list[dict[str, Any]]: + """Read every record of a mapping, following `pageInfo` pages until `moreEntries` is false.""" + path, params = self.resource_path(endpoint) + request_start = self.request_count + records: list[dict[str, Any]] = [] + seen: set[str] = set() + while True: + page, page_info = self._extract(self._json(self._get(path, params), path), path) + records.extend(page) + if not isinstance(page_info, dict): + break + if page_info.get("hasMoreData"): + msg = f"Cisco SD-WAN: {path}: scroll pagination is not supported; choose a pageInfo or unpaged endpoint" + raise CiscosdwanError(msg) + if not page_info.get("moreEntries"): + break + end_id = page_info.get("endId") + if end_id is None or str(end_id) in seen: + msg = f"Cisco SD-WAN: {path}: pagination returned no new endId" + raise CiscosdwanError(msg) + seen.add(str(end_id)) + params = {**params, "startId": str(end_id)} + logger.info( + "Cisco SD-WAN resource fetched", + resource=path, + records=len(records), + requests=self.request_count - request_start, + total_requests=self.request_count, + ) + return records diff --git a/tests/adapters/test_ciscosdwan.py b/tests/adapters/test_ciscosdwan.py new file mode 100644 index 000000000..825258e04 --- /dev/null +++ b/tests/adapters/test_ciscosdwan.py @@ -0,0 +1,278 @@ +"""Cisco SD-WAN adapter loading: shared mapping behavior, record preparation and the example project.""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast +from unittest.mock import Mock + +import pytest +import yaml + +from infrahub_sync import SyncConfig +from infrahub_sync.adapters.ciscosdwan import LOCAL_ID_KEY, CiscosdwanAdapter, CiscosdwanModel +from infrahub_sync.adapters.ciscosdwan_client import CiscosdwanClient, CiscosdwanError + +if TYPE_CHECKING: + from types import ModuleType + +ROOT = Path(__file__).resolve().parents[2] +FIXTURES = ROOT / "tests" / "fixtures" / "ciscosdwan" +EXAMPLE = ROOT / "examples" / "cisco_sdwan_to_infrahub" + + +class Device(CiscosdwanModel): + _modelname = "Device" + _identifiers = ("name",) + _attributes = ("label", "site", "enabled") + name: str + label: str | None = None + site: str | None = None + enabled: bool | None = None + local_id: str | None = None + + +class Site(CiscosdwanModel): + _modelname = "Site" + _identifiers = ("site_id",) + _attributes = ("label",) + site_id: str + label: str | None = None + local_id: str | None = None + + +MODELS: dict[str, type[CiscosdwanModel]] = {"Device": Device, "Site": Site} + + +@pytest.fixture(autouse=True) +def _credentials(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("CISCO_SDWAN_URL", raising=False) + monkeypatch.setenv("CISCO_SDWAN_USERNAME", "invented-user") + monkeypatch.setenv("CISCO_SDWAN_PASSWORD", "invented-login-value") + + +def make_adapter(mappings: list[dict[str, Any]], records: dict[str, list[dict[str, Any]]]) -> CiscosdwanAdapter: + """Build an adapter class the way `generate` does, with a mock client serving `records`.""" + config = SyncConfig.model_validate( + { + "name": "sdwan-test", + "source": {"name": "ciscosdwan", "settings": {"url": "https://manager.example.com"}}, + "destination": {"name": "infrahub"}, + "schema_mapping": mappings, + } + ) + order = [mapping["name"] for mapping in mappings if mapping["name"] in MODELS] + sync_class = type("TestSync", (CiscosdwanAdapter,), {"top_level": order, **MODELS}) + adapter = sync_class("source", config.source, config) + fake = Mock(spec=CiscosdwanClient) + fake.records.side_effect = lambda endpoint: [dict(record) for record in records[endpoint]] + adapter.client = fake + return adapter + + +def mock_client(adapter: CiscosdwanAdapter) -> Mock: + return cast("Mock", adapter.client) + + +def loaded(adapter: CiscosdwanAdapter, model: type[CiscosdwanModel]) -> list[Any]: + return list(adapter.get_all(model)) + + +def device_mapping(**extra: object) -> dict[str, Any]: + return { + "name": "Device", + "mapping": "device", + "fields": [{"name": "name", "mapping": "host-name"}, {"name": "label", "mapping": "label"}], + **extra, + } + + +def test_destination_target_is_rejected() -> None: + config = SyncConfig.model_validate( + {"name": "x", "source": {"name": "infrahub"}, "destination": {"name": "ciscosdwan"}} + ) + with pytest.raises(ValueError, match="only be used as a source"): + CiscosdwanAdapter("destination", config.destination, config) + + +def test_hyphenated_keys_work_in_mappings_and_transforms() -> None: + adapter = make_adapter( + [ + device_mapping( + transforms=[{"field": "label", "expression": "{{ host_name | upper }}-{{ system_ip }}"}], + filters=[{"field": "device-type", "operation": "==", "value": "vedge"}], + ) + ], + { + "device": [ + {"uuid": "u1", "host-name": "Edge1", "system-ip": "10.0.0.1", "device-type": "vedge"}, + {"uuid": "u2", "host-name": "Manager01", "system-ip": "100.0.0.1", "device-type": "vmanage"}, + ] + }, + ) + adapter.model_loader("Device", Device) + assert [(item.name, item.label) for item in loaded(adapter, Device)] == [("Edge1", "EDGE1-10.0.0.1")] + + +@pytest.mark.parametrize( + ("record", "local_id"), + [ + ({"id": "native", "uuid": "u1", "host-name": "a"}, "native"), + ({"uuid": "u1", "deviceId": "10.0.0.1", "host-name": "a"}, "u1"), + ({"deviceId": "10.0.0.1", "host-name": "a"}, "10.0.0.1"), + ({"recordId": "0:Node:1:2", "host-name": "a"}, "0:Node:1:2"), + ], +) +def test_local_id_prefers_native_identifiers(record: dict[str, Any], local_id: str) -> None: + adapter = make_adapter([device_mapping()], {"device": [record]}) + adapter.model_loader("Device", Device) + assert loaded(adapter, Device)[0].local_id == local_id + + +def test_records_without_identifiers_receive_a_stable_source_id() -> None: + first = CiscosdwanAdapter._prepare({"version": "20.18.2.1"}, "client/about", 0) + again = CiscosdwanAdapter._prepare({"version": "20.18.2.1"}, "client/about", 0) + assert first[LOCAL_ID_KEY] == again[LOCAL_ID_KEY] + assert len(first[LOCAL_ID_KEY]) == 64 + assert next(iter(first)) == LOCAL_ID_KEY + + +def test_identical_duplicates_load_once_and_conflicts_stop() -> None: + record = {"uuid": "u1", "host-name": "Edge1", "label": "same"} + adapter = make_adapter([device_mapping()], {"device": [record, {**record, "uuid": "u2"}]}) + adapter.model_loader("Device", Device) + assert len(loaded(adapter, Device)) == 1 + + conflicting = make_adapter([device_mapping()], {"device": [record, {**record, "label": "other"}]}) + with pytest.raises(ValueError, match="share the identifier 'Edge1' with different values"): + conflicting.model_loader("Device", Device) + + +def test_missing_identifier_value_is_reported() -> None: + adapter = make_adapter([device_mapping()], {"device": [{"uuid": "u1", "host-name": ""}]}) + with pytest.raises(ValueError, match="no value for identifier name"): + adapter.model_loader("Device", Device) + + +def test_falsy_static_values_are_kept() -> None: + mapping = device_mapping() + mapping["fields"].append({"name": "enabled", "static": False}) + adapter = make_adapter([mapping], {"device": [{"uuid": "u1", "host-name": "Edge1"}]}) + adapter.model_loader("Device", Device) + assert loaded(adapter, Device)[0].enabled is False + + +def test_shared_endpoint_is_fetched_once_and_transforms_stay_per_mapping() -> None: + site = { + "name": "Site", + "mapping": "device", + "identifiers": ["site_id"], + "transforms": [{"field": "label", "expression": "SITE_{{ site_id }}"}], + "fields": [{"name": "site_id", "mapping": "site-id"}, {"name": "label", "mapping": "label"}], + } + records = {"device": [{"uuid": "u1", "host-name": "Edge1", "site-id": "1", "label": "original"}]} + adapter = make_adapter([site, device_mapping()], records) + adapter.model_loader("Site", Site) + adapter.model_loader("Device", Device) + assert mock_client(adapter).records.call_count == 1 + assert loaded(adapter, Site)[0].label == "SITE_1" + assert loaded(adapter, Device)[0].label == "original" + + +def test_session_closes_after_the_last_mapping() -> None: + records = {"device": [{"uuid": "u1", "host-name": "Edge1", "site-id": "1"}]} + site = {"name": "Site", "mapping": "device", "fields": [{"name": "site_id", "mapping": "site-id"}]} + adapter = make_adapter([site, device_mapping()], records) + adapter.model_loader("Site", Site) + mock_client(adapter).close.assert_not_called() + adapter.model_loader("Device", Device) + mock_client(adapter).close.assert_called_once() + + +def test_session_closes_when_a_fetch_fails() -> None: + adapter = make_adapter([device_mapping(), {"name": "Site", "mapping": "site", "fields": []}], {}) + mock_client(adapter).records.side_effect = CiscosdwanError("Cisco SD-WAN: device: failed") + with pytest.raises(CiscosdwanError): + adapter.model_loader("Device", Device) + mock_client(adapter).close.assert_called_once() + + +@pytest.mark.parametrize( + ("mapping", "message"), + [({"name": "Other", "mapping": "device"}, "no schema mapping"), (device_mapping(mapping=None), "must name a GET")], +) +def test_mapping_errors(mapping: dict[str, Any], message: str) -> None: + adapter = make_adapter([mapping], {}) + with pytest.raises(ValueError, match=message): + adapter.model_loader("Device", Device) + + +def load_example_models(monkeypatch: pytest.MonkeyPatch) -> ModuleType: + spec = importlib.util.spec_from_file_location( + "ciscosdwan_example_models", EXAMPLE / "ciscosdwan" / "sync_models.py" + ) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + # Pydantic resolves the generated postponed annotations through the registered module. + monkeypatch.setitem(sys.modules, spec.name, module) + spec.loader.exec_module(module) + return module + + +def fixture_records(name: str) -> list[dict[str, Any]]: + payload = json.loads((FIXTURES / name).read_text()) + records = payload["data"] if isinstance(payload, dict) and "data" in payload else payload + return records if isinstance(records, list) else [records] + + +def test_example_project_maps_manager_inventory(monkeypatch: pytest.MonkeyPatch) -> None: + config = SyncConfig.model_validate(yaml.safe_load((EXAMPLE / "config.yml").read_text())) + models = load_example_models(monkeypatch) + order = config.compute_order() + sync_class = type( + "ExampleSync", (CiscosdwanAdapter,), {"top_level": order, **{name: getattr(models, name) for name in order}} + ) + adapter = sync_class("source", config.source, config) + payloads = { + "client/about": fixture_records("about.json"), + "v1/network-hierarchy": fixture_records("network-hierarchy.json"), + "v1/config-group": fixture_records("config-group.json"), + "system/device/vedges": fixture_records("vedges.json"), + } + fake = Mock(spec=CiscosdwanClient) + fake.records.side_effect = lambda endpoint: payloads[endpoint] + adapter.client = fake + adapter.load() + + assert order == ["SdwanInstance", "SdwanConfigurationGroup", "SdwanSite", "SdwanRouter"] + fake.close.assert_called_once() + attrs = {name: {obj.get_unique_id(): obj.get_attrs() for obj in adapter.get_all(name)} for name in order} + assert attrs["SdwanInstance"] == {"sdwan-manager": {"manager_version": "20.18.2.1"}} + assert attrs["SdwanSite"] == { + "1": {"instance": "sdwan-manager"}, + "2": {"instance": "sdwan-manager"}, + "100": {"instance": "sdwan-manager"}, + } + assert attrs["SdwanConfigurationGroup"] == { + "edge_basic": { + "instance": "sdwan-manager", + "description": "Do not modify!", + "system_profile": "edge_basic_system", + "transport_profile": "edge_basic_wan", + "service_profile": "edge_basic_lan", + "cli_profile": "edge_basic_cli", + "policy_object_profile": "Default_Policy_Object_Profile", + } + } + assert attrs["SdwanRouter"] == { + "C8K-3D1A8960-6E76-532C-DA93-50626FC5797E": { + "site": "1", + "model": "C8000V", + "configuration_group": "edge_basic", + }, + "C8K-D4CE7174-5261-7E6F-91EA-4926BCF4C2DD": {"site": "2", "model": "C8000V", "configuration_group": None}, + } diff --git a/tests/adapters/test_ciscosdwan_client.py b/tests/adapters/test_ciscosdwan_client.py new file mode 100644 index 000000000..88f3784d1 --- /dev/null +++ b/tests/adapters/test_ciscosdwan_client.py @@ -0,0 +1,377 @@ +"""Cisco SD-WAN Manager HTTP contract tests, with no real credentials or network traffic.""" + +from __future__ import annotations + +import json +from unittest.mock import Mock + +import pytest +import requests +from rich.console import Console +from rich.traceback import Traceback +from structlog.testing import capture_logs + +from infrahub_sync.adapters.ciscosdwan_client import CiscosdwanClient, CiscosdwanError, CiscosdwanHTTPError + +LOGIN_VALUE = "invented-login-value" +URL = "https://manager.example.com" + + +def response( + payload: object = None, status: int = 200, *, text: str | None = None, content_type: str = "application/json" +) -> requests.Response: + result = requests.Response() + result.status_code = status + body = text if text is not None else json.dumps(payload if payload is not None else {"data": []}) + result._content = body.encode() + result.encoding = "utf-8" + result.headers["Content-Type"] = content_type + return result + + +def login_ok() -> list[requests.Response]: + return [response(text=""), response(text="invented-xsrf-value", content_type="text/plain")] + + +def login_page() -> requests.Response: + return response(text="Cisco Catalyst SD-WAN", content_type="text/html") + + +@pytest.fixture(name="http") +def _http_fixture(monkeypatch: pytest.MonkeyPatch) -> Mock: + monkeypatch.delenv("CISCO_SDWAN_URL", raising=False) + monkeypatch.setenv("CISCO_SDWAN_USERNAME", "invented-user") + monkeypatch.setenv("CISCO_SDWAN_PASSWORD", LOGIN_VALUE) + mock = Mock() + monkeypatch.setattr(requests.Session, "request", mock) + monkeypatch.setattr("infrahub_sync.adapters.ciscosdwan_client.time.sleep", Mock()) + return mock + + +def client(**settings: object) -> CiscosdwanClient: + return CiscosdwanClient({"url": URL, **settings}) + + +def test_login_then_get_uses_form_login_and_xsrf_token(http: Mock) -> None: + http.side_effect = [*login_ok(), response({"data": [{"uuid": "a"}]})] + sdwan = client() + assert sdwan.records("device") == [{"uuid": "a"}] + login, token, data = http.call_args_list + assert login.args == ("POST", f"{URL}/j_security_check") + assert login.kwargs["data"] == {"j_username": "invented-user", "j_password": LOGIN_VALUE} + assert token.args == ("GET", f"{URL}/dataservice/client/token") + assert data.args == ("GET", f"{URL}/dataservice/device") + assert all(call.kwargs["allow_redirects"] is False for call in http.call_args_list) + assert sdwan._session is not None + assert sdwan._session.headers["X-XSRF-TOKEN"] == "invented-xsrf-value" + assert sdwan.request_count == 3 + + +@pytest.mark.parametrize( + "rejection", + [ + response({"error": {"message": "Login Error", "details": " invented-user"}}), + login_page(), + response(text="", status=401), + ], +) +def test_rejected_login_names_variables_not_values(rejection: requests.Response, http: Mock) -> None: + http.side_effect = [rejection] * 4 + with pytest.raises(CiscosdwanError, match="CISCO_SDWAN_USERNAME and CISCO_SDWAN_PASSWORD") as exc: + client(retries=0).records("device") + assert LOGIN_VALUE not in str(exc.value) + assert "invented-user" not in str(exc.value) + + +def test_login_without_token_endpoint_continues(http: Mock) -> None: + http.side_effect = [response(text=""), response(text="", status=404), response({"data": []})] + sdwan = client() + assert sdwan.records("device") == [] + assert sdwan._session is not None + assert "X-XSRF-TOKEN" not in sdwan._session.headers + + +def test_login_page_as_token_rejects_session(http: Mock) -> None: + http.side_effect = [response(text=""), login_page()] + with pytest.raises(CiscosdwanError, match="rejected the new session"): + client().records("device") + + +@pytest.mark.parametrize("expired", [login_page(), response(status=401), response(status=403)]) +def test_expired_session_logs_in_once_more(expired: requests.Response, http: Mock) -> None: + http.side_effect = [*login_ok(), expired, *login_ok(), response({"data": [{"id": "1"}]})] + assert client().records("device") == [{"id": "1"}] + assert [call.args[1].rsplit("/", 1)[-1] for call in http.call_args_list] == [ + "j_security_check", + "token", + "device", + "j_security_check", + "token", + "device", + ] + + +@pytest.mark.parametrize( + ("final", "status", "reason"), + [ + (login_page(), 401, "rejected the session"), + (response(status=403), 403, "lacks permission"), + (response(status=404), 404, "endpoint not found"), + ( + response({"error": {"message": "Invalid query", "details": "invented-user"}}, status=400), + 400, + "Invalid query", + ), + (response(text="not json", status=400), 400, "check the mapping path"), + (response(status=302), 302, "redirect refused"), + ], +) +def test_http_failures_report_status_and_short_reason( + final: requests.Response, status: int, reason: str, http: Mock +) -> None: + expired = [login_page(), *login_ok()] if status in {401, 403} else [] + http.side_effect = [*login_ok(), *expired, final] + with pytest.raises(CiscosdwanHTTPError, match=reason) as exc: + client().records("device") + assert exc.value.status == status + assert "/dataservice/device" in str(exc.value) + assert "invented-user" not in str(exc.value) + + +def test_page_info_pagination_follows_end_id(http: Mock) -> None: + http.side_effect = [ + *login_ok(), + response({"data": [{"id": 1}], "pageInfo": {"startId": "1", "endId": "10", "moreEntries": True}}), + response({"data": [{"id": 2}], "pageInfo": {"startId": "11", "endId": "20", "moreEntries": True}}), + response({"data": [], "pageInfo": {"startId": "21", "endId": "21", "moreEntries": False}}), + ] + records = client().records("data/device/state/CEdgeInterface?count=10") + assert records == [{"id": 1}, {"id": 2}] + params = [call.kwargs["params"] for call in http.call_args_list[2:]] + assert params == [{"count": "10"}, {"count": "10", "startId": "10"}, {"count": "10", "startId": "20"}] + + +@pytest.mark.parametrize( + ("page_info", "message"), + [ + ({"endId": "10", "moreEntries": True}, "no new endId"), + ({"moreEntries": True}, "no new endId"), + ({"scrollId": "abc", "hasMoreData": True}, "scroll pagination is not supported"), + ], +) +def test_pagination_stops_on_cycles_and_unsupported_scrolling(page_info: dict, message: str, http: Mock) -> None: + http.side_effect = [*login_ok()] + [response({"data": [{"id": 1}], "pageInfo": page_info})] * 3 + with pytest.raises(CiscosdwanError, match=message): + client().records("data/device/state/Interface") + + +@pytest.mark.parametrize( + ("payload", "records"), + [ + ({"data": [{"id": "1"}]}, [{"id": "1"}]), + ({"header": {}, "data": {"version": "20.18.2.1"}}, [{"version": "20.18.2.1"}]), + ([{"id": "1"}, {"id": "2"}], [{"id": "1"}, {"id": "2"}]), + ({"version": "20.18.2.1"}, [{"version": "20.18.2.1"}]), + ], +) +def test_response_shapes(payload: object, records: list, http: Mock) -> None: + http.side_effect = [*login_ok(), response(payload)] + assert client().records("client/about") == records + + +@pytest.mark.parametrize("payload", [{"data": ["text"]}, {"data": "text"}, ["text"]]) +def test_non_object_records_are_rejected(payload: object, http: Mock) -> None: + http.side_effect = [*login_ok(), response(payload)] + with pytest.raises(CiscosdwanError, match="must contain JSON objects"): + client().records("device") + + +def test_invalid_json_is_rejected(http: Mock) -> None: + http.side_effect = [*login_ok(), response(text="{not json")] + with pytest.raises(CiscosdwanError, match="not valid JSON"): + client().records("device") + + +def test_server_errors_and_rate_limits_are_retried(http: Mock) -> None: + rate_limited = response(status=429) + rate_limited.headers["Retry-After"] = "2" + http.side_effect = [*login_ok(), response(status=503), rate_limited, response({"data": [{"id": "1"}]})] + assert client().records("device") == [{"id": "1"}] + assert http.call_count == 5 + + +def test_retry_after_above_limit_stops(http: Mock) -> None: + rate_limited = response(status=429) + rate_limited.headers["Retry-After"] = "600" + http.side_effect = [*login_ok(), rate_limited] + with pytest.raises(CiscosdwanHTTPError, match="exceeds max_retry_delay") as exc: + client().records("device") + assert exc.value.status == 429 + + +def test_retries_are_bounded(http: Mock) -> None: + http.side_effect = [*login_ok(), response(status=500), response(status=500)] + with pytest.raises(CiscosdwanHTTPError, match="server retries exhausted"): + client(retries=1).records("device") + + +def test_timeouts_are_retried_then_reported(http: Mock) -> None: + http.side_effect = requests.Timeout("invented detail") + with pytest.raises(CiscosdwanError, match="timeout or connection failure after 3 attempts") as exc: + client(retries=2).records("device") + assert "invented detail" not in str(exc.value) + + +def test_certificate_failure_explains_verify_ssl(http: Mock) -> None: + http.side_effect = requests.exceptions.SSLError("invented detail") + with pytest.raises(CiscosdwanError, match="verify_ssl: false"): + client().records("device") + + +def test_verify_ssl_applies_to_the_session(http: Mock) -> None: + http.side_effect = [*login_ok(), *login_ok()] + assert client().login().verify is True + assert client(verify_ssl=False).login().verify is False + + +def test_close_posts_logout_once(http: Mock) -> None: + http.side_effect = [*login_ok(), response(text="", status=302)] + sdwan = client() + sdwan.login() + sdwan.close() + sdwan.close() + assert http.call_args_list[-1].args == ("POST", f"{URL}/logout") + assert http.call_count == 3 + assert sdwan._session is None + + +def test_close_falls_back_to_get_logout_on_older_managers(http: Mock) -> None: + http.side_effect = [*login_ok(), response(text="", status=405), response(text="", status=200)] + sdwan = client() + sdwan.login() + sdwan.close() + assert http.call_args_list[-1].args == ("GET", f"{URL}/logout") + assert "nocache" in http.call_args_list[-1].kwargs["params"] + + +def test_close_failure_is_logged_not_raised(http: Mock) -> None: + http.side_effect = [*login_ok(), requests.ConnectionError("invented detail")] + sdwan = client() + sdwan.login() + with capture_logs() as logs: + sdwan.close() + assert any("logout failed" in entry["event"] for entry in logs) + assert sdwan._session is None + + +@pytest.mark.parametrize("method", ["post", "patch", "put"]) +def test_mutation_helpers_are_rejected(method: str, http: Mock) -> None: + with pytest.raises(CiscosdwanError, match="only GET"): + getattr(client(), method)("device", data={"name": "x"}) + http.assert_not_called() + + +def test_delete_is_rejected(http: Mock) -> None: + with pytest.raises(CiscosdwanError, match="only GET"): + client().delete("device") + http.assert_not_called() + + +def test_get_returns_one_payload(http: Mock) -> None: + http.side_effect = [*login_ok(), response({"data": {"version": "20.18.2.1"}})] + assert client().get("client/about", params={"x": "1"}) == {"data": {"version": "20.18.2.1"}} + assert http.call_args_list[-1].kwargs["params"] == {"x": "1"} + + +@pytest.mark.parametrize( + ("endpoint", "path", "params"), + [ + ("device", "/dataservice/device", {}), + ("/dataservice/device", "/dataservice/device", {}), + ("dataservice/v1/config-group", "/dataservice/v1/config-group", {}), + (" data/device/state/Interface?count=500 ", "/dataservice/data/device/state/Interface", {"count": "500"}), + ], +) +def test_resource_path_accepts_dataservice_paths(endpoint: str, path: str, params: dict) -> None: + assert CiscosdwanClient.resource_path(endpoint) == (path, params) + + +@pytest.mark.parametrize( + "endpoint", ["", "/", "/dataservice/", "https://other.example.com/dataservice/device", "../logout", "device#x"] +) +def test_resource_path_rejects_other_locations(endpoint: str) -> None: + with pytest.raises(CiscosdwanError, match=r"must be a path under /dataservice/"): + CiscosdwanClient.resource_path(endpoint) + + +@pytest.mark.parametrize( + ("settings", "message"), + [ + ({"url": None}, "set the url setting or the CISCO_SDWAN_URL"), + ({"url": "http://manager.example.com"}, "HTTPS origin"), + ({"url": "https://manager.example.com/dataservice"}, "HTTPS origin"), + ({"url": "https://user:pass@manager.example.com"}, "HTTPS origin"), + ({"timeout": 0}, "invalid source settings: timeout"), + ({"unknown": True}, "invalid source settings: unknown"), + ], +) +def test_invalid_settings_fail_before_requests(settings: dict, message: str, http: Mock) -> None: + with pytest.raises(CiscosdwanError, match=message): + CiscosdwanClient({"url": URL, **settings}) + http.assert_not_called() + + +def test_url_environment_variable_replaces_setting(monkeypatch: pytest.MonkeyPatch, http: Mock) -> None: + monkeypatch.setenv("CISCO_SDWAN_URL", "https://env-manager.example.com:8443/") + assert client().base_url == "https://env-manager.example.com:8443" + http.assert_not_called() + + +def test_missing_credentials_name_the_variable(monkeypatch: pytest.MonkeyPatch, http: Mock) -> None: + monkeypatch.delenv("CISCO_SDWAN_PASSWORD") + with pytest.raises(CiscosdwanError, match="CISCO_SDWAN_PASSWORD is not set"): + client() + with pytest.raises(CiscosdwanError, match="OTHER_PASSWORD is not set"): + client(password_env="OTHER_PASSWORD") # noqa: S106 - a variable name, not a value + http.assert_not_called() + + +def test_logs_exclude_credentials_and_tokens(http: Mock) -> None: + http.side_effect = [*login_ok(), response({"data": [{"id": "1"}]}), response(text="", status=302)] + sdwan = client() + with capture_logs() as logs: + sdwan.records("device") + sdwan.close() + text = json.dumps(logs, default=str) + assert LOGIN_VALUE not in text + assert "invented-xsrf-value" not in text + assert any(entry["event"] == "Cisco SD-WAN resource fetched" for entry in logs) + + +def render_failure(sdwan: CiscosdwanClient) -> str: + """Render the failure the way the CLI would with local-variable display turned on.""" + with pytest.raises(CiscosdwanError) as exc: + sdwan.records("device") + rendered = Traceback.from_exception(exc.type, exc.value, exc.tb, show_locals=True) + console = Console(record=True, width=200) + with console.capture() as captured: + console.print(rendered) + return captured.get() + + +@pytest.mark.parametrize( + "failure", + [ + requests.Timeout("invented detail"), + requests.exceptions.SSLError("invented detail"), + [response({"error": {"message": "Login Error"}})], + [*login_ok(), response(status=500)], + ], + ids=["timeout", "certificate", "rejected-login", "server-error"], +) +def test_tracebacks_with_locals_exclude_credentials(failure: object, http: Mock) -> None: + http.side_effect = failure + output = render_failure(client(retries=0)) + assert "Cisco SD-WAN" in output + assert LOGIN_VALUE not in output + assert "invented-xsrf-value" not in output diff --git a/tests/fixtures/ciscosdwan/about.json b/tests/fixtures/ciscosdwan/about.json new file mode 100644 index 000000000..db9f5d071 --- /dev/null +++ b/tests/fixtures/ciscosdwan/about.json @@ -0,0 +1,8 @@ +{ + "header": {}, + "data": { + "title": "Cisco vManage", + "version": "20.18.2.1", + "applicationServer": "Manager01" + } +} diff --git a/tests/fixtures/ciscosdwan/config-group.json b/tests/fixtures/ciscosdwan/config-group.json new file mode 100644 index 000000000..290228d20 --- /dev/null +++ b/tests/fixtures/ciscosdwan/config-group.json @@ -0,0 +1,36 @@ +[ + { + "id": "0cd3c1bd-254d-42f8-a932-1dd4d107c551", + "name": "edge_basic", + "description": "Do not modify!", + "solution": "sdwan", + "numberOfDevices": 4, + "profiles": [ + { + "id": "4d8a5c47-8d39-4716-b7cb-a99c67d34a06", + "name": "Default_Policy_Object_Profile", + "type": "policy-object" + }, + { + "id": "67bb7050-183b-4f91-92b3-a4a0873b3015", + "name": "edge_basic_system", + "type": "system" + }, + { + "id": "0986158a-cd99-45ea-9e5a-7bbaae762bcd", + "name": "edge_basic_wan", + "type": "transport" + }, + { + "id": "a98165bd-c012-4ea7-9e08-93db46123b1c", + "name": "edge_basic_lan", + "type": "service" + }, + { + "id": "d1463291-587d-40a3-9e98-15a83f29a173", + "name": "edge_basic_cli", + "type": "cli" + } + ] + } +] diff --git a/tests/fixtures/ciscosdwan/network-hierarchy.json b/tests/fixtures/ciscosdwan/network-hierarchy.json new file mode 100644 index 000000000..1174296b1 --- /dev/null +++ b/tests/fixtures/ciscosdwan/network-hierarchy.json @@ -0,0 +1,53 @@ +[ + { + "name": "Global", + "description": "Global node for network hierarchy", + "data": { + "label": "GLOBAL" + }, + "id": "62b65697-4044-4b68-995e-86dd56626512", + "hierarchyPath": "Global" + }, + { + "uuid": "6eb02264-df0c-40e4-b473-84c543af5d53", + "name": "SITE_1", + "description": "Auto-Generated Site", + "data": { + "parentUuid": "62b65697-4044-4b68-995e-86dd56626512", + "label": "SITE", + "hierarchyId": { + "siteId": 1 + } + }, + "id": "6eb02264-df0c-40e4-b473-84c543af5d53", + "hierarchyPath": "Global/SITE_1" + }, + { + "uuid": "83fe213c-e97e-4407-8fc0-526eb0cb1ad9", + "name": "SITE_2", + "description": "Auto-Generated Site", + "data": { + "parentUuid": "62b65697-4044-4b68-995e-86dd56626512", + "label": "SITE", + "hierarchyId": { + "siteId": 2 + } + }, + "id": "83fe213c-e97e-4407-8fc0-526eb0cb1ad9", + "hierarchyPath": "Global/SITE_2" + }, + { + "uuid": "c955b38b-edd4-4058-a4b6-f2fda4b9414d", + "name": "SITE_100", + "description": "Auto-Generated Site", + "data": { + "parentUuid": "62b65697-4044-4b68-995e-86dd56626512", + "label": "SITE", + "hierarchyId": { + "siteId": 100 + } + }, + "id": "c955b38b-edd4-4058-a4b6-f2fda4b9414d", + "hierarchyPath": "Global/SITE_100" + } +] diff --git a/tests/fixtures/ciscosdwan/vedges.json b/tests/fixtures/ciscosdwan/vedges.json new file mode 100644 index 000000000..24a799d94 --- /dev/null +++ b/tests/fixtures/ciscosdwan/vedges.json @@ -0,0 +1,48 @@ +{ + "header": { + "generatedOn": 1794852134619 + }, + "data": [ + { + "deviceType": "vedge", + "serialNumber": "63D67D6C", + "uuid": "C8K-3D1A8960-6E76-532C-DA93-50626FC5797E", + "chasisNumber": "C8K-3D1A8960-6E76-532C-DA93-50626FC5797E", + "deviceModel": "vedge-C8000V", + "configuredHostname": "Edge1", + "configuredSiteId": "1", + "host-name": "Edge1", + "site-id": "1", + "system-ip": "10.0.0.1", + "managed-by": "Config-Group edge_basic", + "groupTopologyLabel": "", + "reachability": "reachable", + "version": "17.18.01a.0.182" + }, + { + "deviceType": "vedge", + "serialNumber": "BADC3D49", + "uuid": "C8K-D4CE7174-5261-7E6F-91EA-4926BCF4C2DD", + "chasisNumber": "C8K-D4CE7174-5261-7E6F-91EA-4926BCF4C2DD", + "deviceModel": "vedge-C8000V", + "configuredHostname": "Edge2", + "configuredSiteId": "2", + "host-name": "Edge2", + "site-id": "2", + "system-ip": "10.0.0.2", + "managed-by": "Template Branch_C8000V", + "groupTopologyLabel": "", + "reachability": "reachable", + "version": "17.18.01a.0.182" + }, + { + "deviceType": "vedge", + "serialNumber": "ec73ec75ccd7485c9b1501911b5558b9", + "uuid": "C8K-E5FA8EFC-7B65-C148-2D23-2C72D2745EFA", + "chasisNumber": "C8K-E5FA8EFC-7B65-C148-2D23-2C72D2745EFA", + "deviceModel": "vedge-C8000V-SD-ROUTING", + "managed-by": "Unmanaged", + "groupTopologyLabel": "NA" + } + ] +}