auditwright 0.1.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,92 @@
1
+ """Project overview: languages, frameworks, tooling and existing security controls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ from .walk import CODE_LANGUAGES, Project
9
+
10
+ FRAMEWORKS = {
11
+ "Django": r"\bdjango\b", "Flask": r"\bflask\b", "FastAPI": r"\bfastapi\b", "Starlette": r"\bstarlette\b",
12
+ "Express": r"\"express\"", "Next.js": r"\"next\"", "React": r"\"react\"", "Vue": r"\"vue\"",
13
+ "Svelte": r"\"svelte\"", "Angular": r"\"@angular/core\"", "NestJS": r"\"@nestjs/core\"", "Koa": r"\"koa\"",
14
+ "Fastify": r"\"fastify\"", "Spring": r"spring-boot|org\.springframework", "Rails": r"\brails\b",
15
+ "Laravel": r"laravel/framework", "Gin": r"gin-gonic/gin", "Echo": r"labstack/echo", "Fiber": r"gofiber/fiber",
16
+ "ASP.NET": r"Microsoft\.AspNetCore", "Phoenix": r":phoenix", "Actix": r"actix-web", "Axum": r"\baxum\b",
17
+ } # fmt: skip
18
+ AI_SDKS = {
19
+ "OpenAI SDK": r"\bopenai\b", "LangChain": r"langchain", "LlamaIndex": r"llama[_-]index", "Hugging Face": r"transformers|huggingface",
20
+ "Vercel AI SDK": r"\"ai\"\s*:|@ai-sdk/", "Google GenAI": r"google[.-]generativeai|google-genai|@google/genai",
21
+ "Mistral": r"mistralai", "Cohere": r"\bcohere\b", "Ollama": r"\bollama\b", "LiteLLM": r"litellm",
22
+ "MCP": r"@modelcontextprotocol|\bmcp\b", "CrewAI": r"crewai", "AutoGen": r"autogen", "DSPy": r"\bdspy\b",
23
+ } # fmt: skip
24
+ MANIFESTS = (
25
+ "requirements.txt", "pyproject.toml", "setup.py", "Pipfile", "package.json", "go.mod", "Cargo.toml", "Gemfile",
26
+ "composer.json", "pom.xml", "build.gradle", "build.gradle.kts", "packages.config", "mix.exs", "pubspec.yaml",
27
+ ) # fmt: skip
28
+
29
+
30
+ def build(project: Project) -> dict[str, Any]:
31
+ langs: dict[str, dict[str, int]] = {}
32
+ manifest_text = []
33
+ names = set()
34
+ rels = []
35
+ for f in project.files():
36
+ names.add(f.path.name)
37
+ rels.append(f.rel)
38
+ if f.language:
39
+ entry = langs.setdefault(f.language, {"files": 0, "lines": 0})
40
+ entry["files"] += 1
41
+ if f.language in CODE_LANGUAGES or f.language in ("HTML", "SQL", "Terraform", "Dockerfile"):
42
+ entry["lines"] += f.text().count("\n") + 1
43
+ if f.path.name in MANIFESTS or f.path.name.endswith(".csproj"):
44
+ manifest_text.append(f.text()[:200_000])
45
+ blob = "\n".join(manifest_text)
46
+ tests = []
47
+ if "pytest" in blob or any(re.search(r"(^|/)(test_[^/]+|[^/]+_test)\.py$", r) for r in rels):
48
+ tests.append("pytest")
49
+ for name, pat in (("jest", r"\"jest\""), ("vitest", r"\"vitest\""), ("mocha", r"\"mocha\""), ("playwright", r"@playwright/test"),
50
+ ("cypress", r"\"cypress\""), ("rspec", r"rspec"), ("phpunit", r"phpunit"), ("junit", r"junit")): # fmt: skip
51
+ if re.search(pat, blob):
52
+ tests.append(name)
53
+ if "go.mod" in names and any(r.endswith("_test.go") for r in rels):
54
+ tests.append("go test")
55
+ if "Cargo.toml" in names:
56
+ tests.append("cargo test")
57
+ ci = [n for n, cond in (
58
+ ("GitHub Actions", any(r.startswith(".github/workflows/") for r in rels)),
59
+ ("GitLab CI", ".gitlab-ci.yml" in names), ("CircleCI", any(r.startswith(".circleci/") for r in rels)),
60
+ ("Azure Pipelines", "azure-pipelines.yml" in names), ("Jenkins", "Jenkinsfile" in names),
61
+ ("Bitbucket Pipelines", "bitbucket-pipelines.yml" in names),
62
+ ) if cond] # fmt: skip
63
+ controls = {
64
+ "security_policy": any(r.lower() in ("security.md", ".github/security.md", "docs/security.md") for r in rels),
65
+ "dependabot": ".github/dependabot.yml" in rels or ".github/dependabot.yaml" in rels,
66
+ "renovate": any(n in names for n in ("renovate.json", ".renovaterc", ".renovaterc.json")),
67
+ "codeql": any("codeql" in r for r in rels if r.startswith(".github/workflows/")),
68
+ "pre_commit": ".pre-commit-config.yaml" in names,
69
+ "lockfiles": sorted(n for n in names if n.endswith((".lock", "-lock.json", "-lock.yaml")) or n == "go.sum"),
70
+ "gitignore": ".gitignore" in names,
71
+ "codeowners": any(r.endswith("CODEOWNERS") for r in rels),
72
+ "license": any(n.upper().startswith(("LICENSE", "LICENCE", "COPYING")) for n in names),
73
+ }
74
+ return {
75
+ "files_scanned": len(rels),
76
+ "skipped": dict(project.skipped),
77
+ "languages": dict(sorted(langs.items(), key=lambda kv: -kv[1]["lines"])),
78
+ "frameworks": sorted(k for k, p in FRAMEWORKS.items() if re.search(p, blob)),
79
+ "ai_sdks": sorted(k for k, p in AI_SDKS.items() if re.search(p, blob)),
80
+ "package_managers": sorted({m for m in MANIFESTS if m in names}),
81
+ "test_frameworks": tests,
82
+ "ci": ci,
83
+ "containers": sorted(
84
+ {"Dockerfile" for r in rels if r.endswith("Dockerfile") or "/Dockerfile" in r}
85
+ | {"docker-compose" for n in names if n.startswith(("docker-compose", "compose."))}
86
+ ), # fmt: skip
87
+ "iac": sorted(
88
+ {"Terraform" for r in rels if r.endswith(".tf")}
89
+ | {"Kubernetes" for f in project.by_language("YAML") if "apiVersion:" in f.text()[:4000]}
90
+ ), # fmt: skip
91
+ "controls": controls,
92
+ }
auditwright/model.py ADDED
@@ -0,0 +1,181 @@
1
+ """Shared data model: findings, rules metadata and the assembled report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ from dataclasses import asdict, dataclass, field
8
+ from typing import Any
9
+
10
+ SEVERITIES = ("info", "low", "medium", "high", "critical")
11
+ RANK = {s: i for i, s in enumerate(SEVERITIES)}
12
+ CONFIDENCES = ("low", "medium", "high")
13
+
14
+ CATEGORIES = {
15
+ "code": "Code security",
16
+ "secrets": "Secrets",
17
+ "deps": "Vulnerable and risky dependencies",
18
+ "config": "CI, container and infrastructure configuration",
19
+ "ai": "AI and LLM risks",
20
+ "unicode": "Hidden and deceptive characters",
21
+ "crypto": "Cryptography and post-quantum readiness",
22
+ "supply-chain": "Supply chain",
23
+ "pentest": "Live target (pen test)",
24
+ "tests": "Tests",
25
+ "chain": "Attack chains",
26
+ "network": "Network exposure",
27
+ }
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class RuleMeta:
32
+ id: str
33
+ title: str
34
+ category: str
35
+ severity: str
36
+ cwe: str = ""
37
+ owasp: str = ""
38
+ fix: str = ""
39
+ description: str = ""
40
+
41
+
42
+ @dataclass
43
+ class Finding:
44
+ rule_id: str
45
+ title: str
46
+ category: str
47
+ severity: str
48
+ message: str
49
+ file: str = ""
50
+ line: int = 0
51
+ column: int = 0
52
+ snippet: str = ""
53
+ confidence: str = "medium"
54
+ cwe: str = ""
55
+ owasp: str = ""
56
+ fix: str = ""
57
+ extra: dict[str, Any] = field(default_factory=dict)
58
+ fingerprint: str = ""
59
+
60
+ def __post_init__(self) -> None:
61
+ if self.severity not in RANK:
62
+ raise ValueError(f"unknown severity {self.severity!r}")
63
+ if not self.fingerprint:
64
+ self.fingerprint = make_fingerprint(self.rule_id, self.file, self.snippet or self.message)
65
+
66
+ @classmethod
67
+ def from_rule(cls, rule: RuleMeta, message: str, **kw: Any) -> Finding:
68
+ return cls(
69
+ rule_id=rule.id,
70
+ title=rule.title,
71
+ category=rule.category,
72
+ severity=kw.pop("severity", rule.severity),
73
+ message=message,
74
+ cwe=rule.cwe,
75
+ owasp=rule.owasp,
76
+ fix=rule.fix,
77
+ **kw,
78
+ )
79
+
80
+ def to_dict(self) -> dict[str, Any]:
81
+ return asdict(self)
82
+
83
+
84
+ _WS = re.compile(r"\s+")
85
+
86
+
87
+ def make_fingerprint(rule_id: str, file: str, text: str) -> str:
88
+ """Stable identity for a finding that survives line shifts and whitespace edits."""
89
+ norm = _WS.sub(" ", text).strip()
90
+ return hashlib.sha256(f"{rule_id}|{file}|{norm}".encode()).hexdigest()[:20]
91
+
92
+
93
+ @dataclass
94
+ class TestCase:
95
+ __test__ = False # a data record, not a pytest test class
96
+
97
+ name: str
98
+ classname: str = ""
99
+ status: str = "passed" # passed | failed | error | skipped
100
+ time: float = 0.0
101
+ message: str = ""
102
+
103
+
104
+ @dataclass
105
+ class TestRun:
106
+ __test__ = False
107
+
108
+ framework: str
109
+ command: list[str]
110
+ exit_code: int | None
111
+ duration: float
112
+ cases: list[TestCase] = field(default_factory=list)
113
+ output_tail: str = ""
114
+ error: str = ""
115
+ coverage: float | None = None
116
+
117
+ def counts(self) -> dict[str, int]:
118
+ out = {"passed": 0, "failed": 0, "error": 0, "skipped": 0}
119
+ for c in self.cases:
120
+ out[c.status] = out.get(c.status, 0) + 1
121
+ return out
122
+
123
+
124
+ @dataclass
125
+ class Report:
126
+ tool_version: str
127
+ target: str
128
+ started: str
129
+ finished: str = ""
130
+ findings: list[Finding] = field(default_factory=list)
131
+ inventory: dict[str, Any] = field(default_factory=dict)
132
+ dependencies: list[dict[str, Any]] = field(default_factory=list)
133
+ crypto_inventory: list[dict[str, Any]] = field(default_factory=list)
134
+ test_runs: list[TestRun] = field(default_factory=list)
135
+ pentest: dict[str, Any] = field(default_factory=dict)
136
+ network: dict[str, Any] = field(default_factory=dict)
137
+ analyzers: list[str] = field(default_factory=list)
138
+ notes: list[str] = field(default_factory=list)
139
+ errors: list[str] = field(default_factory=list)
140
+ suppressed: int = 0
141
+ baseline_matched: int = 0
142
+
143
+ def sorted_findings(self) -> list[Finding]:
144
+ return sorted(self.findings, key=lambda f: (-RANK[f.severity], f.category, f.file, f.line, f.rule_id))
145
+
146
+ def counts(self) -> dict[str, int]:
147
+ out = dict.fromkeys(SEVERITIES, 0)
148
+ for f in self.findings:
149
+ out[f.severity] += 1
150
+ return out
151
+
152
+ def by_category(self) -> dict[str, list[Finding]]:
153
+ out: dict[str, list[Finding]] = {}
154
+ for f in self.sorted_findings():
155
+ out.setdefault(f.category, []).append(f)
156
+ return out
157
+
158
+ def to_dict(self) -> dict[str, Any]:
159
+ d = asdict(self)
160
+ d["findings"] = [f.to_dict() for f in self.sorted_findings()]
161
+ d["summary"] = {"counts": self.counts(), **score(self)}
162
+ return d
163
+
164
+
165
+ def score(report: Report) -> dict[str, Any]:
166
+ """A 0-100 risk score and letter grade.
167
+
168
+ Each finding costs points by severity, scaled by confidence, with diminishing
169
+ returns per rule so one noisy rule cannot dominate the grade.
170
+ """
171
+ weights = {"critical": 25.0, "high": 10.0, "medium": 4.0, "low": 1.0, "info": 0.0}
172
+ conf = {"high": 1.0, "medium": 0.75, "low": 0.4}
173
+ per_rule: dict[str, float] = {}
174
+ for f in report.findings:
175
+ per_rule[f.rule_id] = per_rule.get(f.rule_id, 0.0) + weights[f.severity] * conf.get(f.confidence, 0.75)
176
+ penalty = sum(v if v <= 25 else 25 + (v - 25) ** 0.5 for v in per_rule.values())
177
+ value = max(0, round(100 - penalty))
178
+ if any(f.severity == "critical" for f in report.findings):
179
+ value = min(value, 49)
180
+ grade = "A" if value >= 90 else "B" if value >= 80 else "C" if value >= 65 else "D" if value >= 50 else "F"
181
+ return {"score": value, "grade": grade}
auditwright/net.py ADDED
@@ -0,0 +1,91 @@
1
+ """A small, defensive HTTP client on the standard library.
2
+
3
+ * HTTPS only unless a caller explicitly allows plain HTTP (the pen-test module
4
+ does, for targets the operator names).
5
+ * Redirects are never followed automatically; callers see them.
6
+ * Response bodies are capped; time-outs apply to connect and every read.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import ssl
13
+ import urllib.error
14
+ import urllib.request
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from ._version import __version__
19
+
20
+ USER_AGENT = f"auditwright/{__version__} (+https://github.com/shah2017/auditwright)"
21
+
22
+
23
+ @dataclass
24
+ class Response:
25
+ status: int
26
+ headers: dict[str, str]
27
+ body: bytes
28
+ url: str
29
+ header_list: list[tuple[str, str]] = field(default_factory=list)
30
+ truncated: bool = False
31
+
32
+ def json(self) -> Any:
33
+ return json.loads(self.body)
34
+
35
+ def text(self) -> str:
36
+ return self.body.decode("utf-8", "replace")
37
+
38
+
39
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
40
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
41
+ return None
42
+
43
+
44
+ class Http:
45
+ def __init__(
46
+ self,
47
+ *,
48
+ timeout: float = 15.0,
49
+ max_bytes: int = 20 * 1024 * 1024,
50
+ allow_http: bool = False,
51
+ verify_tls: bool = True,
52
+ ) -> None:
53
+ self.timeout = timeout
54
+ self.max_bytes = max_bytes
55
+ self.allow_http = allow_http
56
+ ctx = ssl.create_default_context()
57
+ if not verify_tls: # only used to *report* certificate problems on a pen-test target
58
+ ctx.check_hostname = False
59
+ ctx.verify_mode = ssl.CERT_NONE
60
+ self._opener = urllib.request.build_opener(_NoRedirect, urllib.request.HTTPSHandler(context=ctx))
61
+
62
+ def request(
63
+ self, method: str, url: str, *, headers: dict[str, str] | None = None, data: bytes | None = None
64
+ ) -> Response:
65
+ if not (url.startswith("https://") or (self.allow_http and url.startswith("http://"))):
66
+ raise ValueError(f"refusing to fetch {url.split(':', 1)[0]}:// URL")
67
+ hdrs = {"User-Agent": USER_AGENT, **(headers or {})}
68
+ req = urllib.request.Request(url, data=data, headers=hdrs, method=method) # noqa: S310 - scheme checked above
69
+ try:
70
+ resp = self._opener.open(req, timeout=self.timeout)
71
+ except urllib.error.HTTPError as exc: # non-2xx, including unfollowed redirects
72
+ resp = exc
73
+ with resp:
74
+ body = resp.read(self.max_bytes + 1) if method != "HEAD" else b""
75
+ raw_headers = list(resp.headers.items()) if resp.headers else []
76
+ return Response(
77
+ status=resp.status if hasattr(resp, "status") and resp.status else resp.code,
78
+ headers={k.lower(): v for k, v in raw_headers},
79
+ body=body[: self.max_bytes],
80
+ url=url,
81
+ header_list=raw_headers,
82
+ truncated=len(body) > self.max_bytes,
83
+ )
84
+
85
+ def get(self, url: str, **kw) -> Response:
86
+ return self.request("GET", url, **kw)
87
+
88
+ def post_json(self, url: str, payload: Any) -> Response:
89
+ return self.request(
90
+ "POST", url, headers={"Content-Type": "application/json"}, data=json.dumps(payload).encode("utf-8")
91
+ )