| 1 | package remotehost |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "net/http/cookiejar" |
| 12 | "net/url" |
| 13 | "os" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/sylvinus/agent-vm/internal/host" |
| 20 | "golang.org/x/crypto/ssh" |
| 21 | "golang.org/x/crypto/ssh/agent" |
| 22 | ) |
| 23 | |
| 24 | func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'" } |
| 25 | |
| 26 | |
| 27 | func ServerEntryCommand(p HostProfile) (string, error) { |
| 28 | p, err := normalizeProfile(p) |
| 29 | if err != nil { |
| 30 | return "", err |
| 31 | } |
| 32 | command := shellQuote(p.Executable) + " server-entry --json" |
| 33 | if p.ConfigPath != "" { |
| 34 | command = "env CLAUDE_CAGE_CONFIG=" + shellQuote(p.ConfigPath) + " " + command |
| 35 | } |
| 36 | return "exec " + command, nil |
| 37 | } |
| 38 | |
| 39 | |
| 40 | |
| 41 | func ValidateManifest(m ServerManifest) error { |
| 42 | if m.APIProtocol != APIProtocol { |
| 43 | return failure("protocol_incompatible", "云端 Cage 协议与客户端不兼容,请更新到兼容版本") |
| 44 | } |
| 45 | if !instancePattern.MatchString(m.InstanceID) || m.Platform != "linux" || (m.Runtime != "container" && m.Runtime != "lima") || len(m.Version) > 128 || hasControl(m.Version) { |
| 46 | return failure("manifest_invalid", "云端 Cage 身份响应无效") |
| 47 | } |
| 48 | u, err := url.Parse(m.Origin) |
| 49 | if err != nil || u.Scheme != "http" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" || (u.Hostname() != "localhost" && u.Hostname() != "127.0.0.1" && u.Hostname() != "::1") { |
| 50 | return failure("origin_refused", "云端服务必须使用明确的本机回环地址") |
| 51 | } |
| 52 | port, err := strconv.Atoi(u.Port()) |
| 53 | if err != nil || port < 1 || port > 65535 { |
| 54 | return failure("origin_refused", "云端服务端口无效") |
| 55 | } |
| 56 | if len(m.Ticket) < 32 || len(m.Ticket) > 512 || hasControl(m.Ticket) || len(m.Capabilities) > 64 { |
| 57 | return failure("manifest_invalid", "云端 Cage 连接票据无效") |
| 58 | } |
| 59 | for key := range m.Capabilities { |
| 60 | if key == "" || len(key) > 64 || hasControl(key) { |
| 61 | return failure("manifest_invalid", "云端能力声明无效") |
| 62 | } |
| 63 | } |
| 64 | return nil |
| 65 | } |
| 66 | |
| 67 | func authentication(ctx context.Context, p HostProfile, secrets ConnectSecrets) (ssh.AuthMethod, func(), error) { |
| 68 | if p.Auth.Kind == "agent" { |
| 69 | conn, err := dialAgent(ctx) |
| 70 | if err != nil { |
| 71 | return nil, nil, failure("agent_unavailable", "无法连接本机 SSH agent,请启动 agent 或选择密钥文件") |
| 72 | } |
| 73 | _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) |
| 74 | stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) |
| 75 | signers, err := agent.NewClient(conn).Signers() |
| 76 | if err != nil || len(signers) == 0 { |
| 77 | stop() |
| 78 | conn.Close() |
| 79 | return nil, nil, failure("agent_unavailable", "SSH agent 中没有可用密钥") |
| 80 | } |
| 81 | return ssh.PublicKeys(signers...), func() { stop(); conn.Close() }, nil |
| 82 | } |
| 83 | if err := host.CheckPrivateFile(p.Auth.IdentityFile); err != nil { |
| 84 | return nil, nil, failure("identity_permissions", "SSH 密钥不存在或文件权限不安全") |
| 85 | } |
| 86 | f, err := os.Open(p.Auth.IdentityFile) |
| 87 | if err != nil { |
| 88 | return nil, nil, failure("identity_read", "无法读取 SSH 密钥文件") |
| 89 | } |
| 90 | key, err := io.ReadAll(io.LimitReader(f, (1<<20)+1)) |
| 91 | f.Close() |
| 92 | defer clear(key) |
| 93 | if err != nil || len(key) > 1<<20 { |
| 94 | return nil, nil, failure("identity_read", "SSH 密钥文件无效或过大") |
| 95 | } |
| 96 | var signer ssh.Signer |
| 97 | if len(secrets.Passphrase) > 0 { |
| 98 | signer, err = ssh.ParsePrivateKeyWithPassphrase(key, secrets.Passphrase) |
| 99 | } else { |
| 100 | signer, err = ssh.ParsePrivateKey(key) |
| 101 | } |
| 102 | if err != nil { |
| 103 | var missing *ssh.PassphraseMissingError |
| 104 | if errors.As(err, &missing) { |
| 105 | return nil, nil, failure("passphrase_required", "此 SSH 密钥需要口令") |
| 106 | } |
| 107 | return nil, nil, failure("identity_invalid", "SSH 密钥或口令无效") |
| 108 | } |
| 109 | return ssh.PublicKeys(signer), func() {}, nil |
| 110 | } |
| 111 | |
| 112 | type limitedOutput struct { |
| 113 | bytes.Buffer |
| 114 | limit int |
| 115 | } |
| 116 | |
| 117 | func (w *limitedOutput) Write(p []byte) (int, error) { |
| 118 | if w.Len()+len(p) > w.limit { |
| 119 | return 0, errors.New("SSH response exceeds limit") |
| 120 | } |
| 121 | return w.Buffer.Write(p) |
| 122 | } |
| 123 | |
| 124 | func connect(lifetime context.Context, p HostProfile, secrets ConnectSecrets, phase func(string)) (*Session, error) { |
| 125 | p, err := normalizeProfile(p) |
| 126 | if err != nil { |
| 127 | return nil, err |
| 128 | } |
| 129 | bootstrap, cancelBootstrap := context.WithTimeout(lifetime, 45*time.Second) |
| 130 | defer cancelBootstrap() |
| 131 | phase("ssh_auth") |
| 132 | auth, cleanup, err := authentication(bootstrap, p, secrets) |
| 133 | if err != nil { |
| 134 | return nil, err |
| 135 | } |
| 136 | defer cleanup() |
| 137 | phase("ssh_connect") |
| 138 | address := net.JoinHostPort(p.Host, strconv.Itoa(p.Port)) |
| 139 | raw, err := (&net.Dialer{Timeout: 15 * time.Second}).DialContext(bootstrap, "tcp", address) |
| 140 | if err != nil { |
| 141 | return nil, failure("ssh_connect_failed", "无法连接 SSH 主机,请检查地址、端口和网络") |
| 142 | } |
| 143 | complete := false |
| 144 | defer func() { |
| 145 | if !complete { |
| 146 | raw.Close() |
| 147 | } |
| 148 | }() |
| 149 | _ = raw.SetDeadline(time.Now().Add(20 * time.Second)) |
| 150 | stopBootstrap := context.AfterFunc(bootstrap, func() { raw.Close() }) |
| 151 | defer stopBootstrap() |
| 152 | var keyError *Error |
| 153 | config := &ssh.ClientConfig{User: p.User, Auth: []ssh.AuthMethod{auth}, HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error { |
| 154 | observed := &HostKey{Algorithm: key.Type(), Fingerprint: ssh.FingerprintSHA256(key)} |
| 155 | if p.HostKey == nil { |
| 156 | keyError = &Error{Code: "host_key_unknown", Message: "请核对并确认 SSH 主机密钥指纹后重新连接", HostKey: observed} |
| 157 | return keyError |
| 158 | } |
| 159 | if p.HostKey.Algorithm != observed.Algorithm || p.HostKey.Fingerprint != observed.Fingerprint { |
| 160 | keyError = &Error{Code: "host_key_changed", Message: "SSH 主机密钥已变化,请核对主机身份后更新指纹", HostKey: observed} |
| 161 | return keyError |
| 162 | } |
| 163 | return nil |
| 164 | }} |
| 165 | if p.HostKey != nil { |
| 166 | config.HostKeyAlgorithms = []string{p.HostKey.Algorithm} |
| 167 | if p.HostKey.Algorithm == ssh.KeyAlgoRSA { |
| 168 | |
| 169 | |
| 170 | config.HostKeyAlgorithms = []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256} |
| 171 | } |
| 172 | } |
| 173 | sshConn, channels, requests, err := ssh.NewClientConn(raw, address, config) |
| 174 | if err != nil { |
| 175 | if keyError != nil { |
| 176 | return nil, keyError |
| 177 | } |
| 178 | return nil, failure("ssh_auth_failed", "SSH 认证未完成,请检查用户名和密钥") |
| 179 | } |
| 180 | _ = raw.SetDeadline(time.Time{}) |
| 181 | client := ssh.NewClient(sshConn, channels, requests) |
| 182 | defer func() { |
| 183 | if !complete { |
| 184 | client.Close() |
| 185 | } |
| 186 | }() |
| 187 | phase("server_handshake") |
| 188 | if !stopBootstrap() || bootstrap.Err() != nil { |
| 189 | return nil, failure("ssh_timeout", "SSH 认证超时") |
| 190 | } |
| 191 | timeout := 2 * time.Minute |
| 192 | if secrets.Deploy { |
| 193 | timeout = 90 * time.Minute |
| 194 | } |
| 195 | ready, cancelReady := context.WithTimeout(lifetime, timeout) |
| 196 | defer cancelReady() |
| 197 | stopReady := context.AfterFunc(ready, func() { client.Close() }) |
| 198 | defer stopReady() |
| 199 | output, err := cloudEntry(ready, client, p, secrets.Deploy, phase) |
| 200 | if err != nil { |
| 201 | return nil, err |
| 202 | } |
| 203 | var manifest ServerManifest |
| 204 | decoder := json.NewDecoder(bytes.NewReader(output)) |
| 205 | decoder.DisallowUnknownFields() |
| 206 | if decoder.Decode(&manifest) != nil { |
| 207 | return nil, failure("manifest_invalid", "云端 Cage 未返回有效连接信息") |
| 208 | } |
| 209 | var extra any |
| 210 | if decoder.Decode(&extra) != io.EOF { |
| 211 | return nil, failure("manifest_invalid", "云端 Cage 返回了多余连接信息") |
| 212 | } |
| 213 | if err = ValidateManifest(manifest); err != nil { |
| 214 | return nil, err |
| 215 | } |
| 216 | origin, _ := url.Parse(manifest.Origin) |
| 217 | targetHost := origin.Hostname() |
| 218 | if targetHost == "localhost" { |
| 219 | targetHost = "127.0.0.1" |
| 220 | } |
| 221 | target := net.JoinHostPort(targetHost, origin.Port()) |
| 222 | life, cancelLife := context.WithCancel(lifetime) |
| 223 | transport := &http.Transport{Proxy: nil, ForceAttemptHTTP2: false, MaxIdleConns: 32, MaxIdleConnsPerHost: 16, IdleConnTimeout: 60 * time.Second, ResponseHeaderTimeout: 30 * time.Second, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { |
| 224 | if network != "tcp" || address != origin.Host { |
| 225 | return nil, failure("origin_refused", "拒绝访问云端声明之外的服务") |
| 226 | } |
| 227 | return client.DialContext(ctx, "tcp", target) |
| 228 | }} |
| 229 | jar, _ := cookiejar.New(nil) |
| 230 | bound := &sessionTransport{base: transport, jar: jar, origin: manifest.Origin, ctx: life} |
| 231 | var once sync.Once |
| 232 | s := &Session{Manifest: manifest.Public(), Transport: bound, Context: life, Origin: manifest.Origin} |
| 233 | s.close = func() error { |
| 234 | once.Do(func() { cancelLife(); transport.CloseIdleConnections(); client.Close() }) |
| 235 | return nil |
| 236 | } |
| 237 | bound.invalidate = s.Close |
| 238 | s.Client = &http.Client{Transport: bound, CheckRedirect: func(*http.Request, []*http.Request) error { |
| 239 | return failure("redirect_refused", "云端服务重定向已拒绝") |
| 240 | }} |
| 241 | body, _ := json.Marshal(map[string]string{"token": manifest.Ticket}) |
| 242 | manifest.Ticket = "" |
| 243 | req, _ := http.NewRequestWithContext(ready, "POST", s.Origin+"/api/session", bytes.NewReader(body)) |
| 244 | req.Header.Set("Content-Type", "application/json") |
| 245 | response, err := s.Client.Do(req) |
| 246 | clear(body) |
| 247 | if err != nil { |
| 248 | s.Close() |
| 249 | return nil, failure("server_session_failed", "无法建立云端 Cage 会话") |
| 250 | } |
| 251 | io.Copy(io.Discard, io.LimitReader(response.Body, 4096)) |
| 252 | response.Body.Close() |
| 253 | if response.StatusCode != http.StatusOK || len(jar.Cookies(origin)) == 0 { |
| 254 | s.Close() |
| 255 | return nil, failure("server_session_failed", "云端 Cage 未接受连接票据") |
| 256 | } |
| 257 | if ready.Err() != nil { |
| 258 | s.Close() |
| 259 | return nil, failure("connection_cancelled", "远程连接已取消") |
| 260 | } |
| 261 | stopReady() |
| 262 | complete = true |
| 263 | go func() { _ = client.Wait(); s.Close() }() |
| 264 | context.AfterFunc(life, func() { s.Close() }) |
| 265 | return s, nil |
| 266 | } |
| 267 | |
| 268 | type sessionTransport struct { |
| 269 | base *http.Transport |
| 270 | jar http.CookieJar |
| 271 | origin string |
| 272 | ctx context.Context |
| 273 | invalidate func() error |
| 274 | } |
| 275 | |
| 276 | func (t *sessionTransport) RoundTrip(request *http.Request) (*http.Response, error) { |
| 277 | if request.URL.Scheme+"://"+request.URL.Host != t.origin || request.URL.User != nil { |
| 278 | return nil, failure("origin_refused", "拒绝访问云端声明之外的服务") |
| 279 | } |
| 280 | if err := t.ctx.Err(); err != nil { |
| 281 | return nil, failure("connection_changed", "远程连接已断开") |
| 282 | } |
| 283 | ctx, cancel := context.WithCancel(request.Context()) |
| 284 | stop := context.AfterFunc(t.ctx, cancel) |
| 285 | finish := func() { stop(); cancel() } |
| 286 | req := request.Clone(ctx) |
| 287 | req.Header = request.Header.Clone() |
| 288 | req.Host = req.URL.Host |
| 289 | req.Header.Del("Cookie") |
| 290 | req.Header.Del("Authorization") |
| 291 | req.Header.Del("Proxy-Authorization") |
| 292 | req.Header.Del("Idempotency-Key") |
| 293 | req.Header.Del("X-Idempotency-Key") |
| 294 | req.GetBody = nil |
| 295 | req.Header.Set("Origin", t.origin) |
| 296 | for _, cookie := range t.jar.Cookies(req.URL) { |
| 297 | req.AddCookie(cookie) |
| 298 | } |
| 299 | response, err := t.base.RoundTrip(req) |
| 300 | if err != nil { |
| 301 | finish() |
| 302 | return nil, failure("remote_request_failed", "远程请求中断,请检查连接;已提交的操作不会自动重发") |
| 303 | } |
| 304 | if response.StatusCode == http.StatusUnauthorized { |
| 305 | response.Body.Close() |
| 306 | finish() |
| 307 | if t.invalidate != nil { |
| 308 | _ = t.invalidate() |
| 309 | } |
| 310 | return nil, failure("remote_session_expired", "云端会话已失效,请重新连接并核对云端任务") |
| 311 | } |
| 312 | t.jar.SetCookies(req.URL, response.Cookies()) |
| 313 | response.Header.Del("Set-Cookie") |
| 314 | if response.StatusCode >= 300 && response.StatusCode < 400 && response.Header.Get("Location") != "" { |
| 315 | response.Body.Close() |
| 316 | finish() |
| 317 | return nil, failure("redirect_refused", "云端服务重定向已拒绝") |
| 318 | } |
| 319 | if rw, ok := response.Body.(io.ReadWriteCloser); ok { |
| 320 | response.Body = &cancelReadWriteCloser{ReadWriteCloser: rw, finish: finish} |
| 321 | } else { |
| 322 | response.Body = &cancelReadCloser{ReadCloser: response.Body, finish: finish} |
| 323 | } |
| 324 | return response, nil |
| 325 | } |
| 326 | |
| 327 | type cancelReadCloser struct { |
| 328 | io.ReadCloser |
| 329 | finish func() |
| 330 | once sync.Once |
| 331 | } |
| 332 | |
| 333 | func (b *cancelReadCloser) Read(p []byte) (int, error) { |
| 334 | n, e := b.ReadCloser.Read(p) |
| 335 | if e != nil { |
| 336 | b.once.Do(b.finish) |
| 337 | } |
| 338 | return n, e |
| 339 | } |
| 340 | func (b *cancelReadCloser) Close() error { |
| 341 | err := b.ReadCloser.Close() |
| 342 | b.once.Do(b.finish) |
| 343 | return err |
| 344 | } |
| 345 | |
| 346 | type cancelReadWriteCloser struct { |
| 347 | io.ReadWriteCloser |
| 348 | finish func() |
| 349 | once sync.Once |
| 350 | } |
| 351 | |
| 352 | func (b *cancelReadWriteCloser) Read(p []byte) (int, error) { |
| 353 | n, e := b.ReadWriteCloser.Read(p) |
| 354 | if e != nil { |
| 355 | b.once.Do(b.finish) |
| 356 | } |
| 357 | return n, e |
| 358 | } |
| 359 | func (b *cancelReadWriteCloser) Close() error { |
| 360 | err := b.ReadWriteCloser.Close() |
| 361 | b.once.Do(b.finish) |
| 362 | return err |
| 363 | } |