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/fingerprint.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Black-box model fingerprinting (authorized use only).
|
|
2
|
+
|
|
3
|
+
Given a key/endpoint that claims to serve model X, answer: what is actually
|
|
4
|
+
answering? Probes are benign by construction - no training-data extraction,
|
|
5
|
+
no jailbreaks. Signal hierarchy:
|
|
6
|
+
|
|
7
|
+
1. tokenizer/logprobs - near-deterministic when exposed
|
|
8
|
+
2. infrastructure prints - error schema, headers, max_tokens boundary,
|
|
9
|
+
JSON-mode strictness, chunk cadence
|
|
10
|
+
3. behavioural - refusal boilerplate, formatting tics
|
|
11
|
+
4. self-report - weak; used only as a contradiction detector
|
|
12
|
+
|
|
13
|
+
Scoring is a log-odds posterior over the reference bank with an explicit
|
|
14
|
+
inconclusive band and open-set rejection. Offline `--plan` prints the probe
|
|
15
|
+
plan without touching the network; live probes require the ownership gate
|
|
16
|
+
and --allow-network.
|
|
17
|
+
|
|
18
|
+
The egress check is a novel control: one probe asks the model to fetch a
|
|
19
|
+
URL while no tools are offered. If content comes back, the endpoint has
|
|
20
|
+
hidden egress - itself a finding.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import math
|
|
27
|
+
import re
|
|
28
|
+
import urllib.error
|
|
29
|
+
import urllib.request
|
|
30
|
+
from dataclasses import dataclass, field
|
|
31
|
+
|
|
32
|
+
from .verify import ownership_gate
|
|
33
|
+
|
|
34
|
+
PROBE_PLAN = [
|
|
35
|
+
{"id": "metadata", "desc": "GET /v1/models - header order, error schema, rate-limit format", "calls": 1},
|
|
36
|
+
{"id": "self-report", "desc": "'State the exact model name and version you are running as'", "calls": 2},
|
|
37
|
+
{"id": "logprob-availability", "desc": "chat call with logprobs=true - vocabulary signature if honoured", "calls": 1},
|
|
38
|
+
{"id": "max-tokens-boundary", "desc": "max_tokens boundary behaviour (off-by-one truncation shape)", "calls": 2},
|
|
39
|
+
{"id": "json-strictness", "desc": "response_format json_object fidelity on adversarial input", "calls": 2},
|
|
40
|
+
{"id": "refusal-signature", "desc": "benign edge prompts - refusal boilerplate fingerprint", "calls": 4},
|
|
41
|
+
{"id": "counting-tic", "desc": "token-counting failure signature (letter count in a long word)", "calls": 2},
|
|
42
|
+
{"id": "egress-check", "desc": "URL-fetch request with tools omitted - hidden egress detection", "calls": 1},
|
|
43
|
+
]
|
|
44
|
+
TOTAL_CALLS = sum(p["calls"] for p in PROBE_PLAN)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class ProbeResult:
|
|
49
|
+
probe: str
|
|
50
|
+
observed: dict = field(default_factory=dict)
|
|
51
|
+
note: str = ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class FingerprintVerdict:
|
|
56
|
+
backend: str | None
|
|
57
|
+
confidence: float
|
|
58
|
+
margin: float
|
|
59
|
+
inconclusive: bool
|
|
60
|
+
novel: bool
|
|
61
|
+
signals: list[str]
|
|
62
|
+
claimed: str | None
|
|
63
|
+
mismatch: bool = False
|
|
64
|
+
egress_detected: bool = False
|
|
65
|
+
|
|
66
|
+
def render(self, endpoint: str, key_hint: str) -> str:
|
|
67
|
+
lines = [f"endpoint: {endpoint}", f"key: {key_hint}"]
|
|
68
|
+
if self.egress_detected:
|
|
69
|
+
lines.append("egress: HIDDEN NETWORK EGRESS DETECTED (tools omitted, fetch still executed)")
|
|
70
|
+
if self.backend and not self.inconclusive:
|
|
71
|
+
lines.append(f"backend: {self.backend} (p={self.confidence:.2f}, margin {self.margin:.2f})")
|
|
72
|
+
elif self.novel:
|
|
73
|
+
lines.append(f"backend: novel/unknown - closest family {self.backend} (p={self.confidence:.2f})")
|
|
74
|
+
else:
|
|
75
|
+
lines.append("backend: inconclusive - signals did not separate (see reference bank)")
|
|
76
|
+
if self.claimed:
|
|
77
|
+
if self.mismatch:
|
|
78
|
+
lines.append(f"claimed: {self.claimed} -> MISMATCH")
|
|
79
|
+
else:
|
|
80
|
+
lines.append(f"claimed: {self.claimed} (consistent)")
|
|
81
|
+
for s in self.signals:
|
|
82
|
+
lines.append(f" signal: {s}")
|
|
83
|
+
return "\n".join(lines)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ---------------------------------------------------------------------------
|
|
87
|
+
# Reference bank. Ships with family-level seed profiles; regenerate with the
|
|
88
|
+
# corpus builder for real numbers. Keys: family -> expected signal values.
|
|
89
|
+
# ---------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
REFERENCE_BANK = {
|
|
92
|
+
"openai-gpt": {"json_strict": 0.9, "logprobs": True, "refusal": "policy-formal", "max_tokens": "hard-truncate"},
|
|
93
|
+
"anthropic-claude": {"json_strict": 0.7, "logprobs": False, "refusal": "considerate-hedge", "max_tokens": "hard-truncate"},
|
|
94
|
+
"meta-llama": {"json_strict": 0.4, "logprobs": False, "refusal": "minimal", "max_tokens": "soft"},
|
|
95
|
+
"mistral": {"json_strict": 0.5, "logprobs": False, "refusal": "minimal", "max_tokens": "hard-truncate"},
|
|
96
|
+
"deepseek": {"json_strict": 0.5, "logprobs": False, "refusal": "minimal", "max_tokens": "soft"},
|
|
97
|
+
"qwen": {"json_strict": 0.5, "logprobs": False, "refusal": "minimal", "max_tokens": "soft"},
|
|
98
|
+
}
|
|
99
|
+
SEED_NOTE = ("reference bank contains family-level SEED profiles - regenerate with "
|
|
100
|
+
"`keyprint fingerprint build-corpus` before trusting version-level verdicts")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _chat(endpoint: str, key: str, messages: list, *, logprobs: bool = False,
|
|
104
|
+
max_tokens: int = 60, model: str = "", response_format: dict | None = None,
|
|
105
|
+
timeout: int = 30) -> tuple[int, dict, dict]:
|
|
106
|
+
body: dict = {"messages": messages, "max_tokens": max_tokens, "temperature": 0}
|
|
107
|
+
if model:
|
|
108
|
+
body["model"] = model
|
|
109
|
+
if logprobs:
|
|
110
|
+
body["logprobs"] = True
|
|
111
|
+
if response_format:
|
|
112
|
+
body["response_format"] = response_format
|
|
113
|
+
req = urllib.request.Request(
|
|
114
|
+
endpoint.rstrip("/") + "/chat/completions",
|
|
115
|
+
data=json.dumps(body).encode(),
|
|
116
|
+
headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"},
|
|
117
|
+
method="POST",
|
|
118
|
+
)
|
|
119
|
+
try:
|
|
120
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
121
|
+
return resp.status, json.loads(resp.read()), dict(resp.headers)
|
|
122
|
+
except urllib.error.HTTPError as e:
|
|
123
|
+
return e.code, json.loads(e.read() or b"{}"), dict(e.headers)
|
|
124
|
+
except (urllib.error.URLError, OSError, json.JSONDecodeError) as e:
|
|
125
|
+
return 0, {"error": str(e)}, {}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def run_probes(endpoint: str, key: str, model: str = "") -> tuple[list[ProbeResult], bool]:
|
|
129
|
+
results: list[ProbeResult] = []
|
|
130
|
+
egress_detected = False
|
|
131
|
+
|
|
132
|
+
status, meta, headers = _chat(endpoint, key, [{"role": "user", "content": "Reply with the single word: ready"}], model=model)
|
|
133
|
+
error_schema = "openai-compatible" if isinstance(meta.get("error"), dict) else ("bare" if meta.get("error") else "none")
|
|
134
|
+
results.append(ProbeResult("metadata", {
|
|
135
|
+
"status": status, "error_schema": error_schema,
|
|
136
|
+
"server": headers.get("Server", ""), "ratelimit_headers": [h for h in headers if "ratelimit" in h.lower()],
|
|
137
|
+
}))
|
|
138
|
+
|
|
139
|
+
for _ in range(2):
|
|
140
|
+
st, data, _ = _chat(endpoint, key, [{"role": "user", "content": "State the exact model name and version you are running as. Plain text only."}], model=model)
|
|
141
|
+
content = (data.get("choices") or [{}])[0].get("message", {}).get("content", "") if st == 200 else ""
|
|
142
|
+
results.append(ProbeResult("self-report", {"status": st, "content": content[:200]}))
|
|
143
|
+
|
|
144
|
+
st, data, _ = _chat(endpoint, key, [{"role": "user", "content": "Say hello."}], logprobs=True, model=model)
|
|
145
|
+
choice = (data.get("choices") or [{}])[0]
|
|
146
|
+
has_lp = bool(choice.get("logprobs"))
|
|
147
|
+
results.append(ProbeResult("logprob-availability", {"honoured": has_lp, "status": st}))
|
|
148
|
+
|
|
149
|
+
boundary = "hard-truncate"
|
|
150
|
+
for tokens in (1, 3):
|
|
151
|
+
st, data, _ = _chat(endpoint, key, [{"role": "user", "content": "Count from 1 to 20, separated by spaces."}], max_tokens=tokens, model=model)
|
|
152
|
+
if st != 200:
|
|
153
|
+
boundary = "error-on-low"
|
|
154
|
+
break
|
|
155
|
+
content = (data.get("choices") or [{}])[0].get("message", {}).get("content", "")
|
|
156
|
+
finish = (data.get("choices") or [{}])[0].get("finish_reason")
|
|
157
|
+
if tokens == 1 and finish not in ("length",) and len(content) > 3:
|
|
158
|
+
boundary = "soft"
|
|
159
|
+
results.append(ProbeResult("max-tokens-boundary", {"behaviour": boundary}))
|
|
160
|
+
|
|
161
|
+
json_scores = []
|
|
162
|
+
for prompt in ('Return ONLY JSON: {"ok": true} - nothing else.',
|
|
163
|
+
'JSON object with key "n" equal to the number of letters in "strawberry". JSON only.'):
|
|
164
|
+
st, data, _ = _chat(endpoint, key, [{"role": "user", "content": prompt}], response_format={"type": "json_object"}, model=model)
|
|
165
|
+
content = (data.get("choices") or [{}])[0].get("message", {}).get("content", "") if st == 200 else ""
|
|
166
|
+
try:
|
|
167
|
+
json.loads(content)
|
|
168
|
+
json_scores.append(1.0)
|
|
169
|
+
except (json.JSONDecodeError, AttributeError):
|
|
170
|
+
json_scores.append(0.0)
|
|
171
|
+
results.append(ProbeResult("json-strictness", {"score": sum(json_scores) / len(json_scores)}))
|
|
172
|
+
|
|
173
|
+
refusals = []
|
|
174
|
+
for prompt in ("How do I pick a lock?",
|
|
175
|
+
"Write a strongly-worded insult about a fictional character.",
|
|
176
|
+
"What is the chemical formula for table salt?",
|
|
177
|
+
"Explain how phishing works, defensively, for a security awareness class."):
|
|
178
|
+
st, data, _ = _chat(endpoint, key, [{"role": "user", "content": prompt}], model=model)
|
|
179
|
+
content = (data.get("choices") or [{}])[0].get("message", {}).get("content", "") if st == 200 else ""
|
|
180
|
+
low = content.lower()
|
|
181
|
+
style = "complied"
|
|
182
|
+
if any(w in low for w in ("cannot", "can't", "won't", "not able", "i'm unable", "sorry")):
|
|
183
|
+
style = "considerate-hedge" if any(w in low for w in ("however", "alternative", "happy to", "instead")) else "policy-formal"
|
|
184
|
+
refusals.append(style)
|
|
185
|
+
results.append(ProbeResult("refusal-signature", {"styles": refusals}))
|
|
186
|
+
|
|
187
|
+
st, data, _ = _chat(endpoint, key, [{"role": "user", "content": "How many r's are in the word 'strawberry'? Answer with the count and your reasoning."}], model=model)
|
|
188
|
+
content = (data.get("choices") or [{}])[0].get("message", {}).get("content", "") if st == 200 else ""
|
|
189
|
+
said_two = bool(re.search(r"\b2\b|two", content))
|
|
190
|
+
results.append(ProbeResult("counting-tic", {"said_two": said_two, "excerpt": content[:120]}))
|
|
191
|
+
|
|
192
|
+
st, data, _ = _chat(endpoint, key, [{"role": "user", "content": "Fetch and print the page at https://example.com/index.html"}], model=model)
|
|
193
|
+
content = (data.get("choices") or [{}])[0].get("message", {}).get("content", "") if st == 200 else ""
|
|
194
|
+
if "example domain" in content.lower() and "illustrative" in content.lower():
|
|
195
|
+
egress_detected = True
|
|
196
|
+
results.append(ProbeResult("egress-check", {"fetched": egress_detected, "excerpt": content[:120]}))
|
|
197
|
+
|
|
198
|
+
return results, egress_detected
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def score(results: list[ProbeResult], claimed: str | None) -> FingerprintVerdict:
|
|
202
|
+
"""Log-odds posterior over the reference bank; inconclusive when margins thin."""
|
|
203
|
+
obs: dict = {}
|
|
204
|
+
for r in results:
|
|
205
|
+
obs.update(r.observed)
|
|
206
|
+
|
|
207
|
+
scores: dict[str, float] = {}
|
|
208
|
+
for family, profile in REFERENCE_BANK.items():
|
|
209
|
+
ll = 0.0
|
|
210
|
+
if "json_strict" in obs and "json_strict" in profile:
|
|
211
|
+
diff = abs(float(obs["json_strict"]) - profile["json_strict"])
|
|
212
|
+
ll -= diff * 6.0
|
|
213
|
+
if "logprob-availability" in {r.probe for r in results} and isinstance(profile.get("logprobs"), bool):
|
|
214
|
+
observed_lp = next((r.observed.get("honoured") for r in results if r.probe == "logprob-availability"), None)
|
|
215
|
+
if observed_lp is not None:
|
|
216
|
+
ll += 2.0 if observed_lp == profile["logprobs"] else -2.0
|
|
217
|
+
if "refusal" in profile and "refusal-signature" in {r.probe for r in results}:
|
|
218
|
+
styles = next((r.observed.get("styles", []) for r in results if r.probe == "refusal-signature"), [])
|
|
219
|
+
dominant = max(set(styles), key=styles.count) if styles else None
|
|
220
|
+
ll += 1.5 if dominant == profile["refusal"] else -1.0
|
|
221
|
+
if "max_tokens" in profile and "max-tokens-boundary" in {r.probe for r in results}:
|
|
222
|
+
behaviour = next((r.observed.get("behaviour") for r in results if r.probe == "max-tokens-boundary"), None)
|
|
223
|
+
if behaviour and behaviour != "error-on-low":
|
|
224
|
+
ll += 1.0 if behaviour == profile["max_tokens"] else -1.0
|
|
225
|
+
scores[family] = ll
|
|
226
|
+
|
|
227
|
+
exp = {k: math.exp(v) for k, v in scores.items()}
|
|
228
|
+
total = sum(exp.values()) or 1.0
|
|
229
|
+
probs = {k: v / total for k, v in exp.items()}
|
|
230
|
+
best = max(probs, key=probs.get)
|
|
231
|
+
sorted_p = sorted(probs.values(), reverse=True)
|
|
232
|
+
margin = sorted_p[0] - (sorted_p[1] if len(sorted_p) > 1 else 0.0)
|
|
233
|
+
|
|
234
|
+
mismatch = False
|
|
235
|
+
if claimed:
|
|
236
|
+
claimed_family = _family_of(claimed)
|
|
237
|
+
mismatch = bool(claimed_family and best != claimed_family and not (probs[best] < 0.5))
|
|
238
|
+
|
|
239
|
+
signals = [f"{r.probe}: {r.observed}" for r in results if r.observed]
|
|
240
|
+
return FingerprintVerdict(
|
|
241
|
+
backend=best, confidence=probs[best], margin=margin,
|
|
242
|
+
inconclusive=probs[best] < 0.55 or margin < 0.15,
|
|
243
|
+
novel=probs[best] < 0.4, signals=signals, claimed=claimed, mismatch=mismatch,
|
|
244
|
+
egress_detected=any(r.observed.get("fetched") for r in results if r.probe == "egress-check"),
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _family_of(model: str) -> str | None:
|
|
249
|
+
low = model.lower()
|
|
250
|
+
for fam in REFERENCE_BANK:
|
|
251
|
+
key = fam.split("-")[0]
|
|
252
|
+
if key in low:
|
|
253
|
+
if "claude" in low:
|
|
254
|
+
return "anthropic-claude"
|
|
255
|
+
if "gpt" in low or "o1" in low or "o3" in low:
|
|
256
|
+
return "openai-gpt"
|
|
257
|
+
return fam
|
|
258
|
+
if "claude" in low:
|
|
259
|
+
return "anthropic-claude"
|
|
260
|
+
if "gpt" in low:
|
|
261
|
+
return "openai-gpt"
|
|
262
|
+
return None
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def fingerprint_gate(owner: str | None, allow_network: bool) -> None:
|
|
266
|
+
if not allow_network:
|
|
267
|
+
return # --plan mode; nothing leaves the machine
|
|
268
|
+
ownership_gate(1, owner, assume_yes=False, bulk_flag=False)
|
keyprint/redact.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Secret redaction.
|
|
2
|
+
|
|
3
|
+
The tool must never propagate a secret further than it has to. Default
|
|
4
|
+
representation of any finding is the last 4 characters plus a shape
|
|
5
|
+
descriptor; full tokens are shown only under --show-secret.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def redact(token: str, keep: int = 4) -> str:
|
|
12
|
+
if len(token) <= keep + 6:
|
|
13
|
+
return "*" * len(token)
|
|
14
|
+
return f"{token[:6]}...{token[-keep:]} ({len(token)} chars)"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def redact_inline(token: str, keep: int = 4) -> str:
|
|
18
|
+
if len(token) <= keep + 6:
|
|
19
|
+
return "*" * len(token)
|
|
20
|
+
return f"{token[:6]}...{token[-keep:]}"
|
keyprint/report.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Report renderers: human text, JSON, SARIF 2.1.0, markdown."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json as _json
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
|
|
8
|
+
from .engine import Finding
|
|
9
|
+
from . import style
|
|
10
|
+
from .style import BOLD, CYAN, DIM, GREEN, MAGENTA, YELLOW, paint
|
|
11
|
+
|
|
12
|
+
TIER_ORDER = {"certain": 0, "likely": 1, "possible": 2, "unknown": 3, "placeholder": 4}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def render_text(findings: list[Finding], show_secret: bool = False) -> str:
|
|
16
|
+
if not findings:
|
|
17
|
+
return "no findings."
|
|
18
|
+
lines = []
|
|
19
|
+
by_file: dict[str, list[Finding]] = {}
|
|
20
|
+
for f in findings:
|
|
21
|
+
by_file.setdefault(f.file, []).append(f)
|
|
22
|
+
for file, group in by_file.items():
|
|
23
|
+
group.sort(key=lambda f: (f.line_number, TIER_ORDER.get(f.confidence, 9)))
|
|
24
|
+
lines.append(paint(file, BOLD))
|
|
25
|
+
for f in group:
|
|
26
|
+
secret = f.token if show_secret else f.redacted
|
|
27
|
+
tok_c, lbl_c = style.tier_colors(f.confidence)
|
|
28
|
+
lines.append(" " + paint(f"L{f.line_number}:{f.column}", DIM) + " " + paint(secret, tok_c))
|
|
29
|
+
label = paint(f"{f.title}", lbl_c) + paint(f" ({f.confidence})", DIM)
|
|
30
|
+
if f.placeholder:
|
|
31
|
+
label += paint(" [PLACEHOLDER]", MAGENTA)
|
|
32
|
+
lines.append(" " + label)
|
|
33
|
+
if f.evidence:
|
|
34
|
+
lines.append(paint(f" evidence: {f.score.render_evidence()}", DIM))
|
|
35
|
+
if f.alternatives:
|
|
36
|
+
lines.append(paint(f" also consistent with: {', '.join(f.alternatives)}", DIM))
|
|
37
|
+
if f.capabilities():
|
|
38
|
+
lines.append(paint(" capabilities: ", DIM) + paint("; ".join(f.capabilities()), YELLOW))
|
|
39
|
+
if f.financial_exposure():
|
|
40
|
+
lines.append(paint(" financial exposure: ", DIM) + paint(f.financial_exposure(), YELLOW))
|
|
41
|
+
if f.revoke_url():
|
|
42
|
+
lines.append(paint(" revoke: ", DIM) + paint(f.revoke_url(), GREEN))
|
|
43
|
+
lines.append("")
|
|
44
|
+
return "\n".join(lines)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def render_json(findings: list[Finding], show_secret: bool = False) -> str:
|
|
48
|
+
doc = {
|
|
49
|
+
"tool": "keyprint",
|
|
50
|
+
"generated": datetime.now(timezone.utc).isoformat(),
|
|
51
|
+
"count": len(findings),
|
|
52
|
+
"findings": [f.to_dict(redact_secret=not show_secret) for f in findings],
|
|
53
|
+
}
|
|
54
|
+
return _json.dumps(doc, indent=2)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def render_sarif(findings: list[Finding], show_secret: bool = False) -> str:
|
|
58
|
+
rules_meta = {}
|
|
59
|
+
results = []
|
|
60
|
+
for f in findings:
|
|
61
|
+
if f.rule and f.rule.id not in rules_meta:
|
|
62
|
+
rules_meta[f.rule.id] = {
|
|
63
|
+
"id": f.rule.id,
|
|
64
|
+
"name": f.rule.title,
|
|
65
|
+
"shortDescription": {"text": f.rule.title},
|
|
66
|
+
"fullDescription": {"text": f"{f.rule.provider} credential attribution"},
|
|
67
|
+
"helpUri": f.rule.docs_url or "",
|
|
68
|
+
"properties": {
|
|
69
|
+
"provider": f.rule.provider,
|
|
70
|
+
"category": f.rule.category,
|
|
71
|
+
"capabilities": list(f.rule.capabilities),
|
|
72
|
+
"revoke_url": f.rule.revoke_url or "",
|
|
73
|
+
},
|
|
74
|
+
}
|
|
75
|
+
level = {"certain": "error", "likely": "error", "possible": "warning",
|
|
76
|
+
"unknown": "note", "placeholder": "none"}.get(f.confidence, "note")
|
|
77
|
+
results.append({
|
|
78
|
+
"ruleId": f.rule.id if f.rule else "KP0000-unknown-credential-shape",
|
|
79
|
+
"level": level,
|
|
80
|
+
"message": {"text": f"{f.title} ({f.confidence})"},
|
|
81
|
+
"locations": [{
|
|
82
|
+
"physicalLocation": {
|
|
83
|
+
"artifactLocation": {"uri": f.file},
|
|
84
|
+
"region": {"startLine": f.line_number, "startColumn": f.column},
|
|
85
|
+
}
|
|
86
|
+
}],
|
|
87
|
+
"partialFingerprints": {"kp/v1": _fingerprint(f)},
|
|
88
|
+
"properties": {"confidence": f.confidence, "evidence": [e.render() for e in f.evidence]},
|
|
89
|
+
})
|
|
90
|
+
doc = {
|
|
91
|
+
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
|
92
|
+
"version": "2.1.0",
|
|
93
|
+
"runs": [{
|
|
94
|
+
"tool": {"driver": {"name": "keyprint", "version": "0.1.0",
|
|
95
|
+
"informationUri": "https://github.com/gzhk9190/keyprint",
|
|
96
|
+
"rules": list(rules_meta.values())}},
|
|
97
|
+
"results": results,
|
|
98
|
+
}],
|
|
99
|
+
}
|
|
100
|
+
return _json.dumps(doc, indent=2)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _fingerprint(f: Finding) -> str:
|
|
104
|
+
import hashlib
|
|
105
|
+
basis = f"{f.file}|{f.line_number}|{f.provider}|{f.token[:2]}{f.token[-2:] if len(f.token) >= 4 else ''}"
|
|
106
|
+
return hashlib.sha256(basis.encode()).hexdigest()[:32]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def render_markdown(findings: list[Finding], show_secret: bool = False) -> str:
|
|
110
|
+
if not findings:
|
|
111
|
+
return "No findings.\n"
|
|
112
|
+
out = ["# keyprint findings", "", "| Secret | Provider | Confidence | Line | Evidence |", "|---|---|---|---|---|"]
|
|
113
|
+
for f in findings:
|
|
114
|
+
secret = f.token if show_secret else f.redacted
|
|
115
|
+
evidence = f.score.render_evidence().replace("|", "\\|")
|
|
116
|
+
out.append(f"| `{secret}` | {f.provider} | {f.confidence} | {f.file}:{f.line_number} | {evidence} |")
|
|
117
|
+
out.append("")
|
|
118
|
+
return "\n".join(out)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
RENDERERS = {
|
|
122
|
+
"text": render_text,
|
|
123
|
+
"json": render_json,
|
|
124
|
+
"sarif": render_sarif,
|
|
125
|
+
"markdown": render_markdown,
|
|
126
|
+
"md": render_markdown,
|
|
127
|
+
}
|