Skip to content

AI, fully local on your computer.

18.6 KB
Raw Blame
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { mkdtempSync, readdirSync, readFileSync, existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import * as ocrFactory from '../../src/main/services/ocr/factory'

// Security sentinel for the vision path (image-understanding plan §13/§17, CLAUDE.md §0):
//   1. LOOPBACK ONLY — the sidecar fetch must only ever connect to 127.0.0.1; no remote host is
//      introduced (the offline guard exempts loopback precisely so this local socket is allowed).
//   2. NO CONTENT IN THE LOG — a recognizable prompt + answer + image byte pattern pushed through
//      analyze must NOT appear in any diagnostics-log call (only friendly codes / stderr tails).
//   3. NO VISION AUDIT ROWS — the vision path writes ZERO audit events (ctx.audit is never called).

const ipcState = vi.hoisted(() => ({ handlers: new Map<string, unknown>() }))
vi.mock('electron', () => ({
  ipcMain: {
    handle: (channel: string, fn: unknown) => ipcState.handlers.set(channel, fn),
    removeHandler: (channel: string) => ipcState.handlers.delete(channel)
  },
  BrowserWindow: { getFocusedWindow: () => null },
  dialog: { showOpenDialog: async () => ({ canceled: true, filePaths: [] }) }
}))

import { registerImagesIpc } from '../../src/main/ipc/registerImagesIpc'
import { openDatabase } from '../../src/main/services/db'
import { testCipher } from '../helpers/test-cipher'
import { VisionService } from '../../src/main/services/vision'
import { VisionRuntime } from '../../src/main/services/vision/runtime'
import { log } from '../../src/main/services/logging'
import { IPC, STREAM } from '../../src/shared/ipc'
import type { ImageAnalyzeRequest, ImageJob, VisionStatus } from '../../src/shared/types'
import type { AppContext } from '../../src/main/services/context'
import { ANY_SENDER, invoke, invokeWithEvent, makeEvent, type IpcHandlers } from '../helpers/ipc'
import { until, untilValue } from '../helpers/hang-budget'
import { fakeSpawn, sseBody } from '../helpers/fake-sidecar'
import { pngHeader } from '../helpers/image-fixtures'
import { workspaceStandIn } from '../helpers/workspace-stand-in'

const handlers = ipcState.handlers as unknown as IpcHandlers

// Recognizable sentinels — no real prompt/answer/image would contain these exact strings.
const SENTINEL_PROMPT = 'ZZSENTINELZZ what is the secret account number in this image'
const SENTINEL_ANSWER = 'ZZSENTINELZZ the secret account number is 4444-3333-2222'
// A parseable PNG header (SEC-6 rejects a claimed png whose header won't parse) + a unique tail
// for the leak checks.
const SENTINEL_BYTES = pngHeader(2, 2, [0xab, 0xcd, 0xef, 0x10, 0x20, 0x30])

/** A minimal chat-identical SSE stream carrying the sentinel answer in one delta. */
const SENTINEL_SSE =
  `data: {"choices":[{"finish_reason":null,"index":0,"delta":{"content":${JSON.stringify(SENTINEL_ANSWER)}}}]}\n\n` +
  'data: [DONE]\n\n'

const AVAILABLE: VisionStatus = { available: true, modelId: 'vlm', modelDisplayName: 'VLM' }

// A real (temp) workspace + db + cipher so the NEW history persistence runs for real (the
// content-free-log + no-audit guarantees must hold even WITH persistence — see TEST-3, which
// asserts the stored image rests ENCRYPTED). A fresh temp root per call keeps tests isolated.
function ctxFor(
  audit: ReturnType<typeof vi.fn>,
  rootPath = mkdtempSync(join(tmpdir(), 'hilbertraum-vision-sec-'))
): AppContext {
  const cipher = testCipher()
  return {
    trustedSenders: ANY_SENDER,
    paths: { rootPath, workspacePath: rootPath },
    db: openDatabase(join(rootPath, 'hilbertraum.sqlite')),
    manifestsDir: null,
    isDev: false,
    workspace: workspaceStandIn({ documentCipher: cipher }),
    audit
  } as unknown as AppContext
}

const sentinelReq = (): ImageAnalyzeRequest => ({
  imageBytes: SENTINEL_BYTES,
  mimeType: 'image/png',
  question: SENTINEL_PROMPT
})

async function waitForTerminal(jobId: string): Promise<ImageJob> {
  return untilValue(async () => {
    const job = (await invoke(handlers, IPC.imageGetJob, jobId)).result as ImageJob
    return job.state === 'done' || job.state === 'failed' || job.state === 'cancelled' ? job : undefined
  }, 'the vision job reaching a terminal state')
}

/**
 * Persistence is async: wait for the streamed done event before inspecting the rows.
 *
 * Throws BY NAME rather than falling through. The counted loop this replaces did the latter,
 * so when it ran out on a starved CI worker the next assertion failed with an opaque
 * `expected [] to have a length of 1` instead of saying what had not happened (#458, run
 * 34664328086). It is bounded by `until`'s real-time budget, so it widens on CI like every other detector.
 *
 * Every test whose analyze SUCCEEDS awaits this, even when it inspects no rows: otherwise the
 * history write can outlive the file, hit its closed database and log a warning during worker
 * teardown, which vitest 4 turns into a failed run with every test green (vitest-dev/vitest#11153).
 */
async function waitForDoneEvent(event: { sender: { send: { mock: { calls: unknown[][] } } } }, jobId: string): Promise<void> {
  await until(
    () => event.sender.send.mock.calls.some((c: unknown[]) => c[0] === STREAM.imgDone(jobId)),
    `vision-security: the streamed done event for ${jobId}`
  )
}

let logCalls: string[]
/** The raw (method, msg, meta) of every diagnostics-log call — lets a test assert the exact
 *  SHAPE of a log line (e.g. that a warn carries ONLY {jobId, error}, no content field). */
let logRecords: Array<{ method: 'info' | 'warn' | 'error'; msg: string; meta?: unknown }>
const logSpies: Array<{ mockRestore: () => void }> = []

beforeEach(() => {
  ipcState.handlers.clear()
  logCalls = []
  logRecords = []
  // Capture every diagnostics-log argument WITHOUT writing anything (no real sink needed).
  for (const method of ['info', 'warn', 'error'] as const) {
    logSpies.push(
      vi.spyOn(log, method).mockImplementation((msg: string, meta?: unknown): void => {
        logCalls.push(meta === undefined ? msg : `${msg} ${JSON.stringify(meta)}`)
        logRecords.push({ method, msg, meta })
      })
    )
  }
})

afterEach(() => {
  for (const s of logSpies) s.mockRestore()
  logSpies.length = 0
})

describe('vision security sentinel', () => {
  // The REAL VisionRuntime (recording fetch + an SSE body; TEST-5's success-path twin was folded in
  // here), so the prompt and the image bytes genuinely pass through runAnalyze's data-URL body and
  // readChatSSE. TEETH: log the question, the answer or the image data-URL anywhere on the path →
  // the log spy captures it and this reddens.
  it('connects only to loopback (127.0.0.1) and logs/audits NO image/prompt/answer content', async () => {
    const urls: string[] = []
    const recordingFetch = (async (url: string | URL, init?: RequestInit) => {
      const u = String(url)
      urls.push(u)
      if (u.endsWith('/health')) return { ok: true, status: 200 } as Response
      if (u.endsWith('/v1/chat/completions')) {
        return { ok: true, status: 200, body: sseBody(SENTINEL_SSE) } as unknown as Response
      }
      throw new Error(`unexpected url ${u}`)
    }) as typeof fetch

    const audit = vi.fn()
    const service = new VisionService({
      isWorkspaceLocking: () => false,
      checkModel: async () => 'ok',
      getStatus: async () => AVAILABLE,
      createRuntime: () =>
        new VisionRuntime({
          modelId: 'vlm',
          binPath: '/bin/llama-server',
          modelPath: '/m/vlm.gguf',
          projectorPath: '/m/mmproj.gguf',
          spawn: fakeSpawn().spawn,
          fetchImpl: recordingFetch,
          findPort: async () => 51234,
          healthIntervalMs: 1,
          idleTimeoutMs: 100_000
        })
    })
    registerImagesIpc(ctxFor(audit), service)

    const event = makeEvent()
    const initial = (await invokeWithEvent(handlers, IPC.imageAnalyze, event, sentinelReq())) as ImageJob
    const done = await waitForTerminal(initial.jobId)
    await waitForDoneEvent(event, initial.jobId)
    expect(done.state).toBe('done')
    expect(done.answer).toBe(SENTINEL_ANSWER)

    // 1. LOOPBACK ONLY — every connection targeted 127.0.0.1, nothing remote.
    expect(urls.length).toBeGreaterThan(0)
    for (const u of urls) expect(new URL(u).hostname).toBe('127.0.0.1')

    // 2. NO CONTENT IN THE LOG — neither the prompt, the answer, nor the image bytes leaked.
    const allLog = logCalls.join('\n')
    expect(allLog).not.toContain('ZZSENTINELZZ')
    expect(allLog).not.toContain(Buffer.from(SENTINEL_BYTES).toString('base64'))

    // 3. NO VISION AUDIT ROWS — the vision path records nothing on the audit log.
    expect(audit).not.toHaveBeenCalled()
  })

  it('a runtime FAILURE logs a friendly code only — never the prompt/answer (failure path)', async () => {
    const failingFetch = (async (url: string | URL) => {
      const u = String(url)
      if (u.endsWith('/health')) return { ok: true, status: 200 } as Response
      // Server rejects the request: VisionService logs warn — assert it carries no content.
      return { ok: false, status: 500, body: null } as unknown as Response
    }) as typeof fetch

    const audit = vi.fn()
    const service = new VisionService({
      isWorkspaceLocking: () => false,
      checkModel: async () => 'ok',
      getStatus: async () => AVAILABLE,
      createRuntime: () =>
        new VisionRuntime({
          modelId: 'vlm',
          binPath: '/bin/llama-server',
          modelPath: '/m/vlm.gguf',
          projectorPath: '/m/mmproj.gguf',
          spawn: fakeSpawn().spawn,
          fetchImpl: failingFetch,
          findPort: async () => 51234,
          healthIntervalMs: 1
        })
    })
    registerImagesIpc(ctxFor(audit), service)

    const initial = (await invoke(handlers, IPC.imageAnalyze, sentinelReq())).result as ImageJob
    const terminal = await waitForTerminal(initial.jobId)
    expect(terminal.state).toBe('failed')
    expect(terminal.error).toBe('runtimeFailed') // a friendly code, not raw runtime text

    expect(logCalls.join('\n')).not.toContain('ZZSENTINELZZ')
    expect(audit).not.toHaveBeenCalled()
  })

  // TEST-1 (non-vacuous): the answer ACTUALLY flows through the system (streamed via onToken),
  // then the analyze fails — so we exercise the REAL `index.ts` catch→log.warn path with content
  // present, and assert the warn carries ONLY a content-free {jobId, error}. A regression that
  // logged `req.question` or the answer (an extra meta key, or a content-bearing error) reddens.
  it('a failure AFTER the answer streamed logs ONLY a content-free {jobId, error}', async () => {
    const audit = vi.fn()
    const service = new VisionService({
      isWorkspaceLocking: () => false,
      checkModel: async () => 'ok',
      getStatus: async () => AVAILABLE,
      // Allowed test seam: the answer really flows through onToken, then a content-free throw.
      createRuntime: () => ({
        analyze: async (o: { onToken?: (d: string) => void }) => {
          o.onToken?.(SENTINEL_ANSWER)
          throw new Error('Vision request failed: HTTP 500') // content-free, like the real runtime
        }
      })
    })
    registerImagesIpc(ctxFor(audit), service)

    const initial = (await invoke(handlers, IPC.imageAnalyze, sentinelReq())).result as ImageJob
    const terminal = await waitForTerminal(initial.jobId)
    expect(terminal.state).toBe('failed')
    expect(terminal.error).toBe('runtimeFailed')

    const warns = logRecords.filter((r) => r.method === 'warn' && r.msg === 'Vision analyze failed')
    expect(warns).toHaveLength(1)
    const meta = warns[0].meta as Record<string, unknown>
    // The meta shape is EXACTLY {jobId, error} — no `question`/`answer`/`imageBytes` smuggled in.
    expect(Object.keys(meta).sort()).toEqual(['error', 'jobId'])
    expect(meta.jobId).toBe(initial.jobId)
    expect(JSON.stringify(meta)).not.toContain('ZZSENTINELZZ')
    expect(logCalls.join('\n')).not.toContain('ZZSENTINELZZ')
    expect(audit).not.toHaveBeenCalled()
  })

  // TEST-3 / plan §17 row 11: Images is cleanly separate from OCR/Documents — a vision analyze
  // must NOT construct the OCR engine and must NOT touch documents/ocr_json. The image-history
  // feature DOES persist the analyzed image, but ENCRYPTED AT REST (the old "writes nothing to
  // disk" guarantee is intentionally replaced — see security-model.md): the stored copy is a
  // .enc sidecar under images/ and the raw image bytes never appear in plaintext on disk.
  it('never invokes the OCR engine; stores the image ENCRYPTED under images/ (no plaintext leak)', async () => {
    const ocrSpy = vi.spyOn(ocrFactory, 'createSelectedOcrEngine')
    const root = mkdtempSync(join(tmpdir(), 'hilbertraum-vision-iso-'))
    const audit = vi.fn()
    const service = new VisionService({
      isWorkspaceLocking: () => false,
      checkModel: async () => 'ok',
      getStatus: async () => AVAILABLE,
      createRuntime: () => ({
        analyze: async (o: { onToken?: (d: string) => void }) => {
          o.onToken?.('a bar chart')
          return 'a bar chart'
        }
      })
    })
    registerImagesIpc(ctxFor(audit, root), service)

    const event = makeEvent()
    const initial = (await invokeWithEvent(handlers, IPC.imageAnalyze, event, sentinelReq())) as ImageJob
    const done = await waitForTerminal(initial.jobId)
    expect(done.state).toBe('done')
    // F-12 (audit 2026-07-16): the encrypted store is async, so the .enc sidecar (and the shred of the
    // plaintext temp) land only after the streamed done EVENT fires — wait for it before the disk check.
    await waitForDoneEvent(event, initial.jobId)

    expect(ocrSpy).not.toHaveBeenCalled() // no OCR engine ever built on the vision path
    expect(existsSync(join(root, 'documents'))).toBe(false) // never the documents pipeline
    expect(existsSync(join(root, 'ocr_json'))).toBe(false)

    // The image rests encrypted: a .enc sidecar under images/, no transient temp, no plaintext.
    const imagesPath = join(root, 'images')
    expect(existsSync(imagesPath)).toBe(true)
    const stored = readdirSync(imagesPath)
    expect(stored).toHaveLength(1)
    expect(stored[0]).toMatch(/\.enc$/)
    expect(readFileSync(join(imagesPath, stored[0])).includes(Buffer.from(SENTINEL_BYTES))).toBe(false)
    ocrSpy.mockRestore()
  })

  // MEDIUM vuln-scan-2026-06-21: a completed answer (content derived from the private image)
  // must not linger in the per-process job map after the workspace locks. stop() (wired to lock)
  // must purge it, like the lock path purges resident RAG vectors and zeroes the vault key.
  it('stop() purges completed-answer residue from the job map (lock-time RAM purge)', async () => {
    const audit = vi.fn()
    const service = new VisionService({
      isWorkspaceLocking: () => false,
      checkModel: async () => 'ok',
      getStatus: async () => AVAILABLE,
      createRuntime: () => ({
        analyze: async (o: { onToken?: (d: string) => void }) => {
          o.onToken?.(SENTINEL_ANSWER)
          return SENTINEL_ANSWER
        }
      })
    })
    registerImagesIpc(ctxFor(audit), service)

    const { result, event } = await invoke(handlers, IPC.imageAnalyze, sentinelReq())
    const initial = result as ImageJob
    const done = await waitForTerminal(initial.jobId)
    await waitForDoneEvent(event, initial.jobId)
    expect(done.answer).toBe(SENTINEL_ANSWER) // the answer is resident…

    await service.stop() // …workspace lock / quit teardown
    const after = service.getJob(initial.jobId)
    expect(after.state).toBe('failed') // unknown job ⇒ purged
    expect(after.answer).toBeUndefined() // no answer text survives the lock
  })

  // BUG vuln-scan-2026-06-21: terminal jobs (each holding its answer) accumulated for the
  // process lifetime. The map is now bounded — old terminal jobs are evicted.
  it('bounds the job map: old terminal jobs are evicted (no unbounded growth)', async () => {
    const audit = vi.fn()
    const service = new VisionService({
      isWorkspaceLocking: () => false,
      checkModel: async () => 'ok',
      getStatus: async () => AVAILABLE,
      createRuntime: () => ({ analyze: async () => 'ok' })
    })
    registerImagesIpc(ctxFor(audit), service)

    const ids: string[] = []
    for (let i = 0; i < 20; i++) {
      const { result, event } = await invoke(handlers, IPC.imageAnalyze, sentinelReq())
      const initial = result as ImageJob
      await waitForTerminal(initial.jobId)
      await waitForDoneEvent(event, initial.jobId)
      ids.push(initial.jobId)
    }
    // The earliest jobs were evicted (cap 16); the most recent are still retained.
    expect(service.getJob(ids[0]).state).toBe('failed') // evicted ⇒ unknown
    expect(service.getJob(ids[ids.length - 1]).state).toBe('done') // recent ⇒ kept
  })

  // #120 item 2: the history-persistence fields were the module's one UNCLAMPED renderer input.
  // A compromised renderer (threat #1) sending junk must not store multi-MB titles / NaN
  // dimensions, and a sessionId that names no existing session must not be trusted for the
  // append — a fresh session is created instead.
  it('clamps hostile persistence fields and refuses a forged sessionId (validation clamps)', async () => {
    const audit = vi.fn()
    const service = new VisionService({
      isWorkspaceLocking: () => false,
      checkModel: async () => 'ok',
      getStatus: async () => AVAILABLE,
      createRuntime: () => ({
        analyze: async (o: { onToken?: (d: string) => void }) => {
          o.onToken?.('an answer')
          return 'an answer'
        }
      })
    })
    registerImagesIpc(ctxFor(audit), service)

    const event = makeEvent()
    const hostile = {
      ...sentinelReq(),
      name: 'A'.repeat(2 * 1024 * 1024) + '.png', // multi-MB junk title
      width: Number.NaN,
      height: -5,
      sessionId: 'no-such-session-id' // forged — names no existing row
    }
    const initial = (await invokeWithEvent(handlers, IPC.imageAnalyze, event, hostile)) as ImageJob
    const done = await waitForTerminal(initial.jobId)
    expect(done.state).toBe('done')
    // Persistence is async — wait for the streamed done event before inspecting the rows.
    await waitForDoneEvent(event, initial.jobId)

    const list = (await invoke(handlers, IPC.imageListSessions)).result as Array<{
      id: string
      title: string
      width: number | null
      height: number | null
      turnCount: number
    }>
    expect(list).toHaveLength(1) // a FRESH session — the forged id appended nothing anywhere
    expect(list[0].id).not.toBe('no-such-session-id')
    expect(list[0].title.length).toBeLessThanOrEqual(255) // clamped, not multi-MB
    expect(list[0].width).toBeNull() // NaN coerced to null
    expect(list[0].height).toBeNull() // negative coerced to null
    expect(list[0].turnCount).toBe(1)
  })
})