Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

14.7 KB
Raw Blame

LDR Custom Security Rules

This directory contains custom Semgrep security rules specific to Local Deep Research (LDR).

Rules Overview

ldr-security.yaml

LDR-specific security rules covering:

  1. Hardcoded Secrets

    • Detects API keys, passwords, tokens in source code
    • Severity: ERROR
    • CWE-798
  2. SQL Injection Prevention

    • sql-string-concatenation: follows dynamically constructed strings (f-string, +, %, .format()) to database execution and SQLAlchemy raw-SQL constructors, including inline expressions, aliases and stored values. Named SQL builders also prompt review. Bound SQLAlchemy values remain clear, including mapping values, stored strings without reassignment, and reused bindparams() statements. Column identifiers built from an inline or unchanged stored f-string remain clear when quoting is enabled. Unpacked arguments, quoted_name overrides, reassigned names, explicit or unknown literal flags, and nested raw-SQL constructors remain reportable. Only the name occurrence is cleared; an unsafe table/selectable argument still reaches execution.
    • sql-execute-with-string-format: $X.execute(f"...") or $X.execute("..." + ...)
    • Enforces parameterized queries via SQLAlchemy
    • Severity: ERROR
    • CWE-89
  3. Code Injection

    • Detects dangerous use of eval/exec
    • Prevents arbitrary code execution
    • Severity: ERROR
    • CWE-95
  4. Command Injection

    • Detects unsafe use of os.system, shell=True
    • Enforces subprocess with argument lists
    • Severity: ERROR
    • CWE-78
  5. Path Traversal

    • path-traversal-risk: follows dynamic path construction and fetched database values to file operations, directory enumeration and file responses. A stored path served directly is covered without requiring an intermediate Path(...). Construction or normalization alone is not a file operation. Mutation sinks include Path.touch, both paths in rename/replace, and positional/keyword os.remove/os.unlink. The one-target Path.replace signature keeps string and datetime replacements outside the filesystem rule.
    • request-path-traversal-risk: follows route handler parameters and request.* to path construction and filesystem sinks. Database fetch results are handled by the separate dynamic-path rule, so filtering a query by a request ID does not classify the whole stored row as request input. A response's download-name metadata is not its filesystem path.
    • Only returned values from validate_safe_path, validate_data_path, validate_model_path, safe_join, secure_filename and sanitize_filename clear request taint. Exact call and assignment patterns preserve findings for file access inside their arguments and for later use of the original input. Other PathValidator methods and os.path.basename are not sanitizers (basename("..") is still "..").
    • Intraprocedural only: input is not followed into helper bodies. The sanitizer contracts assume a trusted base directory; they do not prove ownership or protect against concurrent local filesystem changes. These rules prompt a boundary review rather than establish safety.
    • Severity: WARNING
    • CWE-22
  6. Unsafe Deserialization

    • Detects unsafe YAML/pickle loading
    • Prevents code execution via deserialization
    • Severity: ERROR
    • CWE-502
  7. Weak Randomness

    • Detects use of random module for security
    • Enforces secrets module for crypto operations
    • Severity: WARNING
    • CWE-338
  8. Debug Mode in Production

    • Detects Flask debug=True
    • Prevents information disclosure
    • Severity: ERROR
    • CWE-489
  9. SSRF Prevention

    • Detects URL fetching operations
    • Reminds to validate URLs
    • Severity: WARNING
    • CWE-918
  10. XSS Prevention

    • Detects user input in HTML context
    • Enforces proper escaping
    • Severity: WARNING
    • CWE-79
  11. CSRF Protection

    • Detects POST endpoints
    • Reminds to enable CSRF protection
    • Severity: INFO
    • CWE-352
  12. Credential Logging

    • Detects passwords in log statements
    • Prevents credential disclosure
    • Severity: ERROR
    • CWE-532

Usage

These rules are automatically run by the Semgrep CI/CD workflow:

# Run locally
semgrep --config=.semgrep/rules/ src/

# Run with standard rules
semgrep --config=p/security-audit --config=.semgrep/rules/ src/

GitHub upload and source suppressions

The pinned Semgrep 1.181.0 omits nosemgrep findings from its JSON report but retains them in native SARIF with inSource suppression metadata. GitHub's SARIF import does not honor that metadata, so uploading the native report would publish the ignored findings as open alerts.

The workflow validates the complete native JSON and SARIF reports, then creates semgrep-results.github.sarif. Only results with recognized inSource suppressions (no status, or accepted) are omitted from that copy, and only when the scanned file holds a reviewed annotation naming the result's rule (see below) on the result's first line or on the line above it. The SARIF suppression does not record which rule a comment named, so the validator reads the line back; a suppressed result without such an annotation fails validation. Unknown suppression kinds or statuses fail validation too. All other findings and scan metadata are preserved, and the upload copy is validated again. Scanner errors, skipped rules, empty scope and mismatched reports still prevent upload.

The diagnostic artifact retains both native reports and the GitHub upload copy for 7 days. Tests using native scanner reports and synthetic fixtures check that suppressing one result preserves every unsuppressed result, including the same rule at other locations and other rules at the same location; the real-scanner test runs three rules on one line, annotates one or two of them, and checks that the strict scan stays error-free and the rest are uploaded.

References: Semgrep source suppressions and GitHub's supported SARIF properties.

Adding New Rules

To add new custom rules:

  1. Create a new YAML file in .semgrep/rules/
  2. Follow Semgrep rule syntax
  3. Test the rule: semgrep --config=.semgrep/rules/your-rule.yaml src/
  4. Document the rule in this README

Reviewed source annotations

Use a rule-specific reviewed annotation beside a reviewed false positive, at the end of the finding's first line or alone on the line above it:

# nosemgrep: semgrep.rules.weak-random-generation, reason: Non-security jitter
delay_seconds = random.randint(1, 30)

Write it exactly as nosemgrep: <rule-id>[, <rule-id>]..., reason: <reason>, starting a comment (#, //, {#, <!-- or /*), with fully qualified rule ids (list several when one line has several reviewed false positives) and no comma in the reason. Semgrep 1.177.0 honours a case-insensitive nosem marker after a space anywhere on a line, including string literals and words such as "NoSemantics", and a marker without a rule id hides every rule on that line. Semgrep also accepts any suffix of a rule id and reads the first word of each comma-separated item after the colon as a rule id. The check-nosemgrep-annotations pre-commit hook rejects every other marker under src/, including one inside a Python string or docstring, and the upload validator rejects a suppressed result without an annotation naming its exact rule id.

The reason: item is required, not decoration. Semgrep reads it as one more id; reason: is not a valid rule id, so it suppresses nothing. But a comment with a single id makes Semgrep 1.177.0 report a warning for every other rule that matches the same line ("found 'nosem' comment with id ..., but no corresponding rule trying ..."), and under --strict that fails the whole scan, and so the release gate. Semgrep skips that warning when a comment holds two or more ids, so with the reason: item a new or updated rule matching an annotated line produces an ordinary uploaded alert instead. If that alert is another reviewed false positive, add its rule id to the annotation.

Keep the rule enabled elsewhere; do not exclude a file or weaken the release threshold to clear an alert. Re-review the annotation when the expression or its input boundary changes.

Reviews in October 2026 identified these cases:

Finding Why the annotated use is safe Existing verification
Seven script interpolations Jinja's tojson escapes HTML delimiters before embedding JSON in a script. Template injection and JSON rendering tests in tests/security/test_injection_and_template_safety.py.
Eleven unquoted attribute expressions Both branches emit fixed selected/checked tokens or the empty string; no input is inserted into an attribute name. Inspect the literal branches in embedding_settings.html; the rest of each attribute remains quoted.
help_tip's safe filter Every current caller passes a source literal, intentionally containing help markup. Review all call sites. The existing security test catches simple variable arguments, but does not fully parse composed Jinja expressions.
Four random calls They control subscription jitter or rate-limit exploration, not credentials, identifiers or authorization. Scheduler and rate-limit tests; cryptographic operations still use secrets.
Two apparent secrets One is an empty API-key default; the other is the existing placeholder only used for unencrypted databases. Configuration and authentication tests retain the surrounding behavior.
Two pickle calls They raise UnpicklingError on rejected globals/extensions rather than loading data. tests/vector_stores/test_faiss_safe_load_security.py exercises hostile payloads, extension caches, persistent IDs and legitimate docstores.
XML import It imports xml.sax.saxutils.escape to encode text, not an XML parser. Note-AI prompt rendering tests.
Evernote TreeBuilder import ElementTree's TreeBuilder only assembles elements. The Evernote loader's XML is read by defusedxml's parser, which refuses entity declarations, external references and any DOCTYPE with an internal subset. tests/document_loaders/test_evernote_extraction.py.
TOML loader's Path(source) The app builds the loader only in load_from_bytes, from the temporary file it has just written; an upload supplies that file's bytes, not its path. No route passes a request value to get_loader_for_path or to the loader. Review the callers of load_from_bytes and get_loader_for_path. tests/document_loaders/test_toml_loader.py loads uploads through load_from_bytes.

The separate DevSkim annotation in services/ui.js covers its fragment-based anchor renderer, which already adds both noopener and noreferrer.

The combined SQL/path rules carry 100 individually reviewed dispositions. They remain local to the reported operation; no source file, directory or rule is excluded:

Findings Reviewed boundary
30 SQL operations Hex-encoded or explicitly checked SQLCipher keys; typed/range-checked or allowlisted PRAGMAs; dialect-quoted identifiers; migration table/column literals; bound row values; a fixed schema-version integer.
Benchmark and indexing APIs Explicit local Python/CLI output or input paths. The web benchmark worker uses its separate database runner rather than these file-output functions.
Package and startup files Fixed filenames and globs beneath installed package paths or operator-configured application directories.
Upload and converter temporary files Server-generated temporary names, allowlisted extensions and validated stems; web upload callers do not provide scratch directories.
Backup retention cleanup Fixed-pattern glob results filtered by is_safe_glob_result under the server-owned, hashed per-user backup directory. Reordering the checked list to preserve the newly finalized backup does not admit another path.
Library/report cleanup Existing root resolution and symlink checks at the destructive operation; document deletion callers require an allowed root. Operator opt-in alone does not establish ownership.
Index persistence and model cache Service-selected index output paths and generated temporary names; curated embedding repository names in the operator model cache.
Five legacy-index sidecar operations All RAGIndex.index_path writes originate in LibraryRAGService, using an operator cache root and hash-based filenames. Login-time rekey loads those rows from the authenticated user's DB and derives a fixed-suffix sidecar; no request/import endpoint assigns the column. This is a writer/caller boundary, not an assumption that arbitrary stored paths are safe. New writers or callers require another review.
Six index rename/replace operations Legacy relocation checks the source root and hash filename; quarantine uses service-generated index paths and timestamp suffixes. Atomic replacements move this call's mkstemp file to the explicit index output or fixed-suffix migration sidecar. The migration discovers non-symlink pickle files under the operator cache root. Each annotation is confined to its individual mutation; arbitrary stored paths remain reportable.

The previously unresolved legacy-library read was fixed separately in #7268. Successful report validation is evidence that the scan is complete, not that the release has no remaining alerts.

Native SQL controls run from .semgrep/tests/ldr-security.py. The standalone path tests invoke the pinned scanner against unsafe and safe cases, including direct request paths, fetched paths, keyword arguments, nested file accesses, ignored/reassigned validation results, metadata-only response filenames and normalization without file access. Relative-path validation only sanitizes the relative argument: a request-selected base directory remains tainted. Forty assigned/inline call controls cover trusted and request-selected roots, including keyword arguments and the default model root. The workflow uses one scanner worker to keep taint findings reproducible.

Rule Template

rules:
  - id: your-rule-id
    pattern: |
      # Your pattern here
    message: Description of the security issue
    languages: [python]
    severity: ERROR  # or WARNING, INFO
    metadata:
      category: security
      cwe: "CWE-XXX: Description"
      owasp: "AXX:2021 - Category"

References