Files
pipelines/internal/opencode/export_api_test.go
T

133 lines
5.9 KiB
Go

package opencode
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func exportAPI(t *testing.T, body string, status int) (*Connection, *int) {
t.Helper()
calls := new(int)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*calls++
user, pass, ok := r.BasicAuth()
if !ok || user != "opencode" || pass != "test-export-password" {
t.Error("missing endpoint authentication")
w.WriteHeader(401)
return
}
if r.Method != "GET" || r.URL.Path != "/api/experimental/session/ses_ok/export" || r.URL.Query().Get("sanitize") != "false" || r.URL.Query().Get("directory") != "/workspace" {
t.Errorf("unexpected export operation: %s %s", r.Method, r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
fmt.Fprint(w, body)
}))
t.Cleanup(srv.Close)
return &Connection{Backend: "v2", URL: srv.URL, Directory: "/workspace", password: "test-export-password"}, calls
}
func TestV2ExportHTTPPreservesLargeRealParts(t *testing.T) {
image := strings.Repeat("a", 400<<10)
body := `{"data":{"info":{"id":"ses_ok"},"messages":[` +
`{"id":"m1","type":"user","text":"inspect","files":[{"mime":"image/png","data":"` + image + `"}]},` +
`{"id":"m2","type":"assistant","agent":"survey","model":{"id":"luna","providerID":"local"},"content":[` +
`{"type":"reasoning","text":"observed"},{"type":"tool","name":"screenshot","state":{"status":"completed","input":{"path":"screen"},"content":[{"type":"file","mime":"image/png","data":"` + image + `"}]}},` +
`{"type":"text","text":"after the old CLI cap"}]}]}}`
c, calls := exportAPI(t, body, 200)
session, err := ExportSession(context.Background(), "/must-not-run-cli", "/workspace", "v2", "ses_ok", c)
if err != nil || session.Truncated || session.Attempts != 1 || *calls != 1 || len(session.Messages) != 2 {
t.Fatalf("large HTTP read failed: messages=%d truncated=%v attempts=%d calls=%d err=%v", len(session.Messages), session.Truncated, session.Attempts, *calls, err)
}
if string(session.Messages[0].Parts[1].Raw) != `{"mime":"image/png","data":"`+image+`"}` {
t.Fatal("inline user image not preserved")
}
m := session.Messages[1]
if m.ID != "m2" || m.Agent != "survey" || m.Model != "luna" || len(m.Parts) != 3 || m.Parts[0].Text != "observed" || m.Parts[2].Text != "after the old CLI cap" || !strings.Contains(string(m.Parts[1].Raw), image) || !json.Valid(m.Raw) {
t.Fatal("real tool/reasoning/identity lost")
}
}
func TestV2ExportHTTPFailuresDoNotSettleForever(t *testing.T) {
cutPrefix := `{"info":{"id":"ses_ok"},"messages":[{"type":"user","text":"`
cutAtCLICap := cutPrefix + strings.Repeat("x", 262144-len(cutPrefix))
for _, tc := range []struct {
name, body string
status int
}{
{"wrong-session", `{"data":{"info":{"id":"ses_other"},"messages":[]}}`, 200},
{"missing-identity", `{"data":{"messages":[]}}`, 200},
{"auth", `{"error":"private response"}`, 401},
{"not-found", `{}`, 404},
{"old-cli-cut", cutAtCLICap, 200},
} {
t.Run(tc.name, func(t *testing.T) {
c, calls := exportAPI(t, tc.body, tc.status)
s, err := ExportSession(context.Background(), "/must-not-run", "/workspace", "v2", "ses_ok", c)
if err == nil || s.Attempts != 1 || *calls != 1 || strings.Contains(err.Error(), "private response") {
t.Fatalf("permanent failure not bounded/sanitized: attempts=%d calls=%d err=%v", s.Attempts, *calls, err)
}
})
}
}
func TestV2ExportHTTPBoundedWrappedPrefix(t *testing.T) {
for _, initial := range []string{"", `{"id":"m1","type":"assistant","content":[{"type":"text","text":"first"}]},`} {
body := `{"data":{"info":{"id":"ses_ok"},"messages":[` + initial + `{"type":"user","text":"` + strings.Repeat("x", MaxSessionExport) + `"}]}}`
c, calls := exportAPI(t, body, 200)
s, err := ExportSession(context.Background(), "unused", "/workspace", "v2", "ses_ok", c)
if err != nil || !s.Truncated || *calls != 1 || len(s.Messages) != map[bool]int{true: 1, false: 0}[initial != ""] {
t.Fatalf("bounded wrapped prefix: messages=%d truncated=%v calls=%d err=%v", len(s.Messages), s.Truncated, *calls, err)
}
}
}
func TestV2ExportHTTPRecoveryIsBounded(t *testing.T) {
for _, status := range []int{200, 503} {
c, calls := exportAPI(t, `{"data":{"info":{"id":"ses_ok"},"messages":[]}}`, status)
s, err := ExportSession(context.Background(), "unused", "/workspace", "v2", "ses_ok", c)
if err == nil || *calls != 3 || s.Attempts != 3 {
t.Fatalf("HTTP %d recovery is not bounded: attempts=%d calls=%d err=%v", status, s.Attempts, *calls, err)
}
}
}
func TestV2ExportExistingServiceDiscoveryAndEndpointIsolation(t *testing.T) {
c, calls := exportAPI(t, `{"data":{"info":{"id":"ses_ok"},"messages":[{"type":"user","text":"real"}]}}`, 200)
stateDir := t.TempDir()
t.Setenv(OpenCodeServiceStateEnvKey, stateDir)
t.Setenv(EndpointEnvKey, "")
t.Setenv(EndpointPasswordFileEnvKey, "")
t.Setenv(EndpointUsernameEnvKey, "")
if err := os.Mkdir(filepath.Join(stateDir, "opencode"), 0700); err != nil {
t.Fatal(err)
}
data, _ := json.Marshal(map[string]string{"url": c.URL, "password": c.password})
path := filepath.Join(stateDir, "opencode", "service.json")
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
s, err := ExportSession(context.Background(), "/never-start-cli", "/workspace", "v2", "ses_ok")
if err != nil || len(s.Messages) != 1 || *calls != 1 {
t.Fatalf("existing service read: %v", err)
}
t.Setenv(EndpointEnvKey, "http://127.0.0.1:1")
if _, err := ExportSession(context.Background(), "/never-start-cli", "/workspace", "v2", "ses_ok"); err == nil || *calls != 1 {
t.Fatal("credential crossed endpoint boundary")
}
t.Setenv(EndpointEnvKey, "")
if err := os.Chmod(path, 0644); err != nil {
t.Fatal(err)
}
if _, err := ExportSession(context.Background(), "/never-start-cli", "/workspace", "v2", "ses_ok"); err == nil || *calls != 1 {
t.Fatal("public service credential accepted")
}
}