ui-network-mcp 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. ui_network_mcp/__init__.py +19 -0
  2. ui_network_mcp/client/__init__.py +5 -0
  3. ui_network_mcp/client/errors.py +49 -0
  4. ui_network_mcp/client/json_types.py +3 -0
  5. ui_network_mcp/client/redaction.py +29 -0
  6. ui_network_mcp/client/unifi_client.py +120 -0
  7. ui_network_mcp/config.py +50 -0
  8. ui_network_mcp/models/__init__.py +5 -0
  9. ui_network_mcp/models/api_model.py +27 -0
  10. ui_network_mcp/models/firewall/__init__.py +21 -0
  11. ui_network_mcp/models/firewall/action.py +32 -0
  12. ui_network_mcp/models/firewall/matching.py +137 -0
  13. ui_network_mcp/models/firewall/policy.py +26 -0
  14. ui_network_mcp/models/firewall/protocol.py +150 -0
  15. ui_network_mcp/models/firewall/schedule.py +57 -0
  16. ui_network_mcp/models/firewall/traffic_filters.py +132 -0
  17. ui_network_mcp/reports/__init__.py +31 -0
  18. ui_network_mcp/reports/client_search.py +39 -0
  19. ui_network_mcp/reports/client_summary.py +65 -0
  20. ui_network_mcp/reports/device_health.py +47 -0
  21. ui_network_mcp/reports/device_summary.py +6 -0
  22. ui_network_mcp/reports/firewall_overview.py +124 -0
  23. ui_network_mcp/reports/network_map.py +64 -0
  24. ui_network_mcp/reports/site_health.py +72 -0
  25. ui_network_mcp/reports/switch_ports.py +77 -0
  26. ui_network_mcp/reports/topology.py +46 -0
  27. ui_network_mcp/reports/unused_objects.py +78 -0
  28. ui_network_mcp/reports/voucher_summary.py +67 -0
  29. ui_network_mcp/reports/wifi_overview.py +113 -0
  30. ui_network_mcp/server/__init__.py +3 -0
  31. ui_network_mcp/server/app.py +53 -0
  32. ui_network_mcp/server/parameters.py +55 -0
  33. ui_network_mcp/server/sites.py +48 -0
  34. ui_network_mcp/server/tools/__init__.py +44 -0
  35. ui_network_mcp/server/tools/acl.py +37 -0
  36. ui_network_mcp/server/tools/audit.py +46 -0
  37. ui_network_mcp/server/tools/clients.py +137 -0
  38. ui_network_mcp/server/tools/console.py +23 -0
  39. ui_network_mcp/server/tools/devices.py +152 -0
  40. ui_network_mcp/server/tools/dns.py +31 -0
  41. ui_network_mcp/server/tools/dpi.py +33 -0
  42. ui_network_mcp/server/tools/firewall.py +134 -0
  43. ui_network_mcp/server/tools/firewall_writes.py +220 -0
  44. ui_network_mcp/server/tools/health.py +49 -0
  45. ui_network_mcp/server/tools/hotspot.py +158 -0
  46. ui_network_mcp/server/tools/networks.py +77 -0
  47. ui_network_mcp/server/tools/switching.py +100 -0
  48. ui_network_mcp/server/tools/topology.py +26 -0
  49. ui_network_mcp/server/tools/vpn.py +39 -0
  50. ui_network_mcp/server/tools/wifi.py +60 -0
  51. ui_network_mcp-0.1.0.dist-info/METADATA +263 -0
  52. ui_network_mcp-0.1.0.dist-info/RECORD +55 -0
  53. ui_network_mcp-0.1.0.dist-info/WHEEL +4 -0
  54. ui_network_mcp-0.1.0.dist-info/entry_points.txt +3 -0
  55. ui_network_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,19 @@
1
+ import sys
2
+
3
+
4
+ def main() -> None:
5
+ from pydantic import ValidationError
6
+
7
+ from ui_network_mcp.server import create_server
8
+
9
+ try:
10
+ server = create_server()
11
+ except ValidationError as error:
12
+ problems = "; ".join(
13
+ f"{'.'.join(map(str, e['loc'])) or 'settings'}: {e['msg']}"
14
+ for e in error.errors()
15
+ )
16
+ sys.exit(
17
+ f"ui-network-mcp: invalid configuration ({problems}). Set the UNIFI_* environment variables."
18
+ )
19
+ server.run()
@@ -0,0 +1,5 @@
1
+ from ui_network_mcp.client.errors import UniFiAPIError
2
+ from ui_network_mcp.client.json_types import JSON
3
+ from ui_network_mcp.client.unifi_client import MAX_PAGE_SIZE, UniFiClient
4
+
5
+ __all__ = ["JSON", "MAX_PAGE_SIZE", "UniFiAPIError", "UniFiClient"]
@@ -0,0 +1,49 @@
1
+ import httpx
2
+ from fastmcp.exceptions import ToolError
3
+
4
+
5
+ class UniFiAPIError(ToolError):
6
+ """An error response from the UniFi Network API. FastMCP sends the message to the MCP client."""
7
+
8
+ def __init__(
9
+ self,
10
+ status_code: int,
11
+ message: str,
12
+ code: str | None = None,
13
+ request_id: str | None = None,
14
+ hint: str | None = None,
15
+ ):
16
+ self.status_code = status_code
17
+ self.code = code
18
+ self.request_id = request_id
19
+ detail = f"UniFi API error {status_code}"
20
+ if code:
21
+ detail += f" ({code})"
22
+ detail += f": {message}"
23
+ if request_id:
24
+ detail += f" [requestId={request_id}]"
25
+ if hint:
26
+ detail += f" {hint}"
27
+ super().__init__(detail)
28
+
29
+ @classmethod
30
+ def from_response(cls, response: httpx.Response) -> UniFiAPIError:
31
+ """Make an error from an error response. The body of the response is optional."""
32
+ try:
33
+ body = response.json()
34
+ except ValueError:
35
+ body = {}
36
+ if not isinstance(body, dict):
37
+ body = {}
38
+ hint = None
39
+ if response.status_code in (401, 403) and response.request.method != "GET":
40
+ hint = "Make sure that the API key has write access."
41
+ return cls(
42
+ status_code=response.status_code,
43
+ message=body.get("message")
44
+ or response.reason_phrase
45
+ or response.text[:200],
46
+ code=body.get("code"),
47
+ request_id=body.get("requestId"),
48
+ hint=hint,
49
+ )
@@ -0,0 +1,3 @@
1
+ from typing import Any
2
+
3
+ JSON = dict[str, Any]
@@ -0,0 +1,29 @@
1
+ """Redaction of the secrets in API responses, so that the secrets do not get to the agent."""
2
+
3
+ from typing import Any
4
+
5
+ REDACTED = "***REDACTED***"
6
+ # The API uses these keys for secrets. In version 11.0.97, the only secrets are the WiFi
7
+ # passphrases of the WPA2, WPA2/WPA3, and WPA3 personal broadcasts and their pre-shared keys.
8
+ SECRET_KEYS = frozenset({"passphrase"})
9
+
10
+
11
+ def redact(value: Any) -> Any:
12
+ """Return a copy of a JSON value that has REDACTED in place of each secret."""
13
+ if isinstance(value, dict):
14
+ return {
15
+ key: REDACTED if key in SECRET_KEYS and item is not None else redact(item)
16
+ for key, item in value.items()
17
+ }
18
+ if isinstance(value, list):
19
+ return [redact(item) for item in value]
20
+ return value
21
+
22
+
23
+ def contains_redacted(value: Any) -> bool:
24
+ """Return True if REDACTED is a value anywhere in a JSON value."""
25
+ if isinstance(value, dict):
26
+ return any(contains_redacted(item) for item in value.values())
27
+ if isinstance(value, list):
28
+ return any(contains_redacted(item) for item in value)
29
+ return value == REDACTED
@@ -0,0 +1,120 @@
1
+ import asyncio
2
+ from typing import Any
3
+
4
+ import httpx
5
+ from fastmcp.exceptions import ToolError
6
+
7
+ from ui_network_mcp.client.errors import UniFiAPIError
8
+ from ui_network_mcp.client.json_types import JSON
9
+ from ui_network_mcp.client.redaction import REDACTED, contains_redacted, redact
10
+ from ui_network_mcp.config import Settings
11
+
12
+ MAX_PAGE_SIZE = 200
13
+
14
+
15
+ class UniFiClient:
16
+ """A thin async wrapper around the UniFi Network integration API."""
17
+
18
+ def __init__(self, http: httpx.AsyncClient):
19
+ self._http = http
20
+
21
+ @classmethod
22
+ def from_settings(cls, settings: Settings) -> UniFiClient:
23
+ http = httpx.AsyncClient(
24
+ base_url=settings.resolved_base_url,
25
+ headers={
26
+ "X-API-KEY": settings.api_key.get_secret_value(),
27
+ "Accept": "application/json",
28
+ },
29
+ verify=settings.verify_tls,
30
+ timeout=settings.timeout,
31
+ )
32
+ return cls(http)
33
+
34
+ async def aclose(self) -> None:
35
+ await self._http.aclose()
36
+
37
+ async def get(self, path: str, params: dict[str, Any] | None = None) -> Any:
38
+ return await self._request("GET", path, params=_without_none(params or {}))
39
+
40
+ async def post(self, path: str, body: JSON) -> Any:
41
+ """Send a POST request. The body does not include keys with a None value."""
42
+ return await self._request("POST", path, json=_write_body(body))
43
+
44
+ async def put(
45
+ self, path: str, body: JSON, params: dict[str, Any] | None = None
46
+ ) -> Any:
47
+ """Send a PUT request. The body does not include keys with a None value."""
48
+ return await self._request(
49
+ "PUT", path, json=_write_body(body), params=_without_none(params or {})
50
+ )
51
+
52
+ async def patch(self, path: str, body: JSON) -> Any:
53
+ """Send a PATCH request. The body does not include keys with a None value."""
54
+ return await self._request("PATCH", path, json=_write_body(body))
55
+
56
+ async def delete(self, path: str, params: dict[str, Any] | None = None) -> Any:
57
+ return await self._request("DELETE", path, params=_without_none(params or {}))
58
+
59
+ async def _request(self, method: str, path: str, **kwargs: Any) -> Any:
60
+ try:
61
+ response = await self._http.request(method, path, **kwargs)
62
+ except httpx.HTTPError as error:
63
+ raise UniFiAPIError(0, f"Request to {path} failed: {error}") from error
64
+ if response.is_error:
65
+ raise UniFiAPIError.from_response(response)
66
+ # Some action endpoints return an empty body.
67
+ return redact(response.json()) if response.content else {}
68
+
69
+ async def get_page(
70
+ self, path: str, *, offset: int = 0, limit: int = 25, filter: str | None = None
71
+ ) -> JSON:
72
+ return await self.get(
73
+ path, {"offset": offset, "limit": limit, "filter": filter}
74
+ )
75
+
76
+ async def get_all(self, path: str, *, filter: str | None = None) -> list[JSON]:
77
+ """Follow the pagination until all items of a list endpoint are read."""
78
+ items: list[JSON] = []
79
+ while True:
80
+ page = await self.get_page(
81
+ path, offset=len(items), limit=MAX_PAGE_SIZE, filter=filter
82
+ )
83
+ data = page.get("data", [])
84
+ items.extend(data)
85
+ if not data or len(items) >= page.get("totalCount", 0):
86
+ return items
87
+
88
+ async def gather_limited(
89
+ self, paths: list[str], concurrency: int = 8, return_errors: bool = False
90
+ ) -> list[Any]:
91
+ """Get many single resources, with a limit on the number of parallel requests.
92
+
93
+ If return_errors is true, the result has a UniFiAPIError in place of each failed request.
94
+ """
95
+ semaphore = asyncio.Semaphore(concurrency)
96
+
97
+ async def fetch(path: str) -> Any:
98
+ async with semaphore:
99
+ try:
100
+ return await self.get(path)
101
+ except UniFiAPIError as error:
102
+ if return_errors:
103
+ return error
104
+ raise
105
+
106
+ return await asyncio.gather(*(fetch(path) for path in paths))
107
+
108
+
109
+ def _without_none(values: dict[str, Any]) -> dict[str, Any]:
110
+ return {key: value for key, value in values.items() if value is not None}
111
+
112
+
113
+ def _write_body(body: JSON) -> JSON:
114
+ """Remove the None values. Refuse a body that would replace a secret with REDACTED."""
115
+ if contains_redacted(body):
116
+ raise ToolError(
117
+ f"The request body contains {REDACTED}. The server hides the secrets in its "
118
+ "results. Give the real value, or remove the field."
119
+ )
120
+ return _without_none(body)
@@ -0,0 +1,50 @@
1
+ from typing import Self
2
+
3
+ from pydantic import SecretStr, model_validator
4
+ from pydantic_settings import BaseSettings, SettingsConfigDict
5
+
6
+ CLOUD_CONNECTOR_URL = (
7
+ "https://api.ui.com/v1/connector/consoles/{console_id}/proxy/network/integration"
8
+ )
9
+ LOCAL_CONSOLE_URL = "https://{host}/proxy/network/integration"
10
+
11
+
12
+ class Settings(BaseSettings):
13
+ """Connection settings, read from the UNIFI_* environment variables."""
14
+
15
+ # The Claude Code plugin gives an empty string for each option that the user did not set.
16
+ model_config = SettingsConfigDict(
17
+ env_prefix="UNIFI_", extra="ignore", env_ignore_empty=True
18
+ )
19
+
20
+ api_key: SecretStr
21
+ # Set exactly one of these three. The host is the IP address or hostname of a local console.
22
+ host: str | None = None
23
+ console_id: str | None = None
24
+ base_url: str | None = None
25
+
26
+ # Local consoles usually use a self-signed certificate.
27
+ verify_tls: bool = True
28
+ timeout: float = 30.0
29
+ default_site_id: str | None = None
30
+ # The server adds the tools that change the network only if this value is true.
31
+ allow_writes: bool = False
32
+
33
+ @model_validator(mode="after")
34
+ def _check_target(self) -> Self:
35
+ targets = [
36
+ value for value in (self.host, self.console_id, self.base_url) if value
37
+ ]
38
+ if len(targets) != 1:
39
+ raise ValueError(
40
+ "Set exactly one of UNIFI_HOST, UNIFI_CONSOLE_ID, or UNIFI_BASE_URL."
41
+ )
42
+ return self
43
+
44
+ @property
45
+ def resolved_base_url(self) -> str:
46
+ if self.base_url:
47
+ return self.base_url.rstrip("/")
48
+ if self.console_id:
49
+ return CLOUD_CONNECTOR_URL.format(console_id=self.console_id)
50
+ return LOCAL_CONSOLE_URL.format(host=self.host)
@@ -0,0 +1,5 @@
1
+ """Pydantic models for the request bodies of the write tools."""
2
+
3
+ from ui_network_mcp.models.api_model import ApiModel, request_body
4
+
5
+ __all__ = ["ApiModel", "request_body"]
@@ -0,0 +1,27 @@
1
+ from typing import Any
2
+
3
+ from pydantic import BaseModel, ConfigDict
4
+ from pydantic.alias_generators import to_camel
5
+ from pydantic_core import to_jsonable_python
6
+
7
+ from ui_network_mcp.client import JSON
8
+
9
+
10
+ class ApiModel(BaseModel):
11
+ """A part of a request body. The JSON schema uses the camelCase names of the API."""
12
+
13
+ model_config = ConfigDict(
14
+ alias_generator=to_camel,
15
+ validate_by_alias=True,
16
+ validate_by_name=True,
17
+ extra="forbid",
18
+ )
19
+
20
+
21
+ def request_body(**fields: Any) -> JSON:
22
+ """Make a request body from snake_case fields. The body does not include None values."""
23
+ return to_jsonable_python(
24
+ {to_camel(name): value for name, value in fields.items() if value is not None},
25
+ by_alias=True,
26
+ exclude_none=True,
27
+ )
@@ -0,0 +1,21 @@
1
+ """The request bodies of the firewall policy endpoints."""
2
+
3
+ from ui_network_mcp.models.firewall.action import FirewallPolicyAction
4
+ from ui_network_mcp.models.firewall.policy import (
5
+ ConnectionState,
6
+ FirewallPolicyDestination,
7
+ FirewallPolicySource,
8
+ IpsecFilter,
9
+ )
10
+ from ui_network_mcp.models.firewall.protocol import IpProtocolScope
11
+ from ui_network_mcp.models.firewall.schedule import Schedule
12
+
13
+ __all__ = [
14
+ "ConnectionState",
15
+ "FirewallPolicyAction",
16
+ "FirewallPolicyDestination",
17
+ "FirewallPolicySource",
18
+ "IpProtocolScope",
19
+ "IpsecFilter",
20
+ "Schedule",
21
+ ]
@@ -0,0 +1,32 @@
1
+ from typing import Annotated, Literal
2
+
3
+ from pydantic import Field
4
+
5
+ from ui_network_mcp.models.api_model import ApiModel
6
+
7
+
8
+ class AllowAction(ApiModel):
9
+ """Allow the matched traffic."""
10
+
11
+ type: Literal["ALLOW"]
12
+ allow_return_traffic: bool = Field(
13
+ True,
14
+ description="Also allow the return traffic. The console adds a derived policy for the opposite zone pair.",
15
+ )
16
+
17
+
18
+ class BlockAction(ApiModel):
19
+ """Drop the matched traffic and send no reply."""
20
+
21
+ type: Literal["BLOCK"]
22
+
23
+
24
+ class RejectAction(ApiModel):
25
+ """Drop the matched traffic and send a reject reply."""
26
+
27
+ type: Literal["REJECT"]
28
+
29
+
30
+ FirewallPolicyAction = Annotated[
31
+ AllowAction | BlockAction | RejectAction, Field(discriminator="type")
32
+ ]
@@ -0,0 +1,137 @@
1
+ """The values that a traffic filter matches: ports, IP addresses, networks, and other objects."""
2
+
3
+ from typing import Annotated, Literal
4
+
5
+ from pydantic import Field, IPvAnyAddress, IPvAnyNetwork
6
+
7
+ from ui_network_mcp.models.api_model import ApiModel
8
+
9
+ Port = Annotated[int, Field(ge=1, le=65535)]
10
+ MatchOpposite = Annotated[
11
+ bool, Field(description="Match all values except the given values.")
12
+ ]
13
+ TrafficMatchingListId = Annotated[
14
+ str, Field(description="The ID of a traffic matching list.")
15
+ ]
16
+
17
+
18
+ class PortNumber(ApiModel):
19
+ type: Literal["PORT_NUMBER"]
20
+ value: Port
21
+
22
+
23
+ class PortRange(ApiModel):
24
+ type: Literal["PORT_NUMBER_RANGE"]
25
+ start: Port
26
+ stop: Port
27
+
28
+
29
+ class PortList(ApiModel):
30
+ """Match the given ports and port ranges."""
31
+
32
+ type: Literal["PORTS"]
33
+ items: list[Annotated[PortNumber | PortRange, Field(discriminator="type")]] = Field(
34
+ min_length=1
35
+ )
36
+ match_opposite: MatchOpposite = False
37
+
38
+
39
+ class PortTrafficMatchingList(ApiModel):
40
+ """Match the ports of a traffic matching list."""
41
+
42
+ type: Literal["TRAFFIC_MATCHING_LIST"]
43
+ traffic_matching_list_id: TrafficMatchingListId
44
+ match_opposite: MatchOpposite = False
45
+
46
+
47
+ PortFilter = Annotated[PortList | PortTrafficMatchingList, Field(discriminator="type")]
48
+
49
+
50
+ class IpAddress(ApiModel):
51
+ type: Literal["IP_ADDRESS"]
52
+ value: IPvAnyAddress
53
+
54
+
55
+ class IpAddressRange(ApiModel):
56
+ type: Literal["IP_ADDRESS_RANGE"]
57
+ start: IPvAnyAddress
58
+ stop: IPvAnyAddress
59
+
60
+
61
+ class Subnet(ApiModel):
62
+ type: Literal["SUBNET"]
63
+ value: IPvAnyNetwork = Field(description="The subnet in CIDR notation.")
64
+
65
+
66
+ class IpAddressList(ApiModel):
67
+ """Match the given IP addresses, IP address ranges, and subnets."""
68
+
69
+ type: Literal["IP_ADDRESSES"]
70
+ items: list[
71
+ Annotated[IpAddress | IpAddressRange | Subnet, Field(discriminator="type")]
72
+ ] = Field(min_length=1)
73
+ match_opposite: MatchOpposite = False
74
+
75
+
76
+ class IpAddressTrafficMatchingList(ApiModel):
77
+ """Match the IP addresses of a traffic matching list."""
78
+
79
+ type: Literal["TRAFFIC_MATCHING_LIST"]
80
+ traffic_matching_list_id: TrafficMatchingListId
81
+ match_opposite: MatchOpposite = False
82
+
83
+
84
+ IpAddressFilter = Annotated[
85
+ IpAddressList | IpAddressTrafficMatchingList, Field(discriminator="type")
86
+ ]
87
+
88
+
89
+ class NetworkFilter(ApiModel):
90
+ network_ids: list[str] = Field(min_length=1)
91
+ match_opposite: MatchOpposite = False
92
+
93
+
94
+ class VpnServerFilter(ApiModel):
95
+ vpn_server_ids: list[str] = Field(min_length=1)
96
+ match_opposite: MatchOpposite = False
97
+
98
+
99
+ class SiteToSiteVpnTunnelFilter(ApiModel):
100
+ site_to_site_vpn_tunnel_id: str
101
+
102
+
103
+ class RegionFilter(ApiModel):
104
+ regions: list[Annotated[str, Field(pattern=r"^[A-Z]{2}$")]] = Field(
105
+ min_length=1, description="ISO 3166-1 alpha-2 country codes, for example DE."
106
+ )
107
+
108
+
109
+ class Ipv6IidFilter(ApiModel):
110
+ ipv6_iid: str = Field(
111
+ min_length=1,
112
+ description="The IPv6 interface identifier, for example 2001:db8::1/::ffff:ffff:ffff:ffff.",
113
+ )
114
+ match_opposite: MatchOpposite = False
115
+
116
+
117
+ class MacAddressFilter(ApiModel):
118
+ mac_addresses: list[str] = Field(min_length=1)
119
+
120
+
121
+ class DomainFilter(ApiModel):
122
+ type: Literal["DOMAINS"] = "DOMAINS"
123
+ domains: list[str] = Field(min_length=1)
124
+
125
+
126
+ class ApplicationFilter(ApiModel):
127
+ application_ids: list[int] = Field(
128
+ min_length=1,
129
+ max_length=100,
130
+ description="DPI application IDs from list_dpi_applications.",
131
+ )
132
+
133
+
134
+ class ApplicationCategoryFilter(ApiModel):
135
+ application_category_ids: list[int] = Field(
136
+ min_length=1, description="DPI category IDs from list_dpi_categories."
137
+ )
@@ -0,0 +1,26 @@
1
+ from typing import Literal
2
+
3
+ from pydantic import Field
4
+
5
+ from ui_network_mcp.models.api_model import ApiModel
6
+ from ui_network_mcp.models.firewall.traffic_filters import (
7
+ DestinationTrafficFilter,
8
+ SourceTrafficFilter,
9
+ )
10
+
11
+ ConnectionState = Literal["NEW", "INVALID", "ESTABLISHED", "RELATED"]
12
+ IpsecFilter = Literal["MATCH_ENCRYPTED", "MATCH_NOT_ENCRYPTED"]
13
+
14
+
15
+ class FirewallPolicySource(ApiModel):
16
+ zone_id: str = Field(description="The firewall zone where the traffic comes from.")
17
+ traffic_filter: SourceTrafficFilter | None = Field(
18
+ None, description="Omit it to match all traffic from the zone."
19
+ )
20
+
21
+
22
+ class FirewallPolicyDestination(ApiModel):
23
+ zone_id: str = Field(description="The firewall zone where the traffic goes to.")
24
+ traffic_filter: DestinationTrafficFilter | None = Field(
25
+ None, description="Omit it to match all traffic to the zone."
26
+ )
@@ -0,0 +1,150 @@
1
+ """The IP version and the protocol that a firewall policy matches.
2
+
3
+ The API specification gives the protocol names in lowercase, but the console uses the uppercase
4
+ names of the discriminator mapping, for example TCP and ICMPV6.
5
+ """
6
+
7
+ from typing import Annotated, Literal
8
+
9
+ from pydantic import Field
10
+
11
+ from ui_network_mcp.models.api_model import ApiModel
12
+ from ui_network_mcp.models.firewall.matching import MatchOpposite
13
+
14
+ Ipv4ProtocolName = Literal[
15
+ "AH", "AX_25", "DCCP", "DDP", "EGP", "EIGRP", "ENCAP", "ESP", "ETHERIP", "FC",
16
+ "GGP", "GRE", "HIP", "HMP", "IDPR_CMTP", "IDRP", "IGMP", "IGP", "IP", "IPCOMP",
17
+ "IPENCAP", "IPIP", "ISIS", "ISO_TP4", "L2TP", "MANET", "MOBILITY_HEADER",
18
+ "MPLS_IN_IP", "OSPF", "PIM", "PUP", "RDP", "ROHC", "RSPF", "RSVP", "SCTP", "SHIM6",
19
+ "SKIP", "ST", "TCP", "UDP", "UDPLITE", "VMTP", "VRRP", "WESP", "XNS_IDP", "XTP",
20
+ ] # fmt: skip
21
+ Ipv6ProtocolName = Literal[
22
+ "AH", "DCCP", "EIGRP", "ESP", "GRE", "IPCOMP", "IPV6", "IPV6_FRAG", "IPV6_NONXT",
23
+ "IPV6_OPTS", "IPV6_ROUTE", "ISIS", "L2TP", "MANET", "MOBILITY_HEADER", "MPLS_IN_IP",
24
+ "OSPF", "PIM", "RSVP", "SCTP", "SHIM6", "TCP", "UDP", "VRRP",
25
+ ] # fmt: skip
26
+ Ipv4AndIpv6ProtocolName = Literal[
27
+ "AH", "DCCP", "EIGRP", "ESP", "GRE", "IPCOMP", "ISIS", "L2TP", "MANET",
28
+ "MOBILITY_HEADER", "MPLS_IN_IP", "OSPF", "PIM", "RSVP", "SCTP", "SHIM6", "TCP",
29
+ "UDP", "VRRP",
30
+ ] # fmt: skip
31
+ IcmpType = Literal[
32
+ "ADDRESS_MASK_REPLY", "ADDRESS_MASK_REQUEST", "COMMUNICATION_PROHIBITED",
33
+ "DESTINATION_UNREACHABLE", "ECHO_REPLY", "ECHO_REQUEST", "FRAGMENTATION_NEEDED",
34
+ "HOST_PRECEDENCE_VIOLATION", "HOST_PROHIBITED", "HOST_REDIRECT", "HOST_UNKNOWN",
35
+ "HOST_UNREACHABLE", "IP_HEADER_BAD", "NETWORK_PROHIBITED", "NETWORK_REDIRECT",
36
+ "NETWORK_UNKNOWN", "NETWORK_UNREACHABLE", "PARAMETER_PROBLEM", "PORT_UNREACHABLE",
37
+ "PRECEDENCE_CUTOFF", "PROTOCOL_UNREACHABLE", "REDIRECT", "REQUIRED_OPTION_MISSING",
38
+ "ROUTER_ADVERTISEMENT", "ROUTER_SOLICITATION", "SOURCE_QUENCH",
39
+ "SOURCE_ROUTE_FAILED", "TIME_EXCEEDED", "TIMESTAMP_REPLY", "TIMESTAMP_REQUEST",
40
+ "TOS_HOST_REDIRECT", "TOS_HOST_UNREACHABLE", "TOS_NETWORK_REDIRECT",
41
+ "TOS_NETWORK_UNREACHABLE", "TTL_ZERO_DURING_REASSEMBLY", "TTL_ZERO_DURING_TRANSIT",
42
+ ] # fmt: skip
43
+ Icmpv6Type = Literal[
44
+ "ADDRESS_UNREACHABLE", "BAD_HEADER", "BEYOND_SCOPE", "COMMUNICATION_PROHIBITED",
45
+ "DESTINATION_UNREACHABLE", "ECHO_REPLY", "ECHO_REQUEST", "FAILED_POLICY",
46
+ "NEIGHBOR_ADVERTISEMENT", "NEIGHBOR_SOLICITATION", "NO_ROUTE", "PACKET_TOO_BIG",
47
+ "PARAMETER_PROBLEM", "PORT_UNREACHABLE", "REDIRECT", "REJECT_ROUTE",
48
+ "ROUTER_ADVERTISEMENT", "ROUTER_SOLICITATION", "TIME_EXCEEDED",
49
+ "TTL_ZERO_DURING_REASSEMBLY", "TTL_ZERO_DURING_TRANSIT", "UNKNOWN_HEADER_TYPE",
50
+ "UNKNOWN_OPTION",
51
+ ] # fmt: skip
52
+
53
+ TYPENAME_HELP = "Match only this message type. Omit it to match all types."
54
+
55
+
56
+ class Ipv4Protocol(ApiModel):
57
+ name: Ipv4ProtocolName
58
+
59
+
60
+ class Icmp(ApiModel):
61
+ name: Literal["ICMP"]
62
+ typename_filter: IcmpType | None = Field(None, description=TYPENAME_HELP)
63
+
64
+
65
+ class Ipv6Protocol(ApiModel):
66
+ name: Ipv6ProtocolName
67
+
68
+
69
+ class Icmpv6(ApiModel):
70
+ name: Literal["ICMPV6"]
71
+ typename_filter: Icmpv6Type | None = Field(None, description=TYPENAME_HELP)
72
+
73
+
74
+ class Ipv4AndIpv6Protocol(ApiModel):
75
+ name: Ipv4AndIpv6ProtocolName
76
+
77
+
78
+ class Ipv4NamedProtocolFilter(ApiModel):
79
+ type: Literal["NAMED_PROTOCOL"]
80
+ protocol: Annotated[Ipv4Protocol | Icmp, Field(discriminator="name")]
81
+ match_opposite: MatchOpposite = False
82
+
83
+
84
+ class Ipv6NamedProtocolFilter(ApiModel):
85
+ type: Literal["NAMED_PROTOCOL"]
86
+ protocol: Annotated[Ipv6Protocol | Icmpv6, Field(discriminator="name")]
87
+ match_opposite: MatchOpposite = False
88
+
89
+
90
+ class Ipv4AndIpv6NamedProtocolFilter(ApiModel):
91
+ type: Literal["NAMED_PROTOCOL"]
92
+ protocol: Ipv4AndIpv6Protocol
93
+ match_opposite: MatchOpposite = False
94
+
95
+
96
+ class ProtocolPreset(ApiModel):
97
+ name: Literal["TCP_UDP"] = "TCP_UDP"
98
+
99
+
100
+ class ProtocolPresetFilter(ApiModel):
101
+ """Match TCP and UDP."""
102
+
103
+ type: Literal["PRESET"]
104
+ preset: ProtocolPreset = ProtocolPreset()
105
+
106
+
107
+ class ProtocolNumberFilter(ApiModel):
108
+ type: Literal["PROTOCOL_NUMBER"]
109
+ protocol_number: int = Field(ge=0, le=255, description="The IANA protocol number.")
110
+ match_opposite: MatchOpposite = False
111
+
112
+
113
+ class Ipv4Scope(ApiModel):
114
+ ip_version: Literal["IPV4"]
115
+ protocol_filter: (
116
+ Annotated[
117
+ Ipv4NamedProtocolFilter | ProtocolPresetFilter | ProtocolNumberFilter,
118
+ Field(discriminator="type"),
119
+ ]
120
+ | None
121
+ ) = None
122
+
123
+
124
+ class Ipv6Scope(ApiModel):
125
+ ip_version: Literal["IPV6"]
126
+ protocol_filter: (
127
+ Annotated[
128
+ Ipv6NamedProtocolFilter | ProtocolPresetFilter | ProtocolNumberFilter,
129
+ Field(discriminator="type"),
130
+ ]
131
+ | None
132
+ ) = None
133
+
134
+
135
+ class Ipv4AndIpv6Scope(ApiModel):
136
+ ip_version: Literal["IPV4_AND_IPV6"]
137
+ protocol_filter: (
138
+ Annotated[
139
+ Ipv4AndIpv6NamedProtocolFilter
140
+ | ProtocolPresetFilter
141
+ | ProtocolNumberFilter,
142
+ Field(discriminator="type"),
143
+ ]
144
+ | None
145
+ ) = None
146
+
147
+
148
+ IpProtocolScope = Annotated[
149
+ Ipv4Scope | Ipv6Scope | Ipv4AndIpv6Scope, Field(discriminator="ip_version")
150
+ ]