fix(dsh): validate ZIP entries and bound decompression workers
Core regression / Python core and release configuration (push) Successful in 20s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 17s
Core regression / JavaScript syntax (pull_request) Successful in 3s
Core regression / Python core and release configuration (push) Successful in 20s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 17s
Core regression / JavaScript syntax (pull_request) Successful in 3s
This commit is contained in:
1 parent
705c15eb93
commit
b00ca7dac9
4 files changed
+162
-42
No files matched your search
@@ -28,3 +28,13 @@
|
||||
既有协议单测的轻量 UI stub 同步增加 hide、官方加载入口和 WebEngine settings;保留原 UTF-8 分块、重启及坏行恢复断言,并检查真实 HTTP 握手后关闭本地文件访问。
|
||||
|
||||
本次未构建或分发新 EXE,不把源码与本机验收等同于发布包验收。
|
||||
|
||||
## 合并前评论 #197:文件名完整性与解压线程
|
||||
|
||||
原 fflate 异步 unzip 使用普通对象接收文件,根目录 `__proto__` 会被静默漏掉;同时每个较大的条目都可能启动一个 Worker,文件总大小上限无法限制线程数量。新增真实 Harness 回归先在“特殊文件应明确拒绝”的断言处观察失败。
|
||||
|
||||
解压现由专用 Node Worker 执行,全进程最多同时处理两个压缩包,其余排队。每包先做不解压的整包元数据预检,明确拒绝无法可靠表示的根目录 `__proto__`;再在该 Worker 中解压,核对完整名称集合、长度和 CRC 后才传回主进程写入新目录。没有在主服务线程同步解压,也不再按 ZIP 条目创建线程。活动调用取消时终止 Worker,等待退出才结算并释放槽位;排队调用取消后直接移出队列。
|
||||
|
||||
`node tools/verify_dsh_zip_review.mjs`:合法与损坏的特殊文件名均被明确拒绝,无输出目录;4 个压缩包并行、每包 20 个 600 KiB 文件,全部文件完整,恰好创建 4 个 Worker,峰值为 2;活动取消后 Worker 全部退出且不产生半成品。独立审查还验证了 5 个请求中取消一个排队请求,4 个成功、峰值 2、全部线程退出。Worker 文件会随 task-plugin 目录递归打包。
|
||||
|
||||
最终 `python -m pytest -q tests/v1_1 tests/ui tests/dsh tests/packaging --tb=short`:1463 passed、1 skipped(未指定官方 7-Zip 发布工具)、1 条 pywinauto COM 模式警告。原有真实 Harness 文件/目录/ZIP/CRC/自动会话隔离回归再次通过;最终独立审查无新增阻断发现。
|
||||
@@ -1,31 +1,49 @@
|
||||
import {mkdir,mkdtemp,writeFile,realpath,rm} from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {unzip} from 'fflate';
|
||||
import {Worker} from 'node:worker_threads';
|
||||
import {defineTool} from '@deepseek-ai/dsh-tools';
|
||||
import {crc32} from 'node:zlib';
|
||||
|
||||
export const fileToolNames=['read','read_image','glob','grep','working_directory','extract_zip'];
|
||||
|
||||
function zipChecksums(bytes){
|
||||
const data=Buffer.from(bytes.buffer,bytes.byteOffset,bytes.byteLength);
|
||||
let end=data.length-22;
|
||||
for(;end>=Math.max(0,data.length-65557);end--)
|
||||
if(data.readUInt32LE(end)===0x06054b50&&end+22+data.readUInt16LE(end+20)===data.length)break;
|
||||
if(end<0||data.readUInt32LE(end)!==0x06054b50)throw Error('Invalid ZIP central directory');
|
||||
if(data.readUInt16LE(end+4)||data.readUInt16LE(end+6))throw Error('Multi-volume ZIP is unsupported');
|
||||
const count=data.readUInt16LE(end+10),entries=[];
|
||||
if(count===65535||count>10000)throw Error('ZIP exceeds 10000 entries');
|
||||
let offset=data.readUInt32LE(end+16);
|
||||
for(let i=0;i<count;i++){
|
||||
if(offset+46>end||data.readUInt32LE(offset)!==0x02014b50)throw Error('Invalid ZIP entry');
|
||||
if(data.readUInt16LE(offset+8)&1)throw Error('Encrypted ZIP is unsupported');
|
||||
const size=data.readUInt32LE(offset+24);
|
||||
if(size===0xffffffff)throw Error('ZIP64 entries are unsupported');
|
||||
entries.push({crc:data.readUInt32LE(offset+16),size});
|
||||
offset+=46+data.readUInt16LE(offset+28)+data.readUInt16LE(offset+30)+data.readUInt16LE(offset+32);
|
||||
if(offset>end)throw Error('Invalid ZIP entry length');
|
||||
const pending=[];
|
||||
let running=0;
|
||||
function startPending(){
|
||||
while(running<2&&pending.length){
|
||||
const job=pending.shift();
|
||||
if(job.signal.aborted){job.abort();continue;}
|
||||
running++;
|
||||
try{
|
||||
const bytes=Uint8Array.from(job.bytes);
|
||||
job.worker=new Worker(new URL('./zip-worker.mjs',import.meta.url),{
|
||||
workerData:{bytes,fflateUrl:import.meta.resolve('fflate')},transferList:[bytes.buffer],env:{},execArgv:[]});
|
||||
let result,failure;
|
||||
job.worker.once('message',value=>{result=value;});
|
||||
job.worker.once('error',error=>{failure=error;});
|
||||
job.worker.once('exit',code=>{
|
||||
running--;job.signal.removeEventListener('abort',job.abort);
|
||||
if(job.signal.aborted)job.reject(job.signal.reason??Error('ZIP extraction cancelled'));
|
||||
else if(failure||result?.error||code!==0||!result?.entries)
|
||||
job.reject(failure??Error(result?.error??'ZIP worker exited without a result'));
|
||||
else job.resolve(result.entries);
|
||||
startPending();
|
||||
});
|
||||
}catch(error){
|
||||
running--;job.signal.removeEventListener('abort',job.abort);job.reject(error);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function decompress(bytes,signal){
|
||||
signal.throwIfAborted();
|
||||
return new Promise((resolve,reject)=>{
|
||||
const job={bytes,signal,resolve,reject};
|
||||
job.abort=()=>{
|
||||
if(job.worker){void job.worker.terminate();return;}
|
||||
const index=pending.indexOf(job);if(index>=0)pending.splice(index,1);
|
||||
reject(signal.reason??Error('ZIP extraction cancelled'));
|
||||
};
|
||||
signal.addEventListener('abort',job.abort,{once:true});pending.push(job);startPending();
|
||||
});
|
||||
}
|
||||
|
||||
export function registerFileTools(ctx){
|
||||
@@ -38,30 +56,12 @@ export function registerFileTools(ctx){
|
||||
const cwd=exec.agent?ctx.workingDirectory.get(exec.agent.session):process.env.DX_DSH_WORKSPACE;
|
||||
const target=await ctx.fs.resolve(args.file_path,{cwd,signal:exec.signal});
|
||||
const bytes=await ctx.fs.readBytes(target,exec.signal,64*1024*1024);
|
||||
const checksums=zipChecksums(bytes),expected=new Map();
|
||||
let expanded=0,count=0;
|
||||
const files=await new Promise((resolve,reject)=>unzip(bytes,{filter:entry=>{
|
||||
const name=entry.name.replaceAll('\\','/');
|
||||
if(name.startsWith('/')||name.split('/').some(part=>part==='..'||/[\x00-\x1f:]/.test(part)))
|
||||
throw Error('Unsafe ZIP entry path');
|
||||
if(expected.has(entry.name))throw Error('Duplicate ZIP entry');
|
||||
const checksum=checksums[count];
|
||||
if(!checksum||checksum.size!==entry.originalSize)throw Error('Invalid ZIP entry size');
|
||||
expected.set(entry.name,checksum);
|
||||
expanded+=entry.originalSize;
|
||||
if(++count>10000||expanded>256*1024*1024)throw Error('ZIP exceeds 10000 entries or 256 MiB expanded size');
|
||||
return true;
|
||||
}},(error,value)=>error?reject(error):resolve(value)));
|
||||
if(count!==checksums.length)throw Error('Invalid ZIP entry count');
|
||||
for(const [name,data] of Object.entries(files)){
|
||||
const checksum=expected.get(name);
|
||||
if(data.length!==checksum.size||crc32(data)!==checksum.crc)throw Error('ZIP checksum mismatch: '+name);
|
||||
}
|
||||
const files=await decompress(bytes,exec.signal);
|
||||
exec.signal.throwIfAborted();
|
||||
const parent=await realpath(path.resolve(cwd,args.output_directory||'.'));
|
||||
const directory=await mkdtemp(path.join(parent,'dsh-extracted-'));
|
||||
try{
|
||||
for(const [name,data] of Object.entries(files)){
|
||||
for(const [name,data] of files){
|
||||
exec.signal.throwIfAborted();
|
||||
const output=path.resolve(directory,name.replaceAll('\\','/'));
|
||||
const relative=path.relative(directory,output);
|
||||
@@ -69,7 +69,7 @@ export function registerFileTools(ctx){
|
||||
if(name.endsWith('/'))await mkdir(output,{recursive:true});
|
||||
else{await mkdir(path.dirname(output),{recursive:true});await writeFile(output,data,{flag:'wx'});}
|
||||
}
|
||||
return {directory,files:Object.keys(files).slice(0,200),total_entries:count,truncated:count>200};
|
||||
return {directory,files:files.slice(0,200).map(([name])=>name),total_entries:files.length,truncated:files.length>200};
|
||||
}catch(error){
|
||||
// Only this invocation's newly created temporary output is removed.
|
||||
if(path.dirname(directory)===parent&&path.basename(directory).startsWith('dsh-extracted-'))
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import {parentPort,workerData} from 'node:worker_threads';
|
||||
import {crc32} from 'node:zlib';
|
||||
|
||||
function zipChecksums(bytes){
|
||||
const data=Buffer.from(bytes.buffer,bytes.byteOffset,bytes.byteLength);
|
||||
let end=data.length-22;
|
||||
for(;end>=Math.max(0,data.length-65557);end--)
|
||||
if(data.readUInt32LE(end)===0x06054b50&&end+22+data.readUInt16LE(end+20)===data.length)break;
|
||||
if(end<0||data.readUInt32LE(end)!==0x06054b50)throw Error('Invalid ZIP central directory');
|
||||
if(data.readUInt16LE(end+4)||data.readUInt16LE(end+6))throw Error('Multi-volume ZIP is unsupported');
|
||||
const count=data.readUInt16LE(end+10),entries=[];
|
||||
if(count===65535||count>10000)throw Error('ZIP exceeds 10000 entries');
|
||||
let offset=data.readUInt32LE(end+16);
|
||||
for(let i=0;i<count;i++){
|
||||
if(offset+46>end||data.readUInt32LE(offset)!==0x02014b50)throw Error('Invalid ZIP entry');
|
||||
if(data.readUInt16LE(offset+8)&1)throw Error('Encrypted ZIP is unsupported');
|
||||
const size=data.readUInt32LE(offset+24);
|
||||
if(size===0xffffffff)throw Error('ZIP64 entries are unsupported');
|
||||
entries.push({crc:data.readUInt32LE(offset+16),size});
|
||||
offset+=46+data.readUInt16LE(offset+28)+data.readUInt16LE(offset+30)+data.readUInt16LE(offset+32);
|
||||
if(offset>end)throw Error('Invalid ZIP entry length');
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
try{
|
||||
const {unzipSync}=await import(workerData.fflateUrl);
|
||||
const bytes=workerData.bytes,checksums=zipChecksums(bytes),expected=new Map();
|
||||
let expanded=0,count=0;
|
||||
// A metadata-only pass finishes before any entry is decompressed.
|
||||
unzipSync(bytes,{filter:entry=>{
|
||||
const name=entry.name.replaceAll('\\','/');
|
||||
if(name.startsWith('/')||name.split('/').some(part=>part==='..'||/[\x00-\x1f:]/.test(part)))
|
||||
throw Error('Unsafe ZIP entry path');
|
||||
if(entry.name==='__proto__')throw Error('Unsupported ZIP entry name: __proto__');
|
||||
if(expected.has(entry.name))throw Error('Duplicate ZIP entry');
|
||||
const checksum=checksums[count];
|
||||
if(!checksum||checksum.size!==entry.originalSize)throw Error('Invalid ZIP entry size');
|
||||
expected.set(entry.name,checksum);
|
||||
expanded+=entry.originalSize;
|
||||
if(++count>10000||expanded>256*1024*1024)throw Error('ZIP exceeds 10000 entries or 256 MiB expanded size');
|
||||
return false;
|
||||
}});
|
||||
if(count!==checksums.length)throw Error('Invalid ZIP entry count');
|
||||
// Synchronous inflation is confined to this single, terminable worker.
|
||||
const files=unzipSync(bytes),entries=Object.entries(files);
|
||||
if(entries.length!==expected.size||[...expected.keys()].some(name=>!Object.hasOwn(files,name)))
|
||||
throw Error('ZIP decompressed file names do not match the archive');
|
||||
for(const [name,data] of entries){
|
||||
const checksum=expected.get(name);
|
||||
if(!checksum||data.length!==checksum.size||crc32(data)!==checksum.crc)throw Error('ZIP checksum mismatch: '+name);
|
||||
}
|
||||
parentPort.postMessage({entries},[...new Set(entries.map(([,data])=>data.buffer))]);
|
||||
}catch(error){parentPort.postMessage({error:error.message});}
|
||||
finally{parentPort.close();}
|
||||
@@ -0,0 +1,55 @@
|
||||
/** PR18 #197: no silently omitted names, bounded workers, real cancellation. */
|
||||
import assert from 'node:assert/strict';
|
||||
import {mkdir,mkdtemp,writeFile,readdir,readFile} from 'node:fs/promises';
|
||||
import {spawnSync} from 'node:child_process';
|
||||
import {createRequire,syncBuiltinESMExports} from 'node:module';
|
||||
import path from 'node:path';
|
||||
import {bootRuntime} from '../integration/dsh/start.mjs';
|
||||
const output=path.resolve('build/dsh-zip-review-verification');await mkdir(output,{recursive:true});
|
||||
const root=await mkdtemp(path.join(output,'run-'));
|
||||
const fixture=spawnSync('python',['-c',
|
||||
`import sys,zipfile,struct\nfrom pathlib import Path\np=Path(sys.argv[1])\nwith zipfile.ZipFile(p/'proto.zip','w',zipfile.ZIP_STORED) as z:z.writestr('__proto__','ORIGINAL_CONTENT')\ndata=bytearray((p/'proto.zip').read_bytes());n,e=struct.unpack_from('<HH',data,26);data[30+n+e]^=1;(p/'proto-bad.zip').write_bytes(data)\nwith zipfile.ZipFile(p/'many.zip','w',zipfile.ZIP_DEFLATED) as z:\n for i in range(20):z.writestr(str(i)+'.txt',b'x'*(600*1024))\n`,root],{encoding:'utf8'});
|
||||
assert.equal(fixture.status,0,fixture.stderr);
|
||||
const require=createRequire(import.meta.url),threads=require('node:worker_threads');
|
||||
const NativeWorker=threads.Worker;
|
||||
let active=0,peak=0,created=0,abortOnWorker;
|
||||
threads.Worker=new Proxy(NativeWorker,{construct(target,args){
|
||||
const worker=Reflect.construct(target,args);active++;created++;peak=Math.max(peak,active);
|
||||
worker.once('exit',()=>active--);
|
||||
if(abortOnWorker){const cancel=abortOnWorker;abortOnWorker=undefined;queueMicrotask(cancel);}
|
||||
return worker;
|
||||
}});
|
||||
syncBuiltinESMExports();
|
||||
for(const key of ['DSH_API_BASE','DSH_MODEL','DSH_API_KEY','DX_DSH_MODELS'])delete process.env[key];
|
||||
process.env.DX_DSH_HOME=path.join(root,'home');process.env.DX_DSH_CONTEXT_FILE=path.join(root,'context.json');
|
||||
await writeFile(process.env.DX_DSH_CONTEXT_FILE,'{"task_id":"zip-review","revision":"zip-review","status":"observe"}');
|
||||
const {ctx,shutdown}=await bootRuntime({announce:false});
|
||||
try{
|
||||
const call=(file,signal=AbortSignal.timeout(30000))=>ctx.tools.execute({name:'extract_zip',
|
||||
arguments:{file_path:path.join(root,file),output_directory:root},callId:crypto.randomUUID(),signal});
|
||||
const before=await readdir(root);
|
||||
for(const file of ['proto.zip','proto-bad.zip']){
|
||||
const result=await call(file);
|
||||
assert.equal(result.isError,true,'unsupported __proto__ entry must be explicitly rejected, including corrupt payload');
|
||||
assert.deepEqual(await readdir(root),before,'rejected archive must not publish an empty success directory');
|
||||
}
|
||||
peak=0;created=0;
|
||||
const results=await Promise.all(Array.from({length:4},()=>call('many.zip')));
|
||||
for(const result of results){
|
||||
assert.equal(result.isError,false,JSON.stringify(result));
|
||||
assert.equal(result.value.total_entries,20);
|
||||
for(let i=0;i<20;i++)assert.equal((await readFile(path.join(result.value.directory,i+'.txt'))).length,600*1024);
|
||||
}
|
||||
assert.equal(created,4,'each archive must use one worker, with no per-entry worker fan-out');
|
||||
assert.ok(peak<=2,'ZIP decompression must use at most two workers across concurrent calls, actual '+peak);
|
||||
assert.equal(active,0,'completed calls must release all workers');
|
||||
const cancel=new AbortController(),prior=await readdir(root);
|
||||
abortOnWorker=()=>cancel.abort(new Error('owned cancellation fixture'));
|
||||
const cancelled=await call('many.zip',cancel.signal).catch(error=>({isError:true,error}));
|
||||
assert.equal(cancelled.isError,true);
|
||||
assert.equal(active,0,'cancelled call must settle only after its worker exits');
|
||||
assert.deepEqual(await readdir(root),prior,'cancel must not publish a partial directory');
|
||||
const report={status:'passed',realHarness:true,protoEntryExplicitlyRejected:true,corruptProtoRejected:true,
|
||||
parallelArchives:4,filesPerArchive:20,peakWorkers:peak,cancelledWorkerStopped:true};
|
||||
await writeFile(path.join(root,'report.json'),JSON.stringify(report,null,2));console.log(JSON.stringify(report));
|
||||
}finally{threads.Worker=NativeWorker;syncBuiltinESMExports();await shutdown.shutdown(0);}
|
||||
Reference in new issue
Block a user