Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
75 changes: 51 additions & 24 deletions packages/cli/src/ui/utils/terminal-image-renderer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
Expand Down Expand Up @@ -133,52 +134,78 @@ describe('terminalImageRenderer', () => {
}
});

it('caches repeated invalid inline payloads and evicts old entries', () => {
it('caches invalid inline payloads with bounded LRU eviction', () => {
const invalidPayloads = Array.from(
{ length: INLINE_DECODE_NEGATIVE_CACHE_LIMIT + 1 },
(_, index) => Buffer.from(`not a png ${index}`).toString('base64'),
(_, index) =>
Buffer.from(`invalid LRU payload ${index}`).toString('base64'),
);
const bufferFrom = vi.spyOn(Buffer, 'from');

try {
for (const data of invalidPayloads) {
prepareInlineTerminalImage({
data,
mimeType: 'image/png',
contentWidth: 24,
env: { TERM: 'xterm-kitty' },
stdoutIsTTY: true,
});
}

const createHash = vi.spyOn(crypto, 'createHash');
const prepare = (data: string) =>
prepareInlineTerminalImage({
data: invalidPayloads[0],
data,
mimeType: 'image/png',
contentWidth: 24,
env: { TERM: 'xterm-kitty' },
stdoutIsTTY: true,
});

try {
for (const data of invalidPayloads.slice(
0,
INLINE_DECODE_NEGATIVE_CACHE_LIMIT,
)) {
prepare(data);
}
expect(bufferFrom).toHaveBeenCalledTimes(
INLINE_DECODE_NEGATIVE_CACHE_LIMIT,
);

prepare(invalidPayloads[0]);
expect(bufferFrom).toHaveBeenCalledTimes(
INLINE_DECODE_NEGATIVE_CACHE_LIMIT,
);

prepare(invalidPayloads[INLINE_DECODE_NEGATIVE_CACHE_LIMIT]);
expect(bufferFrom).toHaveBeenCalledTimes(
INLINE_DECODE_NEGATIVE_CACHE_LIMIT + 1,
);

prepare(invalidPayloads[0]);
expect(bufferFrom).toHaveBeenCalledTimes(
INLINE_DECODE_NEGATIVE_CACHE_LIMIT + 1,
);

prepare(invalidPayloads[1]);
expect(bufferFrom).toHaveBeenCalledTimes(
INLINE_DECODE_NEGATIVE_CACHE_LIMIT + 2,
);
expect(createHash).not.toHaveBeenCalled();
} finally {
bufferFrom.mockRestore();
createHash.mockRestore();
}
});

it('rejects inline payloads above the shared image limit before decoding', () => {
const oversizedBase64 = 'A'.repeat(MAX_INLINE_IMAGE_ENCODED_LENGTH + 1);
const bufferFrom = vi.spyOn(Buffer, 'from');

expect(
prepareInlineTerminalImage({
data: oversizedBase64,
mimeType: 'image/png',
contentWidth: 24,
env: { TERM: 'xterm-kitty' },
stdoutIsTTY: true,
}),
).toEqual({ fallbackText: '[image: png]', result: null });
try {
expect(
prepareInlineTerminalImage({
data: oversizedBase64,
mimeType: 'image/png',
contentWidth: 24,
env: { TERM: 'xterm-kitty' },
stdoutIsTTY: true,
}),
).toEqual({ fallbackText: '[image: png]', result: null });
expect(bufferFrom).not.toHaveBeenCalled();
} finally {
Comment on lines +245 to +248

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 2fb460ef0957e2c09e6f631a7fb173af924055fe. The oversized-path test now spies on crypto.createHash and asserts zero calls, as suggested.

I also strengthened the resident-cache witness because the standalone SHA assertion alone does not detect every cache-pollution form once the cache uses raw keys: the LRU test fills all 64 resident entries, submits an oversized payload, and then revisits the original oldest entry. Moving the guard back into the decoder now evicts that resident and makes the test fail with an extra decode. The same test uses payloads sharing a 64-character prefix, so a truncated-key implementation fails as well.

The focused file passes 32/32 tests. Independent mutation checks killed the guard/cache-pollution regression, restored SHA key, 64-character prefix key, missing LRU refresh, and missing byte-limit branch.

中文说明

已在 2fb460ef0957e2c09e6f631a7fb173af924055fe 中处理。超限路径测试现在按建议对 crypto.createHash 打桩并断言调用次数为零。

同时加固了驻留缓存见证,因为负缓存改用 raw key 后,单独的零 SHA 断言并不能识别所有缓存污染形式:LRU 测试先填满 64 个驻留项,再提交一个超限 payload,最后复访原本最旧的条目。把 guard 移回 decoder 会挤掉该驻留项并产生额外一次解码,因此测试会失败。该测试的 payload 还共享 64 字符前缀,所以截断 key 的实现同样会失败。

目标测试文件 32/32 通过。独立变异验证已经杀死 guard/缓存污染、恢复 SHA key、64 字符前缀 key、删除 LRU refresh 和删除 byte-limit 分支五类回归。

Comment on lines +246 to +248

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 2fb460ef0957e2c09e6f631a7fb173af924055fe. The oversized test now includes the requested createHash spy and zero-call assertion.

The round-2 cache-pollution witness is covered too: after filling all 64 resident entries, the test submits an oversized payload and confirms that the original oldest entry is still resident. Moving the length guard back into the decoder makes that assertion fail through an extra decode. Payloads in the count/LRU test share a 64-character prefix, which also makes the former N5 prefix-key mutation fail.

The focused file passes 32/32 tests, and an independent verifier killed all five relevant mutations: missing hit refresh, guard-down/cache pollution, missing byte bound, prefix key, and restored SHA key.

中文说明

已在 2fb460ef0957e2c09e6f631a7fb173af924055fe 中处理。超限测试现在包含建议的 createHash spy 与零调用断言。

第 2 轮指出的缓存污染也已有承重见证:测试填满全部 64 个驻留项后提交超限 payload,并确认原本最旧的条目仍然驻留。把长度 guard 移回 decoder 会导致额外一次解码,从而让该断言失败。count/LRU 测试中的 payload 共享 64 字符前缀,因此此前的 N5 前缀 key 变异也会失败。

目标测试文件 32/32 通过;独立 verifier 杀死了五类相关变异:删除命中刷新、guard 下移并污染缓存、删除字节上限、前缀 key,以及恢复 SHA key。

bufferFrom.mockRestore();
}
});

it('rejects inline PNG dimensions above the shared image limit', () => {
Expand Down
41 changes: 16 additions & 25 deletions packages/cli/src/ui/utils/terminal-image-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const inlineDecodeCache = new Map<
string,
{ png: Buffer; size: { width: number; height: number } }
>();
export const INLINE_DECODE_NEGATIVE_CACHE_LIMIT = 64;
export const INLINE_DECODE_NEGATIVE_CACHE_LIMIT = 8;
const invalidInlineImageCache = new Set<string>();

// A Kitty terminal keeps a transmitted image and redraws it from the placeholder
Expand Down Expand Up @@ -346,10 +346,6 @@ function getImageFormat(mimeType: string): string | null {
}

function decodeInlineImage(data: string): Buffer | null {
if (data.length === 0 || data.length > MAX_INLINE_IMAGE_ENCODED_LENGTH) {
return null;
}

const normalized = data.replace(/\s/g, '');
if (
normalized.length === 0 ||
Expand All @@ -374,28 +370,32 @@ function decodeInlineImage(data: string): Buffer | null {
function getDecodedInlinePng(
data: string,
): { png: Buffer; size: { width: number; height: number } } | null {
if (data.length === 0 || data.length > MAX_INLINE_IMAGE_ENCODED_LENGTH) {
return null;
}

const cached = inlineDecodeCache.get(data);
if (cached) {
inlineDecodeCache.delete(data);
inlineDecodeCache.set(data, cached);
return cached;
}

const negativeKey = crypto.createHash('sha256').update(data).digest('hex');
if (invalidInlineImageCache.has(negativeKey)) {
invalidInlineImageCache.delete(negativeKey);
invalidInlineImageCache.add(negativeKey);
if (invalidInlineImageCache.has(data)) {
invalidInlineImageCache.delete(data);
invalidInlineImageCache.add(data);
return null;
}

const png = decodeInlineImage(data);
if (!png) {
cacheInvalidInlineImage(negativeKey);
return null;
}
const size = readValidatedInlinePngSize(png);
if (!size) {
cacheInvalidInlineImage(negativeKey);
const size = png ? readValidatedInlinePngSize(png) : null;
if (!png || !size) {
invalidInlineImageCache.add(data);
while (invalidInlineImageCache.size > INLINE_DECODE_NEGATIVE_CACHE_LIMIT) {
const oldest = invalidInlineImageCache.values().next().value;
if (oldest === undefined) break;
invalidInlineImageCache.delete(oldest);
}
return null;
}

Expand All @@ -409,15 +409,6 @@ function getDecodedInlinePng(
return decoded;
}

function cacheInvalidInlineImage(key: string): void {
invalidInlineImageCache.add(key);
while (invalidInlineImageCache.size > INLINE_DECODE_NEGATIVE_CACHE_LIMIT) {
const oldest = invalidInlineImageCache.values().next().value;
if (oldest === undefined) break;
invalidInlineImageCache.delete(oldest);
}
}

function readValidatedInlinePngSize(
png: Buffer,
): { width: number; height: number } | null {
Expand Down
Loading