diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b6b98d0..a3710ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,13 +9,20 @@ on: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: lint-and-security-audit: name: Lint, Syntax & Security Audit runs-on: ubuntu-latest + timeout-minutes: 15 steps: - name: Checkout Repository uses: actions/checkout@v7 + with: + persist-credentials: false - name: Run Security, Secret & Syntax Audit run: python3 scripts/security_audit.py @@ -30,9 +37,12 @@ jobs: python-lint-and-tests: name: Python Lint & Unit Tests runs-on: ubuntu-latest + timeout-minutes: 15 steps: - name: Checkout Repository uses: actions/checkout@v7 + with: + persist-credentials: false - name: Setup Python 3.12 uses: actions/setup-python@v7 @@ -53,11 +63,13 @@ jobs: helm-lint-and-template: name: Helm Lint, Schema & Template runs-on: ubuntu-latest + timeout-minutes: 15 steps: - name: Checkout Repository uses: actions/checkout@v7 with: fetch-depth: 0 + persist-credentials: false - name: Setup Python 3.12 uses: actions/setup-python@v7 @@ -103,6 +115,7 @@ jobs: docker-and-kind: name: Docker Build & Kind Helm Install runs-on: ubuntu-latest + timeout-minutes: 25 needs: - lint-and-security-audit - python-lint-and-tests @@ -110,6 +123,8 @@ jobs: steps: - name: Checkout Repository uses: actions/checkout@v7 + with: + persist-credentials: false - name: Setup Docker Buildx uses: docker/setup-buildx-action@v4 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..b88fabc --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,52 @@ +name: CodeQL + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: "17 6 * * 1" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [python, actions] + + steps: + - name: Checkout Repository + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + queries: security-and-quality + + - name: Autobuild + uses: github/codeql-action/autobuild@v4 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 + with: + category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/docs-pages.yml b/.github/workflows/docs-pages.yml index 0982718..70e8904 100644 --- a/.github/workflows/docs-pages.yml +++ b/.github/workflows/docs-pages.yml @@ -18,8 +18,6 @@ on: permissions: contents: read - pages: write - id-token: write concurrency: group: "pages" @@ -29,12 +27,19 @@ jobs: build-and-deploy: name: Build & Deploy GitHub Pages runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pages: write + id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - name: Checkout Repository uses: actions/checkout@v7 + with: + persist-credentials: false - name: Setup Python 3.12 uses: actions/setup-python@v7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 546cd43..c51a789 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,18 +7,22 @@ on: workflow_dispatch: permissions: - contents: write - packages: write + contents: read jobs: release: name: Build Containers, Helm OCI & GitHub Release runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: write + packages: write steps: - name: Checkout Tag uses: actions/checkout@v7 with: fetch-depth: 0 + persist-credentials: false - name: Run Security & Syntax Audit run: python3 scripts/security_audit.py @@ -31,7 +35,7 @@ jobs: else VER=$(python3 -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])') fi - echo "version=${VER}" >> "$GITHUB_OUTPUT" + printf 'version=%s\n' "${VER}" >> "$GITHUB_OUTPUT" echo "Releasing nxtflow v${VER}" - name: Setup QEMU & Docker Buildx @@ -73,22 +77,27 @@ jobs: version: "v4.3.1" - name: Package & Push Helm Chart to GHCR OCI + env: + VER: ${{ steps.vars.outputs.version }} + GHCR_USER: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - VER="${{ steps.vars.outputs.version }}" helm repo add grafana-community https://grafana-community.github.io/helm-charts helm repo add prometheus-community https://prometheus-community.github.io/helm-charts helm repo update helm dependency build charts/nxtflow mkdir -p dist helm package charts/nxtflow --version "${VER}" --app-version "${VER}" -d dist/ - echo "${{ secrets.GITHUB_TOKEN }}" | helm registry login ghcr.io -u "${{ github.actor }}" --password-stdin + printf '%s\n' "${GHCR_TOKEN}" | helm registry login ghcr.io -u "${GHCR_USER}" --password-stdin helm push "dist/nxtflow-${VER}.tgz" oci://ghcr.io/nertwork/charts - - name: Build Python sdist & wheel + - name: Setup Python 3.12 uses: actions/setup-python@v7 with: python-version: "3.12" - - run: | + + - name: Build Python sdist & wheel + run: | python -m pip install --upgrade pip build python -m build --outdir dist/ cd dist diff --git a/CHANGELOG.md b/CHANGELOG.md index 950a4d7..38f444e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,21 @@ All notable changes to `nxtflow` are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.2.4] - 2026-12-02 + +### Added +- **Version Display Across CLI, MCP, and Web UI**: + - Added `-V` / `--version` flag to the `nxtflow` CLI (`nxtflow 0.2.4`). + - Included `"version"` in `nxtflow-mcp` `/healthz` and `nxtflow-ui` `/healthz` & `/api/status` JSON responses. + - Added a live header version badge (`v0.2.4`) next to the `nxtflow` brand title in `nxtflow-ui`, populated via `textContent` from `/healthz` and `/api/status`. +- **GitHub CodeQL Code Scanning**: + - Added `.github/workflows/codeql.yml` (`python`, `actions`, `security-and-quality` queries) and hardened existing GitHub Actions workflows with minimal scoped permissions and `env:`-bound variables. + +### Security +- **URL Scheme & TLS Hardening**: + - Added `validate_http_url()` in `nxtflow.config` and enforced `http://`/`https://` scheme validation prior to all `urllib.request.urlopen()` calls across `loki`, `victorialogs`, `clickhouse`, and `nxtflow-enricher` (`NetBoxSync` and `FlowShipper`). + - Replaced private `ssl._create_unverified_context()` calls with `ssl.create_default_context()` configuration and resolved Ruff `E,F,W,B,S,UP,SIM` code-quality and security checks across `src/nxtflow/`. + ## [0.2.3] - 2026-12-02 ### Changed diff --git a/charts/nxtflow/Chart.yaml b/charts/nxtflow/Chart.yaml index 275f15b..4424acb 100644 --- a/charts/nxtflow/Chart.yaml +++ b/charts/nxtflow/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: nxtflow description: AI-ready multi-site NetFlow v5/v9, IPFIX, and sFlow collector, enricher, multi-backend storage (Loki, VictoriaLogs, ClickHouse), Grafana dashboard, and MCP server type: application -version: 0.2.3 -appVersion: "0.2.3" +version: 0.2.4 +appVersion: "0.2.4" home: https://github.com/nertwork/nxtflow sources: - https://github.com/nertwork/nxtflow diff --git a/charts/nxtflow/README.md b/charts/nxtflow/README.md index a3e8805..e760685 100644 --- a/charts/nxtflow/README.md +++ b/charts/nxtflow/README.md @@ -36,7 +36,7 @@ Multi-protocol **NetFlow v5/v9, IPFIX, and sFlow v5** Kubernetes observability p ```bash helm install nxtflow oci://ghcr.io/nertwork/charts/nxtflow \ - --version 0.2.3 \ + --version 0.2.4 \ --namespace nxtflow --create-namespace \ -f https://raw.githubusercontent.com/nertwork/nxtflow/main/examples/values-standalone.yaml ``` @@ -45,7 +45,7 @@ helm install nxtflow oci://ghcr.io/nertwork/charts/nxtflow \ ```bash helm install nxtflow oci://ghcr.io/nertwork/charts/nxtflow \ - --version 0.2.3 \ + --version 0.2.4 \ --namespace nxtflow --create-namespace \ -f https://raw.githubusercontent.com/nertwork/nxtflow/main/examples/values-loki.yaml ``` @@ -54,7 +54,7 @@ helm install nxtflow oci://ghcr.io/nertwork/charts/nxtflow \ ```bash helm install nxtflow oci://ghcr.io/nertwork/charts/nxtflow \ - --version 0.2.3 \ + --version 0.2.4 \ --namespace nxtflow --create-namespace \ -f https://raw.githubusercontent.com/nertwork/nxtflow/main/examples/values-clickhouse.yaml ``` @@ -63,7 +63,7 @@ helm install nxtflow oci://ghcr.io/nertwork/charts/nxtflow \ ```bash helm install nxtflow oci://ghcr.io/nertwork/charts/nxtflow \ - --version 0.2.3 \ + --version 0.2.4 \ --namespace monitoring \ -f https://raw.githubusercontent.com/nertwork/nxtflow/main/examples/values-integrated.yaml \ --set externalLoki.url="https://loki.example.com" @@ -73,7 +73,7 @@ helm install nxtflow oci://ghcr.io/nertwork/charts/nxtflow \ ```bash helm install nxtflow-edge oci://ghcr.io/nertwork/charts/nxtflow \ - --version 0.2.3 \ + --version 0.2.4 \ --namespace nxtflow --create-namespace \ -f https://raw.githubusercontent.com/nertwork/nxtflow/main/examples/values-collector-only.yaml \ --set collector.site="edge-west" \ @@ -119,6 +119,6 @@ See [`values.yaml`](values.yaml) and [`values.schema.json`](values.schema.json) ## Upgrade & Uninstall ```bash -helm upgrade nxtflow oci://ghcr.io/nertwork/charts/nxtflow --version 0.2.3 -n nxtflow -f values.yaml +helm upgrade nxtflow oci://ghcr.io/nertwork/charts/nxtflow --version 0.2.4 -n nxtflow -f values.yaml helm uninstall nxtflow -n nxtflow ``` diff --git a/pyproject.toml b/pyproject.toml index 9ae63bc..7eb3f39 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "nxtflow" -version = "0.2.3" +version = "0.2.4" description = "AI-ready multi-site NetFlow v5/v9, IPFIX, and sFlow collector, enricher, Loki pipeline, CLI, and MCP server" requires-python = ">=3.11" license = {text = "MIT"} diff --git a/src/nxtflow/__init__.py b/src/nxtflow/__init__.py index 67fccda..8fc7ec2 100644 --- a/src/nxtflow/__init__.py +++ b/src/nxtflow/__init__.py @@ -1,3 +1,3 @@ """nxtflow — AI-ready multi-site NetFlow/IPFIX/sFlow telemetry toolkit.""" -__version__ = "0.2.3" +__version__ = "0.2.4" diff --git a/src/nxtflow/backends.py b/src/nxtflow/backends.py index 8a0fed4..7086574 100644 --- a/src/nxtflow/backends.py +++ b/src/nxtflow/backends.py @@ -111,7 +111,10 @@ def build_ssl_context( """Create SSLContext from bool/CA-path setting, raising error_cls on invalid paths.""" try: if tls_verify is False: - return ssl._create_unverified_context() + 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() diff --git a/src/nxtflow/cli.py b/src/nxtflow/cli.py index 45075d5..68bfead 100644 --- a/src/nxtflow/cli.py +++ b/src/nxtflow/cli.py @@ -9,6 +9,7 @@ import yaml +from nxtflow import __version__ from nxtflow.backends import BackendError, create_backend_client, safe_int from nxtflow.config import load_config, validate_dir, validate_range @@ -61,6 +62,7 @@ def build_parser() -> argparse.ArgumentParser: description="Query multi-site NetFlow/IPFIX/sFlow telemetry.", parents=[top_common], ) + parser.add_argument("-V", "--version", action="version", version=f"nxtflow {__version__}") sub = parser.add_subparsers(dest="command", metavar="COMMAND") sub.add_parser("status", aliases=["health"], parents=[sub_common], help="Collector stream & ingestion health") @@ -199,7 +201,12 @@ def _render_top_ports(items: list[dict], n: int, range_str: str, site_val: str | def _render_host(name: str, data: dict | None, range_str: str, as_json: bool) -> None: if not data: - print(json.dumps({"host": name, "flows": 0}) if as_json else f"No traffic found for '{name}' in last {range_str}") + msg = ( + json.dumps({"host": name, "flows": 0}) + if as_json + else f"No traffic found for '{name}' in last {range_str}" + ) + print(msg) return if as_json: print(json.dumps(data, indent=2)) diff --git a/src/nxtflow/clickhouse.py b/src/nxtflow/clickhouse.py index af9c5fe..779d751 100644 --- a/src/nxtflow/clickhouse.py +++ b/src/nxtflow/clickhouse.py @@ -29,6 +29,7 @@ sanitize_url_for_display, validate_dir, validate_header_value, + validate_http_url, validate_range, validate_sql_identifier, ) @@ -114,7 +115,10 @@ def query_sql( query_args[f"param_{key}"] = str(val) qs = urllib.parse.urlencode(query_args) base = self.config.clickhouse_url.rstrip("/") - url = f"{base}/?{qs}" if qs else f"{base}/" + try: + url = validate_http_url(f"{base}/?{qs}" if qs else f"{base}/", "clickhouse_url") + except ValueError as exc: + raise ClickHouseError(str(exc)) from exc headers = self._build_headers() try: @@ -124,7 +128,7 @@ def query_sql( headers=headers, method="POST", ) - with urllib.request.urlopen( + with urllib.request.urlopen( # scheme validated via validate_http_url req, timeout=self.config.timeout_seconds, context=self._ssl_ctx, diff --git a/src/nxtflow/config.py b/src/nxtflow/config.py index 992856a..7674112 100644 --- a/src/nxtflow/config.py +++ b/src/nxtflow/config.py @@ -202,6 +202,17 @@ def sanitize_url_for_display(url: str | None) -> str: return raw +def validate_http_url(url: str, label: str = "URL") -> str: + """Ensure *url* uses an explicit http:// or https:// scheme and non-empty host.""" + cleaned = str(url or "").strip() + parsed = urllib.parse.urlsplit(cleaned) + if parsed.scheme.lower() not in ("http", "https") or not parsed.netloc: + raise ValueError( + f"Invalid {label} {sanitize_url_for_display(cleaned)!r}: only http:// and https:// URLs are permitted" + ) + return cleaned + + def validate_header_value(value: Any, label: str = "header value") -> str: """Reject CR, LF, and NUL characters in HTTP header-bound config values.""" if value is None: @@ -379,22 +390,40 @@ def load_config( cfg.victorialogs_url = str(raw_vl_url).rstrip("/") if str(raw_vl_url).strip(): vl_url_explicit = True - raw_vl_usr = data.get("victorialogs_user") if data.get("victorialogs_user") is not None else vl_sec.get("username") + raw_vl_usr = ( + data.get("victorialogs_user") if data.get("victorialogs_user") is not None else vl_sec.get("username") + ) if raw_vl_usr is not None: cfg.victorialogs_user = str(raw_vl_usr) - raw_vl_pwd = data.get("victorialogs_password") if data.get("victorialogs_password") is not None else vl_sec.get("password") + raw_vl_pwd = ( + data.get("victorialogs_password") + if data.get("victorialogs_password") is not None + else vl_sec.get("password") + ) if raw_vl_pwd is not None: cfg.victorialogs_password = str(raw_vl_pwd) - raw_vl_tok = data.get("victorialogs_token") if data.get("victorialogs_token") is not None else vl_sec.get("bearerToken") + raw_vl_tok = ( + data.get("victorialogs_token") if data.get("victorialogs_token") is not None else vl_sec.get("bearerToken") + ) if raw_vl_tok is not None: cfg.victorialogs_token = str(raw_vl_tok) - raw_vl_aid = data.get("victorialogs_account_id") if data.get("victorialogs_account_id") is not None else vl_sec.get("accountId") + raw_vl_aid = ( + data.get("victorialogs_account_id") + if data.get("victorialogs_account_id") is not None + else vl_sec.get("accountId") + ) if raw_vl_aid is not None: cfg.victorialogs_account_id = str(raw_vl_aid) - raw_vl_pid = data.get("victorialogs_project_id") if data.get("victorialogs_project_id") is not None else vl_sec.get("projectId") + raw_vl_pid = ( + data.get("victorialogs_project_id") + if data.get("victorialogs_project_id") is not None + else vl_sec.get("projectId") + ) if raw_vl_pid is not None: cfg.victorialogs_project_id = str(raw_vl_pid) - raw_vl_tls = data.get("victorialogs_tls_verify") if "victorialogs_tls_verify" in data else vl_sec.get("tlsVerify") + raw_vl_tls = ( + data.get("victorialogs_tls_verify") if "victorialogs_tls_verify" in data else vl_sec.get("tlsVerify") + ) if raw_vl_tls is not None: cfg.victorialogs_tls_verify = parse_tls_verify(raw_vl_tls) @@ -402,7 +431,9 @@ def load_config( raw_ch_url = data.get("clickhouse_url") if data.get("clickhouse_url") is not None else ch_sec.get("url") if raw_ch_url is not None: cfg.clickhouse_url = str(raw_ch_url).rstrip("/") - raw_ch_db = data.get("clickhouse_database") if data.get("clickhouse_database") is not None else ch_sec.get("database") + raw_ch_db = ( + data.get("clickhouse_database") if data.get("clickhouse_database") is not None else ch_sec.get("database") + ) if raw_ch_db is not None: cfg.clickhouse_database = validate_sql_identifier(str(raw_ch_db), "clickhouse_database") raw_ch_tbl = data.get("clickhouse_table") if data.get("clickhouse_table") is not None else ch_sec.get("table") @@ -411,10 +442,14 @@ def load_config( raw_ch_usr = data.get("clickhouse_user") if data.get("clickhouse_user") is not None else ch_sec.get("username") if raw_ch_usr is not None: cfg.clickhouse_user = str(raw_ch_usr) - raw_ch_pwd = data.get("clickhouse_password") if data.get("clickhouse_password") is not None else ch_sec.get("password") + raw_ch_pwd = ( + data.get("clickhouse_password") if data.get("clickhouse_password") is not None else ch_sec.get("password") + ) if raw_ch_pwd is not None: cfg.clickhouse_password = str(raw_ch_pwd) - raw_ch_ttl = data.get("clickhouse_ttl_days") if data.get("clickhouse_ttl_days") is not None else ch_sec.get("ttlDays") + raw_ch_ttl = ( + data.get("clickhouse_ttl_days") if data.get("clickhouse_ttl_days") is not None else ch_sec.get("ttlDays") + ) if raw_ch_ttl is not None: cfg.clickhouse_ttl_days = parse_ttl_days(raw_ch_ttl) raw_ch_tls = data.get("clickhouse_tls_verify") if "clickhouse_tls_verify" in data else ch_sec.get("tlsVerify") diff --git a/src/nxtflow/enricher/app.py b/src/nxtflow/enricher/app.py index d6adf5a..6f5470e 100644 --- a/src/nxtflow/enricher/app.py +++ b/src/nxtflow/enricher/app.py @@ -4,6 +4,7 @@ import argparse import base64 +import contextlib import gzip import http.client import ipaddress @@ -38,8 +39,10 @@ DEFAULT_BACKEND, parse_tls_verify, parse_ttl_days, + sanitize_url_for_display, validate_backend, validate_header_value, + validate_http_url, validate_sql_identifier, ) from nxtflow.enricher.default_cidrs import ( @@ -130,7 +133,10 @@ def _build_ssl_context(tls_verify: bool | str, ca_file: str = "") -> ssl.SSLCont if ca_file: return ssl.create_default_context(cafile=ca_file) if tls_verify is False: - return ssl._create_unverified_context() + 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() @@ -147,7 +153,9 @@ def _parse_cidr_list(items: Iterable[str]) -> list[ipaddress.IPv4Network | ipadd return nets -def _parse_named_cidrs(items: Iterable[dict[str, Any]]) -> list[tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, str]]: +def _parse_named_cidrs( + items: Iterable[dict[str, Any]], +) -> list[tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, str]]: out: list[tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, str]] = [] for entry in items: if not isinstance(entry, dict): @@ -1027,8 +1035,9 @@ def sync_once(self) -> bool: try: while next_url and pages < 50: pages += 1 - req = urllib.request.Request(next_url, headers=headers) - with urllib.request.urlopen( + validated_url = validate_http_url(next_url, "netbox_url") + req = urllib.request.Request(validated_url, headers=headers) + with urllib.request.urlopen( # scheme validated via validate_http_url req, timeout=self.cfg.netbox_timeout_seconds, context=self._ssl_ctx, @@ -1071,10 +1080,12 @@ def sync_once(self) -> bool: base_parsed = urllib.parse.urlparse(self.cfg.netbox_url) next_parsed = urllib.parse.urlparse(candidate_next) if ( - next_parsed.scheme not in ("http", "https") + next_parsed.scheme.lower() not in ("http", "https") or next_parsed.netloc != base_parsed.netloc ): - raise ValueError(f"Unexpected NetBox pagination URL: {candidate_next}") + raise ValueError( + f"Unexpected NetBox pagination URL: {sanitize_url_for_display(candidate_next)}" + ) next_url = candidate_next else: next_url = None @@ -1329,6 +1340,17 @@ def _post_with_retries( ssl_ctx: ssl.SSLContext, count_metrics: bool = True, ) -> bool: + try: + push_url = validate_http_url(push_url, f"{backend}_url") + except ValueError as exc: + LOGGER.error("Invalid %s push URL: %s", backend, exc) + if count_metrics: + self._record_push_status(backend, "error") + self._record_push_error(backend) + if batch_len > 0: + self.metrics.dropped_flows.inc(batch_len) + return False + attempts = max(0, int(self.cfg.max_retries)) + 1 for attempt in range(attempts): try: @@ -2159,10 +2181,8 @@ def _run_file_tailer(self) -> None: if cur_st.st_ino == inode and cur_st.st_size == offset: fh.truncate(0) offset = 0 - try: + with contextlib.suppress(OSError): pos_path.write_text(json.dumps({"inode": inode, "offset": 0}), encoding="utf-8") - except OSError: - pass except OSError as exc: LOGGER.debug("File tailer cycle error: %s", exc) diff --git a/src/nxtflow/loki.py b/src/nxtflow/loki.py index 86d752e..3900b31 100644 --- a/src/nxtflow/loki.py +++ b/src/nxtflow/loki.py @@ -38,6 +38,7 @@ sanitize_url_for_display, validate_dir, validate_header_value, + validate_http_url, validate_range, ) @@ -88,8 +89,12 @@ def request(self, endpoint: str, params: dict[str, Any] | None = None) -> dict[s if not (self.config.use_kubectl and self.config.kube_context): try: - req = urllib.request.Request(f"{self.config.loki_url}{suffix}", headers=headers) - with urllib.request.urlopen( + url = validate_http_url(f"{self.config.loki_url}{suffix}", "loki_url") + except ValueError as exc: + raise LokiError(str(exc)) from exc + try: + req = urllib.request.Request(url, headers=headers) + with urllib.request.urlopen( # scheme validated via validate_http_url req, timeout=self.config.timeout_seconds, context=self._ssl_ctx, @@ -116,7 +121,10 @@ def request(self, endpoint: str, params: dict[str, Any] | None = None) -> dict[s safe_url = sanitize_url_for_display(self.config.loki_url) raise LokiError(f"Loki request failed ({safe_url}): {exc}") from exc - cluster_url = f"{self.config.cluster_loki_url}{suffix}" + try: + cluster_url = validate_http_url(f"{self.config.cluster_loki_url}{suffix}", "cluster_loki_url") + except ValueError as exc: + raise LokiError(str(exc)) from exc req_payload = json.dumps({"url": cluster_url, "headers": headers}) cmd = [ "kubectl", @@ -131,14 +139,17 @@ def request(self, endpoint: str, params: dict[str, Any] | None = None) -> dict[s "python3", "-c", ( - "import json, sys, urllib.request; " + "import json, sys, urllib.parse, urllib.request; " "cfg = json.load(sys.stdin); " - "req = urllib.request.Request(cfg['url'], headers=cfg['headers']); " + "u = cfg['url']; " + "if urllib.parse.urlsplit(u).scheme not in ('http', 'https'): " + "raise ValueError('invalid url scheme'); " + "req = urllib.request.Request(u, headers=cfg['headers']); " "print(urllib.request.urlopen(req, timeout=30).read().decode())" ), ] try: - proc = subprocess.run( + proc = subprocess.run( # fixed list-form kubectl exec; headers sent via stdin cmd, capture_output=True, text=True, diff --git a/src/nxtflow/mcp_server.py b/src/nxtflow/mcp_server.py index c3abe46..0b86a30 100644 --- a/src/nxtflow/mcp_server.py +++ b/src/nxtflow/mcp_server.py @@ -11,6 +11,7 @@ from starlette.requests import Request from starlette.responses import JSONResponse +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 @@ -33,7 +34,7 @@ def _client() -> TelemetryBackend: @mcp.custom_route("/healthz", methods=["GET"]) async def healthz(_request: Request) -> JSONResponse: - return JSONResponse({"status": "ok", "service": "nxtflow-mcp", "backend": cfg.backend}) + return JSONResponse({"status": "ok", "service": "nxtflow-mcp", "version": __version__, "backend": cfg.backend}) @mcp.tool() def nxtflow_status(range_str: str = "5m") -> str: @@ -248,10 +249,7 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: env_transport = raw_transport if raw_transport in _VALID_TRANSPORTS else "stdio" raw_host = os.environ.get("NXTFLOW_MCP_HOST", "127.0.0.1").strip() - if not raw_host or "://" in raw_host or any(ch.isspace() for ch in raw_host): - env_host = "127.0.0.1" - else: - env_host = raw_host + env_host = "127.0.0.1" if not raw_host or "://" in raw_host or any(ch.isspace() for ch in raw_host) else raw_host raw_port = os.environ.get("NXTFLOW_MCP_PORT", "").strip() env_port = 8000 diff --git a/src/nxtflow/ui/app.py b/src/nxtflow/ui/app.py index 44ba755..d00b260 100644 --- a/src/nxtflow/ui/app.py +++ b/src/nxtflow/ui/app.py @@ -18,6 +18,7 @@ from starlette.routing import Route from starlette.types import ASGIApp, Message, Receive, Scope, Send +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 @@ -169,14 +170,14 @@ async def favicon_ico(_request: Request) -> Response: ) async def healthz(_request: Request) -> JSONResponse: - return JSONResponse({"status": "ok", "service": "nxtflow-ui", "backend": cfg.backend}) + return JSONResponse({"status": "ok", "service": "nxtflow-ui", "version": __version__, "backend": cfg.backend}) async def api_status(request: Request) -> Response: async def _call() -> dict[str, Any]: range_str = _parse_range_param(request, default="5m") data = await _run_backend(lambda c: c.get_status_data(range_str=range_str)) - if isinstance(data, dict) and "backend" not in data: - return {**data, "backend": cfg.backend} + if isinstance(data, dict): + return {"backend": cfg.backend, **data, "version": __version__} return data return await _handle_api(_call) @@ -385,7 +386,12 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: description="nxtflow interactive NetFlow/IPFIX/sFlow web dashboard", ) parser.add_argument("--host", default=env_host, help=f"HTTP bind host (default: {DEFAULT_UI_HOST})") - parser.add_argument("--port", type=_valid_port, default=env_port, help=f"HTTP bind port (default: {DEFAULT_UI_PORT})") + parser.add_argument( + "--port", + type=_valid_port, + default=env_port, + help=f"HTTP bind port (default: {DEFAULT_UI_PORT})", + ) parser.add_argument( "--backend", choices=("loki", "victorialogs", "clickhouse"), diff --git a/src/nxtflow/ui/static/index.html b/src/nxtflow/ui/static/index.html index b22a8f6..b9902a0 100644 --- a/src/nxtflow/ui/static/index.html +++ b/src/nxtflow/ui/static/index.html @@ -162,12 +162,36 @@ flex-shrink: 0; } + .brand-title-row { + display: flex; + align-items: center; + gap: 7px; + } + .brand-name { font-weight: 700; font-size: 15px; letter-spacing: -0.02em; } + .version-badge { + display: inline-flex; + align-items: center; + padding: 1px 7px; + border-radius: 999px; + font-size: 10.5px; + font-weight: 600; + line-height: 1.4; + letter-spacing: 0.01em; + color: var(--cyan); + background: var(--cyan-dim); + border: 1px solid rgba(0, 212, 255, 0.32); + } + + .version-badge:empty { + display: none; + } + .brand-sub { font-size: 11px; color: var(--text-dim); @@ -1296,7 +1320,10 @@
- nxtflow +
+ nxtflow + +
NetFlow · IPFIX · sFlow Telemetry
@@ -2205,8 +2232,20 @@ row.replaceChildren(...buttons); } + function setVersionBadge(rawVersion) { + const badge = $("app-version"); + if (!badge) return; + const cleaned = String(rawVersion || "").trim().replace(/^v/i, ""); + if (!cleaned) return; + badge.textContent = `v${cleaned}`; + badge.title = `nxtflow v${cleaned}`; + } + function renderStatus(st) { state.lastStatus = st; + if (st && st.version) { + setVersionBadge(st.version); + } const backend = st.backend || "loki"; const active = Number(st.active_streams || 0); const expected = Number(st.expected_streams || 0); @@ -3262,6 +3301,11 @@ readUrlState(); bindEvents(); syncControlsUi(); + apiGet("/healthz") + .then((h) => { + if (h && h.version) setVersionBadge(h.version); + }) + .catch(() => {}); resetAutoRefresh(); refreshAll(); if (state.host) { diff --git a/src/nxtflow/victorialogs.py b/src/nxtflow/victorialogs.py index 1be5d75..bec78dc 100644 --- a/src/nxtflow/victorialogs.py +++ b/src/nxtflow/victorialogs.py @@ -34,6 +34,7 @@ sanitize_url_for_display, validate_dir, validate_header_value, + validate_http_url, validate_range, ) @@ -93,11 +94,14 @@ def _build_headers(self) -> dict[str, str]: def _post_raw(self, endpoint: str, params: dict[str, Any] | None = None) -> str: body_bytes = urllib.parse.urlencode(params or {}).encode("utf-8") - url = f"{self.config.victorialogs_url.rstrip('/')}{endpoint}" + try: + url = validate_http_url(f"{self.config.victorialogs_url.rstrip('/')}{endpoint}", "victorialogs_url") + except ValueError as exc: + raise VictoriaLogsError(str(exc)) from exc headers = self._build_headers() try: req = urllib.request.Request(url, data=body_bytes, headers=headers, method="POST") - with urllib.request.urlopen( + with urllib.request.urlopen( # scheme validated via validate_http_url req, timeout=self.config.timeout_seconds, context=self._ssl_ctx, diff --git a/tests/test_cli.py b/tests/test_cli.py index 05a3674..b49a821 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1044,3 +1044,31 @@ def do_GET(self) -> None: finally: srv.shutdown() srv.server_close() + + + +def test_cli_version_flag_and_url_scheme_validation(capsys: pytest.CaptureFixture[str]) -> None: + from nxtflow import __version__ + from nxtflow.clickhouse import ClickHouseClient, ClickHouseError + from nxtflow.config import NxtflowConfig, validate_http_url + from nxtflow.victorialogs import VictoriaLogsClient, VictoriaLogsError + + for flag in ("-V", "--version"): + with pytest.raises(SystemExit) as exc: + main([flag]) + assert exc.value.code == 0 + out = capsys.readouterr().out.strip() + assert out == f"nxtflow {__version__}" + + assert validate_http_url("http://localhost:9428/path") == "http://localhost:9428/path" + assert validate_http_url("https://loki.example.com:3100") == "https://loki.example.com:3100" + for bad_url in ("file:///etc/passwd", "ftp://example.com/file", "javascript:alert(1)", "http:///missing-host", ""): + with pytest.raises(ValueError, match="only http:// and https://"): + validate_http_url(bad_url) + + with pytest.raises(LokiError, match="only http:// and https://"): + LokiClient(NxtflowConfig(loki_url="file:///etc/passwd")).check_readiness() + with pytest.raises(VictoriaLogsError, match="only http:// and https://"): + VictoriaLogsClient(NxtflowConfig(victorialogs_url="file:///etc/passwd")).check_readiness() + with pytest.raises(ClickHouseError, match="only http:// and https://"): + ClickHouseClient(NxtflowConfig(clickhouse_url="file:///etc/passwd")).check_readiness() diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 2617f35..ea5ab40 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -9,6 +9,7 @@ import pytest from starlette.testclient import TestClient +from nxtflow import __version__ from nxtflow.config import NxtflowConfig from nxtflow.loki import LokiError from nxtflow.mcp_server import create_server, parse_args @@ -38,6 +39,7 @@ def test_mcp_registers_all_10_tools_and_healthz() -> None: resp = client.get("/healthz") assert resp.status_code == 200 assert resp.json()["status"] == "ok" + assert resp.json()["version"] == __version__ assert resp.json()["backend"] == "victorialogs" @@ -217,6 +219,7 @@ def test_mcp_routes_victorialogs_and_clickhouse_backends() -> None: client = TestClient(app) health = client.get("/healthz") assert health.status_code == 200 + assert health.json()["version"] == __version__ assert health.json()["backend"] == backend async def call_status(server: object = mcp) -> dict: diff --git a/tests/test_ui.py b/tests/test_ui.py index 3aeed31..7a0eada 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -8,6 +8,7 @@ import pytest from starlette.testclient import TestClient +from nxtflow import __version__ from nxtflow.backends import BackendError from nxtflow.clickhouse import ClickHouseError from nxtflow.config import NxtflowConfig @@ -69,7 +70,12 @@ def test_ui_serves_html_and_healthz_across_backends() -> None: default_client = TestClient(create_app(NxtflowConfig())) default_health = default_client.get("/healthz") assert default_health.status_code == 200 - assert default_health.json() == {"status": "ok", "service": "nxtflow-ui", "backend": "victorialogs"} + assert default_health.json() == { + "status": "ok", + "service": "nxtflow-ui", + "version": __version__, + "backend": "victorialogs", + } for backend in ("loki", "victorialogs", "clickhouse"): app = create_app(NxtflowConfig(backend=backend)) @@ -83,6 +89,8 @@ def test_ui_serves_html_and_healthz_across_backends() -> None: assert "echarts@5" in html_resp.text assert "explorer-sort-toggle" in html_resp.text assert "drawer-ips" in html_resp.text + assert 'id="app-version"' in html_resp.text + assert "setVersionBadge" in html_resp.text assert 'href="/favicon.svg"' in html_resp.text assert 'href="/favicon.ico"' in html_resp.text assert ".innerHTML" not in html_resp.text @@ -99,7 +107,12 @@ def test_ui_serves_html_and_healthz_across_backends() -> None: health = client.get("/healthz") assert health.status_code == 200 - assert health.json() == {"status": "ok", "service": "nxtflow-ui", "backend": backend} + assert health.json() == { + "status": "ok", + "service": "nxtflow-ui", + "version": __version__, + "backend": backend, + } # Verify package resource static files are discoverable via importlib.resources static_dir = resources.files("nxtflow.ui").joinpath("static") @@ -118,9 +131,19 @@ def test_ui_all_api_endpoints_and_cache_control() -> None: assert r_status.status_code == 200 assert r_status.headers["cache-control"] == "no-store" assert r_status.json()["backend"] == "loki" + assert r_status.json()["version"] == __version__ assert r_status.json()["active_streams"] == 6 mock_client.get_status_data.assert_called_with(range_str="5m") + mock_client.get_status_data.return_value = { + **mock_client.get_status_data.return_value, + "backend": "victorialogs", + } + r_status_with_backend = http.get("/api/status?range=5m") + assert r_status_with_backend.status_code == 200 + assert r_status_with_backend.json()["backend"] == "victorialogs" + assert r_status_with_backend.json()["version"] == __version__ + r_sum = http.get("/api/summary?range=15m&site=&dir=") assert r_sum.status_code == 200 assert r_sum.headers["cache-control"] == "no-store"