repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(leaks): parse structured secret candidates

baf0004dc1a3dfb42fa2d55bfbc971f110374001

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (3)

+97 / −32 text lines

Diff layout

extensions/leaks/__tests__/false-positives.test.ts

Modified

+17 / −0 text lines

3030 for (const value of negatives) expect(redacted(value)).toBe(value);
3131 });
33 it("keeps source code and complete-name near misses visible", () => {
34 const ordinary = ["ordinary", "metadata", "value", "123456"].join("-");
35 const negatives = [
36 ["agendaFlick", "visibleArea", "yPosition"].join("."),
37 ["application/vnd", "openxmlformats-officedocument", "sheet"].join("."),
38 `const STATUS_KEY = "${ordinary}";`,
39 `const COOKIE = "${ordinary}";`,
40 `const result = { session: runtimeSession };`,
41 'function sum(key: "additions" | "deletions") {}',
42 ["https://example.test/?mon", `key=${ordinary}`].join(""),
43 ["Cookie", `: keyboard=${ordinary}`].join(""),
44 ["<session>", ordinary, "</session>"].join(""),
45 ];
47 for (const value of negatives) expect(redacted(value), value).toBe(value);
48 });
3350 it("still redacts high-confidence provider-specific patterns", () => {
3451 const value = "ghp_" + "A".repeat(36);
3552 expect(redacted(value)).not.toBe(value);

extensions/leaks/__tests__/structures.test.ts

Modified

+42 / −25 text lines

6262 expect(result.text.includes(secret)).toBe(false);
6363 });
65 it("redacts assignment values across common one-line syntaxes", () => {
65 it("redacts only provider-shaped assignment values", () => {
6666 const engine = new __test.LeaksEngine();
67 const samples = [
68 `TOKEN=${secret}`,
69 `token=${secret}`,
70 `token: ${secret}`,
71 `"token": "${secret}"`,
72 `token = "${secret}"`,
73 `<token>${secret}</token>`,
74 `export TOKEN=${secret}`,
75 ];
77 for (const sample of samples) {
78 const result = engine.redactText(sample, "provider");
79 expect(result.text.includes(secret)).toBe(false);
80 expect(result.text.toLowerCase(), sample).toContain("token".slice(0, 3));
67 const shaped = "ghp_" + "A".repeat(36);
68 for (const sample of [
69 `TOKEN=${shaped}`,
70 `token: ${shaped}`,
71 `"token": "${shaped}"`,
72 `<token>${shaped}</token>`,
73 ]) {
74 expect(engine.redactText(sample, "provider").text).not.toContain(shaped);
8175 }
76 expect(engine.redactText(`TOKEN=${secret}`, "provider").text).toContain(
77 secret,
78 );
8279 });
8481 it("redacts shell header value without redacting whole command", () => {
9390 expect(result.text.includes(secret)).toBe(false);
9491 });
93 it("requires decoded JWT objects", () => {
94 const dotted = ["agendaFlick", "visibleArea", "yPosition"].join(".");
95 expect(__test.findJwtSpans(dotted)).toEqual([]);
96 expect(__test.findJwtSpans(jwt).map((span) => span.value)).toEqual([jwt]);
97 });
99 it("uses complete query and cookie names", () => {
100 const ordinary = ["ordinary", "metadata", "value", "123456"].join("-");
101 expect(
102 __test.findSensitiveQuerySpans(
103 ["?mon", `key=${ordinary}`].join(""),
104 ),
105 ).toEqual([]);
106 expect(
107 __test.findCookieSpans(["Cookie", `: keyboard=${ordinary}`].join("")),
108 ).toEqual([]);
109 expect(
110 __test.findSensitiveQuerySpans(`?token=${secret}`).map((span) => span.value),
111 ).toEqual([secret]);
112 expect(
113 __test
114 .findCookieSpans(["Cookie", `: session=${secret}`].join(""))
115 .map((span) => span.value),
116 ).toEqual([secret]);
117 });
96119 it("redacts JWTs and private keys as whole spans", () => {
97120 const engine = new __test.LeaksEngine();
98121 const jwtResult = engine.redactText(`jwt=${jwt}`, "provider");
157180 }
158181 });
160 it("stoplist does not block keys that overlap with SENSITIVE", () => {
161 const longValue = "abcdef1234567890";
162 // 'key' is in dotenv.SENSITIVE; assignment detection must still match.
163 expect(
164 __test.findAssignmentSpans(`KEY=${longValue}`).length,
165 ).toBeGreaterThan(0);
166 // 'token' is in dotenv.SENSITIVE; assignment detection must still match.
167 expect(
168 __test.findAssignmentSpans(`TOKEN=${longValue}`).length,
169 ).toBeGreaterThan(0);
183 it("keeps ambiguous sensitive-name assignments visible", () => {
184 const ordinary = "abcdef1234567890";
185 expect(__test.findAssignmentSpans(`KEY=${ordinary}`)).toEqual([]);
186 expect(__test.findAssignmentSpans(`TOKEN=${ordinary}`)).toEqual([]);
170187 });
172189 it("stoplist is case-insensitive for common programming nouns", () => {

extensions/leaks/src/structures.ts

Modified

+38 / −7 text lines

8484export function findSensitiveQuerySpans(text: string): SecretSpan[] {
8585 const spans: SecretSpan[] = [];
8686 for (const match of text.matchAll(QUERY_RE)) {
87 const name = match[2] as string;
8788 const value = match[3] as string;
88 if (isWeakValue(value)) continue;
89 if (!isSensitiveKey(name) || isWeakValue(value)) continue;
8990 spans.push(
9091 makeSpan(
9192 match,
155156 if (ASSIGNMENT_STOP_KEYS.has(key.toLowerCase())) continue;
156157 if (!isSensitiveKey(key)) continue;
157158 if (isCodeReference(value)) continue;
158 if (isWeakValue(value) && !highConfidenceSecretShape(value)) continue;
159 if (!highConfidenceSecretShape(value)) continue;
159160 spans.push(
160161 makeSpan(match, 2, value, [label(key, "structure")], "structure"),
161162 );
167168export function findJwtSpans(text: string): SecretSpan[] {
168 return [...text.matchAll(JWT_RE)].map((match) => {
169 const spans: SecretSpan[] = [];
170 for (const match of text.matchAll(JWT_RE)) {
171 const [headerPart, payloadPart, signaturePart] = match[0].split(".");
172 if (!headerPart || !payloadPart || !strictBase64Url(signaturePart)) continue;
173 const header = decodeJsonObject(headerPart);
174 const payload = decodeJsonObject(payloadPart);
175 if (!header || !payload || typeof header.alg !== "string" || !header.alg)
176 continue;
169177 const start = match.index as number;
170 return {
178 spans.push({
171179 start,
172180 end: start + match[0].length,
173181 value: match[0],
175183 kind: "jwt",
176184 confidence: 100,
177185 wholeSpan: true,
178 };
179 });
186 });
187 }
188 return spans;
189}
191function strictBase64Url(value: string | undefined) {
192 if (!value || !/^[A-Za-z0-9_-]+$/.test(value)) return false;
193 return Buffer.from(value, "base64url").toString("base64url") === value;
194}
196function decodeJsonObject(value: string) {
197 if (!strictBase64Url(value)) return undefined;
198 try {
199 const bytes = Buffer.from(value, "base64url");
200 const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
201 const parsed: unknown = JSON.parse(text);
202 if (!isPlainRecord(parsed)) return undefined;
203 return parsed;
204 } catch {
205 return undefined;
206 }
207}
209function isPlainRecord(value: unknown): value is Record<string, unknown> {
210 return value !== null && typeof value === "object" && !Array.isArray(value);
182213export function findPrivateKeySpans(text: string): SecretSpan[] {
257288function isSensitiveCookie(name: string) {
258 return /(?:session|token|auth|secret|key|jwt)/i.test(name);
289 return isSensitiveKey(name);