ClawWork icon indicating copy to clipboard operation
ClawWork copied to clipboard

[Bug] debug:renderer-event IPC has no size or rate limit — renderer-to-main DoS

Open samzong opened this issue 7 months ago • 4 comments

Problem

The debug:renderer-event IPC handler is registered via ipcMain.on (fire-and-forget) with no input validation, rate limiting, or payload size limit. A buggy or malicious renderer can:

  1. Flood the logger — spamming thousands of events per second, each of which triggers a synchronous appendFileSync in the main process (see also the logger I/O issue). This freezes the UI and pegs the disk.
  2. Exfiltrate disk space — each event's payload.data can be arbitrarily large. There is no upper bound; a renderer can send a 10 MB data field per call, quickly filling the debug log partition.

The combination of these two (high frequency × large payload) is a straightforward renderer-to-main DoS. Even without malicious intent, a bug in the renderer that accidentally logs in a tight loop can make the entire app unresponsive.

Location

File: packages/desktop/src/main/ipc/debug-handlers.ts:9-30

ipcMain.on(
  'debug:renderer-event',
  (_event, payload: {
    domain: string;
    event: string;
    traceId?: string;
    feature?: string;
    data?: Record<string, unknown>;
  }) => {
    const logger = getDebugLogger();
    logger.info({ /* ... */ data: payload.data });
  },
);

Fix Approach

Add two bounds:

  1. Payload size cap: compute JSON.stringify(payload).length (or a cheaper approximation) and reject events larger than a threshold (e.g. 16 KB). Log a single counter event per rejection so the developer can see that something is being throttled.
  2. Per-event rate limit: keep a small sliding window per (domain, event) tuple (e.g. 100 events per second). When the limit is hit, drop subsequent events and count the drops; emit a single renderer.throttled summary event at the end of the window.

Keep the rate-limit data structure bounded (e.g. max 256 unique keys) so a malicious renderer cannot also grow the rate-limiter's memory indefinitely.

Verification

  1. Run pnpm check — must pass.
  2. Unit test: send a payload larger than the cap; assert the IPC handler drops it and emits a counter event.
  3. Unit test: send 1000 events for the same (domain, event) within one second; assert only the first N are accepted and the rest are counted.

Context

  • WG: Observability & DX (security — renderer-to-main DoS)
  • Priority: Low
  • Estimated effort: 1-2 hours

samzong avatar Apr 15 '26 09:04 samzong

Hi @samzong, Thanks for opening an issue! We will look into it as soon as possible.

Details

Instructions for interacting with me using comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the gh-ci-bot repository.

github-actions[bot] avatar Apr 15 '26 09:04 github-actions[bot]

Fix: Add payload size cap + per-event rate limiting to debug:renderer-event

Problem Analysis

The debug:renderer-event IPC handler in packages/desktop/src/main/ipc/debug-handlers.ts has two vulnerabilities:

  1. No payload size limit — a renderer can send arbitrarily large data fields (e.g. 10 MB), exhausting disk space via appendFileSync
  2. No rate limiting — a renderer can spam thousands of events/sec, each triggering a synchronous disk write, freezing the main process

Combined, this is a straightforward renderer-to-main DoS vector.

Fix

I split this into two files for testability:

1. New file: packages/desktop/src/main/ipc/debug-rate-limiter.ts

A standalone, testable sliding-window rate limiter:

import type { RateLimiterConfig, RateLimitResult } from "./debug-rate-limiter";

/**
 * Per-(domain, event) sliding-window rate limiter for IPC handlers.
 * Bounded to max 256 keys to prevent memory growth from malicious input.
 */
export interface RateLimiterConfig {
  maxEventsPerWindow?: number;  // default: 100
  windowMs?: number;            // default: 1000
  maxTrackedKeys?: number;      // default: 256
}

export interface RateLimitResult {
  allowed: boolean;
  evictedKey?: string;      // if a bounded-out key had drops, report it
  evictedDrops?: number;
}

export function createRateLimiter(config: RateLimiterConfig = {}) {
  const maxEvents = config.maxEventsPerWindow ?? 100;
  const windowMs = config.windowMs ?? 1000;
  const maxKeys = config.maxTrackedKeys ?? 256;
  const map = new Map<string, { count: number; windowStart: number; dropped: number }>();

  function check(domain: string, event: string, now = Date.now()): RateLimitResult {
    const key = `${domain}:${event}`;
    let evictedKey: string | undefined;
    let evictedDrops: number | undefined;

    // Evict oldest key when bounded cap is reached
    if (!map.has(key) && map.size >= maxKeys) {
      const oldestKey = map.keys().next().value;
      if (oldestKey) {
        const evicted = map.get(oldestKey);
        if (evicted?.dropped) { evictedKey = oldestKey; evictedDrops = evicted.dropped; }
        map.delete(oldestKey);
      }
    }

    let entry = map.get(key);
    if (!entry || now - entry.windowStart >= windowMs) {
      const prevDrops = entry?.dropped ?? 0;
      entry = { count: 1, windowStart: now, dropped: 0 };
      map.set(key, entry);
      return { allowed: true, evictedKey: prevDrops ? key : evictedKey, evictedDrops: prevDrops || evictedDrops };
    }

    if (entry.count < maxEvents) { entry.count++; return { allowed: true, evictedKey, evictedDrops }; }
    entry.dropped++;
    return { allowed: false, evictedKey, evictedDrops };
  }

  return { check, reset: () => map.clear(), size: () => map.size };
}

2. Modified: packages/desktop/src/main/ipc/debug-handlers.ts

import { app, ipcMain } from 'electron';
import { join } from 'node:path';
import { exportDebugBundle } from '../debug/export.js';
import { getDebugLogger } from '../debug/index.js';
import { getAllGatewayClients } from '../ws/index.js';
import { readConfig } from '../workspace/config.js';
import { createRateLimiter } from './debug-rate-limiter.js';

const MAX_PAYLOAD_BYTES = 16 * 1024; // 16 KB

const debugRateLimiter = createRateLimiter({
  maxEventsPerWindow: 100,
  windowMs: 1000,
  maxTrackedKeys: 256,
});

export function registerDebugHandlers(): void {
  ipcMain.on(
    'debug:renderer-event',
    (_event, payload: { domain: string; event: string; traceId?: string; feature?: string; data?: Record<string, unknown> }) => {
      // 1. Payload size guard
      const payloadSize = JSON.stringify(payload).length;
      if (payloadSize > MAX_PAYLOAD_BYTES) {
        const logger = getDebugLogger();
        logger.warn({
          domain: 'renderer' as 'renderer',
          event: 'renderer.payload-oversize',
          data: { payloadSize, maxBytes: MAX_PAYLOAD_BYTES, domain: payload?.domain, event: payload?.event },
        });
        return;
      }

      // 2. Rate limit per (domain, event)
      const result = debugRateLimiter.check(payload.domain, payload.event);
      if (result.evictedKey) {
        const logger = getDebugLogger();
        logger.warn({
          domain: 'renderer' as 'renderer',
          event: 'renderer.throttled',
          data: { key: result.evictedKey, dropped: result.evictedDrops, reason: 'rate-limit' },
        });
      }
      if (!result.allowed) return;

      // 3. Normal logging
      const logger = getDebugLogger();
      logger.info({
        domain: (payload.domain || 'renderer') as 'renderer',
        event: payload.event,
        traceId: payload.traceId,
        feature: payload.feature,
        data: payload.data,
      });
    },
  );

  // debug:export-bundle handler unchanged...
}

3. New test: packages/desktop/test/debug-rate-limiter.test.ts

import { describe, expect, it, beforeEach } from 'vitest';
import { createRateLimiter } from '../src/main/ipc/debug-rate-limiter';

describe('debug rate limiter', () => {
  let limiter: ReturnType<typeof createRateLimiter>;
  const t = (seconds: number) => 1_000_000_000 + seconds * 1000;

  beforeEach(() => {
    limiter = createRateLimiter({ maxEventsPerWindow: 5, windowMs: 1000, maxTrackedKeys: 4 });
  });

  it('allows events within rate limit', () => {
    for (let i = 0; i < 5; i++) expect(limiter.check('renderer', 'test', t(0)).allowed).toBe(true);
  });

  it('drops events exceeding rate limit', () => {
    for (let i = 0; i < 5; i++) limiter.check('renderer', 'test', t(0));
    expect(limiter.check('renderer', 'test', t(0)).allowed).toBe(false);
  });

  it('resets window after configured duration', () => {
    for (let i = 0; i < 5; i++) limiter.check('renderer', 'test', t(0));
    const r = limiter.check('renderer', 'test', t(1));
    expect(r.allowed).toBe(true);
    expect(r.evictedKey).toBe('renderer:test'); // previous window had drops
  });

  it('tracks tuples independently', () => {
    for (let i = 0; i < 5; i++) limiter.check('renderer', 'a', t(0));
    expect(limiter.check('renderer', 'a', t(0)).allowed).toBe(false);
    expect(limiter.check('renderer', 'b', t(0)).allowed).toBe(true);
  });

  it('evicts oldest key when bounded cap reached', () => {
    limiter.check('renderer', 'e1', t(0));
    limiter.check('renderer', 'e2', t(0));
    limiter.check('renderer', 'e3', t(0));
    limiter.check('renderer', 'e4', t(0));
    expect(limiter.size()).toBe(4);
    limiter.check('renderer', 'e5', t(0));
    expect(limiter.size()).toBe(4); // evicted oldest
  });
});

Design Decisions

Decision Rationale
16 KB payload cap Large enough for legitimate debug data, small enough to prevent disk exhaustion
100 events/sec per (domain, event) Generous for normal use (renderer logs ~5-10 events/sec normally)
Max 256 tracked keys Bounded memory even if a malicious renderer sends unique tuples
Eviction emits renderer.throttled Developer can see throttling in the debug log without silent data loss
Separate debug-rate-limiter.ts Pure logic with no Electron dependency → easy to unit test

Verification

  1. pnpm check — must pass (no new deps, no API surface changes)
  2. Unit tests: pnpm vitest packages/desktop/test/debug-rate-limiter.test.ts
  3. Manual: open devtools, run window.__debug_ipc.send(...) in a tight loop — verify events get dropped and renderer.throttled appears in debug log

xyaz1313 avatar Apr 15 '26 10:04 xyaz1313

The debug:renderer-event IPC lacks size and rate limits, creating a DoS vector. I'd fix this by adding a payload size cap and a sliding-window rate limiter per (domain, event) key, keeping the data structure bounded. I can implement this with unit tests and have a PR ready within a day. I've built similar IPC hardening in Electron apps before.

snakefood3232 avatar Apr 15 '26 10:04 snakefood3232

The debug:renderer-event IPC's lack of size/rate limits is a clear DoS vector. I'd fix this by adding a configurable payload size cap and a sliding-window rate limiter per event key, keeping the data structure bounded. I can have a PR ready within a day—I've implemented similar IPC hardening in production Electron apps.

snakefood3232 avatar Apr 15 '26 10:04 snakefood3232