driftguard-audit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Adnan Omar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: driftguard-audit
3
+ Version: 0.1.0
4
+ Summary: Offline security capability diffing for Python package releases
5
+ Author: Adnan Omar
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/adnanomar77/driftguard-audit
8
+ Project-URL: Repository, https://github.com/adnanomar77/driftguard-audit
9
+ Project-URL: Issues, https://github.com/adnanomar77/driftguard-audit/issues
10
+ Keywords: security,supply-chain,python,static-analysis,dependency-audit
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Security
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest>=7; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # DriftGuard Audit
25
+
26
+ Offline security-capability diffing for Python package releases.
27
+
28
+ DriftGuard Audit compares two local Python package directories or ZIP/wheel/sdist archives without importing or executing package code. It reports newly observed capabilities such as process spawning, network access, environment reads, dynamic code, native loading, and filesystem access.
29
+
30
+ > This is static analysis, not proof of safety. Dynamic dispatch, obfuscation, native extensions, and behavior outside the analyzed Python source can be missed.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ python -m pip install driftguard-audit
36
+ ```
37
+
38
+ ## CLI
39
+
40
+ ```bash
41
+ driftguard analyze old.whl --json
42
+ driftguard diff old.whl new.whl --json
43
+ ```
44
+
45
+ The `diff` command exits with status `2` when new capabilities are observed, `0` when no capability drift is observed, and a nonzero error status for invalid input.
46
+
47
+ ## Python API
48
+
49
+ ```python
50
+ from driftguard import compare_packages
51
+
52
+ report = compare_packages("old.whl", "new.whl")
53
+ if report.added:
54
+ print(report.to_json())
55
+ ```
56
+
57
+ ## Scope and safety
58
+
59
+ The package is offline and has no runtime dependencies. It reads local directories and ZIP-compatible archives, extracts archives with path-boundary checks into a temporary directory, never imports the target package, and never executes package code. It does not query CVE databases, verify intent, scan native binaries, or replace sandboxing, EDR, SCA, or package-signature verification.
60
+
61
+ ## License
62
+
63
+ MIT
@@ -0,0 +1,40 @@
1
+ # DriftGuard Audit
2
+
3
+ Offline security-capability diffing for Python package releases.
4
+
5
+ DriftGuard Audit compares two local Python package directories or ZIP/wheel/sdist archives without importing or executing package code. It reports newly observed capabilities such as process spawning, network access, environment reads, dynamic code, native loading, and filesystem access.
6
+
7
+ > This is static analysis, not proof of safety. Dynamic dispatch, obfuscation, native extensions, and behavior outside the analyzed Python source can be missed.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ python -m pip install driftguard-audit
13
+ ```
14
+
15
+ ## CLI
16
+
17
+ ```bash
18
+ driftguard analyze old.whl --json
19
+ driftguard diff old.whl new.whl --json
20
+ ```
21
+
22
+ The `diff` command exits with status `2` when new capabilities are observed, `0` when no capability drift is observed, and a nonzero error status for invalid input.
23
+
24
+ ## Python API
25
+
26
+ ```python
27
+ from driftguard import compare_packages
28
+
29
+ report = compare_packages("old.whl", "new.whl")
30
+ if report.added:
31
+ print(report.to_json())
32
+ ```
33
+
34
+ ## Scope and safety
35
+
36
+ The package is offline and has no runtime dependencies. It reads local directories and ZIP-compatible archives, extracts archives with path-boundary checks into a temporary directory, never imports the target package, and never executes package code. It does not query CVE databases, verify intent, scan native binaries, or replace sandboxing, EDR, SCA, or package-signature verification.
37
+
38
+ ## License
39
+
40
+ MIT
@@ -0,0 +1,5 @@
1
+ """DriftGuard: offline security capability diffing for Python packages."""
2
+ from .analyzer import Capability, Report, analyze_package, compare_packages
3
+
4
+ __all__ = ["Capability", "Report", "analyze_package", "compare_packages"]
5
+ __version__ = "0.1.0"
@@ -0,0 +1,143 @@
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import json
5
+ import tempfile
6
+ import zipfile
7
+ from dataclasses import asdict, dataclass, field
8
+ from pathlib import Path
9
+
10
+
11
+ @dataclass(frozen=True, order=True)
12
+ class Capability:
13
+ kind: str
14
+ evidence: str
15
+ file: str
16
+ line: int
17
+ severity: str
18
+
19
+
20
+ @dataclass
21
+ class Report:
22
+ old: str
23
+ new: str
24
+ added: list[Capability] = field(default_factory=list)
25
+ removed: list[Capability] = field(default_factory=list)
26
+ unchanged: list[Capability] = field(default_factory=list)
27
+ warnings: list[str] = field(default_factory=list)
28
+
29
+ @property
30
+ def decision(self) -> str:
31
+ return "REVIEW" if self.added else "UNCHANGED"
32
+
33
+ def to_dict(self) -> dict:
34
+ return {"old": self.old, "new": self.new, "decision": self.decision,
35
+ "added_capabilities": [asdict(x) for x in self.added],
36
+ "removed_capabilities": [asdict(x) for x in self.removed],
37
+ "unchanged_capabilities": [asdict(x) for x in self.unchanged],
38
+ "warnings": self.warnings}
39
+
40
+ def to_json(self) -> str:
41
+ return json.dumps(self.to_dict(), indent=2, sort_keys=True)
42
+
43
+
44
+ _RULES = (
45
+ ("process_spawn", "subprocess", "high"), ("process_spawn", "os.system", "high"),
46
+ ("process_spawn", "os.popen", "high"), ("network_access", "socket", "high"),
47
+ ("network_access", "requests", "medium"), ("network_access", "urllib", "medium"),
48
+ ("network_access", "httpx", "medium"), ("dynamic_code", "eval", "high"),
49
+ ("dynamic_code", "exec", "high"), ("dynamic_import", "importlib", "medium"),
50
+ ("environment_read", "os.environ", "medium"), ("filesystem_access", "open", "low"),
51
+ ("filesystem_access", "pathlib", "low"), ("native_code", "ctypes", "high"),
52
+ )
53
+
54
+
55
+ def _safe_extract(archive: zipfile.ZipFile, destination: Path) -> None:
56
+ destination = destination.resolve()
57
+ for member in archive.infolist():
58
+ name = member.filename.replace("\\", "/")
59
+ target = (destination / name).resolve()
60
+ if target != destination and destination not in target.parents:
61
+ raise ValueError(f"archive member escapes extraction directory: {member.filename}")
62
+ if member.is_dir():
63
+ target.mkdir(parents=True, exist_ok=True)
64
+ else:
65
+ target.parent.mkdir(parents=True, exist_ok=True)
66
+ target.write_bytes(archive.read(member))
67
+
68
+
69
+ def _archive_root(source: str | Path):
70
+ path = Path(source)
71
+ if path.is_dir():
72
+ yield path, None
73
+ return
74
+ if not path.is_file():
75
+ raise FileNotFoundError(source)
76
+ tmp = tempfile.TemporaryDirectory(prefix="driftguard-")
77
+ try:
78
+ with zipfile.ZipFile(path) as archive:
79
+ _safe_extract(archive, Path(tmp.name))
80
+ yield Path(tmp.name), tmp
81
+ except (zipfile.BadZipFile, ValueError) as exc:
82
+ tmp.cleanup()
83
+ if isinstance(exc, ValueError):
84
+ raise
85
+ raise ValueError(f"Expected a directory or ZIP/wheel/sdist archive: {source}") from exc
86
+
87
+
88
+ def _node_text(node: ast.AST) -> str:
89
+ if isinstance(node, (ast.Call, ast.Attribute, ast.Name)):
90
+ return ast.unparse(node)
91
+ if isinstance(node, ast.Import):
92
+ return " ".join(alias.name for alias in node.names)
93
+ if isinstance(node, ast.ImportFrom):
94
+ return node.module or ""
95
+ return ""
96
+
97
+
98
+ def _capabilities(root: Path) -> list[Capability]:
99
+ found: dict[tuple[str, str, int], Capability] = {}
100
+ for source in sorted(root.rglob("*.py")):
101
+ if any(part in {"__pycache__", ".git", ".tox", ".venv"} for part in source.parts):
102
+ continue
103
+ relative = source.relative_to(root).as_posix()
104
+ try:
105
+ tree = ast.parse(source.read_text(encoding="utf-8"), filename=relative)
106
+ except (UnicodeDecodeError, SyntaxError):
107
+ continue
108
+ for node in ast.walk(tree):
109
+ text = _node_text(node)
110
+ for kind, token, severity in _RULES:
111
+ if token in text:
112
+ key = (kind, relative, node.lineno)
113
+ candidate = Capability(kind, text[:160], relative, node.lineno, severity)
114
+ current = found.get(key)
115
+ if current is None or len(candidate.evidence) < len(current.evidence):
116
+ found[key] = candidate
117
+ return sorted(found.values())
118
+
119
+
120
+ def analyze_package(source: str | Path) -> list[Capability]:
121
+ """Analyze a local directory or ZIP-compatible archive without executing it."""
122
+ root, holder = next(_archive_root(source))
123
+ try:
124
+ return _capabilities(root)
125
+ finally:
126
+ if holder is not None:
127
+ holder.cleanup()
128
+
129
+
130
+ def _key(item: Capability) -> tuple[str, str, str, int]:
131
+ return item.kind, item.evidence, item.file, item.line
132
+
133
+
134
+ def compare_packages(old: str | Path, new: str | Path) -> Report:
135
+ """Compare two local package directories or ZIP-compatible archives."""
136
+ old_caps, new_caps = analyze_package(old), analyze_package(new)
137
+ old_map, new_map = {_key(x): x for x in old_caps}, {_key(x): x for x in new_caps}
138
+ return Report(str(old), str(new),
139
+ [new_map[k] for k in sorted(new_map.keys() - old_map.keys())],
140
+ [old_map[k] for k in sorted(old_map.keys() - new_map.keys())],
141
+ [new_map[k] for k in sorted(new_map.keys() & old_map.keys())],
142
+ ["Static analysis cannot prove runtime behavior; dynamic dispatch and native binaries may be missed.",
143
+ "Package code is never executed; archives are extracted only to a private temporary directory."])
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from .analyzer import analyze_package, compare_packages
9
+
10
+
11
+ def _parser() -> argparse.ArgumentParser:
12
+ parser = argparse.ArgumentParser(prog="driftguard", description="Offline security capability diff for Python packages")
13
+ sub = parser.add_subparsers(dest="command", required=True)
14
+ analyze = sub.add_parser("analyze", help="Analyze one local package without executing it")
15
+ analyze.add_argument("package", type=Path)
16
+ analyze.add_argument("--json", action="store_true")
17
+ diff = sub.add_parser("diff", help="Compare security capabilities between two local releases")
18
+ diff.add_argument("old", type=Path)
19
+ diff.add_argument("new", type=Path)
20
+ diff.add_argument("--json", action="store_true")
21
+ return parser
22
+
23
+
24
+ def main(argv: list[str] | None = None) -> int:
25
+ args = _parser().parse_args(argv)
26
+ if args.command == "analyze":
27
+ result = [c.__dict__ for c in analyze_package(args.package)]
28
+ if args.json:
29
+ print(json.dumps(result, indent=2, sort_keys=True))
30
+ else:
31
+ for item in result:
32
+ print(f"{item['severity'].upper():6} {item['kind']:18} {item['file']}:{item['line']} {item['evidence']}")
33
+ return 0
34
+ report = compare_packages(args.old, args.new)
35
+ if args.json:
36
+ print(report.to_json())
37
+ else:
38
+ print(f"Decision: {report.decision}")
39
+ for capability in report.added:
40
+ print(f"+ {capability.severity.upper():6} {capability.kind:18} {capability.file}:{capability.line} {capability.evidence}")
41
+ for capability in report.removed:
42
+ print(f"- {capability.kind:18} {capability.file}:{capability.line} {capability.evidence}")
43
+ for warning in report.warnings:
44
+ print(f"Warning: {warning}", file=sys.stderr)
45
+ return 2 if report.added else 0
File without changes
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: driftguard-audit
3
+ Version: 0.1.0
4
+ Summary: Offline security capability diffing for Python package releases
5
+ Author: Adnan Omar
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/adnanomar77/driftguard-audit
8
+ Project-URL: Repository, https://github.com/adnanomar77/driftguard-audit
9
+ Project-URL: Issues, https://github.com/adnanomar77/driftguard-audit/issues
10
+ Keywords: security,supply-chain,python,static-analysis,dependency-audit
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Security
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest>=7; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # DriftGuard Audit
25
+
26
+ Offline security-capability diffing for Python package releases.
27
+
28
+ DriftGuard Audit compares two local Python package directories or ZIP/wheel/sdist archives without importing or executing package code. It reports newly observed capabilities such as process spawning, network access, environment reads, dynamic code, native loading, and filesystem access.
29
+
30
+ > This is static analysis, not proof of safety. Dynamic dispatch, obfuscation, native extensions, and behavior outside the analyzed Python source can be missed.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ python -m pip install driftguard-audit
36
+ ```
37
+
38
+ ## CLI
39
+
40
+ ```bash
41
+ driftguard analyze old.whl --json
42
+ driftguard diff old.whl new.whl --json
43
+ ```
44
+
45
+ The `diff` command exits with status `2` when new capabilities are observed, `0` when no capability drift is observed, and a nonzero error status for invalid input.
46
+
47
+ ## Python API
48
+
49
+ ```python
50
+ from driftguard import compare_packages
51
+
52
+ report = compare_packages("old.whl", "new.whl")
53
+ if report.added:
54
+ print(report.to_json())
55
+ ```
56
+
57
+ ## Scope and safety
58
+
59
+ The package is offline and has no runtime dependencies. It reads local directories and ZIP-compatible archives, extracts archives with path-boundary checks into a temporary directory, never imports the target package, and never executes package code. It does not query CVE databases, verify intent, scan native binaries, or replace sandboxing, EDR, SCA, or package-signature verification.
60
+
61
+ ## License
62
+
63
+ MIT
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ driftguard/__init__.py
5
+ driftguard/analyzer.py
6
+ driftguard/cli.py
7
+ driftguard/py.typed
8
+ driftguard_audit.egg-info/PKG-INFO
9
+ driftguard_audit.egg-info/SOURCES.txt
10
+ driftguard_audit.egg-info/dependency_links.txt
11
+ driftguard_audit.egg-info/entry_points.txt
12
+ driftguard_audit.egg-info/requires.txt
13
+ driftguard_audit.egg-info/top_level.txt
14
+ tests/test_analyzer.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ driftguard = driftguard.cli:main
@@ -0,0 +1,3 @@
1
+
2
+ [test]
3
+ pytest>=7
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "driftguard-audit"
7
+ version = "0.1.0"
8
+ description = "Offline security capability diffing for Python package releases"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Adnan Omar" }]
13
+ keywords = ["security", "supply-chain", "python", "static-analysis", "dependency-audit"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Topic :: Security",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.scripts]
25
+ driftguard = "driftguard.cli:main"
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/adnanomar77/driftguard-audit"
29
+ Repository = "https://github.com/adnanomar77/driftguard-audit"
30
+ Issues = "https://github.com/adnanomar77/driftguard-audit/issues"
31
+
32
+ [project.optional-dependencies]
33
+ test = ["pytest>=7"]
34
+
35
+ [tool.setuptools.packages.find]
36
+ include = ["driftguard*"]
37
+
38
+ [tool.setuptools.package-data]
39
+ driftguard = ["py.typed"]
40
+
41
+ [tool.pytest.ini_options]
42
+ testpaths = ["tests"]
43
+ addopts = "-q"
44
+ filterwarnings = ["error"]
45
+ markers = ["security: security-focused tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,49 @@
1
+ from pathlib import Path
2
+ from zipfile import ZipFile
3
+
4
+ import pytest
5
+
6
+ from driftguard import analyze_package, compare_packages
7
+
8
+
9
+ def write_pkg(root: Path, body: str) -> Path:
10
+ root.mkdir()
11
+ (root / "pkg.py").write_text(body, encoding="utf-8")
12
+ return root
13
+
14
+
15
+ def test_detects_new_network_and_process(tmp_path):
16
+ old = write_pkg(tmp_path / "old", "def run():\n return 1\n")
17
+ new = write_pkg(tmp_path / "new", "import socket\nimport subprocess\ndef run():\n socket.socket()\n subprocess.run(['x'])\n")
18
+ report = compare_packages(old, new)
19
+ assert report.decision == "REVIEW"
20
+ assert {x.kind for x in report.added} == {"network_access", "process_spawn"}
21
+
22
+
23
+ def test_same_capabilities_are_unchanged(tmp_path):
24
+ old = write_pkg(tmp_path / "old", "import os\nprint(os.environ.get('X'))\n")
25
+ new = write_pkg(tmp_path / "new", "import os\nprint(os.environ.get('X'))\n")
26
+ report = compare_packages(old, new)
27
+ assert report.decision == "UNCHANGED"
28
+ assert len(report.unchanged) >= 1
29
+
30
+
31
+ def test_zip_is_supported_without_execution(tmp_path):
32
+ archive = tmp_path / "pkg.whl"
33
+ with ZipFile(archive, "w") as zf:
34
+ zf.writestr("pkg/__init__.py", "import ctypes\n")
35
+ found = analyze_package(archive)
36
+ assert any(item.kind == "native_code" for item in found)
37
+
38
+
39
+ def test_zip_path_escape_is_rejected(tmp_path):
40
+ archive = tmp_path / "evil.zip"
41
+ with ZipFile(archive, "w") as zf:
42
+ zf.writestr("../../outside.py", "import socket\n")
43
+ with pytest.raises(ValueError, match="escapes"):
44
+ analyze_package(archive)
45
+
46
+
47
+ def test_missing_input_is_rejected(tmp_path):
48
+ with pytest.raises(FileNotFoundError):
49
+ analyze_package(tmp_path / "missing.whl")