Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(device-link): retain source context for handle read denials

elfcv5a09b38b5890
diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
index 187108db8b..8e5fc2e95c 100644
--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -87,6 +87,7 @@ import {
import { readRemoteDeviceFile } from '../fileAccess';
import { DesktopCaptureWindow } from '../../remote-desktop/captureWindow';
import { createHash } from 'node:crypto';
+import { isSourceFileAccessError } from '../sourceFileError';
describe('peer attachment upload preflight', () => {
// #6530: an unreadable local file must not cool down a healthy peer or trigger OSS fallback.
@@ -693,6 +694,81 @@ describe('authorized file peer source', () => {
Buffer.alloc(0.5 * 1024 * 1024, 7),
);
});
+ // #6530 / review r4322213153, unit: open errors do not cover pathless fd failures.
+ // Exercise the upload entry with a real source handle failing at stat, hash or transfer read;
+ // it must reject as a source denial, close the handle, cancel staging and reuse the warm peer.
+ it.each([
+ ['stat', 'EPERM'],
+ ['hash', 'EACCES'],
+ ['transfer', 'EPERM'],
+ ] as const)('preserves the peer after pathless %s denial (%s)', async (phase, code) => {
+ const peer = `fd-denial-${phase}`;
+ const ticket = 'cccccccc-cccc-cccc-cccc-cccccccccccc';
+ const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => ({
+ ok: true,
+ result: (args[0] as { action: string }).action === 'caps'
+ ? { version: 1, streaming: true, attachments: true }
+ : { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },
+ }));
+ const ops = () => mock.commands.filter(c => c.action === 'invoke')
+ .map(c => JSON.parse(c.payload).args[0].request.op as string);
+ mock.commandReply.mockImplementation(action => action === 'invoke'
+ ? JSON.stringify({ ok: true, result: ops().at(-1) === 'begin' ? { ticket } : {} })
+ : 'v=0');
+ // Warm up the connection before injecting the source-only failure.
+ expect(await tryUploadPeerAttachment(peer, Buffer.from('hello'), undefined, invoke)).toContain(ticket);
+ const offers = mock.sent.filter(action => action === 'offer').length;
+ mock.commands.length = 0;
+ const handle = await fsPromises.open(file, 'r');
+ const close = vi.spyOn(handle, 'close');
+ const denial = Object.assign(new Error('fd access denied'), {
+ code, syscall: phase === 'stat' ? 'fstat' : 'read',
+ });
+ if (phase === 'stat') vi.spyOn(handle, 'stat').mockRejectedValueOnce(denial);
+ else {
+ const read = handle.read.bind(handle);
+ let reads = 0;
+ vi.spyOn(handle, 'read').mockImplementation(async (...args: any[]) => {
+ if (++reads === (phase === 'hash' ? 1 : 2)) throw denial;
+ return (read as (...args: any[]) => Promise<any>)(...args);
+ });
+ }
+ const openSource = vi.spyOn(fsPromises, 'open').mockResolvedValueOnce(handle);
+ try {
+ let caught: unknown;
+ try {
+ await tryUploadPeerAttachment(peer, file, undefined, invoke);
+ } catch (error) { caught = error; }
+ expect(isSourceFileAccessError(caught, file)).toBe(true);
+ expect(close).toHaveBeenCalledOnce();
+ if (phase === 'transfer') expect(ops()).toEqual(['begin', 'cancel']);
+ else expect(ops()).toEqual([]);
+ expect(await tryUploadPeerAttachment(peer, Buffer.from('copy'), undefined, invoke)).toContain(ticket);
+ expect(mock.sent.filter(action => action === 'offer')).toHaveLength(offers);
+ } finally {
+ openSource.mockRestore();
+ await handle.close();
+ }
+ });
+
+ // The source handle context must not turn network or explicitly different-file errors
+ // into local attachment guidance. These still return null for the existing OSS fallback.
+ it.each(['network', 'other-file'] as const)('retains fallback for %s permission failures', async kind => {
+ const denial = Object.assign(new Error('permission denied'), kind === 'network'
+ ? { code: 'EACCES', syscall: 'connect' }
+ : { code: 'EPERM', syscall: 'fstat', path: path.join(directory, 'another-file') });
+ const handle = await fsPromises.open(file, 'r');
+ if (kind === 'other-file') vi.spyOn(handle, 'stat').mockRejectedValueOnce(denial);
+ const openSource = vi.spyOn(fsPromises, 'open').mockResolvedValueOnce(handle);
+ const invoke = vi.fn().mockRejectedValue(denial);
+ try {
+ expect(await tryUploadPeerAttachment(`non-source-${kind}`, file, undefined, invoke)).toBeNull();
+ } finally {
+ openSource.mockRestore();
+ await handle.close();
+ }
+ });
+
it('stops a cancelled upload mid-file, discards the staging and keeps the peer usable', async () => {
const peer = 'cancel-upload-peer';
const source = path.join(directory, 'upload');
diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
index 3eb416344f..38632e3833 100644
--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
@@ -101,10 +101,10 @@ describe('rewriteOutboundMedia — channel gating', () => {
});
});
- it('does not try OSS after the peer source file is denied', async () => {
+ it.each(['open', 'fstat', 'read'])('does not try OSS after the peer source %s is denied', async syscall => {
const file = '/private/source.xlsx';
const direct = vi.fn().mockRejectedValue(Object.assign(new Error('access denied'), {
- code: 'EPERM', syscall: 'open', path: file,
+ code: 'EPERM', syscall, path: file,
}));
await expect(withPeerAttachmentUpload(direct, () => rewriteOutboundMedia('maker:send', ['session', {
type: 'user', content: [{ type: 'file', path: file }],
@@ -116,6 +116,8 @@ describe('rewriteOutboundMedia — channel gating', () => {
for (const details of [
{ code: 'EACCES', syscall: 'connect' },
{ code: 'EPERM', syscall: 'open', path: '/other/cache' },
+ { code: 'EACCES', syscall: 'fstat' },
+ { code: 'EPERM', syscall: 'read' },
{},
]) {
const error = Object.assign(new Error('upload failed'), details);
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
index 227e83c1a9..b4c7ac62cd 100644
--- a/apps/desktop/src/main/device-link/filePeer.ts
+++ b/apps/desktop/src/main/device-link/filePeer.ts
@@ -41,7 +41,7 @@ import { createLogger } from '../logger.js';
import { handlePeerAttachment } from './peerAttachmentStore';
import { fileVersion } from './fileVersion';
import { remoteFileVersionCache, type FileVersionMetadata } from './remoteFileVersionCache';
-import { isSourceFileAccessError } from './sourceFileError';
+import { isSourceFileAccessError, withSourceFileHandleContext } from './sourceFileError';
// Local-only diagnostics (scope is not upload-allowlisted): stages, sizes and timings, never paths.
const log = createLogger('device-link:filePeer');
@@ -1025,7 +1025,9 @@ export async function tryUploadPeerAttachment(
try {
if (typeof source === 'string')
handle = await fs.open(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
- const size = handle ? (await handle.stat()).size : (source as Buffer).length;
+ const size = handle
+ ? (await withSourceFileHandleContext(source, () => handle!.stat())).size
+ : (source as Buffer).length;
if (!size) return null;
// 读整份文件算摘要之前先确认对端能收:对端离线、旧版或不支持时不白读一遍(随后还要走 OSS)。
// The probe is the one wait with no checkpoint of its own; a late answer is ignored.
@@ -1036,7 +1038,9 @@ export async function tryUploadPeerAttachment(
checkActive();
if (!handle) return (source as Buffer).subarray(offset, offset + length);
const bytes = Buffer.alloc(length);
- if ((await handle.read(bytes, 0, length, offset)).bytesRead !== length)
+ const result = await withSourceFileHandleContext(source, () =>
+ handle!.read(bytes, 0, length, offset));
+ if (result.bytesRead !== length)
throw new Error('FILE_PEER_CHANGED');
return bytes;
};
diff --git a/apps/desktop/src/main/device-link/sourceFileError.ts b/apps/desktop/src/main/device-link/sourceFileError.ts
index e917a994d9..d1f07242b0 100644
--- a/apps/desktop/src/main/device-link/sourceFileError.ts
+++ b/apps/desktop/src/main/device-link/sourceFileError.ts
@@ -6,5 +6,28 @@ export function isSourceFileAccessError(error: unknown, source: string | Buffer)
const { code, syscall, path } = error as NodeJS.ErrnoException;
return (code === 'EPERM' || code === 'EACCES')
&& path === source
- && (syscall === 'open' || syscall === 'stat' || syscall === 'read');
+ && (syscall === 'open' || syscall === 'stat' || syscall === 'fstat' || syscall === 'read');
+}
+
+/** Use only around stat/read on a handle opened from this source, never around transport work. */
+export async function withSourceFileHandleContext<T>(
+ source: string | Buffer,
+ operation: () => Promise<T>,
+): Promise<T> {
+ try {
+ return await operation();
+ } catch (error) {
+ if (typeof source === 'string' && error && typeof error === 'object') {
+ const { code, syscall, path } = error as NodeJS.ErrnoException;
+ // Node's fd-based failures omit path. Do not overwrite a different explicit path or
+ // reinterpret a write/network failure just because it carries the same errno.
+ if (path === undefined && (code === 'EPERM' || code === 'EACCES')
+ && (syscall === 'fstat' || syscall === 'read')) {
+ throw Object.assign(new Error('Source attachment access denied', { cause: error }), {
+ code, syscall, path: source,
+ });
+ }
+ }
+ throw error;
+ }
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index a16e4645b8..ddc90d3a40 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -626,8 +626,10 @@ warn/warning 状态检查项、等待或处理中的检查项和 warning issue
## 桌面出站附件的本机读取拒绝(#6530)
-控制端上传附件时,仅将源路径一致的文件系统 `open/stat/read` 的 `EPERM/EACCES`
-标记为 `DEVICE_LINK_MEDIA_ACCESS_DENIED`。源文件拒绝不触发直连冷却、连接关闭或 OSS
+控制端上传附件时,仅将源路径一致的文件系统 `open/stat/fstat/read` 的 `EPERM/EACCES`
+标记为 `DEVICE_LINK_MEDIA_ACCESS_DENIED`。已知由该源文件打开的句柄,其 `stat/read` 操作
+产生的无路径 `fstat/read` 拒绝在操作边界补齐来源;不覆盖已有路径,不对网络或写入操作补齐。
+源文件拒绝不触发直连冷却、连接关闭或 OSS
回退;消息仍整条不派发。网络、远端和其他路径的错误保留原有传输失败语义。
该错误经现有 IPC 错误封装返回,不携带原始私人路径;Desktop 与 Mobile 的错误展示
提供五语“另存到可访问文件夹、移除旧附件、用附件按钮重选”指引。