Skip to content

Commit c284ed3

Browse files
committed
test: block hardcoded api keys
1 parent 4552e5e commit c284ed3

1 file changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""Guard against committing real OilPriceAPI tokens in examples/tests."""
2+
3+
from __future__ import annotations
4+
5+
import hashlib
6+
import re
7+
from pathlib import Path
8+
9+
10+
ROOT = Path(__file__).resolve().parents[1]
11+
SCAN_PATHS = [
12+
ROOT / "README.md",
13+
ROOT / "CHANGELOG.md",
14+
ROOT / "docs",
15+
ROOT / "examples",
16+
ROOT / "monitoring",
17+
ROOT / "oilpriceapi",
18+
ROOT / "scripts",
19+
ROOT / "tests",
20+
]
21+
TEXT_SUFFIXES = {
22+
".cfg",
23+
".ini",
24+
".json",
25+
".md",
26+
".py",
27+
".rst",
28+
".toml",
29+
".txt",
30+
".yaml",
31+
".yml",
32+
}
33+
34+
TOKEN_RE = re.compile(r"(?<![A-Fa-f0-9])[A-Fa-f0-9]{64}(?![A-Fa-f0-9])")
35+
36+
37+
def iter_text_files() -> list[Path]:
38+
files: list[Path] = []
39+
for path in SCAN_PATHS:
40+
if path.is_file():
41+
files.append(path)
42+
continue
43+
44+
if not path.exists():
45+
continue
46+
47+
for child in path.rglob("*"):
48+
if not child.is_file():
49+
continue
50+
if any(part in {".git", ".mypy_cache", ".pytest_cache", "__pycache__"} for part in child.parts):
51+
continue
52+
if child.suffix.lower() in TEXT_SUFFIXES:
53+
files.append(child)
54+
55+
return sorted(set(files))
56+
57+
58+
def test_no_hardcoded_oilpriceapi_tokens() -> None:
59+
findings: list[str] = []
60+
61+
for path in iter_text_files():
62+
for line_number, line in enumerate(path.read_text(encoding="utf-8", errors="ignore").splitlines(), 1):
63+
for match in TOKEN_RE.finditer(line):
64+
token_hash = hashlib.sha256(match.group(0).encode("utf-8")).hexdigest()[:16]
65+
findings.append(f"{path.relative_to(ROOT)}:{line_number}: sha256:{token_hash}")
66+
67+
assert findings == [], "Hardcoded OilPriceAPI-shaped token(s) found:\n" + "\n".join(findings)

0 commit comments

Comments
 (0)