fix: bound doctor output buffer and normalize credential values (#497)

This commit is contained in:
Lingxuan Zuo
2026-03-15 20:37:22 +08:00
committed by GitHub
Unverified
parent 1dbe4a8466
commit 89bda3c7af
4 changed files with 340 additions and 5 deletions

View File

@@ -0,0 +1,104 @@
import { readFile, rm } from 'fs/promises';
import { join } from 'path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { testHome, testUserData, mockLoggerWarn, mockLoggerInfo, mockLoggerError } = vi.hoisted(() => {
const suffix = Math.random().toString(36).slice(2);
return {
testHome: `/tmp/clawx-channel-config-${suffix}`,
testUserData: `/tmp/clawx-channel-config-user-data-${suffix}`,
mockLoggerWarn: vi.fn(),
mockLoggerInfo: vi.fn(),
mockLoggerError: vi.fn(),
};
});
vi.mock('os', async () => {
const actual = await vi.importActual<typeof import('os')>('os');
const mocked = {
...actual,
homedir: () => testHome,
};
return {
...mocked,
default: mocked,
};
});
vi.mock('electron', () => ({
app: {
isPackaged: false,
getPath: () => testUserData,
getVersion: () => '0.0.0-test',
getAppPath: () => '/tmp',
},
}));
vi.mock('@electron/utils/logger', () => ({
warn: mockLoggerWarn,
info: mockLoggerInfo,
error: mockLoggerError,
}));
async function readOpenClawJson(): Promise<Record<string, unknown>> {
const content = await readFile(join(testHome, '.openclaw', 'openclaw.json'), 'utf8');
return JSON.parse(content) as Record<string, unknown>;
}
describe('channel credential normalization and duplicate checks', () => {
beforeEach(async () => {
vi.resetAllMocks();
vi.resetModules();
await rm(testHome, { recursive: true, force: true });
await rm(testUserData, { recursive: true, force: true });
});
it('assertNoDuplicateCredential detects duplicates with different whitespace', async () => {
const { saveChannelConfig } = await import('@electron/utils/channel-config');
await saveChannelConfig('feishu', { appId: 'bot-123', appSecret: 'secret-a' }, 'agent-a');
await expect(
saveChannelConfig('feishu', { appId: ' bot-123 ', appSecret: 'secret-b' }, 'agent-b'),
).rejects.toThrow('already bound to another agent');
});
it('assertNoDuplicateCredential does NOT detect duplicates with different case', async () => {
// Case-sensitive credentials (like tokens) should NOT be normalized to lowercase
// to avoid false positives where different tokens become the same after lowercasing
const { saveChannelConfig } = await import('@electron/utils/channel-config');
await saveChannelConfig('feishu', { appId: 'Bot-ABC', appSecret: 'secret-a' }, 'agent-a');
// Should NOT throw - different case is considered a different credential
await expect(
saveChannelConfig('feishu', { appId: 'bot-abc', appSecret: 'secret-b' }, 'agent-b'),
).resolves.not.toThrow();
});
it('normalizes credential values when saving (trim only, preserve case)', async () => {
const { saveChannelConfig } = await import('@electron/utils/channel-config');
await saveChannelConfig('feishu', { appId: ' BoT-XyZ ', appSecret: 'secret' }, 'agent-a');
const config = await readOpenClawJson();
const channels = config.channels as Record<string, { accounts: Record<string, { appId?: string }> }>;
// Should trim whitespace but preserve original case
expect(channels.feishu.accounts['agent-a'].appId).toBe('BoT-XyZ');
});
it('emits warning logs when credential normalization (trim) occurs', async () => {
const { saveChannelConfig } = await import('@electron/utils/channel-config');
await saveChannelConfig('feishu', { appId: ' BoT-Log ', appSecret: 'secret' }, 'agent-a');
expect(mockLoggerWarn).toHaveBeenCalledWith(
'Normalized channel credential value for duplicate check',
expect.objectContaining({ channelType: 'feishu', accountId: 'agent-a', key: 'appId' }),
);
expect(mockLoggerWarn).toHaveBeenCalledWith(
'Normalizing channel credential value before save',
expect.objectContaining({ channelType: 'feishu', accountId: 'agent-a', key: 'appId' }),
);
});
});

View File

@@ -0,0 +1,158 @@
import { EventEmitter } from 'node:events';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const MAX_DOCTOR_OUTPUT_BYTES = 10 * 1024 * 1024;
const {
mockExistsSync,
mockFork,
mockGetUvMirrorEnv,
mockLoggerWarn,
mockLoggerInfo,
mockLoggerError,
} = vi.hoisted(() => ({
mockExistsSync: vi.fn(),
mockFork: vi.fn(),
mockGetUvMirrorEnv: vi.fn(),
mockLoggerWarn: vi.fn(),
mockLoggerInfo: vi.fn(),
mockLoggerError: vi.fn(),
}));
vi.mock('node:fs', async () => {
const actual = await vi.importActual<typeof import('node:fs')>('node:fs');
return {
...actual,
existsSync: mockExistsSync,
default: {
...actual,
existsSync: mockExistsSync,
},
};
});
vi.mock('electron', () => ({
app: {
isPackaged: false,
},
utilityProcess: {
fork: mockFork,
},
}));
vi.mock('@electron/utils/paths', () => ({
getOpenClawDir: () => '/tmp/openclaw',
getOpenClawEntryPath: () => '/tmp/openclaw/openclaw-entry.js',
}));
vi.mock('@electron/utils/uv-env', () => ({
getUvMirrorEnv: mockGetUvMirrorEnv,
}));
vi.mock('@electron/utils/logger', () => ({
logger: {
warn: mockLoggerWarn,
info: mockLoggerInfo,
error: mockLoggerError,
},
}));
class MockUtilityChild extends EventEmitter {
stdout = new EventEmitter();
stderr = new EventEmitter();
kill = vi.fn();
}
describe('openclaw doctor output handling', () => {
beforeEach(() => {
vi.resetAllMocks();
vi.resetModules();
mockExistsSync.mockReturnValue(true);
mockGetUvMirrorEnv.mockResolvedValue({});
});
it('collects normal output under the buffer limit', async () => {
const child = new MockUtilityChild();
mockFork.mockReturnValue(child);
const { runOpenClawDoctor } = await import('@electron/utils/openclaw-doctor');
const resultPromise = runOpenClawDoctor();
await vi.waitFor(() => {
expect(mockFork).toHaveBeenCalledTimes(1);
});
child.stdout.emit('data', Buffer.from('doctor ok\n'));
child.emit('exit', 0);
const result = await resultPromise;
expect(result.success).toBe(true);
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('doctor ok\n');
expect(result.stderr).toBe('');
expect(mockLoggerWarn).not.toHaveBeenCalled();
});
it('truncates output when stdout exceeds MAX_DOCTOR_OUTPUT_BYTES', async () => {
const child = new MockUtilityChild();
mockFork.mockReturnValue(child);
const { runOpenClawDoctor } = await import('@electron/utils/openclaw-doctor');
const resultPromise = runOpenClawDoctor();
await vi.waitFor(() => {
expect(mockFork).toHaveBeenCalledTimes(1);
});
child.stdout.emit('data', Buffer.from('a'.repeat(MAX_DOCTOR_OUTPUT_BYTES - 5)));
child.stdout.emit('data', Buffer.from('b'.repeat(10)));
child.stdout.emit('data', Buffer.from('c'.repeat(1000)));
child.emit('exit', 0);
const result = await resultPromise;
expect(result.stdout.length).toBe(MAX_DOCTOR_OUTPUT_BYTES);
expect(result.stdout.endsWith('bbbbb')).toBe(true);
expect(result.stdout.includes('c')).toBe(false);
});
it('logs a warning when truncation occurs', async () => {
const child = new MockUtilityChild();
mockFork.mockReturnValue(child);
const { runOpenClawDoctor } = await import('@electron/utils/openclaw-doctor');
const resultPromise = runOpenClawDoctor();
await vi.waitFor(() => {
expect(mockFork).toHaveBeenCalledTimes(1);
});
child.stdout.emit('data', Buffer.from('x'.repeat(MAX_DOCTOR_OUTPUT_BYTES + 1)));
child.emit('exit', 0);
await resultPromise;
expect(mockLoggerWarn).toHaveBeenCalledWith(
`OpenClaw doctor stdout exceeded ${MAX_DOCTOR_OUTPUT_BYTES} bytes; truncating additional output`,
);
});
it('collects stdout and stderr independently', async () => {
const child = new MockUtilityChild();
mockFork.mockReturnValue(child);
const { runOpenClawDoctor } = await import('@electron/utils/openclaw-doctor');
const resultPromise = runOpenClawDoctor();
await vi.waitFor(() => {
expect(mockFork).toHaveBeenCalledTimes(1);
});
child.stdout.emit('data', Buffer.from('line-1\n'));
child.stderr.emit('data', Buffer.from('warn-1\n'));
child.stdout.emit('data', Buffer.from('line-2\n'));
child.stderr.emit('data', Buffer.from('warn-2\n'));
child.emit('exit', 1);
const result = await resultPromise;
expect(result.success).toBe(false);
expect(result.exitCode).toBe(1);
expect(result.stdout).toBe('line-1\nline-2\n');
expect(result.stderr).toBe('warn-1\nwarn-2\n');
});
});