repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(leaks): surface protected values in status

009380896a42156a1171e4c532a6a66771314547

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (8)

extensions/leaks/SPEC.md

Modified
481 481 Do not spam per secret.
482 482 Notify once per provider turn with an aggregate summary when new leak values are found.
483 483 Show safe metadata only.
484 -Footer/status must show enabled/off plus last provider redaction count.
484 +Footer/status must show enabled/degraded plus cumulative provider-bound protected-value count.
486 486 Commands remain operational controls and diagnostics:
502 502 - placeholder mapping count
503 503 - last provider redaction count
504 504 - total provider redaction count
505 +- total provider-bound protected-value count
505 506 - recent safe redaction labels
506 507 - latest safe placeholder tags, not secret values

extensions/leaks/__tests__/__snapshots__/demo-corpus.test.ts.snap

Modified
434 434 "fixtureClass": "cloud",
435 - "labels": [],
436 - "redactionCount": 0,
435 + "labels": [
436 + "HCLOUD_TOKEN",
437 + ],
438 + "redactionCount": 1,
437 439 "relativePath": "cloud/linode-hcloud-scaleway.env",
438 440 "restoredExactly": true,
439 - "spans": [],
441 + "spans": [
443 + "end": 155,
444 + "labels": [
445 + "HCLOUD_TOKEN",
446 + ],
447 + "start": 91,
448 + },
449 + ],
442 452 "fixtureClass": "cloud",

extensions/leaks/__tests__/pi-direct.test.ts

Modified
82 82 describe("leaks direct Pi hooks", () => {
83 + it("marks persistence degradation in the status footer", async () => {
84 + const runtime = fakePi();
85 + leaks(runtime.pi as never);
86 + const view = ui();
87 + const ctx = {
88 + ...view.ctx,
89 + sessionManager: {
90 + getBranch: () => [
91 + {
92 + type: "custom",
93 + customType: "leaks-generation-v99",
94 + data: {},
95 + },
96 + ],
97 + getSessionFile: () => undefined,
98 + },
99 + };
101 + await runtime.handlers.get("session_start")?.({}, ctx);
102 + expect(view.statuses.at(-1)).toBe("󰀦 degraded  0");
103 + });
83 105 it("covers hooks and commands with and without UI", async () => {
84 106 const runtime = fakePi();
85 107 leaks(runtime.pi as never);
87 109 const view = ui(false);
89 111 await runtime.handlers.get("session_start")?.({}, view.ctx);
90 - expect(view.statuses.at(-1)).toContain("leaks on");
112 + expect(view.statuses.at(-1)).toBe("󰒘  0");
91 113 await runtime.handlers.get("session_start")?.(
93 115 { ...view.ctx, hasUI: false },
108 130 view.ctx,
110 132 expect(JSON.stringify(context)).not.toContain(secret);
133 + expect(view.statuses.at(-1)).toMatch(/^󰒘  [1-9]/);
111 134 const providerClean = await runtime.handlers.get(
112 135 "before_provider_request",
113 136 )?.({ payload: { text: "clean" } }, view.ctx);

extensions/leaks/__tests__/structures.test.ts

Modified
88 + it("redacts an HCloud token only in exact key context", () => {
89 + const engine = new __test.LeaksEngine();
90 + const token = "A1".repeat(32);
92 + for (const sample of [
93 + `1: hcloud_token = "${token}" ssh_public_key = "ssh-ed25519 public"`,
94 + `TF_VAR_HCLOUD_TOKEN=${token}`,
95 + ]) {
96 + expect(engine.redactText(sample, "provider").text).not.toContain(token);
97 + }
98 + expect(
99 + engine.redactText(`deployment_id = "${token}"`, "provider").text,
100 + ).toContain(token);
101 + expect(
102 + engine.redactText(`hcloud_token = "${token.slice(1)}"`, "provider").text,
103 + ).toContain(token.slice(1));
104 + });
88 106 it("redacts shell header value without redacting whole command", () => {
89 107 const engine = new __test.LeaksEngine();
90 108 const result = engine.redactText(

extensions/leaks/src/engine.ts

Modified
46 46 private learned: LearnedValue[] = [];
47 47 private lastProviderRedactionCount = 0;
48 48 private totalProviderRedactionCount = 0;
49 + private totalProtectedRedactionCount = 0;
49 50 private lastProviderAmbiguityCount = 0;
50 51 private recentLabels: string[] = [];
51 52 private latestTags: string[] = [];
130 131 const count = placeholders.length;
132 + if (origin === "context" || origin === "provider")
133 + this.totalProtectedRedactionCount += count;
131 134 if (origin === "provider") {
132 135 this.lastProviderRedactionCount = count;
133 136 this.lastProviderAmbiguityCount = ambiguities.length;
318 321 persistenceEnabled: this.placeholders.stats().persistenceEnabled,
319 322 lastProviderRedactionCount: this.lastProviderRedactionCount,
320 323 totalProviderRedactionCount: this.totalProviderRedactionCount,
324 + totalProtectedRedactionCount: this.totalProtectedRedactionCount,
321 325 lastProviderAmbiguityCount: this.lastProviderAmbiguityCount,
322 326 recentLabels: [...this.recentLabels],
323 327 latestTags: [...this.latestTags],

extensions/leaks/src/pi.ts

Modified
21 21 engine.reload(ctx.cwd, readSettings(ctx.cwd), process.env);
22 22 notifyInMemorySession(ctx, reportedWarnings);
23 23 flushWarnings(engine, ctx, reportedWarnings);
24 - try {
25 - if (ctx.hasUI)
26 - ctx.ui.setStatus(
27 - "leaks",
28 - `leaks ${engine.stats().persistenceEnabled ? "on" : "degraded"} | last 0`,
29 - );
30 - } catch {
31 - // Status is best-effort.
32 - }
24 + updateLeakStatus(ctx, engine);
35 27 pi.on("session_tree", async (_event, ctx) => {
37 29 flushWarnings(engine, ctx, reportedWarnings);
40 - pi.on("context", async (event) => {
41 - return { messages: engine.redactDeep(event.messages, "context").value };
32 + pi.on("context", async (event, ctx) => {
33 + const result = engine.redactDeep(event.messages, "context");
34 + updateLeakStatus(ctx, engine);
35 + return { messages: result.value };
44 38 pi.on("before_provider_request", async (event, ctx) => {
182 176 type RedactionResult = ReturnType<LeaksEngine["redactDeep"]>;
178 +function updateLeakStatus(ctx: ExtensionContext, engine: LeaksEngine) {
179 + try {
180 + if (!ctx.hasUI) return;
181 + const stats = engine.stats();
182 + const status = stats.persistenceEnabled
183 + ? `󰒘  ${stats.totalProtectedRedactionCount}`
184 + : `󰀦 degraded  ${stats.totalProtectedRedactionCount}`;
185 + ctx.ui.setStatus("leaks", status);
186 + } catch {
187 + // Status is best-effort.
184 191 function updateProviderUi(
185 192 ctx: ExtensionContext,
186 193 engine: LeaksEngine,
200 207 if (newActionable.length > 0)
201 208 notify(ctx, formatAmbiguities(newActionable), "warning");
202 209 if (!ctx.hasUI) return;
203 - ctx.ui.setStatus(
204 - "leaks",
205 - `leaks ${engine.stats().persistenceEnabled ? "on" : "degraded"} | last ${result.count}`,
206 - );
210 + updateLeakStatus(ctx, engine);
207 211 if (result.count === 0) return;
208 212 const newPlaceholders = result.redactions
209 213 .flatMap((r) => r.placeholders)
515 519 `mappings: ${stats.mappingCount}`,
516 520 `last provider redactions: ${stats.lastProviderRedactionCount}`,
517 521 `total provider redactions: ${stats.totalProviderRedactionCount}`,
522 + `total protected redactions: ${stats.totalProtectedRedactionCount}`,
518 523 `last provider ambiguities: ${stats.lastProviderAmbiguityCount}`,
519 524 `recent labels: ${stats.recentLabels.map(noticeLabel).join(", ")}`,
520 525 `latest tags: ${stats.latestTags.join(", ")}`,

extensions/leaks/src/structures.ts

Modified
223 223 const value = match[2] as string;
224 224 if (ASSIGNMENT_STOP_KEYS.has(key.toLowerCase())) continue;
225 225 if (!isSensitiveKey(key)) continue;
226 - if (isCodeReference(value)) continue;
227 - if (!highConfidenceSecretShape(value)) continue;
226 + const hcloudToken = isHCloudTokenAssignment(key, value);
227 + if (isCodeReference(value) && !hcloudToken) continue;
228 + if (!highConfidenceSecretShape(value) && !hcloudToken) continue;
228 229 spans.push(
229 230 makeSpan(match, 2, value, [label(key, "structure")], "structure"),
301 +function isHCloudTokenAssignment(key: string, value: string) {
302 + const normalized = key.replaceAll(/[-_]/g, "").toLowerCase();
303 + return (
304 + (normalized === "hcloudtoken" || normalized === "tfvarhcloudtoken") &&
305 + /^[A-Za-z0-9]{64}$/.test(value)
306 + );
300 309 function isCodeReference(value: string) {
301 310 const text = value.trim();
302 311 return (

extensions/leaks/src/types.ts

Modified
79 79 persistenceEnabled: boolean;
80 80 lastProviderRedactionCount: number;
81 81 totalProviderRedactionCount: number;
82 + totalProtectedRedactionCount: number;
82 83 lastProviderAmbiguityCount: number;
83 84 recentLabels: string[];
84 85 latestTags: string[];