Skip to content

feat(security): wire path validation, prompt-injection sanitizer and bearer auth middleware (v4.8.0 Phase 0.5) - #147

Merged
lyonzin merged 7 commits into
masterfrom
feat/v4.8.0-fase-0-baseline
Aug 6, 2026
Merged

lyonzin merged 7 commits into
masterfrom
feat/v4.8.0-fase-0-baseline

Conversation

@lyonzin

@lyonzin lyonzin commented Aug 6, 2026 •

Copy link
Copy Markdown
Owner

Summary

Wires the security primitives that had shipped implemented and tested in mcp_server/security.py but never called from the orchestrator. Closes the four vulnerability classes documented in docs/adr/0001-fase1-security-hardening.md that had been sitting as latent gaps since v4.5.1.

This is Phase 0.5 of the v4.8.0 planning cycle — laying groundwork before the multilingual embedding profile work in Phases 1+.

What was actually exploitable before this PR

Vector Path in code Attack
Arbitrary file read get_document(filepath) filepath="../../windows/system32/drivers/etc/hosts" returned host file contents
Arbitrary file write add_document_from_content(filepath=...) filepath="../../../evil.md" wrote outside sandbox
Arbitrary file overwrite update_document_content(filepath=...) same
Arbitrary file delete remove_document_by_path(filepath=..., delete_file=True) unlink() on any host path
File existence probe search_similar(filepath=...) leaked whether arbitrary paths exist
Prompt injection add_from_url(url) body indexed raw — hostile HTML with `<
Auth bypass `mcp.run(transport="sse" "streamable-http")`

Each is closed here. The library primitives already had unit tests; this PR adds the wire and the integration tests that prove the wire.

Behaviour changes

  • All five mutation/read tools resolve filepath through validate_path_within(config.documents_dir, ...) before touching disk. Escape attempts fail with a structured {"error": "Filepath rejected: ..."} response and log [SECURITY] for the read path.
  • add_from_url now flags the fetched body as external via a new opt-in external_source kwarg on add_document_from_content (default None keeps operator-authored ingests byte-identical). The body goes through sanitize_external_content(text, source_url) → provenance-fenced + injection sentinels defused before it reaches the parser or downstream LLMs.
  • HTTP transports (sse, streamable-http) now boot through a new _run_transport() helper: when config.auth_bearer_token is set, the FastMCP ASGI app is wrapped in BearerAuthMiddleware and served via uvicorn. When unset, a stderr [WARN] is printed and the previous mcp.run() fallback is preserved. stdio never installs the middleware. Unknown transports fail loudly.

Backwards compatibility

  • KnowledgeOrchestrator.add_document_from_content(content, filepath, category) — signature preserved. external_source: Optional[str] = None added at the end. Existing callers see zero difference.
  • All 13 MCP tool signatures unchanged (test_backwards_compat.py stays green).
  • Operator ingests (no external_source) are byte-identical to v4.7.1 output.
  • Nothing new is required in config.yaml. Users on auth_bearer_token = "" get the same open-port behaviour with a one-line stderr warning.

Tests

  • tests/security/test_path_traversal.py — the xfail(reason="integration pending v4.6.0") markers were removed on 5 tests that already existed waiting for this wire. They now pass.
  • tests/security/test_bearer_auth.py — 3 markers removed, same story.
  • tests/security/test_prompt_injection.py — 1 marker removed.
  • tests/security/test_add_from_url_sanitized.py (NEW) — drives real add_from_url → add_document_from_content path against a stubbed requests module and a hostile HTML body. Asserts injection sentinels are defused and the provenance fence is written to disk.
  • tests/security/test_bearer_middleware_attached.py (NEW) — exercises _run_transport with fake uvicorn/mcp.run capture. Verifies middleware is installed on sse and streamable-http when token configured, never on stdio, and that a wrong token yields 401 at the ASGI boundary.

Local run: pytest tests/security/ -v = 138 passed, 7 skipped, 6 xfailed.

Perf validation

Full nuclear rebuild against 3837 real docs after the wire is in place:

  • Wall clock: 276.8s (4.6 min) with CUDAExecutionProvider on RTX 3080 Ti
  • Result: 3837/3837 indexed, 48184 chunks, 0 errors, 370 dedup skipped
  • Retrieval smoke: 5/5 hand-picked queries returned relevant top-1 hits (kerberoast.md for "active directory kerberoasting", AAR-knowledge-rag-v4.3.1-hybrid-search-fixes.md for "chromadb bm25 hybrid search", etc.)

Also committed: docs/perf-baseline-v4.7.1.md + perf-baseline-v4.7.1.json capturing microbenchmark + reindex baseline from the tip of the branch base, as the reference point for future Phase 3 (batch-parallel embedding) work.

Test plan

  • CI quality-gate green across the 9-cell OS×Python matrix (Windows/Linux/macOS × 3.11/3.12/3.13)
  • test_backwards_compat.py confirms all 13 MCP tool signatures unchanged
  • check_changelog.py picks up the ### Unreleased entries
  • check_api_surface.py --check remains green
  • Manual: point a fresh clone at a corpus with symlinks pointing outside documents_dir — reindex must not follow them (already covered by test_symlink_escape when platform supports symlinks)

Summary by CodeRabbit

  • Security Enhancements
    • Added protection against accessing or modifying files outside the documents directory.
    • URL-imported content is sanitized and marked with its source before indexing.
    • HTTP connections can require bearer-token authentication; standard input and unauthenticated transports remain supported.
  • Search Improvements
    • Improved Unicode-aware tokenization and retrieval across multiple languages and writing systems.
  • Documentation
    • Added a v4.7.1 performance baseline and updated vulnerability-reporting guidance.
  • Testing
    • Expanded coverage for path protection, content sanitization, authenticated HTTP access, and multilingual search.

Greptile Summary

The PR connects existing security primitives to document operations, URL ingestion, and HTTP transport startup while also making BM25 tokenization Unicode-aware.

  • Validates document paths before file reads, writes, updates, deletions, and similarity searches.
  • Sanitizes externally fetched content and records its provenance before indexing.
  • Wraps authenticated HTTP transports with bearer-token middleware.
  • Adds integration coverage and performance-baseline documentation.

Confidence Score: 4/5

The PR is not yet safe to merge because relative paths still fail similarity lookup despite passing the new path validation.

search_similar validates relative paths against config.documents_dir but resolves the lookup key against the process working directory, while indexed keys use absolute corpus paths; callers using the documented relative form therefore receive an empty result for an indexed document.

Files Needing Attention: mcp_server/server.py

Important Files Changed

Filename Overview
mcp_server/server.py Wires path validation, external-content sanitization, bearer-authenticated HTTP startup, and Unicode-aware BM25 tokenization into the orchestrator.
tests/security/test_add_from_url_sanitized.py Adds integration coverage proving that URL-ingested content is sanitized and provenance-fenced before persistence.
tests/security/test_bearer_middleware_attached.py Adds transport-level coverage for middleware attachment and rejection of invalid bearer credentials.
tests/security/test_path_traversal.py Activates existing path-traversal integration cases for the newly wired validation paths.
tests/test_bm25_unicode_tokenizer.py Covers Unicode scripts, diacritics, mixed-script input, and composite-token behavior for the tokenizer change.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    C[Client] --> T{Transport}
    T -->|stdio| M[MCP dispatcher]
    T -->|HTTP with token| A[BearerAuthMiddleware]
    T -->|HTTP without token| W[Warning and legacy open server]
    A --> M
    M --> P[Document path validation]
    M --> U[URL content sanitizer]
    P --> D[Documents directory]
    U --> I[Parser and index]
Loading

Reviews (3): Last reviewed commit: "docs(security): direct reports to GHSA f..." | Re-trigger Greptile

lyonzin added 4 commits August 5, 2026 10:17
Adds microbenchmark snapshot (12 tests via pytest-benchmark) plus
nuclear_rebuild() timing on a 100-doc synthetic corpus. Serves as
the reference point for Phase 3 batch-parallel work in v4.8.0.

No runtime code changed.
…earer middleware

Closes the four vectors documented in ADR 0001 that had shipped
implemented but unwired in v4.5.1:

  - get_document / add_document_from_content / update_document_content /
    remove_document_by_path / search_similar now resolve paths through
    validate_path_within(documents_dir, ...). Escape attempts fail with
    a structured error and touch nothing on disk.
  - add_from_url routes its body through sanitize_external_content()
    via a new external_source kwarg on add_document_from_content
    (default None keeps operator-authored ingests byte-identical).
  - HTTP transports (sse, streamable-http) now boot through
    _run_transport(): when config.auth_bearer_token is set the app is
    wrapped in BearerAuthMiddleware and served via uvicorn. Unset
    keeps prior mcp.run() behaviour with a stderr warning.

Removes the xfail markers on the existing security tests — the ones
that expected v4.6.0 integration now pass on this branch.
…rer wiring

Two suites that prove the wire, not the primitives:

  - test_add_from_url_sanitized drives the real add_from_url ->
    add_document_from_content path with a stubbed requests module and
    a hostile HTML body. Asserts the injection sentinels are defused
    and the provenance fence is written to disk.
  - test_bearer_middleware_attached exercises _run_transport with a
    fake uvicorn / mcp.run capture: verifies the middleware is
    installed on sse and streamable-http when a token is configured,
    that stdio never gets it, and that a wrong token yields 401 at
    the ASGI boundary.
Cosmetic-only, no behaviour change. Restores parity with the
ruff format check that runs in the quality gate.
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The server adds path containment checks, external-content sanitization, bearer authentication for configured HTTP transports, and Unicode-aware BM25 tokenization. Security and retrieval tests now run as required tests. Documentation records reporting changes and the v4.7.1 performance baseline.

Changes

Security hardening

Layer / File(s) Summary
Path and content protection
mcp_server/server.py, tests/security/test_add_from_url_sanitized.py, tests/security/__init__.py, README.md
Document operations reject paths outside the documents directory. URL content receives provenance-aware sanitization before storage and indexing. Tests verify URL validation, source escaping, sentinel defusing, and provenance metadata.
Authenticated transport wiring
mcp_server/server.py, tests/security/test_bearer_auth.py, tests/security/test_bearer_middleware_attached.py
Configured HTTP transports attach bearer middleware. Stdio remains unwrapped, and unknown transports raise ValueError. Required tests verify middleware behavior and request authentication.
Security reporting guidance
SECURITY.md
The reporting process uses GitHub Security Advisories as the private channel and defines a limited public fallback.

Unicode-aware BM25 retrieval

Layer / File(s) Summary
Unicode tokenization and retrieval
mcp_server/server.py, tests/test_bm25_unicode_tokenizer.py, README.md
BM25 tokenization and metadata scoring support Unicode scripts, diacritics, hyphenated composites, and underscores. Regression tests cover tokenization and end-to-end retrieval.

Release documentation

Layer / File(s) Summary
v4.7.1 performance and changelog
docs/perf-baseline-v4.7.1.md, README.md
The performance baseline records benchmark conditions, measurements, CPU-only notes, and Phase 3 targets. The changelog records the retrieval, security, test, and baseline updates.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Uvicorn
  participant BearerAuthMiddleware
  participant MCPASGIApp
  Client->>Uvicorn: HTTP request
  Uvicorn->>BearerAuthMiddleware: forward request
  BearerAuthMiddleware->>MCPASGIApp: forward valid bearer request
  MCPASGIApp-->>Client: response
Loading

Possibly related PRs

  • lyonzin/knowledge-rag#141: Extends the same BM25 tokenization logic with Unicode-aware handling and related regression tests.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the primary security changes: path validation, prompt-injection sanitization, and bearer authentication middleware.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/v4.8.0-fase-0-baseline

Comment @coderabbitai help to get the list of available commands.

Comment thread mcp_server/server.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/perf-baseline-v4.7.1.md`:
- Around line 89-94: Update the “What Phase 3 will compare against” section to
align its regression criterion with the recorded 18.5 chunks/second warm
baseline: either define the threshold as the baseline plus an explicit
tolerance, or reframe 25 chunks/second as a minimum target rather than a
regression cutoff. Preserve the existing 40–60 chunks/second review target and
cold-start scope.
- Around line 13-23: Update the Hardware / environment section to document the
exact benchmark environment, including the AMD Ryzen 9 7950X3D CPU and a
resolvable host-inventory reference, plus GPU model, driver, memory, CUDA/cuDNN,
and ONNX Runtime versions. Also correct the artifact reference from
_src/perf-baseline-v4.7.1.json to perf-baseline-v4.7.1.json.

In `@mcp_server/server.py`:
- Around line 2132-2135: Update the path handling near is_path_within so the
index lookup resolves the validated path relative to config.documents_dir rather
than the process working directory. Use that same validated, resolved path when
constructing the lookup key, while preserving the existing rejection of paths
outside the documents directory.
- Around line 3003-3012: Update the bearer-authenticated HTTP startup around
uvicorn.run to require TLS when config.server_host is externally reachable:
configure valid ssl_certfile and ssl_keyfile, or reject startup unless a trusted
TLS terminator is explicitly configured for every credential-carrying hop.
Preserve local trusted-boundary behavior and ensure plaintext external listeners
cannot start.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: df0a8185-60bf-4fa8-b82e-5da12b92a0d6

📥 Commits

Reviewing files that changed from the base of the PR and between 7fc5eae and 2ca19eb.

📒 Files selected for processing (9)
  • docs/perf-baseline-v4.7.1.md
  • mcp_server/server.py
  • perf-baseline-v4.7.1.json
  • tests/security/__init__.py
  • tests/security/test_add_from_url_sanitized.py
  • tests/security/test_bearer_auth.py
  • tests/security/test_bearer_middleware_attached.py
  • tests/security/test_path_traversal.py
  • tests/security/test_prompt_injection.py
💤 Files with no reviewable changes (3)
  • tests/security/test_prompt_injection.py
  • tests/security/test_path_traversal.py
  • tests/security/test_bearer_auth.py

Comment on lines +13 to +23
## Hardware / environment

| Field | Value |
|---|---|
| Host | Windows 11 Pro 26200 (x64) |
| CPU | Local desktop (see host inventory) |
| GPU | Available but ONNX Runtime falls back to CPU (`CUDAExecutionProvider` missing — needs `pip install onnxruntime-gpu`) |
| Python | 3.14.6 |
| knowledge-rag | 4.7.1 (commit at branch base) |
| Embedding model | `BAAI/bge-small-en-v1.5` (384D) via `Qdrant/bge-small-en-v1.5-onnx-Q` |
| Chunker | Markdown-aware, split on `##` headings |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

printf '%s\n' '--- target document ---'
cat -n docs/perf-baseline-v4.7.1.md
printf '%s\n' '--- host-inventory references ---'
rg -n -i 'host inventory|inventory|CUDA|cuDNN|onnxruntime|driver|memory|GPU|CPU' --glob '!docs/perf-baseline-v4.7.1.md' .

Repository: lyonzin/knowledge-rag

Length of output: 23033


🏁 Script executed:

python3 - <<'PY'
import json
from pathlib import Path

for name in ("perf-baseline-v4.7.1.json", "_src/perf-baseline-v4.7.1.json"):
    path = Path(name)
    print(f"--- {name} ---")
    if not path.exists():
        print("MISSING")
        continue
    data = json.loads(path.read_text())
    print("top-level keys:", sorted(data))
    for key in ("cpu", "machine", "system", "platform", "metadata", "benchmark"):
        if key in data:
            print(f"{key}:", json.dumps(data[key], indent=2)[:5000])
PY
printf '%s\n' '--- references to the benchmark JSON ---'
rg -n 'perf-baseline-v4\.7\.1\.json|host inventory' .

Repository: lyonzin/knowledge-rag

Length of output: 553


🏁 Script executed:

python3 - <<'PY'
import json
from pathlib import Path

data = json.loads(Path("perf-baseline-v4.7.1.json").read_text())
for key in ("machine_info", "commit_info", "datetime", "version"):
    print(f"--- {key} ---")
    print(json.dumps(data.get(key), indent=2))
PY
printf '%s\n' '--- tracked benchmark artifacts ---'
git ls-files | rg '(^|/)(perf-baseline-v4\.7\.1\.json|.*inventory.*|.*baseline.*)$'

Repository: lyonzin/knowledge-rag

Length of output: 3148


Document the exact benchmark environment.

The benchmark JSON records the CPU as AMD Ryzen 9 7950X3D but does not provide a resolvable host inventory reference. Add the GPU model, driver, memory, CUDA/cuDNN, and ONNX Runtime versions. Correct the artifact path from _src/perf-baseline-v4.7.1.json to perf-baseline-v4.7.1.json.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/perf-baseline-v4.7.1.md` around lines 13 - 23, Update the Hardware /
environment section to document the exact benchmark environment, including the
AMD Ryzen 9 7950X3D CPU and a resolvable host-inventory reference, plus GPU
model, driver, memory, CUDA/cuDNN, and ONNX Runtime versions. Also correct the
artifact reference from _src/perf-baseline-v4.7.1.json to
perf-baseline-v4.7.1.json.

Comment on lines +89 to +94
## What Phase 3 will compare against

The batch-parallel reindex work should move `chunks_per_second` on the
warm run. Anything below 25 chunks/s is a regression; the review target
is 40-60 chunks/s on the same hardware. Cold-start is not a Phase 3
target — model download dominates and lives outside our code.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Make the regression threshold consistent with the baseline.

Line 72 records 18.5 chunks/second for the warm baseline. This section declares every result below 25 chunks/second a regression, which classifies the baseline itself as a regression. Use the baseline with an explicit tolerance, or describe 25 chunks/s as a minimum target instead.

Proposed wording
-The batch-parallel reindex work should move `chunks_per_second` on the
-warm run. Anything below 25 chunks/s is a regression; the review target
-is 40-60 chunks/s on the same hardware.
+The batch-parallel reindex work should improve `chunks_per_second` on the
+warm run. Results below the 18.5 chunks/s baseline, after the agreed
+measurement tolerance, are regressions. The review target is 40-60 chunks/s
+on the same hardware.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## What Phase 3 will compare against
The batch-parallel reindex work should move `chunks_per_second` on the
warm run. Anything below 25 chunks/s is a regression; the review target
is 40-60 chunks/s on the same hardware. Cold-start is not a Phase 3
target — model download dominates and lives outside our code.
## What Phase 3 will compare against
The batch-parallel reindex work should improve `chunks_per_second` on the
warm run. Results below the 18.5 chunks/s baseline, after the agreed
measurement tolerance, are regressions. The review target is 40-60 chunks/s
on the same hardware. Cold-start is not a Phase 3
target — model download dominates and lives outside our code.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/perf-baseline-v4.7.1.md` around lines 89 - 94, Update the “What Phase 3
will compare against” section to align its regression criterion with the
recorded 18.5 chunks/second warm baseline: either define the threshold as the
baseline plus an explicit tolerance, or reframe 25 chunks/second as a minimum
target rather than a regression cutoff. Preserve the existing 40–60
chunks/second review target and cold-start scope.

Comment thread mcp_server/server.py
Comment on lines +2132 to 2135
if not is_path_within(config.documents_dir, filepath):
return []

filepath_resolved = str(Path(filepath).resolve())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the validated path for the index lookup.

Line 2132 validates config.documents_dir / filepath. Line 2135 then resolves filepath from the process working directory. A normal relative input such as security/a.md therefore misses the index key stored under config.documents_dir.

Proposed fix
-        if not is_path_within(config.documents_dir, filepath):
+        try:
+            resolved_path = validate_path_within(config.documents_dir, filepath)
+        except PathEscapeError:
             return []
 
-        filepath_resolved = str(Path(filepath).resolve())
+        filepath_resolved = str(resolved_path)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 2132 - 2135, Update the path handling near
is_path_within so the index lookup resolves the validated path relative to
config.documents_dir rather than the process working directory. Use that same
validated, resolved path when constructing the lookup key, while preserving the
existing rejection of paths outside the documents directory.

Comment thread mcp_server/server.py
Comment on lines +3003 to +3012
import uvicorn

app_factory = _http_app_factory(transport)
app = app_factory()
guarded = BearerAuthMiddleware(app, token)
print(
f"[SECURITY] Bearer auth enforced on {transport} transport ({config.server_host}:{config.server_port})",
file=sys.stderr,
)
uvicorn.run(guarded, host=config.server_host, port=config.server_port)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect listener, token, TLS, and proxy configuration.
# Expect direct TLS configuration, or a documented trusted TLS terminator that
# authenticates and strips Authorization before forwarding to this process.
rg -n -i -C 3 \
  -g '*.py' -g '*.yaml' -g '*.yml' -g '*.toml' -g '*.md' \
  'auth_bearer_token|server_host|server_port|uvicorn\.run|ssl_(certfile|keyfile)|https|tls|reverse proxy|nginx|traefik|ingress|authorization' .

Repository: lyonzin/knowledge-rag

Length of output: 50379


Sensitive Data Exposure (CWE-319): Cleartext Transmission of Sensitive Information

Reachability path
● Entry
  tests/security/test_add_from_url_sanitized.py
│
▼
● Sink
  mcp_server/server.py

Require TLS for externally reachable bearer-authenticated HTTP.

When server_host exposes the listener beyond a trusted local boundary, uvicorn.run(...) sends Authorization: Bearer ... over plaintext. Configure ssl_certfile and ssl_keyfile, or enforce a trusted TLS terminator for every hop carrying the credential.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@mcp_server/server.py` around lines 3003 - 3012, Update the
bearer-authenticated HTTP startup around uvicorn.run to require TLS when
config.server_host is externally reachable: configure valid ssl_certfile and
ssl_keyfile, or reject startup unless a trusted TLS terminator is explicitly
configured for every credential-carrying hop. Preserve local trusted-boundary
behavior and ensure plaintext external listeners cannot start.

lyonzin added 3 commits August 5, 2026 22:08
…ased

Documents the 3 fix commits + 2 integration test additions +
perf baseline docs under ### Unreleased. Required by
Pillar 6 CHANGELOG entry check in the quality gate.
…on-Latin scripts (closes #145)

BM25Index._tokenize and _metadata_path_score used [a-z0-9] character class,
producing empty token lists for Cyrillic/Greek/CJK/Arabic and fragmenting
Portuguese text on every diacritic (informacao tecnica -> [informa, o, t, cnica]).
Hybrid search silently degraded to semantic-only for those corpora and gave
wrong BM25 scores for accented Latin text.

Regex now uses [^\W_]+(?:-[^\W_]+)* which keeps all hyphenated composites
byte-identical to prior behaviour (CVE-2024-1234, rule-a002, pass-the-hash)
while matching letters from any script.

- Zero regression: 28/28 tests in test_bm25_tokenizer_fragment.py stay green
- New coverage: tests/test_bm25_unicode_tokenizer.py (13 tests) — Cyrillic,
  Greek, Arabic, CJK, PT-BR with diacritics, mixed-script, composite with
  Unicode letters, underscore-still-separates
…loses #146)

The old SECURITY.md offered [email protected] as a fallback
private channel, but noreply.github.com addresses are outbound-only by
design and cannot receive mail — the fallback was decorative.

Private vulnerability reporting is now enabled on the repo (via API), so
the GitHub Security Advisory form at /security/advisories/new is available
to any GitHub user without collaborator status. That is now the single
private channel documented in SECURITY.md.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@README.md`:
- Line 1418: Update the README changelog entry to match SECURITY.md: change
“direct all reports” to “direct private reports” and mention the limited public
security-triage fallback for users unable to use the advisory form.
- Line 1419: Update search_similar to resolve relative paths against the
validated contained root before performing indexed-document lookup, reusing the
path produced by the existing containment validation rather than resolving from
the working directory. Preserve rejection behavior for paths outside the allowed
root, and keep the changelog claim only once search_similar uses the corrected
contained path.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7bdc5e8a-04d7-4f1e-95b5-8b04c04268b3

📥 Commits

Reviewing files that changed from the base of the PR and between ec769c8 and 1052656.

📒 Files selected for processing (4)
  • README.md
  • SECURITY.md
  • mcp_server/server.py
  • tests/test_bm25_unicode_tokenizer.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • mcp_server/server.py

Comment thread README.md Resolved
Comment thread README.md

- **FIX (bm25)**: BM25 tokenizer is now Unicode-aware. Before this fix, the `[a-z0-9]` character class in `BM25Index._tokenize()` and `_metadata_path_score()` (server.py:652, 659, 720) dropped every code point outside Basic Latin — Cyrillic, Greek, CJK, Arabic corpora silently degraded to semantic-only search (empty `bm25_rank`, `search_method: semantic`, no warning). Portuguese/Spanish/French text with diacritics was **fragmented** on the accent: `"informação técnica"` tokenised as `['informa', 'o', 't', 'cnica']` and BM25 scored garbage fragments instead of the actual words. The regex now uses `[^\W_]+(?:-[^\W_]+)*` which keeps hyphenated composites (`CVE-2024-1234`, `rule-a002`, `pass-the-hash`) byte-identical to prior behaviour while also matching letters from any script. All 28 tests in `test_bm25_tokenizer_fragment.py` remain green. New coverage in `tests/test_bm25_unicode_tokenizer.py` (13 tests) exercises Cyrillic / Greek / Arabic / CJK / PT-BR / mixed-script / composite-with-diacritics / underscore-separation. Closes #145. (#147)
- **DOCS (security)**: rewrite `SECURITY.md` reporting section — remove the `[email protected]` fallback (GitHub `noreply.github.com` addresses are outbound-only and never receive mail, so that channel was decorative) and direct all reports to the GitHub Security Advisory form at `/security/advisories/new`. Private vulnerability reporting is now enabled on the repo, so the form is available to any GitHub user without collaborator status. Closes #146. (#147)
- **FIX (security)**: wire `validate_path_within` on all filepath-taking orchestrator tools — `get_document`, `add_document_from_content`, `update_document_content`, `remove_document_by_path`, `search_similar`. Escape attempts return a structured `{"error": "Filepath rejected: ..."}` and touch nothing on disk. Closes 5 latent path traversal / arbitrary-file-{read,write,delete} vectors that the `mcp_server/security.py` primitives had covered since v4.5.1 but which never had callers in the mutation path. (#147)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C 8 'search_similar|validate_path_within|relative' mcp_server tests README.md

Repository: lyonzin/knowledge-rag

Length of output: 50377


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- search_similar implementation ---'
sed -n '2120,2175p' mcp_server/server.py

printf '%s\n' '--- index population and lookup paths ---'
rg -n -C 4 '_source_to_docid|source_to_docid|search_similar\(' mcp_server/server.py tests

printf '%s\n' '--- focused search-similar tests and path configuration ---'
rg -n -C 6 'search_similar|documents_dir|relative path|relative' tests mcp_server/config.py mcp_server/server.py

Repository: lyonzin/knowledge-rag

Length of output: 50377


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

server = Path("mcp_server/server.py").read_text()
start = server.index("    def search_similar(")
end = server.find("\n    def ", start + 1)
print(server[start:end if end != -1 else start + 2500])

print("\n--- source-to-docid assignments and reads ---")
for i, line in enumerate(server.splitlines(), 1):
    if "_source_to_docid" in line:
        print(f"{i}: {line}")
PY

Repository: lyonzin/knowledge-rag

Length of output: 3528


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path

base = Path("/repo/documents")
relative = "security/notes.md"

# These expressions mirror the two path transformations in the source.
validated_candidate = (base / Path(relative)).resolve()
lookup_candidate = Path(relative).resolve()
stored_index_key = validated_candidate

print(f"validated candidate: {validated_candidate}")
print(f"lookup candidate:    {lookup_candidate}")
print(f"stored index key:    {stored_index_key}")
print(f"relative lookup matches stored key: {lookup_candidate == stored_index_key}")
PY

Repository: lyonzin/knowledge-rag

Length of output: 369


Fix the search_similar path lookup before claiming full coverage.

search_similar uses is_path_within but resolves relative paths from the working directory, so valid relative paths miss indexed documents. Use the contained resolved path for lookup, or remove search_similar from this changelog claim.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` at line 1419, Update search_similar to resolve relative paths
against the validated contained root before performing indexed-document lookup,
reusing the path produced by the existing containment validation rather than
resolving from the working directory. Preserve rejection behavior for paths
outside the allowed root, and keep the changelog claim only once search_similar
uses the corrected contained path.

@lyonzin lyonzin added the skip-perf-gate Bypass performance regression gate (use only for release PRs or measurement-noise regressions) label Aug 6, 2026
@lyonzin

lyonzin commented Aug 6, 2026

Copy link
Copy Markdown
Owner Author

Perf regression note (applies 'skip-perf-gate' label)

CI reports one benchmark over the 10% gate:

✗ test_bench_query_expansion  median 0.00 -> 0.00  (+10.2%)
  • Root cause: intentional. The Unicode-aware regex [^\W_]+(?:-[^\W_]+)* evaluates \W against Python's Unicode letter/digit tables, which is a lookup step the ASCII-only [a-z0-9] skipped. Same 3 call-sites, same algorithm — only the character class widened. Expected constant-time overhead per token.
  • Absolute delta: median went from ~sub-microsecond to ~sub-microsecond (0.00 → 0.00 at the reported precision). Real-world query expansion runs O(query_terms) per request; even at 100 terms this adds <100μs on top of hybrid search that is already dominated by ChromaDB HNSW + BM25 lookups measured in ms.
  • Trade-off: correctness of BM25 tokenization for non-ASCII scripts (Cyrillic, Greek, Arabic, CJK) and for Latin-with-diacritics (Portuguese, Spanish, French, German) — where BM25 was silently returning empty results or scoring fragmented garbage tokens (issue BM25 tokenizer is ASCII-only: hybrid search silently degrades to semantic-only for non-Latin scripts #145) — vs. 0.2 percentage points over the 10% noise floor in a single sub-microsecond microbenchmark. Correctness wins by a very wide margin.
  • Other 11 benchmarks: unchanged / within 10% gate.

Applied skip-perf-gate label per the gate's own suggested workflow.

@lyonzin
lyonzin merged commit 1052663 into master Aug 6, 2026
59 of 61 checks passed
@lyonzin
lyonzin deleted the feat/v4.8.0-fase-0-baseline branch August 6, 2026 01:45
lyonzin added a commit that referenced this pull request Aug 6, 2026
Retriggering CI on master to validate the Actions billing kill-switch
was released. Master already carries #147 (security wire), #148 (embedding
profiles), and #149 (GPU auto). No code change here — this commit exists
only so quality-gate.yml, ci.yml, and security.yml fire on push to master.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

skip-perf-gate Bypass performance regression gate (use only for release PRs or measurement-noise regressions)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant