跳到主要内容

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

浏览文件

windows_ccs_policy_test.py

76 行 · 5.7 KB历史下载
1import importlib.util
2import json
3import os
4from pathlib import Path
5import sys
6import tempfile
7import subprocess
8import types
9import unittest
10from unittest.mock import patch
11
12source=Path(__file__).with_name('mobile_cli_identity.py')
13spec=importlib.util.spec_from_file_location('ccs_identity_policy',source)
14identity=importlib.util.module_from_spec(spec);spec.loader.exec_module(identity)
15
16class CCSPolicyTests(unittest.TestCase):
17 def test_mcp_user_servers_are_preserved_and_cage_or_channel_collisions_refused(self):
18 args=['--mcp-config',json.dumps({'mcpServers':{'user-server':{'command':'fixture'}}}),'--model','fixture-model']
19 before=args.copy();identity.validate_shared_mcp(args);self.assertEqual(args,before)
20 for bad in [
21 ['--mcp-config',json.dumps({'mcpServers':{'cage':{'command':'existing'}}})],
22 ['--channels','server:user'],['--dangerously-load-development-channels','server:user']]:
23 with self.assertRaises(identity.Unverified):identity.validate_shared_mcp(bad)
24 with tempfile.TemporaryDirectory() as folder:
25 config=Path(folder)/'.mcp.json';config.write_text(json.dumps({'mcpServers':{'cage':{}}}))
26 with self.assertRaises(identity.Unverified):identity.validate_shared_mcp([], [config])
27 def test_windows_registry_settings_read_exact_policy_value_and_do_not_ignore_bad_json(self):
28 class Key:
29 def __enter__(self):return self
30 def __exit__(self,*args):pass
31 calls=[]
32 registry=types.SimpleNamespace(HKEY_LOCAL_MACHINE=1,HKEY_CURRENT_USER=2,KEY_WOW64_64KEY=4,KEY_WOW64_32KEY=8,KEY_READ=16,REG_SZ=1,REG_EXPAND_SZ=2,
33 OpenKey=lambda hive,key,zero,rights:(calls.append((hive,key,rights)) or Key()),QueryValueEx=lambda key,name:('{"channelsEnabled":false}',1),ExpandEnvironmentStrings=lambda value:value)
34 with patch.dict(sys.modules,{'winreg':registry}),patch.object(os,'name','nt'):
35 self.assertEqual(identity.windows_registry_settings(),[{'channelsEnabled':False}])
36 self.assertEqual(len(calls),4);self.assertTrue(all(call[1]==r'SOFTWARE\Policies\ClaudeCode' for call in calls))
37 registry.QueryValueEx=lambda key,name:('invalid-json',1)
38 with self.assertRaises(identity.Unverified):identity.windows_registry_settings()
39 def test_actual_ccs_config_and_pinned_model_permissions_use_the_same_auth_snapshot(self):
40 with tempfile.TemporaryDirectory() as folder:
41 root=Path(folder);config=root/'actual-config';config.mkdir()
42 (config/'settings.json').write_text(json.dumps({'theme':'dark'}))
43 profile={'env':{'ANTHROPIC_API_KEY':'fixture-only','ANTHROPIC_BASE_URL':'http://127.0.0.1:45678'},'model':'profile-model','permissions':{'deny':['Bash(profile)']}}
44 env={'CLAUDE_CONFIG_DIR':str(config),'DYNAMIC_PROXY_TOKEN':'fixture-parent-only'}
45 seen=[]
46 def auth(args,**options):
47 seen.append((args,options))
48 # A mutable source change after auth must not affect the turn.
49 (config/'settings.json').write_text('{"model":"changed-after-auth"}')
50 return subprocess.CompletedProcess(args,0,json.dumps({'loggedIn':True,'apiProvider':'firstParty','configDirectory':str(config),'authMethod':'api_key','apiKeySource':'ANTHROPIC_API_KEY'}).encode())
51 with tempfile.NamedTemporaryFile() as snapshot,patch.object(identity,'managed_settings',return_value=[]),patch.object(identity.subprocess,'run',side_effect=auth):
52 binary,args,result_env,material=identity.resolve_actual_context('trusted-native.exe',['ccs','qa'],['--setting-sources','user','--session-id','fixture'],env,profile,snapshot)
53 snapshot.seek(0);frozen=json.load(snapshot)
54 self.assertEqual(frozen['model'],'profile-model')
55 self.assertEqual(frozen['permissions']['deny'],['Bash(profile)']);self.assertEqual(frozen['theme'],'dark')
56 self.assertEqual(args[:4],seen[0][0][1:5]);self.assertEqual(result_env,env)
57 self.assertEqual(material[1],str(config.resolve()))
58 with self.assertRaises(identity.Unverified):
59 identity.merged_settings({'permissions':{'deny':['Bash(user)']}},profile)
60 def test_managed_registry_routing_is_refused_and_disabled_channels_remain_disabled(self):
61 with patch.object(identity,'windows_registry_settings',return_value=[{'env':{'ANTHROPIC_BASE_URL':'https://changed.invalid'}}]):
62 with self.assertRaises(identity.Unverified):identity.managed_settings()
63 with patch.object(identity,'windows_registry_settings',return_value=[{'channelsEnabled':False}]):
64 self.assertTrue(identity.shared_channels_disabled())
65 def test_actual_global_and_current_project_mcp_collisions_are_refused(self):
66 with tempfile.TemporaryDirectory() as folder:
67 config=Path(folder)/'actual-config';config.mkdir();project=Path(folder)/'project';project.mkdir()
68 filename=config/'.claude.json';env={'CLAUDE_CONFIG_DIR':str(config)}
69 valid={'mcpServers':{'user-server':{}},'projects':{str(project):{'mcpServers':{'project-server':{}}},str(Path(folder)/'other'):{'mcpServers':{'cage':{}}}}}
70 filename.write_text(json.dumps(valid));before=filename.read_bytes()
71 identity.validate_shared_mcp([],config_env=env,workspace=project);self.assertEqual(filename.read_bytes(),before)
72 for bad in [{**valid,'mcpServers':{'cage':{}}},{**valid,'projects':{str(project):{'mcpServers':{'cage':{}}}}}]:
73 filename.write_text(json.dumps(bad))
74 with self.assertRaises(identity.Unverified):identity.validate_shared_mcp([],config_env=env,workspace=project)
75
76if __name__=='__main__':unittest.main()