跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

esigner.test.mjs

185 行 · 11.4 KB历史下载
1import assert from 'node:assert/strict';
2import { execFileSync, spawnSync } from 'node:child_process';
3import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
4import { join } from 'node:path';
5import { tmpdir } from 'node:os';
6import { fileURLToPath } from 'node:url';
7import { test } from 'node:test';
8import { assertWindowsExecutable, credentialDiagnostic, invokeJava, invokeSigning, javaArgument, prepareVendorInput, redact, verifyTool } from './esigner.mjs';
9
10test('Java arguments reject line injection and redact overlapping secrets', () => {
11 for (const value of ['line\nbreak', 'line\rbreak', 'a\0b']) assert.throws(() => javaArgument(value));
12 assert.equal(redact('secret-long and secret', ['secret', 'secret-long']), '[redacted] and [redacted]');
13});
14
15test('read-only credential diagnosis emits only fixed stage, exit and error classifications', () => {
16 assert.deepEqual(credentialDiagnostic(), { operation: 'credential_info', success: true, stage: 'csc-credential-info', exitCode: 0, error: '' });
17 for (const [code, stage] of [[1, 'oauth-token'], [2, 'csc-credential-info'], [3, 'client']]) {
18 const result = credentialDiagnostic(new Error(`CodeSignTool failed (exit ${code}). Error: {"error":"server_error","token":"private-token","username":"private-user","credential_id":"private-id"}`));
19 assert.deepEqual(result, { operation: 'credential_info', success: false, stage, exitCode: code, error: 'server_error' });
20 assert.ok(!JSON.stringify(result).includes('private'));
21 }
22 const unknown = credentialDiagnostic(new Error('private-user private-id private-token {"error":"private_password"}'));
23 assert.equal(unknown.error, 'unclassified');
24 assert.equal(unknown.exitCode, null);
25 assert.ok(!JSON.stringify(unknown).includes('private'));
26});
27
28test('signing retries only declared server errors without output and remains bounded', async t => {
29 const root = await mkdtemp(join(tmpdir(), 'cage-sign-retry-'));
30 t.after(() => rm(root, { recursive: true, force: true }));
31 const outputPath = join(root, 'signed.exe'), delays = [];
32 const failure = () => new Error('CodeSignTool failed (exit 11). Error: {"error":"server_error"}');
33 let count = 0;
34 assert.equal(await invokeSigning({ outputPath, pause: async ms => delays.push(ms), invoke: async () => { if (++count < 3) throw failure(); return 'signed'; } }), 'signed');
35 assert.deepEqual(delays, [15000, 30000]);
36 count = 0;
37 await assert.rejects(invokeSigning({ outputPath, pause: async () => {}, invoke: async () => { count++; throw failure(); } }), /server_error/);
38 assert.equal(count, 3);
39 for (const message of ['OTP rejected', 'authentication failed', 'timeout', 'CodeSignTool failed (exit 1). server_error', `${failure().message}\nOTP rejected`, `${failure().message}\ninvalid otp`, `${failure().message}\ntimeout`]) {
40 count = 0;
41 await assert.rejects(invokeSigning({ outputPath, pause: async () => assert.fail('must not wait'), invoke: async () => { count++; throw new Error(message); } }));
42 assert.equal(count, 1);
43 }
44 count = 0;
45 await assert.rejects(invokeSigning({ outputPath, pause: async () => assert.fail('quota is not transient'), invoke: async () => { count++; throw Object.assign(failure(), { quotaExceeded: true }); } }));
46 assert.equal(count, 1);
47 count = 0;
48 await invokeSigning({ outputPath, pause: async () => assert.fail('output requires trust verification, never another signature'), invoke: async () => { count++; await writeFile(outputPath, 'candidate output'); throw failure(); } });
49 assert.equal(count, 1);
50 assert.equal(await readFile(outputPath, 'utf8'), 'candidate output');
51});
52
53test('a real JVM receives quoted Unicode arguments, no secrets in process arguments, and OTP through stdin', async t => {
54 const temp = await mkdtemp(join(tmpdir(), 'cage-esigner-test-'));
55 t.after(() => rm(temp, { recursive: true, force: true }));
56 const source = join(temp, 'Signer.java');
57 const config = join(temp, 'config.properties');
58 await writeFile(config, 'TEST=true\n');
59 await writeFile(source, `
60import java.nio.file.*;
61import java.util.*;
62public class Signer {
63 public static void main(String[] args) throws Exception {
64 String temp = System.getProperty("user.dir");
65 Files.writeString(Path.of(args[0]), temp);
66 String command = ProcessHandle.current().info().commandLine().orElse("");
67 if (!command.contains("@") || command.contains("password=") || command.contains("totp_secret=")) System.exit(13);
68 if (System.getenv("CAGE_ESIGNER_PASSWORD") != null || System.getenv("CAGE_ESIGNER_TOTP_SECRET") != null) System.exit(14);
69 if (!Files.readString(Path.of("conf", "code_sign_tool.properties")).contains("TEST=true")) System.exit(15);
70 for (int i = 1; i < args.length; i++) System.out.println("ARG[" + i + "]=" + args[i]);
71 Files.createDirectories(Path.of("logs"));
72 Files.writeString(Path.of("logs", "sensitive.log"), "must be removed");
73 System.out.print("Enter the OTP - Press enter to continue:");
74 System.out.flush();
75 String otp = new Scanner(System.in).nextLine();
76 if (!otp.equals("123456")) System.exit(16);
77 System.out.println(otp);
78 if (Arrays.asList(args).contains("quota")) {
79 Files.writeString(Path.of("logs", "code_signing_tool.log"), "sensitive-user sensitive-id sensitive-token\\n at com.ssl.code.signing.tool.csc.CscApi.getMalwareScanResponse(CscApi.java:1)\\nQuotaExceededError dummy-password");
80 System.out.println("Error: {\\\"error\\\":\\\"server_error\\\",\\\"token\\\":\\\"sensitive-token\\\"}");
81 System.exit(11);
82 }
83 if (Arrays.asList(args).contains("fail")) { System.out.println("Error: dummy-password"); System.exit(4); }
84 }
85}
86`);
87 execFileSync('javac', ['-d', temp, source]);
88 const jar = join(temp, 'fixture.jar');
89 execFileSync('jar', ['--create', '--file', jar, '--main-class', 'Signer', '-C', temp, 'Signer.class']);
90 const values = [' spaces ', 'quote"slash\\tab\t', '中文路径/空 格.exe', '#hash', '@value', '-password=dummy-password'];
91 for (const fail of [false, true]) {
92 const marker = join(temp, fail ? 'failure-marker' : 'success-marker');
93 let calls = 0;
94 const previous = process.env.CAGE_ESIGNER_PASSWORD;
95 process.env.CAGE_ESIGNER_PASSWORD = 'dummy-password';
96 try {
97 const operation = invokeJava({ jar, config, arguments: [marker, ...values, ...(fail ? ['fail'] : [])],
98 otp: async () => { calls++; return '123456'; }, secrets: ['dummy-password'] });
99 if (fail) {
100 await assert.rejects(operation, error => !error.message.includes('dummy-password') && !error.message.includes('123456') && /exit 4/u.test(error.message));
101 } else {
102 const output = await operation;
103 for (const [i, value] of values.entries()) assert.ok(output.includes(`ARG[${i + 1}]=${redact(value, ['dummy-password'])}`));
104 assert.ok(!output.includes('123456'));
105 }
106 assert.equal(calls, 1);
107 const working = await readFile(marker, 'utf8');
108 await assert.rejects(readFile(join(working, 'java.args')), { code: 'ENOENT' });
109 await assert.rejects(readFile(join(working, 'logs/sensitive.log')), { code: 'ENOENT' });
110 } finally {
111 if (previous === undefined) delete process.env.CAGE_ESIGNER_PASSWORD;
112 else process.env.CAGE_ESIGNER_PASSWORD = previous;
113 }
114 }
115 const quotaMarker = join(temp, 'quota-marker');
116 let quotaCalls = 0;
117 await assert.rejects(invokeSigning({ outputPath: join(temp, 'no-signed-output.exe'), pause: async () => assert.fail('quota cannot cause a second signing request'), invoke: () => {
118 quotaCalls++;
119 return invokeJava({ jar, config, arguments: [quotaMarker, 'quota'], otp: async () => '123456', secrets: ['dummy-password'] });
120 } }), error => {
121 assert.equal(error.failureStage, 'malware-scan');
122 assert.equal(error.providerCode, 'server_error');
123 assert.equal(error.quotaExceeded, true);
124 for (const secret of ['sensitive-user', 'sensitive-id', 'sensitive-token', 'dummy-password', '123456']) assert.ok(!`${error.message}${JSON.stringify(error)}`.includes(secret));
125 return true;
126 });
127 assert.equal(quotaCalls, 1);
128 const quotaWorking = await readFile(quotaMarker, 'utf8');
129 await assert.rejects(readFile(join(quotaWorking, 'logs/code_signing_tool.log')), { code: 'ENOENT' });
130});
131
132test('modified vendor binaries are refused before executing Java', async t => {
133 const temp = await mkdtemp(join(tmpdir(), 'cage-esigner-tampered-'));
134 t.after(() => rm(temp, { recursive: true, force: true }));
135 const { mkdir } = await import('node:fs/promises');
136 await mkdir(join(temp, 'jar'));
137 await writeFile(join(temp, 'jar/code_sign_tool-1.3.3.jar'), 'modified');
138 await assert.rejects(verifyTool(temp), /checksum mismatch/u);
139});
140
141test('NSIS temporary executables without an extension are accepted, unrelated files are refused', async t => {
142 const temp = await mkdtemp(join(tmpdir(), 'cage-esigner-pe-'));
143 t.after(() => rm(temp, { recursive: true, force: true }));
144 const path = join(temp, 'makensis123');
145 const bytes = Buffer.alloc(132);
146 bytes.writeUInt16LE(0x5a4d, 0);
147 bytes.writeUInt32LE(128, 60);
148 bytes.writeUInt32LE(0x4550, 128);
149 await writeFile(path, bytes);
150 await assertWindowsExecutable(path);
151 const prepared = await prepareVendorInput(path, temp);
152 assert.ok(prepared.path.endsWith('.exe'), 'The vendor requires an extension to choose Authenticode.');
153 assert.deepEqual(await readFile(prepared.path), bytes);
154 assert.deepEqual(await readFile(path), bytes);
155 bytes.writeUInt32LE(0, 128);
156 await writeFile(path, bytes);
157 await assert.rejects(assertWindowsExecutable(path), /not a Windows PE/u);
158 await writeFile(path, 'plain text');
159 await assert.rejects(assertWindowsExecutable(path), /not a Windows PE/u);
160});
161
162test('release readiness accepts eSigner without a PFX, requires all secrets and rejects unknown providers', () => {
163 const script = fileURLToPath(new URL('./check-release-readiness.mjs', import.meta.url));
164 const env = {
165 ...process.env,
166 CAGE_MACOS_P12_BASE64: 'fixture', CAGE_MACOS_P12_PASSWORD: 'fixture', CAGE_MACOS_SIGNING_IDENTITY: 'Developer ID Application: Fixture',
167 CAGE_MACOS_NOTARY_KEY_BASE64: 'fixture', CAGE_MACOS_NOTARY_KEY_ID: 'fixture', CAGE_MACOS_NOTARY_ISSUER_ID: 'fixture',
168 CAGE_WINDOWS_QEMU_SOURCE_URL: 'https://example.invalid/source.zip', CAGE_WINDOWS_QEMU_SOURCE_SHA256: 'a'.repeat(64),
169 CAGE_WINDOWS_SIGNING_PROVIDER: 'esigner', CAGE_ESIGNER_USERNAME: 'fixture', CAGE_ESIGNER_PASSWORD: 'private-fixture-password',
170 CAGE_ESIGNER_CREDENTIAL_ID: '11111111-2222-3333-4444-555555555555', CAGE_ESIGNER_TOTP_SECRET: 'private-fixture-seed',
171 CAGE_ESIGNER_CERTIFICATE_SERIAL: '7'.repeat(32), CAGE_WINDOWS_PFX_BASE64: '', CAGE_WINDOWS_PFX_PASSWORD: '',
172 };
173 const run = change => spawnSync(process.execPath, [script], { env: { ...env, ...change }, encoding: 'utf8' });
174 assert.equal(run({}).status, 0);
175 for (const name of ['CAGE_ESIGNER_USERNAME', 'CAGE_ESIGNER_PASSWORD', 'CAGE_ESIGNER_CREDENTIAL_ID', 'CAGE_ESIGNER_TOTP_SECRET', 'CAGE_ESIGNER_CERTIFICATE_SERIAL']) {
176 const result = run({ [name]: '' });
177 assert.equal(result.status, 1);
178 assert.ok(result.stderr.includes(name));
179 assert.ok(!result.stderr.includes('private-fixture-password') && !result.stderr.includes('private-fixture-seed'));
180 }
181 assert.equal(run({ CAGE_WINDOWS_SIGNING_PROVIDER: 'typo' }).status, 1);
182 assert.equal(run({ CAGE_ESIGNER_CERTIFICATE_SERIAL: 'bad' }).status, 1);
183 assert.equal(run({ CAGE_WINDOWS_SIGNING_PROVIDER: '', CAGE_WINDOWS_PFX_BASE64: 'fixture', CAGE_WINDOWS_PFX_PASSWORD: 'fixture' }).status, 0);
184 assert.equal(run({ CAGE_WINDOWS_SIGNING_PROVIDER: '' }).status, 1);
185});