跳到主要内容

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

浏览文件

mobile_cli_identity_test.go

422 行 · 16.9 KB历史下载
1//go:build !windows
2
3package workbench
4
5import (
6 "context"
7 "crypto/ecdsa"
8 "crypto/elliptic"
9 "crypto/rand"
10 "crypto/sha256"
11 "crypto/tls"
12 "crypto/x509"
13 "encoding/json"
14 "encoding/pem"
15 "fmt"
16 "io"
17 "math/big"
18 "net"
19 "net/http"
20 "net/http/httptest"
21 "os"
22 "os/exec"
23 "path/filepath"
24 "runtime"
25 "strings"
26 "sync/atomic"
27 "testing"
28 "time"
29
30 "al.essio.dev/pkg/shellescape"
31 "github.com/google/uuid"
32 "github.com/sylvinus/agent-vm/internal/cliconversation"
33)
34
35func TestMobileCLIStandardGuestSettings(t *testing.T) {
36 python, err := exec.LookPath("python3")
37 if err != nil {
38 t.Skip("python3 unavailable")
39 }
40 // Use the setup script's actual managed policy and a normal user's display
41 // preferences. The fake helper stops at the checked launch boundary.
42 probe := `
43import json, os, sys, tempfile, uuid
44from pathlib import Path
45from unittest.mock import patch
46ns = {"__name__": "identity_test"}
47exec(compile(sys.stdin.read(), "mobile_cli_identity.py", "exec"), ns)
48setup = Path("../../agent-vm.setup.sh").read_text()
49policy = json.loads(setup.split("managed-settings.json > /dev/null\n", 1)[1].split("\nJSON", 1)[0])
50with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {"HOME": directory, "CAGE_CLAUDE_SUBJECT": "a" * 64}, clear=True):
51 home = Path(directory)
52 os.environ["ProgramFiles"] = str(home / "Program Files")
53 managed = Path(os.environ["ProgramFiles"]) / "ClaudeCode" if os.name == "nt" else home / "managed"
54 managed.mkdir(parents=True)
55 (managed / "managed-settings.json").write_text(json.dumps(policy))
56 config = home / ".claude"
57 config.mkdir()
58 (config / "settings.json").write_text(json.dumps({"theme": "dark", "skipDangerousModePermissionPrompt": True}))
59 original_path = Path
60 ns["Path"] = lambda value: managed if str(value) == "/etc/claude-code" else original_path(value)
61 ns["Path"].home = lambda: home
62 sid = str(uuid.uuid4())
63 def helper_main(args, *, mobile_settings_fd, verify_mobile):
64 verify_mobile({"plan": "pro"})
65 return 0
66 helper = {"profile": lambda account: account, "cli_environment": lambda base: dict(os.environ), "main": helper_main}
67 def turn(resume):
68 with tempfile.TemporaryFile() as snapshot, patch.object(ns["runpy"], "run_path", return_value=helper):
69 args = ["--setting-sources", "user", "--resume" if resume else "--session-id", sid]
70 ns["official_turn"]("unused", "default", args, snapshot, sid, resume)
71 turn(False)
72 turn(True)
73 binding = json.loads((home / ".local/share/cage/mobile-cli-identities" / sid).read_text())
74 assert binding[1], "standard Cage settings must support continuation"
75 (managed / "managed-settings.json").write_text(json.dumps({**policy, "channelsEnabled": False}))
76 turn(True)
77 (managed / "managed-settings.json").write_text(json.dumps({**policy, "tui": "alternate"}))
78 try:
79 turn(True)
80 except ns["Changed"]:
81 pass
82 else:
83 raise AssertionError("managed policy missing from session binding")
84 (managed / "managed-settings.json").write_text(json.dumps({**policy, "env": {"ANTHROPIC_BASE_URL": "https://other.invalid"}}))
85 try:
86 turn(True)
87 except ns["Unverified"]:
88 pass
89 else:
90 raise AssertionError("accepted managed upstream override")
91 (managed / "managed-settings.json").write_text(json.dumps(policy))
92 fragments = managed / "managed-settings.d"
93 fragments.mkdir()
94 (fragments / "routing.json").write_text(json.dumps({"apiKeyHelper": "changed"}))
95 try:
96 turn(True)
97 except ns["Unverified"]:
98 pass
99 else:
100 raise AssertionError("accepted managed credential helper")
101`
102 cmd := exec.Command(python, "-I", "-c", probe)
103 cmd.Stdin = strings.NewReader(mobileCLIIdentity)
104 if output, err := cmd.CombinedOutput(); err != nil {
105 t.Fatalf("standard guest identity: %v\n%s", err, output)
106 }
107}
108
109// Exercise an actual saved transcript across two isolated API destinations.
110// CCS is optional; point CAGE_TEST_CCS at a real CCS install for that subtest.
111func TestMobileCLIHistoryStaysAtBoundProvider(t *testing.T) {
112 binary := os.Getenv("CAGE_TEST_CLAUDE_CLI")
113 if !filepath.IsAbs(binary) {
114 t.Skip("set CAGE_TEST_CLAUDE_CLI to an absolute official CLI binary")
115 }
116 for _, mode := range []string{"environment", "user-settings", "ccs", "ccs-bearer", "official-default", "official-managed"} {
117 t.Run(mode, func(t *testing.T) {
118 official := strings.HasPrefix(mode, "official-")
119 home, project := t.TempDir(), t.TempDir()
120 bin := filepath.Join(home, "bin")
121 if err := os.Mkdir(bin, 0700); err != nil {
122 t.Fatal(err)
123 }
124 launch := shellescape.Quote(binary) + " --bare"
125 if mode == "ccs-bearer" || official {
126 if runtime.GOOS != "darwin" {
127 t.Skip("native auth fixture requires macOS sandbox-exec to deny keychain and personal-home reads")
128 }
129 realHome, err := os.UserHomeDir()
130 if err != nil {
131 t.Fatal(err)
132 }
133 realBinary, err := filepath.EvalSymlinks(binary)
134 if err != nil {
135 t.Fatal(err)
136 }
137 quote := func(s string) string { v, _ := json.Marshal(s); return string(v) }
138 policy := "(version 1)(allow default)(deny mach-lookup)(deny file-read* (subpath " + quote(realHome) +
139 ") (subpath \"/Library/Keychains\"))(allow file-read* (literal " + quote(realBinary) +
140 "))(deny network-outbound)(allow network-outbound (remote ip \"localhost:*\"))"
141 launch = "/usr/bin/sandbox-exec -p " + shellescape.Quote(policy) + " " + shellescape.Quote(realBinary)
142 }
143 shim := "#!/bin/sh\n" + `if [ -n "$CAGE_TEST_ROUTE_SOURCE" ]; then
144case " $* " in *" auth status "*) ` + launch + ` "$@"
145r=$?
146/bin/cp "$CAGE_TEST_ROUTE_SOURCE" "$CAGE_TEST_ROUTE_TARGET" || exit 91
147exit "$r";; esac
148fi
149` + "exec " + launch + " \"$@\"\n"
150 if err := os.WriteFile(filepath.Join(bin, "claude"), []byte(shim), 0700); err != nil {
151 t.Fatal(err)
152 }
153 path := bin + ":/usr/bin:/bin"
154 prefix := []string{"claude"}
155 configDir := filepath.Join(home, "config")
156 settings := filepath.Join(configDir, "settings.json")
157 save := func(path string, value any) {
158 t.Helper()
159 data, err := json.Marshal(value)
160 if err != nil {
161 t.Fatal(err)
162 }
163 if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
164 t.Fatal(err)
165 }
166 if err := os.WriteFile(path, data, 0600); err != nil {
167 t.Fatal(err)
168 }
169 }
170 if strings.HasPrefix(mode, "ccs") {
171 ccs := os.Getenv("CAGE_TEST_CCS")
172 if !filepath.IsAbs(ccs) {
173 t.Skip("set CAGE_TEST_CCS to the real ccs executable")
174 }
175 path = bin + ":" + filepath.Dir(ccs) + ":/usr/bin:/bin"
176 if err := os.Symlink(ccs, filepath.Join(bin, "ccs")); err != nil {
177 t.Fatal(err)
178 }
179 prefix = []string{"ccs", "cage-fixture"}
180 settings = filepath.Join(home, ".ccs", "cage-fixture.settings.json")
181 save(filepath.Join(home, ".ccs", "config.json"), map[string]any{"profiles": map[string]string{"cage-fixture": settings}})
182 }
183 var resumed atomic.Bool
184 a := mobileTestModel(t, &resumed)
185 defer a.Close()
186 proxyURL := "http://127.0.0.1:1"
187 var certFile string
188 var writeSubject, writePlan func(string)
189 if official {
190 proxyURL, certFile = mobileOfficialTestProxy(t, a)
191 slot := "default"
192 configDir = filepath.Join(home, ".claude")
193 if mode == "official-managed" {
194 slot = "1234567890abcdef12345678"
195 configDir = filepath.Join(home, ".local/share/cage/claude-accounts", slot, "config")
196 }
197 settings = filepath.Join(configDir, "settings.json")
198 email, organization := "[email protected]", uuid.NewString()
199 prefix = []string{"env", fmt.Sprintf("CAGE_CLAUDE_SUBJECT=%x", sha256.Sum256([]byte(email+"\n"+organization))),
200 "/usr/local/bin/cage-claude-account", "run", slot}
201 writeSubject = func(address string) {
202 state := map[string]any{"hasCompletedOnboarding": true, "oauthAccount": map[string]string{
203 "accountUuid": uuid.NewString(), "emailAddress": address, "organizationUuid": organization}}
204 save(filepath.Join(home, ".claude.json"), state)
205 save(filepath.Join(configDir, ".claude.json"), state)
206 }
207 writeSubject(email)
208 writePlan = func(plan string) {
209 save(filepath.Join(configDir, ".credentials.json"), map[string]any{"claudeAiOauth": map[string]any{
210 "accessToken": "sk-ant-oat01-fake-subscription", "refreshToken": "fake", "expiresAt": time.Now().Add(time.Hour).UnixMilli(),
211 "scopes": []string{"user:inference", "user:profile"}, "subscriptionType": plan}})
212 }
213 writePlan("pro")
214 }
215 var reachedB atomic.Bool
216 b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
217 if req.URL.Path == "/v1/messages" {
218 reachedB.Store(true)
219 }
220 http.Error(w, "unexpected provider", http.StatusBadRequest)
221 }))
222 defer b.Close()
223 base, key := a.URL, "sk-ant-test-account-a"
224 dynamicAuth := false
225 swapAfterAuth := false
226 swapSource := filepath.Join(home, "alternate.json")
227 save(swapSource, map[string]any{"env": map[string]string{"ANTHROPIC_BASE_URL": b.URL}})
228 runner := cliconversation.Runner{Command: func(ctx context.Context, workspace string, args []string) (*exec.Cmd, error) {
229 cmdline := mobileIdentityCommand(prefix, args)
230 if official {
231 // The fixture runs the same helper source that Cage installs inside its VM.
232 helper, err := filepath.Abs("../cage/claude-account.py")
233 if err != nil {
234 return nil, err
235 }
236 for i := range cmdline {
237 if cmdline[i] == "/usr/local/bin/cage-claude-account" {
238 cmdline[i] = helper
239 }
240 }
241 }
242 cmd := exec.CommandContext(ctx, cmdline[0], cmdline[1:]...)
243 cmd.Dir = workspace
244 cmd.Env = []string{"HOME=" + home, "CCS_HOME=" + home, "PATH=" + path, "CLAUDE_CONFIG_DIR=" + configDir,
245 "DISABLE_AUTOUPDATER=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1",
246 "HTTP_PROXY=" + proxyURL, "HTTPS_PROXY=" + proxyURL, "NO_PROXY=127.0.0.1,localhost"}
247 if swapAfterAuth {
248 cmd.Env = append(cmd.Env, "CAGE_TEST_ROUTE_SOURCE="+swapSource, "CAGE_TEST_ROUTE_TARGET="+settings)
249 }
250 if official {
251 // The sandbox permits only loopback. The fake TLS server stands in for the official hostname.
252 cmd.Env = append(cmd.Env, "NODE_EXTRA_CA_CERTS="+certFile, "SSL_CERT_FILE="+certFile)
253 env := map[string]string{}
254 if base != a.URL {
255 env["ANTHROPIC_BASE_URL"] = base
256 }
257 if key != "sk-ant-test-account-a" {
258 env["ANTHROPIC_AUTH_TOKEN"] = key
259 }
260 cfg := map[string]any{"env": env, "theme": "dark", "skipDangerousModePermissionPrompt": true}
261 if dynamicAuth {
262 cfg["apiKeyHelper"] = "printf 'fake'"
263 }
264 save(settings, cfg)
265 } else if mode == "environment" {
266 cmd.Env = append(cmd.Env, "ANTHROPIC_API_KEY="+key, "ANTHROPIC_BASE_URL="+base)
267 } else {
268 credential := "ANTHROPIC_API_KEY"
269 if mode == "ccs-bearer" {
270 credential = "ANTHROPIC_AUTH_TOKEN"
271 }
272 config := map[string]any{"env": map[string]string{credential: key, "ANTHROPIC_BASE_URL": base, "ANTHROPIC_MODEL": "sonnet"}}
273 if dynamicAuth {
274 config["apiKeyHelper"] = "printf 'sk-ant-synthetic-helper'"
275 }
276 save(settings, config)
277 }
278 return cmd, nil
279 }}
280 ctx, cancel := context.WithTimeout(context.Background(), 55*time.Second)
281 defer cancel()
282 id := uuid.NewString()
283 run := func(prompt string, resume bool) (cliconversation.Result, error) {
284 return runner.Run(ctx, cliconversation.Turn{Workspace: project, SessionID: id, Prompt: prompt, Resume: resume}, nil)
285 }
286 if result, err := run("initial mobile prompt", false); err != nil || !result.Started || result.SingleTurn {
287 t.Fatalf("first turn: %#v %v", result, err)
288 }
289 verify := func() ([]byte, error) {
290 cmd, err := runner.Command(ctx, project, []string{"--cage-verify", "--setting-sources", "user", "--resume", id})
291 if err != nil {
292 return nil, err
293 }
294 return cmd.Output()
295 }
296 if out, err := verify(); err != nil || !json.Valid(out) || !strings.Contains(string(out), `"config":`) || resumed.Load() {
297 t.Fatalf("identity-only adoption check ran a turn or failed: %s %v", out, err)
298 }
299 swapAfterAuth = mode != "environment"
300 if _, err := run("follow-up", true); err != nil || !resumed.Load() || reachedB.Load() {
301 t.Fatalf("same upstream did not resume: %v", err)
302 }
303 if swapAfterAuth {
304 raw, err := os.ReadFile(settings)
305 if err != nil || !strings.Contains(string(raw), b.URL) {
306 t.Fatal("test did not replace the source after auth status")
307 }
308 swapAfterAuth = false
309 }
310 base = b.URL
311 if _, err := verify(); err == nil || reachedB.Load() {
312 t.Fatal("adoption check accepted a changed provider")
313 }
314 if result, err := run("changed endpoint", true); err == nil || result.Started || reachedB.Load() {
315 t.Fatalf("new endpoint reached: started=%t upstream=%t err=%v", result.Started, reachedB.Load(), err)
316 }
317 base = a.URL
318 key = "sk-ant-test-account-b"
319 if result, err := run("changed credential", true); err == nil || result.Started {
320 t.Fatalf("new credential accepted: %#v %v", result, err)
321 }
322 binding := filepath.Join(home, ".local/share/cage/mobile-cli-identities", id)
323 state, err := os.ReadFile(binding)
324 if err != nil {
325 t.Fatal(err)
326 }
327 if strings.Contains(string(state), a.URL) || strings.Contains(string(state), "sk-ant") {
328 t.Fatal("binding stored raw connection details")
329 }
330 if official {
331 key, dynamicAuth = "sk-ant-test-account-a", true
332 if result, err := run("dynamic credential helper", true); err == nil || result.Started {
333 t.Fatalf("accepted an external credential helper: %#v %v", result, err)
334 }
335 dynamicAuth = false
336 writeSubject("[email protected]")
337 if result, err := run("changed subscriber", true); err == nil || result.Started {
338 t.Fatalf("accepted a different subscription subject: %#v %v", result, err)
339 }
340 }
341 if err := os.Remove(binding); err != nil {
342 t.Fatal(err)
343 }
344 base, key = b.URL, "sk-ant-test-account-a"
345 if result, err := run("old session missing proof", true); err == nil || result.Started || reachedB.Load() {
346 t.Fatalf("unbound history reached a provider: %#v %v", result, err)
347 }
348 if mode == "user-settings" {
349 id, base, dynamicAuth = uuid.NewString(), a.URL, true
350 if result, err := run("initial mobile prompt", false); err != nil || !result.Started || !result.SingleTurn {
351 t.Fatalf("unverifiable provider failed its first turn: %#v %v", result, err)
352 }
353 base, dynamicAuth = b.URL, false
354 if result, err := run("upgrade from unknown backend", true); err == nil || result.Started || reachedB.Load() {
355 t.Fatalf("history from unverifiable provider escaped: %#v %v", result, err)
356 }
357 }
358 if mode == "official-default" {
359 id, base = uuid.NewString(), a.URL
360 writeSubject("[email protected]")
361 writePlan("team")
362 if result, err := run("initial mobile prompt", false); err != nil || !result.Started || !result.SingleTurn {
363 t.Fatalf("server-managed subscription did not report its one-turn limit: %#v %v", result, err)
364 }
365 writePlan("pro")
366 if result, err := run("downgraded plan", true); err == nil || result.Started {
367 t.Fatalf("history from unknown policy resumed: %#v %v", result, err)
368 }
369 }
370 })
371 }
372}
373
374// Intercept only the official API hostname in the network-isolated fixture.
375// No request from the real CLI is forwarded to an Internet host.
376func mobileOfficialTestProxy(t *testing.T, model *httptest.Server) (string, string) {
377 t.Helper()
378 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
379 if err != nil {
380 t.Fatal(err)
381 }
382 template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{"api.anthropic.com"},
383 NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour),
384 IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,
385 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
386 der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
387 if err != nil {
388 t.Fatal(err)
389 }
390 certFile := filepath.Join(t.TempDir(), "fixture-ca.pem")
391 if err = os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0600); err != nil {
392 t.Fatal(err)
393 }
394 tlsModel := httptest.NewUnstartedServer(model.Config.Handler)
395 tlsModel.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}}
396 tlsModel.StartTLS()
397 t.Cleanup(tlsModel.Close)
398 p := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
399 if req.Method != http.MethodConnect || req.Host != "api.anthropic.com:443" {
400 http.Error(w, "unknown test destination", http.StatusForbidden)
401 return
402 }
403 upstream, err := net.Dial("tcp", tlsModel.Listener.Addr().String())
404 if err != nil {
405 http.Error(w, "fixture unavailable", http.StatusBadGateway)
406 return
407 }
408 defer upstream.Close()
409 client, _, err := w.(http.Hijacker).Hijack()
410 if err != nil {
411 return
412 }
413 defer client.Close()
414 if _, err = io.WriteString(client, "HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil {
415 return
416 }
417 go func() { _, _ = io.Copy(upstream, client); _ = upstream.Close() }()
418 _, _ = io.Copy(client, upstream)
419 }))
420 t.Cleanup(p.Close)
421 return p.URL, certFile
422}