Secure, Fast, and Extensible Sandbox runtime for AI agents.
feat(execd): support browser PTY WebSocket token authentication
ninan.nn8559ab293124
diff --git a/components/execd/pkg/web/controller/pty_ws.go b/components/execd/pkg/web/controller/pty_ws.goindex ba2d6a0c2..c7b5a3adc 100644--- a/components/execd/pkg/web/controller/pty_ws.go+++ b/components/execd/pkg/web/controller/pty_ws.go@@ -35,6 +35,7 @@ import (var wsUpgrader = websocket.Upgrader{ReadBufferSize: 4096,WriteBufferSize: 4096,+ Subprotocols: []string{model.PTYWebSocketProtocol},// Allow all origins — execd runs behind a trusted reverse proxy.CheckOrigin: func(r *http.Request) bool { return true },}diff --git a/components/execd/pkg/web/model/pty_ws.go b/components/execd/pkg/web/model/pty_ws.goindex 749766685..aebe2d1d7 100644--- a/components/execd/pkg/web/model/pty_ws.go+++ b/components/execd/pkg/web/model/pty_ws.go@@ -14,6 +14,11 @@package model+const (+ PTYWebSocketProtocol = "opensandbox-pty"+ PTYWebSocketTokenPrefix = "base64url.bearer.execd.opensandbox."+)+type ClientFrame struct {Type string `json:"type"`Data string `json:"data,omitempty"`diff --git a/components/execd/pkg/web/pty_auth.go b/components/execd/pkg/web/pty_auth.gonew file mode 100644index 000000000..1d7edbed1--- /dev/null+++ b/components/execd/pkg/web/pty_auth.go@@ -0,0 +1,77 @@+// Copyright 2026 The OpenSandbox Authors+//+// 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 web++import (+ "encoding/base64"+ "net/http"+ "strings"++ "github.com/gin-gonic/gin"+ "github.com/gorilla/websocket"++ "github.com/alibaba/opensandbox/execd/pkg/web/model"+)++// requestAccessToken accepts the browser credential only on an actual PTY+// WebSocket upgrade. It strips credential entries before downstream handshake+// negotiation, including when an explicit API-token header takes precedence.+func requestAccessToken(ctx *gin.Context) (string, bool) {+ r := ctx.Request+ token := ""+ if r.Method == http.MethodGet && ctx.FullPath() == "/pty/:sessionId/ws" && websocket.IsWebSocketUpgrade(r) {+ const header = "Sec-WebSocket-Protocol"+ var protocols []string+ var encoded string+ credentialCount := 0+ hasPTYProtocol := false+ for _, value := range r.Header.Values(header) {+ for _, part := range strings.Split(value, ",") {+ protocol := strings.TrimSpace(part)+ if strings.HasPrefix(protocol, model.PTYWebSocketTokenPrefix) {+ credentialCount+++ encoded = strings.TrimPrefix(protocol, model.PTYWebSocketTokenPrefix)+ continue+ }+ if protocol == model.PTYWebSocketProtocol {+ hasPTYProtocol = true+ }+ if protocol != "" {+ protocols = append(protocols, protocol)+ }+ }+ }+ r.Header.Del(header)+ if len(protocols) > 0 {+ r.Header.Set(header, strings.Join(protocols, ", "))+ }+ if credentialCount > 0 {+ if credentialCount != 1 || !hasPTYProtocol {+ return "", false+ }+ decoded, err := base64.RawURLEncoding.Strict().DecodeString(encoded)+ if err != nil || len(decoded) == 0 || base64.RawURLEncoding.EncodeToString(decoded) != encoded {+ return "", false+ }+ token = string(decoded)+ }+ }+ // Presence, not a non-empty value, determines precedence. A bad explicit+ // header must not be rescued by a valid subprotocol credential.+ if _, present := r.Header[http.CanonicalHeaderKey(model.ApiAccessTokenHeader)]; present {+ return r.Header.Get(model.ApiAccessTokenHeader), true+ }+ return token, true+}diff --git a/components/execd/pkg/web/pty_auth_integration_test.go b/components/execd/pkg/web/pty_auth_integration_test.gonew file mode 100644index 000000000..c9a152e4d--- /dev/null+++ b/components/execd/pkg/web/pty_auth_integration_test.go@@ -0,0 +1,141 @@+//go:build !windows++// Copyright 2026 The OpenSandbox Authors+//+// 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 web++import (+ "encoding/base64"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/http/httputil"+ "net/url"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/stretchr/testify/require"++ "github.com/alibaba/opensandbox/execd/pkg/binding"+ "github.com/alibaba/opensandbox/execd/pkg/web/controller"+ "github.com/alibaba/opensandbox/execd/pkg/web/model"+)++func TestPTYBrowserWebSocketHandshake(t *testing.T) {+ const token = "browser/access+token="+ withRuntimeInit(t, false)+ withTestBinding(t, &binding.RuntimeBinding{HasAccessToken: true, AccessTokenHash: mustHash(t, token)})+ runner := controller.InitCodeRunner()+ execd := httptest.NewServer(NewRouter("obsolete-startup-token"))+ t.Cleanup(execd.Close)+ // Exercise an HTTP Upgrade proxy as well as the real execd router. Actual+ // deployment ingress and browser integration are separate acceptance checks.+ target, err := url.Parse(execd.URL)+ require.NoError(t, err)+ proxy := httptest.NewServer(httputil.NewSingleHostReverseProxy(target))+ t.Cleanup(proxy.Close)++ createSession := func() string {+ req, err := http.NewRequest(http.MethodPost, proxy.URL+"/pty", strings.NewReader(`{"command":"/bin/sh"}`))+ require.NoError(t, err)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set(model.ApiAccessTokenHeader, token)+ resp, err := proxy.Client().Do(req)+ require.NoError(t, err)+ defer resp.Body.Close()+ require.Equal(t, http.StatusCreated, resp.StatusCode)+ var created model.CreatePTYSessionResponse+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&created))+ require.NotEmpty(t, created.SessionID)+ t.Cleanup(func() { _ = runner.DeletePTYSession(created.SessionID) })+ return created.SessionID+ }+ credential := model.PTYWebSocketTokenPrefix + base64.RawURLEncoding.EncodeToString([]byte(token))+ protocols := []string{model.PTYWebSocketProtocol, credential}+ wsURL := "ws" + strings.TrimPrefix(proxy.URL, "http")+ id := createSession()+ for _, offered := range [][]string{+ nil,+ {model.PTYWebSocketProtocol, model.PTYWebSocketTokenPrefix + "d3Jvbmc"},+ {model.PTYWebSocketProtocol, credential, credential},+ {credential},+ } {+ dialer := websocket.Dialer{Subprotocols: offered, HandshakeTimeout: 3 * time.Second}+ _, resp, err := dialer.Dial(wsURL+"/pty/"+id+"/ws", nil)+ require.Error(t, err)+ require.NotNil(t, resp)+ require.Equal(t, http.StatusUnauthorized, resp.StatusCode)+ _ = resp.Body.Close()+ running, offset, err := runner.GetPTYSessionStatus(id)+ require.NoError(t, err)+ require.False(t, running, "rejected handshake must not start the shell")+ require.Zero(t, offset, "rejected handshake must not produce replay output")+ }++ dial := func(id, query string, offered []string, headers http.Header) *websocket.Conn {+ dialer := websocket.Dialer{Subprotocols: offered, HandshakeTimeout: 3 * time.Second}+ conn, resp, err := dialer.Dial(wsURL+"/pty/"+id+"/ws"+query, headers)+ require.NoError(t, err)+ t.Cleanup(func() { _ = conn.Close() })+ require.NotContains(t, resp.Header.Get("Sec-WebSocket-Protocol"), credential)+ if len(offered) > 0 {+ require.Equal(t, model.PTYWebSocketProtocol, conn.Subprotocol())+ } else {+ require.Empty(t, conn.Subprotocol())+ }+ require.NoError(t, conn.SetReadDeadline(time.Now().Add(3*time.Second)))+ for {+ kind, data, err := conn.ReadMessage()+ require.NoError(t, err)+ if kind != websocket.TextMessage {+ continue+ }+ var frame model.ServerFrame+ require.NoError(t, json.Unmarshal(data, &frame))+ if frame.Type == "connected" {+ return conn+ }+ }+ }++ holder := dial(id, "", protocols, nil)+ viewer := dial(id, "?mode=viewer", protocols, nil)+ require.NoError(t, holder.WriteJSON(model.ClientFrame{Type: "resize", Cols: 100, Rows: 35}))+ require.NoError(t, holder.WriteMessage(websocket.BinaryMessage, append([]byte{model.BinStdin}, []byte("printf browser-auth-ok\\n\n")...)))+ for _, conn := range []*websocket.Conn{holder, viewer} {+ var output strings.Builder+ for !strings.Contains(output.String(), "browser-auth-ok") {+ kind, data, err := conn.ReadMessage()+ require.NoError(t, err)+ if kind == websocket.BinaryMessage && len(data) > 0 {+ offset := 1+ if data[0] == model.BinReplay {+ offset = 9+ }+ if len(data) > offset {+ output.Write(data[offset:])+ }+ }+ }+ }++ // Header-only SDK/CLI clients still attach without any subprotocol.+ dial(createSession(), "", nil, http.Header{model.ApiAccessTokenHeader: []string{token}})+ // An explicitly valid header wins over a different, well-formed protocol token.+ dial(createSession(), "", []string{model.PTYWebSocketProtocol, model.PTYWebSocketTokenPrefix + "d3Jvbmc"},+ http.Header{model.ApiAccessTokenHeader: []string{token}})+}diff --git a/components/execd/pkg/web/pty_auth_test.go b/components/execd/pkg/web/pty_auth_test.gonew file mode 100644index 000000000..b3296359a--- /dev/null+++ b/components/execd/pkg/web/pty_auth_test.go@@ -0,0 +1,142 @@+// Copyright 2026 The OpenSandbox Authors+//+// 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 web++import (+ "encoding/base64"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/require"++ "github.com/alibaba/opensandbox/execd/pkg/binding"+ "github.com/alibaba/opensandbox/execd/pkg/web/model"+)++func browserPTYProtocols(token string) string {+ return model.PTYWebSocketProtocol + ", " + model.PTYWebSocketTokenPrefix + base64.RawURLEncoding.EncodeToString([]byte(token))+}++func TestPTYSubprotocolAuthentication(t *testing.T) {+ const token = "a/token+with=separators"+ credential := model.PTYWebSocketTokenPrefix + base64.RawURLEncoding.EncodeToString([]byte(token))+ for _, useBinding := range []bool{false, true} {+ mode := "startup-token"+ var runtimeBinding *binding.RuntimeBinding+ if useBinding {+ mode = "runtime-binding"+ runtimeBinding = &binding.RuntimeBinding{HasAccessToken: true, AccessTokenHash: mustHash(t, token)}+ }+ t.Run(mode, func(t *testing.T) {+ withTestBinding(t, runtimeBinding)+ legacyToken := token+ if useBinding {+ legacyToken = "superseded-startup-token"+ }+ tests := []struct {+ name string+ method string+ path string+ protocols []string+ header *string+ upgrade bool+ want int+ }{+ {name: "browser token", protocols: []string{browserPTYProtocols(token)}, upgrade: true, want: 200},+ {name: "multiple header lines", protocols: []string{model.PTYWebSocketProtocol, credential}, upgrade: true, want: 200},+ {name: "viewer", path: "/pty/p1/ws?mode=viewer", protocols: []string{browserPTYProtocols(token)}, upgrade: true, want: 200},+ {name: "missing token", upgrade: true, want: 401},+ {name: "wrong token", protocols: []string{browserPTYProtocols("wrong")}, upgrade: true, want: 401},+ {name: "empty token", protocols: []string{browserPTYProtocols("")}, upgrade: true, want: 401},+ {name: "invalid base64", protocols: []string{model.PTYWebSocketProtocol + ", " + model.PTYWebSocketTokenPrefix + "%%%"}, upgrade: true, want: 401},+ {name: "padded base64", protocols: []string{model.PTYWebSocketProtocol + ", " + model.PTYWebSocketTokenPrefix + "dA=="}, upgrade: true, want: 401},+ {name: "noncanonical base64", protocols: []string{model.PTYWebSocketProtocol + ", " + model.PTYWebSocketTokenPrefix + "dB"}, upgrade: true, want: 401},+ {name: "duplicate token", protocols: []string{browserPTYProtocols(token), credential}, upgrade: true, want: 401},+ {name: "conflicting tokens", protocols: []string{browserPTYProtocols(token), model.PTYWebSocketTokenPrefix + "dA"}, upgrade: true, want: 401},+ {name: "missing application protocol", protocols: []string{credential}, upgrade: true, want: 401},+ {name: "header only unchanged", header: stringPointer(token), upgrade: true, want: 200},+ {name: "header wins", header: stringPointer(token), protocols: []string{browserPTYProtocols("wrong")}, upgrade: true, want: 200},+ {name: "bad header cannot fall back", header: stringPointer("wrong"), protocols: []string{browserPTYProtocols(token)}, upgrade: true, want: 401},+ {name: "empty header cannot fall back", header: stringPointer(""), protocols: []string{browserPTYProtocols(token)}, upgrade: true, want: 401},+ {name: "malformed token rejected with valid header", header: stringPointer(token), protocols: []string{browserPTYProtocols(token), credential}, upgrade: true, want: 401},+ {name: "not an upgrade", protocols: []string{browserPTYProtocols(token)}, want: 401},+ {name: "not a PTY route", path: "/command", protocols: []string{browserPTYProtocols(token)}, upgrade: true, want: 401},+ {name: "PTY create needs header", method: http.MethodPost, path: "/pty", protocols: []string{browserPTYProtocols(token)}, upgrade: true, want: 401},+ {name: "PTY delete needs header", method: http.MethodDelete, path: "/pty/p1", protocols: []string{browserPTYProtocols(token)}, upgrade: true, want: 401},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ r := gin.New()+ r.Use(accessTokenMiddleware(legacyToken))+ handler := func(ctx *gin.Context) {+ if ctx.FullPath() == "/pty/:sessionId/ws" && tt.upgrade {+ for _, value := range ctx.Request.Header.Values("Sec-WebSocket-Protocol") {+ require.NotContains(t, value, model.PTYWebSocketTokenPrefix)+ }+ }+ ctx.Status(http.StatusOK)+ }+ r.GET("/pty/:sessionId/ws", handler)+ r.GET("/command", handler)+ r.POST("/pty", handler)+ r.DELETE("/pty/:sessionId", handler)+ method, path := tt.method, tt.path+ if method == "" {+ method = http.MethodGet+ }+ if path == "" {+ path = "/pty/p1/ws"+ }+ req := httptest.NewRequest(method, path, nil)+ for _, protocol := range tt.protocols {+ req.Header.Add("Sec-WebSocket-Protocol", protocol)+ }+ if tt.header != nil {+ req.Header.Set(model.ApiAccessTokenHeader, *tt.header)+ }+ if tt.upgrade {+ req.Header.Set("Connection", "Upgrade")+ req.Header.Set("Upgrade", "websocket")+ }+ rec := httptest.NewRecorder()+ r.ServeHTTP(rec, req)+ require.Equal(t, tt.want, rec.Code)+ require.NotContains(t, rec.Body.String(), token)+ require.NotContains(t, rec.Body.String(), credential)+ })+ }+ })+ }+}++func TestPTYSubprotocolDoesNotEnableAuthentication(t *testing.T) {+ withTestBinding(t, nil)+ r := gin.New()+ r.Use(accessTokenMiddleware(""))+ r.GET("/pty/:sessionId/ws", func(ctx *gin.Context) { ctx.Status(http.StatusOK) })+ for _, protocols := range []string{"", browserPTYProtocols("arbitrary")} {+ req := httptest.NewRequest(http.MethodGet, "/pty/p1/ws", nil)+ req.Header.Set("Connection", "Upgrade")+ req.Header.Set("Upgrade", "websocket")+ req.Header.Set("Sec-WebSocket-Protocol", protocols)+ rec := httptest.NewRecorder()+ r.ServeHTTP(rec, req)+ require.Equal(t, http.StatusOK, rec.Code)+ }+}++func stringPointer(value string) *string { return &value }diff --git a/components/execd/pkg/web/router.go b/components/execd/pkg/web/router.goindex 8b9b63323..4c5219e9d 100644--- a/components/execd/pkg/web/router.go+++ b/components/execd/pkg/web/router.go@@ -199,8 +199,13 @@ func accessTokenMiddleware(legacyToken string) gin.HandlerFunc {return}+ presented, valid := requestAccessToken(ctx)+ if !valid {+ abortUnauthorized(ctx)+ return+ }+if b := binding.Current(); b != nil && b.HasAccessToken {- presented := ctx.GetHeader(model.ApiAccessTokenHeader)if presented == "" || !b.VerifyAccessToken(presented) {abortUnauthorized(ctx)return@@ -220,8 +225,7 @@ func accessTokenMiddleware(legacyToken string) gin.HandlerFunc {return}- requestedToken := ctx.GetHeader(model.ApiAccessTokenHeader)- if requestedToken == "" || requestedToken != legacyToken {+ if presented == "" || presented != legacyToken {abortUnauthorized(ctx)return}diff --git a/docs/architecture/data-plane/execd.md b/docs/architecture/data-plane/execd.mdindex 738894536..30933d967 100644--- a/docs/architecture/data-plane/execd.md+++ b/docs/architecture/data-plane/execd.md@@ -28,7 +28,7 @@ Execd also fronts a small reverse proxy (`/proxy/{port}`), so one exposed host p## API surface-Everything execd exposes lives under one API. When the platform configures an access token, every endpoint below requires it in the `X-EXECD-ACCESS-TOKEN` header — only liveness and readiness are always open. The contract lives in [specs/execd-api.yaml](https://github.com/opensandbox-group/OpenSandbox/blob/main/specs/execd-api.yaml).+Everything execd exposes lives under one API. When the platform configures an access token, every endpoint below requires it in the `X-EXECD-ACCESS-TOKEN` header — only liveness and readiness are always open. PTY WebSocket handshakes also accept the browser-compatible credential described below. The contract lives in [specs/execd-api.yaml](https://github.com/opensandbox-group/OpenSandbox/blob/main/specs/execd-api.yaml).@@ -78,6 +78,24 @@ Each terminal session is a real PTY served over WebSocket — not a wrapped commThe sharing model is deliberate: exactly one **holder** owns the keyboard, and any number of **viewers** can watch. Viewers first replay what has already been printed, then follow live output — useful for supervision, debugging assistants, or letting a second person watch an agent work without giving it input.+### Browser WebSocket authentication++Browsers cannot attach an arbitrary `X-EXECD-ACCESS-TOKEN` header to a WebSocket handshake. For `GET /pty/{sessionId}/ws` only, a browser can instead offer the `opensandbox-pty` application subprotocol and one credential subprotocol whose suffix is the existing execd token encoded as unpadded base64url:++```javascript+const bytes = new TextEncoder().encode(execdToken);+const encoded = btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join(""))+ .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+const socket = new WebSocket(websocketUrl, [+ "opensandbox-pty",+ `base64url.bearer.execd.opensandbox.${encoded}`,+]);+```++Execd verifies the same token before upgrading the connection, removes the credential entry, and negotiates only `opensandbox-pty`. This works for both interactive attachments and `?mode=viewer`. An explicit `X-EXECD-ACCESS-TOKEN` header takes precedence, including when it is empty or invalid; it never falls back to a subprotocol token. Duplicate credentials, malformed encoding, and a credential without the application subprotocol are rejected with `401`. Existing header-authenticated clients do not need to offer a subprotocol. Other HTTP APIs, including PTY creation and deletion, still require the header when token protection is enabled.++This is a sandbox-wide credential, not a restricted terminal ticket. Obtain it through an authorized endpoint-resolution flow; do not place it in the URL or persistent browser storage. Use WSS in production: base64url is not encryption. Configure proxies and observability systems to redact the credential-bearing `Sec-WebSocket-Protocol` request header. An ingress signed URL satisfies ingress authentication only and does not replace execd authentication. The existing Origin policy and PTY disconnect/reconnect behavior are unchanged; deployments must enforce their browser-origin policy at the trusted gateway.+## Files and directoriesOne API covers the whole filesystem tree: stream files in and out, list and search directories, inspect and change permissions, replace file contents, move and remove paths. The file APIs in every sandbox SDK are a thin wrapper over these endpoints.