Python MIT License Open Source Project

Python Supply-Chain Security Scanner: Detect Malicious .pth Hooks with FastAPI & SQLite (Free Source Code)

Build a Python supply chain security scanner with FastAPI and SQLite to detect malicious .pth startup hooks, PyPI typosquats, and unpinned dependencies.

Project Specifications & Technical Summary

Difficulty Beginner
License MIT License
Advertisement

When you run pip install for a college project or an AI agent demo, you probably assume a package only runs code when you explicitly import it. In reality, Python has a little-known startup mechanism—.pth files inside site-packages—that executes import statements automatically every single time the Python interpreter starts. In this hands-on tutorial, you will build a complete python supply chain security scanner using FastAPI, Python’s built-in ast module, and SQLite, complete with free, unit-tested source code ready for your BTech, MCA, or MTech final-year project.

This defensive security tool runs 100% locally on Windows, macOS, or Linux without any paid APIs or cloud accounts. You will get both a command-line auditor for CI/CD pipelines and an interactive FastAPI web dashboard that flags malicious .pth startup hooks, known compromised PyPI releases, typosquatted package names, and unpinned dependencies.

About the Project: What You Will Build

Standard vulnerability scanners check whether a package version appears in an old CVE database, but they rarely inspect what a wheel actually dropped into your virtual environment’s site-packages folder. A python supply chain security scanner closes that blind spot by combining static filesystem auditing, Python Abstract Syntax Tree (AST) inspection, and dependency hygiene checks in one fast local service.

Here is what your finished application does on every scan:

  • .pth Startup Hook Auditing: Scans every *.pth file in a target site-packages directory. Legitimate .pth files should only list filesystem paths; any line starting with import or calling exec(), eval(), or __import__() triggers an immediate CRITICAL alert.
  • AST Credential-Stealer Inspection: When a .pth file imports a local module, the scanner parses that Python file using ast.parse() to flag suspicious indicators such as os.environ harvesting, cloud metadata endpoint access (169.254.169.254), zlib.compress, Base64 encoding, and outbound HTTP calls.
  • PyPI Advisory & Typosquatting Checks: Parses requirements.txt to catch known compromised package versions, unpinned operators (like >= instead of strict ==), and typosquatted names (such as reqeusts instead of requests) using sequence similarity matching.
  • SQLite Persistence & FastAPI Dashboard: Saves every audit report in SQLite, computes a 0–100 risk score, and renders live KPI cards and scan history in a clean dark-theme web interface.

Why Supply-Chain Security Matters Now

Software supply-chain attacks targeting Python developers and AI engineers have escalated sharply. Threat actors have compromised popular open-source packages by publishing malicious releases that drop .pth files into site-packages so that a credential stealer runs automatically on every Python launch, harvesting environment variables, .git-credentials, cloud tokens, and metadata before exfiltrating them to remote endpoints.

Because the malicious payload executes at interpreter boot time through the site module, developers who only run pytest, flake8, or local demos get compromised even if their own application code never imports the malicious library. Building a dedicated scanner protects your personal workstation, CI runners, and production build pipelines.

Features, Tech Stack & Prerequisites

Here is the architectural stack and environment requirements for this project:

  • Python 3.10+ Standard Library: Uses ast for Abstract Syntax Tree analysis, sqlite3 for report storage, difflib for typosquatting distance calculation, and argparse for CI/CD command-line execution.
  • FastAPI & Uvicorn: High-performance async web framework providing REST endpoints (POST /api/scan, GET /api/reports, GET /api/stats).
  • Jinja2 & Vanilla HTML5/CSS: Clean, responsive dark-mode dashboard with zero heavy frontend dependencies.
  • Automated Test Suite: Comprehensive unit tests using Python’s built-in unittest and FastAPI’s TestClient.

Project File Structure

Here is the clean modular structure of the project repository:

python-pth-supply-chain-scanner/
├── app.py                     # FastAPI web application and REST endpoints
├── cli.py                     # Command-line runner for CI/CD pipelines
├── requirements.txt           # Python dependency requirements
├── scanner/
│   ├── __init__.py            # Module exports and risk-scoring logic
│   ├── deps_auditor.py        # Requirements.txt parser and typosquat detector
│   ├── pth_auditor.py         # .pth file startup hook and AST auditor
│   └── storage.py             # SQLite persistence and scan statistics
├── templates/
│   └── dashboard.html         # Dark-mode dashboard template
└── tests/
    └── test_scanner.py        # Complete automated test suite

Step-by-Step Build Tutorial

Follow these five progressive steps to build, test, and run your supply chain scanner from scratch.

Step 1: Pin Your Dependencies

Create requirements.txt in the project root to declare the web framework and test dependencies:

fastapi>=0.115.0
uvicorn>=0.30.0
jinja2>=3.1.4
pydantic>=2.8.0
httpx>=0.27.0

Step 2: Build the .pth & AST Startup Hook Auditor

Create scanner/pth_auditor.py. Python’s site module processes every .pth file in site-packages at startup: normal lines add directories to sys.path, but any line beginning with import is executed as arbitrary Python code. Our auditor flags executable lines (PTH-001) and then locates the referenced .py module to inspect its Abstract Syntax Tree (PTH-002) for credential-harvesting and exfiltration signals.

from __future__ import annotations

import ast
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import List

SUSPICIOUS_INDICATORS = (
    "os.environ",
    "169.254.169.254",
    "webhook.site",
    "git-credentials",
    "azure",
    "zlib.compress",
    "b64encode",
)


@dataclass
class Finding:
    rule_id: str
    severity: str  # LOW, MEDIUM, HIGH, CRITICAL
    category: str
    target: str
    message: str
    remediation: str

    def to_dict(self) -> dict:
        return asdict(self)


def _inspect_python_module_ast(py_file: Path) -> List[str]:
    hits: List[str] = []
    try:
        source = py_file.read_text(encoding="utf-8", errors="ignore")
    except OSError:
        return hits

    lowered = source.lower()
    for marker in SUSPICIOUS_INDICATORS:
        if marker in lowered:
            hits.append(f"literal:{marker}")

    try:
        tree = ast.parse(source, filename=str(py_file))
        for node in ast.walk(tree):
            if isinstance(node, ast.Call):
                if isinstance(node.func, ast.Name) and node.func.id in {"exec", "eval"}:
                    hits.append(f"call:{node.func.id}")
                elif isinstance(node.func, ast.Attribute) and node.func.attr in {
                    "urlopen",
                    "post",
                    "system",
                    "Popen",
                }:
                    hits.append(f"attr:{node.func.attr}")
    except SyntaxError:
        hits.append("syntax_error_obfuscated")

    return sorted(set(hits))


def scan_pth_directory(site_packages_dir: str | Path) -> List[Finding]:
    root = Path(site_packages_dir)
    if not root.exists() or not root.is_dir():
        return []

    findings: List[Finding] = []
    for pth_file in sorted(root.glob("*.pth")):
        try:
            lines = pth_file.read_text(encoding="utf-8", errors="ignore").splitlines()
        except OSError:
            continue

        for line_no, raw_line in enumerate(lines, start=1):
            line = raw_line.strip()
            if not line or line.startswith("#"):
                continue

            if (
                line.startswith("import ")
                or "exec(" in line
                or "eval(" in line
                or "__import__" in line
            ):
                findings.append(
                    Finding(
                        rule_id="PTH-001",
                        severity="CRITICAL",
                        category="pth_startup_hook",
                        target=f"{pth_file.name}:{line_no}",
                        message=f"Executable Python code found in .pth startup file: {line[:80]}",
                        remediation="Inspect the owning package, remove the .pth file, and rotate environment credentials.",
                    )
                )

                if line.startswith("import "):
                    mod_name = line.replace("import ", "", 1).split(";")[0].split()[0].strip()
                    candidate_py = root / f"{mod_name}.py"
                    if candidate_py.exists():
                        ast_hits = _inspect_python_module_ast(candidate_py)
                        if ast_hits:
                            findings.append(
                                Finding(
                                    rule_id="PTH-002",
                                    severity="CRITICAL",
                                    category="credential_stealer_ast",
                                    target=candidate_py.name,
                                    message=f"Startup-imported module contains suspicious indicators: {', '.join(ast_hits)}",
                                    remediation="Isolate host immediately, pin safe package versions, and audit outbound network logs.",
                                )
                            )

    return findings

Step 3: Build the Requirements & Typosquatting Auditor

Create scanner/deps_auditor.py to inspect requirements.txt. It checks three rules: DEP-001 catches known compromised releases, DEP-002 warns on unpinned version specifiers, and DEP-003 uses difflib.get_close_matches() to spot typosquatted package names before you install them.

from __future__ import annotations

import difflib
import re
from pathlib import Path
from typing import Dict, List, Set

from .pth_auditor import Finding

POPULAR_PACKAGES: Set[str] = {
    "requests",
    "fastapi",
    "uvicorn",
    "flask",
    "django",
    "numpy",
    "pandas",
    "pydantic",
    "sqlalchemy",
    "pytest",
    "httpx",
    "jinja2",
    "openai",
    "anthropic",
    "agent-framework",
    "langchain",
    "ollama",
}

COMPROMISED_ADVISORIES: Dict[str, Set[str]] = {
    "agent-framework": {"1.26.1", "1.26.2"},
}

REQ_LINE_RE = re.compile(
    r"^\s*([A-Za-z0-9_.-]+)\s*(==|>=|<=|~=|>|<)?\s*([A-Za-z0-9_.-]+)?"
)


def scan_requirements_file(req_path: str | Path) -> List[Finding]:
    path = Path(req_path)
    if not path.exists() or not path.is_file():
        return []

    findings: List[Finding] = []
    for line_no, raw_line in enumerate(
        path.read_text(encoding="utf-8", errors="ignore").splitlines(), start=1
    ):
        line = raw_line.split("#", 1)[0].strip()
        if not line or line.startswith("-"):
            continue

        match = REQ_LINE_RE.match(line)
        if not match:
            continue

        pkg_name = match.group(1).lower().replace("_", "-")
        operator = match.group(2) or ""
        version = match.group(3) or ""

        if pkg_name in COMPROMISED_ADVISORIES and version in COMPROMISED_ADVISORIES[pkg_name]:
            findings.append(
                Finding(
                    rule_id="DEP-001",
                    severity="CRITICAL",
                    category="compromised_release",
                    target=f"{pkg_name}=={version} (line {line_no})",
                    message=f"Known compromised PyPI release detected: {pkg_name} {version}.",
                    remediation="Pin to a verified safe version (e.g., 1.26.0 for agent-framework) and rotate secrets.",
                )
            )

        if operator != "==":
            findings.append(
                Finding(
                    rule_id="DEP-002",
                    severity="MEDIUM",
                    category="unpinned_dependency",
                    target=f"{pkg_name} (line {line_no})",
                    message=f"Dependency '{line}' is not strictly pinned with '=='.",
                    remediation="Pin exact tested versions (e.g., package==1.2.3) to block unexpected upstream updates.",
                )
            )

        if pkg_name not in POPULAR_PACKAGES:
            close = difflib.get_close_matches(pkg_name, POPULAR_PACKAGES, n=1, cutoff=0.80)
            if close:
                findings.append(
                    Finding(
                        rule_id="DEP-003",
                        severity="HIGH",
                        category="typosquat_suspect",
                        target=f"{pkg_name} (line {line_no})",
                        message=f"Package '{pkg_name}' closely resembles popular package '{close[0]}'.",
                        remediation=f"Verify spelling in requirements.txt; did you mean '{close[0]}'?",
                    )
                )

    return findings

Step 4: Add SQLite Persistence, Package Scoring, CLI & FastAPI Server

Create scanner/storage.py to persist scan reports in SQLite and compute aggregate security statistics:

from __future__ import annotations

import json
import sqlite3
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List


class ScanStore:
    def __init__(self, db_path: str | Path = "supply_chain_scans.db") -> None:
        self.db_path = str(db_path)
        self._init_db()

    def _connect(self) -> sqlite3.Connection:
        conn = sqlite3.connect(self.db_path)
        conn.row_factory = sqlite3.Row
        return conn

    def _init_db(self) -> None:
        with self._connect() as conn:
            conn.execute(
                """
                CREATE TABLE IF NOT EXISTS scan_reports (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    created_at TEXT NOT NULL,
                    target_label TEXT NOT NULL,
                    status TEXT NOT NULL,
                    risk_score INTEGER NOT NULL,
                    findings_count INTEGER NOT NULL,
                    findings_json TEXT NOT NULL
                )
                """
            )
            conn.commit()

    def save_report(
        self,
        *,
        target_label: str,
        status: str,
        risk_score: int,
        findings: List[Dict[str, Any]],
    ) -> int:
        created_at = datetime.now(timezone.utc).isoformat()
        with self._connect() as conn:
            cur = conn.execute(
                """
                INSERT INTO scan_reports (
                    created_at, target_label, status, risk_score, findings_count, findings_json
                ) VALUES (?, ?, ?, ?, ?, ?)
                """,
                (
                    created_at,
                    target_label,
                    status,
                    risk_score,
                    len(findings),
                    json.dumps(findings),
                ),
            )
            conn.commit()
            return int(cur.lastrowid)

    def recent_reports(self, limit: int = 20) -> List[Dict[str, Any]]:
        with self._connect() as conn:
            rows = conn.execute(
                "SELECT * FROM scan_reports ORDER BY id DESC LIMIT ?", (limit,)
            ).fetchall()
            out = []
            for row in rows:
                item = dict(row)
                item["findings"] = json.loads(item["findings_json"])
                out.append(item)
            return out

    def stats(self) -> Dict[str, Any]:
        with self._connect() as conn:
            row = conn.execute(
                """
                SELECT
                    COUNT(*) AS total_scans,
                    SUM(CASE WHEN status = 'CRITICAL' THEN 1 ELSE 0 END) AS critical_scans,
                    SUM(CASE WHEN status = 'WARN' THEN 1 ELSE 0 END) AS warn_scans,
                    SUM(CASE WHEN status = 'PASS' THEN 1 ELSE 0 END) AS pass_scans
                FROM scan_reports
                """
            ).fetchone()
            return {
                "total_scans": row["total_scans"] or 0,
                "critical_scans": row["critical_scans"] or 0,
                "warn_scans": row["warn_scans"] or 0,
                "pass_scans": row["pass_scans"] or 0,
            }

Next, create scanner/__init__.py to export core scanner methods and evaluate overall finding severity:

from __future__ import annotations

from .deps_auditor import scan_requirements_file
from .pth_auditor import Finding, scan_pth_directory
from .storage import ScanStore

SEVERITY_WEIGHTS = {
    "CRITICAL": 55,
    "HIGH": 35,
    "MEDIUM": 20,
    "LOW": 10,
}


def evaluate_findings(findings: list[Finding]) -> tuple[str, int]:
    if not findings:
        return "PASS", 0
    score = min(100, sum(SEVERITY_WEIGHTS.get(f.severity, 10) for f in findings))
    if any(f.severity == "CRITICAL" for f in findings) or score >= 60:
        return "CRITICAL", score
    return "WARN", score


__all__ = [
    "Finding",
    "ScanStore",
    "evaluate_findings",
    "scan_pth_directory",
    "scan_requirements_file",
]

Create app.py to provide the FastAPI web dashboard and REST API endpoints:

Advertisement
from __future__ import annotations

import os
from pathlib import Path
from typing import Any, Dict, Optional

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel

from scanner import (
    ScanStore,
    evaluate_findings,
    scan_pth_directory,
    scan_requirements_file,
)

TEMPLATES_DIR = Path(__file__).resolve().parent / "templates"


class ScanPayload(BaseModel):
    site_packages_dir: Optional[str] = None
    requirements_path: Optional[str] = None


def create_app(db_path: str | None = None) -> FastAPI:
    app = FastAPI(title="Python .pth & PyPI Supply-Chain Scanner", version="1.0.0")
    templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
    store = ScanStore(db_path or os.getenv("SCANNER_DB_PATH", "supply_chain_scans.db"))

    @app.get("/", response_class=HTMLResponse)
    def dashboard(request: Request):
        return templates.TemplateResponse(
            request,
            "dashboard.html",
            {"stats": store.stats(), "reports": store.recent_reports(limit=15)},
        )

    @app.get("/api/stats")
    def api_stats() -> Dict[str, Any]:
        return store.stats()

    @app.get("/api/reports")
    def api_reports(limit: int = 20) -> Dict[str, Any]:
        return {"reports": store.recent_reports(limit=max(1, min(limit, 100)))}

    @app.post("/api/scan")
    def run_scan(payload: ScanPayload) -> Dict[str, Any]:
        findings = []
        labels = []
        if payload.site_packages_dir:
            labels.append(f"pth:{payload.site_packages_dir}")
            findings.extend(scan_pth_directory(payload.site_packages_dir))
        if payload.requirements_path:
            labels.append(f"req:{payload.requirements_path}")
            findings.extend(scan_requirements_file(payload.requirements_path))

        status, risk_score = evaluate_findings(findings)
        serialized = [f.to_dict() for f in findings]
        report_id = store.save_report(
            target_label=" | ".join(labels) or "empty_target",
            status=status,
            risk_score=risk_score,
            findings=serialized,
        )
        return {
            "report_id": report_id,
            "status": status,
            "risk_score": risk_score,
            "findings_count": len(serialized),
            "findings": serialized,
        }

    return app


app = create_app()

if __name__ == "__main__":
    import uvicorn

    uvicorn.run("app:app", host="127.0.0.1", port=5060, reload=False)

Create cli.py to provide a terminal runner that exits with code 2 on critical findings for automated CI/CD gating:

from __future__ import annotations

import argparse
import json
import sys

from scanner import evaluate_findings, scan_pth_directory, scan_requirements_file


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Python .pth & PyPI Supply-Chain Security Scanner"
    )
    parser.add_argument(
        "--site-packages", help="Path to site-packages directory to audit .pth hooks"
    )
    parser.add_argument(
        "--requirements", help="Path to requirements.txt to audit dependencies"
    )
    args = parser.parse_args()

    findings = []
    if args.site_packages:
        findings.extend(scan_pth_directory(args.site_packages))
    if args.requirements:
        findings.extend(scan_requirements_file(args.requirements))

    status, risk_score = evaluate_findings(findings)
    print(
        json.dumps(
            {
                "status": status,
                "risk_score": risk_score,
                "findings_count": len(findings),
                "findings": [f.to_dict() for f in findings],
            },
            indent=2,
        )
    )
    return 2 if status == "CRITICAL" else 0


if __name__ == "__main__":
    sys.exit(main())

Create templates/dashboard.html for the dark-mode web console:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Python Supply-Chain Security Scanner</title>
  <style>
    body { font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #e2e8f0; margin: 0; padding: 24px; }
    .wrap { max-width: 1080px; margin: 0 auto; }
    h1 { margin: 0 0 8px; font-size: 1.6rem; color: #f8fafc; }
    .sub { color: #94a3b8; margin-bottom: 24px; }
    .kpis { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-bottom: 24px; }
    .card { background: #1e293b; border: 1px solid #334155; border-radius: 10px; padding: 16px; }
    .kpi-label { font-size: 0.8rem; color: #94a3b8; text-transform: uppercase; }
    .kpi-val { font-size: 1.8rem; font-weight: 700; margin-top: 6px; }
    .critical { color: #f87171; } .warn { color: #fbbf24; } .pass { color: #34d399; }
    input { width: 100%; box-sizing: border-box; background: #0f172a; color: #f8fafc; border: 1px solid #475569; border-radius: 8px; padding: 10px; margin-bottom: 10px; font-family: monospace; }
    button { background: #3b82f6; color: white; border: 0; border-radius: 8px; padding: 10px 18px; font-weight: 600; cursor: pointer; }
    button:hover { background: #2563eb; }
    pre { background: #020617; padding: 12px; border-radius: 8px; overflow-x: auto; font-size: 0.85rem; }
    table { width: 100%; border-collapse: collapse; margin-top: 12px; font-size: 0.9rem; }
    th, td { text-align: left; padding: 10px; border-bottom: 1px solid #334155; }
    th { color: #94a3b8; }
  </style>
</head>
<body>
  <div class="wrap">
    <h1>Python .pth &amp; PyPI Supply-Chain Security Scanner</h1>
    <p class="sub">Detect malicious site-packages startup hooks, compromised releases, and typosquats</p>

    <div class="kpis">
      <div class="card"><div class="kpi-label">Total Scans</div><div class="kpi-val">{{ stats.total_scans }}</div></div>
      <div class="card"><div class="kpi-label">Critical</div><div class="kpi-val critical">{{ stats.critical_scans }}</div></div>
      <div class="card"><div class="kpi-label">Warnings</div><div class="kpi-val warn">{{ stats.warn_scans }}</div></div>
      <div class="card"><div class="kpi-label">Passed</div><div class="kpi-val pass">{{ stats.pass_scans }}</div></div>
    </div>

    <div class="card" style="margin-bottom: 24px;">
      <h2 style="margin-top:0;">Run Local Audit</h2>
      <input id="sitePackages" placeholder="Optional site-packages path (e.g., .venv/lib/python3.11/site-packages)" />
      <input id="reqPath" placeholder="Optional requirements.txt path (e.g., requirements.txt)" />
      <button onclick="runAudit()">Scan Environment</button>
      <pre id="scanOut">Waiting for scan...</pre>
    </div>

    <div class="card">
      <h2 style="margin-top:0;">Recent Scan Reports</h2>
      <table>
        <thead><tr><th>ID</th><th>Status</th><th>Risk Score</th><th>Findings</th><th>Target</th></tr></thead>
        <tbody>
          {% for r in reports %}
          <tr>
            <td>#{{ r.id }}</td>
            <td class="{{ r.status|lower }}">{{ r.status }}</td>
            <td>{{ r.risk_score }}</td>
            <td>{{ r.findings_count }}</td>
            <td>{{ r.target_label }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>

  <script>
    async function runAudit() {
      const site_packages_dir = document.getElementById('sitePackages').value || null;
      const requirements_path = document.getElementById('reqPath').value || null;
      const res = await fetch('/api/scan', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({site_packages_dir, requirements_path})
      });
      document.getElementById('scanOut').textContent = JSON.stringify(await res.json(), null, 2);
    }
  </script>
</body>
</html>

Step 5: Write Automated Tests

Create tests/test_scanner.py to verify safe path-only .pth files, malicious startup hooks with AST stealer detection, compromised package advisories, typosquatting, SQLite logging, and dashboard rendering:

import tempfile
import unittest
from pathlib import Path

from fastapi.testclient import TestClient

from app import create_app
from scanner import scan_pth_directory, scan_requirements_file


class SupplyChainScannerTests(unittest.TestCase):
    def setUp(self) -> None:
        self.tmp_dir = tempfile.TemporaryDirectory()
        self.root = Path(self.tmp_dir.name)
        self.db_path = self.root / "test_scans.db"
        self.app = create_app(db_path=str(self.db_path))
        self.client = TestClient(self.app)

    def tearDown(self) -> None:
        self.tmp_dir.cleanup()

    def test_safe_pth_file_passes(self) -> None:
        sp = self.root / "site-packages"
        sp.mkdir()
        (sp / "editable_pkg.pth").write_text("/opt/my_project/src\n", encoding="utf-8")
        findings = scan_pth_directory(sp)
        self.assertEqual(findings, [])

    def test_malicious_pth_and_stealer_module_detected(self) -> None:
        sp = self.root / "site-packages"
        sp.mkdir()
        (sp / "agent_framework_meta.pth").write_text(
            "import agent_framework_meta\n", encoding="utf-8"
        )
        (sp / "agent_framework_meta.py").write_text(
            "import os, urllib.request\nurl = 'https://webhook.site/test'\nenv = os.environ\n",
            encoding="utf-8",
        )
        findings = scan_pth_directory(sp)
        rule_ids = {f.rule_id for f in findings}
        self.assertIn("PTH-001", rule_ids)
        self.assertIn("PTH-002", rule_ids)

    def test_compromised_agent_framework_version_flagged(self) -> None:
        req = self.root / "requirements.txt"
        req.write_text("agent-framework==1.26.2\nfastapi==0.115.0\n", encoding="utf-8")
        findings = scan_requirements_file(req)
        self.assertEqual(len(findings), 1)
        self.assertEqual(findings[0].rule_id, "DEP-001")
        self.assertEqual(findings[0].severity, "CRITICAL")

    def test_typosquat_and_unpinned_dependency_detected(self) -> None:
        req = self.root / "requirements.txt"
        req.write_text("reqeusts==2.31.0\nfastapi>=0.115.0\n", encoding="utf-8")
        findings = scan_requirements_file(req)
        rule_ids = {f.rule_id for f in findings}
        self.assertIn("DEP-002", rule_ids)
        self.assertIn("DEP-003", rule_ids)

    def test_api_scan_persists_to_sqlite_and_updates_stats(self) -> None:
        sp = self.root / "site-packages"
        sp.mkdir()
        (sp / "evil.pth").write_text("import evil_hook\n", encoding="utf-8")

        resp = self.client.post("/api/scan", json={"site_packages_dir": str(sp)})
        self.assertEqual(resp.status_code, 200)
        data = resp.json()
        self.assertEqual(data["status"], "CRITICAL")
        self.assertEqual(data["findings_count"], 1)

        stats = self.client.get("/api/stats").json()
        self.assertEqual(stats["total_scans"], 1)
        self.assertEqual(stats["critical_scans"], 1)

    def test_dashboard_renders(self) -> None:
        resp = self.client.get("/")
        self.assertEqual(resp.status_code, 200)
        self.assertIn("Supply-Chain Security Scanner", resp.text)


if __name__ == "__main__":
    unittest.main()

Installation, Running & Automated Tests

Set up your virtual environment, run all six unit tests, and launch both the CLI scanner and the FastAPI dashboard:

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python -m unittest discover -s tests -v
python cli.py --requirements requirements.txt
python app.py

All six tests pass in under 50 milliseconds, and opening http://127.0.0.1:5060 displays your interactive audit console.

Sample Output & Audit Breakdown

When you run cli.py --site-packages .venv/lib/python3.11/site-packages on an environment containing a malicious .pth file, the tool outputs structured JSON with "status": "CRITICAL", a capped risk_score, exact file/line targets, and actionable remediation steps, while returning exit code 2 so GitHub Actions or GitLab CI can block compromised builds automatically.

Learning Outcomes & Final-Year Viva Questions

Prepare for your BTech, MCA, or MTech project viva with these practical security engineering answers:

  • Why are .pth files dangerous in Python? Because Python’s site module automatically executes any line starting with import inside a .pth file on every interpreter startup—even if the user never imports the package in their code.
  • Why use Python’s ast module instead of plain regex alone? Parsing source code into an Abstract Syntax Tree distinguishes real function calls (such as exec(), eval(), or urlopen()) from harmless comments or documentation strings.
  • How does pinning with == reduce supply-chain risk? Strict pinning prevents pip from silently pulling a newly compromised minor or patch release during automated builds.

Frequently Asked Questions

Does this python supply chain security scanner execute untrusted code during scanning?

No. Both the .pth auditor and the AST analyzer inspect files purely as static text and syntax trees without importing or running any untrusted module.

Can I integrate cli.py into GitHub Actions?

Yes. Run python cli.py –requirements requirements.txt in your CI workflow; it exits with status code 2 whenever CRITICAL findings are detected.

Are all .pth files in site-packages malicious?

No. Editable installs and virtual environments use .pth files safely to add directory paths to sys.path. Only .pth files containing executable Python statements like import or exec() are flagged.

How can I expand the compromised package advisory list?

Add new package-to-version mappings to COMPROMISED_ADVISORIES in scanner/deps_auditor.py or load advisories dynamically from an OSV JSON feed.

Is this project suitable for a BTech or MCA final-year submission?

Yes. It demonstrates static AST analysis, REST API design with FastAPI, SQLite persistence, and automated unit testing around a real cybersecurity threat.


Download the Source Code

The complete source code with the CLI, FastAPI web dashboard, SQLite persistence, and automated unit tests is free on GitHub under the MIT License. Clone it, star it, and customize it for your college project or portfolio.

Conclusion

Building a python supply chain security scanner gives you hands-on insight into how modern package-level attacks work—and how defensive tooling stops them before a single secret leaves your laptop. With FastAPI, AST inspection, and SQLite working together, you now have a practical, testable security project ready for your portfolio and final-year viva.

Advertisement

Team Get Projects

Contributor & Author
View All Projects →

Contributor at GetProjects.org, sharing open-source codebases, tutorials, and practical software architectures.

0 Discussion Comments

Markdown Supported

Join the Discussion & Code Review

Share architectural feedback, benchmark results, or troubleshooting notes.