Files
ai/controllers/dev_bridge.go
zeekay 7571474398 an upgrade is a hijack, so the session owns what outlives the handler
The three websocket handlers move onto the fasthttp upgrader, which was already in
the module graph — gorilla's own fork for this server, same Conn, same
TextMessage, so the guacamole layer under the tunnel changed by its import line
and nothing else.

The shape does change, and it is the whole point. gorilla RETURNS a connection and
lets the handler carry on; fasthttp hands it to a CALLBACK, because an upgrade
detaches the socket from the request — the session runs after the handler's frame
is gone. So the session lives in the callback, and so does everything whose
lifetime is the connection's.

That is not a formality. DevBridge takes a global seat and a per-user seat before
upgrading and released both with `defer`. Left there, those defers now run while
the connection is still live: every accepted socket frees its own seat
immediately, both limits stop counting, and the pod accepts without bound —
exactly the failure the limits exist to prevent, and invisible until something
falls over. The seats are released by the CONNECTION now, through one `release`
that the session calls on the way out or the failed upgrade calls instead. Exactly
one of the two runs.

The pre-upgrade refusals answer through the context, which is the only thing left
that can still set a status: past the upgrade there is no response to write.

Zen's relay already took the callback's writer and its call site never supplied
one; it now runs inside the callback, with the status and headers set before it,
where they can still be set.

Down to the /v1/responses writer swap, which needs the completion to hand back its
non-streaming body rather than have it captured — the last thing here that reaches
into the context instead of being passed a value.
2026-08-17 05:13:12 -07:00

295 lines
8.6 KiB
Go

// Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"bufio"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/fasthttp/websocket"
"github.com/hanzoai/ai/log"
"github.com/valyala/fasthttp"
)
const (
maxBridgeConnsPerUser = 5
maxBridgeConnsGlobal = 50
)
var globalBridgeConns int64
// devBridgeUpgrader is a dedicated WebSocket upgrader for DevBridge with
// origin checking to prevent cross-site WebSocket hijacking. The global
// UpGrader in tunnel.go accepts all origins for guacamole compatibility;
// DevBridge must not share it.
var devBridgeUpgrader = websocket.FastHTTPUpgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: func(ctx *fasthttp.RequestCtx) bool {
origin := string(ctx.Request.Header.Peek("Origin"))
if origin == "" {
return true // non-browser clients (CLI, curl)
}
for _, allowed := range []string{
"https://cloud.hanzo.ai",
"https://platform.hanzo.ai",
"http://localhost:",
"http://127.0.0.1:",
} {
if strings.HasPrefix(origin, allowed) {
return true
}
}
return false
},
}
// bridgeConns tracks active bridge connections per user key (username or IP).
// Values are *int64 counters.
var bridgeConns sync.Map
// blockedPrefixes are system directories that cwd must never resolve into.
var blockedPrefixes = []string{"/etc", "/var", "/usr", "/bin", "/sbin", "/sys", "/proc"}
// validateCwd resolves cwd to an absolute path and rejects unsafe values.
func validateCwd(raw string) (string, error) {
if strings.Contains(raw, "..") {
return "", fmt.Errorf("path must not contain '..'")
}
abs, err := filepath.Abs(raw)
if err != nil {
return "", fmt.Errorf("cannot resolve path: %w", err)
}
abs = filepath.Clean(abs)
// Must exist and be a directory.
info, err := os.Stat(abs)
if err != nil {
return "", fmt.Errorf("path does not exist: %w", err)
}
if !info.IsDir() {
return "", fmt.Errorf("path is not a directory")
}
// Allow home dirs and /tmp only.
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("cannot determine home directory: %w", err)
}
inHome := strings.HasPrefix(abs, homeDir+"/") || abs == homeDir
inTmp := strings.HasPrefix(abs, "/tmp/") || abs == "/tmp"
if !inHome && !inTmp {
return "", fmt.Errorf("path must be under home directory or /tmp")
}
// Reject system directories even if they somehow appear under allowed roots.
for _, prefix := range blockedPrefixes {
if strings.HasPrefix(abs, prefix+"/") || abs == prefix {
return "", fmt.Errorf("path must not be a system directory")
}
}
return abs, nil
}
// DevBridge upgrades to WebSocket and bridges JSON-RPC messages between
// the browser and a hanzo-app-server instance.
//
// In local mode (default): spawns hanzo-app-server as a child process.
// In remote mode (?remote=host:port): proxies to a remote app-server via TCP.
//
// GET /api/dev-bridge?cwd=/path/to/project
// GET /api/dev-bridge?remote=host:port&cwd=/path/to/project
func (c *ApiController) DevBridge() {
// --- auth: require authenticated session ---
// DevBridge route does not match the get-/update-/add-/delete- prefixes
// checked by the permission filter, so we must gate auth explicitly.
user := c.GetSessionUser()
if user == nil {
c.ResponseError(c.T("auth:Please sign in first"))
return
}
// --- cwd validation ---
cwd := c.Input().Get("cwd")
if cwd == "" {
cwd = "."
}
safeCwd, err := validateCwd(cwd)
if err != nil {
log.Error(fmt.Sprintf("DevBridge: invalid cwd %q: %s", cwd, err.Error()))
_ = c.Bytes(http.StatusBadRequest, []byte(fmt.Sprintf(`{"error":"invalid cwd: %s"}`, err.Error())))
return
}
// --- global connection limit ---
if atomic.AddInt64(&globalBridgeConns, 1) > maxBridgeConnsGlobal {
atomic.AddInt64(&globalBridgeConns, -1)
log.Warn("DevBridge: global connection limit exceeded")
_ = c.Bytes(http.StatusServiceUnavailable, []byte(`{"error":"server at capacity"}`))
return
}
// --- per-user connection limit ---
userKey := GetUserName(user)
counterVal, _ := bridgeConns.LoadOrStore(userKey, new(int64))
counter := counterVal.(*int64)
if atomic.AddInt64(counter, 1) > maxBridgeConnsPerUser {
atomic.AddInt64(counter, -1)
log.Warn(fmt.Sprintf("DevBridge: connection limit exceeded for %s", userKey))
_ = c.Bytes(http.StatusTooManyRequests, []byte(`{"error":"too many concurrent connections"}`))
return
}
// Both seats are taken. Releasing them is the CONNECTION's job now, not this
// function's: a hijacked socket outlives the handler that upgraded it, so a
// defer here would free a seat still in use and the limit would stop counting.
// Exactly one caller runs this — the session below on the way out, or the
// upgrade's own failure arm.
release := func() {
atomic.AddInt64(&globalBridgeConns, -1)
atomic.AddInt64(counter, -1)
}
// fasthttp hands the upgraded connection to a CALLBACK instead of returning
// it, because an upgrade IS a hijack: the socket is detached from the request
// and the session runs on it after this function is done. So the session lives
// in here, and so does everything whose lifetime is the connection's.
if err := devBridgeUpgrader.Upgrade(c.Fiber().RequestCtx(), func(ws *websocket.Conn) {
defer release()
defer ws.Close()
// Resolve binary path from env or PATH.
appServerBin := os.Getenv("HANZO_APP_SERVER_BIN")
if appServerBin == "" {
appServerBin = "hanzo-app-server"
}
cmd := exec.Command(appServerBin)
cmd.Dir = safeCwd
stdin, err := cmd.StdinPipe()
if err != nil {
log.Error(fmt.Sprintf("DevBridge: stdin pipe: %s", err.Error()))
writeWSError(ws, "failed to create stdin pipe")
return
}
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Error(fmt.Sprintf("DevBridge: stdout pipe: %s", err.Error()))
writeWSError(ws, "failed to create stdout pipe")
return
}
if err := cmd.Start(); err != nil {
log.Error(fmt.Sprintf("DevBridge: start app-server: %s", err.Error()))
writeWSError(ws, "failed to start hanzo-app-server")
return
}
// --- process cleanup: always kill even on panic ---
defer func() {
_ = cmd.Process.Kill()
_ = cmd.Wait()
}()
var wsMu sync.Mutex
var wg sync.WaitGroup
done := make(chan struct{})
var doneOnce sync.Once
closeDone := func() { doneOnce.Do(func() { close(done) }) }
// WebSocket -> stdin: forward client JSON-RPC messages to app-server.
wg.Add(1)
go func() {
defer wg.Done()
defer stdin.Close()
defer closeDone()
for {
select {
case <-done:
return
default:
}
_, message, err := ws.ReadMessage()
if err != nil {
log.Info(fmt.Sprintf("DevBridge: ws read closed: %s", err.Error()))
return
}
if _, err := stdin.Write(append(message, '\n')); err != nil {
log.Error(fmt.Sprintf("DevBridge: stdin write: %s", err.Error()))
return
}
}
}()
// stdout -> WebSocket: forward app-server JSON-RPC responses to client.
wg.Add(1)
go func() {
defer wg.Done()
defer closeDone()
scanner := bufio.NewScanner(stdout)
scanner.Buffer(make([]byte, 1024*1024), 1024*1024)
for scanner.Scan() {
select {
case <-done:
return
default:
}
wsMu.Lock()
err := ws.WriteMessage(websocket.TextMessage, scanner.Bytes())
wsMu.Unlock()
if err != nil {
log.Error(fmt.Sprintf("DevBridge: ws write: %s", err.Error()))
return
}
}
if err := scanner.Err(); err != nil {
log.Error(fmt.Sprintf("DevBridge: stdout scan: %s", err.Error()))
}
}()
// --- wait with timeout to prevent goroutine leak ---
waitCh := make(chan struct{})
go func() {
wg.Wait()
close(waitCh)
}()
select {
case <-waitCh:
case <-time.After(30 * time.Second):
log.Warn("DevBridge: goroutine wait timed out after 30s, forcing cleanup")
closeDone()
_ = ws.Close()
}
}); err != nil {
release()
log.Error(fmt.Sprintf("DevBridge: websocket upgrade failed: %s", err.Error()))
}
}
func writeWSError(ws *websocket.Conn, msg string) {
_ = ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"error":"%s"}`, msg)))
}