repolens-scan 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.
- repolens/__init__.py +1 -0
- repolens/__main__.py +10 -0
- repolens/analyze.py +38 -0
- repolens/cli.py +147 -0
- repolens/jsanalyzer.py +239 -0
- repolens/models.py +55 -0
- repolens/pyanalyzer.py +110 -0
- repolens/report.py +69 -0
- repolens/scanner.py +168 -0
- repolens/secrets.py +118 -0
- repolens_scan-0.1.0.dist-info/METADATA +100 -0
- repolens_scan-0.1.0.dist-info/RECORD +16 -0
- repolens_scan-0.1.0.dist-info/WHEEL +5 -0
- repolens_scan-0.1.0.dist-info/entry_points.txt +2 -0
- repolens_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
- repolens_scan-0.1.0.dist-info/top_level.txt +1 -0
repolens/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
repolens/__main__.py
ADDED
repolens/analyze.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from . import jsanalyzer, pyanalyzer
|
|
6
|
+
from .models import Finding, Limits
|
|
7
|
+
|
|
8
|
+
COMMENTED_LANGS = {
|
|
9
|
+
"Python", "JavaScript", "TypeScript", "Java", "Go", "Rust", "Ruby", "PHP", "C", "C++",
|
|
10
|
+
"C#", "Shell", "SQL", "HTML", "CSS", "SCSS", "YAML", "TOML",
|
|
11
|
+
}
|
|
12
|
+
MARKER = re.compile(r"(?:#|//|/\*|<!--|^\s*\*)[^\n]*?\b(TODO|FIXME|HACK|XXX)\b[:\s(-]*(.*)") # repolens: ignore
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run(files, limits: Limits) -> list[Finding]:
|
|
16
|
+
findings = []
|
|
17
|
+
for f in files:
|
|
18
|
+
if f.generated:
|
|
19
|
+
continue
|
|
20
|
+
if f.language == "Python":
|
|
21
|
+
findings.extend(pyanalyzer.check(f, limits))
|
|
22
|
+
elif f.language == "JavaScript":
|
|
23
|
+
findings.extend(jsanalyzer.check(f, limits))
|
|
24
|
+
if f.language in COMMENTED_LANGS:
|
|
25
|
+
findings.extend(_markers(f))
|
|
26
|
+
return findings
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _markers(f):
|
|
30
|
+
out = []
|
|
31
|
+
for number, line in enumerate(f.text.splitlines(), 1):
|
|
32
|
+
if "repolens: ignore" in line:
|
|
33
|
+
continue
|
|
34
|
+
m = MARKER.search(line)
|
|
35
|
+
if m:
|
|
36
|
+
note = m.group(2).strip().rstrip("*/-> ").strip()[:60]
|
|
37
|
+
out.append(Finding(f.path, number, "todo", f"{m.group(1)} {note}".strip()))
|
|
38
|
+
return out
|
repolens/cli.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import __version__, analyze, report, secrets
|
|
8
|
+
from .models import RULES, SEVERITY_ORDER, Limits
|
|
9
|
+
from .scanner import scan
|
|
10
|
+
|
|
11
|
+
COMMANDS = {"scan", "secrets", "report", "rules"}
|
|
12
|
+
SHOW_LIMIT = 20
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
16
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
17
|
+
common.add_argument("path", nargs="?", default=".", help="directory to look at (default: .)")
|
|
18
|
+
common.add_argument("-x", "--exclude", action="append", default=[], metavar="GLOB",
|
|
19
|
+
help="skip files or directories matching GLOB; may be given more than once")
|
|
20
|
+
common.add_argument("--max-function-lines", type=int, default=60, metavar="N")
|
|
21
|
+
common.add_argument("--max-complexity", type=int, default=15, metavar="N")
|
|
22
|
+
common.add_argument("--max-args", type=int, default=7, metavar="N")
|
|
23
|
+
|
|
24
|
+
parser = argparse.ArgumentParser(
|
|
25
|
+
prog="repolens",
|
|
26
|
+
description="Summarize a source tree: size, code problems and leaked secrets.",
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument("--version", action="version", version=f"repolens {__version__}")
|
|
29
|
+
sub = parser.add_subparsers(dest="command", metavar="command")
|
|
30
|
+
|
|
31
|
+
p = sub.add_parser("scan", parents=[common], help="print a summary and the findings (default)")
|
|
32
|
+
p.add_argument("--all", action="store_true", help=f"show every finding, not just the first {SHOW_LIMIT}")
|
|
33
|
+
p.add_argument("--fail-on", choices=list(SEVERITY_ORDER), metavar="LEVEL",
|
|
34
|
+
help="exit 1 if there is a finding at LEVEL (low, medium, high) or above")
|
|
35
|
+
|
|
36
|
+
sub.add_parser("secrets", parents=[common], help="only look for secrets; exit 1 if any are found")
|
|
37
|
+
|
|
38
|
+
p = sub.add_parser("report", parents=[common], help="write a Markdown report")
|
|
39
|
+
p.add_argument("-o", "--output", default="repolens-report.md", metavar="FILE")
|
|
40
|
+
|
|
41
|
+
sub.add_parser("rules", help="list what is checked")
|
|
42
|
+
return parser
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv=None) -> int:
|
|
46
|
+
argv = list(sys.argv[1:] if argv is None else argv)
|
|
47
|
+
if not argv or (argv[0] not in COMMANDS and argv[0] not in ("-h", "--help", "--version")):
|
|
48
|
+
argv.insert(0, "scan")
|
|
49
|
+
args = build_parser().parse_args(argv)
|
|
50
|
+
|
|
51
|
+
if args.command == "rules":
|
|
52
|
+
return _print_rules()
|
|
53
|
+
|
|
54
|
+
root = Path(args.path)
|
|
55
|
+
if not root.is_dir():
|
|
56
|
+
print(f"repolens: {args.path}: not a directory", file=sys.stderr)
|
|
57
|
+
return 2
|
|
58
|
+
|
|
59
|
+
limits = Limits(args.max_function_lines, args.max_complexity, args.max_args)
|
|
60
|
+
result = scan(root, args.exclude)
|
|
61
|
+
leaks = secrets.scan(result)
|
|
62
|
+
|
|
63
|
+
if args.command == "secrets":
|
|
64
|
+
_print_findings("Secrets", leaks, show_all=True)
|
|
65
|
+
if not leaks:
|
|
66
|
+
print("No secrets found.")
|
|
67
|
+
return 1 if leaks else 0
|
|
68
|
+
|
|
69
|
+
quality = analyze.run(result.files, limits)
|
|
70
|
+
|
|
71
|
+
if args.command == "report":
|
|
72
|
+
Path(args.output).write_text(report.render(result, quality, leaks), encoding="utf-8")
|
|
73
|
+
print(f"Wrote {args.output} ({len(quality)} findings, {len(leaks)} possible secrets)")
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
_print_scan(result, quality, leaks, show_all=args.all)
|
|
77
|
+
if args.fail_on:
|
|
78
|
+
bar = SEVERITY_ORDER[args.fail_on]
|
|
79
|
+
if any(SEVERITY_ORDER[x.severity] >= bar for x in quality + leaks):
|
|
80
|
+
return 1
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _print_scan(result, quality, leaks, show_all):
|
|
85
|
+
print(f"Scanning {result.root}\n")
|
|
86
|
+
_print_languages(result)
|
|
87
|
+
_print_project(result)
|
|
88
|
+
_print_findings("Secrets", leaks, show_all=True)
|
|
89
|
+
_print_findings("Findings", quality, show_all=show_all)
|
|
90
|
+
print(f"{len(quality)} findings, {len(leaks)} possible secrets. Run `repolens report` for a file.")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _print_languages(result):
|
|
94
|
+
rows = sorted(result.languages().items(), key=lambda kv: -kv[1][1])
|
|
95
|
+
if not rows:
|
|
96
|
+
print("No source files found.\n")
|
|
97
|
+
return
|
|
98
|
+
rows.append(("Total", (sum(v[0] for _, v in rows), sum(v[1] for _, v in rows))))
|
|
99
|
+
files = [f"{n} file" + ("" if n == 1 else "s") for _, (n, _) in rows]
|
|
100
|
+
lines = [f"{n:,} line" + ("" if n == 1 else "s") for _, (_, n) in rows]
|
|
101
|
+
width = max(len(name) for name, _ in rows)
|
|
102
|
+
fw, lw = max(map(len, files)), max(map(len, lines))
|
|
103
|
+
print("Languages")
|
|
104
|
+
for (name, _), fcol, lcol in zip(rows, files, lines):
|
|
105
|
+
if name == "Total":
|
|
106
|
+
print()
|
|
107
|
+
print(f" {name:<{width}} {fcol:>{fw}} {lcol:>{lw}}")
|
|
108
|
+
print()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _print_project(result):
|
|
112
|
+
lines = []
|
|
113
|
+
if result.manifests():
|
|
114
|
+
lines.append("dependency files: " + ", ".join(result.manifests()[:6]))
|
|
115
|
+
if result.missing():
|
|
116
|
+
lines.append("not found: " + ", ".join(result.missing()))
|
|
117
|
+
hidden = len(result.files) - len(result.counted)
|
|
118
|
+
if hidden:
|
|
119
|
+
lines.append(f"{hidden} generated/minified files not counted")
|
|
120
|
+
if lines:
|
|
121
|
+
print("Project")
|
|
122
|
+
for line in lines:
|
|
123
|
+
print(" " + line)
|
|
124
|
+
print()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _print_findings(title, findings, show_all):
|
|
128
|
+
if not findings:
|
|
129
|
+
return
|
|
130
|
+
ordered = report.sort_findings(findings)
|
|
131
|
+
shown = ordered if show_all else ordered[:SHOW_LIMIT]
|
|
132
|
+
print(f"{title} ({len(findings)})")
|
|
133
|
+
loc_w = min(max(len(x.location) for x in shown), 44)
|
|
134
|
+
rule_w = max(len(x.rule) for x in shown)
|
|
135
|
+
for x in shown:
|
|
136
|
+
loc = x.location if len(x.location) <= loc_w else "..." + x.location[-(loc_w - 3):]
|
|
137
|
+
print(f" {loc:<{loc_w}} {x.rule:<{rule_w}} {x.message}")
|
|
138
|
+
if len(shown) < len(ordered):
|
|
139
|
+
print(f" ... {len(ordered) - len(shown)} more (use --all)")
|
|
140
|
+
print()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _print_rules() -> int:
|
|
144
|
+
width = max(map(len, RULES))
|
|
145
|
+
for name, text in RULES.items():
|
|
146
|
+
print(f"{name:<{width}} {text}")
|
|
147
|
+
return 0
|
repolens/jsanalyzer.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Regex based checks for JavaScript.
|
|
2
|
+
|
|
3
|
+
There is no real parser here. Comments and strings are blanked out first so
|
|
4
|
+
braces inside them don't throw off the function-length counting, but regex
|
|
5
|
+
literals can still fool it. When braces don't balance, a function is skipped
|
|
6
|
+
rather than guessed at.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import bisect
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from .models import Finding, Limits
|
|
14
|
+
|
|
15
|
+
_NON_NEWLINE = re.compile(r"[^\n]")
|
|
16
|
+
_SPECIAL = re.compile(r"[/'\"`]")
|
|
17
|
+
_KEYWORDS = {"if", "for", "while", "switch", "catch", "function", "return", "with"}
|
|
18
|
+
|
|
19
|
+
_PATTERNS = [
|
|
20
|
+
(re.compile(r"\bfunction\s*\*?\s*([A-Za-z_$][\w$]*)\s*(?=\()"), "fn"),
|
|
21
|
+
(re.compile(r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?function\b"), "fn"),
|
|
22
|
+
(re.compile(r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?"
|
|
23
|
+
r"(?:\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>"), "arrow"),
|
|
24
|
+
(re.compile(r"\bfunction\s*\*?\s*(?=\()"), "fn"),
|
|
25
|
+
(re.compile(r"(?:\([^()]*\)|\b[A-Za-z_$][\w$]*)\s*=>"), "arrow"),
|
|
26
|
+
(re.compile(r"^[ \t]*(?:(?:static|async|get|set)\s+)*([A-Za-z_$][\w$]*)\s*\([^()]*\)\s*\{", re.M), "method"),
|
|
27
|
+
]
|
|
28
|
+
_DECISIONS = re.compile(r"\b(?:if|for|while|case|catch)\b|&&|\|\||(?<!\?)\?(?![?.])")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _mask(text):
|
|
32
|
+
return _NON_NEWLINE.sub(" ", text)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _mask_template(body):
|
|
36
|
+
"""Blank template literal text but keep the code inside ${ ... }."""
|
|
37
|
+
out = []
|
|
38
|
+
depth = 0
|
|
39
|
+
i = 0
|
|
40
|
+
while i < len(body):
|
|
41
|
+
ch = body[i]
|
|
42
|
+
if depth == 0:
|
|
43
|
+
if body.startswith("${", i):
|
|
44
|
+
out.append("${")
|
|
45
|
+
depth = 1
|
|
46
|
+
i += 2
|
|
47
|
+
continue
|
|
48
|
+
out.append(ch if ch == "\n" else " ")
|
|
49
|
+
else:
|
|
50
|
+
depth += (ch == "{") - (ch == "}")
|
|
51
|
+
out.append(ch)
|
|
52
|
+
i += 1
|
|
53
|
+
return "".join(out)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _string_end(src, start):
|
|
57
|
+
quote = src[start]
|
|
58
|
+
j = start + 1
|
|
59
|
+
while j < len(src):
|
|
60
|
+
ch = src[j]
|
|
61
|
+
if ch == "\\":
|
|
62
|
+
j += 2
|
|
63
|
+
continue
|
|
64
|
+
if ch == quote:
|
|
65
|
+
return j + 1, True
|
|
66
|
+
if ch == "\n" and quote != "`":
|
|
67
|
+
break
|
|
68
|
+
j += 1
|
|
69
|
+
return min(j, len(src)), False
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def strip_source(src):
|
|
73
|
+
"""Blank out comments and string contents, keeping offsets and newlines."""
|
|
74
|
+
out = []
|
|
75
|
+
i, n = 0, len(src)
|
|
76
|
+
while i < n:
|
|
77
|
+
m = _SPECIAL.search(src, i)
|
|
78
|
+
if not m:
|
|
79
|
+
out.append(src[i:])
|
|
80
|
+
break
|
|
81
|
+
out.append(src[i:m.start()])
|
|
82
|
+
i = m.start()
|
|
83
|
+
c = src[i]
|
|
84
|
+
two = src[i:i + 2]
|
|
85
|
+
if two == "//":
|
|
86
|
+
j = src.find("\n", i)
|
|
87
|
+
j = n if j == -1 else j
|
|
88
|
+
out.append(_mask(src[i:j]))
|
|
89
|
+
i = j
|
|
90
|
+
elif two == "/*":
|
|
91
|
+
j = src.find("*/", i + 2)
|
|
92
|
+
j = n if j == -1 else j + 2
|
|
93
|
+
out.append(_mask(src[i:j]))
|
|
94
|
+
i = j
|
|
95
|
+
elif c == "/":
|
|
96
|
+
out.append(c)
|
|
97
|
+
i += 1
|
|
98
|
+
else:
|
|
99
|
+
j, closed = _string_end(src, i)
|
|
100
|
+
if not closed and c != "`":
|
|
101
|
+
out.append(c) # e.g. the apostrophe in JSX text
|
|
102
|
+
i += 1
|
|
103
|
+
continue
|
|
104
|
+
seg = src[i:j]
|
|
105
|
+
if closed:
|
|
106
|
+
inner = _mask_template(seg[1:-1]) if c == "`" else _mask(seg[1:-1])
|
|
107
|
+
out.append(c + inner + c)
|
|
108
|
+
else:
|
|
109
|
+
out.append(_mask(seg))
|
|
110
|
+
i = j
|
|
111
|
+
return "".join(out)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _match(code, start, opener, closer):
|
|
115
|
+
depth = 0
|
|
116
|
+
for k in range(start, len(code)):
|
|
117
|
+
ch = code[k]
|
|
118
|
+
if ch == opener:
|
|
119
|
+
depth += 1
|
|
120
|
+
elif ch == closer:
|
|
121
|
+
depth -= 1
|
|
122
|
+
if depth == 0:
|
|
123
|
+
return k
|
|
124
|
+
return -1
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _skip_space(code, k):
|
|
128
|
+
while k < len(code) and code[k].isspace():
|
|
129
|
+
k += 1
|
|
130
|
+
return k
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _functions(code):
|
|
134
|
+
seen = set()
|
|
135
|
+
found = []
|
|
136
|
+
for rx, kind in _PATTERNS:
|
|
137
|
+
for m in rx.finditer(code):
|
|
138
|
+
name = m.group(1) if m.lastindex else "(anonymous)"
|
|
139
|
+
if kind == "method":
|
|
140
|
+
if name in _KEYWORDS:
|
|
141
|
+
continue
|
|
142
|
+
body = m.end() - 1
|
|
143
|
+
elif kind == "arrow":
|
|
144
|
+
body = _skip_space(code, m.end())
|
|
145
|
+
else:
|
|
146
|
+
paren = code.find("(", m.end())
|
|
147
|
+
if paren == -1:
|
|
148
|
+
continue
|
|
149
|
+
close = _match(code, paren, "(", ")")
|
|
150
|
+
if close == -1:
|
|
151
|
+
continue
|
|
152
|
+
body = _skip_space(code, close + 1)
|
|
153
|
+
if body >= len(code) or code[body] != "{" or body in seen:
|
|
154
|
+
continue
|
|
155
|
+
seen.add(body)
|
|
156
|
+
end = _match(code, body, "{", "}")
|
|
157
|
+
if end != -1:
|
|
158
|
+
found.append((name, m.start(), body, end))
|
|
159
|
+
return found
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def check(f, limits: Limits) -> list[Finding]:
|
|
163
|
+
skeleton = strip_source(f.text)
|
|
164
|
+
starts = [0] + [i + 1 for i, ch in enumerate(f.text) if ch == "\n"]
|
|
165
|
+
|
|
166
|
+
def line_of(offset):
|
|
167
|
+
return bisect.bisect_right(starts, offset)
|
|
168
|
+
|
|
169
|
+
out = []
|
|
170
|
+
for name, start, body, end in _functions(skeleton):
|
|
171
|
+
label = "anonymous function" if name == "(anonymous)" else f"{name}()"
|
|
172
|
+
length = line_of(end) - line_of(start) + 1
|
|
173
|
+
if length > limits.max_function_lines:
|
|
174
|
+
out.append(Finding(f.path, line_of(start), "long-function",
|
|
175
|
+
f"{label} is {length} lines (limit {limits.max_function_lines})"))
|
|
176
|
+
score = 1 + len(_DECISIONS.findall(skeleton, body, end))
|
|
177
|
+
if score > limits.max_complexity:
|
|
178
|
+
out.append(Finding(f.path, line_of(start), "complexity",
|
|
179
|
+
f"{label} has complexity about {score} (limit {limits.max_complexity})"))
|
|
180
|
+
|
|
181
|
+
out.extend(_unused_imports(f, skeleton, line_of))
|
|
182
|
+
|
|
183
|
+
for m in re.finditer(r"\beval\s*\(", skeleton):
|
|
184
|
+
out.append(Finding(f.path, line_of(m.start()), "eval-call", "call to eval()", "medium"))
|
|
185
|
+
for m in re.finditer(r"\bcatch\s*(?:\([^)]*\))?\s*\{\s*\}", f.text):
|
|
186
|
+
out.append(Finding(f.path, line_of(m.start()), "empty-catch", "empty catch block", "medium"))
|
|
187
|
+
|
|
188
|
+
out.extend(_counted(f.path, skeleton, line_of, r"\bvar\s+[A-Za-z_$\[{]", "use-var",
|
|
189
|
+
"var used {n} {times}", 1))
|
|
190
|
+
out.extend(_counted(f.path, skeleton, line_of, r"(?<![=!<>])(?:==|!=)(?!=)(?!\s*null\b)", "loose-equality",
|
|
191
|
+
"== or != used {n} {times}", 1))
|
|
192
|
+
out.extend(_counted(f.path, skeleton, line_of, r"\bconsole\.log\s*\(", "console-log",
|
|
193
|
+
"console.log called {n} {times}", 5))
|
|
194
|
+
return out
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _counted(path, code, line_of, pattern, rule, template, minimum):
|
|
198
|
+
hits = list(re.finditer(pattern, code))
|
|
199
|
+
if len(hits) < minimum:
|
|
200
|
+
return []
|
|
201
|
+
return [Finding(path, line_of(hits[0].start()), rule, template.format(n=len(hits), times="time" if len(hits) == 1 else "times"))]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
_IMPORT_FORMS = [
|
|
205
|
+
re.compile(r"\bimport\s+([A-Za-z_$][\w$]*)\s*(?:,\s*\{([^}]*)\})?\s*from\b"),
|
|
206
|
+
re.compile(r"\bimport\s*\{([^}]*)\}\s*from\b"),
|
|
207
|
+
re.compile(r"\bimport\s*\*\s*as\s+([A-Za-z_$][\w$]*)\s*from\b"),
|
|
208
|
+
re.compile(r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*require\s*\("),
|
|
209
|
+
re.compile(r"\b(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\s*\("),
|
|
210
|
+
]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _unused_imports(f, skeleton, line_of):
|
|
214
|
+
names = [] # (name, offset)
|
|
215
|
+
for rx in _IMPORT_FORMS:
|
|
216
|
+
for m in rx.finditer(skeleton):
|
|
217
|
+
for group in m.groups():
|
|
218
|
+
if not group:
|
|
219
|
+
continue
|
|
220
|
+
for part in group.split(","):
|
|
221
|
+
part = part.strip()
|
|
222
|
+
if not part:
|
|
223
|
+
continue
|
|
224
|
+
part = re.split(r"\s+as\s+|:", part)[-1]
|
|
225
|
+
part = part.split("=")[0].strip()
|
|
226
|
+
if re.fullmatch(r"[A-Za-z_$][\w$]*", part):
|
|
227
|
+
names.append((part, m.start()))
|
|
228
|
+
|
|
229
|
+
out = []
|
|
230
|
+
seen = set()
|
|
231
|
+
for name, offset in names:
|
|
232
|
+
if name in seen or (name == "React" and f.path.endswith(".jsx")):
|
|
233
|
+
continue
|
|
234
|
+
seen.add(name)
|
|
235
|
+
uses = len(re.findall(r"(?<![\w$.])" + re.escape(name) + r"(?![\w$])", skeleton))
|
|
236
|
+
uses += len(re.findall(r"</?" + re.escape(name) + r"(?![\w$])", f.text))
|
|
237
|
+
if uses <= 1:
|
|
238
|
+
out.append(Finding(f.path, line_of(offset), "unused-import", f"'{name}' imported but never used"))
|
|
239
|
+
return out
|
repolens/models.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
SEVERITY_ORDER = {"low": 0, "medium": 1, "high": 2}
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Finding:
|
|
10
|
+
path: str
|
|
11
|
+
line: int
|
|
12
|
+
rule: str
|
|
13
|
+
message: str
|
|
14
|
+
severity: str = "low"
|
|
15
|
+
kind: str = "quality" # "quality" or "secret"
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def location(self) -> str:
|
|
19
|
+
return f"{self.path}:{self.line}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Limits:
|
|
24
|
+
max_function_lines: int = 60
|
|
25
|
+
max_complexity: int = 15
|
|
26
|
+
max_args: int = 7
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# One line per rule, used by `repolens rules` and the report.
|
|
30
|
+
RULES = {
|
|
31
|
+
"long-function": "Function is longer than the limit. Long functions are hard to read and test.",
|
|
32
|
+
"complexity": "Too many branches in one function. Early returns or helpers usually help.",
|
|
33
|
+
"many-args": "Function takes many parameters. Group related ones or use keyword arguments.",
|
|
34
|
+
"unused-import": "Imported name is never used in the file.",
|
|
35
|
+
"bare-except": "A bare 'except:' also swallows KeyboardInterrupt and SystemExit.",
|
|
36
|
+
"mutable-default": "A mutable default argument is shared between calls.",
|
|
37
|
+
"eval-call": "eval/exec runs arbitrary code. Avoid it for anything not fully trusted.",
|
|
38
|
+
"empty-catch": "An empty catch block hides errors.",
|
|
39
|
+
"use-var": "'var' is function scoped; let or const are safer.",
|
|
40
|
+
"loose-equality": "'==' and '!=' coerce types; '===' and '!==' do not.",
|
|
41
|
+
"console-log": "Many console.log calls, probably leftover debugging.",
|
|
42
|
+
"todo": "A TODO/FIXME/HACK/XXX marker in a comment.",
|
|
43
|
+
"syntax-error": "The file could not be parsed.",
|
|
44
|
+
"env-file": "A .env file that .gitignore does not cover.",
|
|
45
|
+
"private-key": "A PEM private key block.",
|
|
46
|
+
"aws-access-key": "An AWS access key ID.",
|
|
47
|
+
"github-token": "A GitHub personal access or app token.",
|
|
48
|
+
"slack-token": "A Slack API token.",
|
|
49
|
+
"google-api-key": "A Google API key.",
|
|
50
|
+
"stripe-key": "A live Stripe key.",
|
|
51
|
+
"api-key": "A long 'sk-' style secret key.",
|
|
52
|
+
"jwt": "A JSON web token.",
|
|
53
|
+
"db-url-credentials": "A database URL with a password in it.",
|
|
54
|
+
"hardcoded-secret": "A password, token or key assigned a literal value.",
|
|
55
|
+
}
|
repolens/pyanalyzer.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from .models import Finding, Limits
|
|
7
|
+
|
|
8
|
+
_WORDS = re.compile(r"[A-Za-z_]\w*")
|
|
9
|
+
_BRANCHES = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.ExceptHandler, ast.IfExp)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def check(f, limits: Limits) -> list[Finding]:
|
|
13
|
+
try:
|
|
14
|
+
tree = ast.parse(f.text, filename=f.path)
|
|
15
|
+
except SyntaxError as exc:
|
|
16
|
+
return [Finding(f.path, exc.lineno or 1, "syntax-error", f"cannot parse: {exc.msg}", "medium")]
|
|
17
|
+
except (ValueError, RecursionError):
|
|
18
|
+
return []
|
|
19
|
+
|
|
20
|
+
out = []
|
|
21
|
+
for node in ast.walk(tree):
|
|
22
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
23
|
+
out.extend(_check_function(f.path, node, limits))
|
|
24
|
+
elif isinstance(node, ast.ExceptHandler) and node.type is None:
|
|
25
|
+
out.append(Finding(f.path, node.lineno, "bare-except", "bare 'except:' clause", "medium"))
|
|
26
|
+
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in ("eval", "exec"):
|
|
27
|
+
out.append(Finding(f.path, node.lineno, "eval-call", f"call to {node.func.id}()", "medium"))
|
|
28
|
+
if not f.path.endswith("__init__.py"):
|
|
29
|
+
out.extend(_unused_imports(f.path, tree))
|
|
30
|
+
return out
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _check_function(path, node, limits):
|
|
34
|
+
found = []
|
|
35
|
+
length = node.end_lineno - node.lineno + 1
|
|
36
|
+
if length > limits.max_function_lines:
|
|
37
|
+
found.append(Finding(path, node.lineno, "long-function",
|
|
38
|
+
f"{node.name}() is {length} lines (limit {limits.max_function_lines})"))
|
|
39
|
+
|
|
40
|
+
score = _complexity(node)
|
|
41
|
+
if score > limits.max_complexity:
|
|
42
|
+
found.append(Finding(path, node.lineno, "complexity",
|
|
43
|
+
f"{node.name}() has complexity {score} (limit {limits.max_complexity})"))
|
|
44
|
+
|
|
45
|
+
a = node.args
|
|
46
|
+
names = [x.arg for x in a.posonlyargs + a.args + a.kwonlyargs]
|
|
47
|
+
if names and names[0] in ("self", "cls"):
|
|
48
|
+
names = names[1:]
|
|
49
|
+
if len(names) > limits.max_args:
|
|
50
|
+
found.append(Finding(path, node.lineno, "many-args",
|
|
51
|
+
f"{node.name}() takes {len(names)} parameters (limit {limits.max_args})"))
|
|
52
|
+
|
|
53
|
+
defaults = a.defaults + [d for d in a.kw_defaults if d is not None]
|
|
54
|
+
for d in defaults:
|
|
55
|
+
mutable_call = isinstance(d, ast.Call) and isinstance(d.func, ast.Name) and d.func.id in ("list", "dict", "set")
|
|
56
|
+
if isinstance(d, (ast.List, ast.Dict, ast.Set)) or mutable_call:
|
|
57
|
+
found.append(Finding(path, d.lineno, "mutable-default",
|
|
58
|
+
f"{node.name}() uses a mutable default argument", "medium"))
|
|
59
|
+
return found
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _complexity(fn) -> int:
|
|
63
|
+
total = 1
|
|
64
|
+
stack = list(ast.iter_child_nodes(fn))
|
|
65
|
+
while stack:
|
|
66
|
+
node = stack.pop()
|
|
67
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
|
|
68
|
+
continue # nested definitions are scored on their own
|
|
69
|
+
if isinstance(node, _BRANCHES):
|
|
70
|
+
total += 1
|
|
71
|
+
elif isinstance(node, ast.BoolOp):
|
|
72
|
+
total += len(node.values) - 1
|
|
73
|
+
elif isinstance(node, ast.comprehension):
|
|
74
|
+
total += 1 + len(node.ifs)
|
|
75
|
+
stack.extend(ast.iter_child_nodes(node))
|
|
76
|
+
return total
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _imported_names(tree):
|
|
80
|
+
imported = {}
|
|
81
|
+
for node in ast.walk(tree):
|
|
82
|
+
if isinstance(node, ast.Import):
|
|
83
|
+
for alias in node.names:
|
|
84
|
+
imported[(alias.asname or alias.name).split(".")[0]] = node.lineno
|
|
85
|
+
elif isinstance(node, ast.ImportFrom) and node.module != "__future__":
|
|
86
|
+
for alias in node.names:
|
|
87
|
+
if alias.name != "*":
|
|
88
|
+
imported[alias.asname or alias.name] = node.lineno
|
|
89
|
+
return imported
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _used_names(tree):
|
|
93
|
+
used = set()
|
|
94
|
+
for node in ast.walk(tree):
|
|
95
|
+
if isinstance(node, ast.Name):
|
|
96
|
+
used.add(node.id)
|
|
97
|
+
elif isinstance(node, ast.Constant) and isinstance(node.value, str) and len(node.value) < 80:
|
|
98
|
+
# quoted annotations and __all__ entries
|
|
99
|
+
used.update(_WORDS.findall(node.value))
|
|
100
|
+
return used
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _unused_imports(path, tree):
|
|
104
|
+
used = _used_names(tree)
|
|
105
|
+
imported = _imported_names(tree)
|
|
106
|
+
return [
|
|
107
|
+
Finding(path, line, "unused-import", f"'{name}' imported but never used")
|
|
108
|
+
for name, line in sorted(imported.items(), key=lambda kv: kv[1])
|
|
109
|
+
if name not in used
|
|
110
|
+
]
|
repolens/report.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
|
|
6
|
+
from .models import RULES, SEVERITY_ORDER
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def sort_findings(findings):
|
|
10
|
+
return sorted(findings, key=lambda x: (-SEVERITY_ORDER[x.severity], x.path, x.line))
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def render(result, quality, leaks) -> str:
|
|
14
|
+
langs = sorted(result.languages().items(), key=lambda kv: -kv[1][1])
|
|
15
|
+
total_files = sum(v[0] for v in result.languages().values())
|
|
16
|
+
total_lines = sum(v[1] for v in result.languages().values())
|
|
17
|
+
|
|
18
|
+
out = [
|
|
19
|
+
f"# {result.root.name}",
|
|
20
|
+
"",
|
|
21
|
+
f"RepoLens report, {datetime.now():%Y-%m-%d %H:%M}. Scanned `{result.root}`.",
|
|
22
|
+
"",
|
|
23
|
+
"## Size",
|
|
24
|
+
"",
|
|
25
|
+
f"{total_files:,} files, {total_lines:,} non-blank lines.",
|
|
26
|
+
"",
|
|
27
|
+
"| Language | Files | Lines |",
|
|
28
|
+
"| --- | ---: | ---: |",
|
|
29
|
+
]
|
|
30
|
+
out += [f"| {name} | {n:,} | {lines:,} |" for name, (n, lines) in langs]
|
|
31
|
+
|
|
32
|
+
notes = _project_notes(result)
|
|
33
|
+
out += ["", "## Project", ""] + [f"- {n}" for n in notes]
|
|
34
|
+
|
|
35
|
+
out += ["", f"## Secrets ({len(leaks)})", ""]
|
|
36
|
+
out += _table(sort_findings(leaks)) if leaks else ["Nothing that looks like a secret was found."]
|
|
37
|
+
|
|
38
|
+
out += ["", f"## Code findings ({len(quality)})", ""]
|
|
39
|
+
out += _table(sort_findings(quality)) if quality else ["No findings."]
|
|
40
|
+
|
|
41
|
+
used = Counter(x.rule for x in quality + leaks)
|
|
42
|
+
if used:
|
|
43
|
+
out += ["", "## Rules that fired", ""]
|
|
44
|
+
out += [f"- `{rule}` ({count}): {RULES.get(rule, '')}" for rule, count in used.most_common()]
|
|
45
|
+
|
|
46
|
+
out += ["", "Secret values are masked in this report.", ""]
|
|
47
|
+
return "\n".join(out)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _table(findings):
|
|
51
|
+
rows = ["| Where | Rule | Severity | Detail |", "| --- | --- | --- | --- |"]
|
|
52
|
+
for x in findings:
|
|
53
|
+
detail = x.message.replace("|", "\\|")
|
|
54
|
+
rows.append(f"| `{x.location}` | {x.rule} | {x.severity} | {detail} |")
|
|
55
|
+
return rows
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _project_notes(result):
|
|
59
|
+
notes = []
|
|
60
|
+
if result.manifests():
|
|
61
|
+
notes.append("Dependency files: " + ", ".join(f"`{m}`" for m in result.manifests()))
|
|
62
|
+
if result.missing():
|
|
63
|
+
notes.append("Not found: " + ", ".join(result.missing()))
|
|
64
|
+
ignored = len(result.files) - len(result.counted)
|
|
65
|
+
if ignored:
|
|
66
|
+
notes.append(f"{ignored} generated or minified files were left out of the counts.")
|
|
67
|
+
if result.skipped:
|
|
68
|
+
notes.append(f"{result.skipped} files were skipped (too large or unreadable).")
|
|
69
|
+
return notes
|
repolens/scanner.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import fnmatch
|
|
4
|
+
import os
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
LANGUAGES = {
|
|
10
|
+
".py": "Python", ".js": "JavaScript", ".jsx": "JavaScript", ".mjs": "JavaScript",
|
|
11
|
+
".cjs": "JavaScript", ".ts": "TypeScript", ".tsx": "TypeScript", ".java": "Java",
|
|
12
|
+
".go": "Go", ".rs": "Rust", ".rb": "Ruby", ".php": "PHP", ".c": "C", ".h": "C",
|
|
13
|
+
".cpp": "C++", ".cc": "C++", ".hpp": "C++", ".cs": "C#", ".html": "HTML",
|
|
14
|
+
".css": "CSS", ".scss": "SCSS", ".json": "JSON", ".yml": "YAML", ".yaml": "YAML",
|
|
15
|
+
".toml": "TOML", ".md": "Markdown", ".sh": "Shell", ".bash": "Shell", ".sql": "SQL",
|
|
16
|
+
}
|
|
17
|
+
NAMED_FILES = {"Dockerfile": "Docker", "Makefile": "Make"}
|
|
18
|
+
|
|
19
|
+
SKIP_DIRS = {
|
|
20
|
+
".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build", ".next",
|
|
21
|
+
".idea", ".vscode", "target", "vendor", ".tox", ".mypy_cache", ".pytest_cache",
|
|
22
|
+
"coverage", ".gradle",
|
|
23
|
+
}
|
|
24
|
+
SKIP_FILES = {"repolens-report.md"}
|
|
25
|
+
BINARY_EXT = {
|
|
26
|
+
".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg", ".pdf", ".zip", ".gz", ".tar",
|
|
27
|
+
".woff", ".woff2", ".ttf", ".eot", ".mp3", ".mp4", ".pyc", ".so", ".dll", ".exe",
|
|
28
|
+
".class", ".jar",
|
|
29
|
+
}
|
|
30
|
+
LOCKFILES = {
|
|
31
|
+
"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "Pipfile.lock",
|
|
32
|
+
"composer.lock", "Cargo.lock", "go.sum",
|
|
33
|
+
}
|
|
34
|
+
MANIFESTS = {
|
|
35
|
+
"package.json", "requirements.txt", "pyproject.toml", "setup.py", "Pipfile",
|
|
36
|
+
"pom.xml", "build.gradle", "go.mod", "Cargo.toml", "Gemfile", "composer.json",
|
|
37
|
+
}
|
|
38
|
+
TEST_DIRS = {"test", "tests", "__tests__", "spec", "specs"}
|
|
39
|
+
MAX_BYTES = 1_000_000
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class FileInfo:
|
|
44
|
+
path: str # relative to the scan root, always with forward slashes
|
|
45
|
+
language: str
|
|
46
|
+
lines: int
|
|
47
|
+
blank: int
|
|
48
|
+
text: str
|
|
49
|
+
generated: bool = False
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def loc(self) -> int:
|
|
53
|
+
return self.lines - self.blank
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass
|
|
57
|
+
class ScanResult:
|
|
58
|
+
root: Path
|
|
59
|
+
files: list[FileInfo] = field(default_factory=list)
|
|
60
|
+
skipped: int = 0
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def counted(self) -> list[FileInfo]:
|
|
64
|
+
return [f for f in self.files if not f.generated]
|
|
65
|
+
|
|
66
|
+
def languages(self) -> dict[str, tuple[int, int]]:
|
|
67
|
+
totals = defaultdict(lambda: [0, 0])
|
|
68
|
+
for f in self.counted:
|
|
69
|
+
totals[f.language][0] += 1
|
|
70
|
+
totals[f.language][1] += f.loc
|
|
71
|
+
return {k: (v[0], v[1]) for k, v in totals.items()}
|
|
72
|
+
|
|
73
|
+
def manifests(self) -> list[str]:
|
|
74
|
+
return sorted(f.path for f in self.files if f.path.rsplit("/", 1)[-1] in MANIFESTS)
|
|
75
|
+
|
|
76
|
+
def missing(self) -> list[str]:
|
|
77
|
+
top = [f.path.lower() for f in self.files if "/" not in f.path]
|
|
78
|
+
out = []
|
|
79
|
+
if not any(p.startswith("readme") for p in top):
|
|
80
|
+
out.append("README")
|
|
81
|
+
if not any(p.startswith(("license", "licence", "copying")) for p in top):
|
|
82
|
+
out.append("LICENSE")
|
|
83
|
+
if ".gitignore" not in top:
|
|
84
|
+
out.append(".gitignore")
|
|
85
|
+
if not any(_is_test(f.path) for f in self.files):
|
|
86
|
+
out.append("tests")
|
|
87
|
+
return out
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _is_test(path: str) -> bool:
|
|
91
|
+
parts = path.lower().split("/")
|
|
92
|
+
name = parts[-1]
|
|
93
|
+
if any(p in TEST_DIRS for p in parts[:-1]):
|
|
94
|
+
return True
|
|
95
|
+
return name.startswith("test_") or name.endswith(("_test.py", ".test.js", ".spec.js", ".test.ts", ".spec.ts"))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _load_ignore(root: Path) -> list[str]:
|
|
99
|
+
gitignore = root / ".gitignore"
|
|
100
|
+
if not gitignore.is_file():
|
|
101
|
+
return []
|
|
102
|
+
patterns = []
|
|
103
|
+
for raw in gitignore.read_text(errors="ignore").splitlines():
|
|
104
|
+
line = raw.strip()
|
|
105
|
+
# negations ("!keep.me") are not supported
|
|
106
|
+
if line and not line.startswith(("#", "!")):
|
|
107
|
+
patterns.append(line)
|
|
108
|
+
return patterns
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _ignored(rel: str, name: str, is_dir: bool, patterns: list[str]) -> bool:
|
|
112
|
+
for pat in patterns:
|
|
113
|
+
if pat.endswith("/"):
|
|
114
|
+
if not is_dir:
|
|
115
|
+
continue
|
|
116
|
+
pat = pat[:-1]
|
|
117
|
+
if pat.startswith("/") or "/" in pat:
|
|
118
|
+
if fnmatch.fnmatch(rel, pat.lstrip("/")):
|
|
119
|
+
return True
|
|
120
|
+
elif fnmatch.fnmatch(name, pat):
|
|
121
|
+
return True
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def scan(root, exclude=()) -> ScanResult:
|
|
126
|
+
root = Path(root).resolve()
|
|
127
|
+
patterns = _load_ignore(root) + list(exclude)
|
|
128
|
+
result = ScanResult(root=root)
|
|
129
|
+
|
|
130
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
131
|
+
rel_dir = Path(dirpath).relative_to(root)
|
|
132
|
+
dirnames[:] = sorted(
|
|
133
|
+
d for d in dirnames
|
|
134
|
+
if d not in SKIP_DIRS
|
|
135
|
+
and not d.endswith(".egg-info")
|
|
136
|
+
and not _ignored((rel_dir / d).as_posix(), d, True, patterns)
|
|
137
|
+
)
|
|
138
|
+
for name in sorted(filenames):
|
|
139
|
+
rel = (rel_dir / name).as_posix()
|
|
140
|
+
ext = os.path.splitext(name)[1].lower()
|
|
141
|
+
if name in SKIP_FILES or ext in BINARY_EXT or _ignored(rel, name, False, patterns):
|
|
142
|
+
continue
|
|
143
|
+
info = _read(Path(dirpath) / name, rel, name, ext, result)
|
|
144
|
+
if info:
|
|
145
|
+
result.files.append(info)
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _read(full: Path, rel: str, name: str, ext: str, result: ScanResult):
|
|
150
|
+
try:
|
|
151
|
+
if full.stat().st_size > MAX_BYTES:
|
|
152
|
+
result.skipped += 1
|
|
153
|
+
return None
|
|
154
|
+
data = full.read_bytes()
|
|
155
|
+
except OSError:
|
|
156
|
+
result.skipped += 1
|
|
157
|
+
return None
|
|
158
|
+
if b"\x00" in data[:8192]:
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
text = data.decode("utf-8", errors="replace")
|
|
162
|
+
lines = text.splitlines()
|
|
163
|
+
blank = sum(1 for line in lines if not line.strip())
|
|
164
|
+
language = NAMED_FILES.get(name) or LANGUAGES.get(ext, "Other")
|
|
165
|
+
minified = name.endswith((".min.js", ".min.css", ".map")) or (
|
|
166
|
+
len(lines) > 0 and len(text) / len(lines) > 300
|
|
167
|
+
)
|
|
168
|
+
return FileInfo(rel, language, len(lines), blank, text, generated=name in LOCKFILES or minified)
|
repolens/secrets.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from .models import Finding
|
|
6
|
+
|
|
7
|
+
# (rule, pattern, severity, label)
|
|
8
|
+
SPECIFIC = [
|
|
9
|
+
("private-key", re.compile(r"-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----"), "high", "private key block"),
|
|
10
|
+
("aws-access-key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), "high", "AWS access key"),
|
|
11
|
+
("github-token", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{50,})\b"), "high", "GitHub token"),
|
|
12
|
+
("slack-token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}"), "high", "Slack token"),
|
|
13
|
+
("google-api-key", re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b"), "high", "Google API key"),
|
|
14
|
+
("stripe-key", re.compile(r"\b[sr]k_live_[0-9A-Za-z]{20,}\b"), "high", "Stripe live key"),
|
|
15
|
+
("api-key", re.compile(r"\bsk-[A-Za-z0-9_\-]{32,}"), "high", "secret key"),
|
|
16
|
+
("jwt", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}"), "medium", "JSON web token"),
|
|
17
|
+
("db-url-credentials",
|
|
18
|
+
re.compile(r"\b(?:mongodb(?:\+srv)?|postgres(?:ql)?|mysql|redis|amqp)://[^\s:/@'\"]+:([^\s@'\"]{3,})@"),
|
|
19
|
+
"high", "database URL with password"),
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
NAME = r"[\w.-]*(?:password|passwd|pwd|secret|api[_-]?key|apikey|auth[_-]?token|access[_-]?token|token|private[_-]?key)[\w.-]*"
|
|
23
|
+
ASSIGNMENT = re.compile(r"(?<![\w\\.-])(" + NAME + r")[\"']?\s*[:=]\s*[\"']([^\"'\s]{8,})[\"']", re.I)
|
|
24
|
+
ENV_LINE = re.compile(r"^\s*(?:export\s+)?(" + NAME.replace("[\\w.-]*", "[A-Z0-9_]*") + r")\s*=\s*(\S{8,})\s*$", re.I)
|
|
25
|
+
|
|
26
|
+
FAKE_WORDS = (
|
|
27
|
+
"example", "changeme", "change_me", "change-me", "your", "xxxx", "placeholder",
|
|
28
|
+
"dummy", "sample", "fake", "redacted", "<", "{{", "${", "process.env", "os.environ", "getenv",
|
|
29
|
+
)
|
|
30
|
+
FAKE_EXACT = {"password", "pass", "secret", "root", "admin", "postgres", "user"}
|
|
31
|
+
PLAIN_WORD = re.compile(r"[A-Za-z]+(?:[_.\-][A-Za-z]+)*")
|
|
32
|
+
ENV_FILE_SUFFIXES = (".example", ".sample", ".template", ".dist", ".defaults")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def is_env_file(path: str) -> bool:
|
|
36
|
+
name = path.rsplit("/", 1)[-1]
|
|
37
|
+
return (name == ".env" or name.startswith(".env.")) and not name.endswith(ENV_FILE_SUFFIXES)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _fake(value: str) -> bool:
|
|
41
|
+
v = value.lower()
|
|
42
|
+
return v in FAKE_EXACT or any(w in v for w in FAKE_WORDS) or len(set(v)) <= 2
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _mask(value: str) -> str:
|
|
46
|
+
return value[:4] + "*" * 8
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def scan(result) -> list[Finding]:
|
|
50
|
+
findings = []
|
|
51
|
+
for f in result.counted:
|
|
52
|
+
env = is_env_file(f.path)
|
|
53
|
+
if env:
|
|
54
|
+
findings.append(Finding(f.path, 1, "env-file",
|
|
55
|
+
"environment file is not covered by .gitignore", "medium", "secret"))
|
|
56
|
+
for number, line in enumerate(f.text.splitlines(), 1):
|
|
57
|
+
if len(line) > 2000 or "repolens: ignore" in line:
|
|
58
|
+
continue
|
|
59
|
+
findings.extend(_scan_line(f.path, number, line, env))
|
|
60
|
+
return _collapse(findings)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _collapse(findings, keep=3):
|
|
64
|
+
"""A seed file with eleven identical demo passwords should read as one problem."""
|
|
65
|
+
groups = {}
|
|
66
|
+
for x in findings:
|
|
67
|
+
groups.setdefault((x.path, x.rule), []).append(x)
|
|
68
|
+
out = []
|
|
69
|
+
for items in groups.values():
|
|
70
|
+
if items[0].rule != "hardcoded-secret" or len(items) <= keep:
|
|
71
|
+
out.extend(items)
|
|
72
|
+
continue
|
|
73
|
+
first = items[0]
|
|
74
|
+
extra = len(items) - 1
|
|
75
|
+
out.append(Finding(first.path, first.line, first.rule,
|
|
76
|
+
f"{first.message} (and {extra} more in this file)", first.severity, first.kind))
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _scan_line(path, number, line, env):
|
|
81
|
+
hits = _scan_known(path, number, line)
|
|
82
|
+
if hits:
|
|
83
|
+
return hits
|
|
84
|
+
if env:
|
|
85
|
+
return _scan_env_line(path, number, line)
|
|
86
|
+
return _scan_assignments(path, number, line)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _scan_known(path, number, line):
|
|
90
|
+
hits = []
|
|
91
|
+
for rule, rx, severity, label in SPECIFIC:
|
|
92
|
+
for m in rx.finditer(line):
|
|
93
|
+
secret = m.group(1) if rx.groups else m.group(0)
|
|
94
|
+
if rule != "private-key" and _fake(secret):
|
|
95
|
+
continue
|
|
96
|
+
text = label if rule == "private-key" else f"{label}: {_mask(m.group(0))}"
|
|
97
|
+
hits.append(Finding(path, number, rule, text, severity, "secret"))
|
|
98
|
+
return hits
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _scan_env_line(path, number, line):
|
|
102
|
+
m = ENV_LINE.match(line)
|
|
103
|
+
if not m:
|
|
104
|
+
return []
|
|
105
|
+
value = m.group(2).strip("'\"")
|
|
106
|
+
if not value or value.startswith("$") or _fake(value):
|
|
107
|
+
return []
|
|
108
|
+
return [Finding(path, number, "hardcoded-secret", f"value for {m.group(1)}: {_mask(value)}", "medium", "secret")]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _scan_assignments(path, number, line):
|
|
112
|
+
hits = []
|
|
113
|
+
for m in ASSIGNMENT.finditer(line):
|
|
114
|
+
name, value = m.group(1), m.group(2)
|
|
115
|
+
if _fake(value) or PLAIN_WORD.fullmatch(value):
|
|
116
|
+
continue
|
|
117
|
+
hits.append(Finding(path, number, "hardcoded-secret", f"value for {name}: {_mask(value)}", "medium", "secret"))
|
|
118
|
+
return hits
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: repolens-scan
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Summarize a source tree: size, code problems and leaked secrets.
|
|
5
|
+
Author: Prabhat Yadav
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Prabhatyadav92/repolens
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# repolens
|
|
18
|
+
|
|
19
|
+
A small command line tool that looks through a project folder and tells you how big it is, which functions have grown out of hand, and whether anyone committed a password.
|
|
20
|
+
|
|
21
|
+
It only uses the Python standard library, works offline, and reads files without running or importing any of your code.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
pip install repolens-scan
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Or from a clone:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
git clone https://github.com/Prabhatyadav92/repolens
|
|
33
|
+
cd repolens
|
|
34
|
+
pip install .
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Python 3.9 or newer.
|
|
38
|
+
|
|
39
|
+
## Use
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
repolens . # summary and findings
|
|
43
|
+
repolens secrets . # only secrets, exit code 1 if any are found
|
|
44
|
+
repolens report . # write repolens-report.md
|
|
45
|
+
repolens rules # list every check
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Example:
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
$ repolens src/
|
|
52
|
+
Scanning /home/me/newspulse/src
|
|
53
|
+
|
|
54
|
+
Languages
|
|
55
|
+
JavaScript 41 files 7,204 lines
|
|
56
|
+
Python 22 files 3,118 lines
|
|
57
|
+
|
|
58
|
+
Total 63 files 10,322 lines
|
|
59
|
+
|
|
60
|
+
Secrets (1)
|
|
61
|
+
config.js:7 aws-access-key AWS access key: AKIA********
|
|
62
|
+
|
|
63
|
+
Findings (9)
|
|
64
|
+
server.js:10 long-function anonymous function is 112 lines (limit 60)
|
|
65
|
+
...
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Useful options:
|
|
69
|
+
|
|
70
|
+
| Option | What it does |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `-x GLOB`, `--exclude GLOB` | Skip matching files or folders. Repeatable. |
|
|
73
|
+
| `--max-function-lines N` | Length before `long-function` fires (default 60). |
|
|
74
|
+
| `--max-complexity N` | Branch count before `complexity` fires (default 15). |
|
|
75
|
+
| `--fail-on LEVEL` | Exit 1 if something at `low`, `medium` or `high` is found. Handy in CI. |
|
|
76
|
+
| `--all` | Print every finding instead of the first 20. |
|
|
77
|
+
|
|
78
|
+
Files matched by `.gitignore` are skipped, along with `node_modules`, virtualenvs and build folders. To silence a single line, put `repolens: ignore` in a comment on it.
|
|
79
|
+
|
|
80
|
+
## What it checks
|
|
81
|
+
|
|
82
|
+
- **Python** (via `ast`): long or complex functions, too many parameters, mutable default arguments, bare `except`, `eval`/`exec`, unused imports.
|
|
83
|
+
- **JavaScript** (regex, no parser): long or complex functions, unused imports and requires, `var`, loose equality, empty `catch`, `eval`, leftover `console.log`.
|
|
84
|
+
- **Any text file**: TODO / FIXME / HACK / XXX in comments.
|
|
85
|
+
- **Secrets**: private keys, AWS, GitHub, Slack, Google and Stripe keys, JWTs, database URLs with passwords, `password = "..."` style assignments, and `.env` files. Secret values are always masked in output.
|
|
86
|
+
|
|
87
|
+
## Limits
|
|
88
|
+
|
|
89
|
+
The JavaScript checks are approximate. Regex literals and unusual formatting can confuse the function-length counting, and TypeScript is counted but not analyzed. `.gitignore` negation rules (`!pattern`) are ignored. The secret scanner will miss secrets it has no pattern for and will sometimes flag test fixtures; use `repolens: ignore` for those. It is not a replacement for a tool like gitleaks if you need serious coverage.
|
|
90
|
+
|
|
91
|
+
## Development
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
pip install pytest
|
|
95
|
+
pytest
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
repolens/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
2
|
+
repolens/__main__.py,sha256=BXsXUgNoNPnkbW9UaOkN5znUJHrS6T1afisaStFO_OM,141
|
|
3
|
+
repolens/analyze.py,sha256=7KfecDyHpEsUpO0Yf9phXRKMyAn3UZIwWFnX7GRu8M4,1206
|
|
4
|
+
repolens/cli.py,sha256=rr3A5HnaP8s3qtqS9sEZc4f8sdkxyb6Sufrr3fADpgw,5638
|
|
5
|
+
repolens/jsanalyzer.py,sha256=ryGlnIiBkUdxxkT20236WHj5kuAASbRhYgtzjFca55E,8322
|
|
6
|
+
repolens/models.py,sha256=iiQiTq8sRcX_oljpJMuq9vMO2QFjNZD8OXg6DEv89Ro,2160
|
|
7
|
+
repolens/pyanalyzer.py,sha256=G2IzCWbKykeOkUDH0Tf5tR_d7Uo-kuRU55hanJhT9nk,4328
|
|
8
|
+
repolens/report.py,sha256=qdmc6wZeXWv6qQl1tdjCWg2S2b6Iet4AP0qSl6a7jp4,2441
|
|
9
|
+
repolens/scanner.py,sha256=jcDrYWdL-qNih3QOTK6tXR9Ek1tFKPUSLVZMLj9Yr1w,5817
|
|
10
|
+
repolens/secrets.py,sha256=QPG3hgpTQyHpjazBaqoIhEEOyhJtb5FpVx0cn4xZBYU,4812
|
|
11
|
+
repolens_scan-0.1.0.dist-info/licenses/LICENSE,sha256=w02vDRpnA_fwOTA8Z6ISKhcpF1o94Vmdr50uAulmW5o,1070
|
|
12
|
+
repolens_scan-0.1.0.dist-info/METADATA,sha256=F--k7QJlSpbQm8dV3PXD7UYEnnIspp7QZZ17FBJDagA,3366
|
|
13
|
+
repolens_scan-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
14
|
+
repolens_scan-0.1.0.dist-info/entry_points.txt,sha256=5LWia6GrZ82g7yWHnI25F7by5KO9hZFnonxeCn0tpik,47
|
|
15
|
+
repolens_scan-0.1.0.dist-info/top_level.txt,sha256=7EK5ft9AlN9kOeOjzFv_PgnLxREn2EGvgu5jZdcL9CA,9
|
|
16
|
+
repolens_scan-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Prabhat Yadav
|
|
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 @@
|
|
|
1
|
+
repolens
|