~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(ci): combine SQL and path scanner coverage with reviewed exceptions (#7140)
LearningCircuit1065a973634b
diff --git a/.file-whitelist.txt b/.file-whitelist.txtindex 11114de165..ae62aeaa36 100644--- a/.file-whitelist.txt+++ b/.file-whitelist.txt@@ -70,6 +70,8 @@# pip-compile inputs for the focused CI workflows.^requirements/ci-health\.in$^requirements/gitleaks-tests\.in$+^requirements/semgrep\.in$+^requirements/twine\.in$# ---------------------------------------------------------------------------# Shell scripts — path-scopeddiff --git a/.github/SECURITY_SCORECARD.md b/.github/SECURITY_SCORECARD.mdindex 1034f7cfff..e2c4e9c4d7 100644--- a/.github/SECURITY_SCORECARD.md+++ b/.github/SECURITY_SCORECARD.md@@ -9,7 +9,7 @@ and documents any accepted risks or false positives.- ✅ 196/196 GitHub Actions pinned by SHA- ✅ 4/4 Container images pinned by digest- ✅ 1/1 Security tools use official SHA-pinned actions (zizmor)-- ⚠️ 2/27 pip commands pinned by hash (remainder version-pinned — accepted risk)+- ⚠️ 5/30 pip commands pinned by hash (remainder version-pinned — accepted risk)- ⚠️ 21/24 npm commands pinned (3 are operational commands)- ⚠️ 1 false positive for downloadThenRun- ⚠️ APT packages intentionally unpinned (base image controls versions)@@ -76,7 +76,9 @@ The remaining pip commands use exact version pinning.| mypy-type-check.yml | 39,47-48 | `pip install pdm==2.26.2 mypy==1.14.1...` | Version-pinned || publish.yml | 139,328 | `pip install pdm==2.26.2` `pip install wheel==0.46.2` | Version-pinned || puppeteer-e2e-tests.yml | 65 | `pip install -e .` | Local package |-| semgrep.yml | 50 | `python -m pip install semgrep==1.177.0` | Version-pinned |+| semgrep.yml | Install step | `python -m pip install --require-hashes --only-binary=:all: -r requirements/semgrep.txt` | Hash-pinned (Semgrep 1.179.0) |+| dependency-review.yml | Install step | `python -m pip install --require-hashes --only-binary=:all: -r requirements/dependency-review.txt` | Hash-pinned |+| release-gate.yml | Twine check | `python -m pip install --require-hashes --only-binary=:all: -r requirements/twine.txt` | Hash-pinned || update-precommit-hooks.yml | 35-38 | `pip install pip==25.0` `pip install pre-commit-update==0.6.1` | **Hash-pinned** || validate-image-pinning.yml | 67 | `pip install pyyaml==6.0.2` | Version-pinned |@@ -94,12 +96,12 @@ The remaining pip commands use exact version pinning.> an info-level `IncompatibleRule` error from an upstream rule that needs a newer> Semgrep, a rule timeout (runner-speed dependent, so possibly intermittent), and a> semgrep.dev registry outage while the rulesets are fetched. Remedy for-> `IncompatibleRule`: bump the `semgrep==` pin in `semgrep.yml` (Dependabot does not-> update pins in workflow `run:` lines) and update the line reference above;+> `IncompatibleRule`: bump the `semgrep==` pin in `requirements/semgrep.in`,+> regenerate the hash lock and review the scanner contracts and native controls;> otherwise re-run once the registry recovers.>> A parse error in a scanned file under `src/` also fails the job: with `--strict`,-> Semgrep 1.177.0 exits non-zero on some valid syntax its parsers do not support+> Semgrep 1.179.0 exits non-zero on some valid syntax its parsers do not support> (reported for Python 3.12 mapping patterns with `**rest` in `match`/`case`, and> JavaScript class static blocks). `semgrep.yml`'s `pull_request` trigger includes> `src/**`, so this fails the pull request that adds such code instead of the next@@ -116,7 +118,7 @@ The remaining pip commands use exact version pinning.> integer (`8`) has it copied through, and a score of 4.0 or more then makes its> alerts block releases with no change to the gate. GitHub documents the property> as a string, so whether it maps an integer score is unverified. An unquoted float-> (`7.5`) in a `.semgrep/rules/` file instead crashes Semgrep 1.177.0 ("Invalid YAML+> (`7.5`) in a `.semgrep/rules/` file instead crashes Semgrep 1.179.0 ("Invalid YAML> tree structure ... ScalarFloat"), which fails the job. The report validation> checks the score of every loaded rule, including rules with no finding, and> accepts only a JSON number or a plain ASCII decimal string (`"8"`, `"7.5"`) fromdiff --git a/.github/scripts/check_dependency_licenses.py b/.github/scripts/check_dependency_licenses.pynew file mode 100644index 0000000000..a9ebd84033--- /dev/null+++ b/.github/scripts/check_dependency_licenses.py@@ -0,0 +1,362 @@+#!/usr/bin/env python3+"""Bound package-wide license exceptions to reviewed Python dependencies.++The Dependency Review action ignores versions and manifests in its package+exceptions. Inspect repository requirements/PEP 621/PDM dependencies,+including local requirements includes, before applying those exceptions.+Other Python manifests and unreviewed project configuration fail closed.+"""++from __future__ import annotations++import argparse+import re+import shlex+import subprocess+import sys+import tomllib+from pathlib import Path++from packaging.requirements import Requirement+from packaging.specifiers import InvalidSpecifier, SpecifierSet+from packaging.utils import canonicalize_name+++REVIEWED = {+ "docutils": ("0.23", {"requirements/twine.txt"}),+ "semgrep": (+ "1.179.0",+ {"requirements/semgrep.in", "requirements/semgrep.txt"},+ ),+ "protobuf": ("6.33.6", {"requirements/semgrep.txt"}),+ "typing-extensions": (+ "4.16.0",+ {+ "pyproject.toml",+ "pdm.lock",+ "requirements/bootstrap-builder.txt",+ "requirements/bootstrap-ci.txt",+ "requirements/semgrep.txt",+ },+ ),+}++# These dependency formats/configurations are not parsed by this guard.+# Refuse them even when they currently contain no exempted package: adding+# parser support must precede any package-wide license exception there.+UNSUPPORTED_MANIFESTS = frozenset(+ {+ "setup.py",+ "setup.cfg",+ "pipfile",+ "pipfile.lock",+ "poetry.lock",+ "uv.lock",+ "uv.toml",+ "pdm.toml",+ ".pdm.toml",+ }+)++# New tool schemas may supply dependencies or override their sources without+# using PEP 621. Keep the existing tools; review a schema before adding it.+REVIEWED_TOOL_TABLES = frozenset(+ {"coverage", "mypy", "pdm", "pytest", "ruff", "setuptools", "towncrier"}+)+REVIEWED_PDM_KEYS = frozenset(+ {+ "build",+ "dev-dependencies",+ "distribution",+ "resolution",+ "source",+ "version",+ }+)+REVIEWED_PDM_SOURCE = {+ "name": "torch",+ "url": "https://download.pytorch.org/whl/cpu",+ "include_packages": ["torch", "torch*"],+}++# Keys a legacy-format [[package]] entry may carry without describing a+# direct source. pdm installs from url/git/hg/svn/bzr sources and their+# ref/revision/subdirectory companions (and from a [package.source]+# table), and any unrecognized key could do the same in a future lock+# format, so every package fails closed on anything outside this set.+# PDM can install a differently named distribution from a direct-source+# wheel, so source restrictions cannot depend on the lock's claimed name.+# files entries are additionally inspected for url keys (below).+LOCK_PACKAGE_KEYS = frozenset(+ {+ "name",+ "version",+ "requires_python",+ "summary",+ "groups",+ "files",+ "dependencies",+ "marker",+ "extras",+ }+)+++class PolicyError(ValueError):+ """A dependency cannot be covered by the reviewed exception."""+++def check_requirement(text: str, manifest: str) -> None:+ requirement = Requirement(text)+ name = canonicalize_name(requirement.name)+ if requirement.url:+ # A direct artifact may declare a different distribution name.+ # Do not let an alias put an exempted wheel outside source review.+ raise PolicyError(f"{manifest}: {name}: direct source requires review")+ if name not in REVIEWED:+ return+ version, locations = REVIEWED[name]+ if manifest not in locations:+ raise PolicyError(+ f"{manifest}: {name} is outside its reviewed locations"+ )+ allowed = {f"=={version}"}+ if manifest == "pyproject.toml" and name == "typing-extensions":+ # Preserve the published application constraint. pdm.lock is checked+ # separately; this exception does not freeze consumer installations.+ allowed.add("~=4.15")+ # Never evaluate markers on the CI host: other platforms need review too.+ if str(requirement.specifier) not in allowed:+ raise PolicyError(+ f"{manifest}: {name} requires review (reviewed version: {version})"+ )+++def logical_lines(path: Path):+ pending = ""+ for line in path.read_text(encoding="utf-8").splitlines():+ if line.lstrip().startswith("#") or not line.endswith("\\"):+ # A comment-led line terminates the logical line being+ # joined instead of extending it (pip's join_lines never+ # joins across a comment), so a requirement placed after an+ # interior comment stays visible rather than being hidden.+ line = pending + line+ pending = ""+ else:+ pending += line[:-1]+ continue+ line = re.sub(r"(^|\s+)#.*$", "", line).strip()+ if line:+ yield line+ if pending:+ raise PolicyError(f"{path}: unfinished requirements continuation")+++def check_requirements(+ root: Path, path: Path, origin: str, parents: tuple[Path, ...] = ()+) -> None:+ resolved = path.resolve()+ if not resolved.is_relative_to(root) or resolved in parents:+ raise PolicyError(f"{origin}: external or cyclic requirements include")+ if path.is_symlink():+ raise PolicyError(f"{origin}: symlinked requirements need review")+ for line in logical_lines(path):+ if re.fullmatch(r"--only-binary[=\s]+:all:", line):+ # Emitted by pip-compile for the isolated, wheel-only tool locks.+ continue+ include = re.fullmatch(+ r"(?:-r\s*|-c\s*|--requirement[=\s]+|--constraint[=\s]+)(.+)",+ line,+ )+ if include:+ targets = shlex.split(include[1])+ if len(targets) != 1 or ":" in targets[0] or "$" in targets[0]:+ raise PolicyError(+ f"{origin}: requirements include must be local"+ )+ # Retain the importing environment. An application requirements+ # file must not import the otherwise-approved Semgrep/Twine lock.+ check_requirements(+ root, path.parent / targets[0], origin, (*parents, resolved)+ )+ continue+ # Only hashes are per-requirement options in our committed locks.+ # Other options, bare URLs, editables and environment substitutions+ # are rejected by Requirement instead of being silently skipped.+ line = re.sub(r"\s+--hash(?:=|\s+)\S+", "", line)+ check_requirement(line, origin)+++def check_project_configuration(project: dict) -> None:+ metadata = project.get("project", {})+ dependency_fields = {"dependencies", "optional-dependencies"}+ if dependency_fields.intersection(metadata.get("dynamic", [])):+ raise PolicyError("dynamic dependency metadata needs review")+ tools = project.get("tool", {})+ if unknown := tools.keys() - REVIEWED_TOOL_TABLES:+ raise PolicyError(+ f"unparsed tool schema {sorted(unknown)} needs review"+ )+ if dependency_fields.intersection(+ tools.get("setuptools", {}).get("dynamic", {})+ ):+ raise PolicyError("dynamic setuptools dependency metadata needs review")+ pdm = tools.get("pdm", {})+ if unknown := pdm.keys() - REVIEWED_PDM_KEYS:+ raise PolicyError(+ f"unparsed PDM configuration {sorted(unknown)} needs review"+ )+ # A plain {file, hash} lock entry is still resolved against these indexes.+ # Match the complete reviewed configuration: broadening include_packages,+ # renaming it to pypi, or adding a find_links index can substitute a wheel+ # with the same exempted name/version but different license contents.+ if pdm.get("source", []) not in ([], [REVIEWED_PDM_SOURCE]):+ raise PolicyError("PDM source configuration needs review")+ resolution = pdm.get("resolution", {})+ if unknown := resolution.keys() - {"overrides"}:+ raise PolicyError(+ f"unparsed PDM resolution {sorted(unknown)} needs review"+ )+ for name, value in resolution.get("overrides", {}).items():+ # PDM accepts extras in override keys. They still replace the same+ # distribution; normalize its parsed name rather than the whole key.+ if canonicalize_name(Requirement(name).name) in REVIEWED:+ raise PolicyError(f"{name}: PDM dependency override needs review")+ try:+ SpecifierSet(value)+ except InvalidSpecifier as exc:+ raise PolicyError(+ f"{name}: PDM override must be a version constraint; "+ "other sources need review"+ ) from exc+++def project_requirements(project: dict):+ metadata = project.get("project", {})+ yield from metadata.get("dependencies", [])+ yield from project.get("build-system", {}).get("requires", [])+ for groups in (+ metadata.get("optional-dependencies", {}),+ project.get("dependency-groups", {}),+ project.get("tool", {}).get("pdm", {}).get("dev-dependencies", {}),+ ):+ for group in groups.values():+ # All dependency groups are inspected, so include-group entries+ # do not need to be expanded or evaluated for this environment.+ yield from (entry for entry in group if isinstance(entry, str))+++def repository_paths(root: Path) -> list[Path]:+ result = subprocess.run(+ ["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"],+ cwd=root,+ check=True,+ capture_output=True,+ text=True,+ )+ return [+ Path(name) for name in sorted(set(result.stdout.split("\0"))) if name+ ]+++def validate(root: Path) -> list[str]:+ root = root.resolve()+ errors = []+ for relative in repository_paths(root):+ path = root / relative+ manifest = relative.as_posix()+ name = relative.name.casefold()+ requirements = relative.suffix.casefold() in {".in", ".txt"} and (+ name.startswith("requirements")+ or "requirements"+ in [part.casefold() for part in relative.parts[:-1]]+ )+ unsupported = name in UNSUPPORTED_MANIFESTS or (+ name.startswith("pylock.") and name.endswith(".toml")+ )+ selected = (+ requirements+ or unsupported+ or name in {"pyproject.toml", "pdm.lock"}+ )+ if not selected:+ continue+ try:+ if path.is_symlink() or not path.resolve().is_relative_to(root):+ raise PolicyError("symlinked or external manifests need review")+ if unsupported:+ raise PolicyError("unsupported Python manifest needs review")+ if requirements:+ check_requirements(root, path, manifest)+ elif name == "pyproject.toml":+ project = tomllib.loads(path.read_text(encoding="utf-8"))+ check_project_configuration(project)+ for requirement in project_requirements(project):+ check_requirement(requirement, manifest)+ else:+ lock = tomllib.loads(path.read_text(encoding="utf-8"))+ if "packages" in lock or "lock-version" in lock:+ # pdm also installs from pylock-format locks+ # ([[packages]] with nested [packages.vcs]); this+ # guard parses only the legacy format, so refuse+ # the file rather than check none of it.+ raise PolicyError(+ "pylock-format locks need review"+ " (only the legacy [[package]] format is parsed)"+ )+ # pdm's "static URLs" lock strategy ([metadata] strategy+ # static-urls/static_urls) installs files[].url entries,+ # hash-checked only against the same lock entry's hash,+ # so reject the strategy and any url-carrying entry for+ # all packages; plain {file, hash} entries stay+ # allowed.+ strategies = {+ str(item).replace("-", "_")+ for item in lock.get("metadata", {}).get("strategy", ())+ }+ if lock.get("metadata", {}).get("static_urls", False):+ # PDM also recognizes this legacy strategy spelling.+ strategies.add("static_urls")+ for package in lock.get("package", []):+ # A lock stores a distribution name, not a requirement.+ # Otherwise name[extras] misses REVIEWED here but is+ # parsed as name by check_requirement below, allowing+ # its source to escape review.+ name = canonicalize_name(package["name"], validate=True)+ if not LOCK_PACKAGE_KEYS.issuperset(package):+ raise PolicyError(f"{name}: direct sources need review")+ if "static_urls" in strategies:+ raise PolicyError(+ f"{name}: static-urls lock strategy needs review"+ )+ files = package.get("files", ())+ if any("url" in entry for entry in files):+ raise PolicyError(+ f"{name}: lock file url entries need review"+ )+ check_requirement(f"{name}=={package['version']}", manifest)+ except (ValueError, OSError, KeyError) as exc:+ errors.append(f"{manifest}: {exc}")+ return errors+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "root",+ nargs="?",+ type=Path,+ default=Path(__file__).resolve().parents[2],+ )+ errors = validate(parser.parse_args().root)+ if errors:+ print("Dependency license exception policy failed:", file=sys.stderr)+ for error in errors:+ print(f"- {error}", file=sys.stderr)+ return 1+ print("Dependency license exception policy passed.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.ymlindex 6d99592737..00f665e49b 100644--- a/.github/workflows/dependency-review.yml+++ b/.github/workflows/dependency-review.yml@@ -6,14 +6,7 @@ on:# The osv-scanner and npm-audit in release gate cover dependency vulnerabilities.pull_request:branches: [main, develop]- paths:- - 'pyproject.toml'- - 'pdm.lock'- - 'requirements*.txt'- - 'package.json'- - 'package-lock.json'- - 'tests/ui_tests/package.json'- - 'tests/ui_tests/package-lock.json'+ # Run for every PR: local requirements includes may use arbitrary paths.workflow_dispatch:permissions: {} # Minimal top-level for OSSF Scorecard Token-Permissions@@ -43,6 +36,22 @@ jobs:with:persist-credentials: false+ - name: Set up Python+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'++ - name: Install license guard dependencies+ run: >-+ python -m pip install --require-hashes --only-binary=:all:+ -r requirements/dependency-review.txt++ - name: Test license exception guard+ run: python -m unittest discover -s tests/ci/standalone -p 'test_dependency_licenses.py' -v++ - name: Enforce reviewed license exception scope+ run: python .github/scripts/check_dependency_licenses.py+- name: Dependency Reviewuses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0with:@@ -53,6 +62,7 @@ jobs:# LGPL is excluded per ASF Category X policyallow-licenses: >-MIT,+ MIT-0,Apache-2.0,BSD-2-Clause,BSD-3-Clause,@@ -68,9 +78,22 @@ jobs:OFL-1.1,Zlib,BlueOak-1.0.0- # Allow specific packages with complex license expressions+ # Allow specific packages with complex license expressions.# dompurify is dual-licensed (Apache-2.0 OR MPL-2.0) but npm reports complex SPDX+ # docutils 0.23 is only in the isolated Twine validation environment.+ # Its wheel omits the GPL-covered Emacs source file; metadata reports+ # all source licenses. The guard above rejects application use.+ # Semgrep is an isolated CI CLI, never an application dependency.+ # Protobuf's wheel carries BSD-3-Clause; typing-extensions declares+ # PSF-2.0. GitHub reports extra LicenseRef / historical GPL terms.+ # The guard above checks reviewed versions and manifest locations,+ # including requirements includes and normalized names. Exceptions+ # do not bypass vulnerability review.allow-dependencies-licenses: >-- pkg:npm/dompurify+ pkg:npm/dompurify,+ pkg:pypi/docutils,+ pkg:pypi/semgrep,+ pkg:pypi/protobuf,+ pkg:pypi/typing-extensions# Comment on PR with review summarycomment-summary-in-pr: on-failurediff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.ymlindex a575e342e5..d606291cfa 100644--- a/.github/workflows/release-gate.yml+++ b/.github/workflows/release-gate.yml@@ -464,9 +464,12 @@ jobs:# README renders cleanly on PyPI. pdm build accepts metadata twine# rejects (e.g. malformed long_description), so this catches a class# of "PyPI project page silently broken" failures pip-install-check- # cannot see. Installed transiently inside the throwaway venv.- pip install --quiet twine- twine check --strict dist/*+ # cannot see. Keep validation tools outside the application venv,+ # with reviewed hashes for their complete dependency tree.+ python -m venv /tmp/twine-verify-env+ /tmp/twine-verify-env/bin/python -m pip install --quiet \+ --require-hashes --only-binary=:all: -r requirements/twine.txt+ /tmp/twine-verify-env/bin/twine check --strict dist/*echo ""echo "=== Installing [mcp] extra so ldr-mcp can resolve ==="diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.ymlindex 3a44e3a163..99ae039437 100644--- a/.github/workflows/semgrep.yml+++ b/.github/workflows/semgrep.yml@@ -8,6 +8,7 @@ on:# release gate.- "src/**"- ".github/workflows/semgrep.yml"+ - "requirements/semgrep.*"- ".github/scripts/check_semgrep_report.py"- ".semgrep/**"# Semgrep drops files matched by a .semgrepignore at the root or in@@ -15,6 +16,7 @@ on:- ".semgrepignore"- "**/.semgrepignore"- "tests/ci/standalone/test_semgrep*.py"+ - "tests/ci/test_semgrep_workflow.py"workflow_call: # Called by release-gate.ymlworkflow_dispatch:@@ -47,11 +49,18 @@ jobs:python-version: '3.12'- name: Install Semgrep- run: python -m pip install semgrep==1.177.0+ run: >-+ python -m pip install --require-hashes --only-binary=:all:+ -r requirements/semgrep.txt- name: Verify scanner and report contractsrun: python -m unittest discover -s tests/ci/standalone -p 'test_semgrep*.py' -v+ - name: Verify custom SQL rule controls+ run: >-+ semgrep --test --config .semgrep/rules/ldr-security.yaml+ .semgrep/tests/ldr-security.py+# No --severity filter: it selects exact levels, not a minimum severity.# Scanner/configuration errors must fail this step (--strict, no || true).# Uploading a narrowed report (an extra option such as --exclude or@@ -66,19 +75,15 @@ jobs:# accidental regressions of that kind. It cannot guarantee# anything against a deliberately adversarial edit; changes to this file# and to .semgrepignore need CODEOWNERS review.- # Release blocking: Semgrep copies a rule's metadata.security-severity- # into the SARIF rule's properties["security-severity"], which GitHub maps- # to security_severity_level, the only field release-gate.yml's- # check-code-scanning-alerts counts (medium and above, i.e. a score of 4.0- # or more, blocks). No loaded rule sets it today, so Semgrep alerts do not- # yet block a release (until #6646 falls back to the SARIF level). A- # custom rule in .semgrep/rules/ or an upstream update to- # p/security-audit or p/secrets that adds the metadata as a quoted- # string ("7.5") or an integer (8) has it copied through, and a score of- # 4.0 or more then makes its alerts block releases with no change here+ # Release blocking: the release gate counts unscored SARIF error/warning+ # alerts as well as medium-and-above scored alerts. Semgrep copies a rule's+ # metadata.security-severity into the SARIF rule's+ # properties["security-severity"], which GitHub maps to+ # security_severity_level. A custom rule or upstream registry rule with a+ # score of 4.0 or more blocks a release regardless of its SARIF level# (GitHub documents the property as a string; whether it maps an integer# is unverified). An unquoted float (7.5) in a .semgrep/rules/ file- # instead crashes Semgrep 1.177.0 ("Invalid YAML tree structure ...+ # instead crashes Semgrep 1.179.0 ("Invalid YAML tree structure ...# ScalarFloat"), which fails this job and so the release gate.# check_semgrep_report.py checks the score of every loaded rule, with or# without a finding, and accepts only a JSON number or a plain ASCII@@ -93,10 +98,11 @@ jobs:# Semgrep, and a semgrep.dev registry outage while the p/ packs are# fetched. p/security-audit and p/secrets are fetched live and unpinned,# so these can fail this job with no repo change. Remedy for- # IncompatibleRule: bump the semgrep pin in "Install Semgrep" (Dependabot- # does not update pins in `run:` lines); otherwise re-run once the+ # IncompatibleRule: bump the `semgrep==` pin in `requirements/semgrep.in`,+ # regenerate the hash lock and review the scanner contracts and native+ # controls; otherwise re-run once the# registry recovers. A parse error in a scanned file also fails this job:- # with --strict, Semgrep 1.177.0 exits non-zero on some valid syntax its+ # with --strict, Semgrep 1.179.0 exits non-zero on some valid syntax its# parsers do not support (reported for Python 3.12 mapping patterns with# **rest in `match`/`case`, and JavaScript class static blocks). The# pull_request trigger includes src/** so this fails the PR that adds such@@ -108,6 +114,8 @@ jobs:# cannot tell which config each rule came from, so completeness of the# rulesets rests on the pinned --config list and on Semgrep failing hard# when a config cannot be fetched.+ # Semgrep 1.177.0's 14-worker default produced inconsistent taint findings+ # and rule timeouts under concurrent load. One worker keeps this scan stable.- name: Run Semgrep security scanid: scanrun: |@@ -115,6 +123,7 @@ jobs:--config=p/security-audit \--config=p/secrets \--config=.semgrep/rules/ \+ --jobs=1 \--strict \--metrics=off \--json-output=semgrep-results.json \diff --git a/.semgrep/rules/README.md b/.semgrep/rules/README.mdindex f8a06a7de4..ea95bd77d3 100644--- a/.semgrep/rules/README.md+++ b/.semgrep/rules/README.md@@ -14,7 +14,13 @@ LDR-specific security rules covering:- CWE-7982. **SQL Injection Prevention**- - Detects string concatenation in SQL queries+ - `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; nested raw-SQL constructors remain findings.+ - `sql-execute-with-string-format`: `$X.execute(f"...")` or+ `$X.execute("..." + ...)`- Enforces parameterized queries via SQLAlchemy- Severity: ERROR- CWE-89@@ -32,8 +38,26 @@ LDR-specific security rules covering:- CWE-785. **Path Traversal**- - Detects unsanitized user input in file paths- - Prevents directory traversal attacks+ - `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.+ - `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@@ -93,7 +117,7 @@ semgrep --config=p/security-audit --config=.semgrep/rules/ src/## GitHub upload and source suppressions-Semgrep 1.177.0 omits `nosemgrep` findings from its JSON report but retains+The pinned Semgrep 1.179.0 omits `nosemgrep` findings from its JSON report but retainsthem in native SARIF with `inSource` suppression metadata. GitHub's SARIFimport does not honor that metadata, so uploading the native report wouldpublish the ignored findings as open alerts.@@ -184,6 +208,35 @@ The October 2026 review identified these cases:The separate DevSkim annotation in `services/ui.js` covers its fragment-basedanchor renderer, which already adds both `noopener` and `noreferrer`.+The combined SQL/path rules carry 94 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. The legacy PDF read remains a finding; operator opt-in 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. |++One legacy-library read is intentionally unresolved and still appears in the+uploaded report. 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```yamldiff --git a/.semgrep/rules/ldr-security.yaml b/.semgrep/rules/ldr-security.yamlindex 7ea07bde94..220d9d717f 100644--- a/.semgrep/rules/ldr-security.yaml+++ b/.semgrep/rules/ldr-security.yaml@@ -16,14 +16,157 @@ rules:owasp: "A07:2021 - Identification and Authentication Failures"- id: sql-string-concatenation- pattern-either:- - pattern: |- $QUERY = "..." + $USER_INPUT + "..."- - pattern: |- $QUERY = f"...{$USER_INPUT}..."- - pattern: |- $QUERY = "..." % ($USER_INPUT)- message: Potential SQL injection via string concatenation. Use parameterized queries with SQLAlchemy.+ mode: taint+ pattern-sources:+ # Taint the constructed string, not its inputs: formatting a log label+ # must not taint a value later bound as a SQL parameter.+ - pattern: f"...{$INPUT}..."+ exact: true+ - pattern: '"..." + $INPUT'+ exact: true+ - pattern: '$INPUT + "..."'+ exact: true+ - pattern: '"..." % $INPUT'+ exact: true+ - pattern: '"...".format(...)'+ exact: true+ pattern-sanitizers:+ # SQLAlchemy binds these string values. Sanitize only the formatted+ # value, so nested text()/literal_column()/DDL() SQL remains a sink.+ - patterns:+ - pattern-either:+ - pattern: sqlalchemy.update(...).values(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.update(...).where(...).values(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.insert(...).values(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.select(...).where(..., $COLUMN == $VALUE, ...)+ - pattern: sqlalchemy.select(...).select_from(...).where(..., $COLUMN == $VALUE, ...)+ - pattern: sqlalchemy.update(...).where(..., $COLUMN == $VALUE, ...)+ - pattern: sqlalchemy.delete(...).where(..., $COLUMN == $VALUE, ...)+ - pattern: sqlalchemy.text(...).bindparams(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.TextClause(...).bindparams(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.sql.text(...).bindparams(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.sql.expression.text(...).bindparams(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.sql.expression.TextClause(...).bindparams(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.sql.elements.TextClause(...).bindparams(..., $FIELD=$VALUE, ...)+ - pattern: sqlalchemy.bindparam($NAME, $VALUE, ...)+ - metavariable-pattern:+ metavariable: $VALUE+ pattern-either:+ - pattern: f"...{$INPUT}..."+ - pattern: '"..." + $INPUT'+ - pattern: '"..." % $INPUT'+ - pattern: '"...".format(...)'+ # metavariable-pattern also searches subexpressions. Require the+ # value itself to start with a string, excluding text(f"...").+ - metavariable-regex:+ metavariable: $VALUE+ regex: >-+ (?is)^[frbu]*["']+ - focus-metavariable: $VALUE+ exact: true+ pattern-sinks:+ - patterns:+ - pattern-either:+ - pattern: $DB.execute($SQL, ...)+ - pattern: $DB.execute(statement=$SQL, ...)+ - pattern: $DB.scalar($SQL, ...)+ - pattern: $DB.scalar(statement=$SQL, ...)+ - pattern: $DB.scalars($SQL, ...)+ - pattern: $DB.scalars(statement=$SQL, ...)+ - pattern: $DB.executemany($SQL, ...)+ - pattern: $DB.executescript($SQL, ...)+ - pattern: $DB.exec_driver_sql($SQL, ...)+ - pattern: $DB.exec_driver_sql(statement=$SQL, ...)+ - pattern: sqlalchemy.text($SQL, ...)+ - pattern: sqlalchemy.text(text=$SQL, ...)+ - pattern: sqlalchemy.TextClause($SQL, ...)+ - pattern: sqlalchemy.TextClause(text=$SQL, ...)+ - pattern: sqlalchemy.sql.text($SQL, ...)+ - pattern: sqlalchemy.sql.text(text=$SQL, ...)+ - pattern: sqlalchemy.sql.expression.text($SQL, ...)+ - pattern: sqlalchemy.sql.expression.text(text=$SQL, ...)+ - pattern: sqlalchemy.sql.expression.TextClause($SQL, ...)+ - pattern: sqlalchemy.sql.expression.TextClause(text=$SQL, ...)+ - pattern: sqlalchemy.sql.elements.TextClause($SQL, ...)+ - pattern: sqlalchemy.sql.elements.TextClause(text=$SQL, ...)+ - pattern: sqlalchemy.literal_column($SQL, ...)+ - pattern: sqlalchemy.literal_column(text=$SQL, ...)+ - pattern: sqlalchemy.sql.literal_column($SQL, ...)+ - pattern: sqlalchemy.sql.literal_column(text=$SQL, ...)+ - pattern: sqlalchemy.sql.expression.literal_column($SQL, ...)+ - pattern: sqlalchemy.sql.expression.literal_column(text=$SQL, ...)+ - pattern: sqlalchemy.sql.elements.literal_column($SQL, ...)+ - pattern: sqlalchemy.sql.elements.literal_column(text=$SQL, ...)+ - pattern: sqlalchemy.DDL($SQL, ...)+ - pattern: sqlalchemy.DDL(statement=$SQL, ...)+ - pattern: sqlalchemy.sql.DDL($SQL, ...)+ - pattern: sqlalchemy.sql.DDL(statement=$SQL, ...)+ - pattern: sqlalchemy.schema.DDL($SQL, ...)+ - pattern: sqlalchemy.schema.DDL(statement=$SQL, ...)+ - pattern: sqlalchemy.sql.ddl.DDL($SQL, ...)+ - pattern: sqlalchemy.sql.ddl.DDL(statement=$SQL, ...)+ # Only SQL text is the sink; parameter values are deliberately bound.+ - focus-metavariable: $SQL+ - patterns:+ # column()/ColumnClause() quote identifiers by default. An explicit+ # literal flag makes them raw SQL constructors like literal_column().+ # Unknown flags need review too; only known false values are safe.+ - pattern-either:+ - pattern: sqlalchemy.column($SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.column(text=$SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.column($SQL, $TYPE, $LITERAL, ...)+ - pattern: sqlalchemy.ColumnClause($SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.ColumnClause(text=$SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.ColumnClause($SQL, $TYPE, $LITERAL, ...)+ - pattern: sqlalchemy.sql.column($SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.sql.column(text=$SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.sql.column($SQL, $TYPE, $LITERAL, ...)+ - pattern: sqlalchemy.sql.expression.column($SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.sql.expression.column(text=$SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.sql.expression.column($SQL, $TYPE, $LITERAL, ...)+ - pattern: sqlalchemy.sql.expression.ColumnClause($SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.sql.expression.ColumnClause(text=$SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.sql.expression.ColumnClause($SQL, $TYPE, $LITERAL, ...)+ - pattern: sqlalchemy.sql.elements.ColumnClause($SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.sql.elements.ColumnClause(text=$SQL, ..., is_literal=$LITERAL, ...)+ - pattern: sqlalchemy.sql.elements.ColumnClause($SQL, $TYPE, $LITERAL, ...)+ - metavariable-pattern:+ metavariable: $LITERAL+ patterns:+ - pattern: $FLAG+ - pattern-not: "False"+ - pattern-not: "None"+ - pattern-not: "0"+ - focus-metavariable: $SQL+ - patterns:+ # Also inspect explicitly named SQL/query/statement builders.+ # Natural-language prompts beginning with "Select" or "Create"+ # are not SQL. The OSS engine cannot follow function boundaries.+ - pattern: $QUERY = $SQL+ - metavariable-regex:+ metavariable: $QUERY+ regex: >-+ (?i)(?:[a-z_][a-z0-9_.]*[_.])?(?:sql|query|statement|pragma)(?:_[a-z0-9_]+)?$+ - metavariable-regex:+ metavariable: $SQL+ regex: >-+ (?is)^[frbu]*["']{1,3}(?:\s|\\[rnt]|--[^\r\n]*(?:\r?\n|\\n)|/\*.*?\*/)*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE|CREATE|ALTER|DROP|TRUNCATE|PRAGMA|ATTACH|DETACH|WHERE|GROUP|HAVING|ORDER|JOIN|INNER|OUTER|LEFT|RIGHT|AND|OR|LIMIT|OFFSET|VALUES|SET|UNION|INTERSECT|EXCEPT|EXPLAIN|VACUUM|REINDEX|ANALYZE)\b+ - focus-metavariable: $SQL+ - patterns:+ - pattern: return $SQL+ - pattern-inside: |+ def $BUILDER(...):+ ...+ - metavariable-regex:+ metavariable: $BUILDER+ regex: >-+ (?i)(?:[a-z_][a-z0-9_]*_)?(?:sql|query|statement|pragma)(?:_[a-z0-9_]+)?$+ - metavariable-regex:+ metavariable: $SQL+ regex: >-+ (?is)^[frbu]*["']{1,3}(?:\s|\\[rnt]|--[^\r\n]*(?:\r?\n|\\n)|/\*.*?\*/)*(?:SELECT|WITH|INSERT|UPDATE|DELETE|REPLACE|CREATE|ALTER|DROP|TRUNCATE|PRAGMA|ATTACH|DETACH|WHERE|GROUP|HAVING|ORDER|JOIN|INNER|OUTER|LEFT|RIGHT|AND|OR|LIMIT|OFFSET|VALUES|SET|UNION|INTERSECT|EXCEPT|EXPLAIN|VACUUM|REINDEX|ANALYZE)\b+ - focus-metavariable: $SQL+ message: Dynamically constructed SQL reaches a database operation or named SQL builder. Use parameterized queries; separately validate any required SQL identifiers.languages: [python]severity: ERRORmetadata:@@ -59,11 +202,153 @@ rules:owasp: "A03:2021 - Injection"- id: path-traversal-risk- pattern-either:- - pattern: open($PATH + $USER_INPUT, ...)- - pattern: open(f"{$PATH}/{$USER_INPUT}", ...)- - pattern: Path($USER_INPUT)- - pattern: os.path.join($PATH, $USER_INPUT)+ # Path construction alone is not an access: validation and normalization+ # also call Path(...). Follow dynamic paths to actual filesystem reads,+ # writes, deletes, directory enumeration, or file-serving sinks.+ mode: taint+ pattern-sources:+ - patterns:+ - pattern: Path($PART)+ - pattern-not: Path("...")+ - pattern: os.path.join($BASE, $PART)+ - pattern: |+ f"{$BASE}/{$PART}"+ - pattern: $BASE + $PART+ # A stored path can reach FileResponse/open without being wrapped in+ # Path(). Mark fetched values, not the query inputs, for review too.+ - patterns:+ - pattern: $QUERY.$FETCH(...)+ - metavariable-regex:+ metavariable: $FETCH+ regex: ^(first|one|one_or_none|all|scalar|scalar_one|scalar_one_or_none|scalars|fetchone|fetchall)$+ exact: true+ pattern-sinks:+ - patterns:+ - pattern-either:+ - pattern: open($PATH, ...)+ - pattern: open(file=$PATH, ...)+ - pattern: io.open($PATH, ...)+ - pattern: io.open(file=$PATH, ...)+ - pattern: aiofiles.open($PATH, ...)+ - pattern: aiofiles.open(file=$PATH, ...)+ - pattern: os.open($PATH, ...)+ - pattern: os.listdir($PATH)+ - pattern: os.scandir($PATH)+ - pattern: $PATH.open(...)+ - pattern: $PATH.read_text(...)+ - pattern: $PATH.read_bytes(...)+ - pattern: $PATH.write_text(...)+ - pattern: $PATH.write_bytes(...)+ - pattern: $PATH.iterdir(...)+ - pattern: $PATH.glob(...)+ - pattern: $PATH.rglob(...)+ - pattern: $PATH.unlink(...)+ - pattern: $PATH.mkdir(...)+ - pattern: $PATH.rmdir(...)+ - pattern: shutil.rmtree($PATH, ...)+ - pattern: FileResponse($PATH, ...)+ - pattern: FileResponse(path=$PATH, ...)+ - pattern: send_file($PATH, ...)+ - pattern: send_file(path_or_file=$PATH, ...)+ - focus-metavariable: $PATH+ message: Dynamic path reaches a file operation. Validate containment and ownership.+ languages: [python]+ severity: WARNING+ metadata:+ category: security+ cwe: "CWE-22: Path Traversal"+ owasp: "A01:2021 - Broken Access Control"+++ - id: request-path-traversal-risk+ # Taint rule: request-controlled data (route handler parameters, which+ # include Request, UploadFile and Depends values, and request.*)+ # reaching a filesystem path sink in the same function. The previous+ # syntactic pattern matched every Path(x) call, including literals and+ # internal configuration. Limitation: Semgrep OSS taint is+ # intraprocedural, so input passed into a helper that builds the path+ # is only caught if the helper itself reads request.*.+ mode: taint+ pattern-sources:+ - patterns:+ - pattern-inside: |+ @$ROUTER.$METHOD(...)+ def $FUNC(..., $PARAM, ...):+ ...+ - metavariable-regex:+ metavariable: $METHOD+ regex: ^(get|post|put|patch|delete|head|options|api_route|websocket|route)$+ - focus-metavariable: $PARAM+ - pattern: request.$ATTR+ pattern-sanitizers:+ # These helpers validate the relative path, not the trustworthiness of+ # their base directory. Sanitize only that argument so request-derived+ # roots still reach the returned path and file operation. Exact matches+ # keep file operations nested inside an argument visible.+ - patterns:+ - pattern-either:+ - pattern: PathValidator.validate_safe_path($INPUT, ...)+ - pattern: PathValidator.validate_safe_path(..., user_input=$INPUT, ...)+ - pattern: PathValidator.validate_data_path($INPUT, ...)+ - pattern: PathValidator.validate_data_path(..., file_path=$INPUT, ...)+ - pattern: PathValidator.validate_model_path($INPUT, ...)+ - pattern: PathValidator.validate_model_path(..., model_path=$INPUT, ...)+ - pattern: safe_join($ROOT, ..., $INPUT, ...)+ - focus-metavariable: $INPUT+ exact: true+ - pattern-either:+ - pattern: secure_filename(...)+ - pattern: $SAFE = secure_filename(...)+ - pattern: sanitize_filename(...)+ - pattern: $SAFE = sanitize_filename(...)+ exact: true+ # Rows loaded from the database: filtering a query by a request value+ # does not make the stored row request-controlled. Stored values are+ # outside this rule's request-to-sink scope.+ - patterns:+ - pattern-either:+ - pattern: $QUERY.$FETCH()+ - pattern: $ROW = $QUERY.$FETCH()+ - metavariable-regex:+ metavariable: $FETCH+ regex: ^(first|one|one_or_none|all|scalar|scalar_one|scalar_one_or_none|scalars|fetchone|fetchall)$+ exact: true+ pattern-sinks:+ - patterns:+ - pattern-either:+ - pattern: open($PATH, ...)+ - pattern: open(file=$PATH, ...)+ - pattern: io.open($PATH, ...)+ - pattern: io.open(file=$PATH, ...)+ - pattern: aiofiles.open($PATH, ...)+ - pattern: aiofiles.open(file=$PATH, ...)+ - focus-metavariable: $PATH+ - pattern: Path(...)+ - pattern: PurePath(...)+ - pattern: os.path.join(...)+ - pattern: $BASE.joinpath(...)+ - patterns:+ # pathlib "/" only; a path-like left operand keeps arithmetic+ # division on request values out of scope.+ - pattern: $BASE / $PATH+ - metavariable-regex:+ metavariable: $BASE+ regex: (?i)((Pure\w*)?Path\(|.*(path|dir|directory|root|folder|base|home)\w*\)?$|.*\.parent$)+ - focus-metavariable: $PATH+ - patterns:+ - pattern-either:+ - pattern: FileResponse($PATH, ...)+ - pattern: FileResponse(path=$PATH, ...)+ - pattern: send_file($PATH, ...)+ - pattern: send_file(path_or_file=$PATH, ...)+ - focus-metavariable: $PATH+ - pattern: send_from_directory(...)+ - pattern: shutil.$FN(...)+ - patterns:+ - pattern: os.$FN(...)+ - metavariable-regex:+ metavariable: $FN+ regex: ^(remove|unlink|rename|replace|rmdir|removedirs|makedirs|mkdir|listdir|scandir|open|walk|chmod|chown|symlink|link)$message: Potential path traversal vulnerability. Validate and sanitize user-provided file paths.languages: [python]severity: WARNINGdiff --git a/.semgrep/tests/ldr-security.py b/.semgrep/tests/ldr-security.pynew file mode 100644index 0000000000..9f3fefee70--- /dev/null+++ b/.semgrep/tests/ldr-security.py@@ -0,0 +1,491 @@+import sqlalchemy as sa+import sqlalchemy.schema as sa_schema+import sqlalchemy.sql as sa_sql+import sqlalchemy.sql.ddl as sa_ddl+import sqlalchemy.sql.elements as sa_elements+import sqlalchemy.sql.expression as sa_expression+from sqlalchemy.sql import text as nested_text+from sqlalchemy.sql.elements import TextClause+from sqlalchemy.sql.expression import text as expression_text+++def plain_url(host):+ # ok: sql-string-concatenation+ url = f"https://{host}/content"+ return url+++def plain_log(user):+ # ok: sql-string-concatenation+ message = f"Requested by {user}"+ return message+++def plain_key(provider):+ # ok: sql-string-concatenation+ key = "settings." + provider + ".url"+ return key+++def plain_selection_prompt(topic):+ # ok: sql-string-concatenation+ prompt = f"Select the most relevant sources for {topic}"+ return prompt+++def plain_creation_prompt(topic):+ # ok: sql-string-concatenation+ return f"Create a summary of research about {topic}"+++def plain_sql_error(kind):+ # ok: sql-string-concatenation+ message = f"PRAGMA rekey failed ({kind})"+ return message+++def direct_fstring(db, user):+ # ruleid: sql-string-concatenation, sql-execute-with-string-format+ db.execute(f"SELECT * FROM records WHERE owner = '{user}'")+++def stored_fstring(db, user):+ # ruleid: sql-string-concatenation+ statement = f"SELECT * FROM records WHERE owner = '{user}'"+ # ruleid: sql-string-concatenation+ db.execute(statement)+++def stored_percent(db, user):+ # ruleid: sql-string-concatenation+ statement = "SELECT * FROM records WHERE owner = '%s'" % user+ # ruleid: sql-string-concatenation+ db.execute(statement)+++def stored_concat(db, user):+ # ruleid: sql-string-concatenation+ statement = "SELECT * FROM records WHERE owner = '" + user + "'"+ # ruleid: sql-string-concatenation+ db.execute(statement)+++def stored_format(db, user):+ # ruleid: sql-string-concatenation+ statement = "SELECT * FROM records WHERE owner = '{}'".format(user)+ # ruleid: sql-string-concatenation+ db.execute(statement)+++def alias_flow(db, user):+ raw = f"{user}"+ alias = raw+ # ruleid: sql-string-concatenation+ db.execute(alias)+++def batch_flow(db, user, rows):+ statement = f"{user}"+ # ruleid: sql-string-concatenation+ db.executemany(statement, rows)+++def script_flow(db, user):+ statement = f"{user}"+ # ruleid: sql-string-concatenation+ db.executescript(statement)+++def driver_flow(db, user):+ statement = f"{user}"+ # ruleid: sql-string-concatenation+ db.exec_driver_sql(statement)+++def sql_text_flow(db, user):+ statement = f"{user}"+ # ruleid: sql-string-concatenation+ query = sa.text(statement)+ # ruleid: sql-string-concatenation+ db.execute(query)+++def returned_sql(user):+ # ruleid: sql-string-concatenation+ return f"SELECT * FROM records WHERE owner = '{user}'"+++def stored_cross_function_sql(user):+ # ruleid: sql-string-concatenation+ statement = f"SELECT * FROM records WHERE owner = '{user}'"+ return statement+++def safe_parameterized(db, user):+ # ok: sql-string-concatenation+ label = f"Requested by {user}"+ # ok: sql-string-concatenation+ db.execute("SELECT * FROM records WHERE owner = ?", (user,))+ return label+++def safe_formatted_parameter(db, user):+ parameters = (f"{user}",)+ # ok: sql-string-concatenation+ db.execute("SELECT * FROM records WHERE owner = ?", parameters)+++def safe_fixed_statement(db):+ statement = "SELECT * FROM records"+ # ok: sql-string-concatenation+ db.execute(statement)+++def sql_comment_builder(user):+ # ruleid: sql-string-concatenation+ statement = f"-- note\nSELECT id FROM records WHERE owner = '{user}'"+ return statement+++def sql_fragment_builder(user):+ # ruleid: sql-string-concatenation+ statement = f" WHERE owner = '{user}'"+ return statement+++def escaped_newline_builder(user):+ # ruleid: sql-string-concatenation+ statement = f"\nSELECT * FROM records WHERE owner = '{user}'"+ return statement+++def safe_orm_update(db, model, user):+ statement = sa.update(model).values(owner=f"{user}")+ # ok: sql-string-concatenation+ db.execute(statement)+++def safe_orm_select(db, model, user):+ statement = sa.select(model).where(model.owner == f"{user}")+ # ok: sql-string-concatenation+ db.execute(statement)+++def safe_orm_insert(db, model, user):+ statement = sa.insert(model).values(owner=f"{user}")+ # ok: sql-string-concatenation+ db.execute(statement)+++def safe_orm_delete(db, model, user):+ statement = sa.delete(model).where(model.owner == f"{user}")+ # ok: sql-string-concatenation+ db.execute(statement)+++def safe_orm_update_filter(db, model, user):+ statement = (+ sa.update(model).where(model.owner == f"{user}").values(owner="fixed")+ )+ # ok: sql-string-concatenation+ db.execute(statement)+++def safe_sql_text_bindparams(db, user):+ statement = sa.text(+ "SELECT * FROM records WHERE owner = :owner"+ ).bindparams(owner=f"{user}")+ # ok: sql-string-concatenation+ db.execute(statement)+++def safe_bindparam_value(db, model, user):+ owner = sa.bindparam("owner", f"{user}")+ statement = sa.select(model).where(model.owner == owner)+ # ok: sql-string-concatenation+ db.execute(statement)+++def unsafe_sql_text_in_orm(db, model, user):+ # ruleid: sql-string-concatenation+ statement = sa.update(model).values(owner=sa.text(f"'{user}'"))+ # ruleid: sql-string-concatenation+ db.execute(statement)+++def unsafe_literal_column_in_orm(db, model, user):+ # ruleid: sql-string-concatenation+ statement = sa.select(sa.literal_column(f"{user}"))+ # ruleid: sql-string-concatenation+ db.execute(statement)+++def unsafe_ddl(db, user):+ # ruleid: sql-string-concatenation+ statement = sa.DDL(f"DROP TABLE {user}")+ # ruleid: sql-string-concatenation+ db.execute(statement)+++def keyword_driver_flow(db, user):+ # Avoid the named-builder fallback: this must be detected at execution.+ command = f"SELECT * FROM records WHERE owner = '{user}'"+ # ruleid: sql-string-concatenation+ db.exec_driver_sql(statement=command)+++def keyword_execute_flow(db, user):+ raw = "SELECT * FROM records WHERE owner = '{}'".format(user)+ # ruleid: sql-string-concatenation+ command = sa.text(text=raw)+ # ruleid: sql-string-concatenation+ db.execute(statement=command)+++def keyword_literal_column_flow(db, user):+ raw = "'" + user + "'"+ # ruleid: sql-string-concatenation+ command = sa.select(sa.literal_column(type_=sa.String, text=raw))+ # ruleid: sql-string-concatenation+ db.execute(statement=command)+++def keyword_ddl_flow(db, user):+ command = "DROP TABLE %s" % user+ # ruleid: sql-string-concatenation+ db.execute(statement=sa.DDL(context={}, statement=command))+++def safe_keyword_driver_parameter(db, user):+ parameters = (f"{user}",)+ # ok: sql-string-concatenation+ db.exec_driver_sql(+ parameters=parameters,+ statement="SELECT * FROM records WHERE owner = ?",+ )+++def safe_keyword_execute_parameter(db, user):+ parameters = {"owner": f"{user}"}+ # ok: sql-string-concatenation+ db.execute(+ parameters=parameters,+ statement=sa.text(text="SELECT * FROM records WHERE owner = :owner"),+ )+++def safe_keyword_orm_bound_value(db, model, user):+ command = sa.select(model).where(model.owner == f"{user}")+ # ok: sql-string-concatenation+ db.execute(statement=command)+++def safe_keyword_fixed_constructors(db):+ # ok: sql-string-concatenation+ db.execute(statement=sa.select(sa.literal_column(text="owner")))+ # ok: sql-string-concatenation+ db.execute(statement=sa.DDL(statement="CREATE TABLE example (id INTEGER)"))+++def safe_keyword_select_from_bound_value(db, user):+ command = (+ sa.select(sa.column("name"))+ .select_from(sa.table("records"))+ .where(sa.column("name") == f"{user}")+ )+ # ok: sql-string-concatenation+ db.execute(statement=command)+++def unsafe_keyword_select_from_with_bound_value(db, table, user):+ # A bound WHERE value must not sanitize the constructed FROM clause.+ # ruleid: sql-string-concatenation+ source = sa.text(text=f"{table}")+ command = (+ sa.select(sa.column("name"))+ .select_from(source)+ .where(sa.column("name") == f"{user}")+ )+ # ruleid: sql-string-concatenation+ db.execute(statement=command)+++def scalar_positional_flow(db, user):+ payload = f"SELECT name FROM records WHERE owner = '{user}'"+ # ruleid: sql-string-concatenation+ return db.scalar(nested_text(payload))+++def scalar_keyword_flow(db, user):+ payload = "SELECT name FROM records WHERE owner = '%s'" % user+ # ruleid: sql-string-concatenation+ return db.scalar(statement=expression_text(text=payload))+++def scalars_positional_flow(db, user):+ payload = "SELECT name FROM records WHERE owner = '" + user + "'"+ # ruleid: sql-string-concatenation+ return db.scalars(nested_text(payload)).all()+++def scalars_keyword_flow(db, user):+ payload = "SELECT name FROM records WHERE owner = '{}'".format(user)+ # ruleid: sql-string-concatenation+ return db.scalars(parameters={}, statement=TextClause(text=payload)).all()+++def safe_scalar_bound_parameters(db, user):+ command = nested_text("SELECT name FROM records WHERE owner = :owner")+ # ok: sql-string-concatenation+ db.scalar(command, {"owner": f"{user}"})+ # ok: sql-string-concatenation+ db.scalar(statement=command, parameters={"owner": f"{user}"})+++def safe_scalars_bound_parameters(db, user):+ command = TextClause(text="SELECT name FROM records WHERE owner = :owner")+ # ok: sql-string-concatenation+ db.scalars(command, {"owner": f"{user}"})+ # ok: sql-string-concatenation+ db.scalars(parameters={"owner": f"{user}"}, statement=command)+++def safe_scalar_orm_bound_values(db, model, user):+ command = sa.select(model).where(model.owner == f"{user}")+ # ok: sql-string-concatenation+ db.scalar(command)+ # ok: sql-string-concatenation+ db.scalars(statement=command)+++def unsafe_text_constructor_exports(user):+ payload = f"SELECT name FROM records WHERE owner = '{user}'"+ # ruleid: sql-string-concatenation+ sa.TextClause(payload)+ # ruleid: sql-string-concatenation+ sa.TextClause(text=payload)+ # ruleid: sql-string-concatenation+ sa_sql.text(payload)+ # ruleid: sql-string-concatenation+ sa_sql.text(text=payload)+ # ruleid: sql-string-concatenation+ sa_expression.text(payload)+ # ruleid: sql-string-concatenation+ sa_expression.text(text=payload)+ # ruleid: sql-string-concatenation+ sa_expression.TextClause(payload)+ # ruleid: sql-string-concatenation+ sa_expression.TextClause(text=payload)+ # ruleid: sql-string-concatenation+ sa_elements.TextClause(payload)+ # ruleid: sql-string-concatenation+ sa_elements.TextClause(text=payload)+++def unsafe_literal_column_exports(user):+ payload = f"name = '{user}'"+ # ruleid: sql-string-concatenation+ sa_sql.literal_column(payload)+ # ruleid: sql-string-concatenation+ sa_sql.literal_column(text=payload)+ # ruleid: sql-string-concatenation+ sa_expression.literal_column(payload)+ # ruleid: sql-string-concatenation+ sa_expression.literal_column(text=payload)+ # ruleid: sql-string-concatenation+ sa_elements.literal_column(payload)+ # ruleid: sql-string-concatenation+ sa_elements.literal_column(text=payload)+++def unsafe_ddl_constructor_exports(user):+ payload = f"CREATE TABLE {user} (id INTEGER)"+ # ruleid: sql-string-concatenation+ sa_sql.DDL(payload)+ # ruleid: sql-string-concatenation+ sa_sql.DDL(statement=payload)+ # ruleid: sql-string-concatenation+ sa_schema.DDL(payload)+ # ruleid: sql-string-concatenation+ sa_schema.DDL(statement=payload)+ # ruleid: sql-string-concatenation+ sa_ddl.DDL(payload)+ # ruleid: sql-string-concatenation+ sa_ddl.DDL(statement=payload)+++def safe_constructor_exports_with_bound_values(db, user):+ # Each alternate text constructor still binds plain string parameters.+ # ok: sql-string-concatenation+ db.scalar(sa.TextClause("SELECT :owner").bindparams(owner=f"{user}"))+ # ok: sql-string-concatenation+ db.scalar(sa_sql.text("SELECT :owner").bindparams(owner=f"{user}"))+ # ok: sql-string-concatenation+ db.scalar(sa_expression.text("SELECT :owner").bindparams(owner=f"{user}"))+ # ok: sql-string-concatenation+ db.scalar(+ sa_expression.TextClause("SELECT :owner").bindparams(owner=f"{user}")+ )+ # ok: sql-string-concatenation+ db.scalar(+ sa_elements.TextClause("SELECT :owner").bindparams(owner=f"{user}")+ )+++def unsafe_alias_sql_with_bound_value(db, table, user):+ # Binding one field cannot sanitize SQL text constructed in another.+ payload = f"SELECT name FROM {table} WHERE owner = :owner"+ # ruleid: sql-string-concatenation+ command = sa_elements.TextClause(payload)+ command = command.bindparams(owner=f"{user}")+ # ruleid: sql-string-concatenation+ db.scalars(statement=command)+++def unsafe_explicit_literal_column_exports(user, literal_mode):+ payload = f"name = '{user}'"+ # ruleid: sql-string-concatenation+ sa.column(payload, is_literal=True)+ # ruleid: sql-string-concatenation+ sa.column(text=payload, is_literal=True)+ # ruleid: sql-string-concatenation+ sa.ColumnClause(payload, None, True)+ # ruleid: sql-string-concatenation+ sa.ColumnClause(is_literal=True, text=payload)+ # ruleid: sql-string-concatenation+ sa_sql.column(payload, is_literal=True)+ # ruleid: sql-string-concatenation+ sa_sql.column(payload, None, True)+ # ruleid: sql-string-concatenation+ sa_expression.column(text=payload, is_literal=True)+ # ruleid: sql-string-concatenation+ sa_expression.column(payload, None, True)+ # ruleid: sql-string-concatenation+ sa_expression.ColumnClause(payload, is_literal=True)+ # ruleid: sql-string-concatenation+ sa_expression.ColumnClause(text=payload, is_literal=True)+ # ruleid: sql-string-concatenation+ sa_elements.ColumnClause(payload, None, True)+ # ruleid: sql-string-concatenation+ sa_elements.ColumnClause(text=payload, is_literal=True)+ # Unknown flags can enable literal SQL, and truthy values also do so.+ # ruleid: sql-string-concatenation+ sa.column(payload, is_literal=literal_mode)+ # ruleid: sql-string-concatenation+ sa.column(payload, None, 1)+++def safe_quoted_column_exports(user):+ payload = f"{user}"+ # ok: sql-string-concatenation+ sa.column(payload)+ # ok: sql-string-concatenation+ sa.ColumnClause(payload, is_literal=False)+ # ok: sql-string-concatenation+ sa_sql.column(payload, None, False)+ # ok: sql-string-concatenation+ sa_expression.column(is_literal=False, text=payload)+ # ok: sql-string-concatenation+ sa_expression.ColumnClause(payload, None, None)+ # ok: sql-string-concatenation+ sa_elements.ColumnClause(text=payload, is_literal=0)diff --git a/changelog.d/+ci-tool-hash-locks.bugfix.md b/changelog.d/+ci-tool-hash-locks.bugfix.mdnew file mode 100644index 0000000000..1eefa1c492--- /dev/null+++ b/changelog.d/+ci-tool-hash-locks.bugfix.md@@ -0,0 +1,14 @@+Verify hashes for Semgrep and package metadata validation dependencies in CI,+and keep validation tools separate from the application install checks.+Use Semgrep 1.179.0 with PyJWT 2.15.1 so the scanner's isolated dependency lock+includes the published JWT security fixes.+Review the scanner's package license metadata separately from runtime policy;+retain vulnerability checks and require review when scanner versions change.+Enforce reviewed license versions and manifest locations directly in Dependency+Review, including plain requirements, normalized names and local includes.+Reject unparsed Python dependency manifests and unreviewed package sources so+package-wide license exceptions cannot silently extend to another environment+or an alternate wheel with the same name and version.+Validate bare lock package names before applying source restrictions.+Apply source restrictions to all dependencies so artifact names cannot hide+an exempted package behind a different declared name.diff --git a/changelog.d/+semgrep-rule-precision.bugfix.md b/changelog.d/+semgrep-rule-precision.bugfix.mdnew file mode 100644index 0000000000..08847b2b8f--- /dev/null+++ b/changelog.d/+semgrep-rule-precision.bugfix.md@@ -0,0 +1 @@+Combine SQL execution-flow checks with separate request-path and dynamic-path file-operation checks. Cover inline SQL, directly served database paths, keyword arguments and file access nested inside validation calls while preserving bound SQL values and download-name metadata. Relative-path validation leaves request-controlled base directories visible to the scanner. Reviewed SQL and filesystem operations carry rule-specific annotations explaining their input boundaries; unresolved legacy-path findings remain visible. Scanner tools use hash-locked dependencies and regression checks run before the complete single-worker scan.diff --git a/changelog.d/+semgrep-sql-dataflow.bugfix.md b/changelog.d/+semgrep-sql-dataflow.bugfix.mdnew file mode 100644index 0000000000..de38fac841--- /dev/null+++ b/changelog.d/+semgrep-sql-dataflow.bugfix.md@@ -0,0 +1,9 @@+Make the SQL scanner follow constructed strings into database operations and+recognizable SQL builders, keeping ordinary URL, setting-key, and log formatting+out of SQL injection findings. Add native rule controls for unsafe SQL and+parameterized queries, including SQLAlchemy SQL text passed by keyword and+scalar/scalars execution through alternate text constructors.+Cover SQLAlchemy text, literal-column and DDL constructor exports in helpers,+while preserving bound-value handling for each text constructor.+Inspect column constructors when their literal flag allows raw SQL, while+leaving quoted identifier construction outside the constructor checks.diff --git a/pyproject.toml b/pyproject.tomlindex df49f3a591..54b5b81e76 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -403,6 +403,7 @@ unfixable = []dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"[tool.ruff.lint.per-file-ignores]+".semgrep/tests/ldr-security.py" = ["S608", "RET504"] # Intentional SQL rule controls and assignment-flow cases.# Tests: assert is the standard pattern; hardcoded values are test fixtures; print is fine"tests/**" = ["S101", "S104", "S105", "S106", "S107", "S108", "S113", "S311", "S324", "S602", "S608", "T20", "TRY201", "G004", "C420", "TRY002", "C408", "C401", "C416", "C414", "PERF102", "PERF402", "PERF403", "RET503", "RET504", "TRY301"]# Examples: hardcoded values are demo fixtures; print is fine; bare exceptions acceptablediff --git a/requirements/README.md b/requirements/README.mdnew file mode 100644index 0000000000..663158fe43--- /dev/null+++ b/requirements/README.md@@ -0,0 +1,92 @@+# CI dependency locks++The bootstrap and focused CI requirement files pin complete dependency trees+with SHA256 hashes. Regenerate `.in` files using the pip-tools command in their+headers on Python 3.12, and review version and hash changes before committing+the input and export together. Installs use `--require-hashes`.++Semgrep is pinned to 1.179.0, whose default ignore rules are modeled by the report+integrity tests. Twine is pinned to the current 7.0.0 release and runs in its own+virtual environment so it cannot change application dependencies under test.+Both tool installs require binary wheels. The application wheel and sdist checks+continue to use fresh pip resolution of the shipped package metadata; these CI+tool locks do not constrain application dependencies.++The Semgrep input also requires PyJWT >=2.15.1 so regeneration cannot retain the+vulnerable 2.13.0 transitive dependency used by Semgrep and its MCP client.+Semgrep 1.179.0 is the first release that permits this dependency upgrade; older+versions require PyJWT 2.13.x. This security floor applies to the isolated scanner+environment.++### Reviewed scanner license metadata++Dependency review adds MIT-0 to its general license list alongside these+changes. The package-level exceptions for the isolated scanner were reviewed at+Semgrep 1.179.0, protobuf 6.33.6 and typing-extensions 4.16.0. Docutils 0.23 is+reviewed only in the isolated Twine lock. The action ignores versions and+manifest locations in exception PURLs, so+`.github/scripts/check_dependency_licenses.py` runs in the Dependency Review+job before the action can apply these exceptions. Its parser and+command-line regression tests run in the same job, using only the+hash-locked `packaging` dependency in `dependency-review.txt`.++The guard checks every tracked or new, non-ignored requirements manifest+(`requirements*.in`, `requirements*.txt`, and `.in`/`.txt` files under any+`requirements/` directory), plus every `pyproject.toml` and `pdm.lock`.+Manifest discovery is case-insensitive; reviewed locations remain exact.+It parses plain and hash-continued requirements, normalizes package names, and+checks markers regardless of the CI host. Local `-r` and `-c` includes retain+the importing environment's restrictions. Remote includes, editables, direct+artifact URLs (including named PEP 508 URLs), environment substitutions and+unsupported pip options fail the check for every dependency.+In `pdm.lock`, package names must be valid bare distribution names; extras,+version specifiers, URLs, and whitespace in a name cannot bypass source checks.+All packages must resolve from the legacy lock format's+index metadata: direct-source keys on their entries (`url`, `git`, `hg`,+`svn`, `bzr`, VCS revisions, subdirectories, source tables or any other+unrecognized key) are rejected, and pylock-format locks (`[[packages]]` with+a top-level `lock-version`) fail closed because the guard does not parse+them. The workflow runs for every PR so changes to an included file cannot+evade it.++Unparsed Python manifests (`setup.py`, `setup.cfg`, `Pipfile`, `Pipfile.lock`,+`poetry.lock`, `uv.lock`, `pylock.toml`, and `pylock.*.toml`) fail closed at any repository+depth. The guard never executes packaging scripts. Pyproject dependencies+must use the parsed PEP 621, build-system, dependency-group, or PDM development+sections. Dynamic dependency metadata and new tool schemas (including Poetry,+uv, Hatch, and Pixi) require parser/policy review first. Existing setuptools+package-data and dynamic version metadata remain supported.++Source restrictions cover all packages because PDM can install a wheel whose+distribution name differs from the manifest's claimed name. Restricting only+the four exempted names would allow another name to conceal an exempted wheel.++PDM sources may be absent (default PyPI) or exactly the existing PyTorch CPU+index limited to `torch` and `torch*`. Any other index configuration, extra+source fields, source glob changes, or project-local `pdm.toml`/`.pdm.toml`+configuration requires review. This prevents an alternate index or local+`find_links` directory from supplying an exempted package under the same name+and version, even with a matching wheel hash in `pdm.lock`. Standalone+`uv.toml`, unparsed PDM options, and overrides of exempted dependencies also+fail closed. Other PDM overrides must be version constraints; the current+requests/lxml resolution overrides remain supported.+This source policy covers committed configuration, not ambient machine+configuration or arbitrary commands outside the dependency manifests.++The explicit version and location policy keeps Semgrep in its scanner files,+protobuf in the scanner lock, and docutils in the Twine lock. Typing-extensions+is already an application dependency: its existing `~=4.15` project constraint+remains, while the application and CI locks must resolve to reviewed 4.16.0.+New versions, locations or requirement forms need an explicit policy review.+This checks committed dependencies; it does not constrain versions installed+by package consumers. Vulnerability checks still apply to every package, and+LGPL/GPL are not added to the general license list.++- [Semgrep's tagged LGPL-2.1 license](https://github.com/semgrep/semgrep/blob/v1.179.0/LICENSE)+ covers the CLI used in CI; it is not included in LDR's runtime dependencies.+- [Protobuf's tagged license](https://github.com/protocolbuffers/protobuf/blob/v33.6/LICENSE)+ matches the installed wheel's BSD-3-Clause text. GitHub additionally reports+ `LicenseRef-scancode-protobuf`.+- [typing-extensions' tagged license](https://github.com/python/typing_extensions/blob/4.16.0/LICENSE)+ matches the wheel's license file; the wheel declares `PSF-2.0`. GitHub's+ expression includes GPL wording from the historical Python license text.diff --git a/requirements/dependency-review.txt b/requirements/dependency-review.txtnew file mode 100644index 0000000000..79af2f7688--- /dev/null+++ b/requirements/dependency-review.txt@@ -0,0 +1,4 @@+# Standalone license-policy guard. No application or scanner installation.+# packaging is also reviewed and hash-pinned in bootstrap-ci.txt.+packaging==26.3 \+ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1cdiff --git a/requirements/semgrep.in b/requirements/semgrep.innew file mode 100644index 0000000000..eb6e5d68a0--- /dev/null+++ b/requirements/semgrep.in@@ -0,0 +1,5 @@+# Python 3.12 on Linux. Regenerate using pip-tools 7.6.1:+# pip-compile --generate-hashes --strip-extras --no-emit-index-url --no-emit-trusted-host --index-url=https://pypi.org/simple --pip-args=--only-binary=:all: requirements/semgrep.in+semgrep==1.179.0+# Keep scanner authentication dependencies above the published PyJWT fixes.+pyjwt>=2.15.1diff --git a/requirements/semgrep.txt b/requirements/semgrep.txtnew file mode 100644index 0000000000..a001d05567--- /dev/null+++ b/requirements/semgrep.txt@@ -0,0 +1,482 @@+#+# This file is autogenerated by pip-compile with Python 3.12+# by the following command:+#+# pip-compile --generate-hashes --index-url=https://pypi.org/simple --no-emit-index-url --no-emit-trusted-host --pip-args='--only-binary=:all:' --strip-extras requirements/semgrep.in+#+--only-binary :all:++annotated-types==0.8.0 \+ --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \+ --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0+ # via pydantic+anyio==4.15.1 \+ --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \+ --hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94+ # via+ # httpx+ # mcp+ # sse-starlette+ # starlette+attrs==26.1.0 \+ --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 \+ --hash=sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32+ # via+ # glom+ # jsonschema+ # referencing+ # semgrep+boltons==21.0.0 \+ --hash=sha256:65e70a79a731a7fe6e98592ecfb5ccf2115873d01dbc576079874629e5c90f13 \+ --hash=sha256:b9bb7b58b2b420bbe11a6025fdef6d3e5edc9f76a42fb467afe7ca212ef9948b+ # via+ # face+ # glom+ # semgrep+bracex==3.0.1 \+ --hash=sha256:4e38e32392e4a4780fe15d644bfc7c8514057cfc3861e060b11814ce829c25e4 \+ --hash=sha256:6523ad83aeb5098a4ee597cff0f964442ff74e460bd3fafaffab6a013ff2288c+ # via wcmatch+certifi==2026.7.22 \+ --hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 \+ --hash=sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55+ # via+ # httpcore+ # httpx+ # requests+cffi==2.1.1 \+ --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \+ --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \+ --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \+ --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \+ --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \+ --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \+ --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \+ --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \+ --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \+ --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \+ --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \+ --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \+ --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf+ # via cryptography+charset-normalizer==3.5.2 \+ --hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \+ --hash=sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf \+ --hash=sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26 \+ --hash=sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93 \+ --hash=sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875 \+ --hash=sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7 \+ --hash=sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011 \+ --hash=sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869 \+ --hash=sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0 \+ --hash=sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621 \+ --hash=sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51 \+ --hash=sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0 \+ --hash=sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef \+ --hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649 \+ --hash=sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e \+ --hash=sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd \+ --hash=sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e \+ --hash=sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc \+ --hash=sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c \+ --hash=sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade \+ --hash=sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4 \+ --hash=sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0 \+ --hash=sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036 \+ --hash=sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413 \+ --hash=sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346 \+ --hash=sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685 \+ --hash=sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c \+ --hash=sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f \+ --hash=sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1 \+ --hash=sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e \+ --hash=sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3 \+ --hash=sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491 \+ --hash=sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5 \+ --hash=sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1+ # via requests+click==8.4.2 \+ --hash=sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6 \+ --hash=sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76+ # via+ # click-option-group+ # semgrep+ # uvicorn+click-option-group==0.5.9 \+ --hash=sha256:ad2599248bd373e2e19bec5407967c3eec1d0d4fc4a5e77b08a0481e75991080 \+ --hash=sha256:f94ed2bc4cf69052e0f29592bd1e771a1789bd7bfc482dd0bc482134aff95823+ # via semgrep+colorama==0.4.6 \+ --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \+ --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6+ # via semgrep+cryptography==50.0.2 \+ --hash=sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602 \+ --hash=sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2 \+ --hash=sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c \+ --hash=sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51 \+ --hash=sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856 \+ --hash=sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de \+ --hash=sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd \+ --hash=sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2 \+ --hash=sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0 \+ --hash=sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e \+ --hash=sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c \+ --hash=sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5 \+ --hash=sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93 \+ --hash=sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04 \+ --hash=sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107 \+ --hash=sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079 \+ --hash=sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134 \+ --hash=sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227 \+ --hash=sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e \+ --hash=sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd \+ --hash=sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94 \+ --hash=sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454 \+ --hash=sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767 \+ --hash=sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5 \+ --hash=sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc \+ --hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \+ --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb+ # via pyjwt+exceptiongroup==1.2.2 \+ --hash=sha256:3111b9d131c238bec2f8f516e123e14ba243563fb135d3fe885990585aa7795b \+ --hash=sha256:47c2edf7c6738fafb49fd34290706d1a1a2f4d1c6df275526b62cbb4aa5393cc+ # via semgrep+face==26.0.1 \+ --hash=sha256:8183d94bc248baaea855a9f8445f97a22a9988908e60abddccc6e251da77c4c6 \+ --hash=sha256:ab0a83c37c9789dce658a67a9a80eafaa113c9ec37c5a9d950ff5480542a062d+ # via glom+glom==25.12.0 \+ --hash=sha256:1ae7da88be3693df40ad27bdf57a765a55c075c86c971bcddd67927403eb0069 \+ --hash=sha256:b9f21e77f71a6576a43864e85066b8cc3f0f778d0d50961563f8981377a6dcb1+ # via semgrep+googleapis-common-protos==1.75.5 \+ --hash=sha256:c7a866fc34ed29a3b10af627a4b9b1dc2433313ca6e959f0ae4feb132047ed72 \+ --hash=sha256:d7285525c23039db98f2463e6d5a4f9b958b94d497f03a844ece3259c4e72d5d+ # via opentelemetry-exporter-otlp-proto-http+h11==0.16.0 \+ --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \+ --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86+ # via+ # httpcore+ # uvicorn+httpcore==1.0.9 \+ --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \+ --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8+ # via httpx+httpx==0.28.1 \+ --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \+ --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad+ # via mcp+httpx-sse==0.4.3 \+ --hash=sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc \+ --hash=sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d+ # via mcp+idna==3.20 \+ --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \+ --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c+ # via+ # anyio+ # httpx+ # requests+importlib-metadata==8.7.1 \+ --hash=sha256:49fef1ae6440c182052f407c8d34a68f72efc36db9ca90dc0113398f2fdde8bb \+ --hash=sha256:5a1f80bf1daa489495071efbb095d75a634cf28a8bc299581244063b53176151+ # via opentelemetry-api+jsonschema==4.25.1 \+ --hash=sha256:3fba0169e345c7175110351d456342c364814cfcf3b964ba4587f22915230a63 \+ --hash=sha256:e4a9655ce0da0c0b67a085847e00a3a51449e1157f4f75e9fb5aa545e122eb85+ # via+ # mcp+ # semgrep+jsonschema-specifications==2025.9.1 \+ --hash=sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe \+ --hash=sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d+ # via jsonschema+markdown-it-py==4.2.0 \+ --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \+ --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a+ # via rich+mcp==1.29.0 \+ --hash=sha256:52d01f334de1868cc3bb2d6604931126a67631f99a6c5d3b82ba47290315ec36 \+ --hash=sha256:f5a075bb611f23d6f4d080c6a1699fa62772eebc562ba9e66b306ddde1c755f7+ # via semgrep+mdurl==0.1.2 \+ --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \+ --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba+ # via markdown-it-py+opentelemetry-api==1.37.0 \+ --hash=sha256:540735b120355bd5112738ea53621f8d5edb35ebcd6fe21ada3ab1c61d1cd9a7 \+ --hash=sha256:accf2024d3e89faec14302213bc39550ec0f4095d1cf5ca688e1bfb1c8612f47+ # via+ # opentelemetry-exporter-otlp-proto-http+ # opentelemetry-instrumentation+ # opentelemetry-instrumentation-requests+ # opentelemetry-instrumentation-threading+ # opentelemetry-sdk+ # opentelemetry-semantic-conventions+ # semgrep+opentelemetry-exporter-otlp-proto-common==1.37.0 \+ --hash=sha256:53038428449c559b0c564b8d718df3314da387109c4d36bd1b94c9a641b0292e \+ --hash=sha256:c87a1bdd9f41fdc408d9cc9367bb53f8d2602829659f2b90be9f9d79d0bfe62c+ # via opentelemetry-exporter-otlp-proto-http+opentelemetry-exporter-otlp-proto-http==1.37.0 \+ --hash=sha256:54c42b39945a6cc9d9a2a33decb876eabb9547e0dcb49df090122773447f1aef \+ --hash=sha256:e52e8600f1720d6de298419a802108a8f5afa63c96809ff83becb03f874e44ac+ # via semgrep+opentelemetry-instrumentation==0.58b0 \+ --hash=sha256:50f97ac03100676c9f7fc28197f8240c7290ca1baa12da8bfbb9a1de4f34cc45 \+ --hash=sha256:df640f3ac715a3e05af145c18f527f4422c6ab6c467e40bd24d2ad75a00cb705+ # via+ # opentelemetry-instrumentation-requests+ # opentelemetry-instrumentation-threading+opentelemetry-instrumentation-requests==0.58b0 \+ --hash=sha256:672a0be0bb5b52bea0c11820b35e27edcf4cd22d34abe4afc59a92a80519f8a8 \+ --hash=sha256:ae9495e6ff64e27bdb839fce91dbb4be56e325139828e8005f875baf41951a2e+ # via semgrep+opentelemetry-instrumentation-threading==0.58b0 \+ --hash=sha256:eacc072881006aceb5b9b6831bcdce718c67ef6f31ac0b32bd6a23a94d979b4a \+ --hash=sha256:f68c61f77841f9ff6270176f4d496c10addbceacd782af434d705f83e4504862+ # via semgrep+opentelemetry-proto==1.37.0 \+ --hash=sha256:30f5c494faf66f77faeaefa35ed4443c5edb3b0aa46dad073ed7210e1a789538 \+ --hash=sha256:8ed8c066ae8828bbf0c39229979bdf583a126981142378a9cbe9d6fd5701c6e2+ # via+ # opentelemetry-exporter-otlp-proto-common+ # opentelemetry-exporter-otlp-proto-http+opentelemetry-sdk==1.37.0 \+ --hash=sha256:8f3c3c22063e52475c5dbced7209495c2c16723d016d39287dfc215d1771257c \+ --hash=sha256:cc8e089c10953ded765b5ab5669b198bbe0af1b3f89f1007d19acd32dc46dda5+ # via+ # opentelemetry-exporter-otlp-proto-http+ # semgrep+opentelemetry-semantic-conventions==0.58b0 \+ --hash=sha256:5564905ab1458b96684db1340232729fce3b5375a06e140e8904c78e4f815b28 \+ --hash=sha256:6bd46f51264279c433755767bb44ad00f1c9e2367e1b42af563372c5a6fa0c25+ # via+ # opentelemetry-instrumentation+ # opentelemetry-instrumentation-requests+ # opentelemetry-sdk+opentelemetry-util-http==0.58b0 \+ --hash=sha256:6c6b86762ed43025fbd593dc5f700ba0aa3e09711aedc36fd48a13b23d8cb1e7 \+ --hash=sha256:de0154896c3472c6599311c83e0ecee856c4da1b17808d39fdc5cce5312e4d89+ # via opentelemetry-instrumentation-requests+packaging==26.3 \+ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \+ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c+ # via+ # opentelemetry-instrumentation+ # semgrep+peewee==3.19.0 \+ --hash=sha256:de220b94766e6008c466e00ce4ba5299b9a832117d9eb36d45d0062f3cfd7417 \+ --hash=sha256:f88292a6f0d7b906cb26bca9c8599b8f4d8920ebd36124400d0cbaaaf915511f+ # via semgrep+protobuf==6.33.6 \+ --hash=sha256:0cd27b587afca21b7cfa59a74dcbd48a50f0a6400cfb59391340ad729d91d326 \+ --hash=sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901 \+ --hash=sha256:7d29d9b65f8afef196f8334e80d6bc1d5d4adedb449971fefd3723824e6e77d3 \+ --hash=sha256:9720e6961b251bde64edfdab7d500725a2af5280f3f4c87e57c0208376aa8c3a \+ --hash=sha256:a6768d25248312c297558af96a9f9c929e8c4cee0659cb07e780731095f38135 \+ --hash=sha256:c96c37eec15086b79762ed265d59ab204dabc53056e3443e702d2681f4b39ce3 \+ --hash=sha256:e2afbae9b8e1825e3529f88d514754e094278bb95eadc0e199751cdd9a2e82a2 \+ --hash=sha256:e9db7e292e0ab79dd108d7f1a94fe31601ce1ee3f7b79e0692043423020b0593+ # via+ # googleapis-common-protos+ # opentelemetry-proto+pycparser==3.0 \+ --hash=sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29 \+ --hash=sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992+ # via cffi+pydantic==2.13.5 \+ --hash=sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73 \+ --hash=sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08+ # via+ # mcp+ # pydantic-settings+pydantic-core==2.46.5 \+ --hash=sha256:0fc5be0abd4a407e200d844b404e33639a554e7bd0d448e7b9ae181be4789ac2 \+ --hash=sha256:10416c15b8839ecc4ef4d0885da76da6fd0f67333a0eb8aff6d93c4b8f2910fc \+ --hash=sha256:18a09e1e1011b462f2e32774f25859ef1223d5c2b0546a633cf56654710721e0 \+ --hash=sha256:2bc9419666990c06d7397831f2126a1ecc3594aaa3ff7de5bf2d066802f4e07b \+ --hash=sha256:4fdc8b93a41521988916eeaa271173fcca7fa0803d62f87675aac8dcec1c8e29 \+ --hash=sha256:5cb482e9e84c851f4e623fe4acc1ced89168cf1fe18f7089db4548c8f5bbb65b \+ --hash=sha256:5e81740c09e310f5aa5cbd3e434a01c154d4bef93241c7877b39f211d2b78ba8 \+ --hash=sha256:816ff0a6550ffc06c098ccd2e0698600f9aa7da192a79eaa6f9af504a35db869 \+ --hash=sha256:a39ac25a9a2fa4072efdb429833c4a4c8009a51ff9eea3eeae131713cd27991e \+ --hash=sha256:b98134087d9de723658d17a42c7d0da8d6e2ef08015dee7dc93889047315f5e4 \+ --hash=sha256:b9fe6fb92520e3fd61f2e49000b6911b188824f089b75973ea06d6267f0b476d \+ --hash=sha256:c7ea57fc63aa7da93a1bd2d644e6577befae10c52c4e36377635eea1056a74f5 \+ --hash=sha256:d925f3d9afd05a8c0fb3a1031463a8d59ebe5e2afad297e29c78be19e13b4e62 \+ --hash=sha256:e652ab17569c94bff5475520f907b7148b8c24036a8ebbe5cf7cf7493d28579a \+ --hash=sha256:efd62a42486f1bda5d24cb4f63d15a3c7768375fe83d36f9417b4ad7a2fb20b3 \+ --hash=sha256:f7b0ec93a2893de856652154d73b7ba622f26fa97726487dcac373de5f4c6084+ # via pydantic+pydantic-settings==2.15.0 \+ --hash=sha256:0ba092c291c94baceb5eff768aa0d56400a457585bc0175925a5a5510303da42 \+ --hash=sha256:694b793e84f766ba76a90ebdefc01d0a9a045dab0382bee70393da93712ad117+ # via mcp+pygments==2.21.0 \+ --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \+ --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c+ # via rich+pyjwt==2.15.1 \+ --hash=sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193+ # via+ # -r requirements/semgrep.in+ # mcp+ # semgrep+python-dotenv==1.2.4 \+ --hash=sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc \+ --hash=sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0+ # via pydantic-settings+python-multipart==0.0.32 \+ --hash=sha256:be54b7f3fa167bb83e4fcd936b887b708f4e57fe75911c02aebf53efaf8d938e \+ --hash=sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23+ # via mcp+referencing==0.37.0 \+ --hash=sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231 \+ --hash=sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8+ # via+ # jsonschema+ # jsonschema-specifications+requests==2.34.2 \+ --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \+ --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed+ # via+ # opentelemetry-exporter-otlp-proto-http+ # semgrep+rich==15.0.0 \+ --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \+ --hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36+ # via semgrep+rpds-py==2026.6.3 \+ --hash=sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680 \+ --hash=sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4 \+ --hash=sha256:22bffe6042b9bcb0822bcd1955ec00e245daf17b4344e4ed8e9551b976b63e96 \+ --hash=sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975 \+ --hash=sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f \+ --hash=sha256:2c99f7e8ccb3dd6e3e4bfeac657a7b208c9bac8075f4b078c02d7404c34107fa \+ --hash=sha256:501f9f04a588d6a09179368c57071301445191767c64e4b52a6aa9871f1ef5ed \+ --hash=sha256:538949e262e46caa31ac01bdb3c1e8f642622922cacbabbae6a8445d9dc33eaf \+ --hash=sha256:55927d532399c2c646100ff7feb48eaa940ad70f42cd68e1328f3ded9f81ca24 \+ --hash=sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a \+ --hash=sha256:62698275682bf121181861295c9181e789030a2d516071f5b8f3c23c170cd0fc \+ --hash=sha256:7491ee23305ac3eb59e492b6945881f5cd77a6f731061a3f25b77fd40f9e99a4 \+ --hash=sha256:a0811d33247c3d6128a3001d763f2aa056bb3425204335400ac54f89eec3a0d0 \+ --hash=sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822 \+ --hash=sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6 \+ --hash=sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e+ # via+ # jsonschema+ # referencing+ruamel-yaml==0.19.1 \+ --hash=sha256:27592957fedf6e0b62f281e96effd28043345e0e66001f97683aa9a40c667c93 \+ --hash=sha256:53eb66cd27849eff968ebf8f0bf61f46cdac2da1d1f3576dd4ccee9b25c31993+ # via semgrep+ruamel-yaml-clib==0.2.15 \+ --hash=sha256:11e5499db1ccbc7f4b41f0565e4f799d863ea720e01d3e99fa0b7b5fcd7802c9 \+ --hash=sha256:2b216904750889133d9222b7b873c199d48ecbb12912aca78970f84a5aa1a4bc \+ --hash=sha256:46e4cc8c43ef6a94885f72512094e482114a8a706d3c555a34ed4b0d20200600 \+ --hash=sha256:4b293a37dc97e2b1e8a1aec62792d1e52027087c8eea4fc7b5abd2bdafdd6642 \+ --hash=sha256:512571ad41bba04eac7268fe33f7f4742210ca26a81fe0c75357fa682636c690 \+ --hash=sha256:64da03cbe93c1e91af133f5bec37fd24d0d4ba2418eaf970d7166b0a26a148a2 \+ --hash=sha256:71845d377c7a47afc6592aacfea738cc8a7e876d586dfba814501d8c53c1ba60 \+ --hash=sha256:cb15a2e2a90c8475df45c0949793af1ff413acfb0a716b8b94e488ea95ce7cff \+ --hash=sha256:e5e9f630c73a490b758bf14d859a39f375e6999aea5ddd2e2e9da89b9953486a \+ --hash=sha256:f4421ab780c37210a07d138e56dd4b51f8642187cdfb433eb687fe8c11de0144 \+ --hash=sha256:f6d3655e95a80325b84c4e14c080b2470fe4f33b6846f288379ce36154993fb1+ # via semgrep+semantic-version==2.10.0 \+ --hash=sha256:bdabb6d336998cbb378d4b9db3a4b56a1e3235701dc05ea2690d9a997ed5041c \+ --hash=sha256:de78a3b8e0feda74cabc54aab2da702113e33ac9d9eb9d2389bcf1f58b7d9177+ # via semgrep+semgrep==1.179.0 \+ --hash=sha256:34b5e801e3f4325c93014124ccfab6da96857f74aae68458d2a07defd4727b0f \+ --hash=sha256:69bce348296374df6c51e72758801ce06dd18d6dfb307bc73d24b9de53bbe5f1 \+ --hash=sha256:6c6cf104ad0959c0b11de56d15c5d31f56949c620b4bd130c5d1fb899f2bb5a3 \+ --hash=sha256:9b57026f587a4bc7833bca2b6e4d6778072a79dcf0b9f2e5e01d3d5df39c7759 \+ --hash=sha256:b529c4db63f293918989b84ce4640f12f1b1e4680d9e7fcab5f3554f9113dfc5 \+ --hash=sha256:c23d79c4839540372acc39b59aad167c1c7f3dc21bacacb27f19aa2edd79d271 \+ --hash=sha256:dc6317fbfad49b1dbe396df7da7d9702cffc5ea9ea62cb3b4b2209824496b425+ # via -r requirements/semgrep.in+sse-starlette==3.5.0 \+ --hash=sha256:3e6e1070df3f0f5d9cea81496de92dbb72f6721871d99748ece67441dd8b7997 \+ --hash=sha256:75de713aa8a9441513cc283220826da079d982770965b951e9437720e8bafdb2+ # via mcp+starlette==1.7.0 \+ --hash=sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e \+ --hash=sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d+ # via+ # mcp+ # sse-starlette+tomli==2.4.1 \+ --hash=sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe \+ --hash=sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5 \+ --hash=sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9 \+ --hash=sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1 \+ --hash=sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585 \+ --hash=sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f \+ --hash=sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085 \+ --hash=sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a \+ --hash=sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917 \+ --hash=sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257 \+ --hash=sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9+ # via semgrep+typing-extensions==4.16.0 \+ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \+ --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5+ # via+ # anyio+ # mcp+ # opentelemetry-api+ # opentelemetry-exporter-otlp-proto-http+ # opentelemetry-sdk+ # opentelemetry-semantic-conventions+ # pydantic+ # pydantic-core+ # referencing+ # semgrep+ # starlette+ # typing-inspection+typing-inspection==0.4.4 \+ --hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \+ --hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147+ # via+ # mcp+ # pydantic+ # pydantic-settings+urllib3==2.8.0 \+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \+ --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63+ # via+ # requests+ # semgrep+uvicorn==0.54.0 \+ --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \+ --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620+ # via mcp+wcmatch==8.5.2 \+ --hash=sha256:17d3ad3758f9d0b5b4dedc770b65420d4dac62e680229c287bf24c9db856a478 \+ --hash=sha256:a70222b86dea82fb382dd87b73278c10756c138bd6f8f714e2183128887b9eb2+ # via semgrep+wrapt==1.17.3 \+ --hash=sha256:042ec3bb8f319c147b1301f2393bc19dba6e176b7da446853406d041c36c7828 \+ --hash=sha256:0b02e424deef65c9f7326d8c19220a2c9040c51dc165cddb732f16198c168396 \+ --hash=sha256:3af60380ba0b7b5aeb329bc4e402acd25bd877e98b3727b0135cb5c2efdaefe9 \+ --hash=sha256:4da9f45279fff3543c371d5ababc57a0384f70be244de7759c85a7f989cb4ebe \+ --hash=sha256:604d076c55e2fdd4c1c03d06dc1a31b95130010517b5019db15365ec4a405fc6 \+ --hash=sha256:6b538e31eca1a7ea4605e44f81a48aa24c4632a277431a6ed3f328835901f4fd \+ --hash=sha256:7171ae35d2c33d326ac19dd8facb1e82e5fd04ef8c6c0e394d7af55a55051c22 \+ --hash=sha256:74afa28374a3c3a11b3b5e5fca0ae03bef8450d6aa3ab3a1e2c30e3a75d023dc \+ --hash=sha256:9baa544e6acc91130e926e8c802a17f3b16fbea0fd441b5a60f5cf2cc5c3deba \+ --hash=sha256:ab232e7fdb44cdfbf55fc3afa31bcdb0d8980b9b95c38b6405df2acb672af0e0 \+ --hash=sha256:e71d5c6ebac14875668a1e90baf2ea0ef5b7ac7918355850c0908ae82bcb297c \+ --hash=sha256:f66eb08feaa410fe4eebd17f2a2c8e2e46d3476e9f8c783daa8e09e0faa666d0+ # via+ # opentelemetry-instrumentation+ # opentelemetry-instrumentation-threading+zipp==4.1.0 \+ --hash=sha256:25ad4e16390cd314347dd8f1de67a2ac538ae658ed4ab9db16029c07c188e97f \+ --hash=sha256:4cb57381f544315db7688e976e922a2b18cdb513d21cc194eb42232ba2a3e602+ # via importlib-metadatadiff --git a/requirements/twine.in b/requirements/twine.innew file mode 100644index 0000000000..5b175d3167--- /dev/null+++ b/requirements/twine.in@@ -0,0 +1,3 @@+# Python 3.12 on Linux. Regenerate using pip-tools 7.6.1:+# pip-compile --generate-hashes --strip-extras --no-emit-index-url --no-emit-trusted-host --index-url=https://pypi.org/simple --pip-args=--only-binary=:all: requirements/twine.in+twine==7.0.0diff --git a/requirements/twine.txt b/requirements/twine.txtnew file mode 100644index 0000000000..84c3335f43--- /dev/null+++ b/requirements/twine.txt@@ -0,0 +1,210 @@+#+# This file is autogenerated by pip-compile with Python 3.12+# by the following command:+#+# pip-compile --generate-hashes --index-url=https://pypi.org/simple --no-emit-index-url --no-emit-trusted-host --pip-args='--only-binary=:all:' --strip-extras requirements/twine.in+#+--only-binary :all:++certifi==2026.7.22 \+ --hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 \+ --hash=sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55+ # via requests+cffi==2.1.1 \+ --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \+ --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \+ --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \+ --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \+ --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \+ --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \+ --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \+ --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \+ --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \+ --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \+ --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \+ --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \+ --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf+ # via cryptography+charset-normalizer==3.5.2 \+ --hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \+ --hash=sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf \+ --hash=sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26 \+ --hash=sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93 \+ --hash=sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875 \+ --hash=sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7 \+ --hash=sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011 \+ --hash=sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869 \+ --hash=sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0 \+ --hash=sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621 \+ --hash=sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51 \+ --hash=sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0 \+ --hash=sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef \+ --hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649 \+ --hash=sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e \+ --hash=sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd \+ --hash=sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e \+ --hash=sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc \+ --hash=sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c \+ --hash=sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade \+ --hash=sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4 \+ --hash=sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0 \+ --hash=sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036 \+ --hash=sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413 \+ --hash=sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346 \+ --hash=sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685 \+ --hash=sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c \+ --hash=sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f \+ --hash=sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1 \+ --hash=sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e \+ --hash=sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3 \+ --hash=sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491 \+ --hash=sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5 \+ --hash=sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1+ # via requests+cryptography==50.0.2 \+ --hash=sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602 \+ --hash=sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2 \+ --hash=sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c \+ --hash=sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51 \+ --hash=sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856 \+ --hash=sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de \+ --hash=sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd \+ --hash=sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2 \+ --hash=sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0 \+ --hash=sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e \+ --hash=sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c \+ --hash=sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5 \+ --hash=sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93 \+ --hash=sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04 \+ --hash=sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107 \+ --hash=sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079 \+ --hash=sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134 \+ --hash=sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227 \+ --hash=sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e \+ --hash=sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd \+ --hash=sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94 \+ --hash=sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454 \+ --hash=sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767 \+ --hash=sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5 \+ --hash=sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc \+ --hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \+ --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb+ # via secretstorage+docutils==0.23 \+ --hash=sha256:25d013af9bf23bc1c7b2b093dff4208166c53a94786c9e447808335ef1185fea \+ --hash=sha256:746f5060322511280a1e50eb76846ed6bf2342984b2ac04dc42caa1a8d78799e+ # via readme-renderer+id==1.6.1 \+ --hash=sha256:d0732d624fb46fd4e7bc4e5152f00214450953b9e772c182c1c22964def1a069 \+ --hash=sha256:f5ec41ed2629a508f5d0988eda142e190c9c6da971100612c4de9ad9f9b237ca+ # via twine+idna==3.20 \+ --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \+ --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c+ # via requests+jaraco-classes==3.4.0 \+ --hash=sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd \+ --hash=sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790+ # via keyring+jaraco-context==6.1.2 \+ --hash=sha256:bf8150b79a2d5d91ae48629d8b427a8f7ba0e1097dd6202a9059f29a36379535 \+ --hash=sha256:f1a6c9d391e661cc5b8d39861ff077a7dc24dc23833ccee564b234b81c82dfe3+ # via keyring+jaraco-functools==4.6.0 \+ --hash=sha256:880c577ec9720b3a052d5bc611fb9f2269b3d87902ef42440df443b88e443280 \+ --hash=sha256:99e3dc0060c5cbe8fcd1cdb36258e2a65ca40f1566b2033b12abb1bb44dd3c30+ # via keyring+jeepney==0.9.0 \+ --hash=sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683 \+ --hash=sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732+ # via+ # keyring+ # secretstorage+keyring==25.7.0 \+ --hash=sha256:be4a0b195f149690c166e850609a477c532ddbfbaed96a404d4e43f8d5e2689f \+ --hash=sha256:fe01bd85eb3f8fb3dd0405defdeac9a5b4f6f0439edbb3149577f244a2e8245b+ # via twine+markdown-it-py==4.2.0 \+ --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \+ --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a+ # via rich+mdurl==0.1.2 \+ --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \+ --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba+ # via markdown-it-py+more-itertools==11.1.0 \+ --hash=sha256:48e8f4d9e7e5878571ecf6f2b4e57634f93cd474cc8cfbd2376f2d11b396e30d \+ --hash=sha256:4b65538ae22f6fed0ce4874efd317463a7489796a0939fa66824dd542125a192+ # via+ # jaraco-classes+ # jaraco-functools+nh3==0.3.7 \+ --hash=sha256:15f5fbf090f5c88d61c820e1fc1fceecb6520cca9fe85649c06b57ef9dc9ff62 \+ --hash=sha256:19f288c938ec6eef1f5d2c6cab47838e71fef8097e1c1233802be5a6230ba086 \+ --hash=sha256:5ffdfcb9a686ffb12765376bcfb6b5b55728516d3c0ee317d29982381ded3df8 \+ --hash=sha256:618e3059caf41ccdf5dcccb3fa9df4cf6e4efe23d1382a8bbfca272a8a4f8bfc \+ --hash=sha256:6698a822132beedab80f131c08d8d0ac5a178ddeb488d02ca4b67716ecfac7af \+ --hash=sha256:6c3aa50eb26e9228238271db9f983cbc3b006dfbfeca2d4dc34c33ddc6ac5ea5 \+ --hash=sha256:6e4280115d44c3b278eef712a86748c1a723105cd79feec46952383117ab4e59 \+ --hash=sha256:70f5ac8626e899a4bab0ef74ca2f5bd602f49c7b739e6e5026b4afc6d63dac42 \+ --hash=sha256:71860d01c16f4d8c72e334e0674beb2b0899dbd0bf760de18932ef4390303848 \+ --hash=sha256:9b7279d43323a25225df23576af6594a16693f61431170848b8b2ac21ad4f174 \+ --hash=sha256:bc42bb1193c1e28a1e74c2cabaca178e118a7103e8832699fef8a2b3e2496493 \+ --hash=sha256:d56e76bd3cadb09b6b0cef364850811663734b348a25f5f587a2819c495367bd \+ --hash=sha256:de2b2aab32ea303405debefdcfc58043d3e635fa3f67b9eb140d2b0e0c0d2563 \+ --hash=sha256:e8fd1ab205258b29254f72db377d99e2c96aa7653ef3b015ccab0420b094b506 \+ --hash=sha256:f04b7d333b27f13ca439da3cf1c75c2fba34f104969f6ce4ac8e7079699c2f4a \+ --hash=sha256:f266d3f1b3647449923a8e406524632220dd5d8b647078dfe45b885d33d10479 \+ --hash=sha256:fd4a70efb45d5372174f718878eb7a35c12677626a63b2f103b23b833457dcac+ # via readme-renderer+packaging==26.3 \+ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \+ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c+ # via twine+pycparser==3.0 \+ --hash=sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29 \+ --hash=sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992+ # via cffi+pygments==2.21.0 \+ --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \+ --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c+ # via+ # readme-renderer+ # rich+readme-renderer==46.0 \+ --hash=sha256:af3e964914f6310a33ff67b72a4bdd940bed8d7c3bdecd2d14f40edf284bfe90 \+ --hash=sha256:d0dae1f74bb273b534770cb4cccb6bb78735540afdb03c2146f4e19dcd412560+ # via twine+requests==2.34.2 \+ --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \+ --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed+ # via+ # requests-toolbelt+ # twine+requests-toolbelt==1.0.0 \+ --hash=sha256:7681a0a3d047012b5bdc0ee37d7f8f07ebe76ab08caeccfc3921ce23c88d5bc6 \+ --hash=sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06+ # via twine+rfc3986==2.0.0 \+ --hash=sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd \+ --hash=sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c+ # via twine+rich==15.0.0 \+ --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \+ --hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36+ # via twine+secretstorage==3.5.0 \+ --hash=sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137 \+ --hash=sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be+ # via keyring+twine==7.0.0 \+ --hash=sha256:85cdb29c518efef867360ae4acd4b0dfd61c8654a22fca08e6f8539f05022177 \+ --hash=sha256:b854164df26db268af05f49aa5c0344b10e27a494343ff05b1e0bad3b135f5a7+ # via -r requirements/twine.in+urllib3==2.8.0 \+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \+ --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63+ # via+ # id+ # requests+ # twinediff --git a/src/local_deep_research/benchmarks/benchmark_functions.py b/src/local_deep_research/benchmarks/benchmark_functions.pyindex 0769fc25ad..e879b1f72b 100644--- a/src/local_deep_research/benchmarks/benchmark_functions.py+++ b/src/local_deep_research/benchmarks/benchmark_functions.py@@ -357,6 +357,7 @@ def compare_configurations(# Create output directory+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python benchmark API intentionally accepts an output directory; the web runner does not call this functionPath(output_dir).mkdir(parents=True, exist_ok=True)# Run benchmarks for each configurationdiff --git a/src/local_deep_research/benchmarks/comparison/evaluator.py b/src/local_deep_research/benchmarks/comparison/evaluator.pyindex d1f315729d..b56f442119 100644--- a/src/local_deep_research/benchmarks/comparison/evaluator.py+++ b/src/local_deep_research/benchmarks/comparison/evaluator.py@@ -227,6 +227,7 @@ def compare_configurations(# Generate visualizations_viz_dir_path = Path(output_dir) / "visualizations"+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python comparison output root with a fixed visualizations child; no web caller_viz_dir_path.mkdir(parents=True, exist_ok=True)visualizations_dir = str(_viz_dir_path)diff --git a/src/local_deep_research/benchmarks/evaluators/base.py b/src/local_deep_research/benchmarks/evaluators/base.pyindex ad0cc08263..eabb20715b 100644--- a/src/local_deep_research/benchmarks/evaluators/base.py+++ b/src/local_deep_research/benchmarks/evaluators/base.py@@ -67,5 +67,6 @@ class BaseBenchmarkEvaluator(ABC):Path to the benchmark-specific directory"""benchmark_dir = Path(output_dir) / self.name+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python benchmark output root and evaluator name; no request path is accepted by this helperbenchmark_dir.mkdir(parents=True, exist_ok=True)return str(benchmark_dir)diff --git a/src/local_deep_research/benchmarks/evaluators/simpleqa.py b/src/local_deep_research/benchmarks/evaluators/simpleqa.pyindex 90a11aeea3..1e196ff598 100644--- a/src/local_deep_research/benchmarks/evaluators/simpleqa.py+++ b/src/local_deep_research/benchmarks/evaluators/simpleqa.py@@ -215,6 +215,7 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):results.append(result)# Write result to file+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python SimpleQA output root with a fixed prefix and generated timestampwith open(results_file, "a", encoding="utf-8") as f:f.write(json.dumps(result) + "\n")@@ -234,6 +235,7 @@ class SimpleQAEvaluator(BaseBenchmarkEvaluator):results.append(error_result)# Write error result to file+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Same generated SimpleQA results file used by the success path abovewith open(results_file, "a", encoding="utf-8") as f:f.write(json.dumps(error_result) + "\n")diff --git a/src/local_deep_research/benchmarks/graders.py b/src/local_deep_research/benchmarks/graders.pyindex 8c66abd72b..57ddba29bd 100644--- a/src/local_deep_research/benchmarks/graders.py+++ b/src/local_deep_research/benchmarks/graders.py@@ -460,6 +460,7 @@ def _load_results_for_grading(# Remove output file if it existsoutput_path = Path(output_file)if output_path.exists():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python grading API intentionally replaces its caller-selected output file; web grading uses grade_single_resultoutput_path.unlink()return results@@ -700,6 +701,7 @@ def human_evaluation(# Remove output file if it existsoutput_path = Path(output_file)if output_path.exists():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Interactive local grading intentionally replaces its caller-selected output fileoutput_path.unlink()human_graded_results = []diff --git a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.pyindex c70bf8efba..88f55c4cdf 100644--- a/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py+++ b/src/local_deep_research/benchmarks/optimization/optuna_optimizer.py@@ -638,6 +638,7 @@ class OptunaOptimizer:# Create directory for visualizations_viz_dir_path = Path(self.output_dir) / "visualizations"+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python optimizer output directory with a fixed visualizations child_viz_dir_path.mkdir(parents=True, exist_ok=True)viz_dir = str(_viz_dir_path)@@ -661,6 +662,7 @@ class OptunaOptimizer:# Create directory for visualizations_quick_viz_dir_path = Path(self.output_dir) / "visualizations"+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python optimizer output directory with a fixed visualizations child_quick_viz_dir_path.mkdir(parents=True, exist_ok=True)viz_dir = str(_quick_viz_dir_path)diff --git a/src/local_deep_research/benchmarks/runners.py b/src/local_deep_research/benchmarks/runners.pyindex 044818df80..c2370816c9 100644--- a/src/local_deep_research/benchmarks/runners.py+++ b/src/local_deep_research/benchmarks/runners.py@@ -123,6 +123,7 @@ def run_benchmark(for file in [results_file, evaluation_file, report_file]:file_path = Path(file)if file_path.exists():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python benchmark output paths are selected by the invoking program; web benchmarks use the separate database runnerfile_path.unlink()# Progress tracking@@ -234,6 +235,7 @@ def run_benchmark(results.append(result)# Write result to file+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: CLI/Python benchmark result file generated under its caller-selected output rootwith open(results_file, "a", encoding="utf-8") as f:f.write(json.dumps(result) + "\n")@@ -268,6 +270,7 @@ def run_benchmark(results.append(error_result)# Write error result to file+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Same generated benchmark result file used by the success path abovewith open(results_file, "a", encoding="utf-8") as f:f.write(json.dumps(error_result) + "\n")diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.pyindex 83f4d52228..649b514df3 100644--- a/src/local_deep_research/database/backup/backup_service.py+++ b/src/local_deep_research/database/backup/backup_service.py@@ -323,7 +323,9 @@ class BackupService:# single quote by doubling it per the SQLite literal grammar# (all other unsafe chars were rejected above).attach_path = temp_path_str.replace("'", "''")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: ATTACH cannot be bound; unsafe path chars rejected; quotes doubled; key checked as hexcursor.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: ATTACH path rejects unsafe characters and doubles quotes; the derived key is validated as ASCII hexf"ATTACH DATABASE '{attach_path}' AS backup KEY \"x'{hex_key}'\"")@@ -336,12 +338,17 @@ class BackupService:page_size = int(settings["page_size"])kdf_iter = int(settings["kdf_iterations"])hmac_alg = str(settings["hmac_algorithm"])+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: PRAGMA cannot be bound; value coerced with int() abovecursor.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA page size is converted to int before interpolationf"PRAGMA backup.cipher_page_size = {page_size}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: PRAGMA cannot be bound; hmac_algorithm is an EnumSetting allow-list valuecursor.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA HMAC algorithm comes from the EnumSetting allowlistf"PRAGMA backup.cipher_hmac_algorithm = {hmac_alg}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA cannot be bound; value coerced with int() abovecursor.execute(f"PRAGMA backup.kdf_iter = {kdf_iter}")# Export all data to the backup database@@ -629,6 +636,7 @@ class BackupService:if should_delete:try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Retention unlinks only fixed-pattern backup glob results checked by is_safe_glob_result under the server-owned per-user backup directorybackup.unlink()deleted_count += 1logger.debug(diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex c1c342a4c8..d546be40cf 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -259,6 +259,7 @@ def _remove_partial_user_db_files(db_path: Path) -> None:for path in artifacts:try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Creation failure cleanup receives the generated user DB path and derives only its fixed sidecar namespath.unlink(missing_ok=True)except OSError:# Best-effort: a leftover artifact is worth surfacing but must not@@ -648,6 +649,7 @@ class DatabaseManager:]for pragma in pragmas:try:+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Both PRAGMA values come from get_sqlcipher_settings numeric range and page-size validationconnection.execute(pragma)except Exception as e:logger.debug(f"Could not apply pragma '{pragma}': {e}")diff --git a/src/local_deep_research/database/migrations/versions/0008_fix_research_strategy_fk.py b/src/local_deep_research/database/migrations/versions/0008_fix_research_strategy_fk.pyindex 4a5ebae0d0..1564aa02ec 100644--- a/src/local_deep_research/database/migrations/versions/0008_fix_research_strategy_fk.py+++ b/src/local_deep_research/database/migrations/versions/0008_fix_research_strategy_fk.py@@ -55,6 +55,7 @@ def _table_row_count(bind, table_name: str) -> int:# bearer:disable python_lang_sql_injectionreturn (bind.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Both migration callers pass the literal research_strategies table nametext(f"SELECT COUNT(*) FROM {table_name}") # noqa: S608 — hardcoded name).scalar()or 0diff --git a/src/local_deep_research/database/migrations/versions/0010_add_chat_tables.py b/src/local_deep_research/database/migrations/versions/0010_add_chat_tables.pyindex 8ce81cee13..d9da47fc09 100644--- a/src/local_deep_research/database/migrations/versions/0010_add_chat_tables.py+++ b/src/local_deep_research/database/migrations/versions/0010_add_chat_tables.py@@ -130,6 +130,7 @@ def _sqlite_fk_signatures(bind, table_name: str) -> list[dict] | None:quoted_table = dialect.identifier_preparer.quote(table_name)# ``table_name`` is supplied by this migration and dialect-quoted.rows = bind.exec_driver_sql( # noqa: S608+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: SQLite table identifier is escaped with the dialect identifier preparer abovef"PRAGMA foreign_key_list({quoted_table})").mappings()grouped: dict[int, list] = {}diff --git a/src/local_deep_research/database/migrations/versions/0013_remove_meta_search_engines.py b/src/local_deep_research/database/migrations/versions/0013_remove_meta_search_engines.pyindex c2b1a1d8f2..cd459cc12c 100644--- a/src/local_deep_research/database/migrations/versions/0013_remove_meta_search_engines.py+++ b/src/local_deep_research/database/migrations/versions/0013_remove_meta_search_engines.py@@ -177,6 +177,7 @@ def _rewrite_benchmark_search_configs(conn, table: str) -> None:# trailing prose after the rule id, is silently ignored.# bearer:disable python_lang_sql_injectionrows = conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Only benchmark_runs and benchmark_configs literals reach this migration helpersa.text(f"SELECT id, search_config FROM {table}") # noqa: S608).fetchall()@@ -196,6 +197,7 @@ def _rewrite_benchmark_search_configs(conn, table: str) -> None:# directive, or any trailing prose after the rule id, is ignored.# bearer:disable python_lang_sql_injectionconn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Table comes from two migration literals; row ID and JSON config are bound parameterssa.text(f"UPDATE {table} SET search_config = :config " # noqa: S608"WHERE id = :id"diff --git a/src/local_deep_research/database/migrations/versions/0021_add_note_tables.py b/src/local_deep_research/database/migrations/versions/0021_add_note_tables.pyindex dade0e5ad7..fb00b36869 100644--- a/src/local_deep_research/database/migrations/versions/0021_add_note_tables.py+++ b/src/local_deep_research/database/migrations/versions/0021_add_note_tables.py@@ -333,6 +333,7 @@ def downgrade():if inspector.has_table(table_name):try:count = conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Table name comes only from the six literal note tables listed abovesa.text(f"SELECT COUNT(*) FROM {table_name}") # noqa: S608).scalar()except Exception:diff --git a/src/local_deep_research/database/migrations/versions/0025_split_context_warning_dismissals.py b/src/local_deep_research/database/migrations/versions/0025_split_context_warning_dismissals.pyindex b0c21e24e1..58ee41ebf2 100644--- a/src/local_deep_research/database/migrations/versions/0025_split_context_warning_dismissals.py+++ b/src/local_deep_research/database/migrations/versions/0025_split_context_warning_dismissals.py@@ -45,6 +45,7 @@ def _copy_setting_if_missing(conn, source_key: str, target_key: str) -> None:columns_sql = ", ".join(copy_columns)conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Columns are intersected with the fixed _COPYABLE_COLUMNS tuple; setting keys remain bound parameterssa.text(f"INSERT INTO settings (key, {columns_sql}) " # noqa: S608f"SELECT :target_key, {columns_sql} FROM settings "diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex eb9dce2a68..f08f0a8f6d 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -251,6 +251,7 @@ def set_sqlcipher_key(per-database salt. If not provided, uses legacy salt."""key = get_key_from_password(password, db_path=db_path) # gitleaks:allow+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA key cannot be bound; key.hex() is [0-9a-f] onlycursor_or_conn.execute(f"PRAGMA key = \"x'{key.hex()}'\"")@@ -270,6 +271,7 @@ def set_sqlcipher_key_from_hex(cursor_or_conn: Any, hex_key: str) -> None:or re.fullmatch(r"[0-9a-fA-F]+", hex_key) is None):raise ValueError("hex_key must be non-empty even-length ASCII hex")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA key cannot be bound; hex_key is validated as non-empty even-length ASCII hex abovecursor_or_conn.execute(f"PRAGMA key = \"x'{hex_key}'\"") # gitleaks:allow@@ -344,6 +346,7 @@ def set_sqlcipher_rekey(del key# The hex encoding already prevents injection since it only contains [0-9a-f]+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA rekey cannot be bound; key.hex() is [0-9a-f] onlysafe_sql = f"PRAGMA rekey = \"x'{key_hex}'\""# Any failure here must not carry ``safe_sql`` outwards. SQLAlchemy wraps@@ -369,9 +372,11 @@ def set_sqlcipher_rekey(# Try SQLAlchemy connection (needs text() wrapper)from sqlalchemy import text+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: safe_sql interpolates only the derived key bytes.hex output into PRAGMA rekeycursor_or_conn.execute(text(safe_sql))except TypeError:# Raw SQLCipher connection - use string directly+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: safe_sql interpolates only the derived key bytes.hex output into PRAGMA rekeycursor_or_conn.execute(safe_sql)except Exception as exc: # noqa: BLE001 - re-raised below as a key-free errorfailure_type = type(exc).__name__@@ -531,6 +536,7 @@ def warn_if_weak_kdf_with_existing_databases(return False# Only count + truthiness are used, so no need to sort the glob result.+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Startup diagnostic enumerates a fixed DB filename pattern under the operator-configured data directoryexisting = list(Path(data_dir).glob("ldr_user_*.db"))if not existing:return False@@ -576,13 +582,19 @@ def apply_cipher_defaults_before_key(f"Applying cipher_default_* pragmas for new DB: settings={settings}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: PRAGMA cannot be bound; page_size is an int in VALID_PAGE_SIZEScursor_or_conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA page_size is an int checked against VALID_PAGE_SIZESf"PRAGMA cipher_default_page_size = {settings['page_size']}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: PRAGMA cannot be bound; hmac_algorithm is an EnumSetting allow-list valuecursor_or_conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA HMAC algorithm comes from the EnumSetting allowlistf"PRAGMA cipher_default_hmac_algorithm = {settings['hmac_algorithm']}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: PRAGMA cannot be bound; kdf_algorithm is an EnumSetting allow-list valuecursor_or_conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA KDF algorithm comes from the EnumSetting allowlistf"PRAGMA cipher_default_kdf_algorithm = {settings['kdf_algorithm']}")@@ -610,17 +622,24 @@ def apply_sqlcipher_pragmas(if not creation_mode:# For existing databases: cipher_* pragmas go AFTER the key+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: PRAGMA cannot be bound; page_size is an int in VALID_PAGE_SIZEScursor_or_conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA page_size is an int checked against VALID_PAGE_SIZESf"PRAGMA cipher_page_size = {settings['page_size']}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: PRAGMA cannot be bound; hmac_algorithm is an EnumSetting allow-list valuecursor_or_conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA HMAC algorithm comes from the EnumSetting allowlistf"PRAGMA cipher_hmac_algorithm = {settings['hmac_algorithm']}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: PRAGMA cannot be bound; kdf_algorithm is an EnumSetting allow-list valuecursor_or_conn.execute(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: PRAGMA KDF algorithm comes from the EnumSetting allowlistf"PRAGMA cipher_kdf_algorithm = {settings['kdf_algorithm']}")# kdf_iter can be set after the key (applies to future derivation)+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA cannot be bound; kdf_iterations is a range-checked IntegerSettingcursor_or_conn.execute(f"PRAGMA kdf_iter = {settings['kdf_iterations']}")# cipher_memory_security is a runtime PRAGMA. ON zeroes SQLCipher buffers@@ -640,6 +659,7 @@ def apply_sqlcipher_pragmas(raise ValueError(f"cipher_memory_security must be ON or OFF, got: {mem_security!r}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA cannot be bound; value checked against ("ON"; "OFF") abovecursor_or_conn.execute(f"PRAGMA cipher_memory_security = {mem_security}")@@ -678,6 +698,7 @@ def apply_performance_pragmas(cursor_or_conn: Any) -> None:# transaction, and the upper bound (300 s) caps tail latency if a# query goes pathological.busy_timeout_ms = int(get_env_setting("db_config.busy_timeout_ms", 30000))+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA cannot be bound; value coerced with int() abovecursor_or_conn.execute(f"PRAGMA busy_timeout = {busy_timeout_ms}")# SQLite defaults foreign_keys to OFF — without this every@@ -690,6 +711,7 @@ def apply_performance_pragmas(cursor_or_conn: Any) -> None:# at this point rather than becoming an injection vector downstream.cache_mb = int(get_env_setting("db_config.cache_size_mb", 64))cache_pages = -(cache_mb * 1024) # Negative for KB cache size+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA cannot be bound; value derived from int() abovecursor_or_conn.execute(f"PRAGMA cache_size = {cache_pages}")# Journal mode - registry validates against allowed values. Belt-and-@@ -705,7 +727,7 @@ def apply_performance_pragmas(cursor_or_conn: Any) -> None:):raise ValueError(f"Invalid journal_mode: {journal_mode!r}")if journal_mode == "WAL":- # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: journal_mode is one of the six literal modes checked above; PRAGMA mode cannot be bound+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: journal_mode is one of the six literal modes checked above; PRAGMA mode cannot be boundcursor_or_conn.execute(f"PRAGMA journal_mode = {journal_mode}")else:# Leaving WAL mode closes the WAL inside SQLite's pager. On SQLite@@ -714,13 +736,14 @@ def apply_performance_pragmas(cursor_or_conn: Any) -> None:from .sqlcipher_compat import wal_lifecycle_guardwith wal_lifecycle_guard():- # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: journal_mode is one of the six literal modes checked above; PRAGMA mode cannot be bound+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: journal_mode is one of the six literal modes checked above; PRAGMA mode cannot be boundcursor_or_conn.execute(f"PRAGMA journal_mode = {journal_mode}")# Synchronous mode - same defense-in-depth pattern.sync_mode = get_env_setting("db_config.synchronous", "NORMAL")if sync_mode not in ("OFF", "NORMAL", "FULL", "EXTRA"):raise ValueError(f"Invalid synchronous mode: {sync_mode!r}")+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA cannot be bound; value checked against an allow-list abovecursor_or_conn.execute(f"PRAGMA synchronous = {sync_mode}")# WAL autocheckpoint frame threshold. SQLite's default of 1000 frames@@ -729,6 +752,7 @@ def apply_performance_pragmas(cursor_or_conn: Any) -> None:# threshold bounds the WAL high-water-mark on disk for users who never# log out (the explicit TRUNCATE checkpoint runs on dispose, not here).wal_autocheckpoint = get_env_setting("db_config.wal_autocheckpoint", 250)+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, semgrep.rules.sql-string-concatenation, reason: PRAGMA cannot be bound; wal_autocheckpoint is a range-checked IntegerSettingcursor_or_conn.execute(f"PRAGMA wal_autocheckpoint = {wal_autocheckpoint}")diff --git a/src/local_deep_research/document_loaders/bytes_loader.py b/src/local_deep_research/document_loaders/bytes_loader.pyindex d3d61ece96..959144948d 100644--- a/src/local_deep_research/document_loaders/bytes_loader.py+++ b/src/local_deep_research/document_loaders/bytes_loader.py@@ -170,6 +170,7 @@ def load_from_bytes(# Clean up temp fileif tmp_path:try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: tmp_path is this call's NamedTemporaryFile name; the upload filename is not used as a pathPath(tmp_path).unlink(missing_ok=True)except Exception:logger.warning(f"Failed to clean up temp file: {tmp_path}")diff --git a/src/local_deep_research/document_loaders/text_encoding.py b/src/local_deep_research/document_loaders/text_encoding.pyindex b09640f7f2..50f3faea4f 100644--- a/src/local_deep_research/document_loaders/text_encoding.py+++ b/src/local_deep_research/document_loaders/text_encoding.py@@ -72,6 +72,7 @@ def detect_text_encoding(raw: bytes) -> str | None:def _file_encoding(file_path: str | Path) -> str:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Encoding loader reads its explicit local file argument; byte uploads pass a server-created temporary fileencoding = detect_text_encoding(Path(file_path).read_bytes())if encoding is None:raise ValueError(diff --git a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.pyindex e0126a50ac..f6a7659861 100644--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py@@ -456,6 +456,7 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):/ "main")try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Repository comes from the curated embedding catalog; refs/main is inside the operator model cachecached_revision = reference.read_text(encoding="ascii").strip()except FileNotFoundError:cached_revision = None@@ -482,6 +483,7 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):cache_dir = cls._model_cache_directory()cache = Path(cache_dir) / ("models--" + repository.replace("/", "--"))try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Repository comes from the curated embedding catalog; only its local cache directory is enumeratedreturn next(cache.iterdir(), None) is not Noneexcept FileNotFoundError:return Falsediff --git a/src/local_deep_research/journal_quality/db.py b/src/local_deep_research/journal_quality/db.pyindex f0c0f642d1..d49e3f98fd 100644--- a/src/local_deep_research/journal_quality/db.py+++ b/src/local_deep_research/journal_quality/db.py@@ -1354,6 +1354,7 @@ def build_db(# Stamp schema version so _ensure_engine can detect drift# without depending on the external version.json.conn.exec_driver_sql(+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Schema version is the module integer constant JOURNAL_QUALITY_SCHEMA_VERSIONf"PRAGMA user_version = {JOURNAL_QUALITY_SCHEMA_VERSION}")except Exception:diff --git a/src/local_deep_research/llm/providers/auto_discovery.py b/src/local_deep_research/llm/providers/auto_discovery.pyindex 56dd859a75..dccde6a7f2 100644--- a/src/local_deep_research/llm/providers/auto_discovery.py+++ b/src/local_deep_research/llm/providers/auto_discovery.py@@ -95,6 +95,7 @@ class ProviderDiscovery:# Scan all Python files in the implementations directorylogger.info(f"Scanning directory: {implementations_dir}")+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Provider modules are discovered beneath the installed package __file__ directoryfor file_path in implementations_dir.glob("*.py"):# Skip special files (like __init__.py)if file_path.name.startswith("_"):diff --git a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py b/src/local_deep_research/research_library/deletion/utils/cascade_helper.pyindex be0301a992..66a9188030 100644--- a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py+++ b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py@@ -393,6 +393,7 @@ class CascadeHelper:return Falseif path.is_file():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Leaf symlinks are refused and resolved containment is checked above; document callers require an allowed rootpath.unlink()logger.debug(f"Deleted filesystem file: {file_path}")return True@@ -441,6 +442,7 @@ class CascadeHelper:f"Refusing to delete symlinked FAISS index file: {faiss_file}")elif faiss_file.is_file():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: The index base passed the resolved root check and this .faiss leaf is not a symlinkfaiss_file.unlink()logger.debug(f"Deleted FAISS index file: {faiss_file}")deleted_any = True@@ -452,6 +454,7 @@ class CascadeHelper:f"Refusing to delete symlinked FAISS pkl file: {pkl_file}")elif pkl_file.is_file():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: The index base passed the resolved root check and this .pkl leaf is not a symlinkpkl_file.unlink()logger.debug(f"Deleted FAISS pkl file: {pkl_file}")deleted_any = True@@ -466,6 +469,7 @@ class CascadeHelper:f"Refusing to delete symlinked FAISS idmap sidecar: {idmap_file}")elif idmap_file.is_file():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: The index base passed the resolved root check and this id-map leaf is not a symlinkidmap_file.unlink()logger.debug(f"Deleted FAISS idmap sidecar: {idmap_file}")deleted_any = True@@ -484,6 +488,7 @@ class CascadeHelper:# temps old enough to be certainly crash-orphaned (mirrors# persist()'s own _STALE_TMP_AGE_SECONDS sweep). A younger temp is# left; a later delete/persist sweeps it once it ages out.+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Enumerate generated temp names beside the root-checked index basefor stray in parent.glob(f"{base.name}.*.tmp"):try:if stray.is_symlink():@@ -493,6 +498,7 @@ class CascadeHelper:continueif now - stray.stat().st_mtime < _STALE_TMP_AGE_SECONDS:continue+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Only aged index temp files from the bounded parent glob reach this unlink; symlink leaves are skippedstray.unlink()logger.debug(f"Removed stray temp index file: {stray}")deleted_any = True@@ -505,6 +511,7 @@ class CascadeHelper:)# .corrupt-* are quarantine artefacts (and .pkl.corrupt-* is# PLAINTEXT) — always safe and required to remove, no age gate.+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Enumerate generated quarantine names beside the root-checked index basefor stray in parent.glob(f"{base.name}.corrupt-*"):try:if stray.is_symlink():@@ -512,6 +519,7 @@ class CascadeHelper:f"Refusing to remove symlinked stray index file: {stray}")continue+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Only files from the bounded quarantine glob reach this unlink; symlink leaves are skippedstray.unlink()logger.debug(f"Removed quarantined index file: {stray}")deleted_any = Truediff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 28e23cfa23..77b2f8f129 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -2000,6 +2000,7 @@ class DownloadService:"""Check for legacy text files on disk."""txt_path = Path(self.library_root) / "txt"existing_files = (+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Per-user library text directory and integer resource ID from the user DB; this only enumerates legacy nameslist(txt_path.glob(f"*_{resource_id}.txt"))if txt_path.exists()else []diff --git a/src/local_deep_research/security/directory_creation.py b/src/local_deep_research/security/directory_creation.pyindex 4a31b201c1..1a493fb922 100644--- a/src/local_deep_research/security/directory_creation.py+++ b/src/local_deep_research/security/directory_creation.py@@ -101,8 +101,10 @@ def create_directory()if mode is not None:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Verified directory helper rejects nulls and traversal segments and checks resolved containment when root is suppliedp.mkdir(parents=parents, exist_ok=exist_ok, mode=mode)else:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Verified directory helper rejects nulls and traversal segments and checks resolved containment when root is suppliedp.mkdir(parents=parents, exist_ok=exist_ok)logger.debug(f"Verified directory creation: {p} ({context})")diff --git a/src/local_deep_research/security/security_settings.py b/src/local_deep_research/security/security_settings.pyindex 8028ebc2f5..ef6fe4f393 100644--- a/src/local_deep_research/security/security_settings.py+++ b/src/local_deep_research/security/security_settings.py@@ -32,6 +32,7 @@ def _load_security_settings() -> dict:"""try:if _SETTINGS_PATH.exists():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Fixed settings filename below the installed package __file__ directorywith open(_SETTINGS_PATH, "r", encoding="utf-8-sig") as f:return json.load(f)except Exception:diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.pyindex 5e42be8856..04da74d7a8 100644--- a/src/local_deep_research/settings/manager.py+++ b/src/local_deep_research/settings/manager.py@@ -788,6 +788,7 @@ class SettingsManager(ISettingsManager):defaults_path = Path(defaults.__file__).parent# Find all JSON files recursively in the defaults directory+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Only JSON defaults beneath the installed defaults package are enumeratedjson_files = sorted(defaults_path.rglob("*.json"))logger.debug(f"Found {len(json_files)} JSON settings files")@@ -795,6 +796,7 @@ class SettingsManager(ISettingsManager):# Load and merge all JSON filesfor json_file in json_files:try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Each file comes from the installed defaults package JSON glob abovewith open(json_file, "r", encoding="utf-8-sig") as f:file_settings = json.load(f)diff --git a/src/local_deep_research/utilities/es_utils.py b/src/local_deep_research/utilities/es_utils.pyindex ed14063ea5..7212944d1f 100644--- a/src/local_deep_research/utilities/es_utils.py+++ b/src/local_deep_research/utilities/es_utils.py@@ -359,6 +359,7 @@ class ElasticsearchManager:all_files = []directory = Path(directory_path)for pattern in file_patterns:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Local Python indexing API intentionally accepts caller-selected directories and glob patterns; no web callermatching_files = list(directory.glob(pattern))all_files.extend([str(f) for f in matching_files])diff --git a/src/local_deep_research/utilities/office_conversion.py b/src/local_deep_research/utilities/office_conversion.pyindex 00dff59687..d79c880176 100644--- a/src/local_deep_research/utilities/office_conversion.py+++ b/src/local_deep_research/utilities/office_conversion.py@@ -139,9 +139,11 @@ def convert_legacy_office_bytes(profile_dir = work_dir / f"profile_{uuid.uuid4().hex}"try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Validated stem and allowlisted extension inside a private conversion directory; upload callers cannot choose output_dirin_path.write_bytes(content)# Defensive pre-clean: a stale file at out_path from an earlier# call in a shared output_dir must not fake a successful run.+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Fixed converted filename derived from the validated stem and allowlisted target extension in the conversion directoryout_path.unlink(missing_ok=True)command = [@@ -200,6 +202,7 @@ def convert_legacy_office_bytes(f"converted output is larger than {max_output_bytes} bytes")+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Read the size-checked converter output with the fixed target extension from this call's conversion directoryconverted = out_path.read_bytes()logger.debug("legacy office conversion ok: {} -> {} ({} bytes)",@@ -213,11 +216,14 @@ def convert_legacy_office_bytes(# caller's content, soffice's output, and the profile tree.for path in (in_path, out_path):try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Cleanup is limited to this conversion's validated input and output filenamespath.unlink(missing_ok=True)except OSError:logger.warning("could not remove conversion temp file")+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Profile directory uses a fresh UUID beneath this call's conversion directoryshutil.rmtree(profile_dir, ignore_errors=True)if output_dir is None:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Only this call's mkdtemp directory is recursively removed; caller-owned output directories are retainedshutil.rmtree(work_dir, ignore_errors=True)diff --git a/src/local_deep_research/utilities/pandoc_conversion.py b/src/local_deep_research/utilities/pandoc_conversion.pyindex d7d5b6727b..06a34578e7 100644--- a/src/local_deep_research/utilities/pandoc_conversion.py+++ b/src/local_deep_research/utilities/pandoc_conversion.py@@ -270,7 +270,9 @@ def pandoc_convert_bytes_to_html(out_path = scratch / "out.html"try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Fixed filename and allowlisted extension inside a private conversion directory; upload callers cannot choose work_dirin_path.write_bytes(content)+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Fixed out.html inside this call's conversion directoryout_path.unlink(missing_ok=True)# --sandbox restricts pandoc's own file access (same posture@@ -337,6 +339,7 @@ def pandoc_convert_bytes_to_html(f"converted output is larger than {max_output_bytes} bytes")+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Read the size-checked fixed out.html from this call's conversion directoryconverted = out_path.read_bytes()logger.debug("pandoc conversion ok: {} -> html ({} bytes)",@@ -347,8 +350,10 @@ def pandoc_convert_bytes_to_html(finally:for path in (in_path, out_path):try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Cleanup is limited to this conversion's fixed input and output filenamespath.unlink(missing_ok=True)except OSError:logger.warning("could not remove conversion temp file")if owned_dir:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Only this call's mkdtemp directory is recursively removed; caller-owned work directories are retainedshutil.rmtree(scratch, ignore_errors=True)diff --git a/src/local_deep_research/vector_stores/implementations/faiss_store.py b/src/local_deep_research/vector_stores/implementations/faiss_store.pyindex 23ae534ee5..768d9030ac 100644--- a/src/local_deep_research/vector_stores/implementations/faiss_store.py+++ b/src/local_deep_research/vector_stores/implementations/faiss_store.py@@ -552,10 +552,12 @@ class FaissVectorStore(BaseVectorStore):# minutes/hours old, while an in-flight one was just created, and no# single write approaches this age — so a live temp is never swept.now = time.time()+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Index persistence intentionally targets its service-supplied local index path; glob is limited to that basename's temp filesfor stale in path.parent.glob(f"{path.name}.*.tmp"):try:if now - stale.stat().st_mtime < _STALE_TMP_AGE_SECONDS:continue # too recent — may be a concurrent worker's temp+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Only aged temp files from this index basename's parent glob are unlinkedstale.unlink()except OSError:logger.warning(f"Could not remove stale temp file {stale}")@@ -576,6 +578,7 @@ class FaissVectorStore(BaseVectorStore):# leave a renamed-but-unflushed (torn) index — the rename is only# atomic w.r.t. what has actually reached disk.try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: tmp is the random O_EXCL mkstemp file created above inside the private index directorywith open(tmp, "r+b") as f:os.fsync(f.fileno())except OSError:@@ -583,6 +586,7 @@ class FaissVectorStore(BaseVectorStore):os.replace(tmp, path)# fsync the directory so the rename itself is durable across a crash.try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Open the service-supplied index parent directory only to fsync the completed atomic renamedir_fd = os.open(str(path.parent), os.O_RDONLY)try:os.fsync(dir_fd)@@ -593,6 +597,7 @@ class FaissVectorStore(BaseVectorStore):finally:if tmp.exists():try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: tmp is this persist call's mkstemp file; final cleanup never uses the index payload as a pathtmp.unlink()except OSError:logger.warning(f"Could not remove temp index file {tmp}")diff --git a/src/local_deep_research/vector_stores/legacy_cleanup.py b/src/local_deep_research/vector_stores/legacy_cleanup.pyindex a9adbdd0e6..78659af7a6 100644--- a/src/local_deep_research/vector_stores/legacy_cleanup.py+++ b/src/local_deep_research/vector_stores/legacy_cleanup.py@@ -263,6 +263,7 @@ def _write_sidecar_atomic(sidecar: Path, id_map: Dict[str, str]) -> None:finally:if tmp.exists():try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: tmp is this sidecar write's mkstemp file; final cleanup removes only that generated temporary nametmp.unlink()except OSError:logger.warning(f"Could not remove temp sidecar {tmp}")@@ -539,6 +540,7 @@ def rekey_index_file(# after the uuid->id resolution changed) would be silently adopted, and# its baked-in ids would rehydrate the WRONG document's text on search.try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: production caller rekey_user_indexes derives this sidecar from LibraryRAGService's generated index path in the authenticated user's DB; requests cannot assign that pathpos_to_uuid = json.loads(sidecar_path.read_text(encoding="utf-8"))except FileNotFoundError:# The sidecar is the caller's COMPLETION SIGNAL: it is deleted only@@ -638,6 +640,7 @@ def rekey_index_file()try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: production caller rekey_user_indexes derives this sidecar from LibraryRAGService's generated index path in the authenticated user's DB; requests cannot assign that pathpos_to_uuid = json.loads(sidecar_path.read_text(encoding="utf-8"))except FileNotFoundError:# A concurrent worker (multi-process: gunicorn -w N / the scheduler,diff --git a/src/local_deep_research/vector_stores/legacy_rekey.py b/src/local_deep_research/vector_stores/legacy_rekey.pyindex 297458d574..c202dd6de3 100644--- a/src/local_deep_research/vector_stores/legacy_rekey.py+++ b/src/local_deep_research/vector_stores/legacy_rekey.py@@ -343,6 +343,10 @@ def rekey_user_indexes(username: str, db_password: str) -> Dict[str, int]:for rag_index in indexes:stats["checked"] += 1+ # LibraryRAGService owns all index_path writes: _get_index_path uses+ # an operator cache root and hash-based names. No request or import+ # endpoint accepts this column. Keep that boundary when adding writers;+ # being stored in the DB alone would not make a path trustworthy.faiss_path = Path(rag_index.index_path)sidecar_path = _sidecar_for(faiss_path)# Per-(user, index_path) write lock, held for every file mutation@@ -442,6 +446,7 @@ def rekey_user_indexes(username: str, db_password: str) -> Dict[str, int]:if not _purge_redundant_pkl(faiss_path, db_password):all_resolved = Falsetry:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: fixed-suffix sidecar of LibraryRAGService's generated index path loaded from the authenticated user's DB; see the index_path writer boundary abovesidecar_path.unlink(missing_ok=True)except OSError:logger.warning(@@ -481,6 +486,7 @@ def rekey_user_indexes(username: str, db_password: str) -> Dict[str, int]:# legacy index (which would force a needless full re-embed); withhold the# marker and retry next login instead.try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: fixed-suffix sidecar of LibraryRAGService's generated index path loaded from the authenticated user's DB; see the index_path writer boundary abovepos_to_uuid = json.loads(sidecar_path.read_text(encoding="utf-8"))uuid_to_id = _load_uuid_to_id(username, db_password, set(pos_to_uuid.values())@@ -548,6 +554,7 @@ def rekey_user_indexes(username: str, db_password: str) -> Dict[str, int]:)# Config was already pinned before the build (see above), so# Phase B only records integrity and drops the sidecar signal.+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: fixed-suffix sidecar of LibraryRAGService's generated index path loaded from the authenticated user's DB; see the index_path writer boundary abovesidecar_path.unlink(missing_ok=True)# Backstop: if phase-1 wrote the sidecar but its .pkl unlink# failed, the plaintext .pkl is still on disk. The re-key justdiff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.pyindex 8d064b3091..6509308c1a 100644--- a/src/local_deep_research/web/fastapi_app.py+++ b/src/local_deep_research/web/fastapi_app.py@@ -183,7 +183,10 @@ def _load_secret_key() -> str:new_key = secrets.token_hex(32)try:fd = os.open(- str(secret_key_file), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Fixed .secret_key below the operator data root; creation is exclusive with mode 0600+ str(secret_key_file),+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,+ 0o600,)try:os.write(fd, new_key.encode())@@ -196,6 +199,7 @@ def _load_secret_key() -> str:# in-memory key would silently invalidate every existing session# on restart and prevent any future restart from being consistent.try:+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Fixed .secret_key below the operator data root; requests cannot select this filenamewith open(secret_key_file, "r", encoding="utf-8") as f:key = f.read().strip()except Exception as e:@@ -399,6 +403,7 @@ async def lifespan(app: FastAPI):static_dir = Path(STATIC_DIR)themes_css_path = static_dir / "css" / "themes.css"combined_css = theme_registry.get_combined_css()+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Fixed css/themes.css below the installed package static directory at startupthemes_css_path.write_text(combined_css, encoding="utf-8")logger.debug(f"Generated themes.css with {len(theme_registry.themes)} themes"@@ -2808,9 +2813,11 @@ def _validate_url_for_bindings(app: "FastAPI") -> None:template_dir = Path(TEMPLATE_DIR)names: set[str] = set()+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Startup link validation enumerates only the installed package HTML templatesfor tpl_path in template_dir.rglob("*.html"):names.update(_URL_FOR_NAME_RE.findall(+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Template path comes from the installed package HTML glob abovetpl_path.read_text(encoding="utf-8", errors="replace")))diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.pyindex 1d5fe783c2..ffe3618b87 100644--- a/src/local_deep_research/web/routers/library.py+++ b/src/local_deep_research/web/routers/library.py@@ -891,6 +891,7 @@ def download_all_text(txt_path = Path(download_service.library_root) / "txt"existing_resource_ids = set()if txt_path.exists():+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Only enumerate fixed txt names under this authenticated user's resolved library directoryfor txt_file in txt_path.glob("*.txt"):# Extract resource ID from filename pattern *_{id}.txtparts = txt_file.stem.rsplit("_", 1)diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.pyindex 8e4387ac35..40ba354b8b 100644--- a/src/local_deep_research/web/routers/research.py+++ b/src/local_deep_research/web/routers/research.py@@ -1770,6 +1770,7 @@ def _unlink_report_file_if_inside_root(report_path: Optional[str]) -> bool:)return False+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Leaf symlinks are refused and the fully resolved path must be inside the reports root before unlinkpath.unlink()return Trueexcept FileNotFoundError:diff --git a/tests/ci/standalone/test_dependency_licenses.py b/tests/ci/standalone/test_dependency_licenses.pynew file mode 100644index 0000000000..8d41c15552--- /dev/null+++ b/tests/ci/standalone/test_dependency_licenses.py@@ -0,0 +1,591 @@+"""Exercise the real license guard against repository and requirements changes."""++import importlib.util+import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[3]+SCRIPT = ROOT / ".github/scripts/check_dependency_licenses.py"+SPEC = importlib.util.spec_from_file_location("dependency_licenses", SCRIPT)+POLICY = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(POLICY)+++class LicensePolicyTests(unittest.TestCase):+ def setUp(self):+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.root = Path(directory.name)+ subprocess.run(["git", "init", "-q", self.root], check=True)+ self.write(+ "pyproject.toml",+ '[project]\ndependencies = ["typing-extensions~=4.15"]\n',+ )+ self.write(+ "pdm.lock",+ '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n',+ )+ self.write("requirements/semgrep.in", "semgrep==1.179.0\n")+ self.write(+ "requirements/semgrep.txt",+ "semgrep==1.179.0\nprotobuf==6.33.6\ntyping-extensions==4.16.0\n",+ )+ self.write("requirements/twine.txt", "docutils==0.23\n")++ def write(self, relative, content):+ path = self.root / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content, encoding="utf-8")+ return path++ def reject(self, relative, content, message):+ path = self.root / relative+ previous = path.read_text(encoding="utf-8") if path.exists() else None+ try:+ self.write(relative, content)+ errors = POLICY.validate(self.root)+ self.assertTrue(errors, (relative, content))+ self.assertIn(message, "\n".join(errors))+ finally:+ if previous is None:+ path.unlink()+ else:+ path.write_text(previous, encoding="utf-8")++ def test_repository_and_reviewed_fixture_pass(self):+ self.assertEqual(POLICY.validate(ROOT), [])+ self.assertEqual(POLICY.validate(self.root), [])++ def test_plain_requirements_in_new_locations_do_not_bypass_review(self):+ # Regression: the old regex only recognized pins ending in a backslash.+ for location in (+ "requirements/probe.txt",+ "requirements/probe.in",+ "requirements/nested/probe.txt",+ "requirements/nested/probe.in",+ "requirements.txt",+ "requirements-dev.in",+ "ci/requirements-extra.txt",+ "ci/requirements/extra.in",+ "Requirements-dev.TXT",+ "ci/Requirements/extra.IN",+ ):+ with self.subTest(location=location):+ self.reject(location, "protobuf==6.33.5\n", "protobuf")++ def test_normalized_names_spaces_markers_extras_and_hashes_are_parsed(self):+ self.write(+ "requirements/semgrep.txt",+ "# protobuf==6.33.5 is only a comment\n"+ ' PROTOBUF [extra] == 6.33.6 ; sys_platform == "win32"\n'+ "TyPiNg_.Extensions == 4.16.0 \\\n"+ " --hash=sha256:1234 # pip hash option\n",+ )+ self.assertEqual(POLICY.validate(self.root), [])+ for spelling in (+ "typing_extensions",+ "Typing.Extensions",+ "TYPING__EXTENSIONS",+ ):+ with self.subTest(spelling=spelling):+ self.reject(+ "requirements/semgrep.txt",+ f"{spelling}==4.15.0\n",+ "typing-extensions",+ )++ def test_versions_ranges_direct_urls_and_false_markers_need_review(self):+ for requirement in (+ "protobuf==6.33.5",+ "protobuf>=6.33.6",+ "protobuf~=6.33.6",+ "protobuf==6.33.*",+ "protobuf===6.33.6",+ "protobuf",+ 'protobuf==6.33.5; python_version < "2"',+ "protobuf @ https://example.test/protobuf-6.33.6.whl",+ "semgrep==1.180.0",+ "typing_extensions>=4.16.0",+ ):+ with self.subTest(requirement=requirement):+ self.reject(+ "requirements/semgrep.txt", requirement, "requires review"+ )+ self.reject(+ "requirements/twine.txt", "docutils==0.24", "requires review"+ )+ self.reject(+ "requirements/semgrep.in", "semgrep>=1.179.0", "requires review"+ )++ def test_reviewed_version_cannot_move_to_another_environment(self):+ for requirement in (+ "semgrep==1.179.0",+ "docutils==0.23",+ "protobuf==6.33.6",+ "typing_extensions==4.16.0",+ ):+ with self.subTest(requirement=requirement):+ self.reject("requirements/runtime.txt", requirement, "outside")++ def test_local_includes_are_checked_in_the_importing_environment(self):+ self.write("requirements/pins.data", "protobuf==6.33.6\n")+ for directive in (+ "-r pins.data",+ "-rpins.data",+ "--requirement=pins.data",+ "--requirement pins.data",+ "-c pins.data",+ "-cpins.data",+ '--constraint "pins.data"',+ "--constraint=pins.data",+ ):+ with self.subTest(directive=directive):+ self.write("requirements/semgrep.txt", directive)+ self.assertEqual(POLICY.validate(self.root), [])+ self.reject(+ "requirements/pins.data",+ "protobuf==6.33.5",+ "requires review",+ )+ self.write("requirements/middle.data", "-r semgrep.txt\n")+ self.reject(+ "requirements.txt", "-r requirements/middle.data", "outside"+ )+ self.reject("requirements.txt", "-c requirements/twine.txt", "docutils")++ def test_remote_missing_cyclic_and_external_includes_fail_closed(self):+ for directive in (+ "-r https://example.test/pins.txt",+ "-r ${REMOTE_REQUIREMENTS}",+ "-r missing.txt",+ "-r semgrep.txt",+ "-r ../../outside.txt",+ ):+ with self.subTest(directive=directive):+ self.reject(+ "requirements/semgrep.txt",+ directive,+ "requirements/semgrep.txt",+ )++ def test_unsupported_requirements_syntax_fails_closed(self):+ for requirement in (+ "https://example.test/protobuf-6.33.5.whl",+ "-e git+https://example.test/protobuf.git#egg=protobuf",+ "${PACKAGE}==6.33.5",+ "protobuf==6.33.5 \\\n",+ "--index-url https://example.test/simple",+ ):+ with self.subTest(requirement=requirement):+ self.reject(+ "requirements/semgrep.txt",+ requirement,+ "requirements/semgrep.txt",+ )++ def test_comment_lines_terminate_continuations(self):+ # Regression: continuations were joined before comment-stripping,+ # so a comment line inside a join hid the requirement that pip+ # parses on the line after it (pip's join_lines terminates the+ # logical line at a comment, so both requirements are installed).+ for third_line in (+ "protobuf==6.33.5",+ "protobuf @ https://example.test/protobuf-evil.whl",+ ):+ with self.subTest(third_line=third_line):+ self.reject(+ "requirements/semgrep.txt",+ "typing-extensions==4.16.0 \\\n"+ "# via semgrep \\\n"+ f"{third_line}\n",+ "protobuf",+ )+ # A comment without its own continuation also terminates the join.+ self.reject(+ "requirements/semgrep.txt",+ "typing-extensions==4.16.0 \\\n# via semgrep\nprotobuf==6.33.5\n",+ "protobuf",+ )+ # The requirement before the terminated comment stays checked too.+ self.reject(+ "requirements/semgrep.txt",+ "typing-extensions==4.15.0 \\\n# via semgrep\nprotobuf==6.33.6\n",+ "typing-extensions",+ )++ def test_lock_static_urls_and_file_url_entries_need_review(self):+ # Regression: pdm's static-urls strategy installs files[].url+ # entries hash-checked only against the same lock entry, while+ # every [[package]] key stayed inside the allowed set and the+ # guard never inspected [metadata].+ self.reject(+ "pdm.lock",+ '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n'+ 'files = [{url = "https://evil.test/typing_extensions-4.16.0'+ '-py3-none-any.whl", hash = "sha256:abc"}]\n',+ "url entries",+ )+ for strategy in ("static-urls", "static_urls"):+ with self.subTest(strategy=strategy):+ self.write(+ "pdm.lock",+ '[[package]]\nname = "typing-extensions"\n'+ 'version = "4.16.0"\n\n[metadata]\n'+ f'strategy = ["inherit_metadata", "{strategy}"]\n',+ )+ errors = POLICY.validate(self.root)+ self.assertTrue(errors)+ self.assertIn("static-urls lock strategy", "\n".join(errors))+ # The executed bypass shape: url entry plus the enabling strategy.+ self.reject(+ "pdm.lock",+ '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n'+ 'groups = ["default"]\n'+ 'files = [{url = "https://evil.test/typing_extensions-4.16.0'+ '-py3-none-any.whl", hash = "sha256:abc"}]\n'+ '\n[metadata]\nstrategy = ["inherit_metadata", "static-urls"]\n',+ "pdm.lock",+ )+ # Plain {file, hash} entries and non-static strategies stay allowed.+ self.write(+ "pdm.lock",+ '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n'+ 'files = [{file = "typing_extensions-4.16.0-py3-none-any.whl", '+ 'hash = "sha256:abc"}]\n\n'+ '[metadata]\nstrategy = ["inherit_metadata"]\n',+ )+ self.assertEqual(POLICY.validate(self.root), [])++ def test_lock_vcs_pin_and_inline_source_spellings_need_review(self):+ # Companion spellings of the direct-source keys pinned above:+ # vcs pin keys and the inline [package.source] table spelling.+ for source in (+ 'commit = "8f14e45fceea167a5a36dedd4bea2543"',+ 'branch = "backdoor"',+ 'tag = "v4.16.0-backdoor"',+ 'source = {name = "private", url = "https://example.test/simple"}',+ ):+ with self.subTest(source=source):+ self.reject(+ "pdm.lock",+ '[[package]]\nname = "typing-extensions"\n'+ 'version = "4.16.0"\n' + source + "\n",+ "direct sources",+ )++ def test_lock_names_cannot_hide_reviewed_sources_in_requirement_syntax(+ self,+ ):+ # PDM 2.27 accepts an extras-bearing lock name and installs the+ # actual wheel's distribution. Requirement() strips those extras,+ # so checking the unparsed name first used to bypass source policy.+ for name in (+ "typing-extensions[probe]",+ "typing-extensions[]",+ "typing-extensions==4.16.0",+ 'typing-extensions; python_version >= "0"',+ "typing-extensions @ https://example.test/te.whl",+ "typing-extensions\n",+ "typing-extensions\r\n",+ " typing-extensions",+ "typing-extensions ",+ "typing extensions",+ "typing/extensions",+ "other-package[probe]",+ ):+ for source in (+ 'url = "https://example.test/te.whl"\n',+ 'git = "https://example.test/te.git"\n',+ 'files = [{url = "https://example.test/te.whl", hash = "sha256:abc"}]\n',+ "",+ ):+ with self.subTest(name=name, source=source):+ self.reject(+ "pdm.lock",+ f"[[package]]\nname = {json.dumps(name)}\n"+ 'version = "4.16.0"\n' + source,+ "name is invalid",+ )+ # Extras have a separate lock field. Legitimate case, underscore,+ # dot, and repeated-separator spellings retain their normal meaning.+ for name in (+ "Typing_Extensions",+ "typing..extensions",+ "typing---extensions",+ ):+ with self.subTest(valid_name=name):+ self.write(+ "pdm.lock",+ f"[[package]]\nname = {json.dumps(name)}\n"+ 'version = "4.16.0"\nextras = ["probe"]\n',+ )+ self.assertEqual(POLICY.validate(self.root), [])++ def test_all_project_dependency_sections_reject_isolated_tools(self):+ for section, key in (+ ("project", "dependencies"),+ ("project.optional-dependencies", "tools"),+ ("build-system", "requires"),+ ("dependency-groups", "tools"),+ ("tool.pdm.dev-dependencies", "tools"),+ ):+ for requirement in ("Semgrep==1.179.0", "docutils==0.23"):+ with self.subTest(section=section, requirement=requirement):+ self.reject(+ "pyproject.toml",+ f'[{section}]\n{key} = ["{requirement}"]\n',+ "outside",+ )++ def test_application_range_and_resolved_version_are_reviewed_separately(+ self,+ ):+ self.reject(+ "pyproject.toml",+ '[project]\ndependencies = ["typing_extensions>=4"]\n',+ "requires review",+ )+ self.reject(+ "pdm.lock",+ '[[package]]\nname = "Typing_Extensions"\nversion = "4.15.0"\n',+ "requires review",+ )+ for source in (+ 'url = "https://example.test/a.whl"',+ 'git = "https://example.test/a.git"',+ 'path = "./vendor"',+ 'hg = "https://example.test/a.hg"',+ 'svn = "https://example.test/a.svn"',+ 'bzr = "https://example.test/a.bzr"',+ 'vcs = "hg"',+ 'ref = "backdoor"',+ 'revision = "backdoor"',+ 'subdirectory = "nested"',+ 'remote = "https://example.test/a"',+ '[package.source]\nurl = "https://example.test/a.whl"',+ ):+ with self.subTest(source=source):+ self.reject(+ "pdm.lock",+ '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n'+ + source,+ "direct sources",+ )++ def test_pylock_format_locks_fail_closed(self):+ # Regression: pdm installs from pylock-format locks ([[packages]],+ # top-level lock-version), which the legacy lock.get("package")+ # loop never inspected, so no reviewed check ran at all.+ self.reject(+ "pdm.lock",+ 'lock-version = "1.0"\n\n[[packages]]\n'+ 'name = "typing-extensions"\nversion = "4.16.0"\n\n'+ '[packages.vcs]\ntype = "hg"\n'+ 'url = "https://example.test/te.hg"\n'+ 'requested-revision = "backdoor"\n',+ "pylock",+ )+ # Even a source-free pylock lock must not slip past unexamined.+ self.reject(+ "pdm.lock",+ '[[packages]]\nname = "typing-extensions"\nversion = "4.15.0"\n',+ "pylock",+ )+ # Even another claimed name must not hide an exempted wheel behind+ # a direct source; PDM uses the installed artifact's actual name.+ self.reject(+ "pdm.lock",+ '[[package]]\nname = "typing-extensions"\nversion = "4.16.0"\n\n'+ '[[package]]\nname = "other-package"\nversion = "1.0"\n'+ 'hg = "https://example.test/other.hg"\n',+ "direct sources",+ )++ def test_valid_aliases_cannot_hide_direct_artifacts(self):+ for name in ("helper-package", "typing-extensions"):+ for source in (+ 'url = "https://example.test/typing_extensions-4.16.0.whl"',+ 'path = "./vendor/helper"',+ 'git = "https://example.test/helper.git"',+ '[package.source]\nurl = "https://example.test/simple"',+ 'files = [{url = "https://example.test/te.whl", hash = "sha256:abc"}]',+ ):+ with self.subTest(name=name, source=source):+ self.reject(+ "pdm.lock",+ f'[[package]]\nname = "{name}"\nversion = "4.16.0"\n'+ + source,+ "review",+ )+ self.reject(+ "pdm.lock",+ "[metadata]\nstatic_urls = true\n"+ f'[[package]]\nname = "{name}"\nversion = "4.16.0"\n',+ "static-urls",+ )+ for location, content in (+ (+ "requirements/semgrep.txt",+ "helper @ https://example.test/te.whl",+ ),+ (+ "pyproject.toml",+ '[project]\ndependencies=["helper @ https://example.test/te.whl"]',+ ),+ (+ "pyproject.toml",+ '[build-system]\nrequires=["helper @ https://example.test/te.whl"]',+ ),+ ):+ with self.subTest(location=location, content=content):+ self.reject(location, content, "direct source requires review")+ for value in (+ "https://example.test/te.whl",+ "file:///tmp/te.whl",+ "git+https://example.test/te.git",+ "./vendor/helper",+ ):+ with self.subTest(override=value):+ self.reject(+ "pyproject.toml",+ "[tool.pdm.resolution.overrides]\n"+ f"helper = {json.dumps(value)}\n",+ "sources need review",+ )++ def test_subproject_manifests_are_not_skipped(self):+ self.reject(+ "tools/pyproject.toml",+ '[project]\ndependencies = ["semgrep==1.179.0"]',+ "outside",+ )+ self.reject(+ "tools/pdm.lock",+ '[[package]]\nname = "docutils"\nversion = "0.23"',+ "outside",+ )++ def test_unsupported_python_manifests_fail_closed(self):+ # These formats can add dependencies without going through the+ # requirements/PEP 621/PDM parsers. Never execute setup.py to read it.+ manifests = {+ "setup.py": 'raise RuntimeError("must not execute setup.py")',+ "setup.cfg": "[options]\ninstall_requires = semgrep==1.178.0\n",+ "Pipfile": '[packages]\nsemgrep = "==1.178.0"\n',+ "Pipfile.lock": '{"default":{"semgrep":{"version":"==1.178.0"}}}',+ "poetry.lock": '[[package]]\nname="semgrep"\nversion="1.178.0"\n',+ "uv.lock": '[[package]]\nname="semgrep"\nversion="1.178.0"\n',+ "uv.toml": 'index-url = "https://example.test/simple"\n',+ "pylock.toml": 'lock-version = "1.0"\n',+ "pylock.tools.toml": 'lock-version = "1.0"\n',+ "pdm.toml": '[pypi]\nurl = "https://example.test/simple"\n',+ ".pdm.toml": '[pypi]\nurl = "https://example.test/simple"\n',+ }+ for name, content in manifests.items():+ for location in (name, f"tools/{name}", f"tools/{name.upper()}"):+ with self.subTest(location=location):+ self.reject(+ location, content, "unsupported Python manifest"+ )++ def test_unparsed_project_dependency_schemas_fail_closed(self):+ for content in (+ '[tool.poetry.dependencies]\nsemgrep = "1.178.0"\n',+ '[tool.poetry.group.dev.dependencies]\nsemgrep = "1.178.0"\n',+ '[tool.uv]\ndev-dependencies = ["semgrep==1.178.0"]\n',+ '[tool.hatch.envs.default]\ndependencies = ["semgrep==1.178.0"]\n',+ '[tool.pixi.pypi-dependencies]\nsemgrep = "==1.178.0"\n',+ '[project]\ndynamic = ["dependencies"]\n',+ '[project]\ndynamic = ["optional-dependencies"]\n',+ '[tool.setuptools.dynamic]\ndependencies = {file = "deps.data"}\n',+ '[tool.pdm]\nplugins = ["semgrep==1.178.0"]\n',+ '[tool.pdm.resolution.overrides]\nTyping_Extensions = ">=4"\n',+ "[tool.pdm.resolution.overrides]\n"+ '"typing-extensions[extra]" = "https://example.test/te.whl"\n',+ ):+ for location in ("pyproject.toml", "tools/pyproject.toml"):+ with self.subTest(location=location, content=content):+ self.reject(location, content, "needs review")++ def test_pdm_indexes_are_limited_to_the_reviewed_torch_source(self):+ baseline = (self.root / "pyproject.toml").read_text(encoding="utf-8")+ torch = (+ '\n[[tool.pdm.source]]\nname = "torch"\n'+ 'url = "https://download.pytorch.org/whl/cpu"\n'+ 'include_packages = ["torch", "torch*"]\n'+ )+ self.write("pyproject.toml", baseline + torch)+ self.assertEqual(POLICY.validate(self.root), [])+ for source in (+ 'name = "pypi"\nurl = "https://example.test/simple"\n',+ 'name = "pypi"\ntype = "find_links"\nurl = "file:///tmp/wheels"\n'+ 'include_packages = ["typing-extensions"]\n',+ 'name = "extra"\nurl = "https://example.test/simple"\n',+ 'name = "extra"\nurl = "https://example.test/simple"\n'+ 'include_packages = ["TyPiNg_Extensions", "protobuf*"]\n',+ ):+ with self.subTest(source=source):+ self.reject(+ "pyproject.toml",+ baseline + torch + "\n[[tool.pdm.source]]\n" + source,+ "PDM source configuration needs review",+ )+ for changed in (+ torch.replace('"torch*"', '"*"'),+ torch.replace('name = "torch"', 'name = "pypi"'),+ torch.replace("download.pytorch.org", "example.test"),+ torch.replace('include_packages = ["torch", "torch*"]', ""),+ torch + 'exclude_packages = ["torch"]\n',+ torch + 'type = "find_links"\n',+ torch + torch,+ ):+ with self.subTest(changed=changed):+ self.reject(+ "pyproject.toml",+ baseline + changed,+ "PDM source configuration needs review",+ )++ def test_unrecognized_pdm_resolution_options_need_review(self):+ self.reject(+ "pyproject.toml",+ '[tool.pdm.resolution]\nfuture-source = "https://example.test"\n',+ "needs review",+ )+ self.write(+ "pyproject.toml",+ '[project]\ndynamic = ["version"]\n'+ '[tool.pdm.resolution.overrides]\nrequests = ">=2.33"\n'+ 'lxml = ">=6.0"\n[tool.setuptools]\ninclude-package-data = true\n',+ )+ self.assertEqual(POLICY.validate(self.root), [])++ def test_symlinked_manifests_and_includes_are_rejected(self):+ target = self.write("pins.data", "protobuf==6.33.6\n")+ path = self.root / "requirements/semgrep.txt"+ path.unlink()+ path.symlink_to(target)+ self.assertIn("symlink", "\n".join(POLICY.validate(self.root)))++ def test_cli_returns_failure_for_the_original_bypass(self):+ self.write(+ "requirements/license-review-probe.txt", "protobuf==6.33.5\n"+ )+ result = subprocess.run(+ [sys.executable, str(SCRIPT), str(self.root)],+ capture_output=True,+ text=True,+ check=False,+ )+ self.assertEqual(result.returncode, 1)+ self.assertIn("protobuf", result.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ci/standalone/test_semgrep_path_rule.py b/tests/ci/standalone/test_semgrep_path_rule.pynew file mode 100644index 0000000000..d7069da599--- /dev/null+++ b/tests/ci/standalone/test_semgrep_path_rule.py@@ -0,0 +1,409 @@+"""Exercise path-flow findings with the same Semgrep CLI used by CI."""++import json+import shutil+import subprocess+import tempfile+import textwrap+import unittest+from pathlib import Path+++REPO_ROOT = Path(__file__).resolve().parents[3]+RULES = REPO_ROOT / ".semgrep" / "rules" / "ldr-security.yaml"+++class TestPathTraversalRiskRule(unittest.TestCase):+ def test_dynamic_paths_report_file_operations_not_validation(self) -> None:+ semgrep = shutil.which("semgrep")+ if semgrep is None:+ self.skipTest(+ "Semgrep CLI is not installed in this test environment"+ )++ source = textwrap.dedent(+ """\+ import os+ import shutil+ from pathlib import Path++ def unsafe(root, filename):+ candidate = Path(filename)+ candidate.read_text() # expected-finding+ child = os.path.join(root, filename)+ open(child, "rb") # expected-finding+ os.listdir(child) # expected-finding+ os.open(f"{root}/{filename}", os.O_RDONLY) # expected-finding+ FileResponse(candidate) # expected-finding+ shutil.rmtree(candidate) # expected-finding++ def only_validates(filename):+ candidate = Path(filename)+ return candidate.resolve(), candidate.name, candidate.exists()++ def constant_path():+ return Path("/srv/app/static/logo.svg").read_bytes()+ """+ )+ expected_lines = {+ line_number+ for line_number, line in enumerate(source.splitlines(), 1)+ if "# expected-finding" in line+ }++ with tempfile.TemporaryDirectory(prefix="ldr-semgrep-path-") as tmp:+ target = Path(tmp) / "path_rule_case.py"+ target.write_text(source, encoding="utf-8")+ scan = subprocess.run(+ [+ semgrep,+ "scan",+ f"--config={RULES}",+ "--jobs=1",+ "--strict",+ "--metrics=off",+ "--json",+ str(target),+ ],+ capture_output=True,+ text=True,+ timeout=90,+ check=False,+ )++ self.assertEqual(scan.returncode, 0, scan.stderr)+ report = json.loads(scan.stdout)+ self.assertEqual(report["errors"], [])+ self.assertEqual(report["skipped_rules"], [])+ actual_lines = {+ result["start"]["line"]+ for result in report["results"]+ if result["check_id"].endswith(".path-traversal-risk")+ }+ self.assertEqual(actual_lines, expected_lines)++ def test_request_and_stored_paths_keep_distinct_boundaries(self) -> None:+ # This source is scanned only. The annotations identify exact finding+ # locations; absence of extra findings also verifies the safe controls.+ semgrep = shutil.which("semgrep")+ if semgrep is None:+ self.skipTest(+ "Semgrep CLI is not installed in this test environment"+ )++ source = textwrap.dedent(+ """\+ import os+ from pathlib import Path+ from fastapi import APIRouter, Request+ from starlette.responses import FileResponse+ from werkzeug.utils import safe_join, secure_filename+ from local_deep_research.security.path_validator import PathValidator++ router = APIRouter()+ ROOT = "/srv/reports"+++ @router.get("/direct/{name:path}")+ def direct_response(name: str):+ # expect: request-path-traversal-risk+ return FileResponse(name)+++ @router.get("/query")+ def request_alias(req: Request):+ name = req.query_params.get("name")+ # expect: request-path-traversal-risk+ return FileResponse(name)+++ @router.post("/body")+ async def async_body(req: Request):+ payload = await req.json()+ # expect: request-path-traversal-risk+ return FileResponse(payload["name"])+++ def stored_path(session):+ row = session.query(Report).first()+ candidate = Path(row.report_path)+ # expect: path-traversal-risk+ return FileResponse(candidate)+++ @router.get("/stored/{report_id}")+ def stored_path_in_route(report_id: str, session):+ row = session.query(Report).filter_by(id=report_id).first()+ candidate = Path(row.report_path)+ # expect: path-traversal-risk+ return FileResponse(candidate)+++ def direct_stored_path(session):+ row = session.query(Report).first()+ # expect: path-traversal-risk+ return FileResponse(row.report_path)+++ @router.get("/nested/{name:path}")+ def read_before_validation(name: str):+ # expect: request-path-traversal-risk+ return safe_join(ROOT, open(name).read())+++ @router.get("/normalization/{name:path}")+ def normalization_is_not_containment(name: str):+ normalized = PathValidator.sanitize_for_filesystem_ops(name)+ # expect: request-path-traversal-risk+ return FileResponse(normalized)+++ @router.get("/ignored/{name:path}")+ def ignored_validation_result(name: str):+ PathValidator.validate_safe_path(name, ROOT)+ # expect: request-path-traversal-risk+ return FileResponse(name)+++ @router.get("/valid/{name:path}")+ def checked_relative_path(name: str):+ checked = PathValidator.validate_safe_path(name, ROOT)+ return FileResponse(checked)+++ @router.get("/join/{name:path}")+ def safe_join_result(name: str):+ checked = safe_join(ROOT, name)+ return FileResponse(checked)+++ @router.get("/filename/{name:path}")+ def filename_only(name: str):+ checked = secure_filename(name)+ return FileResponse(checked)+++ def only_normalizes(name):+ candidate = Path(name)+ return candidate.resolve(), candidate.name, candidate.exists()+++ def fixed_resource():+ return Path("/srv/reports/logo.svg").read_bytes()+++ @router.get("/ratio")+ def arithmetic(total: int, per_page: int):+ return total / per_page+++ @router.get("/basename/{name:path}")+ def basename_is_not_validation(name: str):+ # expect: request-path-traversal-risk+ return FileResponse(os.path.basename(name))+++ def stored_keyword_path(session):+ row = session.query(Report).first()+ # expect: path-traversal-risk+ return FileResponse(path=row.report_path)+++ @router.get("/keyword/{name:path}")+ def keyword_open(name: str):+ # expect: request-path-traversal-risk+ return open(file=name, mode="rb")+++ @router.get("/download")+ def response_filename_is_only_metadata(name: str):+ return FileResponse("/srv/reports/fixed.txt", filename=name)+++ @router.get("/inline/{name:path}")+ def inline_validation(name: str):+ return FileResponse(PathValidator.validate_safe_path(name, ROOT))+++ @router.get("/typed/{name:path}")+ def typed_validation(name: str):+ checked: Path = PathValidator.validate_safe_path(name, ROOT)+ alias = checked+ return FileResponse(alias)+++ @router.get("/reassigned/{name:path}")+ def reassigned_after_validation(name: str):+ checked = PathValidator.validate_safe_path(name, ROOT)+ checked = name+ # expect: request-path-traversal-risk+ return FileResponse(checked)+++ @router.get("/assigned-nested/{name:path}")+ def assigned_read_before_validation(name: str):+ # expect: request-path-traversal-risk+ checked = safe_join(ROOT, open(name).read())+ return FileResponse(checked)+++ @router.get("/conditional/{name:path}")+ def only_one_branch_validates(name: str, validate: bool):+ checked = PathValidator.validate_safe_path(name, ROOT) if validate else name+ # expect: request-path-traversal-risk+ return FileResponse(checked)+ """+ )+ expected = {+ (line.split("# expect: ")[1], number + 1)+ for number, line in enumerate(source.splitlines(), 1)+ if "# expect: " in line+ }+ with tempfile.TemporaryDirectory(prefix="ldr-semgrep-path-") as tmp:+ target = Path(tmp) / "path_boundaries.py"+ target.write_text(source, encoding="utf-8")+ scan = subprocess.run(+ [+ semgrep,+ "scan",+ f"--config={RULES}",+ "--jobs=1",+ "--strict",+ "--metrics=off",+ "--json",+ str(target),+ ],+ capture_output=True,+ text=True,+ timeout=90,+ check=False,+ )+ self.assertEqual(scan.returncode, 0, scan.stderr)+ report = json.loads(scan.stdout)+ self.assertEqual(report["errors"], [])+ self.assertEqual(report["skipped_rules"], [])+ self.assertEqual(len(report["paths"]["scanned"]), 1)+ actual = {+ (result["check_id"].rsplit(".", 1)[-1], result["start"]["line"])+ for result in report["results"]+ }+ self.assertEqual(actual, expected)++ def test_request_controlled_roots_are_not_sanitized(self) -> None:+ semgrep = shutil.which("semgrep")+ if semgrep is None:+ self.skipTest(+ "Semgrep CLI is not installed in this test environment"+ )++ # These helpers constrain the relative input to their supplied root.+ # They cannot establish that a request-selected root is authorized.+ # Scan the real call forms instead of asserting the YAML spelling.+ unsafe_calls = {+ "join": "safe_join(directory, name)",+ "join_fixed_name": "safe_join(directory, 'report.pdf')",+ "join_keyword_root": "safe_join(directory=directory)",+ "join_filename": "safe_join(directory, secure_filename(name))",+ "safe_path": "PathValidator.validate_safe_path(name, directory)",+ "safe_path_keywords": (+ "PathValidator.validate_safe_path("+ "base_dir=directory, user_input=name)"+ ),+ "data_path": "PathValidator.validate_data_path(name, directory)",+ "data_path_keywords": (+ "PathValidator.validate_data_path("+ "data_root=directory, file_path=name)"+ ),+ "model_path": "PathValidator.validate_model_path(name, directory)",+ "model_path_keywords": (+ "PathValidator.validate_model_path("+ "model_root=directory, model_path=name)"+ ),+ }+ safe_calls = {+ "join": "safe_join(ROOT, name)",+ "join_parts": "safe_join(ROOT, directory, name)",+ "join_keyword_root": "safe_join(directory=ROOT)",+ "safe_path": "PathValidator.validate_safe_path(name, ROOT)",+ "safe_path_keywords": (+ "PathValidator.validate_safe_path("+ "base_dir=ROOT, user_input=name)"+ ),+ "data_path": "PathValidator.validate_data_path(name, ROOT)",+ "data_path_keywords": (+ "PathValidator.validate_data_path("+ "data_root=ROOT, file_path=name)"+ ),+ "model_path": "PathValidator.validate_model_path(name, ROOT)",+ "model_path_keywords": (+ "PathValidator.validate_model_path("+ "model_root=ROOT, model_path=name)"+ ),+ "default_model_root": "PathValidator.validate_model_path(name)",+ }+ source = textwrap.dedent(+ """\+ from fastapi import APIRouter+ from starlette.responses import FileResponse+ from werkzeug.utils import safe_join, secure_filename+ from local_deep_research.security.path_validator import PathValidator++ router = APIRouter()+ ROOT = "/srv/reports"+ """+ )+ for label, calls in (("unsafe", unsafe_calls), ("safe", safe_calls)):+ for name, call in calls.items():+ for style in ("assigned", "inline"):+ expression = call+ case = f"{label}_{name}_{style}"+ source += (+ f'\[email protected]("/{case}")\n'+ f"def {case}(name: str, directory: str):\n"+ )+ if style == "assigned":+ source += f" checked = {call}\n"+ expression = "checked"+ marker = " # expected-finding" if label == "unsafe" else ""+ source += f" return FileResponse({expression}){marker}\n"+ expected_lines = {+ number+ for number, line in enumerate(source.splitlines(), 1)+ if "# expected-finding" in line+ }+ with tempfile.TemporaryDirectory(prefix="ldr-semgrep-root-") as tmp:+ target = Path(tmp) / "root_boundaries.py"+ target.write_text(source, encoding="utf-8")+ scan = subprocess.run(+ [+ semgrep,+ "scan",+ f"--config={RULES}",+ "--jobs=1",+ "--strict",+ "--metrics=off",+ "--json",+ str(target),+ ],+ capture_output=True,+ text=True,+ timeout=90,+ check=False,+ )+ self.assertEqual(scan.returncode, 0, scan.stderr)+ report = json.loads(scan.stdout)+ self.assertEqual(report["errors"], [])+ self.assertEqual(report["skipped_rules"], [])+ self.assertEqual(len(report["paths"]["scanned"]), 1)+ actual = {+ (result["check_id"].rsplit(".", 1)[-1], result["start"]["line"])+ for result in report["results"]+ }+ expected = {+ ("request-path-traversal-risk", line) for line in expected_lines+ }+ self.assertEqual(actual, expected)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/ci/test_dependency_review_workflow.py b/tests/ci/test_dependency_review_workflow.pynew file mode 100644index 0000000000..bb008aea92--- /dev/null+++ b/tests/ci/test_dependency_review_workflow.py@@ -0,0 +1,73 @@+"""Keep reviewed package license exceptions bounded to their intended use."""++from pathlib import Path++import yaml+++ROOT = Path(__file__).resolve().parents[2]+WORKFLOW = ROOT / ".github/workflows/dependency-review.yml"+++def _workflow() -> dict:+ return yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))+++def test_dependency_review_covers_all_manifest_and_include_changes() -> None:+ # Includes can use arbitrary filenames: every PR must run the guard.+ assert _workflow()[True]["pull_request"] == {+ "branches": ["main", "develop"]+ }+++def test_license_scope_guard_is_mandatory_before_dependency_review() -> None:+ job = _workflow()["jobs"]["dependency-review"]+ assert not {"if", "continue-on-error", "defaults"} & job.keys()+ steps = job["steps"]+ commands = [+ "python -m pip install --require-hashes --only-binary=:all: -r requirements/dependency-review.txt",+ "python -m unittest discover -s tests/ci/standalone -p 'test_dependency_licenses.py' -v",+ "python .github/scripts/check_dependency_licenses.py",+ ]+ indexes = []+ for command in commands:+ step = next(step for step in steps if step.get("run") == command)+ assert set(step) == {"name", "run"}+ indexes.append(steps.index(step))+ review = next(+ step+ for step in steps+ if step.get("uses", "").startswith("actions/dependency-review-action@")+ )+ assert indexes[0] < indexes[1] < indexes[2] < steps.index(review)+ assert "if" not in review+ assert "continue-on-error" not in review+++def test_package_exceptions_preserve_general_license_and_vulnerability_policy() -> (+ None+):+ steps = _workflow()["jobs"]["dependency-review"]["steps"]+ review = next(+ step+ for step in steps+ if step.get("uses", "").startswith("actions/dependency-review-action@")+ )+ policy = review["with"]+ allowed = {item.strip() for item in policy["allow-licenses"].split(",")}+ exceptions = {+ item.strip()+ for item in policy["allow-dependencies-licenses"].split(",")+ }+ assert "MIT-0" in allowed+ assert exceptions == {+ "pkg:npm/dompurify",+ "pkg:pypi/docutils",+ "pkg:pypi/semgrep",+ "pkg:pypi/protobuf",+ "pkg:pypi/typing-extensions",+ }+ assert "LGPL-2.1-or-later" not in allowed+ assert "GPL-1.0-or-later" not in allowed+ assert policy["fail-on-severity"] == "high"+ assert policy.get("license-check", True) in (True, "true")diff --git a/tests/ci/test_semgrep_workflow.py b/tests/ci/test_semgrep_workflow.pyindex d0032e9c3e..828c8eee0f 100644--- a/tests/ci/test_semgrep_workflow.py+++ b/tests/ci/test_semgrep_workflow.py@@ -51,17 +51,25 @@ VERIFY_RUN = ("python -m unittest discover -s tests/ci/standalone"" -p 'test_semgrep*.py' -v")-INSTALL_RUN = re.compile(r"python -m pip install semgrep==\d+(\.\d+)+")-# The complete scan argv. Any added option (``--exclude``,-# ``--exclude-rule``, ``--include``, ``--baseline-commit``,-# ``--max-target-bytes``, ...) or dropped ``--config`` narrows the report,-# and the validator cannot tell a narrowed report from a complete one.+SQL_CONTROL_RUN = (+ "semgrep --test --config .semgrep/rules/ldr-security.yaml"+ " .semgrep/tests/ldr-security.py"+)+INSTALL_RUN = (+ "python -m pip install --require-hashes --only-binary=:all:"+ " -r requirements/semgrep.txt"+)+# The complete scan argv. Changing the worker count can destabilize taint+# findings; options such as ``--exclude``, ``--exclude-rule``, ``--include``,+# ``--baseline-commit``, ``--max-target-bytes`` or a dropped ``--config``+# narrow the report, which the validator cannot detect.SCAN_ARGV = ["semgrep","scan","--config=p/security-audit","--config=p/secrets","--config=.semgrep/rules/",+ "--jobs=1","--strict","--metrics=off",f"--json-output={JSON_REPORT}",@@ -91,6 +99,7 @@ STEP_ORDER = ["setup-python","install","verify",+ "test-sql-rules","scan","validate","upload-sarif",@@ -123,7 +132,7 @@ JOB_KEYS = {"runs-on", "timeout-minutes", "permissions", "steps"}# ``defaults``, ``env`` or ``concurrency`` would change how, or whether, the# job runs.WORKFLOW_KEYS = {"name", True, "permissions", "jobs"}-# Semgrep 1.177.0's built-in ignore patterns, which apply when no+# Semgrep 1.179.0's built-in ignore patterns, which apply when no# ``.semgrepignore`` exists (as test_no_semgrepignore_in_the_scanned_tree# requires). Files or directories with these names, at any depth:DEFAULT_IGNORED_NAMES = {".git", ".svn", ".hg", "_darcs", "CVS"}@@ -147,7 +156,7 @@ DEFAULT_IGNORED_DIRS = {}# and files matching these patterns.DEFAULT_IGNORED_FILES = ("*.min.js", "*_test.go")-# Semgrep 1.177.0's default ``--max-target-bytes``: a tracked file above+# Semgrep 1.179.0's default ``--max-target-bytes``: a tracked file above# this size is silently skipped, the same as a default-ignored path.MAX_TARGET_BYTES = 1_000_000# ``run`` steps may carry nothing that changes how their command runs:@@ -199,7 +208,16 @@ def _invokes_semgrep(step: dict) -> bool:def _scan_step(steps: list[dict]) -> dict:- scans = [step for step in steps if _invokes_semgrep(step)]+ invocations = [step for step in steps if _invokes_semgrep(step)]+ # Only this exact rule-test command may accompany the production scan.+ # It has no report output flags; altered or additional invocations fail.+ controls = [+ step+ for step in invocations+ if str(step.get("run", "")).strip() == SQL_CONTROL_RUN+ ]+ assert len(controls) == 1, [step.get("name") for step in controls]+ scans = [step for step in invocations if step not in controls]assert len(scans) == 1, [step.get("name") for step in scans]return scans[0]@@ -217,10 +235,12 @@ def _step_kind(step: dict) -> str:return kindreturn f"unknown action {uses!r}"run = str(step.get("run", "")).strip()- if INSTALL_RUN.fullmatch(run):+ if run == INSTALL_RUN:return "install"if run == VERIFY_RUN:return "verify"+ if run == SQL_CONTROL_RUN:+ return "test-sql-rules"if run == VALIDATOR_RUN:return "validate"if step.get("run") == SCAN_RUN:@@ -481,12 +501,31 @@ UPLOAD_CASES = []+def test_installed_scanner_matches_the_version_whose_ignores_we_model():+ """A tool update needs a review of the scanner's default skip rules."""+ tools = REPO_ROOT / "requirements"+ roots = [+ line.strip()+ for line in (tools / "semgrep.in").read_text().splitlines()+ if line.strip() and not line.lstrip().startswith("#")+ ]+ assert roots == ["semgrep==1.179.0", "pyjwt>=2.15.1"]+ assert re.search(+ r"(?m)^semgrep==1\.179\.0(?:\s|;)",+ (tools / "semgrep.txt").read_text(),+ )+ assert re.search(+ r"(?m)^pyjwt==2\.15\.1(?:\s|;)",+ (tools / "semgrep.txt").read_text(),+ )++def test_scan_has_no_severity_filter():"""``--severity`` selects exact levels; any use drops the other levels."""assert not [t for t in _scan_tokens(_steps()) if "--severity" in t]-def test_exactly_one_step_runs_semgrep():+def test_exactly_one_step_runs_the_production_semgrep_scan():"""A second scan (e.g. INFO-only ``|| true``) could overwrite the reports."""steps = _steps()assert _scan_step(steps) is steps[_index(steps, "scan")]@@ -538,7 +577,7 @@ def _default_ignored(path: str) -> bool:def test_no_default_ignored_paths_under_src():"""No tracked file under ``src/`` matches Semgrep's built-in ignores.- With no ``.semgrepignore``, Semgrep 1.177.0 silently skips e.g. any+ With no ``.semgrepignore``, Semgrep 1.179.0 silently skips e.g. any``tests/``, ``build/``, ``dist/`` or ``vendor/`` directory,``node_modules/`` and ``*.min.js`` files at any depth, and the narrowedreport still validates. None is tracked under ``src/`` today; adding one@@ -562,7 +601,7 @@ def test_no_default_ignored_paths_under_src():def test_no_oversized_or_special_entries_under_src():"""No tracked ``src/`` entry is a symlink, a submodule, or too big.- With no ``--max-target-bytes`` override, Semgrep 1.177.0 silently skips+ With no ``--max-target-bytes`` override, Semgrep 1.179.0 silently skipsany tracked file above its default 1,000,000-byte cap (exit 0, noerror, no skipped-rule entry) the same way it silently skips adefault-ignored path, and the narrowed report still validates. It also@@ -622,7 +661,7 @@ def test_job_has_only_the_pinned_keys():def test_no_semgrepignore_in_the_scanned_tree():"""No ``.semgrepignore`` at the repo root or anywhere under ``src/``.- Semgrep 1.177.0 honours a ``.semgrepignore`` at the root and in any+ Semgrep 1.179.0 honours a ``.semgrepignore`` at the root and in anyscanned subdirectory, and silently drops the matching files, so thenarrowed report still validates. None exists; false positives aresuppressed per line with ``nosemgrep``, which stays next to the code it@@ -678,7 +717,13 @@ def test_no_step_or_default_can_mask_failure():allowed = RUN_STEP_KEYS if "run" in step else ACTION_STEP_KEYSassert set(step) <= allowed, (step.get("name"), set(step) - allowed)assert step.get("continue-on-error") in (None, False)- for kind in ("harden-runner", "checkout", "setup-python", "scan"):+ for kind in (+ "harden-runner",+ "checkout",+ "setup-python",+ "test-sql-rules",+ "scan",+ ):assert "if" not in _steps()[_index(_steps(), kind)]@@ -778,3 +823,33 @@ def test_pull_requests_touching_the_scanned_tree_run_the_scan():triggers = _workflow()[True]assert "src/**" in triggers["pull_request"]["paths"]assert "paths-ignore" not in triggers["pull_request"]+++def test_release_gate_twine_install_is_hash_pinned():+ """The release-gate twine check installs from requirements/twine.txt with+ --require-hashes. Reverting to unpinned ``pip install twine`` must fail+ this test — the twine venv handles PyPI metadata for the release+ pipeline, so it must not accept a silently-substituted distribution."""+ from pathlib import Path+ import yaml++ wf = yaml.safe_load(Path(".github/workflows/release-gate.yml").read_text())+ found = False+ for job in wf.get("jobs", {}).values():+ for step in job.get("steps", []):+ run = step.get("run", "")+ if "twine-verify-env" in run:+ found = True+ assert "--require-hashes" in run, (+ "twine verify-env install lost --require-hashes"+ )+ assert "requirements/twine.txt" in run, (+ "twine verify-env install lost the hash-pinned requirements file"+ )+ assert "pip install twine\n" not in run, (+ "unpinned twine install must not return"+ )+ assert found, (+ "the hash-pinned twine verify-env install step was deleted from "+ "release-gate.yml"+ )diff --git a/tests/deployment/test_deployment_surface_contracts.py b/tests/deployment/test_deployment_surface_contracts.pyindex 0fb4a72e6e..4c7a5e8b86 100644--- a/tests/deployment/test_deployment_surface_contracts.py+++ b/tests/deployment/test_deployment_surface_contracts.py@@ -21,6 +21,7 @@ consequence in its ``reason``.from __future__ import annotations+import astimport jsonimport reimport shutil@@ -677,10 +678,32 @@ class TestProcessAndOwnership:def test_sensitive_files_are_created_owner_only(self):"""The entrypoint fixes directories; the app fixes the files."""+ module = ast.parse(FASTAPI_APP_PY.read_text(encoding="utf-8"))+ loader = next(+ node+ for node in module.body+ if isinstance(node, ast.FunctionDef)+ and node.name == "_load_secret_key"+ )+ calls = [+ node+ for node in ast.walk(loader)+ if isinstance(node, ast.Call)+ and ast.unparse(node.func) == "os.open"+ ]+ assert len(calls) == 1, (+ "secret-key creation must have one audited os.open"+ )+ creation = calls[0]+ assert ast.unparse(creation.args[0]) == "str(secret_key_file)"assert (- "os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600"- in FASTAPI_APP_PY.read_text(encoding="utf-8")- ), ".secret_key must be created 0o600 with O_EXCL"+ ast.unparse(creation.args[1])+ == "os.O_WRONLY | os.O_CREAT | os.O_EXCL"+ )+ assert isinstance(creation.args[2], ast.Constant)+ assert creation.args[2].value == 0o600, (+ ".secret_key must be created owner-only"+ )encrypted_db = (REPO_ROOT/ "src"