Repository navigation
feat(security): wire path validation, prompt-injection sanitizer and bearer auth middleware (v4.8.0 Phase 0.5) - #147
Conversation
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.
📝 WalkthroughWalkthroughThe 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. ChangesSecurity hardening
Unicode-aware BM25 retrieval
Release documentation
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (9)
docs/perf-baseline-v4.7.1.mdmcp_server/server.pyperf-baseline-v4.7.1.jsontests/security/__init__.pytests/security/test_add_from_url_sanitized.pytests/security/test_bearer_auth.pytests/security/test_bearer_middleware_attached.pytests/security/test_path_traversal.pytests/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
| ## 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 | |
There was a problem hiding this comment.
🚀 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.
| ## 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. |
There was a problem hiding this comment.
🚀 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.
| ## 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.
| if not is_path_within(config.documents_dir, filepath): | ||
| return [] | ||
|
|
||
| filepath_resolved = str(Path(filepath).resolve()) |
There was a problem hiding this comment.
🎯 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.
| 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) |
There was a problem hiding this comment.
🔒 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.
…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.
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
README.mdSECURITY.mdmcp_server/server.pytests/test_bm25_unicode_tokenizer.py
🚧 Files skipped from review as they are similar to previous changes (1)
- mcp_server/server.py
|
|
||
| - **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) |
There was a problem hiding this comment.
🎯 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.mdRepository: 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.pyRepository: 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}")
PYRepository: 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}")
PYRepository: 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.
Perf regression note (applies 'skip-perf-gate' label)CI reports one benchmark over the 10% gate:
Applied |
Summary
Wires the security primitives that had shipped implemented and tested in
mcp_server/security.pybut never called from the orchestrator. Closes the four vulnerability classes documented indocs/adr/0001-fase1-security-hardening.mdthat 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
get_document(filepath)filepath="../../windows/system32/drivers/etc/hosts"returned host file contentsadd_document_from_content(filepath=...)filepath="../../../evil.md"wrote outside sandboxupdate_document_content(filepath=...)remove_document_by_path(filepath=..., delete_file=True)unlink()on any host pathsearch_similar(filepath=...)add_from_url(url)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
filepaththroughvalidate_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_urlnow flags the fetched body as external via a new opt-inexternal_sourcekwarg onadd_document_from_content(defaultNonekeeps operator-authored ingests byte-identical). The body goes throughsanitize_external_content(text, source_url)→ provenance-fenced + injection sentinels defused before it reaches the parser or downstream LLMs.sse,streamable-http) now boot through a new_run_transport()helper: whenconfig.auth_bearer_tokenis set, the FastMCP ASGI app is wrapped inBearerAuthMiddlewareand served via uvicorn. When unset, a stderr[WARN]is printed and the previousmcp.run()fallback is preserved.stdionever installs the middleware. Unknown transports fail loudly.Backwards compatibility
KnowledgeOrchestrator.add_document_from_content(content, filepath, category)— signature preserved.external_source: Optional[str] = Noneadded at the end. Existing callers see zero difference.test_backwards_compat.pystays green).external_source) are byte-identical to v4.7.1 output.config.yaml. Users onauth_bearer_token = ""get the same open-port behaviour with a one-line stderr warning.Tests
tests/security/test_path_traversal.py— thexfail(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 realadd_from_url → add_document_from_contentpath against a stubbedrequestsmodule 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_transportwith fake uvicorn/mcp.run capture. Verifies middleware is installed onsseandstreamable-httpwhen token configured, never onstdio, 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:
CUDAExecutionProvideron RTX 3080 Tikerberoast.mdfor "active directory kerberoasting",AAR-knowledge-rag-v4.3.1-hybrid-search-fixes.mdfor "chromadb bm25 hybrid search", etc.)Also committed:
docs/perf-baseline-v4.7.1.md+perf-baseline-v4.7.1.jsoncapturing microbenchmark + reindex baseline from the tip of the branch base, as the reference point for future Phase 3 (batch-parallel embedding) work.Test plan
test_backwards_compat.pyconfirms all 13 MCP tool signatures unchangedcheck_changelog.pypicks up the### Unreleasedentriescheck_api_surface.py --checkremains greendocuments_dir— reindex must not follow them (already covered bytest_symlink_escapewhen platform supports symlinks)Summary by CodeRabbit
Greptile Summary
The PR connects existing security primitives to document operations, URL ingestion, and HTTP transport startup while also making BM25 tokenization Unicode-aware.
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_similarvalidates relative paths againstconfig.documents_dirbut 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
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]Reviews (3): Last reviewed commit: "docs(security): direct reports to GHSA f..." | Re-trigger Greptile