Skip to content

Commit 94bfecd

Browse files
Gkrumbach07claude
andcommitted
fix(bff): preserve full policy fidelity and fix binary upload corruption
Two HIGH-severity data-integrity regressions from the SDK-migration audit. 1) Policy fidelity (models): the hand-rolled policy<->JSON converter only serialized 6 endpoint fields, silently dropping L7 allow/deny rules, IP allowlists, multi-port, MCP options, credential binding, signing, GraphQL persisted queries, and network middleware on both read AND write — a sandbox created or a rule edited with those fields lost them before reaching the gateway, weakening egress policy with no error. Replace it with a proto round-trip via protojson (policyproto.go ports the SDK's internal domain<->proto converter, which is not importable), reproducing the exact camelCase, full-fidelity JSON contract the pre-SDK code emitted. Unknown-field rejection is preserved. Added a round-trip test over a fully-populated policy. 2) Binary upload (files): uploads were piped through Exec().Interactive, which forces a PTY — terminal line discipline (EOF/flow-control bytes, CR/LF translation, echo) silently corrupts binary payloads. The SDK exposes no non-TTY stdin exec (Run has no stdin; Interactive forces TTY) and its file transport is a stub, on latest too. Add a small dedicated RawExecClient that calls the gateway's ExecSandbox RPC with Stdin bytes and Tty=false, resolving name->UUID via the SDK first. Uses the same address/TLS/bearer-forwarding as the main client. Added a bufconn test proving raw stdin bytes and Tty=false reach the server. Verified live against a local gateway (v0.0.85, podman): creating a sandbox with L7 rules / allowedIps / multi-port / denyRules and GETting it back preserves every field; the upload path issues ExecSandbox (non-TTY), with zero ExecSandboxInteractive calls. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Signed-off-by: Gage Krumbach <gkrumbac@redhat.com>
1 parent 68e8eaf commit 94bfecd

9 files changed

Lines changed: 964 additions & 244 deletions

File tree

‎backend/cmd/server/main.go‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,19 @@ func main() { //nolint:gocyclo // main is inherently branchy due to flag/config
122122
}
123123
defer sdkClient.Close()
124124

125-
app := api.NewApp(sdkClient, authMiddleware, *staticDir, authCfg)
125+
// Dedicated raw client for the one gateway capability the SDK omits:
126+
// non-TTY, stdin-carrying ExecSandbox, used for binary file upload.
127+
rawHost := sdkAddress
128+
rawHost = strings.TrimPrefix(rawHost, "https://")
129+
rawHost = strings.TrimPrefix(rawHost, "http://")
130+
uploadExec, err := sdkclient.NewRawExecClient(rawHost, *gatewayCACert, useTLS)
131+
if err != nil {
132+
slog.Error("upload exec client setup failed", "error", err)
133+
os.Exit(1)
134+
}
135+
defer uploadExec.Close()
136+
137+
app := api.NewApp(sdkClient, uploadExec, authMiddleware, *staticDir, authCfg)
126138

127139
addr := net.JoinHostPort(*listenAddress, *port)
128140
slog.Info("openshell-dashboard BFF listening",

‎backend/internal/api/app.go‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
package api
33

44
import (
5+
"context"
56
"net/http"
67
"os"
78
"path/filepath"
@@ -15,10 +16,18 @@ import (
1516
"github.com/Gkrumbach07/openshell-dashboard/backend/internal/auth"
1617
)
1718

19+
// StdinExecer runs a command in a sandbox with piped stdin and no TTY — the
20+
// binary-safe exec path the SDK does not expose. Used only for file upload.
21+
// Implemented by sdkclient.RawExecClient.
22+
type StdinExecer interface {
23+
ExecWithStdin(ctx context.Context, sandboxID string, command []string, stdin []byte) (string, int, error)
24+
}
25+
1826
// App wires the OpenShell SDK client, auth middleware, and REST routes.
1927
type App struct { //nolint:govet // fieldalignment: readability over padding
20-
sdk openshell.ClientInterface
21-
auth *auth.Middleware
28+
sdk openshell.ClientInterface
29+
execUpload StdinExecer
30+
auth *auth.Middleware
2231
// authConfig is serialized to the browser via GET /auth/config — never
2332
// put secrets in it.
2433
authConfig AuthConfigResponse
@@ -28,9 +37,10 @@ type App struct { //nolint:govet // fieldalignment: readability over padding
2837
}
2938

3039
// NewApp builds the application.
31-
func NewApp(sdkClient openshell.ClientInterface, authMiddleware *auth.Middleware, staticDir string, authCfg AuthConfigResponse) *App {
40+
func NewApp(sdkClient openshell.ClientInterface, execUpload StdinExecer, authMiddleware *auth.Middleware, staticDir string, authCfg AuthConfigResponse) *App {
3241
app := &App{
3342
sdk: sdkClient,
43+
execUpload: execUpload,
3444
auth: authMiddleware,
3545
authConfig: authCfg,
3646
staticDir: staticDir,

‎backend/internal/api/files_handler.go‎

Lines changed: 8 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package api
22

33
import (
4-
"bytes"
54
"context"
65
"fmt"
76
"io"
@@ -54,38 +53,6 @@ func resolveUploadDest(w http.ResponseWriter, destQuery, filename string) (strin
5453
return destPath, true
5554
}
5655

57-
type uploadSession interface {
58-
io.Reader
59-
io.Writer
60-
Close() error
61-
ExitCode() (int, error)
62-
}
63-
64-
func pipeUpload(session uploadSession, fileBytes []byte) (stdout string, exitCode int, err error) {
65-
var stdoutBuf bytes.Buffer
66-
drainDone := make(chan struct{})
67-
go func() {
68-
defer close(drainDone)
69-
_, _ = io.Copy(&stdoutBuf, session)
70-
}()
71-
72-
if _, writeErr := session.Write(fileBytes); writeErr != nil && writeErr != io.EOF {
73-
_ = session.Close()
74-
<-drainDone
75-
return stdoutBuf.String(), 0, writeErr
76-
}
77-
if closeErr := session.Close(); closeErr != nil {
78-
<-drainDone
79-
return stdoutBuf.String(), 0, closeErr
80-
}
81-
<-drainDone
82-
83-
if code, exitErr := session.ExitCode(); exitErr == nil {
84-
exitCode = code
85-
}
86-
return stdoutBuf.String(), exitCode, nil
87-
}
88-
8956
func (app *App) UploadFile(w http.ResponseWriter, r *http.Request) {
9057
workspace := chi.URLParam(r, "workspace")
9158
name := chi.URLParam(r, "name")
@@ -117,21 +84,22 @@ func (app *App) UploadFile(w http.ResponseWriter, r *http.Request) {
11784
return
11885
}
11986

120-
// Files().Upload is a stub in this SDK build (defaultSSHTransport.available
121-
// is always false). Pipe bytes into dd via Interactive stdin, matching the
122-
// pre-migration ExecSandbox contract.
87+
// The SDK exposes no non-TTY stdin exec (Run has no stdin; Interactive
88+
// forces a PTY that corrupts binary payloads) and its file transport is a
89+
// stub. Stream the bytes into `dd` over the gateway's non-TTY ExecSandbox
90+
// RPC via the dedicated raw client, resolving name -> sandbox UUID first.
12391
ctx, cancel := app.execContext(r.Context())
12492
defer cancel()
12593

126-
session, err := app.sdk.Exec().Interactive(ctx, workspace, name, []string{"dd", "of=" + destPath, "bs=4096"}, defaultTerminalCols, defaultTerminalRows)
94+
sandbox, err := app.sdk.Sandboxes().Get(ctx, workspace, name)
12795
if err != nil {
12896
writeSDKError(w, err)
12997
return
13098
}
13199

132-
stdout, exitCode, pipeErr := pipeUpload(session, fileBytes)
133-
if pipeErr != nil {
134-
writeSDKError(w, pipeErr)
100+
stdout, exitCode, execErr := app.execUpload.ExecWithStdin(ctx, sandbox.ID, []string{"dd", "of=" + destPath, "bs=4096"}, fileBytes)
101+
if execErr != nil {
102+
writeSDKError(w, execErr)
135103
return
136104
}
137105
if exitCode != 0 {

‎backend/internal/api/files_handler_test.go‎

Lines changed: 81 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -45,48 +45,75 @@ func TestValidateFilePath(t *testing.T) {
4545
}
4646
}
4747

48-
func TestUploadFile(t *testing.T) {
49-
session := &mockInteractiveSession{}
50-
sdk := &mockSDK{}
51-
sdk.exec.interactiveFn = func(_ context.Context, _, _ string, command []string, _, _ uint32, _ ...openshell.ExecOptions) (openshell.InteractiveSession, error) {
52-
if len(command) != 3 || command[0] != "dd" || command[1] != "of=/sandbox/hello.txt" || command[2] != "bs=4096" {
53-
t.Errorf("command = %v, want dd of=/sandbox/hello.txt bs=4096", command)
54-
}
55-
return session, nil
48+
// mockUploader is a test double for the non-TTY stdin exec (StdinExecer).
49+
type mockUploader struct {
50+
fn func(ctx context.Context, sandboxID string, command []string, stdin []byte) (string, int, error)
51+
gotID string
52+
gotCmd []string
53+
gotStdin []byte
54+
}
55+
56+
func (m *mockUploader) ExecWithStdin(ctx context.Context, sandboxID string, command []string, stdin []byte) (string, int, error) {
57+
m.gotID = sandboxID
58+
m.gotCmd = command
59+
m.gotStdin = append([]byte(nil), stdin...)
60+
if m.fn != nil {
61+
return m.fn(ctx, sandboxID, command, stdin)
5662
}
57-
app := newTestAppWithSDK(sdk)
58-
r := chi.NewRouter()
59-
r.Post("/workspaces/{workspace}/sandboxes/{name}/files", app.UploadFile)
63+
return "", 0, nil
64+
}
6065

66+
func uploadRequest(t *testing.T, filename, content string) *http.Request {
67+
t.Helper()
6168
body := &bytes.Buffer{}
6269
mw := multipart.NewWriter(body)
63-
part, err := mw.CreateFormFile("file", "hello.txt")
70+
part, err := mw.CreateFormFile("file", filename)
6471
if err != nil {
6572
t.Fatal(err)
6673
}
67-
if _, err := part.Write([]byte("hello")); err != nil {
74+
if _, err := part.Write([]byte(content)); err != nil {
6875
t.Fatal(err)
6976
}
7077
if err := mw.Close(); err != nil {
7178
t.Fatal(err)
7279
}
73-
7480
req := httptest.NewRequest(http.MethodPost, "/workspaces/default/sandboxes/sb/files", body)
7581
req.Header.Set("Content-Type", mw.FormDataContentType())
82+
return req
83+
}
84+
85+
func TestUploadFile(t *testing.T) {
86+
sdk := &mockSDK{}
87+
sdk.sandboxes.getFn = func(_ context.Context, workspace, name string) (*openshell.Sandbox, error) {
88+
if workspace != "default" || name != "sb" {
89+
t.Errorf("Get(%q,%q), want (default,sb)", workspace, name)
90+
}
91+
return &openshell.Sandbox{ID: "sb-uuid-123"}, nil
92+
}
93+
up := &mockUploader{fn: func(_ context.Context, sandboxID string, command []string, _ []byte) (string, int, error) {
94+
if sandboxID != "sb-uuid-123" {
95+
t.Errorf("sandboxID = %q, want sb-uuid-123 (resolved UUID, not name)", sandboxID)
96+
}
97+
if len(command) != 3 || command[0] != "dd" || command[1] != "of=/sandbox/hello.txt" || command[2] != "bs=4096" {
98+
t.Errorf("command = %v, want dd of=/sandbox/hello.txt bs=4096", command)
99+
}
100+
return "5+0 records in", 0, nil
101+
}}
102+
app := newTestAppWithSDK(sdk)
103+
app.execUpload = up
104+
r := chi.NewRouter()
105+
r.Post("/workspaces/{workspace}/sandboxes/{name}/files", app.UploadFile)
106+
107+
// Include a control byte (0x04 = EOT) that a PTY path would corrupt/truncate.
108+
content := "he\x04llo"
109+
req := uploadRequest(t, "hello.txt", content)
76110
w := httptest.NewRecorder()
77111
r.ServeHTTP(w, req)
78112
if w.Code != http.StatusOK {
79113
t.Fatalf("status = %d; body: %s", w.Code, w.Body.String())
80114
}
81-
session.mu.Lock()
82-
written := string(session.written)
83-
closed := session.closed
84-
session.mu.Unlock()
85-
if written != "hello" {
86-
t.Errorf("written = %q, want hello", written)
87-
}
88-
if !closed {
89-
t.Error("session not closed")
115+
if string(up.gotStdin) != content {
116+
t.Errorf("stdin = %q, want %q (raw bytes, no TTY mangling)", up.gotStdin, content)
90117
}
91118
var resp map[string]any
92119
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
@@ -97,6 +124,22 @@ func TestUploadFile(t *testing.T) {
97124
}
98125
}
99126

127+
func TestUploadFileSandboxNotFound(t *testing.T) {
128+
sdk := &mockSDK{}
129+
sdk.sandboxes.getFn = func(_ context.Context, _, _ string) (*openshell.Sandbox, error) {
130+
return nil, &openshell.StatusError{Code: openshell.ErrorNotFound, Message: "sandbox not found"}
131+
}
132+
app := newTestAppWithSDK(sdk)
133+
app.execUpload = &mockUploader{}
134+
r := chi.NewRouter()
135+
r.Post("/workspaces/{workspace}/sandboxes/{name}/files", app.UploadFile)
136+
w := httptest.NewRecorder()
137+
r.ServeHTTP(w, uploadRequest(t, "hello.txt", "hi"))
138+
if w.Code != http.StatusNotFound {
139+
t.Fatalf("status = %d, want 404; body: %s", w.Code, w.Body.String())
140+
}
141+
}
142+
100143
func TestDownloadFile(t *testing.T) {
101144
sdk := &mockSDK{}
102145
sdk.exec.runFn = func(_ context.Context, _, _ string, command []string, _ ...openshell.ExecOptions) (*openshell.ExecResult, error) {
@@ -136,32 +179,20 @@ func TestDownloadFileNotFound(t *testing.T) {
136179
}
137180

138181
func TestUploadFileFailed(t *testing.T) {
139-
session := &mockInteractiveSession{exit: 1}
140182
sdk := &mockSDK{}
141-
sdk.exec.interactiveFn = func(_ context.Context, _, _ string, _ []string, _, _ uint32, _ ...openshell.ExecOptions) (openshell.InteractiveSession, error) {
142-
return session, nil
183+
sdk.sandboxes.getFn = func(_ context.Context, _, _ string) (*openshell.Sandbox, error) {
184+
return &openshell.Sandbox{ID: "sb-uuid-123"}, nil
143185
}
186+
up := &mockUploader{fn: func(_ context.Context, _ string, _ []string, _ []byte) (string, int, error) {
187+
return "dd: write error", 1, nil
188+
}}
144189
app := newTestAppWithSDK(sdk)
190+
app.execUpload = up
145191
r := chi.NewRouter()
146192
r.Post("/workspaces/{workspace}/sandboxes/{name}/files", app.UploadFile)
147193

148-
body := &bytes.Buffer{}
149-
mw := multipart.NewWriter(body)
150-
part, err := mw.CreateFormFile("file", "hello.txt")
151-
if err != nil {
152-
t.Fatal(err)
153-
}
154-
if _, err := part.Write([]byte("hello")); err != nil {
155-
t.Fatal(err)
156-
}
157-
if err := mw.Close(); err != nil {
158-
t.Fatal(err)
159-
}
160-
161-
req := httptest.NewRequest(http.MethodPost, "/workspaces/default/sandboxes/sb/files", body)
162-
req.Header.Set("Content-Type", mw.FormDataContentType())
163194
w := httptest.NewRecorder()
164-
r.ServeHTTP(w, req)
195+
r.ServeHTTP(w, uploadRequest(t, "hello.txt", "hello"))
165196
if w.Code != http.StatusBadGateway {
166197
t.Fatalf("status = %d, want 502; body: %s", w.Code, w.Body.String())
167198
}
@@ -170,32 +201,21 @@ func TestUploadFileFailed(t *testing.T) {
170201
}
171202
}
172203

173-
func TestUploadFileInteractiveError(t *testing.T) {
204+
func TestUploadFileExecError(t *testing.T) {
174205
sdk := &mockSDK{}
175-
sdk.exec.interactiveFn = func(_ context.Context, _, _ string, _ []string, _, _ uint32, _ ...openshell.ExecOptions) (openshell.InteractiveSession, error) {
176-
return nil, fmt.Errorf("exec unavailable")
206+
sdk.sandboxes.getFn = func(_ context.Context, _, _ string) (*openshell.Sandbox, error) {
207+
return &openshell.Sandbox{ID: "sb-uuid-123"}, nil
177208
}
209+
up := &mockUploader{fn: func(_ context.Context, _ string, _ []string, _ []byte) (string, int, error) {
210+
return "", 0, fmt.Errorf("exec unavailable")
211+
}}
178212
app := newTestAppWithSDK(sdk)
213+
app.execUpload = up
179214
r := chi.NewRouter()
180215
r.Post("/workspaces/{workspace}/sandboxes/{name}/files", app.UploadFile)
181216

182-
body := &bytes.Buffer{}
183-
mw := multipart.NewWriter(body)
184-
part, err := mw.CreateFormFile("file", "hello.txt")
185-
if err != nil {
186-
t.Fatal(err)
187-
}
188-
if _, err := part.Write([]byte("hello")); err != nil {
189-
t.Fatal(err)
190-
}
191-
if err := mw.Close(); err != nil {
192-
t.Fatal(err)
193-
}
194-
195-
req := httptest.NewRequest(http.MethodPost, "/workspaces/default/sandboxes/sb/files", body)
196-
req.Header.Set("Content-Type", mw.FormDataContentType())
197217
w := httptest.NewRecorder()
198-
r.ServeHTTP(w, req)
218+
r.ServeHTTP(w, uploadRequest(t, "hello.txt", "hello"))
199219
if w.Code != http.StatusInternalServerError {
200220
t.Fatalf("status = %d, want 500; body: %s", w.Code, w.Body.String())
201221
}

0 commit comments

Comments
 (0)