Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions packages/desktop-electron/src/main/logging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,42 @@ describe("desktop logging", () => {
expect(tail).toContain("Backend log")
expect(tail).toContain("backend failed")
})

test("bounds the tail to the most recent bytes of a large file", async () => {
logDir = mkdtempSync(join(tmpdir(), "pawwork-logging-test-"))
const mainPath = join(logDir, "main.log")
// Larger than the 512 KB byte cap so the oldest content falls outside the tail.
const filler = Array.from({ length: 60_000 }, (_, i) => `entry ${i}`).join("\n")
writeFileSync(mainPath, ["OLDEST_LINE", filler, "NEWEST_LINE"].join("\n"))
fakeLog.transports.file = {
maxSize: 0,
getFile: () => ({ path: mainPath }),
}

const { diagnosticsLogTail } = await import(`./logging?logging-test=${crypto.randomUUID()}`)
const tail = diagnosticsLogTail({})

expect(tail).toContain("NEWEST_LINE")
expect(tail).not.toContain("OLDEST_LINE")
// The main-log section is bounded by the byte-tail read (plus the section header), not the file.
expect(Buffer.byteLength(tail, "utf8")).toBeLessThanOrEqual(512 * 1024 + 4_096)
})

test("drops a mid-line fragment instead of emitting it before redaction", async () => {
logDir = mkdtempSync(join(tmpdir(), "pawwork-logging-test-"))
const mainPath = join(logDir, "main.log")
// A single line larger than the 512 KB byte cap with no newline: the byte tail starts mid-line.
// Emitting that fragment would feed redaction a prefix-less secret, so it must be dropped.
writeFileSync(mainPath, "S".repeat(600_000))
fakeLog.transports.file = {
maxSize: 0,
getFile: () => ({ path: mainPath }),
}

const { diagnosticsLogTail } = await import(`./logging?logging-test=${crypto.randomUUID()}`)
const tail = diagnosticsLogTail({})

expect(tail).toContain("(empty)")
expect(tail).not.toContain("S".repeat(100))
})
})
40 changes: 37 additions & 3 deletions packages/desktop-electron/src/main/logging.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import log from "electron-log/main.js"
import { readFileSync, readdirSync, statSync, unlinkSync } from "node:fs"
import { closeSync, fstatSync, openSync, readdirSync, readSync, statSync, unlinkSync } from "node:fs"
import { dirname, join } from "node:path"

const MAX_LOG_AGE_DAYS = 7
const TAIL_LINES = 1000
// Read at most this many bytes from the END of each log file. The main log rotates at 5 MB (maxSize
// below), but the backend log path is external and unbounded — without this a multi-GB log would
// load fully into memory just to take the tail. This also bounds any single line, so no separate
// per-line cap is needed (and a pre-redaction per-line cut would risk slicing a secret's prefix off).
const TAIL_MAX_BYTES = 512 * 1024
const CONSOLE_TRANSPORT_INITIALIZED = Symbol.for("pawwork.consoleTransportInitialized")

export function initLogging() {
Expand All @@ -29,10 +34,39 @@ export function diagnosticsLogTail(input: { backendLogPath?: string | null } = {
return sections.join("\n\n")
}

// Read up to maxBytes from the end of the file without loading the whole thing. truncatedHead is
// true when the file was larger, so the caller can drop the (likely partial) first line.
function readTailBytes(path: string, maxBytes: number): { text: string; truncatedHead: boolean } {
let fd: number | undefined
try {
fd = openSync(path, "r")
const size = fstatSync(fd).size
const readBytes = Math.min(size, maxBytes)
const start = size - readBytes
const buffer = Buffer.allocUnsafe(readBytes)
let offset = 0
while (offset < readBytes) {
const read = readSync(fd, buffer, offset, readBytes - offset, start + offset)
if (read <= 0) break
offset += read
}
return { text: buffer.toString("utf8", 0, offset), truncatedHead: start > 0 }
} finally {
if (fd !== undefined) closeSync(fd)
}
}

function tailFile(path: string): string {
try {
const contents = readFileSync(path, "utf8")
const lines = contents.split("\n")
const { text, truncatedHead } = readTailBytes(path, TAIL_MAX_BYTES)
const lines = text.split("\n")
// Started mid-file: the first line is a fragment (and may begin on a split multibyte char). Drop it
// even when it is the only line, so only COMPLETE lines are emitted — emitting a mid-line fragment,
// or head-cutting a long line here (before redaction), could leave a token with its recognizable
// prefix sliced off so the downstream redactor no longer matches it. A multi-line secret whose
// header (e.g. a PEM key's BEGIN) is stranded outside the window is handled at the redaction layer,
// which scrubs bare base64 key bodies directly (problem-report-redact.ts) — not by line surgery here.
if (truncatedHead) lines.shift()
return lines.slice(Math.max(0, lines.length - TAIL_LINES)).join("\n")
} catch {
return ""
Expand Down
93 changes: 93 additions & 0 deletions packages/desktop-electron/src/main/problem-report-redact.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,91 @@ describe("makeRedactor", () => {
expect(redact("url https://:plainsecretvalue@127.0.0.1/api")).not.toContain("plainsecretvalue")
})

test("redacts a bare multi-line base64 key body whose BEGIN header was truncated away", () => {
// A pre-redaction log tail can strand a key body without its header; the body-shape rule catches it.
const body = Array.from({ length: 8 }, () => "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3").join("\n")
const out = redact(`some log line\n${body}\nmore log`)
expect(out).not.toContain("MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3")
expect(out).toContain("[redacted-key-body]")
expect(out).toContain("some log line")
expect(out).toContain("more log")
})

test("redacts a stranded key body after PGP armor / encrypted-PEM header lines", () => {
// Header-agnostic: the body rule matches the base64 directly, so Version/Proc-Type lines don't shield it.
const body = Array.from({ length: 8 }, () => "lQOYBFB2k3IBCADHmQE7AgEAAkEAq2u3MIIBVQIBADANBgkqhkiG9w0").join("\n")
const pgp = redact(`Version: GnuPG v2\nComment: a comment\n\n${body}`)
expect(pgp).toContain("[redacted-key-body]")
expect(pgp).not.toContain("lQOYBFB2k3IBCADHmQE7AgEAAkEAq2u3MIIBVQIBADANBgkqhkiG9w0")
const enc = redact(`Proc-Type: 4,ENCRYPTED\nDEK-Info: AES-256-CBC,FEED\n\n${body}`)
expect(enc).toContain("[redacted-key-body]")
})

test("redacts a CRLF base64 key body", () => {
const body = Array.from({ length: 8 }, () => "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3").join("\r\n")
expect(redact(body)).toContain("[redacted-key-body]")
})

test("redacts a single stranded body line terminated by an orphaned private-key END", () => {
// BEGIN truncated away, only one full body line + a short line + END survive: the END signals a key,
// so the body is redacted even though the multi-line block rule alone would not fire on one line.
const full = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3"
const out = redact([full, "AQAB", "-----END RSA PRIVATE KEY-----"].join("\n"))
expect(out).toContain("[redacted-key]")
expect(out).not.toContain(full)
// A public certificate END is not a secret marker — its body is left intact.
const cert = redact(["aGVsbG8gd29ybGQgZm9vYmFyYmF6", "-----END CERTIFICATE-----"].join("\n"))
expect(cert).toContain("aGVsbG8gd29ybGQgZm9vYmFyYmF6")
})

test("redacts a body and END that share one physical line (newline-stripped serialization)", () => {
const body = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3"
const out = redact(`${body}-----END RSA PRIVATE KEY-----`)
expect(out).toContain("[redacted-key]")
expect(out).not.toContain(body)
})

test("redacts a stranded PGP body whose END is preceded by a =CRC checksum line", () => {
// ASCII-armored PGP keys end the body with a "=<4 base64 chars>" CRC-24 line before the END.
// That line starts with "=", so the body/short-line groups can't traverse it; the rule must hop it.
const body = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3"
const out = redact([body, "=aBcD", "-----END PGP PRIVATE KEY BLOCK-----"].join("\n"))
expect(out).toContain("[redacted-key]")
expect(out).not.toContain(body)
// Armor headers above the body are not secret and stay; everything from the body through END goes.
const armored = redact(
["Version: GnuPG v2", "", body, "=aBcD", "-----END PGP PRIVATE KEY BLOCK-----"].join("\n"),
)
expect(armored).toContain("Version: GnuPG v2")
expect(armored).toContain("[redacted-key]")
expect(armored).not.toContain(body)
})

test("redacts full body lines even when the last line is short (e.g. the AQAB exponent)", () => {
// A PEM body's final line is usually < 16 chars; it must not prevent matching the full lines above it.
const full = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3"
const out = redact([full, full, full, "AQAB"].join("\n"))
expect(out).toContain("[redacted-key-body]")
expect(out).not.toContain(full)
})

test("does not redact a single base64 line or inline base64 (a kept token/hash stays diagnostic)", () => {
// One base64 line is a token/id/hash; only a multi-line block is treated as a key body.
const inline = "id MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7 done"
expect(redact(inline)).toBe(inline)
const single = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3"
expect(redact(single)).toBe(single)
// A following plain word is not swallowed into the block.
expect(redact([single, single, "done note"].join("\n"))).toContain("done note")
})

test("does not backtrack on a long unbroken base64 run (no ReDoS)", () => {
const huge = "A".repeat(300_000)
const start = performance.now()
redact(huge)
expect(performance.now() - start).toBeLessThan(1_000)
})

test("redacts an over-long basic-auth password to an IP host (no length cap on the credential)", () => {
const longPass = "S".repeat(300)
expect(redact(`url https://user:${longPass}@127.0.0.1/api`)).not.toContain(longPass)
Expand Down Expand Up @@ -464,6 +549,8 @@ describe("sanitizeSessionInfo", () => {

describe("buildProblemReport redaction gate", () => {
test("the full uploaded report contains no seeded secret, path, username, or email", () => {
// A private-key body whose BEGIN header was stranded outside a pre-redaction log-tail truncation.
const strandedKeyBody = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAq2u3leiyKeyBody"
const logTail = [
`anthropic ${TOKENS.anthropic}`,
`aws ${TOKENS.aws} google ${TOKENS.google}`,
Expand All @@ -475,6 +562,10 @@ describe("buildProblemReport redaction gate", () => {
`url https://${USERNAME}:${TOKENS.basicPass}@internal.example.com/api`,
`email ${EMAIL}`,
`paths ${Object.values(PATHS).join(" ")}`,
strandedKeyBody,
strandedKeyBody,
strandedKeyBody,
strandedKeyBody,
].join("\n")

const report = buildProblemReport(
Expand Down Expand Up @@ -553,6 +644,8 @@ describe("buildProblemReport redaction gate", () => {
for (const sample of samples) {
expect(report.markdown, sample).not.toContain(sample)
}
// A bare key body stranded in the log tail (header truncated away) is scrubbed end-to-end.
expect(report.markdown).not.toContain(strandedKeyBody)
// The rogue rendererError field was dropped, not carried through.
expect(report.markdown).not.toContain("extra-field-secret-7f3a")
// The renderer summary (not just events) is scrubbed.
Expand Down
28 changes: 28 additions & 0 deletions packages/desktop-electron/src/main/problem-report-redact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,34 @@ const SECRET_REPLACERS: Array<(value: string) => string> = [
/-----BEGIN[A-Z0-9 ]{0,40}PRIVATE[A-Z0-9 ]{0,40}-----[\s\S]*?(?:-----END[A-Z0-9 ]{0,40}-----|$)/g,
"[redacted-key]",
),
// Bare multi-line base64 block (the wrapped body of a PEM/PGP key). The BEGIN-keyed rule above only
// fires when the header is present, but a pre-redaction truncation of an unbounded log (logging.ts
// byte/line tail) can strand a key body without its BEGIN — leaving headerless base64 the rule misses.
// Matching the body shape directly is header-agnostic: it covers a body stranded after armor lines
// (PGP Version/Comment, encrypted-PEM Proc-Type/DEK-Info), with or without an END, and CRLF logs. The
// run is >= 2 WHOLE lines of only base64 (>= 16 chars each), so a single base64 line (a token/hash/id
// kept for diagnostics) and inline base64 (a quoted literal) are untouched. Every MATCHED line needs
// >= 16 chars so a trailing word ("done") is never eaten; the line-start anchor plus the per-line
// length floor keep it linear (no catastrophic backtracking on a long non-base64 run). This runs
// before the orphan-END rule so a long body is consumed here as one match, not chewed line by line.
(v) =>
v.replace(
/(^|\n)(?:[A-Za-z0-9+/]{16,}={0,2}\r?\n){1,}[A-Za-z0-9+/]{16,}={0,2}(?=\r?\n|$)/g,
"$1[redacted-key-body]",
),
// Orphaned private-key END: the BEGIN rule consumed every complete BEGIN..END block, so a surviving
// "-----END ... PRIVATE ... -----" had its BEGIN truncated away. Redact the contiguous body above it
// through the END — this catches even a SINGLE stranded body line that the >= 2-line block rule misses
// (the END is the signal). The body can be preceding whole lines, a short final line, an optional PGP
// "=CRC" checksum line, and a same-physical-line base64 run right before the END (a log that serialized
// the key without a newline between body and END). Anchored at a line start with per-line length floors
// so it stays linear; only a PRIVATE END triggers it (a public CERTIFICATE body is not secret), and a
// real private-key END never follows unrelated base64, so the body match cannot eat legitimate content.
(v) =>
v.replace(
/(^|\n)(?:[A-Za-z0-9+/]{16,}={0,2}\r?\n)*(?:[A-Za-z0-9+/]{1,}={0,2}\r?\n)?(?:=[A-Za-z0-9+/]{1,6}\r?\n)?[ \t]*[A-Za-z0-9+/]*={0,2}[ \t]*-----END[A-Z0-9 ]{0,40}PRIVATE[A-Z0-9 ]{0,40}-----/g,
"$1[redacted-key]",
),
// URL basic-auth credentials. The username is optional ([^/@\s:]*) so `scheme://:pass@host` and
// IP hosts are covered, not only `scheme://user:pass@host`. ONLY the scheme length is bounded
// ([a-z0-9+.-]{0,40}): the scheme is unanchored, so an unbounded greedy run scans for "://" from
Expand Down
Loading