keyprint-cli 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.
- keyprint/__init__.py +3 -0
- keyprint/__main__.py +4 -0
- keyprint/checksum.py +173 -0
- keyprint/cli.py +283 -0
- keyprint/context.py +90 -0
- keyprint/engine.py +390 -0
- keyprint/export.py +80 -0
- keyprint/fingerprint.py +268 -0
- keyprint/redact.py +20 -0
- keyprint/report.py +127 -0
- keyprint/rules/data/providers.json +1903 -0
- keyprint/ruleset.py +120 -0
- keyprint/scanner.py +96 -0
- keyprint/scoring.py +57 -0
- keyprint/style.py +82 -0
- keyprint/verify.py +234 -0
- keyprint_cli-0.1.0.dist-info/METADATA +380 -0
- keyprint_cli-0.1.0.dist-info/RECORD +22 -0
- keyprint_cli-0.1.0.dist-info/WHEEL +5 -0
- keyprint_cli-0.1.0.dist-info/entry_points.txt +2 -0
- keyprint_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
- keyprint_cli-0.1.0.dist-info/top_level.txt +1 -0
keyprint/ruleset.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Rule loading and validation.
|
|
2
|
+
|
|
3
|
+
Rules are data. The bundled corpus ships with the package; a user-supplied
|
|
4
|
+
corpus (a directory or JSON file) can be layered on top via --rules.
|
|
5
|
+
Schema validation fails loudly: a silently malformed rule is worse than no
|
|
6
|
+
rule, because it destroys trust in every verdict the engine emits.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from importlib import resources
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
REQUIRED_FIELDS = ("id", "provider", "category", "title", "pattern")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Rule:
|
|
22
|
+
id: str
|
|
23
|
+
provider: str
|
|
24
|
+
category: str
|
|
25
|
+
title: str
|
|
26
|
+
pattern: str
|
|
27
|
+
prefixes: tuple[str, ...] = ()
|
|
28
|
+
min_length: int = 0
|
|
29
|
+
max_length: int = 0
|
|
30
|
+
checksum: str | None = None
|
|
31
|
+
requires_context: tuple[str, ...] = ()
|
|
32
|
+
context: tuple[str, ...] = ()
|
|
33
|
+
capabilities: tuple[str, ...] = ()
|
|
34
|
+
revoke_url: str | None = None
|
|
35
|
+
docs_url: str | None = None
|
|
36
|
+
verify: str | None = None
|
|
37
|
+
financial_exposure: str | None = None
|
|
38
|
+
severity_hint: str | None = None
|
|
39
|
+
distinctive: bool = False
|
|
40
|
+
fixtures: dict = field(default_factory=dict)
|
|
41
|
+
compiled: re.Pattern | None = None
|
|
42
|
+
|
|
43
|
+
def __post_init__(self):
|
|
44
|
+
object.__setattr__(self, "compiled", re.compile(self.pattern))
|
|
45
|
+
|
|
46
|
+
def to_dict(self) -> dict:
|
|
47
|
+
d = {
|
|
48
|
+
"id": self.id, "provider": self.provider, "category": self.category,
|
|
49
|
+
"title": self.title, "pattern": self.pattern,
|
|
50
|
+
"prefixes": list(self.prefixes), "min_length": self.min_length,
|
|
51
|
+
"max_length": self.max_length, "checksum": self.checksum,
|
|
52
|
+
"context": list(self.context), "requires_context": list(self.requires_context),
|
|
53
|
+
"capabilities": list(self.capabilities), "revoke_url": self.revoke_url,
|
|
54
|
+
"docs_url": self.docs_url, "verify": self.verify,
|
|
55
|
+
}
|
|
56
|
+
if self.financial_exposure:
|
|
57
|
+
d["financial_exposure"] = self.financial_exposure
|
|
58
|
+
if self.severity_hint:
|
|
59
|
+
d["severity_hint"] = self.severity_hint
|
|
60
|
+
return d
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class RuleError(ValueError):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _validate(raw: dict, source: str) -> Rule:
|
|
68
|
+
for f in REQUIRED_FIELDS:
|
|
69
|
+
if not raw.get(f):
|
|
70
|
+
raise RuleError(f"{source}: rule missing required field '{f}': {raw.get('id', '<unnamed>')}")
|
|
71
|
+
try:
|
|
72
|
+
re.compile(raw["pattern"])
|
|
73
|
+
except re.error as e:
|
|
74
|
+
raise RuleError(f"{source}: rule {raw['id']} has invalid pattern: {e}") from e
|
|
75
|
+
for p in raw.get("prefixes", []):
|
|
76
|
+
if not raw["pattern"].startswith(re.escape(p).replace("\\\\", "\\")) and p not in raw["pattern"] and not raw["pattern"].startswith(p):
|
|
77
|
+
# pattern should embed the prefix; warn silently by allowing both
|
|
78
|
+
pass
|
|
79
|
+
return Rule(
|
|
80
|
+
id=raw["id"],
|
|
81
|
+
provider=raw["provider"],
|
|
82
|
+
category=raw.get("category", "unknown"),
|
|
83
|
+
title=raw.get("title", raw["id"]),
|
|
84
|
+
pattern=raw["pattern"],
|
|
85
|
+
prefixes=tuple(raw.get("prefixes", ())),
|
|
86
|
+
min_length=int(raw.get("min_length", 0)),
|
|
87
|
+
max_length=int(raw.get("max_length", 0)),
|
|
88
|
+
checksum=raw.get("checksum") or None,
|
|
89
|
+
requires_context=tuple(raw.get("requires_context", ())),
|
|
90
|
+
context=tuple(raw.get("context", ())),
|
|
91
|
+
capabilities=tuple(raw.get("capabilities", ())),
|
|
92
|
+
revoke_url=raw.get("revoke_url"),
|
|
93
|
+
docs_url=raw.get("docs_url"),
|
|
94
|
+
verify=raw.get("verify"),
|
|
95
|
+
financial_exposure=raw.get("financial_exposure"),
|
|
96
|
+
severity_hint=raw.get("severity_hint"),
|
|
97
|
+
distinctive=bool(raw.get("distinctive", False)),
|
|
98
|
+
fixtures=raw.get("fixtures") or {},
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def load_rules(extra_paths: list[str] | None = None) -> list[Rule]:
|
|
103
|
+
corpus = resources.files("keyprint.rules.data").joinpath("providers.json")
|
|
104
|
+
data = json.loads(corpus.read_text(encoding="utf-8"))
|
|
105
|
+
rules = [_validate(r, "bundled providers.json") for r in data["rules"]]
|
|
106
|
+
for path in extra_paths or []:
|
|
107
|
+
p = Path(path)
|
|
108
|
+
if p.is_dir():
|
|
109
|
+
files = sorted(p.glob("*.json"))
|
|
110
|
+
else:
|
|
111
|
+
files = [p]
|
|
112
|
+
for f in files:
|
|
113
|
+
payload = json.loads(f.read_text(encoding="utf-8"))
|
|
114
|
+
batch = payload["rules"] if isinstance(payload, dict) and "rules" in payload else payload
|
|
115
|
+
rules.extend(_validate(r, str(f)) for r in batch)
|
|
116
|
+
# bundled rules first so user rules can shadow by id
|
|
117
|
+
by_id: dict[str, Rule] = {}
|
|
118
|
+
for r in rules:
|
|
119
|
+
by_id[r.id] = r
|
|
120
|
+
return list(by_id.values())
|
keyprint/scanner.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Filesystem and git-history scanning.
|
|
2
|
+
|
|
3
|
+
- Walks files, skips binary-looking blobs and conventional noise
|
|
4
|
+
(node_modules, .git internals unless --git-history, lockfiles).
|
|
5
|
+
- --git-history scans `git log -p --all` output so commits that *removed*
|
|
6
|
+
a secret still surface - the majority of real leaks.
|
|
7
|
+
- A secret in git history is reported even if the working tree is clean.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .engine import Engine, Finding
|
|
17
|
+
|
|
18
|
+
SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", ".tox",
|
|
19
|
+
"dist", "build", ".mypy_cache", ".pytest_cache", "target"}
|
|
20
|
+
BINARY_SNIFF = 8192
|
|
21
|
+
MAX_FILE_BYTES = 8 * 1024 * 1024
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _looks_binary(chunk: bytes) -> bool:
|
|
25
|
+
return b"\x00" in chunk or chunk.count(b"\xff") > len(chunk) * 0.3
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def iter_files(paths: list[str]) -> list[Path]:
|
|
29
|
+
out: list[Path] = []
|
|
30
|
+
for p in paths:
|
|
31
|
+
path = Path(p)
|
|
32
|
+
if path.is_file():
|
|
33
|
+
out.append(path)
|
|
34
|
+
elif path.is_dir():
|
|
35
|
+
for f in path.rglob("*"):
|
|
36
|
+
if f.is_file() and not any(part in SKIP_DIRS for part in f.parts):
|
|
37
|
+
out.append(f)
|
|
38
|
+
return out
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def scan_path(engine: Engine, target: str) -> list[Finding]:
|
|
42
|
+
findings: list[Finding] = []
|
|
43
|
+
path = Path(target)
|
|
44
|
+
if path.is_dir():
|
|
45
|
+
files = iter_files([target])
|
|
46
|
+
else:
|
|
47
|
+
files = [path]
|
|
48
|
+
for f in files:
|
|
49
|
+
try:
|
|
50
|
+
if f.stat().st_size > MAX_FILE_BYTES:
|
|
51
|
+
continue
|
|
52
|
+
with open(f, "rb") as fh:
|
|
53
|
+
head = fh.read(BINARY_SNIFF)
|
|
54
|
+
if _looks_binary(head):
|
|
55
|
+
continue
|
|
56
|
+
fh.seek(0)
|
|
57
|
+
text = fh.read().decode("utf-8", errors="replace")
|
|
58
|
+
except OSError:
|
|
59
|
+
continue
|
|
60
|
+
findings.extend(engine.scan_text(text, file=str(f)))
|
|
61
|
+
return findings
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def scan_stdin(engine: Engine) -> list[Finding]:
|
|
65
|
+
text = sys.stdin.read()
|
|
66
|
+
return engine.scan_text(text, file="<stdin>")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def scan_git_history(engine: Engine, repo: str) -> list[Finding]:
|
|
70
|
+
"""Scan every line of every commit diff on the current branch set."""
|
|
71
|
+
try:
|
|
72
|
+
proc = subprocess.run(
|
|
73
|
+
["git", "-C", repo, "log", "-p", "-U0", "--all", "--no-color", "--full-index"],
|
|
74
|
+
capture_output=True, text=True, errors="replace", timeout=600,
|
|
75
|
+
)
|
|
76
|
+
except (OSError, subprocess.TimeoutExpired) as e:
|
|
77
|
+
raise RuntimeError(f"git history scan failed: {e}") from e
|
|
78
|
+
if proc.returncode != 0:
|
|
79
|
+
raise RuntimeError(f"git log failed: {proc.stderr.strip()}")
|
|
80
|
+
findings = engine.scan_text(proc.stdout, file="<git history>")
|
|
81
|
+
# attribute pseudo-file names from diff headers where possible
|
|
82
|
+
current_file = "<git history>"
|
|
83
|
+
attributed: list[Finding] = []
|
|
84
|
+
lines = proc.stdout.splitlines()
|
|
85
|
+
for f in findings:
|
|
86
|
+
# find the last +++ header before the finding's line
|
|
87
|
+
consumed = 0
|
|
88
|
+
for ln in lines:
|
|
89
|
+
if consumed >= f.line_number:
|
|
90
|
+
break
|
|
91
|
+
if ln.startswith("+++ b/"):
|
|
92
|
+
current_file = ln[6:].split("\t")[0]
|
|
93
|
+
consumed += 1
|
|
94
|
+
f.file = f"<git history> {current_file}"
|
|
95
|
+
attributed.append(f)
|
|
96
|
+
return attributed
|
keyprint/scoring.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Evidence-based confidence scoring.
|
|
2
|
+
|
|
3
|
+
Additive weighted evidence -> tier. A tier is never printed without its
|
|
4
|
+
evidence list; the evidence *is* the verdict. Tiers:
|
|
5
|
+
|
|
6
|
+
certain - format + structure + a checksum or context converges
|
|
7
|
+
likely - strong format evidence, no checksum available
|
|
8
|
+
possible - prefix/shape evidence only (includes truncated attribution)
|
|
9
|
+
unknown - high-entropy string no rule claims; alternatives listed
|
|
10
|
+
placeholder - matches a format but is a documentation sample / dummy
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
|
|
17
|
+
WEIGHTS = {
|
|
18
|
+
"distinctive_prefix": 30, # provider-unique prefix present in match
|
|
19
|
+
"generic_prefix": 10, # short/collision-prone prefix
|
|
20
|
+
"structure_match": 25, # full pattern matched (length + charset)
|
|
21
|
+
"checksum_valid": 35, # format carries one and it validates
|
|
22
|
+
"checksum_failed": -30, # format carries one and it does not
|
|
23
|
+
"context_boost": 20, # env var / header / path naming the provider
|
|
24
|
+
"required_context": 10, # required context satisfied
|
|
25
|
+
"ambiguous": -10, # another provider claims the same shape
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
TIER_THRESHOLDS = ((80, "certain"), (55, "likely"), (30, "possible"), (0, "unknown"))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Evidence:
|
|
33
|
+
signal: str
|
|
34
|
+
weight: int
|
|
35
|
+
detail: str = ""
|
|
36
|
+
|
|
37
|
+
def render(self) -> str:
|
|
38
|
+
d = f" ({self.detail})" if self.detail else ""
|
|
39
|
+
sign = "+" if self.weight >= 0 else ""
|
|
40
|
+
return f"{self.signal} {sign}{self.weight}{d}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Score:
|
|
45
|
+
tier: str
|
|
46
|
+
value: int
|
|
47
|
+
evidence: list[Evidence] = field(default_factory=list)
|
|
48
|
+
|
|
49
|
+
def render_evidence(self) -> str:
|
|
50
|
+
return " | ".join(e.render() for e in self.evidence)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def tier_for(value: int) -> str:
|
|
54
|
+
for threshold, name in TIER_THRESHOLDS:
|
|
55
|
+
if value >= threshold:
|
|
56
|
+
return name
|
|
57
|
+
return "unknown"
|
keyprint/style.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""ANSI styling — zero dependencies.
|
|
2
|
+
|
|
3
|
+
Color communicates the confidence tier at a glance: red = confirmed,
|
|
4
|
+
yellow = likely, cyan = possible, dim = unknown, magenta = placeholder.
|
|
5
|
+
|
|
6
|
+
Rules:
|
|
7
|
+
- color only when the stream is a TTY (never pollute redirected output/CI);
|
|
8
|
+
- NO_COLOR env (https://no-color.org) and --no-color disable everything;
|
|
9
|
+
- FORCE_COLOR=1 forces on (for testing/screenshots);
|
|
10
|
+
- on Windows legacy consoles we enable VT processing via ctypes.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
|
|
18
|
+
RESET = "\033[0m"
|
|
19
|
+
BOLD = "\033[1m"
|
|
20
|
+
DIM = "\033[2m"
|
|
21
|
+
RED = "\033[31m"
|
|
22
|
+
GREEN = "\033[32m"
|
|
23
|
+
YELLOW = "\033[33m"
|
|
24
|
+
MAGENTA = "\033[35m"
|
|
25
|
+
CYAN = "\033[36m"
|
|
26
|
+
|
|
27
|
+
_enabled = True
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def enable_windows_ansi() -> None:
|
|
31
|
+
"""Best-effort VT enablement for legacy Windows consoles."""
|
|
32
|
+
if os.name != "nt":
|
|
33
|
+
return
|
|
34
|
+
try:
|
|
35
|
+
import ctypes
|
|
36
|
+
kernel32 = ctypes.windll.kernel32
|
|
37
|
+
handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
|
|
38
|
+
mode = ctypes.c_uint32()
|
|
39
|
+
if kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
|
|
40
|
+
kernel32.SetConsoleMode(handle, mode.value | 0x0004) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
|
41
|
+
except Exception:
|
|
42
|
+
pass
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def decide(stream=None) -> bool:
|
|
46
|
+
stream = stream or sys.stdout
|
|
47
|
+
if os.environ.get("NO_COLOR"):
|
|
48
|
+
return False
|
|
49
|
+
if os.environ.get("FORCE_COLOR"):
|
|
50
|
+
return True
|
|
51
|
+
if os.environ.get("TERM") == "dumb":
|
|
52
|
+
return False
|
|
53
|
+
return hasattr(stream, "isatty") and stream.isatty()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def set_enabled(value: bool) -> None:
|
|
57
|
+
global _enabled
|
|
58
|
+
_enabled = bool(value)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def is_enabled() -> bool:
|
|
62
|
+
return _enabled
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def paint(text: str, *codes: str) -> str:
|
|
66
|
+
if not _enabled or not codes:
|
|
67
|
+
return text
|
|
68
|
+
return "".join(codes) + text + RESET
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# tier -> (token color, label color)
|
|
72
|
+
TIER_STYLES = {
|
|
73
|
+
"certain": (BOLD + RED, BOLD + RED),
|
|
74
|
+
"likely": (YELLOW, YELLOW),
|
|
75
|
+
"possible": (CYAN, CYAN),
|
|
76
|
+
"unknown": (DIM, DIM),
|
|
77
|
+
"placeholder": (DIM, MAGENTA),
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def tier_colors(confidence: str) -> tuple[str, str]:
|
|
82
|
+
return TIER_STYLES.get(confidence, (DIM, DIM))
|
keyprint/verify.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Authorized verification of keys you own.
|
|
2
|
+
|
|
3
|
+
Hard gates, enforced in code:
|
|
4
|
+
- requires an explicit --authorized-owner attestation;
|
|
5
|
+
- refuses to run without it (attribution alone is always available offline);
|
|
6
|
+
- refuses batch verification above a hard cap without --i-know-this-is-bulk;
|
|
7
|
+
- every network call is appended to a local audit log (no secrets in it).
|
|
8
|
+
|
|
9
|
+
Each spec declares cost and side effects BEFORE the call is printed and made.
|
|
10
|
+
Liveness taxonomy: valid / revoked / invalid / expired / quota-exhausted /
|
|
11
|
+
ip-restricted / rate-limited / error. Distinguishing 'revoked' from
|
|
12
|
+
'valid-but-blocked' removes the most common false negative in this class.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.request
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
AUDIT_LOG = Path.home() / ".keyprint" / "audit.jsonl"
|
|
26
|
+
HARD_BATCH_CAP = 10
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Spec:
|
|
31
|
+
provider: str
|
|
32
|
+
method: str
|
|
33
|
+
url: str
|
|
34
|
+
headers: dict # values may use {key}
|
|
35
|
+
body: str | None = None
|
|
36
|
+
cost: str = "free"
|
|
37
|
+
audit_visible: str = "yes - the call appears in provider logs"
|
|
38
|
+
may_alert: str = "no"
|
|
39
|
+
notes: str = ""
|
|
40
|
+
parse_identity: str = "" # json path list for identity fields
|
|
41
|
+
parse_scopes_header: str | None = None
|
|
42
|
+
|
|
43
|
+
def describe(self) -> str:
|
|
44
|
+
return (f"{self.method} {self.url}\n"
|
|
45
|
+
f" cost: {self.cost} | audit-visible: {self.audit_visible} | may-alert: {self.may_alert}\n"
|
|
46
|
+
f" notes: {self.notes}")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _h(auth: str, extra: dict | None = None) -> dict:
|
|
50
|
+
h = {"User-Agent": "keyprint/0.1 (offline attribution tool; authorized verification)"}
|
|
51
|
+
if auth:
|
|
52
|
+
h.update(extra or {})
|
|
53
|
+
return h
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
SPECS: dict[str, Spec] = {
|
|
57
|
+
"github": Spec(
|
|
58
|
+
provider="github", method="GET", url="https://api.github.com/user",
|
|
59
|
+
headers={"Authorization": "Bearer {key}", "Accept": "application/vnd.github+json"},
|
|
60
|
+
cost="free", audit_visible="yes - appears in GitHub audit logs of the account",
|
|
61
|
+
may_alert="possible - GitHub may notify the account holder of unusual access",
|
|
62
|
+
parse_identity=["login", "id", "type"],
|
|
63
|
+
parse_scopes_header="X-OAuth-Scopes",
|
|
64
|
+
),
|
|
65
|
+
"openai": Spec(
|
|
66
|
+
provider="openai", method="GET", url="https://api.openai.com/v1/models",
|
|
67
|
+
headers={"Authorization": "Bearer {key}"},
|
|
68
|
+
cost="free", audit_visible="yes",
|
|
69
|
+
may_alert="possible on repeated failures",
|
|
70
|
+
parse_identity=["object"],
|
|
71
|
+
),
|
|
72
|
+
"anthropic": Spec(
|
|
73
|
+
provider="anthropic", method="GET", url="https://api.anthropic.com/v1/models",
|
|
74
|
+
headers={"x-api-key": "{key}", "anthropic-version": "2023-06-01"},
|
|
75
|
+
cost="free", audit_visible="yes",
|
|
76
|
+
may_alert="no",
|
|
77
|
+
),
|
|
78
|
+
"stripe": Spec(
|
|
79
|
+
provider="stripe", method="GET", url="https://api.stripe.com/v1/balance",
|
|
80
|
+
headers={"Authorization": "Bearer {key}"},
|
|
81
|
+
cost="free", audit_visible="yes - key usage is logged in the Stripe dashboard",
|
|
82
|
+
may_alert="yes - Stripe may email the account owner on new key usage",
|
|
83
|
+
parse_identity=["object"],
|
|
84
|
+
),
|
|
85
|
+
"slack": Spec(
|
|
86
|
+
provider="slack", method="POST", url="https://slack.com/api/auth.test",
|
|
87
|
+
headers={"Authorization": "Bearer {key}", "Content-Type": "application/x-www-form-urlencoded"},
|
|
88
|
+
body="", cost="free", audit_visible="yes",
|
|
89
|
+
parse_identity=["team", "user", "bot_id"],
|
|
90
|
+
),
|
|
91
|
+
"google": Spec(
|
|
92
|
+
provider="google", method="GET",
|
|
93
|
+
url="https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={key}",
|
|
94
|
+
headers={}, cost="free", audit_visible="no (tokeninfo endpoint)",
|
|
95
|
+
parse_identity=["aud", "scope", "expires_in"],
|
|
96
|
+
),
|
|
97
|
+
"huggingface": Spec(
|
|
98
|
+
provider="huggingface", method="GET", url="https://huggingface.co/api/whoami-v2",
|
|
99
|
+
headers={"Authorization": "Bearer {key}"},
|
|
100
|
+
cost="free", audit_visible="yes", parse_identity=["name", "type"],
|
|
101
|
+
),
|
|
102
|
+
"twilio": Spec(
|
|
103
|
+
provider="twilio", method="GET", url="https://api.twilio.com/2010-04-01/Accounts.json",
|
|
104
|
+
headers={"Authorization": "Basic {basic}"},
|
|
105
|
+
cost="free", audit_visible="yes", parse_identity=["sid", "friendly_name"],
|
|
106
|
+
),
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def classify_liveness(status: int, body: str, provider: str) -> tuple[str, str]:
|
|
111
|
+
"""(liveness, human note)."""
|
|
112
|
+
if status == 200:
|
|
113
|
+
return "valid", "credential accepted"
|
|
114
|
+
if status == 401:
|
|
115
|
+
return "revoked-or-invalid", "rejected by provider - revoked, malformed, or wrong secret"
|
|
116
|
+
if status == 403:
|
|
117
|
+
low = body.lower()
|
|
118
|
+
if "quota" in low or "billing" in low or "limit" in low:
|
|
119
|
+
return "quota-exhausted", "identity accepted but blocked by quota/billing"
|
|
120
|
+
if "ip" in low or "region" in low or "not allowed" in low:
|
|
121
|
+
return "ip-restricted", "identity accepted but blocked by IP/region policy"
|
|
122
|
+
return "forbidden", "authenticated identity lacks permission (key may still be live)"
|
|
123
|
+
if status == 429:
|
|
124
|
+
return "rate-limited", "rate limited - identity may be valid; retry later"
|
|
125
|
+
if status == 410:
|
|
126
|
+
return "expired", "resource gone"
|
|
127
|
+
if status in (301, 302):
|
|
128
|
+
return "error", "unexpected redirect"
|
|
129
|
+
return "error", f"HTTP {status}"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class VerifyResult:
|
|
133
|
+
def __init__(self, provider: str, liveness: str, note: str, status: int,
|
|
134
|
+
identity: dict, scopes: str | None, spec: Spec):
|
|
135
|
+
self.provider = provider
|
|
136
|
+
self.liveness = liveness
|
|
137
|
+
self.note = note
|
|
138
|
+
self.status = status
|
|
139
|
+
self.identity = identity
|
|
140
|
+
self.scopes = scopes
|
|
141
|
+
self.spec = spec
|
|
142
|
+
|
|
143
|
+
def render(self, key_hint: str) -> str:
|
|
144
|
+
lines = [f"{self.provider}: {self.liveness} ({self.note})", f" HTTP {self.status}, key {key_hint}"]
|
|
145
|
+
if self.identity:
|
|
146
|
+
for k, v in self.identity.items():
|
|
147
|
+
lines.append(f" identity.{k}: {v}")
|
|
148
|
+
if self.scopes is not None:
|
|
149
|
+
lines.append(f" scopes: {self.scopes or '(none)'}")
|
|
150
|
+
return "\n".join(lines)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def verify_key(provider: str, key: str, *, basic: str | None = None,
|
|
154
|
+
timeout: int = 15) -> VerifyResult:
|
|
155
|
+
if provider not in SPECS:
|
|
156
|
+
raise KeyError(f"no verification spec for provider '{provider}' "
|
|
157
|
+
f"(available: {', '.join(sorted(SPECS))})")
|
|
158
|
+
spec = SPECS[provider]
|
|
159
|
+
headers = {k: v.replace("{key}", key).replace("{basic}", basic or "")
|
|
160
|
+
for k, v in spec.headers.items()}
|
|
161
|
+
data = spec.body.encode() if spec.body is not None else None
|
|
162
|
+
req = urllib.request.Request(spec.url, headers=headers, data=data, method=spec.method)
|
|
163
|
+
status, body = 0, ""
|
|
164
|
+
try:
|
|
165
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
166
|
+
status, body = resp.status, resp.read().decode("utf-8", errors="replace")
|
|
167
|
+
except urllib.error.HTTPError as e:
|
|
168
|
+
status, body = e.code, e.read().decode("utf-8", errors="replace")
|
|
169
|
+
except (urllib.error.URLError, OSError) as e:
|
|
170
|
+
_audit(spec, None, note=f"network error: {e}")
|
|
171
|
+
raise ConnectionError(f"network error calling {spec.url}: {e}") from e
|
|
172
|
+
|
|
173
|
+
identity: dict = {}
|
|
174
|
+
try:
|
|
175
|
+
payload = json.loads(body)
|
|
176
|
+
for path in [p for p in spec.parse_identity.split(",") if p]:
|
|
177
|
+
if isinstance(payload, dict) and path.strip() in payload:
|
|
178
|
+
identity[path.strip()] = payload[path.strip()]
|
|
179
|
+
except _json.JSONDecodeError:
|
|
180
|
+
pass
|
|
181
|
+
scopes = None
|
|
182
|
+
if spec.parse_scopes_header:
|
|
183
|
+
# urlopen hides response headers on HTTPError; capture what we can
|
|
184
|
+
try:
|
|
185
|
+
with urllib.request.urlopen(urllib.request.Request(spec.url, headers=headers, method=spec.method), timeout=timeout) as resp:
|
|
186
|
+
scopes = resp.headers.get(spec.parse_scopes_header)
|
|
187
|
+
except urllib.error.HTTPError as e:
|
|
188
|
+
scopes = e.headers.get(spec.parse_scopes_header)
|
|
189
|
+
except (urllib.error.URLError, OSError):
|
|
190
|
+
scopes = None
|
|
191
|
+
liveness, note = classify_liveness(status, body, provider)
|
|
192
|
+
_audit(spec, status)
|
|
193
|
+
return VerifyResult(provider, liveness, note, status, identity, scopes, spec)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _audit(spec: Spec, status: int | None, note: str | None = None) -> None:
|
|
197
|
+
"""Local-only, secret-free audit trail of every network call."""
|
|
198
|
+
AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
|
|
199
|
+
entry = {
|
|
200
|
+
"ts": datetime.now(timezone.utc).isoformat(),
|
|
201
|
+
"provider": spec.provider,
|
|
202
|
+
"method": spec.method,
|
|
203
|
+
"url": spec.url.split("?")[0],
|
|
204
|
+
"status": status,
|
|
205
|
+
"note": note,
|
|
206
|
+
}
|
|
207
|
+
with open(AUDIT_LOG, "a", encoding="utf-8") as fh:
|
|
208
|
+
fh.write(_json.dumps(entry) + "\n")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def ownership_gate(count: int, owner: str | None, assume_yes: bool, bulk_flag: bool) -> None:
|
|
212
|
+
if not owner:
|
|
213
|
+
sys.stderr.write(
|
|
214
|
+
"refusing to verify: no ownership attestation.\n"
|
|
215
|
+
" Verification calls provider endpoints with the key. That is only\n"
|
|
216
|
+
" legitimate for a key YOU own or are authorized to test.\n"
|
|
217
|
+
" Pass --authorized-owner <you@example.com> to attest ownership.\n"
|
|
218
|
+
" Offline attribution (explain/scan) needs no gate and works on any string.\n")
|
|
219
|
+
sys.exit(2)
|
|
220
|
+
if count > HARD_BATCH_CAP and not bulk_flag:
|
|
221
|
+
sys.stderr.write(
|
|
222
|
+
f"refusing to verify {count} keys: bulk validation above {HARD_BATCH_CAP}\n"
|
|
223
|
+
" requires --i-know-this-is-bulk. Bulk credential checking is the\n"
|
|
224
|
+
" signature of credential-stuffing; this tool does not enable it silently.\n")
|
|
225
|
+
sys.exit(2)
|
|
226
|
+
if not assume_yes:
|
|
227
|
+
sys.stderr.write(
|
|
228
|
+
f"attested owner: {owner}\n"
|
|
229
|
+
f"keys to verify: {count}\n"
|
|
230
|
+
"Each call is read-only but audit-visible; details are printed per provider.\n"
|
|
231
|
+
"Proceed? [y/N] ")
|
|
232
|
+
if sys.stdin.readline().strip().lower() not in ("y", "yes"):
|
|
233
|
+
sys.stderr.write("aborted by user.\n")
|
|
234
|
+
sys.exit(1)
|