From f18eda47923cbecb9616b73fb11f0c0c32180dbe Mon Sep 17 00:00:00 2001 From: James Gomez Date: Wed, 2 Dec 2026 12:39:00 -0800 Subject: [PATCH] fix(security): pin GitHub Actions to SHAs, fix docs-pages permissions, and resolve CodeQL findings --- .github/workflows/ci.yml | 26 +-- .github/workflows/codeql.yml | 8 +- .github/workflows/docs-pages.yml | 11 +- .github/workflows/release.yml | 18 +- src/nxtflow/_backend_base.py | 362 +++++++++++++++++++++++++++++ src/nxtflow/backends.py | 381 +++---------------------------- src/nxtflow/clickhouse.py | 2 +- src/nxtflow/enricher/app.py | 6 +- src/nxtflow/loki.py | 4 +- src/nxtflow/mcp_server.py | 2 +- src/nxtflow/victorialogs.py | 2 +- tests/test_enricher.py | 30 +-- 12 files changed, 449 insertions(+), 403 deletions(-) create mode 100644 src/nxtflow/_backend_base.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a3710ad..3914e71 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ jobs: timeout-minutes: 15 steps: - name: Checkout Repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false @@ -40,12 +40,12 @@ jobs: timeout-minutes: 15 steps: - name: Checkout Repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false - name: Setup Python 3.12 - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 with: python-version: "3.12" @@ -66,13 +66,13 @@ jobs: timeout-minutes: 15 steps: - name: Checkout Repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 0 persist-credentials: false - name: Setup Python 3.12 - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 with: python-version: "3.12" @@ -82,7 +82,7 @@ jobs: pip install -e ".[mcp,dev]" jsonschema - name: Setup Helm v4 - uses: azure/setup-helm@v5 + uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5 with: version: "v4.3.1" @@ -107,7 +107,7 @@ jobs: run: pytest -v tests/test_helm.py - name: Setup Helm chart-testing (ct) - uses: helm/chart-testing-action@v2 + uses: helm/chart-testing-action@6ec842c01de15ebb84c8627d2744a0c2f2755c9f # v2 - name: Run Helm chart-testing (ct lint) run: ct lint --config ct.yaml --all @@ -122,15 +122,15 @@ jobs: - helm-lint-and-template steps: - name: Checkout Repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false - name: Setup Docker Buildx - uses: docker/setup-buildx-action@v4 + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4 - name: Build Enricher Container Image - uses: docker/build-push-action@v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7 with: context: . file: docker/Dockerfile.enricher @@ -139,7 +139,7 @@ jobs: tags: ghcr.io/nertwork/nxtflow-enricher:ci-test - name: Build MCP Container Image - uses: docker/build-push-action@v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7 with: context: . file: docker/Dockerfile.mcp @@ -148,7 +148,7 @@ jobs: tags: ghcr.io/nertwork/nxtflow-mcp:ci-test - name: Setup Helm v4 - uses: azure/setup-helm@v5 + uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5 with: version: "v4.3.1" @@ -160,7 +160,7 @@ jobs: helm dependency build charts/nxtflow - name: Create Kind Cluster - uses: helm/kind-action@v1 + uses: helm/kind-action@ef37e7f390d99f746eb8b610417061a60e82a6cc # v1 - name: Load Images & Smoke-Test Helm Install in Kind run: | diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index b88fabc..21a9a53 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -33,20 +33,20 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false - name: Initialize CodeQL - uses: github/codeql-action/init@v4 + uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4 with: languages: ${{ matrix.language }} queries: security-and-quality - name: Autobuild - uses: github/codeql-action/autobuild@v4 + uses: github/codeql-action/autobuild@915412ff23e8b7659517e607487dbeae018f2934 # v4 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4 + uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4 with: category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/docs-pages.yml b/.github/workflows/docs-pages.yml index 70e8904..a80844f 100644 --- a/.github/workflows/docs-pages.yml +++ b/.github/workflows/docs-pages.yml @@ -29,6 +29,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 permissions: + actions: read contents: read pages: write id-token: write @@ -37,12 +38,12 @@ jobs: url: ${{ steps.deployment.outputs.page_url }} steps: - name: Checkout Repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false - name: Setup Python 3.12 - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 with: python-version: "3.12" @@ -53,13 +54,13 @@ jobs: run: python3 .github/scripts/sync_gh_pages.py _site - name: Configure GitHub Pages - uses: actions/configure-pages@v6 + uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6 - name: Upload Pages Artifact - uses: actions/upload-pages-artifact@v5 + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5 with: path: _site - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@v5 + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c51a789..c877ca9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,7 +19,7 @@ jobs: packages: write steps: - name: Checkout Tag - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 0 persist-credentials: false @@ -39,18 +39,18 @@ jobs: echo "Releasing nxtflow v${VER}" - name: Setup QEMU & Docker Buildx - uses: docker/setup-qemu-action@v4 - - uses: docker/setup-buildx-action@v4 + uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4 + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4 - name: Log in to GHCR - uses: docker/login-action@v4 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Build & Push Multi-Arch Enricher Image - uses: docker/build-push-action@v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7 with: context: . file: docker/Dockerfile.enricher @@ -61,7 +61,7 @@ jobs: ghcr.io/nertwork/nxtflow-enricher:latest - name: Build & Push Multi-Arch MCP Image - uses: docker/build-push-action@v7 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7 with: context: . file: docker/Dockerfile.mcp @@ -72,7 +72,7 @@ jobs: ghcr.io/nertwork/nxtflow-mcp:latest - name: Setup Helm v4 - uses: azure/setup-helm@v5 + uses: azure/setup-helm@2f5e7bc67f1f9972ab16657bb795f36d8f04de0e # v5 with: version: "v4.3.1" @@ -92,7 +92,7 @@ jobs: helm push "dist/nxtflow-${VER}.tgz" oci://ghcr.io/nertwork/charts - name: Setup Python 3.12 - uses: actions/setup-python@v7 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 with: python-version: "3.12" @@ -105,7 +105,7 @@ jobs: cat SHA256SUMS.txt - name: Publish GitHub Release - uses: softprops/action-gh-release@v3 + uses: softprops/action-gh-release@88b783939ccdbabad21b9a37510aed7fad5f2e60 # v3 with: files: | dist/* diff --git a/src/nxtflow/_backend_base.py b/src/nxtflow/_backend_base.py new file mode 100644 index 0000000..f748634 --- /dev/null +++ b/src/nxtflow/_backend_base.py @@ -0,0 +1,362 @@ +"""Shared telemetry backend protocol, base exception, and aggregation helpers for nxtflow.""" + +from __future__ import annotations + +import math +import ssl +from collections import Counter +from collections.abc import Sequence +from typing import Any, Protocol + +from nxtflow.config import parse_range_seconds + + +class BackendError(RuntimeError): + """Base exception raised when a telemetry backend returns an error or cannot be reached.""" + + +class TelemetryBackend(Protocol): + """Common query interface implemented by Loki, VictoriaLogs, and ClickHouse clients.""" + + def check_readiness(self) -> list[str]: + pass + + def get_status_data(self, range_str: str = "5m") -> dict[str, Any]: + pass + + def get_summary_data( + self, + range_str: str = "5m", + dir_val: str | None = None, + site_val: str | None = None, + ) -> dict[str, Any]: + pass + + def get_top_data( + self, + field: str, + n: int = 10, + range_str: str = "5m", + dir_val: str | None = None, + site_val: str | None = None, + exclude_hosts: Sequence[str] | None = None, + ) -> list[dict[str, Any]]: + pass + + def get_top_connections_data( + self, + n: int = 15, + range_str: str = "5m", + dir_val: str | None = None, + site_val: str | None = None, + exclude_hosts: Sequence[str] | None = None, + ) -> list[dict[str, Any]]: + pass + + def get_top_ports_data( + self, + n: int = 10, + range_str: str = "5m", + dir_val: str | None = None, + site_val: str | None = None, + exclude_hosts: Sequence[str] | None = None, + ) -> list[dict[str, Any]]: + pass + + def get_host_data( + self, + name: str, + range_str: str = "5m", + site_val: str | None = None, + ) -> dict[str, Any] | None: + pass + + def get_sessions_data( + self, + name: str, + range_str: str = "5m", + site_val: str | None = None, + limit: int = 30, + ) -> list[dict[str, Any]]: + pass + + def get_search_data( + self, + term: str = "", + range_str: str = "5m", + n: int = 20, + site_val: str | None = None, + dir_val: str | None = None, + peer_term: str | None = None, + exclude_hosts: Sequence[str] | None = None, + ) -> tuple[int, list[dict[str, Any]]]: + pass + + def get_directory_data( + self, + range_str: str = "5m", + site_val: str | None = None, + limit: int = 500, + ) -> dict[str, str]: + pass + + +def safe_int(val: Any, default: int = 0) -> int: + """Safely convert numeric/string flow field values into an int.""" + if isinstance(val, bool) or val is None: + return default + try: + num = float(val) + except (TypeError, ValueError, OverflowError): + return default + if not math.isfinite(num): + return default + return int(num) + + +def build_ssl_context( + tls_verify: bool | str, + error_cls: type[BackendError] = BackendError, +) -> ssl.SSLContext: + """Create SSLContext from bool/CA-path setting, raising error_cls on invalid paths.""" + try: + if tls_verify is False: + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + return ctx + if isinstance(tls_verify, str): + return ssl.create_default_context(cafile=tls_verify) + return ssl.create_default_context() + except (OSError, ssl.SSLError) as exc: + raise error_cls(f"Invalid TLS configuration ({tls_verify!r}): {exc}") from exc + + +def percentile_95(values: list[float]) -> float: + """Return 95th percentile of a list of float values (0.0 when empty).""" + if not values: + return 0.0 + s = sorted(values) + idx = min(len(s) - 1, int(0.95 * (len(s) - 1) + 0.5)) + return s[idx] + + +def rate_window_and_step(range_str: str) -> tuple[str, str]: + """Select smoothing rate window and step interval based on query range.""" + secs = parse_range_seconds(range_str) + if secs <= 900: + return "1m", "15s" + if secs <= 3600: + return "2m", "30s" + if secs <= 21600: + return "2m", "60s" + if secs <= 86400: + return "5m", "5m" + if secs <= 604800: + return "15m", "15m" + return "1h", "1h" + + +def extract_metric_results(data: dict[str, Any]) -> list[dict[str, Any]]: + """Parse Prometheus-compatible instant vector response into sorted label/value dicts.""" + data_block = data.get("data") if isinstance(data, dict) else None + results = data_block.get("result") if isinstance(data_block, dict) else None + if not isinstance(results, list): + return [] + out = [] + for item in results: + if not isinstance(item, dict): + continue + raw_labels = item.get("metric") + labels = raw_labels if isinstance(raw_labels, dict) else {} + raw_val = item.get("value") + if isinstance(raw_val, (list, tuple)) and len(raw_val) > 1: + try: + value = float(raw_val[1]) + if not math.isfinite(value): + value = 0.0 + except (TypeError, ValueError, OverflowError): + value = 0.0 + else: + value = 0.0 + out.append({"labels": labels, "value": value}) + out.sort(key=lambda x: x["value"], reverse=True) + return out + + +def extract_matrix_series( + data: dict[str, Any], + multiplier: float = 1.0, + total_series: dict[Any, float] | None = None, +) -> list[float]: + """Parse Prometheus-compatible matrix response values into a flat rate list.""" + rate_vals: list[float] = [] + data_block = data.get("data") if isinstance(data, dict) else None + results = data_block.get("result") if isinstance(data_block, dict) else None + if not isinstance(results, list): + return rate_vals + for series in results: + if not isinstance(series, dict): + continue + series_values = series.get("values") + if not isinstance(series_values, list): + continue + for entry in series_values: + if not isinstance(entry, (list, tuple)) or len(entry) < 2: + continue + ts, val = entry[0], entry[1] + try: + v = float(val) * multiplier + except (TypeError, ValueError, OverflowError): + continue + if not math.isfinite(v): + continue + rate_vals.append(v) + if total_series is not None: + total_series[ts] = total_series.get(ts, 0.0) + v + return rate_vals + + +def aggregate_host_flows(name: str, lines: list[dict[str, Any]]) -> dict[str, Any] | None: + """Aggregate flow dicts into the host profile breakdown.""" + if not lines: + return None + dirs: Counter[str] = Counter() + sites: Counter[str] = Counter() + total_bytes = 0 + peers: Counter[str] = Counter() + ports: Counter[Any] = Counter() + ips: Counter[str] = Counter() + needle = name.strip().lower() + for line in lines: + dirs[str(line.get("dir") or "?")] += 1 + sites[str(line.get("site") or "?")] += 1 + b = safe_int(line.get("bytes"), 0) + total_bytes += b + src = str(line.get("src_host") or "") + dst = str(line.get("dst_host") or "") + src_addr = str(line.get("src_addr") or "") + dst_addr = str(line.get("dst_addr") or "") + src_match = needle in src.lower() or needle in src_addr.lower() + dst_match = needle in dst.lower() or needle in dst_addr.lower() + if src_match: + peer = dst + if src_addr: + ips[src_addr] += b + else: + peer = src + if dst_match and dst_addr and (not src_match or dst_addr != src_addr): + ips[dst_addr] += b + if peer: + peers[peer] += b + raw_port = line.get("dst_port") + if raw_port is None or raw_port == "": + port_key: int | str = "?" + elif isinstance(raw_port, (int, str)) and not isinstance(raw_port, bool): + port_key = raw_port + elif isinstance(raw_port, float) and math.isfinite(raw_port): + port_key = int(raw_port) if raw_port.is_integer() else str(raw_port) + else: + port_key = str(raw_port) + ports[port_key] += b + return { + "host": name, + "flows": len(lines), + "bytes": total_bytes, + "direction": dict(dirs), + "sites": dict(sites), + "top_peers": [{"name": k, "bytes": v} for k, v in peers.most_common(10)], + "top_ports": [{"port": k, "bytes": v} for k, v in ports.most_common(10)], + "ips": [{"ip": k, "bytes": v} for k, v in ips.most_common(20)], + } + + +def aggregate_sessions(lines: list[dict[str, Any]], limit: int = 30) -> list[dict[str, Any]]: + """Aggregate flow dicts into sorted 5-tuple session summaries.""" + if not lines: + return [] + sessions: Counter[tuple[str, str, str, str, str, str, str, str]] = Counter() + session_bytes: Counter[tuple[str, str, str, str, str, str, str, str]] = Counter() + for line in lines: + raw_port = line.get("dst_port") + key = ( + str(line.get("site") or "?"), + str(line.get("src_host") or ""), + str(line.get("dst_host") or ""), + "" if raw_port is None else str(raw_port), + str(line.get("proto") or ""), + str(line.get("src_addr") or ""), + str(line.get("dst_addr") or ""), + str(line.get("nat_dst") or ""), + ) + sessions[key] += 1 + session_bytes[key] += safe_int(line.get("bytes"), 0) + sorted_sessions = sorted(session_bytes.items(), key=lambda x: x[1], reverse=True) + out: list[dict[str, Any]] = [] + for k, b in sorted_sessions[:limit]: + row: dict[str, Any] = { + "site": k[0], + "src": k[1], + "dst": k[2], + "src_addr": k[5], + "dst_addr": k[6], + "port": k[3], + "proto": k[4], + "flows": sessions[k], + "bytes": b, + } + if k[7]: + row["nat_dst"] = k[7] + out.append(row) + return out + + +def merge_excluded_hosts( + config_excluded: Sequence[str] | None, + extra_excluded: Sequence[str] | None = None, +) -> list[str]: + """Merge configured and caller-supplied excluded hosts, deduplicated in order.""" + merged: list[str] = [] + seen: set[str] = set() + for source in (config_excluded or (), extra_excluded or ()): + for item in source: + if item is None: + continue + cleaned = str(item).replace("\r", "").replace("\n", "").replace("\x00", "").strip() + if not cleaned or cleaned in seen: + continue + seen.add(cleaned) + merged.append(cleaned) + return merged + + +def filter_excluded_flows( + lines: list[dict[str, Any]], + excluded: Sequence[str] | None, +) -> list[dict[str, Any]]: + """Filter out flow dicts whose src_host or dst_host matches any excluded host.""" + if not excluded: + return lines + excluded_set = {str(h).strip().lower() for h in excluded if h is not None and str(h).strip()} + if not excluded_set: + return lines + out: list[dict[str, Any]] = [] + for line in lines: + src = str(line.get("src_host") or "").strip().lower() + dst = str(line.get("dst_host") or "").strip().lower() + if src in excluded_set or dst in excluded_set: + continue + out.append(line) + return out + + +def build_directory_map(lines: list[dict[str, Any]]) -> dict[str, str]: + """Build sorted IP -> hostname mapping from flow dicts.""" + mapping: dict[str, str] = {} + for line in lines: + for addr_key, host_key in (("src_addr", "src_host"), ("dst_addr", "dst_host")): + addr = str(line.get(addr_key) or "").strip() + host = str(line.get(host_key) or "").strip() + if addr and host and addr != host: + mapping[addr] = host + return dict(sorted(mapping.items(), key=lambda item: (item[1], item[0]))) diff --git a/src/nxtflow/backends.py b/src/nxtflow/backends.py index 7086574..c1ba20a 100644 --- a/src/nxtflow/backends.py +++ b/src/nxtflow/backends.py @@ -2,354 +2,39 @@ from __future__ import annotations -import math -import ssl -from collections import Counter -from collections.abc import Sequence -from typing import Any, Protocol - -from nxtflow.config import NxtflowConfig, load_config, parse_range_seconds, validate_backend - - -class BackendError(RuntimeError): - """Base exception raised when a telemetry backend returns an error or cannot be reached.""" - - -class TelemetryBackend(Protocol): - """Common query interface implemented by Loki, VictoriaLogs, and ClickHouse clients.""" - - def check_readiness(self) -> list[str]: ... - - def get_status_data(self, range_str: str = "5m") -> dict[str, Any]: ... - - def get_summary_data( - self, - range_str: str = "5m", - dir_val: str | None = None, - site_val: str | None = None, - ) -> dict[str, Any]: ... - - def get_top_data( - self, - field: str, - n: int = 10, - range_str: str = "5m", - dir_val: str | None = None, - site_val: str | None = None, - exclude_hosts: Sequence[str] | None = None, - ) -> list[dict[str, Any]]: ... - - def get_top_connections_data( - self, - n: int = 15, - range_str: str = "5m", - dir_val: str | None = None, - site_val: str | None = None, - exclude_hosts: Sequence[str] | None = None, - ) -> list[dict[str, Any]]: ... - - def get_top_ports_data( - self, - n: int = 10, - range_str: str = "5m", - dir_val: str | None = None, - site_val: str | None = None, - exclude_hosts: Sequence[str] | None = None, - ) -> list[dict[str, Any]]: ... - - def get_host_data( - self, - name: str, - range_str: str = "5m", - site_val: str | None = None, - ) -> dict[str, Any] | None: ... - - def get_sessions_data( - self, - name: str, - range_str: str = "5m", - site_val: str | None = None, - limit: int = 30, - ) -> list[dict[str, Any]]: ... - - def get_search_data( - self, - term: str = "", - range_str: str = "5m", - n: int = 20, - site_val: str | None = None, - dir_val: str | None = None, - peer_term: str | None = None, - exclude_hosts: Sequence[str] | None = None, - ) -> tuple[int, list[dict[str, Any]]]: ... - - def get_directory_data( - self, - range_str: str = "5m", - site_val: str | None = None, - limit: int = 500, - ) -> dict[str, str]: ... - - -def safe_int(val: Any, default: int = 0) -> int: - """Safely convert numeric/string flow field values into an int.""" - if isinstance(val, bool) or val is None: - return default - try: - num = float(val) - except (TypeError, ValueError, OverflowError): - return default - if not math.isfinite(num): - return default - return int(num) - - -def build_ssl_context( - tls_verify: bool | str, - error_cls: type[BackendError] = BackendError, -) -> ssl.SSLContext: - """Create SSLContext from bool/CA-path setting, raising error_cls on invalid paths.""" - try: - if tls_verify is False: - ctx = ssl.create_default_context() - ctx.check_hostname = False - ctx.verify_mode = ssl.CERT_NONE - return ctx - if isinstance(tls_verify, str): - return ssl.create_default_context(cafile=tls_verify) - return ssl.create_default_context() - except (OSError, ssl.SSLError) as exc: - raise error_cls(f"Invalid TLS configuration ({tls_verify!r}): {exc}") from exc - - -def percentile_95(values: list[float]) -> float: - """Return 95th percentile of a list of float values (0.0 when empty).""" - if not values: - return 0.0 - s = sorted(values) - idx = min(len(s) - 1, int(0.95 * (len(s) - 1) + 0.5)) - return s[idx] - - -def rate_window_and_step(range_str: str) -> tuple[str, str]: - """Select smoothing rate window and step interval based on query range.""" - secs = parse_range_seconds(range_str) - if secs <= 900: - return "1m", "15s" - if secs <= 3600: - return "2m", "30s" - if secs <= 21600: - return "2m", "60s" - if secs <= 86400: - return "5m", "5m" - if secs <= 604800: - return "15m", "15m" - return "1h", "1h" - - -def extract_metric_results(data: dict[str, Any]) -> list[dict[str, Any]]: - """Parse Prometheus-compatible instant vector response into sorted label/value dicts.""" - data_block = data.get("data") if isinstance(data, dict) else None - results = data_block.get("result") if isinstance(data_block, dict) else None - if not isinstance(results, list): - return [] - out = [] - for item in results: - if not isinstance(item, dict): - continue - raw_labels = item.get("metric") - labels = raw_labels if isinstance(raw_labels, dict) else {} - raw_val = item.get("value") - if isinstance(raw_val, (list, tuple)) and len(raw_val) > 1: - try: - value = float(raw_val[1]) - if not math.isfinite(value): - value = 0.0 - except (TypeError, ValueError, OverflowError): - value = 0.0 - else: - value = 0.0 - out.append({"labels": labels, "value": value}) - out.sort(key=lambda x: x["value"], reverse=True) - return out - - -def extract_matrix_series( - data: dict[str, Any], - multiplier: float = 1.0, - total_series: dict[Any, float] | None = None, -) -> list[float]: - """Parse Prometheus-compatible matrix response values into a flat rate list.""" - rate_vals: list[float] = [] - data_block = data.get("data") if isinstance(data, dict) else None - results = data_block.get("result") if isinstance(data_block, dict) else None - if not isinstance(results, list): - return rate_vals - for series in results: - if not isinstance(series, dict): - continue - series_values = series.get("values") - if not isinstance(series_values, list): - continue - for entry in series_values: - if not isinstance(entry, (list, tuple)) or len(entry) < 2: - continue - ts, val = entry[0], entry[1] - try: - v = float(val) * multiplier - except (TypeError, ValueError, OverflowError): - continue - if not math.isfinite(v): - continue - rate_vals.append(v) - if total_series is not None: - total_series[ts] = total_series.get(ts, 0.0) + v - return rate_vals - - -def aggregate_host_flows(name: str, lines: list[dict[str, Any]]) -> dict[str, Any] | None: - """Aggregate flow dicts into the host profile breakdown.""" - if not lines: - return None - dirs: Counter[str] = Counter() - sites: Counter[str] = Counter() - total_bytes = 0 - peers: Counter[str] = Counter() - ports: Counter[Any] = Counter() - ips: Counter[str] = Counter() - needle = name.strip().lower() - for line in lines: - dirs[str(line.get("dir") or "?")] += 1 - sites[str(line.get("site") or "?")] += 1 - b = safe_int(line.get("bytes"), 0) - total_bytes += b - src = str(line.get("src_host") or "") - dst = str(line.get("dst_host") or "") - src_addr = str(line.get("src_addr") or "") - dst_addr = str(line.get("dst_addr") or "") - src_match = needle in src.lower() or needle in src_addr.lower() - dst_match = needle in dst.lower() or needle in dst_addr.lower() - if src_match: - peer = dst - if src_addr: - ips[src_addr] += b - else: - peer = src - if dst_match and dst_addr and (not src_match or dst_addr != src_addr): - ips[dst_addr] += b - if peer: - peers[peer] += b - raw_port = line.get("dst_port") - if raw_port is None or raw_port == "": - port_key: int | str = "?" - elif isinstance(raw_port, (int, str)) and not isinstance(raw_port, bool): - port_key = raw_port - elif isinstance(raw_port, float) and math.isfinite(raw_port): - port_key = int(raw_port) if raw_port.is_integer() else str(raw_port) - else: - port_key = str(raw_port) - ports[port_key] += b - return { - "host": name, - "flows": len(lines), - "bytes": total_bytes, - "direction": dict(dirs), - "sites": dict(sites), - "top_peers": [{"name": k, "bytes": v} for k, v in peers.most_common(10)], - "top_ports": [{"port": k, "bytes": v} for k, v in ports.most_common(10)], - "ips": [{"ip": k, "bytes": v} for k, v in ips.most_common(20)], - } - - -def aggregate_sessions(lines: list[dict[str, Any]], limit: int = 30) -> list[dict[str, Any]]: - """Aggregate flow dicts into sorted 5-tuple session summaries.""" - if not lines: - return [] - sessions: Counter[tuple[str, str, str, str, str, str, str, str]] = Counter() - session_bytes: Counter[tuple[str, str, str, str, str, str, str, str]] = Counter() - for line in lines: - raw_port = line.get("dst_port") - key = ( - str(line.get("site") or "?"), - str(line.get("src_host") or ""), - str(line.get("dst_host") or ""), - "" if raw_port is None else str(raw_port), - str(line.get("proto") or ""), - str(line.get("src_addr") or ""), - str(line.get("dst_addr") or ""), - str(line.get("nat_dst") or ""), - ) - sessions[key] += 1 - session_bytes[key] += safe_int(line.get("bytes"), 0) - sorted_sessions = sorted(session_bytes.items(), key=lambda x: x[1], reverse=True) - out: list[dict[str, Any]] = [] - for k, b in sorted_sessions[:limit]: - row: dict[str, Any] = { - "site": k[0], - "src": k[1], - "dst": k[2], - "src_addr": k[5], - "dst_addr": k[6], - "port": k[3], - "proto": k[4], - "flows": sessions[k], - "bytes": b, - } - if k[7]: - row["nat_dst"] = k[7] - out.append(row) - return out - - -def merge_excluded_hosts( - config_excluded: Sequence[str] | None, - extra_excluded: Sequence[str] | None = None, -) -> list[str]: - """Merge configured and caller-supplied excluded hosts, deduplicated in order.""" - merged: list[str] = [] - seen: set[str] = set() - for source in (config_excluded or (), extra_excluded or ()): - for item in source: - if item is None: - continue - cleaned = str(item).replace("\r", "").replace("\n", "").replace("\x00", "").strip() - if not cleaned or cleaned in seen: - continue - seen.add(cleaned) - merged.append(cleaned) - return merged - - -def filter_excluded_flows( - lines: list[dict[str, Any]], - excluded: Sequence[str] | None, -) -> list[dict[str, Any]]: - """Filter out flow dicts whose src_host or dst_host matches any excluded host.""" - if not excluded: - return lines - excluded_set = {str(h).strip().lower() for h in excluded if h is not None and str(h).strip()} - if not excluded_set: - return lines - out: list[dict[str, Any]] = [] - for line in lines: - src = str(line.get("src_host") or "").strip().lower() - dst = str(line.get("dst_host") or "").strip().lower() - if src in excluded_set or dst in excluded_set: - continue - out.append(line) - return out - - -def build_directory_map(lines: list[dict[str, Any]]) -> dict[str, str]: - """Build sorted IP -> hostname mapping from flow dicts.""" - mapping: dict[str, str] = {} - for line in lines: - for addr_key, host_key in (("src_addr", "src_host"), ("dst_addr", "dst_host")): - addr = str(line.get(addr_key) or "").strip() - host = str(line.get(host_key) or "").strip() - if addr and host and addr != host: - mapping[addr] = host - return dict(sorted(mapping.items(), key=lambda item: (item[1], item[0]))) +from nxtflow._backend_base import ( + BackendError, + TelemetryBackend, + aggregate_host_flows, + aggregate_sessions, + build_directory_map, + build_ssl_context, + extract_matrix_series, + extract_metric_results, + filter_excluded_flows, + merge_excluded_hosts, + percentile_95, + rate_window_and_step, + safe_int, +) +from nxtflow.config import NxtflowConfig, load_config, validate_backend + +__all__ = [ + "BackendError", + "TelemetryBackend", + "aggregate_host_flows", + "aggregate_sessions", + "build_directory_map", + "build_ssl_context", + "create_backend_client", + "extract_matrix_series", + "extract_metric_results", + "filter_excluded_flows", + "merge_excluded_hosts", + "percentile_95", + "rate_window_and_step", + "safe_int", +] def create_backend_client(cfg: NxtflowConfig | None = None) -> TelemetryBackend: diff --git a/src/nxtflow/clickhouse.py b/src/nxtflow/clickhouse.py index 779d751..acbd43f 100644 --- a/src/nxtflow/clickhouse.py +++ b/src/nxtflow/clickhouse.py @@ -11,7 +11,7 @@ from collections.abc import Sequence from typing import Any -from nxtflow.backends import ( +from nxtflow._backend_base import ( BackendError, aggregate_host_flows, build_directory_map, diff --git a/src/nxtflow/enricher/app.py b/src/nxtflow/enricher/app.py index 6f5470e..153fc0c 100644 --- a/src/nxtflow/enricher/app.py +++ b/src/nxtflow/enricher/app.py @@ -250,7 +250,7 @@ def parse_goflow2_batch( except (json.JSONDecodeError, ValueError) as exc: if "\n" not in text and not isinstance(exc, json.JSONDecodeError): raise - parsed = None + # Fall through to NDJSON decoder below for multi-line streams. else: if isinstance(parsed, dict): return [parsed], 0 @@ -2162,14 +2162,12 @@ def _run_file_tailer(self) -> None: except (ValueError, TypeError, OverflowError) as exc: self.metrics.dropped_flows.inc() LOGGER.warning("Dropped batch during file tailer ingest: %s", exc) - try: + with contextlib.suppress(OSError): pos_path.parent.mkdir(parents=True, exist_ok=True) pos_path.write_text( json.dumps({"inode": inode, "offset": offset}), encoding="utf-8", ) - except OSError: - pass if ( self.cfg.file_truncate_bytes > 0 diff --git a/src/nxtflow/loki.py b/src/nxtflow/loki.py index 3900b31..d818712 100644 --- a/src/nxtflow/loki.py +++ b/src/nxtflow/loki.py @@ -14,7 +14,7 @@ from collections.abc import Sequence from typing import Any -from nxtflow.backends import ( +from nxtflow._backend_base import ( BackendError, aggregate_host_flows, aggregate_sessions, @@ -26,7 +26,6 @@ merge_excluded_hosts, percentile_95, rate_window_and_step, - safe_int, ) from nxtflow.config import ( NxtflowConfig, @@ -47,7 +46,6 @@ class LokiError(BackendError): """Raised when Loki returns an error or cannot be reached.""" -_safe_int = safe_int _percentile_95 = percentile_95 _rate_window_and_step = rate_window_and_step _extract_metric_results = extract_metric_results diff --git a/src/nxtflow/mcp_server.py b/src/nxtflow/mcp_server.py index 0b86a30..6d449f5 100644 --- a/src/nxtflow/mcp_server.py +++ b/src/nxtflow/mcp_server.py @@ -14,7 +14,7 @@ from nxtflow import __version__ from nxtflow.backends import BackendError, TelemetryBackend, create_backend_client from nxtflow.config import NxtflowConfig, clamp_limit, load_config, validate_dir, validate_range -from nxtflow.loki import LokiClient, LokiError # noqa: F401 - exported for compatibility +from nxtflow.loki import LokiClient def create_server( diff --git a/src/nxtflow/victorialogs.py b/src/nxtflow/victorialogs.py index bec78dc..0fedb78 100644 --- a/src/nxtflow/victorialogs.py +++ b/src/nxtflow/victorialogs.py @@ -12,7 +12,7 @@ from collections.abc import Sequence from typing import Any -from nxtflow.backends import ( +from nxtflow._backend_base import ( BackendError, aggregate_host_flows, aggregate_sessions, diff --git a/tests/test_enricher.py b/tests/test_enricher.py index 17a8758..a435145 100644 --- a/tests/test_enricher.py +++ b/tests/test_enricher.py @@ -27,6 +27,9 @@ normalize_proto, parse_goflow2_batch, ) +from nxtflow.enricher.app import ( + main as enricher_main, +) from nxtflow.enricher.default_cidrs import ( PUBLIC_CIDRS, PUBLIC_DOMAIN_SERVICES, @@ -60,7 +63,7 @@ def test_default_cidrs_strictly_public() -> None: addr = ipaddress.ip_address(ip_str) assert addr.is_global, f"non-global well-known IP: {ip_str}" - assert "apple.com" in PUBLIC_DOMAIN_SERVICES + assert PUBLIC_DOMAIN_SERVICES.get("apple.com") == "apple" def test_simplify_rdns_longest_suffix_and_fallback() -> None: @@ -1590,10 +1593,9 @@ def test_tier5_enricher_yaml_sections_and_main_lifecycle( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: + import signal from unittest.mock import patch - import nxtflow.enricher.app as enr_app - full_yaml = tmp_path / "full-enricher.yaml" full_yaml.write_text( f""" @@ -1683,26 +1685,26 @@ def test_tier5_enricher_yaml_sections_and_main_lifecycle( assert cfg.shipper_file_truncate_bytes == 4096 # Missing explicit config -> exit 2 cleanly - assert enr_app.main(["--config", str(tmp_path / "missing.yaml")]) == 2 + assert enricher_main(["--config", str(tmp_path / "missing.yaml")]) == 2 assert "Error loading enricher configuration" in capsys.readouterr().err with ( - patch.object(enr_app.EnricherPipeline, "start"), - patch.object(enr_app.EnricherPipeline, "stop"), - patch.object(enr_app.signal, "signal"), + patch.object(EnricherPipeline, "start"), + patch.object(EnricherPipeline, "stop"), + patch.object(signal, "signal"), ): real_event = threading.Event() real_event.set() - with patch.object(enr_app.threading, "Event", return_value=real_event): - assert enr_app.main(["--config", str(full_yaml), "--stdin", "--input-file", "-"]) == 0 - assert enr_app.main(["--config", str(full_yaml), "--input-file", str(tmp_path / "goflow.jsonl")]) == 0 + with patch.object(threading, "Event", return_value=real_event): + assert enricher_main(["--config", str(full_yaml), "--stdin", "--input-file", "-"]) == 0 + assert enricher_main(["--config", str(full_yaml), "--input-file", str(tmp_path / "goflow.jsonl")]) == 0 with ( - patch.object(enr_app.EnricherPipeline, "start", side_effect=OSError("port in use")), - patch.object(enr_app.EnricherPipeline, "stop"), - patch.object(enr_app.signal, "signal"), + patch.object(EnricherPipeline, "start", side_effect=OSError("port in use")), + patch.object(EnricherPipeline, "stop"), + patch.object(signal, "signal"), ): - assert enr_app.main(["--config", str(full_yaml)]) == 2 + assert enricher_main(["--config", str(full_yaml)]) == 2 assert "Error starting enricher pipeline" in capsys.readouterr().err