diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index d12257c..0c89c95 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -1,13 +1,38 @@
version: 2
updates:
- - package-ecosystem: "pip"
+ - package-ecosystem: github-actions
directory: "/"
+ target-branch: dev
schedule:
- interval: "weekly"
- target-branch: "dev"
+ interval: monthly
+ open-pull-requests-limit: 5
+ groups:
+ github-actions:
+ patterns:
+ - "*"
- - package-ecosystem: "github-actions"
+ - package-ecosystem: pip
directory: "/"
+ target-branch: dev
schedule:
- interval: "weekly"
- target-branch: "dev"
+ interval: monthly
+ open-pull-requests-limit: 5
+ groups:
+ dev-dependencies:
+ dependency-type: development
+ patterns:
+ - "*"
+ # Major bumps are deliberately not listed here: they stay individual
+ # PRs, since those are the ones that actually break things.
+ production-dependencies:
+ dependency-type: production
+ patterns:
+ - "*"
+ update-types:
+ - minor
+ # Patch bumps are ignored to keep PR volume low; security fixes still
+ # arrive through Dependabot security alerts, which ignore this filter.
+ ignore:
+ - dependency-name: "*"
+ update-types:
+ - version-update:semver-patch
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 5562541..21b03f8 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -16,4 +16,3 @@
- [ ] Related issue(s)
- [ ] Tests added / updated
- [ ] Documentation updated
-- [ ] `CHANGELOG.md` entry added
diff --git a/.github/release.yml b/.github/release.yml
index 0659e33..1be56d3 100644
--- a/.github/release.yml
+++ b/.github/release.yml
@@ -1,25 +1,38 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-release-notes.json
-# Configuration for GitHub auto-generated release notes
+# Categories for GitHub's generated release notes.
# https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes
-
+#
+# A pull request is filed by its labels, and lands in the FIRST category below
+# whose labels it carries โ so the order is a priority rule, not cosmetic. A PR
+# labelled both `bug` and `enhancement` shows up under New Features only, never
+# twice. The order puts what users care about first and pushes dependency/CI
+# noise to the bottom.
+#
+# The catch-all `*` at the end means an unlabelled PR is still listed instead of
+# being dropped silently.
changelog:
categories:
- - title: "Features"
- labels:
- - "enhancement"
- - "feature"
- - title: "Bug Fixes"
- labels:
- - "bug"
- - "fix"
- - title: "Documentation"
- labels:
- - "documentation"
- - "docs"
- - title: "CI / Tooling"
- labels:
- - "ci"
- - "tooling"
+ - title: "โ ๏ธ Breaking Changes"
+ labels: ["breaking", "breaking-change"]
+ - title: "๐ Security"
+ labels: ["security"]
+ - title: "โจ New Features"
+ labels: ["enhancement", "feature"]
+ - title: "๐ Bug Fixes"
+ labels: ["bug", "fix"]
+ - title: "โก Performance"
+ labels: ["performance"]
+ - title: "โป๏ธ Refactoring"
+ labels: ["refactor"]
+ - title: "๐ Documentation"
+ labels: ["documentation", "docs"]
+ - title: "๐งช Tests"
+ labels: ["test"]
+ - title: "๐ฆ Dependencies"
+ labels: ["dependencies", "depfu"]
+ - title: "๐ง CI / Tooling"
+ labels: ["ci", "tooling", "chore", "github_actions"]
+ - title: "๐งฉ Other Changes"
+ labels: ["*"]
exclude:
- labels:
- - "skip-changelog"
+ labels: ["skip-changelog"]
diff --git a/.github/workflows/bandit-sarif.yml b/.github/workflows/bandit-sarif.yml
index a826515..fbd1b00 100644
--- a/.github/workflows/bandit-sarif.yml
+++ b/.github/workflows/bandit-sarif.yml
@@ -30,7 +30,7 @@ jobs:
- # Setup Python for Bandit scanning
name: Set up Python
- uses: actions/setup-python@v6
+ uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: "pip"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dfd8e46..e74baef 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -57,7 +57,7 @@ jobs:
- # Setup Python version and pip cache
name: Set up Python
- uses: actions/setup-python@v6
+ uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
@@ -94,7 +94,7 @@ jobs:
- # Upload coverage.xml to Codecov
name: Upload coverage to Codecov
if: ${{ matrix.run-coverage && github.repository == 'Ajimaru/OctoPrint-LogMonitor' }}
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: coverage.xml
@@ -117,7 +117,7 @@ jobs:
- # Setup Node.js for pre-commit hooks (ESLint/Prettier)
name: Set up Node.js for hooks
if: ${{ matrix.run-precommit && hashFiles('.pre-commit-config.yaml') != '' }}
- uses: actions/setup-node@v6
+ uses: actions/setup-node@v7
with:
node-version: "20.19.0"
cache: "npm"
@@ -194,7 +194,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Python
- uses: actions/setup-python@v6
+ uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python-version }}
cache: pip
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 3c17ad8..ca125aa 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -28,7 +28,7 @@ jobs:
- # Setup Python for MkDocs build
name: Set up Python
- uses: actions/setup-python@v6
+ uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
diff --git a/.github/workflows/i18n.yml b/.github/workflows/i18n.yml
index d6e28ce..16dd9ef 100644
--- a/.github/workflows/i18n.yml
+++ b/.github/workflows/i18n.yml
@@ -25,7 +25,7 @@ jobs:
- # Setup Python 3.12 for i18n tools
name: Set up Python
- uses: actions/setup-python@v6
+ uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index c5dbf22..25b5dcc 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -30,7 +30,7 @@ jobs:
- # Setup Python and pip cache
name: Set up Python
- uses: actions/setup-python@v6
+ uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
@@ -54,7 +54,7 @@ jobs:
- # Setup Node.js for ESLint/Prettier hooks
name: Set up Node.js for hooks
if: ${{ hashFiles('.pre-commit-config.yaml') != '' }}
- uses: actions/setup-node@v6
+ uses: actions/setup-node@v7
with:
node-version: "20.19.0"
cache: "npm"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 5acc737..5e913ac 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -2,8 +2,7 @@ name: Release
on:
push:
- tags:
- - "v*"
+ tags: ["v*", "[0-9]*"]
permissions:
contents: write
@@ -18,7 +17,7 @@ jobs:
uses: actions/checkout@v7
- name: Set up Python
- uses: actions/setup-python@v6
+ uses: actions/setup-python@v7
with:
python-version: "3.12"
cache: pip
@@ -29,17 +28,53 @@ jobs:
python -m pip install build
- name: Build sdist and wheel
+ run: python -m build
+
+ - name: Validate paths (prevent directory traversal)
+ run: |
+ for f in dist/*; do
+ rel="$(realpath --relative-to="$(pwd)" "$f")"
+ case "$rel" in
+ .*) echo "Suspicious path: $f ($rel)"; exit 1 ;;
+ esac
+ done
+
+ - name: Determine prerelease
+ id: prerelease
run: |
- python -m build
+ TAG="${{ github.ref_name }}"
+ TAG_LOWER="$(printf '%s' "$TAG" | tr '[:upper:]' '[:lower:]')"
+ # Prerelease = a/b/rc/dev segment in the VERSION part of the tag
+ # (PEP 440 style, digit or separator before it, e.g. 0.2.2rc1 or
+ # 0.2.2.dev6). The match must end at the tag end or at the local
+ # part ("+hash"), so a commit hash that happens to end in e.g.
+ # "b1" can never flip the detection.
+ if echo "$TAG_LOWER" | grep -qE '(^|[-.0-9])(a|b|rc|dev)([.-]?[0-9]+)?($|\+)'; then
+ echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
+ fi
- - name: Create zip assets (versioned + latest)
+ - name: Stage release artifacts
shell: bash
run: |
set -euo pipefail
-
+ mkdir -p release_zips
+
+ # Keep the wheel's original, PEP 427-compliant filename
+ # ({name}-{version}-{pytag}-{abitag}-{platformtag}.whl). pip rejects
+ # any renamed wheel ("wrong number of parts"), so it must not be
+ # aliased โ both the OctoPrint plugin manager and pip parse the name.
+ cp dist/*.whl dist/*.tar.gz release_zips/
+
+ # Also publish a source .zip (versioned + a stable -latest.zip). A zip
+ # has no strict filename parser, so the OctoPrint plugin manager can
+ # install it directly from a fixed "โฆ-latest.zip" URL. Build it from
+ # the sdist tarball rather than the working tree so it matches the
+ # released source exactly.
version="${GITHUB_REF_NAME#v}"
- zip_versioned="dist/OctoPrint-LogMonitor-${version}.zip"
- zip_latest="dist/OctoPrint-LogMonitor-latest.zip"
+ zip_versioned="release_zips/OctoPrint-LogMonitor-${version}.zip"
+ zip_latest="release_zips/OctoPrint-LogMonitor-latest.zip"
shopt -s nullglob
sdist_candidates=(dist/*"${version}".tar.gz)
@@ -50,11 +85,6 @@ jobs:
fi
sdist="${sdist_candidates[0]}"
- if [[ ! -f "$sdist" ]]; then
- echo "Expected sdist not found: $sdist" >&2
- exit 1
- fi
-
python - "$sdist" "$zip_versioned" <<'PY'
import sys
import tarfile
@@ -72,8 +102,8 @@ jobs:
if not member.isfile():
continue
- # Defensive: ensure tar member paths cannot become path traversal entries in the zip.
- # Tar archives always use POSIX-style paths.
+ # Defensive: never let a tar member become a path-traversal
+ # entry in the zip. Tar archives always use POSIX paths.
member_path = PurePosixPath(member.name)
if (
member_path.is_absolute()
@@ -86,11 +116,10 @@ jobs:
extracted = tf.extractfile(member)
if extracted is None:
continue
- data = extracted.read()
zi = zipfile.ZipInfo(str(member_path))
zi.external_attr = (member.mode & 0o777) << 16
- zf.writestr(zi, data)
+ zf.writestr(zi, extracted.read())
PY
cp -f "$zip_versioned" "$zip_latest"
@@ -99,60 +128,21 @@ jobs:
uses: actions/upload-artifact@v7
with:
name: dist
- path: dist/*
-
- - name: Generate release notes
- uses: actions/github-script@v9
- with:
- script: |
- const fs = require("fs");
-
- const tag = process.env.GITHUB_REF_NAME;
- const title = String(tag || "")
- .replace(/^OctoPrint[-_\s]?LogMonitor[-_\s]?/i, "")
- .trim() || tag;
-
- const { owner, repo } = context.repo;
- const response = await github.rest.repos.generateReleaseNotes({
- owner,
- repo,
- tag_name: tag,
- });
-
- const assets = [
- "wheel (.whl)",
- "sdist (.tar.gz)",
- "versioned zip (.zip)",
- "OctoPrint-LogMonitor-latest.zip",
- ];
-
- const body = [
- title,
- "",
- response.data.body?.trim() || "",
- "",
- "Assets:",
- ...assets.map((a) => `- ${a}`),
- "",
- ].join("\n");
-
- fs.writeFileSync("release_notes.md", body, { encoding: "utf-8" });
- fs.writeFileSync("release_title.txt", title, { encoding: "utf-8" });
-
- - name: Read release title
- id: release_title
- run: |
- title=$(cat release_title.txt)
- echo "title=$title" >> "$GITHUB_OUTPUT"
+ path: release_zips/*
- - name: Create GitHub Release
- uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
+ - name: Create GitHub release (draft)
+ uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
- name: ${{ steps.release_title.outputs.title }}
- draft: false
- prerelease: ${{ contains(github.ref_name, 'rc') || contains(github.ref_name, 'a') || contains(github.ref_name, 'b') }}
- body_path: release_notes.md
- files: dist/*
+ files: |
+ release_zips/*
+ # Notes are grouped by PR label; the categories live in
+ # .github/release.yml.
+ generate_release_notes: true
+ # Always a draft: a release is published by hand once the notes and
+ # the attached artifacts have been eyeballed. Pushing a tag must
+ # never publish on its own.
+ draft: true
+ prerelease: ${{ steps.prerelease.outputs.is_prerelease }}
# Optional: Publish to PyPI
#
diff --git a/babel.cfg b/babel.cfg
index 202a4ee..e0ec776 100644
--- a/babel.cfg
+++ b/babel.cfg
@@ -6,3 +6,11 @@ extensions=jinja2.ext.do, octoprint.util.jinja.trycatch
[javascript: */**.js]
extract_messages = gettext, ngettext
+# Disable JSX/E4X parsing. This codebase has no JSX, but Babel's lexer reads
+# the regex literal />/g (in escapeHtml()) as a JSX tag close. Tokenisation is
+# then off by one from that point on: the rest of the file is swallowed into
+# phantom strings and every gettext() call after it is silently dropped from
+# the catalog. The value is left empty on purpose -- Babel reads config values
+# as strings and only checks truthiness, so "false" or "0" would still enable
+# it; only an empty value is falsy.
+jsx =
diff --git a/octoprint_logmonitor/__init__.py b/octoprint_logmonitor/__init__.py
index a5014ad..9e1190e 100644
--- a/octoprint_logmonitor/__init__.py
+++ b/octoprint_logmonitor/__init__.py
@@ -6,6 +6,7 @@
from __future__ import annotations
+import io
import json
import logging
import os
@@ -21,6 +22,7 @@
from .log_searcher import LogSearcher
from .log_tailer import LogTailer
from .security import (
+ MAX_DOWNLOAD_BYTES,
MAX_HISTORY_LIMIT,
MAX_SEARCH_LIMIT,
RateLimiter,
@@ -1050,8 +1052,36 @@ def download_log_file(self, filename):
if not os.path.isfile(filepath):
return flask.jsonify({"error": "File not found"}), 404
+ if not check_file_size(filepath, MAX_DOWNLOAD_BYTES):
+ size_mb = MAX_DOWNLOAD_BYTES // (1024 * 1024)
+ return (
+ flask.jsonify(
+ {
+ "error": (
+ f"File is too large to download "
+ f"(limit {size_mb} MiB)"
+ )
+ }
+ ),
+ 413,
+ )
+
+ # Serve a fixed-size snapshot rather than handing send_file() the
+ # path. A live log keeps growing: send_file() stats the file to
+ # set Content-Length, but the body is only read afterwards, while
+ # the response is streamed. If the file grew in between, the body
+ # is longer than the advertised length and Tornado aborts the
+ # response with "Tried to write more data than Content-Length",
+ # which escapes this handler (it is raised after the return) and
+ # surfaces as "Exception in WSGI application".
+ with open(filepath, "rb") as handle:
+ payload = handle.read()
+
return flask.send_file(
- filepath, as_attachment=True, download_name=filename
+ io.BytesIO(payload),
+ as_attachment=True,
+ download_name=filename,
+ mimetype="text/plain",
)
except Exception as e:
diff --git a/octoprint_logmonitor/_version.py b/octoprint_logmonitor/_version.py
index 38ff8c1..57a3810 100644
--- a/octoprint_logmonitor/_version.py
+++ b/octoprint_logmonitor/_version.py
@@ -1,3 +1,3 @@
"""Single source of truth for the plugin version used by dev tooling."""
-VERSION = "0.2.4"
+VERSION = "0.2.5"
diff --git a/octoprint_logmonitor/log_searcher.py b/octoprint_logmonitor/log_searcher.py
index 39f7371..880d164 100644
--- a/octoprint_logmonitor/log_searcher.py
+++ b/octoprint_logmonitor/log_searcher.py
@@ -13,6 +13,15 @@
from typing import Any, ClassVar, Optional
from .log_parser import parse_line
+from .security import (
+ MAX_QUERY_LENGTH,
+ MAX_SCAN_LINES,
+ PATTERN_SYNTAX_ERRORS,
+ PatternTimeoutError,
+ UnsafePatternError,
+ compile_search_pattern,
+ search_with_timeout,
+)
class LogSearcher:
@@ -105,17 +114,38 @@ def search(
# Compile search pattern
search_pattern = None
+ if query and len(query) > MAX_QUERY_LENGTH:
+ if self._logger:
+ self._logger.error(
+ f"Search query rejected: exceeds {MAX_QUERY_LENGTH} "
+ "characters"
+ )
+ return {
+ "results": [],
+ "total": 0,
+ "offset": offset,
+ "limit": limit,
+ "error": f"Query exceeds maximum length of "
+ f"{MAX_QUERY_LENGTH} characters",
+ }
if query:
try:
- if use_regex:
- flags = 0 if case_sensitive else re.IGNORECASE
- search_pattern = re.compile(query, flags)
- else:
- # Escape regex special characters for literal search
- escaped_query = re.escape(query)
- flags = 0 if case_sensitive else re.IGNORECASE
- search_pattern = re.compile(escaped_query, flags)
- except re.error as e:
+ search_pattern = compile_search_pattern(
+ query,
+ use_regex=use_regex,
+ case_sensitive=case_sensitive,
+ )
+ except UnsafePatternError as e:
+ if self._logger:
+ self._logger.warning(f"Unsafe regex rejected: {e}")
+ return {
+ "results": [],
+ "total": 0,
+ "offset": offset,
+ "limit": limit,
+ "error": str(e),
+ }
+ except PATTERN_SYNTAX_ERRORS as e:
if self._logger:
self._logger.error(f"Invalid regex pattern: {e}")
return {
@@ -140,8 +170,21 @@ def search(
# list of [entry, remaining_line_count] pairs.
pending_after: list[list[Any]] = []
+ truncated = False
with open(filepath, encoding="utf-8", errors="replace") as f:
- for line in f:
+ for lineno, line in enumerate(f, 1):
+ # Bound total work per request: even with a per-match
+ # timeout, an unbounded file would still let one request
+ # burn arbitrary CPU.
+ if lineno > MAX_SCAN_LINES:
+ truncated = True
+ if self._logger:
+ self._logger.warning(
+ f"Search stopped after {MAX_SCAN_LINES} "
+ f"lines in {filepath}"
+ )
+ break
+
parsed = self._parse_line(line)
# Feed after-context of earlier matches first, so the
@@ -189,13 +232,33 @@ def search(
if before_buffer is not None:
before_buffer.append(parsed)
- return {
+ response: dict[str, Any] = {
"results": results,
"total": total_matches,
"offset": offset,
"limit": limit,
}
+ if truncated:
+ # Signal that `total` is a lower bound, not the real count.
+ response["truncated"] = True
+ response["scan_limit"] = MAX_SCAN_LINES
+ return response
+ except PatternTimeoutError:
+ if self._logger:
+ self._logger.warning(
+ f"Search aborted: pattern too slow for query {query!r}"
+ )
+ return {
+ "results": [],
+ "total": 0,
+ "offset": offset,
+ "limit": limit,
+ "error": (
+ "Search pattern took too long to evaluate. "
+ "Please simplify the expression."
+ ),
+ }
except OSError as e:
if self._logger:
self._logger.error(f"Error searching log file: {e}")
@@ -242,11 +305,12 @@ def _matches_filters(
if not search_pattern:
return True
- # Search in message field, fall back to full raw line
- return bool(
- search_pattern.search(parsed["message"])
- or search_pattern.search(parsed["raw"])
- )
+ # Search in message field, fall back to full raw line.
+ # search_with_timeout bounds each attempt so a pathological
+ # user-supplied pattern cannot pin a CPU core (ReDoS).
+ return search_with_timeout(
+ search_pattern, parsed["message"]
+ ) or search_with_timeout(search_pattern, parsed["raw"])
def get_file_stats(self, filepath: str) -> dict[str, Any]:
"""Get statistics about a log file.
diff --git a/octoprint_logmonitor/security.py b/octoprint_logmonitor/security.py
index 7dd15b8..7f0f6d8 100644
--- a/octoprint_logmonitor/security.py
+++ b/octoprint_logmonitor/security.py
@@ -9,7 +9,21 @@
import re
import threading
import time
-from typing import Optional
+from typing import Any, Optional
+
+try: # pragma: no cover - import guard depends on the environment
+ # The third-party ``regex`` module is a drop-in replacement for ``re``
+ # that supports a per-call ``timeout``. The stdlib ``re`` has no way to
+ # bound matching time, so a user-supplied pattern can pin a CPU core
+ # indefinitely (ReDoS). ``regex`` is an optional dependency: when it is
+ # missing we fall back to ``re`` plus a conservative pattern-complexity
+ # check, which is weaker but needs no extra install.
+ import regex as _regex_module
+
+ HAS_REGEX_TIMEOUT: bool = True
+except ImportError: # pragma: no cover - exercised in the no-regex env
+ _regex_module = None # type: ignore[assignment]
+ HAS_REGEX_TIMEOUT = False
# ---------------------------------------------------------------------------
# Constants
@@ -19,12 +33,38 @@
#: to prevent excessive memory/CPU usage.
MAX_FILE_SIZE_BYTES: int = 1024 * 1024 * 1024 # 1 GiB
+#: Hard upper bound for a log file served through the download endpoint.
+#: That endpoint buffers the file in memory to pin Content-Length against a
+#: file that is still being written to, so this bound is about available RAM,
+#: not disk: OctoPrint commonly runs on a Pi with well under 1 GiB free.
+#: Larger files are refused rather than risking the server process.
+MAX_DOWNLOAD_BYTES: int = 64 * 1024 * 1024 # 64 MiB
+
#: Hard upper bound for the ``limit`` query parameter in search requests.
MAX_SEARCH_LIMIT: int = 1000
#: Hard upper bound for alert-history ``limit`` parameter.
MAX_HISTORY_LIMIT: int = 500
+#: Hard upper bound for the length of a user-supplied search query/regex.
+#: Note: this is an input-size guard only. It does NOT prevent catastrophic
+#: backtracking -- a pattern such as ``(x+)+$`` is six characters long and can
+#: still hang a backtracking engine indefinitely. ReDoS is handled separately
+#: by the execution timeout in :func:`compile_search_pattern` /
+#: :func:`search_with_timeout`.
+MAX_QUERY_LENGTH: int = 200
+
+#: Wall-clock budget for a single regex match attempt, in seconds. A
+#: user-supplied pattern that exceeds this on one line is aborted rather than
+#: allowed to pin a CPU core. Only enforced when the ``regex`` module is
+#: available (see :data:`HAS_REGEX_TIMEOUT`).
+REGEX_TIMEOUT_SECONDS: float = 0.25
+
+#: Maximum number of lines a single search request may scan. Bounds the total
+#: work of one request even when every individual match stays under
+#: :data:`REGEX_TIMEOUT_SECONDS`.
+MAX_SCAN_LINES: int = 500_000
+
#: Regex patterns used to detect and mask sensitive values in log text.
#: Each entry is a (compiled_pattern, replacement_string) pair.
_SENSITIVE_PATTERNS: list[tuple[re.Pattern, str]] = [
@@ -302,3 +342,170 @@ def _cleanup_locked(self, now: float) -> None:
self._clients[key] = remaining
else:
del self._clients[key]
+
+
+# ---------------------------------------------------------------------------
+# Regex execution safety (ReDoS mitigation)
+# ---------------------------------------------------------------------------
+
+#: Characters that act as a quantifier directly after a group.
+_QUANTIFIER_CHARS = frozenset("*+{")
+
+
+#: Exception type(s) raised for invalid regex syntax by whichever engine is
+#: in use. ``regex.error`` does NOT subclass ``re.error``, so both must be
+#: caught; callers should use this tuple rather than ``re.error`` alone.
+PATTERN_SYNTAX_ERRORS: tuple = (
+ (re.error, _regex_module.error) if HAS_REGEX_TIMEOUT else (re.error,)
+)
+
+
+class UnsafePatternError(ValueError):
+ """Raised when a user-supplied regex is rejected as unsafe to execute."""
+
+
+class PatternTimeoutError(Exception):
+ """Raised when a regex match exceeds :data:`REGEX_TIMEOUT_SECONDS`."""
+
+
+def _looks_catastrophic(pattern: str) -> bool:
+ r"""Report whether a pattern has a shape known to backtrack badly.
+
+ This is a deliberately coarse heuristic used only when the ``regex``
+ module (and therefore a real execution timeout) is unavailable. It
+ rejects nested quantifiers such as ``(x+)+`` and quantified
+ alternations such as ``(a|a)*``.
+
+ Implemented as a single left-to-right scan rather than a regular
+ expression: matching this shape with a regex needs nested character
+ classes whose runtime grows quadratically with the input, which would
+ make the ReDoS guard a ReDoS vector itself. The scan below is O(n) and
+ allocates nothing.
+
+ It errs towards refusing: some nested shapes it rejects would in fact
+ run fine. That trade is deliberate -- this path is only reached when no
+ execution timeout is available, where a false refusal costs a search
+ and a false pass can cost the server. It also tracks escaping and
+ character classes, so ``\(x+\)+`` and ``[a*+]+`` are correctly
+ allowed where a regex-based check rejected them.
+
+ Args:
+ pattern: The raw, user-supplied regular expression source.
+
+ Returns:
+ True if the pattern should be refused.
+ """
+ # Track, per open group, whether it contains a quantifier or an
+ # alternation. When the group closes and is itself quantified, that is
+ # the nested-quantifier shape we refuse.
+ risky_stack: list[bool] = []
+ escaped = False
+ in_class = False
+ index = 0
+ length = len(pattern)
+
+ while index < length:
+ char = pattern[index]
+
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif in_class:
+ # Inside [...] the quantifier characters are literals.
+ if char == "]":
+ in_class = False
+ elif char == "[":
+ in_class = True
+ elif char == "(":
+ risky_stack.append(False)
+ elif char == ")":
+ risky = risky_stack.pop() if risky_stack else False
+ # Skip whitespace between the group and its quantifier.
+ probe = index + 1
+ while probe < length and pattern[probe].isspace():
+ probe += 1
+ quantified = probe < length and pattern[probe] in _QUANTIFIER_CHARS
+ if risky and quantified:
+ return True
+ # A quantified group is itself a risk marker for any group
+ # enclosing it.
+ if quantified and risky_stack:
+ risky_stack[-1] = True
+ elif char in _QUANTIFIER_CHARS or char == "|":
+ if risky_stack:
+ risky_stack[-1] = True
+
+ index += 1
+
+ return False
+
+
+def compile_search_pattern(
+ query: str,
+ *,
+ use_regex: bool,
+ case_sensitive: bool,
+) -> Any:
+ """Compile a user-supplied search query into a safe pattern object.
+
+ Literal searches are escaped, so they are always safe. Regex searches
+ are compiled with the ``regex`` module when available, which allows a
+ per-call execution timeout; otherwise they are screened with
+ :func:`_looks_catastrophic` and refused if they look dangerous.
+
+ Args:
+ query: Raw search text or regular expression from the client.
+ use_regex: True to treat ``query`` as a regular expression.
+ case_sensitive: True for a case-sensitive match.
+
+ Returns:
+ A compiled pattern object (``regex.Pattern`` or ``re.Pattern``).
+
+ Raises:
+ UnsafePatternError: The pattern is refused as likely-catastrophic.
+ re.error: The pattern is not valid regular expression syntax.
+ """
+ engine = _regex_module if HAS_REGEX_TIMEOUT else re
+ flags = 0 if case_sensitive else engine.IGNORECASE
+
+ if not use_regex:
+ # A literal search can never backtrack pathologically once escaped.
+ return engine.compile(engine.escape(query), flags)
+
+ if not HAS_REGEX_TIMEOUT and _looks_catastrophic(query):
+ raise UnsafePatternError(
+ "Pattern rejected: nested quantifiers can cause excessive "
+ "backtracking. Install the 'regex' package to allow it, or "
+ "simplify the expression."
+ )
+
+ return engine.compile(query, flags)
+
+
+def search_with_timeout(pattern: Any, text: str) -> bool:
+ """Run ``pattern`` against ``text`` under a wall-clock budget.
+
+ Args:
+ pattern: A compiled pattern from :func:`compile_search_pattern`.
+ text: The subject string (a single log line or message).
+
+ Returns:
+ True if the pattern matches.
+
+ Raises:
+ PatternTimeoutError: Matching exceeded
+ :data:`REGEX_TIMEOUT_SECONDS`. Only possible when the ``regex``
+ module is installed; the stdlib fallback cannot interrupt a
+ running match.
+ """
+ if not HAS_REGEX_TIMEOUT:
+ return bool(pattern.search(text))
+
+ try:
+ return bool(pattern.search(text, timeout=REGEX_TIMEOUT_SECONDS))
+ except TimeoutError as exc:
+ # regex>=2022 raises the builtin TimeoutError on expiry.
+ raise PatternTimeoutError(
+ "Search pattern exceeded its time budget"
+ ) from exc
diff --git a/octoprint_logmonitor/static/js/logmonitor.js b/octoprint_logmonitor/static/js/logmonitor.js
index 87b8051..496abec 100644
--- a/octoprint_logmonitor/static/js/logmonitor.js
+++ b/octoprint_logmonitor/static/js/logmonitor.js
@@ -138,6 +138,9 @@ $(() => {
self.isStreaming = ko.observable(false);
self.isSwitchingStream = ko.observable(false);
self.selectedLogFile = ko.observable("");
+ //: True while a log download request is in flight; disables the
+ //: download button so a slow file cannot be requested repeatedly.
+ self.downloadInProgress = ko.observable(false);
self.activeStreamFile = ko.observable("");
self.availableLogFiles = ko.observableArray([]);
self.allLines = ko.observableArray([]);
@@ -962,10 +965,71 @@ $(() => {
};
// Download log file
+ //
+ // Fetched as a blob rather than navigated to. window.location.assign()
+ // used to be used here, but a non-file response (a JSON error body, or
+ // a 500 raised while the file is being streamed) would then be treated
+ // as a navigation: the browser left the page and OctoPrint reloaded
+ // onto its first tab, losing the user's place with no error shown.
self.downloadLogFile = function (filename) {
+ if (!filename) {
+ return;
+ }
+
var url =
pluginBaseUrl + "/download/" + encodeURIComponent(filename);
- window.location.assign(url);
+
+ self.downloadInProgress(true);
+
+ pluginAjax({
+ url: url,
+ method: "GET",
+ xhrFields: { responseType: "blob" },
+ })
+ .done((blob) => {
+ var objectUrl = window.URL.createObjectURL(blob);
+ var link = document.createElement("a");
+ link.href = objectUrl;
+ link.download = filename;
+ link.rel = "noopener";
+ link.click();
+ window.URL.revokeObjectURL(objectUrl);
+ })
+ .fail((xhr) => {
+ // The endpoint reports failures as JSON, but with
+ // responseType "blob" the body arrives as a Blob and
+ // reading xhr.responseText throws. Parse the Blob
+ // instead, and notify once the text is available.
+ var notify = function (detail) {
+ var base = gettext("Failed to download log file");
+ new PNotify({
+ title: "Log Monitor",
+ text: detail ? base + ": " + detail : base,
+ type: "error",
+ hide: false,
+ });
+ };
+
+ var body = xhr && xhr.response;
+ if (body instanceof Blob) {
+ body.text()
+ .then((text) => {
+ var detail = "";
+ try {
+ detail = JSON.parse(text).error || "";
+ } catch (e) {
+ detail = "";
+ }
+ notify(detail);
+ })
+ .catch(() => notify(""));
+ } else {
+ notify("");
+ }
+ })
+ .always(() => {
+ self.downloadInProgress(false);
+ });
};
// Load alert history
diff --git a/octoprint_logmonitor/templates/logmonitor_tab.jinja2 b/octoprint_logmonitor/templates/logmonitor_tab.jinja2
index a9d7373..74477fc 100644
--- a/octoprint_logmonitor/templates/logmonitor_tab.jinja2
+++ b/octoprint_logmonitor/templates/logmonitor_tab.jinja2
@@ -29,7 +29,7 @@
{{ _("Start Streaming") }}
diff --git a/octoprint_logmonitor/translations/de/LC_MESSAGES/messages.mo b/octoprint_logmonitor/translations/de/LC_MESSAGES/messages.mo
index dacabb9..ea6a0d1 100644
Binary files a/octoprint_logmonitor/translations/de/LC_MESSAGES/messages.mo and b/octoprint_logmonitor/translations/de/LC_MESSAGES/messages.mo differ
diff --git a/pyproject.toml b/pyproject.toml
index b2b8993..e2300e2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "OctoPrint-LogMonitor"
-version = "0.2.4"
+version = "0.2.5"
description = "Live log streaming and searching for OctoPrint with severity alerting"
license = "AGPL-3.0-or-later"
authors = [
@@ -15,7 +15,16 @@ readme = {file = "README.md", content-type = "text/markdown"}
requires-python = ">=3.9, <4"
# any additional requirements (besides OctoPrint) should be listed here
-dependencies = []
+#
+# `regex` is a drop-in replacement for the stdlib `re` that supports a
+# per-call execution timeout. Without it, a user-supplied search pattern can
+# trigger catastrophic backtracking and pin a CPU core (ReDoS). The plugin
+# degrades safely when it is absent -- patterns with nested quantifiers are
+# then refused outright -- but installing it keeps the regex search feature
+# fully usable.
+dependencies = [
+ "regex>=2022.1.18",
+]
[tool.setuptools]
include-package-data = true
@@ -37,7 +46,8 @@ develop = [
"build",
"pytest",
"pytest-cov",
- "go-task-bin"
+ "go-task-bin",
+ "flask"
]
[tool.black]
diff --git a/tests/test_i18n_extraction.py b/tests/test_i18n_extraction.py
new file mode 100644
index 0000000..efb5410
--- /dev/null
+++ b/tests/test_i18n_extraction.py
@@ -0,0 +1,95 @@
+"""
+Tests for translation-catalog extraction.
+
+Guards the Babel configuration itself rather than the plugin code: a
+misconfigured extractor fails silently, dropping strings from the catalog
+with no error anywhere in the build.
+"""
+
+import io
+import unittest
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+JS_FILE = (
+ REPO_ROOT / "octoprint_logmonitor" / "static" / "js" / "logmonitor.js"
+)
+BABEL_CFG = REPO_ROOT / "babel.cfg"
+
+KEYWORDS = {"gettext": None, "ngettext": (1, 2)}
+
+
+def _babel():
+ """Import Babel's extractor, skipping the test if unavailable."""
+ try:
+ from babel.messages.extract import extract_javascript
+ except ImportError: # pragma: no cover - babel is a dev dependency
+ raise unittest.SkipTest("Babel not installed")
+ return extract_javascript
+
+
+class TestJavaScriptExtraction(unittest.TestCase):
+ """Regression tests for the JSX-lexer bug in Babel.
+
+ Babel's JS lexer treats the regex literal ``/>/g`` -- used by
+ ``escapeHtml()`` -- as a JSX tag close when JSX support is on. From that
+ token onward the file is tokenised incorrectly and every later
+ ``gettext()`` call is dropped from the catalog without warning. Disabling
+ JSX in babel.cfg restores correct tokenisation.
+ """
+
+ def test_babel_cfg_disables_jsx(self):
+ """babel.cfg must switch JSX parsing off for the JS extractor."""
+ text = BABEL_CFG.read_text(encoding="utf-8")
+ self.assertRegex(
+ text,
+ r"(?m)^jsx\s*=\s*$",
+ "babel.cfg must contain an empty 'jsx =' line. Babel reads "
+ "config values as strings and only tests truthiness, so "
+ "'false' or '0' would still leave JSX enabled.",
+ )
+
+ def test_strings_after_escape_html_are_extracted(self):
+ """A gettext() call late in the file must reach the catalog.
+
+ The marker is appended past escapeHtml(), which is where the
+ tokeniser used to give up.
+ """
+ extract_javascript = _babel()
+ marker = "PROBE_MARKER_DO_NOT_TRANSLATE"
+ source = JS_FILE.read_bytes() + (
+ f'\nvar __probe = gettext("{marker}");\n'.encode()
+ )
+
+ rows = list(
+ extract_javascript(io.BytesIO(source), KEYWORDS, [], {"jsx": ""})
+ )
+ found = [r for r in rows if r[2] == marker]
+ self.assertTrue(
+ found,
+ "A gettext() call at the end of logmonitor.js was not "
+ "extracted; Babel's JSX lexer has broken tokenisation again.",
+ )
+
+ def test_jsx_enabled_still_reproduces_the_bug(self):
+ """Documents the failure mode the configuration protects against.
+
+ If this ever stops failing, Babel has fixed the lexer upstream and
+ the jsx workaround in babel.cfg can be reconsidered.
+ """
+ extract_javascript = _babel()
+ marker = "PROBE_MARKER_DO_NOT_TRANSLATE"
+ source = JS_FILE.read_bytes() + (
+ f'\nvar __probe = gettext("{marker}");\n'.encode()
+ )
+
+ rows = list(extract_javascript(io.BytesIO(source), KEYWORDS, [], {}))
+ self.assertFalse(
+ [r for r in rows if r[2] == marker],
+ "Babel now extracts this with JSX enabled -- the lexer bug "
+ "appears fixed upstream; revisit the 'jsx =' line in babel.cfg.",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_integration_api.py b/tests/test_integration_api.py
index 90590b6..71d3dcf 100644
--- a/tests/test_integration_api.py
+++ b/tests/test_integration_api.py
@@ -10,6 +10,7 @@
"""
import contextlib
+import io
import os
import tempfile
import unittest
@@ -619,5 +620,147 @@ def test_manual_connection_status(self):
"""
+class TestDownloadContentLength(unittest.TestCase):
+ """Regression tests for the log-download Content-Length race.
+
+ ``send_file(path)`` stats the file to set Content-Length, but the body
+ is only read afterwards while the response is streamed. A log file that
+ is still being written to grows in between, so more bytes are sent than
+ advertised and Tornado aborts with::
+
+ tornado.httputil.HTTPOutputError:
+ Tried to write more data than Content-Length
+
+ That error is raised after the view returns, so the endpoint's own
+ try/except cannot catch it; it surfaces as "Exception in WSGI
+ application". Reading a snapshot up front pins both values together.
+ """
+
+ def setUp(self):
+ """Create a log file and a Flask app serving it both ways."""
+ self.temp_dir = tempfile.mkdtemp()
+ self.log_file = Path(self.temp_dir) / "growing.log"
+ self.log_file.write_bytes(b"x" * 10000)
+
+ flask = self._flask()
+ app = flask.Flask(__name__)
+ log_file = self.log_file
+
+ @app.route("/snapshot")
+ def snapshot(): # pragma: no cover - exercised via test client
+ with open(log_file, "rb") as handle:
+ payload = handle.read()
+ return flask.send_file(
+ io.BytesIO(payload),
+ as_attachment=True,
+ download_name="growing.log",
+ mimetype="text/plain",
+ )
+
+ self.app = app
+
+ def tearDown(self):
+ """Remove temporary files."""
+ with contextlib.suppress(OSError):
+ self.log_file.unlink()
+ with contextlib.suppress(OSError):
+ os.rmdir(self.temp_dir)
+
+ @staticmethod
+ def _flask():
+ """Import flask, skipping the test if it is unavailable."""
+ try:
+ import flask
+ except ImportError: # pragma: no cover
+ raise unittest.SkipTest("flask not installed")
+ return flask
+
+ def _serve(self, path, grow_by=0):
+ """Drive the WSGI app the way OctoPrint's Tornado bridge does.
+
+ Returns:
+ Tuple of (declared Content-Length, actual body length).
+ """
+ environ = {
+ "REQUEST_METHOD": "GET",
+ "PATH_INFO": path,
+ "SERVER_NAME": "localhost",
+ "SERVER_PORT": "80",
+ "wsgi.url_scheme": "http",
+ "wsgi.input": io.BytesIO(b""),
+ "wsgi.errors": io.BytesIO(),
+ }
+ captured = {}
+
+ def start_response(status, headers, exc_info=None):
+ captured["headers"] = headers
+ return []
+
+ response = self.app(environ, start_response)
+ header_map = {k.lower(): v for k, v in captured["headers"]}
+ declared = int(header_map["content-length"])
+
+ # Grow the file after the headers are built but before the body is
+ # consumed -- exactly the window the bug lives in.
+ if grow_by:
+ with open(self.log_file, "ab") as handle:
+ handle.write(b"y" * grow_by)
+
+ body = b"".join(response)
+ if hasattr(response, "close"):
+ response.close()
+ return declared, len(body)
+
+ def test_content_length_matches_body_when_file_grows(self):
+ """A file growing mid-request must not desync Content-Length."""
+ declared, actual = self._serve("/snapshot", grow_by=5000)
+ self.assertEqual(
+ declared,
+ actual,
+ "Content-Length and body length diverged; Tornado would raise "
+ "HTTPOutputError",
+ )
+
+ def test_content_length_matches_body_when_file_is_static(self):
+ """The normal case keeps working."""
+ declared, actual = self._serve("/snapshot")
+ self.assertEqual(declared, actual)
+ self.assertEqual(actual, 10000)
+
+
+class TestDownloadSizeLimit(unittest.TestCase):
+ """The download endpoint buffers in memory, so it needs a size bound."""
+
+ def setUp(self):
+ """Create a temporary directory for size-check fixtures."""
+ self.temp_dir = tempfile.mkdtemp()
+
+ def tearDown(self):
+ """Remove temporary files."""
+ with contextlib.suppress(OSError):
+ for name in os.listdir(self.temp_dir):
+ os.unlink(os.path.join(self.temp_dir, name))
+ os.rmdir(self.temp_dir)
+
+ def test_limit_is_memory_safe(self):
+ """The bound must suit a Pi, not the 1 GiB disk-side file cap."""
+ from octoprint_logmonitor.security import (
+ MAX_DOWNLOAD_BYTES,
+ MAX_FILE_SIZE_BYTES,
+ )
+
+ self.assertLess(MAX_DOWNLOAD_BYTES, MAX_FILE_SIZE_BYTES)
+ self.assertLessEqual(MAX_DOWNLOAD_BYTES, 128 * 1024 * 1024)
+
+ def test_check_file_size_honours_download_limit(self):
+ """Files above the limit are reported as too large."""
+ from octoprint_logmonitor.security import check_file_size
+
+ small = Path(self.temp_dir) / "small.log"
+ small.write_bytes(b"x" * 1024)
+ self.assertTrue(check_file_size(str(small), 4096))
+ self.assertFalse(check_file_size(str(small), 512))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_log_searcher.py b/tests/test_log_searcher.py
index 51be076..98dc566 100644
--- a/tests/test_log_searcher.py
+++ b/tests/test_log_searcher.py
@@ -4,10 +4,12 @@
import os
import tempfile
+import time
import unittest
from pathlib import Path
from octoprint_logmonitor.log_searcher import LogSearcher
+from octoprint_logmonitor.security import MAX_SCAN_LINES
class TestLogSearcher(unittest.TestCase):
@@ -375,3 +377,109 @@ def test_search_binary_file_uses_replace_error_handler(self):
if __name__ == "__main__":
unittest.main()
+
+
+class TestRegexDoSProtection(unittest.TestCase):
+ """Regression tests for the ReDoS fix (CodeQL py/regex-injection).
+
+ A user-supplied regex reaches ``re.search`` via the /search endpoint.
+ Patterns such as ``(x+)+$`` are only a handful of characters long, so
+ MAX_QUERY_LENGTH cannot stop them, and the stdlib ``re`` has no way to
+ bound matching time.
+ """
+
+ #: Patterns that hang a backtracking engine on a non-matching subject.
+ EVIL_PATTERNS = (r"(x+)+$", r"(x|x)*$", r"(a*)*$")
+
+ def setUp(self):
+ """Create a log file whose lines trigger worst-case backtracking."""
+ self.temp_dir = tempfile.mkdtemp()
+ self.log_file = Path(self.temp_dir) / "redos.log"
+ payload = "x" * 40 + "!"
+ self.log_file.write_text(
+ f"2024-01-01 10:00:00,000 - octoprint - ERROR - {payload}\n" * 5
+ )
+ self.searcher = LogSearcher()
+
+ def tearDown(self):
+ """Remove the temporary log file."""
+ if self.log_file.exists():
+ self.log_file.unlink()
+ try:
+ os.rmdir(self.temp_dir)
+ except OSError:
+ pass
+
+ def test_evil_patterns_complete_quickly(self):
+ """A catastrophic pattern must not hang the search."""
+ for pattern in self.EVIL_PATTERNS:
+ with self.subTest(pattern=pattern):
+ start = time.monotonic()
+ result = self.searcher.search(
+ str(self.log_file), query=pattern, use_regex=True
+ )
+ elapsed = time.monotonic() - start
+
+ # Generous bound: the point is "returns", not "is fast".
+ self.assertLess(
+ elapsed,
+ 15.0,
+ f"{pattern!r} took {elapsed:.1f}s - ReDoS not mitigated",
+ )
+ # It must fail loudly, not silently return bogus matches.
+ self.assertIsInstance(result, dict)
+
+ def test_benign_regex_still_works(self):
+ """The fix must not break legitimate regex search."""
+ result = self.searcher.search(
+ str(self.log_file), query=r"ERROR - x+!", use_regex=True
+ )
+ self.assertNotIn("error", result)
+ self.assertEqual(result["total"], 5)
+
+ def test_literal_search_unaffected(self):
+ """Literal search of regex metacharacters stays safe and exact."""
+ result = self.searcher.search(
+ str(self.log_file), query="(x+)+$", use_regex=False
+ )
+ self.assertNotIn("error", result)
+ self.assertEqual(result["total"], 0)
+
+ def test_invalid_pattern_returns_error_not_exception(self):
+ """Bad syntax yields an error dict regardless of regex engine.
+
+ ``regex.error`` does not subclass ``re.error``, so catching only
+ ``re.error`` would let this escape as a 500.
+ """
+ result = self.searcher.search(
+ str(self.log_file), query=r"(unclosed", use_regex=True
+ )
+ self.assertIn("error", result)
+ self.assertEqual(result["results"], [])
+
+ def test_scan_stops_at_line_budget(self):
+ """Scanning is bounded when a query matches nothing.
+
+ The existing early-exit only fires once a result page is full, so
+ it does not bound a query with few or no matches -- that case has
+ to read every line. MAX_SCAN_LINES is what caps it.
+ """
+ big = Path(self.temp_dir) / "big.log"
+ line = "2024-01-01 10:00:00,000 - octoprint - ERROR - hit\n"
+ big.write_text(line * (MAX_SCAN_LINES + 100))
+ try:
+ result = self.searcher.search(
+ str(big), query="nomatch-zzz", use_regex=False, limit=5
+ )
+ self.assertTrue(result.get("truncated"))
+ self.assertEqual(result.get("scan_limit"), MAX_SCAN_LINES)
+ self.assertEqual(result["total"], 0)
+ finally:
+ big.unlink()
+
+ def test_no_truncation_flag_for_small_files(self):
+ """Normal-sized searches must not advertise truncation."""
+ result = self.searcher.search(
+ str(self.log_file), query="ERROR", use_regex=False
+ )
+ self.assertNotIn("truncated", result)
diff --git a/tests/test_security.py b/tests/test_security.py
index a006eac..baf3f75 100644
--- a/tests/test_security.py
+++ b/tests/test_security.py
@@ -21,6 +21,7 @@
MAX_SEARCH_LIMIT,
VALID_SEVERITY_LEVELS,
RateLimiter,
+ _looks_catastrophic,
check_file_size,
is_safe_path,
mask_sensitive_data,
@@ -437,5 +438,78 @@ def test_high_quota(self):
self.assertFalse(limiter.is_allowed("client"))
+class TestCatastrophicPatternHeuristic(unittest.TestCase):
+ """Tests for the no-regex fallback that screens dangerous patterns.
+
+ This guard runs only when the ``regex`` module (and therefore a real
+ execution timeout) is unavailable. It used to be a regular expression
+ itself, which CodeQL flagged as py/polynomial-redos: matching the
+ nested-quantifier shape needed character classes whose runtime grew
+ quadratically, so the ReDoS guard was a ReDoS vector. It is now a
+ single linear scan.
+ """
+
+ def test_rejects_nested_quantifiers(self):
+ """Classic catastrophic shapes must be refused."""
+ for pattern in (
+ r"(x+)+$",
+ r"(a*)*$",
+ r"(a|a)*",
+ r"(ab|cd){2,}",
+ r"(\d+)+",
+ ):
+ with self.subTest(pattern=pattern):
+ self.assertTrue(_looks_catastrophic(pattern))
+
+ def test_accepts_ordinary_patterns(self):
+ """Legitimate searches must not be refused."""
+ for pattern in (
+ r"ERROR.*timeout",
+ r"^\d+ fail",
+ r"(abc)",
+ r"(abc)+",
+ r"foo|bar",
+ ):
+ with self.subTest(pattern=pattern):
+ self.assertFalse(_looks_catastrophic(pattern))
+
+ def test_quantifiers_inside_character_class_are_literal(self):
+ """``[a*+]+`` quantifies a class, not a group -- it is safe."""
+ self.assertFalse(_looks_catastrophic(r"[a*+]+"))
+
+ def test_escaped_parentheses_are_not_groups(self):
+ r"""``\(x+\)+`` matches literal brackets and cannot nest.
+
+ The previous regex-based heuristic rejected this; the scan tracks
+ escaping and allows it.
+ """
+ self.assertFalse(_looks_catastrophic(r"\(x+\)+"))
+
+ def test_runs_in_linear_time(self):
+ """The guard must not blow up on its own worst-case input.
+
+ CodeQL's reported attack string is "(" followed by many "*". The
+ old regex took ~6.7s at 50k characters; a linear scan stays in the
+ low milliseconds. The bound is loose so the test is not flaky on
+ slow CI runners -- it is checking the growth curve, not a budget.
+ """
+ payload = "(" + "*" * 50000
+ start = time.monotonic()
+ _looks_catastrophic(payload)
+ elapsed = time.monotonic() - start
+ self.assertLess(
+ elapsed,
+ 1.0,
+ f"heuristic took {elapsed:.2f}s on a 50k input; it should be "
+ "linear",
+ )
+
+ def test_unbalanced_parentheses_do_not_crash(self):
+ """Malformed input must return a verdict, not raise."""
+ for pattern in ("(((", ")))", "(a+", "a+)", "", "("):
+ with self.subTest(pattern=pattern):
+ self.assertIsInstance(_looks_catastrophic(pattern), bool)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/translations/de/LC_MESSAGES/messages.mo b/translations/de/LC_MESSAGES/messages.mo
index b2feea9..ea6a0d1 100644
Binary files a/translations/de/LC_MESSAGES/messages.mo and b/translations/de/LC_MESSAGES/messages.mo differ
diff --git a/translations/de/LC_MESSAGES/messages.po b/translations/de/LC_MESSAGES/messages.po
index 9571ced..cfb40b8 100644
--- a/translations/de/LC_MESSAGES/messages.po
+++ b/translations/de/LC_MESSAGES/messages.po
@@ -7,29 +7,29 @@ msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: i18n@octoprint.org\n"
-"POT-Creation-Date: 2026-07-05 22:43+0200\n"
+"POT-Creation-Date: 2026-10-18 17:34+0200\n"
"PO-Revision-Date: 2026-05-04 21:46+0200\n"
"Last-Translator: FULL NAME \n"
-"Language: de\n"
"Language-Team: de \n"
-"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"Language: de\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
-"Generated-By: Babel 2.16.0\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+"Generated-By: Babel 2.18.0\n"
-#: octoprint_logmonitor/static/js/logmonitor.js:332
+#: octoprint_logmonitor/static/js/logmonitor.js:335
msgid " (switching...)"
msgstr " (wird gewechselt...)"
-#: octoprint_logmonitor/static/js/logmonitor.js:359
+#: octoprint_logmonitor/static/js/logmonitor.js:362
#, python-format
msgid "%(count)s alert"
msgid_plural "%(count)s alerts"
msgstr[0] "%(count)s Alarm"
msgstr[1] "%(count)s Alarme"
-#: octoprint_logmonitor/static/js/logmonitor.js:289
+#: octoprint_logmonitor/static/js/logmonitor.js:292
#, python-format
msgid "%(count)s history entry"
msgid_plural "%(count)s history entries"
@@ -65,7 +65,8 @@ msgid "Auto-start streaming on page load"
msgstr "Streaming beim Laden der Seite automatisch starten"
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:42
-msgid "Automatically start streaming the default log file when OctoPrint loads."
+msgid ""
+"Automatically start streaming the default log file when OctoPrint loads."
msgstr ""
"Startet beim Laden von OctoPrint automatisch das Streaming der Standard-"
"Logdatei."
@@ -96,8 +97,8 @@ msgstr "Verlauf loeschen"
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:170
msgid ""
-"Controls which log files are monitored for severity trigger alerts in the"
-" background."
+"Controls which log files are monitored for severity trigger alerts in the "
+"background."
msgstr ""
"Legt fest, welche Logdateien im Hintergrund auf Schweregrad-Trigger fuer "
"Alarme ueberwacht werden."
@@ -150,6 +151,10 @@ msgstr "CSV exportieren"
msgid "Export TXT"
msgstr "TXT exportieren"
+#: octoprint_logmonitor/static/js/logmonitor.js:1004
+msgid "Failed to download log file"
+msgstr "Download der Logdatei fehlgeschlagen"
+
#: octoprint_logmonitor/templates/logmonitor_tab.jinja2:71
msgid "Filter logs..."
msgstr "Protokolle filtern..."
@@ -226,7 +231,7 @@ msgstr "Weiter"
msgid "No alert history entries yet."
msgstr "Noch keine Alarmverlaufseintraege vorhanden."
-#: octoprint_logmonitor/static/js/logmonitor.js:365
+#: octoprint_logmonitor/static/js/logmonitor.js:368
msgid "No alerts"
msgstr "Keine Alarme"
@@ -234,7 +239,7 @@ msgstr "Keine Alarme"
msgid "No results found."
msgstr "Keine Ergebnisse gefunden."
-#: octoprint_logmonitor/static/js/logmonitor.js:336
+#: octoprint_logmonitor/static/js/logmonitor.js:339
msgid "Not streaming"
msgstr "Kein Streaming aktiv"
@@ -267,7 +272,8 @@ msgid "Privacy"
msgstr "Datenschutz"
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:240
-msgid "Redact API keys, passwords and e-mail addresses from streamed log lines."
+msgid ""
+"Redact API keys, passwords and e-mail addresses from streamed log lines."
msgstr ""
"Entfernt API-Schluessel, Passwoerter und E-Mail-Adressen aus gestreamten "
"Logzeilen."
@@ -284,7 +290,7 @@ msgstr "Status aktualisieren"
msgid "Results per page"
msgstr "Ergebnisse pro Seite"
-#: octoprint_logmonitor/static/js/logmonitor.js:757
+#: octoprint_logmonitor/static/js/logmonitor.js:760
msgid "Search"
msgstr "Suchen"
@@ -304,11 +310,11 @@ msgstr "Suchbegriff..."
msgid "Searching logs..."
msgstr "Protokolle werden durchsucht..."
-#: octoprint_logmonitor/static/js/logmonitor.js:756
+#: octoprint_logmonitor/static/js/logmonitor.js:759
msgid "Searching..."
msgstr "Wird durchsucht..."
-#: octoprint_logmonitor/static/js/logmonitor.js:417
+#: octoprint_logmonitor/static/js/logmonitor.js:420
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:30
#: octoprint_logmonitor/templates/logmonitor_tab.jinja2:25
#: octoprint_logmonitor/templates/logmonitor_tab.jinja2:94
@@ -321,8 +327,8 @@ msgstr "Waehle, welche Schweregrade Navbar-/Sidebar-Alarme ausloesen sollen."
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:76
msgid ""
-"Sets the initial auto-scroll state when the page loads. Can be toggled at"
-" any time directly in the stream view."
+"Sets the initial auto-scroll state when the page loads. Can be toggled at "
+"any time directly in the stream view."
msgstr ""
"Setzt den anfaenglichen Auto-Scroll-Zustand beim Laden der Seite. Kann "
"jederzeit direkt in der Stream-Ansicht umgeschaltet werden."
@@ -356,8 +362,8 @@ msgid ""
"Show an OctoPrint-style toast notification in the web UI when a severity "
"alert fires."
msgstr ""
-"Zeigt bei einem Schweregrad-Alarm eine Toast-Benachrichtigung im "
-"OctoPrint-Stil in der Weboberflaeche an."
+"Zeigt bei einem Schweregrad-Alarm eine Toast-Benachrichtigung im OctoPrint-"
+"Stil in der Weboberflaeche an."
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:8
msgid "Show indicator in Navbar"
@@ -368,8 +374,10 @@ msgid "Show widget in Sidebar"
msgstr "Widget in der Sidebar anzeigen"
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:196
-msgid "Shows which logs are currently monitored by the background alert worker."
-msgstr "Zeigt, welche Logs aktuell vom Hintergrund-Alarmdienst ueberwacht werden."
+msgid ""
+"Shows which logs are currently monitored by the background alert worker."
+msgstr ""
+"Zeigt, welche Logs aktuell vom Hintergrund-Alarmdienst ueberwacht werden."
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:123
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:131
@@ -392,17 +400,17 @@ msgstr "Ausgeloeste Alarme in einer Verlaufsliste speichern."
msgid "Streaming Settings"
msgstr "Streaming-Einstellungen"
-#: octoprint_logmonitor/static/js/logmonitor.js:330
+#: octoprint_logmonitor/static/js/logmonitor.js:333
msgid "Streaming: "
msgstr "Streaming: "
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:182
msgid ""
-"These logs are monitored for severity triggers even when no live stream "
-"is open."
+"These logs are monitored for severity triggers even when no live stream is "
+"open."
msgstr ""
-"Diese Logs werden auch dann auf Schweregrad-Trigger ueberwacht, wenn kein"
-" Live-Stream geoeffnet ist."
+"Diese Logs werden auch dann auf Schweregrad-Trigger ueberwacht, wenn kein "
+"Live-Stream geoeffnet ist."
#: octoprint_logmonitor/templates/logmonitor_tab.jinja2:158
msgid "Timestamp"
@@ -415,8 +423,8 @@ msgstr "Alarme ausloesen fuer"
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:110
msgid "Turns all severity alert monitoring and notifications on or off."
msgstr ""
-"Schaltet die gesamte Schweregrad-Alarmueberwachung und Benachrichtigungen"
-" ein oder aus."
+"Schaltet die gesamte Schweregrad-Alarmueberwachung und Benachrichtigungen "
+"ein oder aus."
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:190
msgid "Unknown"
@@ -424,14 +432,16 @@ msgstr "Unbekannt"
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:124
msgid "Very high alert volume when OctoPrint debug mode is enabled."
-msgstr "Sehr hohes Alarmaufkommen, wenn der OctoPrint-Debug-Modus aktiviert ist."
+msgstr ""
+"Sehr hohes Alarmaufkommen, wenn der OctoPrint-Debug-Modus aktiviert ist."
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:256
msgid "Write Debug Test Entries"
msgstr "Debug-Testeintraege schreiben"
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:251
-msgid "Writes Log Monitor frontend debug events into the OctoPrint server log."
+msgid ""
+"Writes Log Monitor frontend debug events into the OctoPrint server log."
msgstr ""
"Schreibt Frontend-Debug-Ereignisse des Log-Monitors in das OctoPrint-"
"Serverlog."
@@ -441,10 +451,9 @@ msgid ""
"Writes one test log entry for DEBUG, INFO, WARNING, ERROR, CRITICAL and "
"UNKNOWN categories."
msgstr ""
-"Schreibt je einen Test-Logeintrag fuer die Kategorien DEBUG, INFO, "
-"WARNING, ERROR, CRITICAL und UNKNOWN."
+"Schreibt je einen Test-Logeintrag fuer die Kategorien DEBUG, INFO, WARNING, "
+"ERROR, CRITICAL und UNKNOWN."
#: octoprint_logmonitor/templates/logmonitor_tab.jinja2:137
msgid "results"
msgstr "Ergebnisse"
-
diff --git a/translations/messages.pot b/translations/messages.pot
index abbe578..2c92f83 100644
--- a/translations/messages.pot
+++ b/translations/messages.pot
@@ -8,27 +8,27 @@ msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
-"POT-Creation-Date: 2026-07-05 22:43+0200\n"
+"POT-Creation-Date: 2026-10-18 17:34+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME \n"
"Language-Team: LANGUAGE \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
-"Generated-By: Babel 2.16.0\n"
+"Generated-By: Babel 2.18.0\n"
-#: octoprint_logmonitor/static/js/logmonitor.js:332
+#: octoprint_logmonitor/static/js/logmonitor.js:335
msgid " (switching...)"
msgstr ""
-#: octoprint_logmonitor/static/js/logmonitor.js:359
+#: octoprint_logmonitor/static/js/logmonitor.js:362
#, python-format
msgid "%(count)s alert"
msgid_plural "%(count)s alerts"
msgstr[0] ""
msgstr[1] ""
-#: octoprint_logmonitor/static/js/logmonitor.js:289
+#: octoprint_logmonitor/static/js/logmonitor.js:292
#, python-format
msgid "%(count)s history entry"
msgid_plural "%(count)s history entries"
@@ -143,6 +143,10 @@ msgstr ""
msgid "Export TXT"
msgstr ""
+#: octoprint_logmonitor/static/js/logmonitor.js:1004
+msgid "Failed to download log file"
+msgstr ""
+
#: octoprint_logmonitor/templates/logmonitor_tab.jinja2:71
msgid "Filter logs..."
msgstr ""
@@ -219,7 +223,7 @@ msgstr ""
msgid "No alert history entries yet."
msgstr ""
-#: octoprint_logmonitor/static/js/logmonitor.js:365
+#: octoprint_logmonitor/static/js/logmonitor.js:368
msgid "No alerts"
msgstr ""
@@ -227,7 +231,7 @@ msgstr ""
msgid "No results found."
msgstr ""
-#: octoprint_logmonitor/static/js/logmonitor.js:336
+#: octoprint_logmonitor/static/js/logmonitor.js:339
msgid "Not streaming"
msgstr ""
@@ -275,7 +279,7 @@ msgstr ""
msgid "Results per page"
msgstr ""
-#: octoprint_logmonitor/static/js/logmonitor.js:757
+#: octoprint_logmonitor/static/js/logmonitor.js:760
msgid "Search"
msgstr ""
@@ -295,11 +299,11 @@ msgstr ""
msgid "Searching logs..."
msgstr ""
-#: octoprint_logmonitor/static/js/logmonitor.js:756
+#: octoprint_logmonitor/static/js/logmonitor.js:759
msgid "Searching..."
msgstr ""
-#: octoprint_logmonitor/static/js/logmonitor.js:417
+#: octoprint_logmonitor/static/js/logmonitor.js:420
#: octoprint_logmonitor/templates/logmonitor_settings.jinja2:30
#: octoprint_logmonitor/templates/logmonitor_tab.jinja2:25
#: octoprint_logmonitor/templates/logmonitor_tab.jinja2:94
@@ -379,7 +383,7 @@ msgstr ""
msgid "Streaming Settings"
msgstr ""
-#: octoprint_logmonitor/static/js/logmonitor.js:330
+#: octoprint_logmonitor/static/js/logmonitor.js:333
msgid "Streaming: "
msgstr ""