Source code for aiopnsense.firewall

"""Firewall, NAT, alias, and state methods for OPNsenseClient."""

from collections.abc import Callable, MutableMapping
import csv
from io import StringIO
from typing import Any

from ._error_policy import _log_boolean_errors, _log_errors
from ._styled_endpoint import _StyledEndpoint
from ._typing import AiopnsenseClientProtocol
from .client_toggle import TOGGLE_ITEM_RESULTS, ToggleSpec, ToggleStep
from .const import SOURCE_NAT_AUTOMATIC_ROW_FILTER_CAPABILITY, UNIFIED_NAT_TEMPLATE_CAPABILITY
from .helpers import _LOGGER, api_value_matches, coerce_bool

FIREWALL_FILTER_RULES_DOWNLOAD_ENDPOINT = "/api/firewall/filter/download_rules"
FIREWALL_DNAT_RULES_SEARCH_ENDPOINT = "/api/firewall/d_nat/search_rule"
FIREWALL_ONE_TO_ONE_RULES_SEARCH_ENDPOINT = "/api/firewall/one_to_one/search_rule"
FIREWALL_SOURCE_NAT_RULES_SEARCH_ENDPOINT = "/api/firewall/source_nat/search_rule"
FIREWALL_NPT_RULES_SEARCH_ENDPOINT = "/api/firewall/npt/search_rule"
FIREWALL_FILTER_TOGGLE_RULE_ENDPOINT_PREFIX = "/api/firewall/filter/toggle_rule/"
FIREWALL_FILTER_APPLY_ENDPOINT = "/api/firewall/filter/apply"
FIREWALL_NAT_TOGGLE_RULE_ENDPOINT_PREFIX = "/api/firewall/"
FIREWALL_NAT_APPLY_ENDPOINT_SUFFIX = "/apply"
FIREWALL_KILL_STATES_ENDPOINT = "/api/diagnostics/firewall/kill_states/"
FIREWALL_ALIAS_SEARCH_ENDPOINT = _StyledEndpoint(
    snake_case="/api/firewall/alias/search_item",
    camel_case="/api/firewall/alias/searchItem",
)
FIREWALL_ALIAS_TOGGLE_ENDPOINT_PREFIX = _StyledEndpoint(
    snake_case="/api/firewall/alias/toggle_item/",
    camel_case="/api/firewall/alias/toggleItem/",
)
FIREWALL_ALIAS_SET_ENDPOINT = "/api/firewall/alias/set"
FIREWALL_ALIAS_RECONFIGURE_ENDPOINT = "/api/firewall/alias/reconfigure"


class FirewallMixin(AiopnsenseClientProtocol):
    """Firewall methods for OPNsenseClient."""

    @staticmethod
    def _index_rule_rows(
        rows: list,
        normalizer: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
        include_rule: Callable[[dict[str, Any]], bool] | None = None,
    ) -> dict[str, Any]:
        """Return UUID-keyed rule rows after filtering malformed and lockout rows.

        Args:
            rows (list): Raw rule rows returned by an OPNsense search endpoint.
            normalizer (Callable[[dict[str, Any]], dict[str, Any]] | None, optional):
                Optional row normalizer applied after common filtering.
            include_rule (Callable[[dict[str, Any]], bool] | None, optional):
                Optional row predicate applied after normalization.

        Returns:
            dict[str, Any]: Rule mapping keyed by UUID.
        """
        rules_dict: dict[str, Any] = {}
        for rule in rows:
            if not isinstance(rule, MutableMapping):
                continue
            uuid = rule.get("uuid")
            if not uuid or "lockout" in str(uuid):
                continue
            new_rule = dict(rule)
            if normalizer is not None:
                new_rule = normalizer(new_rule)
            if include_rule is not None and not include_rule(new_rule):
                continue
            rules_dict[str(new_rule["uuid"])] = new_rule
        return rules_dict

    @staticmethod
    def _normalize_nat_destination_rule(
        rule: dict[str, Any], *, normalize_categories: bool = False
    ) -> dict[str, Any]:
        """Normalize destination NAT rule field names and enabled state.

        Args:
            rule (dict[str, Any]): Destination NAT rule row returned by OPNsense.
            normalize_categories (bool): Whether to mirror DNAT's singular
                category keys to plural category keys for newer unified NAT UI
                template firmware.

        Returns:
            dict[str, Any]: Normalized destination NAT rule row.
        """
        rule["description"] = rule.pop("descr", "")
        if "enabled" not in rule:
            rule["enabled"] = "1" if api_value_matches(rule.pop("disabled", "0"), "0") else "0"
        rule.pop("disabled", None)
        if normalize_categories:
            if "category" in rule and "categories" not in rule:
                rule["categories"] = rule["category"]
            if "%category" in rule and "%categories" not in rule:
                rule["%categories"] = rule["%category"]
        return rule

    @staticmethod
    def _normalize_source_nat_rule(rule: dict[str, Any]) -> dict[str, Any]:
        """Normalize source NAT rule display fields.

        Args:
            rule (dict[str, Any]): Source NAT rule row returned by OPNsense.

        Returns:
            dict[str, Any]: Normalized source NAT rule row.
        """
        if rule.get("target") == "" and not rule.get("%target"):
            interface_label = rule.get("%interface") or rule.get("interface")
            rule["%target"] = (
                f"{interface_label} address" if interface_label else "Interface address"
            )
        return rule

    async def _get_uuid_indexed_rules(
        self,
        endpoint: str,
        debug_label: str,
        normalizer: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
        include_rule: Callable[[dict[str, Any]], bool] | None = None,
    ) -> dict[str, Any]:
        """Fetch rule rows from one endpoint and return them keyed by UUID.

        Args:
            endpoint (str): Search endpoint to query.
            debug_label (str): Label used in endpoint-unavailable and result-size logs.
            normalizer (Callable[[dict[str, Any]], dict[str, Any]] | None, optional):
                Optional row normalizer applied after common filtering.
            include_rule (Callable[[dict[str, Any]], bool] | None, optional):
                Optional row predicate applied after normalization.

        Returns:
            dict[str, Any]: Rule mapping keyed by UUID.
        """
        outcome = await self._fetch_endpoint_outcome(endpoint)
        if not outcome.is_data:
            _LOGGER.debug("%s endpoint not available", debug_label)
            return {}

        rules: list = outcome.mapping().get("rows", [])
        rules_dict = self._index_rule_rows(rules, normalizer=normalizer, include_rule=include_rule)
        _LOGGER.debug("[%s] rules_dict length: %s", debug_label, len(rules_dict))
        return rules_dict

    @_log_errors
    async def get_firewall(self) -> dict[str, Any]:
        """Return firewall filter rules and all supported NAT rule groups.

        Returns:
            dict[str, Any]: Mapping with top-level ``rules`` for firewall
                filter rules, excluding lockout and automatically generated
                firewall rules, and ``nat`` groups for destination NAT,
                one-to-one NAT, source NAT, and NPT rules. Rule groups are
                keyed by rule UUID.
        """
        firewall: dict[str, Any] = {"nat": {}}
        firewall["rules"] = await self._get_firewall_rules()
        firewall["nat"]["d_nat"] = await self._get_nat_destination_rules()
        firewall["nat"]["one_to_one"] = await self._get_nat_one_to_one_rules()
        firewall["nat"]["source_nat"] = await self._get_nat_source_rules()
        firewall["nat"]["npt"] = await self._get_nat_npt_rules()
        return firewall

    @_log_errors
    async def _get_firewall_rules(self) -> dict[str, Any]:
        """Retrieve firewall rules from OPNsense.

        Returns:
            dict[str, Any]: Firewall filter rules keyed by UUID, excluding
                malformed rows, lockout rules, and automatically generated
                rules (the download endpoint exports only MVC model rules
                and structurally excludes plugin-generated entries).
        """
        outcome = await self._fetch_endpoint_outcome(
            FIREWALL_FILTER_RULES_DOWNLOAD_ENDPOINT, response_format="text"
        )
        if not outcome.is_data:
            _LOGGER.debug("get_firewall_rules endpoint not available")
            return {}

        response = outcome.text()
        if not response:
            return {}

        csv_response = response.lstrip("\ufeff")
        header = csv_response.partition("\n")[0]
        # OPNsense 26.1 and 26.1.1 export comma-separated CSV. OPNsense 26.1.2
        # switched the shared CSV exporter to semicolons, which remains the
        # format used by newer releases.
        delimiter = ";" if ";" in header else ","

        rows: list[dict[str, Any]] = []
        for csv_row in csv.DictReader(StringIO(csv_response), delimiter=delimiter):
            if None in csv_row:
                _LOGGER.debug("Skipping malformed firewall rule row with extra column")
                continue
            uuid = csv_row.pop("@uuid", None)
            if not uuid:
                continue
            row = {key: value for key, value in csv_row.items() if key is not None}
            row["uuid"] = uuid
            rows.append(row)

        rules = self._index_rule_rows(rows)
        _LOGGER.debug("[get_firewall_rules] rules_dict length: %s", len(rules))
        return rules

    @_log_errors
    async def _get_nat_destination_rules(self) -> dict[str, Any]:
        """Retrieve NAT destination rules from OPNsense.

        Returns:
            dict[str, Any]: Destination NAT rules keyed by UUID, with
                ``descr`` normalized to ``description``, ``disabled`` normalized
                to ``enabled``, and on unified-NAT firmware category keys mirrored
                from ``category``/``%category`` into ``categories``/``%categories``.
        """
        normalize_categories = await self._firmware_capability_enabled(
            UNIFIED_NAT_TEMPLATE_CAPABILITY
        )
        return await self._get_uuid_indexed_rules(
            endpoint=FIREWALL_DNAT_RULES_SEARCH_ENDPOINT,
            debug_label="get_nat_destination_rules",
            normalizer=lambda rule: self._normalize_nat_destination_rule(
                rule, normalize_categories=normalize_categories
            ),
        )

    @_log_errors
    async def _get_nat_one_to_one_rules(self) -> dict[str, Any]:
        """Retrieve NAT one-to-one rules from OPNsense.

        Returns:
            dict[str, Any]: Mapping of NAT one-to-one rules keyed by rule
                identifiers, with each value containing the corresponding
                rule details (for example, source, destination, external IP,
                and description fields when present).
        """
        return await self._get_uuid_indexed_rules(
            endpoint=FIREWALL_ONE_TO_ONE_RULES_SEARCH_ENDPOINT,
            debug_label="get_nat_one_to_one_rules",
        )

    @_log_errors
    async def _get_nat_source_rules(self) -> dict[str, Any]:
        """Retrieve NAT source rules from OPNsense.

        Returns:
            dict[str, Any]: Source NAT rules keyed by UUID, excluding
                malformed rows and lockout rules. For OPNsense 26.1.11 and
                newer, generated automatic source NAT rows are also excluded.
        """
        outcome = await self._fetch_endpoint_outcome(FIREWALL_SOURCE_NAT_RULES_SEARCH_ENDPOINT)
        if not outcome.is_data:
            _LOGGER.debug("%s endpoint not available", "get_nat_source_rules")
            return {}

        rules: list = outcome.mapping().get("rows", [])
        has_automatic_rows = any(
            isinstance(rule, MutableMapping) and coerce_bool(rule.get("is_automatic"))
            for rule in rules
        )
        filter_automatic_rules = has_automatic_rows and await self._firmware_capability_enabled(
            SOURCE_NAT_AUTOMATIC_ROW_FILTER_CAPABILITY
        )
        rules_dict = self._index_rule_rows(
            rules,
            normalizer=self._normalize_source_nat_rule,
            include_rule=(
                (lambda rule: not coerce_bool(rule.get("is_automatic")))
                if filter_automatic_rules
                else None
            ),
        )
        _LOGGER.debug(
            "[%s] rules_dict length: %s",
            "get_nat_source_rules",
            len(rules_dict),
        )
        return rules_dict

    @_log_errors
    async def _get_nat_npt_rules(self) -> dict[str, Any]:
        """Retrieve NAT NPT rules from OPNsense.

        Returns:
            dict[str, Any]: NPT NAT rules keyed by UUID, excluding malformed
                rows and lockout rules.
        """
        return await self._get_uuid_indexed_rules(
            endpoint=FIREWALL_NPT_RULES_SEARCH_ENDPOINT,
            debug_label="get_nat_npt_rules",
        )

    @_log_boolean_errors
    async def toggle_firewall_rule(self, uuid: str, toggle_on_off: str | None = None) -> bool:
        """Toggle a Firewall Rule on or off and apply the filter.

        Args:
            uuid (str): UUID of the firewall filter rule to toggle.
            toggle_on_off (str | None, optional): Target state. Use ``on`` to
                enable, ``off`` to disable, or ``None`` or ``toggle`` to flip
                the current state.

        Returns:
            bool: True when the Router acknowledged the save and confirmed
                the apply. False when the save was not acknowledged (no apply is
                sent), the apply was not confirmed, or an error was suppressed.
                With ``throw_errors`` enabled, an invalid ``toggle_on_off`` raises
                ``OPNsenseInvalidArgument`` and transport errors raise
                ``OPNsenseError``.
        """
        target = self._parse_toggle_target(toggle_on_off)
        url = f"{FIREWALL_FILTER_TOGGLE_RULE_ENDPOINT_PREFIX}{uuid}{target.endpoint_suffix()}"
        _LOGGER.debug("[toggle_firewall_rule] uuid: %s, target: %s, url: %s", uuid, target, url)
        return await self._run_toggle(
            ToggleSpec(
                label="toggle_firewall_rule",
                target=target,
                save=(ToggleStep.save(url, TOGGLE_ITEM_RESULTS, payload={}),),
                apply=(ToggleStep.apply(FIREWALL_FILTER_APPLY_ENDPOINT),),
            )
        )

    @_log_boolean_errors
    async def toggle_nat_rule(
        self, nat_rule_type: str, uuid: str, toggle_on_off: str | None = None
    ) -> bool:
        """Toggle a NAT rule on or off and apply the NAT changes.

        Args:
            nat_rule_type (str): NAT rule category path segment, such as
                ``d_nat``, ``source_nat``, ``one_to_one``, or ``npt``.
            uuid (str): UUID of the NAT rule to toggle.
            toggle_on_off (str | None, optional): Target state. Use ``on`` to
                enable, ``off`` to disable, or ``None`` or ``toggle`` to flip
                the current state.

        Returns:
            bool: True when the Router acknowledged the save and confirmed
                the apply. False when the save was not acknowledged (no apply is
                sent), the apply was not confirmed, or an error was suppressed.
                With ``throw_errors`` enabled, an invalid ``toggle_on_off`` raises
                ``OPNsenseInvalidArgument`` and transport errors raise
                ``OPNsenseError``.
        """
        target = self._parse_toggle_target(toggle_on_off)
        # d_nat stores a *disabled* flag, so on/off map to the opposite URL suffix.
        suffix = target.endpoint_suffix(inverted=nat_rule_type == "d_nat")
        url = (
            f"{FIREWALL_NAT_TOGGLE_RULE_ENDPOINT_PREFIX}{nat_rule_type}/toggle_rule/{uuid}{suffix}"
        )
        _LOGGER.debug("[toggle_nat_rule] uuid: %s, target: %s, url: %s", uuid, target, url)
        return await self._run_toggle(
            ToggleSpec(
                label="toggle_nat_rule",
                target=target,
                save=(ToggleStep.save(url, TOGGLE_ITEM_RESULTS, payload={}),),
                apply=(
                    ToggleStep.apply(
                        f"{FIREWALL_NAT_TOGGLE_RULE_ENDPOINT_PREFIX}{nat_rule_type}"
                        f"{FIREWALL_NAT_APPLY_ENDPOINT_SUFFIX}"
                    ),
                ),
            )
        )

    async def kill_states(self, ip_addr: str) -> MutableMapping[str, Any]:
        """Kill the active states of the IP address.

        Args:
            ip_addr (str): IP address whose states should be terminated.

        Returns:
            MutableMapping[str, Any]: Mapping with ``success`` and
                ``dropped_states`` from the firewall state-kill response.
        """
        payload: dict[str, Any] = {"filter": ip_addr}
        response = await self._safe_dict_post(
            FIREWALL_KILL_STATES_ENDPOINT,
            payload=payload,
        )
        _LOGGER.debug("[kill_states] ip_addr: %s, response: %s", ip_addr, response)
        return {
            "success": bool(response.get("result", "") == "ok"),
            "dropped_states": response.get("dropped_states", 0),
        }

    @_log_boolean_errors
    async def toggle_alias(self, alias: str, toggle_on_off: str | None = None) -> bool:
        """Toggle an alias on or off, commit it and reconfigure the aliases.

        Args:
            alias (str): Alias name to toggle in firewall configuration.
            toggle_on_off (str | None, optional): Target state. Use ``on`` to
                enable, ``off`` to disable, or ``None`` or ``toggle`` to flip
                the current state.

        Returns:
            bool: True when the Router acknowledged the toggle and the
                commit and confirmed the reconfigure. False when the alias cannot
                be found, a save step was not acknowledged (nothing further is
                sent), the reconfigure was not confirmed, or an error was suppressed.
                With ``throw_errors`` enabled, an invalid ``toggle_on_off`` raises
                ``OPNsenseInvalidArgument`` and transport errors raise
                ``OPNsenseError``.
        """
        target = self._parse_toggle_target(toggle_on_off)
        alias_search_outcome = await self._fetch_endpoint_outcome(FIREWALL_ALIAS_SEARCH_ENDPOINT)
        if not alias_search_outcome.is_data:
            _LOGGER.debug("Firewall alias search endpoint unavailable")
            return False

        alias_list_resp = alias_search_outcome.mapping()
        alias_list: list = alias_list_resp.get("rows", [])
        if not isinstance(alias_list, list):
            return False
        uuid: str | None = None
        for item in alias_list:
            if not isinstance(item, MutableMapping):
                continue
            if item.get("name") == alias:
                uuid = item.get("uuid")
                break
        if not uuid:
            return False
        url: str = await self._resolve_endpoint(
            FIREWALL_ALIAS_TOGGLE_ENDPOINT_PREFIX.with_suffix(uuid)
        )
        url = f"{url}{target.endpoint_suffix()}"
        _LOGGER.debug(
            "[toggle_alias] alias: %s, uuid: %s, target: %s, url: %s", alias, uuid, target, url
        )
        return await self._run_toggle(
            ToggleSpec(
                label="toggle_alias",
                target=target,
                save=(
                    ToggleStep.save(url, TOGGLE_ITEM_RESULTS, payload={}),
                    ToggleStep.save(FIREWALL_ALIAS_SET_ENDPOINT, frozenset({"saved"})),
                ),
                apply=(ToggleStep.apply(FIREWALL_ALIAS_RECONFIGURE_ENDPOINT),),
            )
        )