compliance-core 1.0.0__py3-none-any.whl

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,35 @@
1
+ """
2
+ compliance_core
3
+ Universal multi-stack codebase compliance and security auditing engine.
4
+ """
5
+
6
+ from compliance_core.engine import ComplianceEngine
7
+ from compliance_core.models import (
8
+ AuditControl,
9
+ ComplianceFramework,
10
+ ComplianceReport,
11
+ Finding,
12
+ Severity,
13
+ ControlStatus,
14
+ AuditIntegrityStats,
15
+ RemediationItem
16
+ )
17
+ from compliance_core.discovery import discover_codebase, CodebaseInventory
18
+ from compliance_core.reporters.html_reporter import generate_html_report
19
+
20
+ __version__ = "1.0.0"
21
+
22
+ __all__ = [
23
+ "ComplianceEngine",
24
+ "ComplianceReport",
25
+ "Finding",
26
+ "Severity",
27
+ "ControlStatus",
28
+ "AuditControl",
29
+ "ComplianceFramework",
30
+ "AuditIntegrityStats",
31
+ "RemediationItem",
32
+ "discover_codebase",
33
+ "CodebaseInventory",
34
+ "generate_html_report"
35
+ ]
compliance_core/cli.py ADDED
@@ -0,0 +1,127 @@
1
+ """
2
+ compliance_core.cli
3
+ Command Line Interface for compliance-core.
4
+ Usage:
5
+ compliance-scan <path> [--format json|html|summary] [--output <file>] [--threshold <int>]
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+ from compliance_core.engine import ComplianceEngine
13
+ from compliance_core.reporters.html_reporter import generate_html_report
14
+
15
+
16
+ def main() -> None:
17
+ parser = argparse.ArgumentParser(
18
+ prog="compliance-scan",
19
+ description="Universal multi-stack codebase compliance and security auditing engine."
20
+ )
21
+ parser.add_argument(
22
+ "path",
23
+ nargs="?",
24
+ default=".",
25
+ help="Path to the repository/codebase root (default: current directory)"
26
+ )
27
+ parser.add_argument(
28
+ "-f", "--format",
29
+ choices=["summary", "json", "html"],
30
+ default="summary",
31
+ help="Report output format (default: summary)"
32
+ )
33
+ parser.add_argument(
34
+ "-o", "--output",
35
+ default="",
36
+ help="File path to save output report (optional)"
37
+ )
38
+ parser.add_argument(
39
+ "--html",
40
+ default="compliance-report.html",
41
+ help="Path where the interactive HTML cockpit report will be saved (default: compliance-report.html)"
42
+ )
43
+ parser.add_argument(
44
+ "--no-html",
45
+ action="store_true",
46
+ help="Disable automatic HTML report generation"
47
+ )
48
+ parser.add_argument(
49
+ "-t", "--threshold",
50
+ type=int,
51
+ default=0,
52
+ help="Minimum required readiness percentage (0-100). Fails with exit code 1 if below threshold."
53
+ )
54
+
55
+ args = parser.parse_args()
56
+
57
+ target_dir = os.path.abspath(args.path)
58
+ if not os.path.isdir(target_dir):
59
+ print(f"Error: Target path '{target_dir}' is not a valid directory.", file=sys.stderr)
60
+ sys.exit(2)
61
+
62
+ print(f"[*] Crawling and auditing codebase at: {target_dir}")
63
+ engine = ComplianceEngine(root_path=target_dir)
64
+ report = engine.scan()
65
+
66
+ output_content = ""
67
+
68
+ if args.format == "json":
69
+ output_content = json.dumps(report.to_cockpit_dict(), indent=2)
70
+ if not args.output:
71
+ print(output_content)
72
+
73
+ elif args.format == "html":
74
+ output_content = generate_html_report(report)
75
+ if not args.output:
76
+ print(output_content)
77
+
78
+ else: # summary
79
+ print("\n" + "=" * 70)
80
+ print(" COMPLIANCE & SECURITY AUDIT SUMMARY")
81
+ print("=" * 70)
82
+ print(f" Scanned Files : {report.scanned_files_count}")
83
+ print(f" Execution Time : {report.execution_time_ms} ms")
84
+ print(f" Regulatory Readiness: {report.readiness_score}%")
85
+ print(f" Standards Passing : {report.standards_passing}")
86
+ print(f" Active Controls : {report.security_controls_active}")
87
+ print(f" SHA-256 Block Hash : {report.audit_integrity.currentBlockHash[:20]}...")
88
+ print("-" * 70)
89
+ print(" FRAMEWORK READINESS BREAKDOWN:")
90
+ for fw in report.frameworks:
91
+ print(f" - {fw.name:<24}: {fw.readiness_percent:>3}% Ready")
92
+ print("-" * 70)
93
+ print(f" TOTAL FINDINGS: {len(report.findings)}")
94
+
95
+ crit = sum(1 for f in report.findings if f.severity.value == "CRITICAL")
96
+ high = sum(1 for f in report.findings if f.severity.value == "HIGH")
97
+ med = sum(1 for f in report.findings if f.severity.value == "MEDIUM")
98
+ print(f" Critical: {crit} | High: {high} | Medium: {med}")
99
+
100
+ if report.findings:
101
+ print("\n TOP FINDINGS (First 5):")
102
+ for f in report.findings[:5]:
103
+ print(f" [{f.severity.value}] {f.location} - {f.description[:60]}... ({f.cwe_id})")
104
+
105
+ print("=" * 70 + "\n")
106
+
107
+ if args.output:
108
+ with open(args.output, "w", encoding="utf-8") as out_f:
109
+ out_f.write(output_content)
110
+ print(f"[+] Output report written to: {args.output}")
111
+
112
+ # Automatically generate interactive HTML Cockpit report unless --no-html is set
113
+ if not args.no_html and args.format != "html":
114
+ html_path = os.path.abspath(args.html)
115
+ html_content = generate_html_report(report)
116
+ with open(html_path, "w", encoding="utf-8") as html_f:
117
+ html_f.write(html_content)
118
+ print(f"[+] Interactive HTML Cockpit Report generated at: file:///{html_path.replace(os.sep, '/')}")
119
+
120
+ # Check CI/CD threshold
121
+ if args.threshold > 0 and report.readiness_score < args.threshold:
122
+ print(f"[!] FAILED: Regulatory readiness {report.readiness_score}% is below threshold {args.threshold}%.", file=sys.stderr)
123
+ sys.exit(1)
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()
@@ -0,0 +1,103 @@
1
+ """
2
+ compliance_core.discovery
3
+ Multi-language codebase crawler and file categorization engine.
4
+ """
5
+
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Dict, List, Set
9
+
10
+ IGNORED_DIRS: Set[str] = {
11
+ ".git",
12
+ ".hg",
13
+ ".svn",
14
+ "node_modules",
15
+ ".venv",
16
+ "venv",
17
+ "env",
18
+ "__pycache__",
19
+ ".mypy_cache",
20
+ ".pytest_cache",
21
+ ".ruff_cache",
22
+ "dist",
23
+ "build",
24
+ "out",
25
+ ".angular",
26
+ ".next",
27
+ ".nuxt",
28
+ ".idea",
29
+ ".vscode",
30
+ "coverage",
31
+ ".tox",
32
+ ".eggs"
33
+ }
34
+
35
+ IGNORED_EXTENSIONS: Set[str] = {
36
+ ".pyc", ".pyo", ".pyd", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg",
37
+ ".woff", ".woff2", ".ttf", ".eot", ".zip", ".tar", ".gz", ".rar",
38
+ ".pdf", ".exe", ".dll", ".so", ".dylib", ".db", ".sqlite", ".db-wal", ".db-shm",
39
+ ".lock", ".map"
40
+ }
41
+
42
+
43
+ class CodebaseInventory:
44
+ def __init__(self, root_dir: str):
45
+ self.root_dir = os.path.abspath(root_dir)
46
+ self.python_files: List[str] = []
47
+ self.frontend_files: List[str] = []
48
+ self.dependency_files: List[str] = []
49
+ self.iac_files: List[str] = []
50
+ self.config_files: List[str] = []
51
+ self.all_scannable_files: List[str] = []
52
+
53
+ @property
54
+ def total_files_count(self) -> int:
55
+ return len(self.all_scannable_files)
56
+
57
+
58
+ def discover_codebase(root_dir: str) -> CodebaseInventory:
59
+ """
60
+ Crawls the target codebase directory and categorizes files for targeted security scans.
61
+ Respects common ignored paths and binary file extensions.
62
+ """
63
+ inventory = CodebaseInventory(root_dir)
64
+ root_path = Path(inventory.root_dir)
65
+
66
+ if not root_path.exists():
67
+ return inventory
68
+
69
+ for dirpath, dirnames, filenames in os.walk(inventory.root_dir):
70
+ # Prune ignored directories in-place so os.walk does not descend into them
71
+ dirnames[:] = [d for d in dirnames if d not in IGNORED_DIRS and not d.startswith(".git")]
72
+
73
+ for filename in filenames:
74
+ ext = os.path.splitext(filename)[1].lower()
75
+ if ext in IGNORED_EXTENSIONS:
76
+ continue
77
+
78
+ full_path = os.path.join(dirpath, filename)
79
+ rel_name = filename.lower()
80
+
81
+ inventory.all_scannable_files.append(full_path)
82
+
83
+ # Python
84
+ if ext == ".py":
85
+ inventory.python_files.append(full_path)
86
+
87
+ # Frontend (TypeScript, JavaScript, HTML, Templates)
88
+ elif ext in (".ts", ".tsx", ".js", ".jsx", ".html", ".htm"):
89
+ inventory.frontend_files.append(full_path)
90
+
91
+ # Supply Chain / Dependencies
92
+ if rel_name in ("requirements.txt", "poetry.lock", "pipfile", "package.json", "package-lock.json"):
93
+ inventory.dependency_files.append(full_path)
94
+
95
+ # Infrastructure as Code / Container
96
+ if "dockerfile" in rel_name or rel_name.startswith("docker-compose") or ext in (".yaml", ".yml"):
97
+ inventory.iac_files.append(full_path)
98
+
99
+ # Environment and config
100
+ if rel_name.startswith(".env") or ext in (".env", ".ini", ".toml", ".cfg", ".json"):
101
+ inventory.config_files.append(full_path)
102
+
103
+ return inventory
@@ -0,0 +1,77 @@
1
+ """
2
+ compliance_core.engine
3
+ Central orchestrator for codebase discovery, scanner execution, framework mapping, and report generation.
4
+ """
5
+
6
+ from datetime import datetime, timezone
7
+ import time
8
+ from typing import List, Optional
9
+ from compliance_core.discovery import discover_codebase
10
+ from compliance_core.frameworks.mapper import map_findings_to_frameworks
11
+ from compliance_core.integrity.merkle import generate_audit_integrity_proof
12
+ from compliance_core.models import ComplianceReport, Finding, Severity
13
+ from compliance_core.scanners import get_default_scanners
14
+ from compliance_core.scanners.base import BaseScanner
15
+
16
+
17
+ class ComplianceEngine:
18
+ def __init__(
19
+ self,
20
+ root_path: str = ".",
21
+ scanners: Optional[List[BaseScanner]] = None
22
+ ):
23
+ self.root_path = root_path
24
+ self.scanners = scanners or get_default_scanners()
25
+
26
+ def scan(self) -> ComplianceReport:
27
+ """
28
+ Executes a comprehensive, full-codebase compliance scan and returns a structured ComplianceReport.
29
+ """
30
+ start_time = time.perf_counter()
31
+ scan_time_iso = datetime.now(timezone.utc).isoformat()
32
+
33
+ # 1. Discover codebase files across all languages
34
+ inventory = discover_codebase(self.root_path)
35
+
36
+ # 2. Execute all registered scanners
37
+ all_findings: List[Finding] = []
38
+ for scanner in self.scanners:
39
+ try:
40
+ findings = scanner.scan(inventory)
41
+ all_findings.extend(findings)
42
+ except Exception:
43
+ continue
44
+
45
+ # 3. Sort findings by severity
46
+ severity_rank = {
47
+ Severity.CRITICAL: 0,
48
+ Severity.HIGH: 1,
49
+ Severity.MEDIUM: 2,
50
+ Severity.LOW: 3,
51
+ Severity.INFO: 4
52
+ }
53
+ all_findings.sort(key=lambda f: severity_rank.get(f.severity, 5))
54
+
55
+ # 4. Map findings to regulatory frameworks and compute readiness score
56
+ frameworks, measures, readiness_score, standards_passing, remediations = map_findings_to_frameworks(all_findings)
57
+
58
+ # 5. Generate cryptographic SHA-256 Merkle proof
59
+ integrity_stats = generate_audit_integrity_proof(all_findings, scan_time_iso)
60
+
61
+ elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
62
+
63
+ active_measures_count = sum(1 for m in measures if m.status == "active")
64
+
65
+ return ComplianceReport(
66
+ readiness_score=readiness_score,
67
+ standards_passing=standards_passing,
68
+ security_controls_active=f"{active_measures_count} / {len(measures)}",
69
+ audit_integrity=integrity_stats,
70
+ frameworks=frameworks,
71
+ measures=measures,
72
+ findings=all_findings,
73
+ remediations=remediations,
74
+ execution_time_ms=elapsed_ms,
75
+ scanned_files_count=inventory.total_files_count,
76
+ timestamp=scan_time_iso
77
+ )