Metadata-Version: 2.4
Name: sentinel-remediation
Version: 0.1.0
Summary: Autonomous CVE remediation — patches build files and source code, verifies the build, opens a PR
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source groups, and issue tracking systems that are managed by, or on
              behalf of, the Licensor for the purpose of discussing and improving
              the Work, but excluding communication that is conspicuously marked or
              otherwise designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and included
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent Contributions
              contributed by such Contributor that are necessarily infringed by
              their Contribution(s) alone or by their combination of their
              Contribution(s) with the Work to which such Contribution(s) was
              submitted. If You institute patent litigation against any entity
              (including a cross-claim or counterclaim in a lawsuit) alleging that
              the Work or any Contribution embodied within the Work constitutes
              direct or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate as
              of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file, as part of your
                  distribution, You must include a readable copy of the
                  attribution notices contained within such NOTICE file, in
                  at least one of the following places: within a NOTICE text
                  file distributed as part of the Derivative Works; within
                  the Source form or documentation, if provided along with the
                  Derivative Works; or, within a display generated by the
                  Derivative Works, if and wherever such third-party notices
                  normally appear. The contents of the NOTICE file are for
                  informational purposes only and do not modify the License.
                  You may add Your own attribution notices within Derivative
                  Works that You distribute, alongside or in addition to the
                  NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the
                  License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, copy, modify, merge,
              publish, distribute, sublicense, and/or sell copies of the
              Contribution(s) and such Derivative Works.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (even if such Contributor has been advised of the possibility
              of such damages).
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer, and
              charge a fee for, acceptance of support, warranty, indemnity, or
              other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may offer only
              conditions that are completely consistent with the terms of this
              License and this may induce additional liability for the contributor
              accepting such obligations.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 Anupam Ojha
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/anupamojha-eng/agentic-remediation-factory
Project-URL: Issues, https://github.com/anupamojha-eng/agentic-remediation-factory/issues
Keywords: security,cve,remediation,devops,devsecops,supply-chain
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Build Tools
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: docker>=7.1.0
Requires-Dist: PyGithub>=2.1.1
Requires-Dist: google-genai>=1.0.0
Requires-Dist: fastapi>=0.111.0
Requires-Dist: uvicorn>=0.29.0
Requires-Dist: python-dotenv>=1.0.1
Requires-Dist: requests>=2.31.0
Requires-Dist: click>=8.1.0
Requires-Dist: opentelemetry-api>=1.15.0
Requires-Dist: opentelemetry-sdk>=1.15.0
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.15.0
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc>=1.15.0
Dynamic: license-file

# Sentinel — Autonomous CVE Remediation

[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/)
[![PyPI](https://img.shields.io/pypi/v/sentinel-remediation.svg)](https://pypi.org/project/sentinel-remediation/)
[![Ecosystems](https://img.shields.io/badge/ecosystems-Java%20%7C%20Python-green.svg)](#supported-ecosystems)

**Sentinel closes the "last mile" of CVE remediation.**  
Most tools tell you what's vulnerable. Sentinel fixes it — opening a verified, build-passing pull request with no human in the loop.

```
CVE detected → fork repo → resolve full dep tree → query OSV →
patch build files + source code → verify build in sandbox → open PR
```

**Live demo PRs opened by Sentinel:**
- Java: [monitorjbl/excel-streaming-reader#271](https://github.com/monitorjbl/excel-streaming-reader/pull/271) — Log4Shell + Apache POI CVEs, `pom.xml` + Java source patched
- Python: [vulnerable-data-pipeline#2](https://github.com/anupamojha-eng/vulnerable-data-pipeline/pull/2) — 5 PyPI CVEs, `requirements.txt` + `config.py` + `cache.py` patched

---

## Install

```bash
pip install sentinel-remediation
```

Requires Docker running locally. Set credentials in a `.env` file (see [Quick start](#quick-start)).

---

## Usage

```bash
# Fix CVEs in any public GitHub repo
sentinel fix-cve --repo https://github.com/org/repo

# Target a specific branch
sentinel fix-cve --repo https://github.com/org/repo --branch develop

# Force a specific LLM provider
sentinel fix-cve --repo https://github.com/org/repo --llm gemini

# Override the model
sentinel fix-cve --repo https://github.com/org/repo --llm anthropic --model claude-sonnet-4-6
```

Sentinel forks the repo, opens a sandbox container, scans, patches, verifies, and opens a PR — typically in under 3 minutes.

---

## Why this is different

| Tool | Detects | Patches build file | Patches source code | Verifies build | Opens PR |
|---|---|---|---|---|---|
| Dependabot | ✅ | ✅ | ❌ | ❌ | ✅ |
| Snyk | ✅ | Partial | ❌ | ❌ | ✅ |
| Renovate | ✅ | ✅ | ❌ | ❌ | ✅ |
| **Sentinel** | ✅ | ✅ | ✅ | ✅ | ✅ |

Dependabot bumps versions. Sentinel bumps versions *and* fixes the dangerous call sites in your code — then proves the build still passes before touching your repo.

---

## What Sentinel does

### Three-layer remediation

**Layer 1 — Transitive CVE detection**  
Resolves the *complete* dependency tree (not just declared deps) using the native build tool, then queries the OSV REST API for every package including transitively pulled dependencies. Catches CVEs that arrive silently through frameworks.

**Layer 2 — Build file patching**  
LLM upgrades `pom.xml`, `build.gradle`, `build.gradle.kts`, `gradle/libs.versions.toml`, `requirements.txt`, and `pyproject.toml` to the minimum safe version. Handles version variables, BOM imports, Kotlin DSL, and Gradle version catalogs.

**Layer 3 — Source code patching**  
Greps source files for dangerous call-site patterns — both CVE-specific and a built-in set of always-checked anti-patterns:

**Python anti-patterns (always checked):**
| Pattern | Risk |
|---------|------|
| `yaml.load(` | RCE via unsafe deserialization |
| `pickle.loads(` / `pickle.load(` | RCE via deserialization |

**Java anti-patterns (always checked):**
| Pattern | Risk |
|---------|------|
| `new ObjectInputStream(` | Java deserialization RCE |
| `Runtime.getRuntime().exec(` | OS command injection |
| `new ProcessBuilder(` | OS command injection |
| `MessageDigest.getInstance("MD5"` | Weak hashing |
| `MessageDigest.getInstance("SHA-1"` | Weak hashing |
| `new Random(` | Insecure randomness |
| `DocumentBuilderFactory.newInstance(` | XML External Entity (XXE) |
| `XMLInputFactory.newInstance(` | XML External Entity (XXE) |

### PR audit trail

Every PR opened by Sentinel includes a structured evidence trail:
- CVEs addressed
- Files changed with patterns found
- Build verification status and attempt count
- Truncated build output (collapsible)
- Timestamp

### Verify before merge

Every patch is tested in an isolated Docker sandbox (JDK 17 + Maven/Gradle, Python 3 + pip) before the PR is opened. If the build fails, Sentinel extracts the error, feeds it back to the LLM, and retries up to 3 times.

### Fallback when PR can't be opened

If the GitHub API is unavailable or rate-limited, Sentinel extracts the diff from the container and saves it as `sentinel-patch-<timestamp>.diff` locally with apply instructions. The fix is never lost.

---

## Supported ecosystems

| Build system | Detection | Transitive scan | Source patching | Verify command |
|---|---|---|---|---|
| Maven (`pom.xml`) | ✅ | `mvn dependency:list` | ✅ `.java` | `mvn clean compile` |
| Gradle Groovy | ✅ | `gradle dependencies` | ✅ `.java` | `gradle compileJava` |
| Gradle KTS | ✅ | `gradle dependencies` | ✅ `.java` | `gradle compileJava` |
| Gradle version catalog | ✅ | `gradle dependencies` | ✅ `.java` | `gradle compileJava` |
| `requirements.txt` | ✅ | `pip install` + `pip list` | ✅ `.py` | `pip install && pytest` |
| `pyproject.toml` | ✅ | `pip install` + `pip list` | ✅ `.py` | `pip install && pytest` |

---

## Quick start

```bash
# 1. Install
pip install sentinel-remediation

# 2. Set credentials
cp .env.example .env
# Edit .env — add GITHUB_TOKEN and at least one LLM key:
#   ANTHROPIC_API_KEY  (Claude — recommended, best accuracy)
#   GEMINI_API_KEY     (Gemini Flash — cost-effective alternative)

# 3. Build the sandbox image (one-time, ~5 min)
docker build -t cve-fixer-sandbox:latest sandbox/

# 4. Run
sentinel fix-cve --repo https://github.com/anupamojha-eng/vulnerable-data-pipeline
```

### Running via API (FastAPI server)

```bash
python3 orchestrator/driver.py  # starts on :8080

curl -X POST http://localhost:8080/remediate \
  -H "Content-Type: application/json" \
  -d '{"repo_url": "https://github.com/org/repo", "target_tag": "main"}'
```

---

## Architecture

```
┌─────────────────────────────────────────────────────────┐
│                    orchestrator/                         │
│                                                         │
│  cli.py           `sentinel` CLI entry point            │
│  driver.py        FastAPI service — HTTP entry point    │
│  factory.py       RemediationFactory                    │
│    ├─ _detect_build_system()   Maven/Gradle/Python      │
│    ├─ _scan_internal()         resolve deps → OSV API   │
│    │    └─ _scan_with_osv_scanner()  fallback           │
│    ├─ _get_verify_command()    build tool selector      │
│    └─ retry loop (MAX=3)       smart error routing      │
│                                                         │
│  remediator.py    RemediationActor                      │
│    ├─ get_vulnerable_code_files()  grep → source files  │
│    ├─ get_affected_java_files()    parse compile errors  │
│    ├─ autonomous_patch()           LLM → write → verify │
│    ├─ create_pull_request()        branch → push → PR   │
│    ├─ _build_pr_body()             audit trail          │
│    └─ _patch_fallback()            save diff locally    │
│                                                         │
│  llm_client.py    SecurityAgentClient                   │
│    ├─ _AnthropicProvider  Claude Opus 4.8 (default)     │
│    ├─ _GeminiProvider     Gemini 2.5 Flash (alt)        │
│    ├─ get_vulnerable_patterns()    CVE → grep strings   │
│    └─ get_remediation_plan()       full patch plan      │
└─────────────────────────────────────────────────────────┘
                           │
                           │ Docker SDK
                           ▼
┌─────────────────────────────────────────────────────────┐
│               sandbox/  (Docker image)                   │
│                                                         │
│  JDK 17 · Maven 3.9 · Gradle 9.4 · OSV-Scanner         │
│  Python 3 · pip3 · git                                  │
│                                                         │
│  Isolated per-run: no shared state between remediations │
└─────────────────────────────────────────────────────────┘
```

---

## Running tests

```bash
# Fast unit tests (no Docker, no API keys)
pytest tests/test_python_support.py tests/test_patching.py \
       tests/test_build_detection.py tests/test_scanner.py -v

# Docker e2e — needs Docker + LLM key
pytest tests/test_e2e_docker.py -v -s              # Java
pytest tests/test_e2e_python_docker.py -v -s       # Python

# Source patching e2e
pytest tests/test_java_source_patching_e2e.py -v -s
pytest tests/test_python_source_patching_e2e.py -v -s

# Full pipeline — needs Docker + LLM key + GITHUB_TOKEN
pytest tests/test_real_repo_e2e.py -v -s           # Java
pytest tests/test_real_python_repo_e2e.py -v -s    # Python
```

---

## Technical stack

- **CLI**: Click — `sentinel fix-cve --repo <url>`
- **Orchestrator**: Python / FastAPI — container lifecycle, retry loop, GitHub API
- **Sandbox**: Docker (JDK 17, Maven 3.9.15, Gradle 9.4.1, OSV-Scanner, Python 3 + pip)
- **Scanning**: `mvn dependency:list` / `gradle dependencies` / `pip list` + OSV REST API; OSV-Scanner (fallback)
- **Reasoning**: Multi-provider — Anthropic Claude (default) or Google Gemini
- **Version control**: PyGithub — fork, branch, commit, PR

### LLM provider comparison

| | Claude Opus 4.8 (default) | Gemini 2.5 Flash |
|---|---|---|
| Complex multi-file patches | Excellent | Good |
| JSON output reliability | Excellent | Good |
| Prompt caching on retries | Yes (~80% savings) | No |
| Speed | Moderate | Fast |
| Cost per run | Higher | Lower |

Set `ANTHROPIC_API_KEY` for Claude, `GEMINI_API_KEY` for Gemini, or both (Claude wins when both set).  
Override with `ANTHROPIC_MODEL=claude-sonnet-4-6` or `GEMINI_MODEL=gemini-2.5-pro`.

---

## Roadmap

- [ ] `sentinel fix-antipatterns` — standalone anti-pattern fixing without a CVE trigger
- [ ] Local LLM mode — Ollama + quantized model for air-gapped / zero-cost runs
- [ ] OSV offline cache — local SQLite built from OSV data dumps, no API calls
- [ ] Go (`go.mod`) and Rust (`Cargo.toml`) ecosystem support
- [ ] GitHub Actions integration — trigger on Dependabot alert webhook
- [ ] Container image scanning — pair with Chainguard Wolfi or distroless base images

---

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md).

## Security

See [SECURITY.md](SECURITY.md) for vulnerability disclosure policy.

## License

Apache License 2.0 — see [LICENSE](LICENSE).  
Copyright 2026 Anupam Ojha
