From 5ef1a56cf8b020bacc9aa930bba4840ce06f306e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 16 Jul 2026 09:33:58 +0000 Subject: [PATCH 01/13] build(deps): bump actions/setup-node from 6 to 7 Bumps [actions/setup-node](https://github.com/actions/setup-node) from 6 to 7. - [Release notes](https://github.com/actions/setup-node/releases) - [Commits](https://github.com/actions/setup-node/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/setup-node dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/ci.yml | 2 +- .github/workflows/lint.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dfd8e46..fb69110 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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" diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index c5dbf22..0e455e0 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -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" From b56740308ca6c0c7b943fde3984fbc1a6d594820 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 23 Jul 2026 09:34:03 +0000 Subject: [PATCH 02/13] build(deps): bump actions/setup-python from 6 to 7 Bumps [actions/setup-python](https://github.com/actions/setup-python) from 6 to 7. - [Release notes](https://github.com/actions/setup-python/releases) - [Commits](https://github.com/actions/setup-python/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/setup-python dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/bandit-sarif.yml | 2 +- .github/workflows/ci.yml | 4 ++-- .github/workflows/docs.yml | 2 +- .github/workflows/i18n.yml | 2 +- .github/workflows/lint.yml | 2 +- .github/workflows/release.yml | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) 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..0afde85 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 @@ -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..b9d09be 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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5acc737..6554129 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,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 From 8f28b8042bfa100d2073284c309a09a363ce2855 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Sep 2026 09:33:44 +0000 Subject: [PATCH 03/13] build(deps): bump softprops/action-gh-release from 3.0.1 to 3.0.3 Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 3.0.1 to 3.0.3. - [Release notes](https://github.com/softprops/action-gh-release/releases) - [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md) - [Commits](https://github.com/softprops/action-gh-release/compare/718ea10b132b3b2eba29c1007bb80653f286566b...efb35369e0ad2afab669f228072c1b0d510eae64) --- updated-dependencies: - dependency-name: softprops/action-gh-release dependency-version: 3.0.3 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5acc737..f5929b9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -146,7 +146,7 @@ jobs: echo "title=$title" >> "$GITHUB_OUTPUT" - name: Create GitHub Release - uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3 + uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 with: name: ${{ steps.release_title.outputs.title }} draft: false From 3dc4e16ea24793f9bb817cb56fa085482850ff73 Mon Sep 17 00:00:00 2001 From: Ajimaru <38381946+Ajimaru@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:13:07 +0200 Subject: [PATCH 04/13] feat: add flask to develop dependencies in pyproject.toml --- pyproject.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index b2b8993..ddcc809 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,7 +37,8 @@ develop = [ "build", "pytest", "pytest-cov", - "go-task-bin" + "go-task-bin", + "flask" ] [tool.black] From 5c7732a93c339c265b8c563fe05182125c586478 Mon Sep 17 00:00:00 2001 From: Ajimaru <38381946+Ajimaru@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:13:56 +0200 Subject: [PATCH 05/13] feat: update dependabot configuration for monthly updates and improved grouping --- .github/dependabot.yml | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) 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 From a80e193ddf84b660a367ff566ea3c6ee94c5c6da Mon Sep 17 00:00:00 2001 From: Ajimaru <38381946+Ajimaru@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:17:41 +0200 Subject: [PATCH 06/13] feat: add MAX_QUERY_LENGTH constant and enforce query length limit in LogSearcher --- octoprint_logmonitor/log_searcher.py | 15 +++++++++++++++ octoprint_logmonitor/security.py | 5 +++++ 2 files changed, 20 insertions(+) diff --git a/octoprint_logmonitor/log_searcher.py b/octoprint_logmonitor/log_searcher.py index 39f7371..e79bc12 100644 --- a/octoprint_logmonitor/log_searcher.py +++ b/octoprint_logmonitor/log_searcher.py @@ -13,6 +13,7 @@ from typing import Any, ClassVar, Optional from .log_parser import parse_line +from .security import MAX_QUERY_LENGTH class LogSearcher: @@ -105,6 +106,20 @@ 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: diff --git a/octoprint_logmonitor/security.py b/octoprint_logmonitor/security.py index 7dd15b8..f513000 100644 --- a/octoprint_logmonitor/security.py +++ b/octoprint_logmonitor/security.py @@ -25,6 +25,11 @@ #: 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. +#: Keeps ``re.compile`` input small enough that even a pathological pattern +#: cannot cause catastrophic backtracking to run for long. +MAX_QUERY_LENGTH: int = 200 + #: 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]] = [ From 1032cc5b794f546f20d7ef9fcac7b417f5602bb8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 Oct 2026 14:14:41 +0200 Subject: [PATCH 07/13] build(deps): bump codecov/codecov-action from 7.0.0 to 7.1.1 (#29) Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 7.0.0 to 7.1.1. - [Release notes](https://github.com/codecov/codecov-action/releases) - [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/codecov/codecov-action/compare/fb8b3582c8e4def4969c97caa2f19720cb33a72f...303a32d7a59b442fa8d48b6a1cc6825c09c847a5) --- updated-dependencies: - dependency-name: codecov/codecov-action dependency-version: 7.1.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c76feb..e74baef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 From 1b19526920db36d5e9670635d34d57ebff0b47a2 Mon Sep 17 00:00:00 2001 From: Hi My Name Is <38381946+Ajimaru@users.noreply.github.com> Date: Sun, 18 Oct 2026 12:01:55 +0200 Subject: [PATCH 08/13] Refactor release workflow and pull request template for clarity (#30) refactor: update release workflow and pull request template for clarity and organization Co-authored-by: Ajimaru --- .github/pull_request_template.md | 1 - .github/release.yml | 53 ++++++++----- .github/workflows/release.yml | 126 ++++++++++++++----------------- 3 files changed, 91 insertions(+), 89 deletions(-) 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/release.yml b/.github/workflows/release.yml index b7bd22d..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 @@ -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@efb35369e0ad2afab669f228072c1b0d510eae64 # 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 # From 9c6cd7ae77c3baea1e1aadf970e148188554aca6 Mon Sep 17 00:00:00 2001 From: Hi My Name Is <38381946+Ajimaru@users.noreply.github.com> Date: Sun, 18 Oct 2026 12:48:47 +0200 Subject: [PATCH 09/13] feat: enhance regex safety and performance with ReDoS mitigation (#31) # Description This pull request introduces robust protections against Regular Expression Denial of Service (ReDoS) in the log search feature, ensuring that user-supplied search patterns cannot hang or exhaust server resources. It does so by enforcing per-pattern execution timeouts (using the `regex` module), bounding the total number of lines scanned per request, and safely handling invalid or dangerous patterns. The changes also include comprehensive regression tests for these protections. The most important changes are: **ReDoS Mitigation and Search Safety** * Introduced the `regex` module as a dependency to enable per-call regex execution timeouts, preventing user-supplied patterns from causing catastrophic backtracking and CPU exhaustion. Fall-back heuristics are used if the module is unavailable. (`pyproject.toml`, `octoprint_logmonitor/security.py`) [[1]](diffhunk://#diff-50c86b7ed8ac2cf95bd48334961bf0530cdc77b5a56f852c5c61b89d735fd711L18-R27) [[2]](diffhunk://#diff-41a8e5a5fa5019f8f91d8233685c7a44fdb88c202fd58fd8f39dde68cfdafd64L12-R26) [[3]](diffhunk://#diff-41a8e5a5fa5019f8f91d8233685c7a44fdb88c202fd58fd8f39dde68cfdafd64L29-R60) [[4]](diffhunk://#diff-41a8e5a5fa5019f8f91d8233685c7a44fdb88c202fd58fd8f39dde68cfdafd64R338-R453) * Added a hard limit (`MAX_SCAN_LINES`) on the number of log lines scanned per search request to bound total resource usage, with the search response indicating when this limit is reached. (`octoprint_logmonitor/security.py`, `octoprint_logmonitor/log_searcher.py`) [[1]](diffhunk://#diff-41a8e5a5fa5019f8f91d8233685c7a44fdb88c202fd58fd8f39dde68cfdafd64L29-R60) [[2]](diffhunk://#diff-e906023f371a948050e1f66ec8a75239636761f1ed4fc4ddc5c5158d7524f8acR173-R187) [[3]](diffhunk://#diff-e906023f371a948050e1f66ec8a75239636761f1ed4fc4ddc5c5158d7524f8acL207-R261) **Pattern Compilation and Error Handling** * Centralized pattern compilation and execution in new utility functions (`compile_search_pattern`, `search_with_timeout`), which enforce timeouts, detect unsafe patterns, and handle syntax errors consistently. Errors are now reported to the client in a structured way, never causing server exceptions. (`octoprint_logmonitor/security.py`, `octoprint_logmonitor/log_searcher.py`) [[1]](diffhunk://#diff-41a8e5a5fa5019f8f91d8233685c7a44fdb88c202fd58fd8f39dde68cfdafd64R338-R453) [[2]](diffhunk://#diff-e906023f371a948050e1f66ec8a75239636761f1ed4fc4ddc5c5158d7524f8acL16-R24) [[3]](diffhunk://#diff-e906023f371a948050e1f66ec8a75239636761f1ed4fc4ddc5c5158d7524f8acL125-R148) [[4]](diffhunk://#diff-e906023f371a948050e1f66ec8a75239636761f1ed4fc4ddc5c5158d7524f8acL260-R313) **Testing** * Added a dedicated test suite (`TestRegexDoSProtection`) with regression tests to verify that dangerous patterns are safely rejected or timed out, legitimate searches still work, and line scan limits are enforced. (`tests/test_log_searcher.py`) These changes significantly harden the log search endpoint against resource exhaustion attacks while preserving correct and predictable behavior for legitimate queries. ## Related Issues ## Type of Change - [ ] Bugfix - [x] Feature - [ ] Docs - [ ] Refactor - [ ] Security ## Checklist - [x] Description of change - [ ] Related issue(s) - [x] Tests added / updated - [ ] Documentation updated Co-authored-by: Ajimaru --- octoprint_logmonitor/log_searcher.py | 83 ++++++++++++--- octoprint_logmonitor/security.py | 150 ++++++++++++++++++++++++++- pyproject.toml | 11 +- tests/test_log_searcher.py | 108 +++++++++++++++++++ 4 files changed, 331 insertions(+), 21 deletions(-) diff --git a/octoprint_logmonitor/log_searcher.py b/octoprint_logmonitor/log_searcher.py index e79bc12..880d164 100644 --- a/octoprint_logmonitor/log_searcher.py +++ b/octoprint_logmonitor/log_searcher.py @@ -13,7 +13,15 @@ from typing import Any, ClassVar, Optional from .log_parser import parse_line -from .security import MAX_QUERY_LENGTH +from .security import ( + MAX_QUERY_LENGTH, + MAX_SCAN_LINES, + PATTERN_SYNTAX_ERRORS, + PatternTimeoutError, + UnsafePatternError, + compile_search_pattern, + search_with_timeout, +) class LogSearcher: @@ -122,15 +130,22 @@ def search( } 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 { @@ -155,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 @@ -204,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}") @@ -257,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 f513000..c559764 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 @@ -26,10 +40,24 @@ MAX_HISTORY_LIMIT: int = 500 #: Hard upper bound for the length of a user-supplied search query/regex. -#: Keeps ``re.compile`` input small enough that even a pathological pattern -#: cannot cause catastrophic backtracking to run for long. +#: 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]] = [ @@ -307,3 +335,119 @@ def _cleanup_locked(self, now: float) -> None: self._clients[key] = remaining else: del self._clients[key] + + +# --------------------------------------------------------------------------- +# Regex execution safety (ReDoS mitigation) +# --------------------------------------------------------------------------- + +#: Heuristic markers for patterns prone to catastrophic backtracking: a +#: quantified group that itself contains a quantifier or an alternation, +#: e.g. ``(x+)+``, ``(a*)*``, ``(a|a)*``, ``(ab|cd){2,}``. Only used as a +#: fallback when the ``regex`` module is unavailable. +_NESTED_QUANTIFIER_RE = re.compile( + r"\([^()]*(?:[*+]|\{\d+(?:,\d*)?\}|\|)[^()]*\)\s*(?:[*+]|\{\d+(?:,\d*)?\})" +) + + +#: 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: + """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)*``. + + Args: + pattern: The raw, user-supplied regular expression source. + + Returns: + True if the pattern should be refused. + """ + return bool(_NESTED_QUANTIFIER_RE.search(pattern)) + + +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/pyproject.toml b/pyproject.toml index ddcc809..6855126 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 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) From 58156626529fd1fdf8cf661dd47b3ebe396d0d70 Mon Sep 17 00:00:00 2001 From: Hi My Name Is <38381946+Ajimaru@users.noreply.github.com> Date: Sun, 18 Oct 2026 17:28:29 +0200 Subject: [PATCH 10/13] feat: implement download size limit and improve error handling for log file downloads (#32) # Description This pull request addresses a critical bug with log file downloads, improves memory safety, and enhances the user experience when downloading logs. The main changes include ensuring the downloaded file size matches the advertised Content-Length to prevent server errors, enforcing a memory-safe download size limit, and improving the frontend download flow with better error handling and UI feedback. Additional updates include new regression tests and translation catalog updates. **Bug fixes and backend improvements:** * The log download endpoint now reads the entire file into memory before sending it, ensuring the `Content-Length` header matches the actual body size even if the log file grows during the request. This prevents Tornado server errors caused by mismatched content lengths. (`octoprint_logmonitor/__init__.py`) * Introduced a strict maximum download size (`MAX_DOWNLOAD_BYTES`, default 64 MiB) to prevent excessive memory use, especially important for devices with limited RAM. Files exceeding this limit are refused with a clear error message. (`octoprint_logmonitor/security.py`, `octoprint_logmonitor/__init__.py`) [[1]](diffhunk://#diff-41a8e5a5fa5019f8f91d8233685c7a44fdb88c202fd58fd8f39dde68cfdafd64R36-R42) [[2]](diffhunk://#diff-cde56103e85d941d453102d07311ee781e056a66958f75ef17ea16c28ad037c6R25) **Frontend and user experience:** * The download button is now disabled while a download is in progress to prevent repeated requests for large files. The download is performed via AJAX, with improved error handling and user notifications if the download fails. (`octoprint_logmonitor/static/js/logmonitor.js`, `octoprint_logmonitor/templates/logmonitor_tab.jinja2`) [[1]](diffhunk://#diff-a94d011c290f077261d7f9a1f2aaf45c80428a437bd72d48f53db463b9acbcc5R141-R143) [[2]](diffhunk://#diff-a94d011c290f077261d7f9a1f2aaf45c80428a437bd72d48f53db463b9acbcc5R968-R1037) [[3]](diffhunk://#diff-dc6958562dfd60a69726029c5c278b4c10dfcfbd05af6bf72d914938fed5a60eL32-R32) **Testing and regression coverage:** * Added regression tests to ensure that the file download endpoint correctly synchronizes `Content-Length` and the actual body size, and that the download size limit is enforced as intended. (`tests/test_integration_api.py`) **Translation and catalog maintenance:** * Updated translation catalogs and message extraction to reflect changes in the JavaScript code, including line number updates and Babel version bumps. (`translations/messages.pot`, `translations/de/LC_MESSAGES/messages.po`) [[1]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L10-R10) [[2]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L19-R32) [[3]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L229-R237) [[4]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L287-R287) [[5]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L307-R311) [[6]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L395-R395) [[7]](diffhunk://#diff-23223ffa0d428b33548d614c397707d7b03d1ccd39dff7cd8809fa6e62af39a2L11-R31) [[8]](diffhunk://#diff-23223ffa0d428b33548d614c397707d7b03d1ccd39dff7cd8809fa6e62af39a2L222-R230) [[9]](diffhunk://#diff-23223ffa0d428b33548d614c397707d7b03d1ccd39dff7cd8809fa6e62af39a2L278-R278) [[10]](diffhunk://#diff-23223ffa0d428b33548d614c397707d7b03d1ccd39dff7cd8809fa6e62af39a2L298-R302) [[11]](diffhunk://#diff-23223ffa0d428b33548d614c397707d7b03d1ccd39dff7cd8809fa6e62af39a2L382-R382) These changes together make log downloads more robust, safer for low-memory environments, and more user-friendly. ## Type of Change - [x] Bugfix - [x] Feature - [ ] Docs - [ ] Refactor - [ ] Security ## Checklist - [x] Description of change - [ ] Related issue(s) - [x] Tests added / updated - [ ] Documentation updated Co-authored-by: Ajimaru --- octoprint_logmonitor/__init__.py | 32 +++- octoprint_logmonitor/security.py | 7 + octoprint_logmonitor/static/js/logmonitor.js | 71 ++++++++- .../templates/logmonitor_tab.jinja2 | 2 +- tests/test_integration_api.py | 143 ++++++++++++++++++ translations/de/LC_MESSAGES/messages.po | 22 +-- translations/messages.pot | 22 +-- 7 files changed, 274 insertions(+), 25 deletions(-) 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/security.py b/octoprint_logmonitor/security.py index c559764..afea053 100644 --- a/octoprint_logmonitor/security.py +++ b/octoprint_logmonitor/security.py @@ -33,6 +33,13 @@ #: 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 diff --git a/octoprint_logmonitor/static/js/logmonitor.js b/octoprint_logmonitor/static/js/logmonitor.js index 87b8051..109b966 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,76 @@ $(() => { }; // 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) { + // Not wrapped in gettext(): Babel's JS lexer stops + // extracting at the regex literals in escapeHtml() + // below, so any gettext() call after that point never + // reaches the catalog. Matches the other PNotify + // messages in this file, which are untranslated too. + var base = "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/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/translations/de/LC_MESSAGES/messages.po b/translations/de/LC_MESSAGES/messages.po index 9571ced..ba53373 100644 --- a/translations/de/LC_MESSAGES/messages.po +++ b/translations/de/LC_MESSAGES/messages.po @@ -7,7 +7,7 @@ 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 12:56+0200\n" "PO-Revision-Date: 2026-05-04 21:46+0200\n" "Last-Translator: FULL NAME \n" "Language: de\n" @@ -16,20 +16,20 @@ msgstr "" "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 " (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" @@ -226,7 +226,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 +234,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" @@ -284,7 +284,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 +304,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 @@ -392,7 +392,7 @@ 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: " diff --git a/translations/messages.pot b/translations/messages.pot index abbe578..74e5758 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 12:56+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" @@ -219,7 +219,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 +227,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 +275,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 +295,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 +379,7 @@ msgstr "" msgid "Streaming Settings" msgstr "" -#: octoprint_logmonitor/static/js/logmonitor.js:330 +#: octoprint_logmonitor/static/js/logmonitor.js:333 msgid "Streaming: " msgstr "" From 70486053b77c59ab7544536450b3b0ef28dcbdff Mon Sep 17 00:00:00 2001 From: Hi My Name Is <38381946+Ajimaru@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:00:50 +0200 Subject: [PATCH 11/13] fix: disable JSX parsing in Babel config to prevent extraction issues (#33) # Description This pull request addresses a silent bug in JavaScript translation string extraction caused by Babel's JSX lexer, ensures all gettext() calls are correctly extracted, and adds regression tests to prevent future issues. It also updates translation templates and the German translation catalog to include a previously missing string and improve formatting. **Internationalization extraction and configuration:** * Disabled JSX parsing in the JavaScript extractor section of `babel.cfg` to prevent Babel from misinterpreting regex literals as JSX, which caused all subsequent gettext() calls to be dropped from the catalog. * Added regression tests in `tests/test_i18n_extraction.py` to ensure the Babel configuration reliably extracts all translation strings, especially those after problematic code patterns. **Translation updates:** * Updated `octoprint_logmonitor/static/js/logmonitor.js` to wrap the "Failed to download log file" message in `gettext()`, making it translatable. * Updated `translations/messages.pot` and `translations/de/LC_MESSAGES/messages.po` to include the new "Failed to download log file" string and to improve formatting and consistency in several multi-line messages. [[1]](diffhunk://#diff-23223ffa0d428b33548d614c397707d7b03d1ccd39dff7cd8809fa6e62af39a2R146-R149) [[2]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2R154-R157) [[3]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L68-R69) [[4]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L270-R276) [[5]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L359-R366) [[6]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L371-R380) [[7]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L401-R410) [[8]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L427-R444) [[9]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L444-L450) **Translation template metadata:** * Updated the POT-Creation-Date in translation template files to reflect the latest extraction. [[1]](diffhunk://#diff-23223ffa0d428b33548d614c397707d7b03d1ccd39dff7cd8809fa6e62af39a2L11-R11) [[2]](diffhunk://#diff-7bbaceb3b8b7a78ec382ae40085e5ceded5173447987067b676afaacce2560c2L10-R18) ## Type of Change - [x] Bugfix - [ ] Feature - [ ] Docs - [ ] Refactor - [ ] Security ## Checklist - [x] Description of change - [ ] Related issue(s) - [x] Tests added / updated - [ ] Documentation updated Co-authored-by: Ajimaru --- babel.cfg | 8 ++ octoprint_logmonitor/static/js/logmonitor.js | 7 +- .../translations/de/LC_MESSAGES/messages.mo | Bin 8204 -> 8237 bytes tests/test_i18n_extraction.py | 95 ++++++++++++++++++ translations/de/LC_MESSAGES/messages.mo | Bin 8156 -> 8237 bytes translations/de/LC_MESSAGES/messages.po | 57 ++++++----- translations/messages.pot | 6 +- 7 files changed, 142 insertions(+), 31 deletions(-) create mode 100644 tests/test_i18n_extraction.py 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/static/js/logmonitor.js b/octoprint_logmonitor/static/js/logmonitor.js index 109b966..496abec 100644 --- a/octoprint_logmonitor/static/js/logmonitor.js +++ b/octoprint_logmonitor/static/js/logmonitor.js @@ -1001,12 +1001,7 @@ $(() => { // reading xhr.responseText throws. Parse the Blob // instead, and notify once the text is available. var notify = function (detail) { - // Not wrapped in gettext(): Babel's JS lexer stops - // extracting at the regex literals in escapeHtml() - // below, so any gettext() call after that point never - // reaches the catalog. Matches the other PNotify - // messages in this file, which are untranslated too. - var base = "Failed to download log file"; + var base = gettext("Failed to download log file"); new PNotify({ title: "Log Monitor", text: detail ? base + ": " + detail : base, diff --git a/octoprint_logmonitor/translations/de/LC_MESSAGES/messages.mo b/octoprint_logmonitor/translations/de/LC_MESSAGES/messages.mo index dacabb958ce305ee36d2499125d6352640512618..ea6a0d1da8c630ab5da90ff14dc547663913f713 100644 GIT binary patch delta 2147 zcmZ|PUu;uV9KiA8Ha6VYfEL(bFz)6+#@41Ch2a>we<i0LVFdt~Pe$F}f zo^yV`-?_Ihx4+w-z2qr6q4-4jU&(){PSbs9bfuHrnbp0Csbti^Kl;~s27x&8_+!U@;6@B#WC z;1>J?Wq#mZrIz7Vtiv!$03#>?y@sXiucl@jN_~peT=)tr@CwR8H!y_7rT=EO1tpLj zNRldyQlTM~jEAumN8Ic0;d1)taTQLx{oipB`>Qf$1#l(G#9pKr>Lo0~<0unPAhD=C zO36P$snFLb75ovU^kqaX*K1q@xQTuzQXDmkvi=xmx6?T04ostD{sT&hub^aj6Iojo zu$yFB;aY>TksrB5wW9>ki=FrsT6h}yQ(hJ)X;tgmR6+eEqZS5afezOlC}%!|Rd^2N zEWbbr_$QQk>xo7J3h^b^yRiX>Py%@YCGZK{iEpCJyY629dm;62XTU?cQj$Jw!y%N7 zC-4zGheLP+<-R?nJ$?^w11_b1jomby?^S9eHlVys`>_%ap*&mT?)W51U>CA9XNkF?% z63jkB<9-@PaXr3+YjFl;qg$@!%&Moq3Rz2aqMYd<%0nANZdGrf1TuwEsgF_C`5YzV z8I*u7BMD_yJz+=%8d2WUUR;d_Q5HOo@?M|C7W^6I46Avkq#|pu37b%!p}iBpnzEtaVJWok6|D7qh$Iv%7Rm_7f=GYj1uT?D5aNO zcs`W}C6QW`hp_|YzA$# z2{bW*=TYA8I*l)FU3$cHA_+4U_xt?~YR$Tcl}R}bX-!WWw&V8OZV#mA+>tQTj%AN( zM#`~A?=o&0>HN1PM+z2nTO+BYrAM_ME1nxHJrvyb+(FBBw64B>z@eu%*UP qYGGsWq5;#6=Ig6}E&2yXZb1|P delta 2133 zcmY+^e`r-@9LMqR?rv+F-D+pc)#mKBALX38I`>1poAWw#+FEVbwseg#Zf;$#*{o$m z+aCu*kRT8`1QCe?|EPZ=$$g;s3lK{c+x7_P=R zK7=E<2WK&fpJ6kuEHR@C-*!^Diy!(hg8Oh7C-V>3CwMQ{7oC@J3)eTW6KhI&8IE8r zzJTgDKqYbx@5XslKR2)qe@9P4Z6Iw8b~6@XH)_PYkUtydUmR1Y`|sidcm`|mg1cTo zCAx$gu!!E&ZWA(DHjQDNLACR-L{oi=il+2E)C_!#nxZdJQ@iBu7jsk3RbdCNLuS(s zpgK5=n(CwO`T}a?pQ93+M{={DPy_q}eN_s0N-r)$by$Zz*nvmzRpeP)L}tzYafWEj zDp&-`(JGzws3mN{`|$*7iRMrVo=3GKD?gV>De38fDs03SR3f9OjHhrAXHX5lLEXQC z3H${$1C5NL3tLbfPvLGnf!g4gP|r2d__+eJR*(6=j~`B#=Xd`(tmOJKR^v_gdl6e- ziPWJs*LvKDNlfB#9K);Fj%~bDd*u)^SbGu4(T?FW_$F%4E%{VP%5EWTEy6Tx$6DNh z6R45AkB{I*T#JkNFjkN)O|28PL`l@98%G|ocTgRjMUDJCDxptN1M)9XQHKktjBDsk zBdkXqr(S#zGpHB7jyiU8xCyVLmZX9sq4ukB9X6o$#9q{QVjMNV8LY>X$PD}T5fzQ# zJNLlPxQ**usEj*ltxR{|lQ@7H=^4}u&pN+ACAff^(La%WYGHcO0LoGKTX84$;cGho zC#k4`$LCKC>Yc5qj(SjQH|R`ZhU;mJ;&s%A=0AKCS8=$N@Uy7*P9wS4acslW$Yk3* zuAqPWmC6MEs~>QTw`oQ)xDS2Q6n~F8K0hLl+FFJ+fP3&DzKuGb1yKSuN-eF52C{|d z)CGlA%YTG)jP!D?wO*zvP7-YV+ltn@kI)oqHaZB6b`8-?sO%y(6HgGW#3=DJLB6@f zAa}eUQ-#9B`!$;oJj#r5hTGL)#P_&N*iN}c+g1vlOdCFb& zq^YoPa%XfsvV^%!62^W)ADM1KMaN12_GU?CVNe{2X9pr<;owTyNNw}bWa{~NbYe2v)!&~uoQWNoPIs5~ zr>4>`r_z(U5zKn+g~LO=LDs7al3r7A)!UdIFaIkP99kJ/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/translations/de/LC_MESSAGES/messages.mo b/translations/de/LC_MESSAGES/messages.mo index b2feea927c049bc332c0f1c78e471f28910811d0..ea6a0d1da8c630ab5da90ff14dc547663913f713 100644 GIT binary patch delta 1728 zcmYM!duYvJ9LMqRE@sTej=9d}x8)L>IpZ*9%Qlm_44b)i60>u5;pDj0QgWC?{*qgh zKM)d9oAZYu67h$OKUR}m%KSx55k+h9{_vC2&R)Og_xnB1^ZkCG=Q(fY-zbT^^TeMr zK6QM@@%6>2_5ZUh!E7kaN_21o=Hot0!!}IC$2b;Wq6fcX5)K$>mWipDge#y*&|Hn!E;Q(PpE-@q7M@W|IKV3Dv;$!l2(JNkRO%tRxHG3_xVj6L;E&n zV3*teg2R~KlIZ2daj1@!NHOdP#^W(m$5Tiw7Dbi(9;!kwP!)WODt!`B>v^WD7iZHh zLyBX2P~*2?q=Jj1?u{-~=C4sD{)Eb~4;kBHnN69dxMrdz%0phU5>x<{ScaQ0j2DqV z8_wV)ZCS3lDb!yX6>viXl)5fQt+^jZV>@aspP~YOkLov-XcUl-e|lbyQ_znJnz$7gVLSTqC+fY`qE3Tc1=bniLc8)6&cHsb!aUB_2HcMt@EvL?(wL3lEggx)a&R*i zp*H0?)RJ6Ay4Wo&#b>wxQz(-HszxOk*}}zSE)L>UypEHw8#PhCYcjni(9S@{vNF_~ zu0w6wdgN8RfC{7oRjK=^ah{+u?nVXFgCrEO351~vweb5VO}J?e+39#w$@sK8I7mf$WbftP=tv;MtY%;!cdy%cd7D$*sm3fG`A zy@ndF!?hC?Ko2U=kEqgX7WSukP>E!rHe)I3y&5dXt=Pi+*2aZ8&Sb}^<3iUO)WmhD zwcg>{f=#qfpo9IWU$jhqBo<>aDuKhOaZezz*=6+M1El))9oOi^WO@g1463~kRidM~ z7SE$f{sVRVVo8g>wiH)j6E@;))cMYKqJ;^E;>OlCg@OTRci0Jpo419+wE-s-ZgA?k z8@)H^)xe~D@3j0mPJTh*OkeausuL44C;HGcJwChq-|K!IOe;1$MWa)Q}(Ovf2GA2(q!>iS_!!{d(Uu!8;oF2%Q~`QAjcO!Q$su0jRSjtb}m zCb7R=`P(pyU_lR)W2jR1qAGIvh z)^EmI+=gKd^wUu0*HDp-pfY@btYuG8nT|P5q5_E_3YsLVhW@)$>aPkEl6DpPQ5)~Vwb+fDF^amch_p|;I05LPf1BOB_!7(TC+ZZH&NR!y z2AqQ(sPQAHz%HU*#=$U+5*iP%5o0)0Td@hX;C0la_<#g$pOIMXH|ofy5rt00UeqHw zh+MKBT!DSK630*h6;LiExEu>H+(KiK8d!h>sEr;uzCq^N1nOD3Sw%0a2N|*kQ~>R$ z3hhSC--pVy8x=?|Dv`&i%%3C2GHgF+m5_yQc2KEJYUo26q!W=w|+fnnzFopf?s~Q-~8={RfP|w)wxEMR>htP{x zQNLhOT!$Y~36%3=p@l=p-qwUc>_Uocmr?iKz&5;#Yc$|vHI=9WTd*Eg@_y8@8$#~2 z?^uu7q}hQTsB`@&H?n?OcWh)l@tHe0u*4TA^OlrU21_H+bg#=*9{H5vkBfw|#uNSk DH_)5< diff --git a/translations/de/LC_MESSAGES/messages.po b/translations/de/LC_MESSAGES/messages.po index ba53373..cfb40b8 100644 --- a/translations/de/LC_MESSAGES/messages.po +++ b/translations/de/LC_MESSAGES/messages.po @@ -7,15 +7,15 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: i18n@octoprint.org\n" -"POT-Creation-Date: 2026-10-18 12:56+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" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" "Generated-By: Babel 2.18.0\n" #: octoprint_logmonitor/static/js/logmonitor.js:335 @@ -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..." @@ -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." @@ -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 @@ -398,11 +406,11 @@ 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 74e5758..2c92f83 100644 --- a/translations/messages.pot +++ b/translations/messages.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: PROJECT VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2026-10-18 12:56+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" @@ -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 "" From 17a77599c68765583e0141653a5f2d237cd2a788 Mon Sep 17 00:00:00 2001 From: Ajimaru Date: Sun, 18 Oct 2026 19:02:05 +0200 Subject: [PATCH 12/13] chore: bump version to 0.2.5 in _version.py and pyproject.toml --- octoprint_logmonitor/_version.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/pyproject.toml b/pyproject.toml index 6855126..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 = [ From b8a6332dc90e73208a30d4c016b50e662680ed76 Mon Sep 17 00:00:00 2001 From: Hi My Name Is <38381946+Ajimaru@users.noreply.github.com> Date: Sun, 18 Oct 2026 19:51:26 +0200 Subject: [PATCH 13/13] feat: implement linear-time ReDoS guard and add unit tests for regex safety (#35) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description This pull request replaces the regular expression-based heuristic for detecting potentially catastrophic regular expressions (ReDoS risks) with a custom linear-time scan, addressing a CodeQL alert about the previous approach being itself vulnerable to ReDoS. It also introduces comprehensive tests to verify the new implementation’s correctness and performance. **Heuristic replacement for ReDoS detection:** * Replaces the regex-based `_NESTED_QUANTIFIER_RE` with a new linear-time scan in `_looks_catastrophic`, which analyzes patterns for nested quantifiers and alternations without risking quadratic runtime. This avoids the previous vulnerability where the ReDoS guard could itself be attacked. [[1]](diffhunk://#diff-41a8e5a5fa5019f8f91d8233685c7a44fdb88c202fd58fd8f39dde68cfdafd64L351-R352) [[2]](diffhunk://#diff-41a8e5a5fa5019f8f91d8233685c7a44fdb88c202fd58fd8f39dde68cfdafd64L377-R441) * Adds `_QUANTIFIER_CHARS` as a set of quantifier characters to simplify detection logic in the scan. **Testing and validation:** * Exposes `_looks_catastrophic` for testing and adds a new `TestCatastrophicPatternHeuristic` test class that: - Verifies classic catastrophic patterns are correctly rejected. - Ensures legitimate patterns are accepted. - Confirms that quantifiers inside character classes and escaped parentheses are handled safely. - Checks that the scan runs in linear time even on large inputs. - Ensures malformed patterns do not cause crashes. [[1]](diffhunk://#diff-8793908c3adeba22dbedcdf620d3d4456cc1e7e0df9d1e69a62f01646dab3ddeR24) [[2]](diffhunk://#diff-8793908c3adeba22dbedcdf620d3d4456cc1e7e0df9d1e69a62f01646dab3ddeR441-R513) ## Type of Change - [ ] Bugfix - [x] Feature - [ ] Docs - [ ] Refactor - [ ] Security ## Checklist - [x] Description of change - [ ] Related issue(s) - [x] Tests added / updated - [ ] Documentation updated Co-authored-by: Ajimaru --- octoprint_logmonitor/security.py | 69 +++++++++++++++++++++++++---- tests/test_security.py | 74 ++++++++++++++++++++++++++++++++ 2 files changed, 134 insertions(+), 9 deletions(-) diff --git a/octoprint_logmonitor/security.py b/octoprint_logmonitor/security.py index afea053..7f0f6d8 100644 --- a/octoprint_logmonitor/security.py +++ b/octoprint_logmonitor/security.py @@ -348,13 +348,8 @@ def _cleanup_locked(self, now: float) -> None: # Regex execution safety (ReDoS mitigation) # --------------------------------------------------------------------------- -#: Heuristic markers for patterns prone to catastrophic backtracking: a -#: quantified group that itself contains a quantifier or an alternation, -#: e.g. ``(x+)+``, ``(a*)*``, ``(a|a)*``, ``(ab|cd){2,}``. Only used as a -#: fallback when the ``regex`` module is unavailable. -_NESTED_QUANTIFIER_RE = re.compile( - r"\([^()]*(?:[*+]|\{\d+(?:,\d*)?\}|\|)[^()]*\)\s*(?:[*+]|\{\d+(?:,\d*)?\})" -) +#: 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 @@ -374,20 +369,76 @@ class PatternTimeoutError(Exception): def _looks_catastrophic(pattern: str) -> bool: - """Report whether a pattern has a shape known to backtrack badly. + 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. """ - return bool(_NESTED_QUANTIFIER_RE.search(pattern)) + # 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( 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()