fix: pin native exports to stage execution service
This commit is contained in:
@@ -28,6 +28,7 @@ type Connection struct {
|
||||
Backend, Executable, Directory string
|
||||
URL string
|
||||
password string
|
||||
credentialFile string // V2 auth stays in the existing private service file
|
||||
// username overrides the backend-default basic-auth user for an
|
||||
// operator-supplied endpoint (PIPELINES_OPENCODE_ENDPOINT_USERNAME). It is
|
||||
// empty for the owned serve connection, which keeps the detected default.
|
||||
@@ -49,8 +50,9 @@ type Connection struct {
|
||||
unauthorized bool
|
||||
}
|
||||
|
||||
// Reference records only our ephemeral loopback service credentials, never provider auth.
|
||||
// The private file lets crash recovery abort the same owned service, not a new instance.
|
||||
// Reference retains the execution service, never provider auth. V1 retains its
|
||||
// ephemeral loopback password privately; V2 records only the existing credential
|
||||
// file's path and endpoint identity, so rotation can never redirect recovery.
|
||||
func (c *Connection) Reference() (string, error) {
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
@@ -64,7 +66,16 @@ func (c *Connection) Reference() (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, _ := json.Marshal(map[string]string{"url": c.URL, "password": c.password, "directory": c.Directory})
|
||||
reference := map[string]string{"url": c.URL, "password": c.password, "directory": c.Directory}
|
||||
if c.Backend == "v2" {
|
||||
if c.credentialFile == "" || c.URL == "" {
|
||||
_ = f.Close()
|
||||
_ = os.Remove(f.Name())
|
||||
return "", fmt.Errorf("V2 stage requires an existing service credential reference")
|
||||
}
|
||||
reference = map[string]string{"backend": "v2", "url": c.URL, "directory": c.Directory, "credentialFile": c.credentialFile}
|
||||
}
|
||||
data, _ := json.Marshal(reference)
|
||||
_, writeErr := f.Write(data)
|
||||
closeErr := f.Close()
|
||||
if writeErr != nil {
|
||||
@@ -91,10 +102,23 @@ func FromReference(path string) (*Connection, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var reference struct{ URL, Password, Directory string }
|
||||
var reference struct{ Backend, URL, Password, Directory, CredentialFile string }
|
||||
if err = json.Unmarshal(data, &reference); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if reference.Backend == "v2" {
|
||||
if !filepath.IsAbs(reference.CredentialFile) {
|
||||
return nil, fmt.Errorf("invalid V2 service credential reference")
|
||||
}
|
||||
c, err := serviceConnection(reference.CredentialFile, reference.Directory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.URL != reference.URL {
|
||||
return nil, fmt.Errorf("retained OpenCode service endpoint changed")
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
u, err := url.Parse(reference.URL)
|
||||
if err != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.Port() == "" || u.Path != "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || len(reference.Password) != 64 {
|
||||
return nil, fmt.Errorf("invalid owned OpenCode service endpoint")
|
||||
@@ -152,11 +176,15 @@ func Open(ctx context.Context, executable, directory, backend string) (*Connecti
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The V2 CLI talks to its own managed service, so stages reach it through the
|
||||
// `api` subcommand and Open returns no owned process for them. Only
|
||||
// OpenStream (brokered chat) opens the owned V2 endpoint.
|
||||
// V2 stages use the existing CLI-managed service, pinned before admission.
|
||||
// Missing registration fails closed: never discover/start another service.
|
||||
if c.Backend == "v2" {
|
||||
return c, nil
|
||||
managed, err := sessionExportConnection(c.Directory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
managed.Executable = c.Executable
|
||||
return managed, nil
|
||||
}
|
||||
if err := c.startServe(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -164,12 +192,35 @@ func Open(ctx context.Context, executable, directory, backend string) (*Connecti
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// PinCLI binds an api subprocess to this exact existing service, bypassing CLI
|
||||
// discovery (which could otherwise start or select a different service). Auth is
|
||||
// inherited privately, never passed in argv or persisted in ownership records.
|
||||
func (c *Connection) PinCLI(cmd *exec.Cmd) {
|
||||
if c.Backend != "v2" || c.URL == "" {
|
||||
return
|
||||
}
|
||||
cmd.Args = append(cmd.Args, "--server", c.URL)
|
||||
if cmd.Env == nil {
|
||||
cmd.Env = os.Environ()
|
||||
}
|
||||
for _, key := range []string{"OPENCODE_PASSWORD", "OPENCODE_SERVER_PASSWORD"} {
|
||||
filtered := cmd.Env[:0]
|
||||
for _, entry := range cmd.Env {
|
||||
if !strings.HasPrefix(entry, key+"=") {
|
||||
filtered = append(filtered, entry)
|
||||
}
|
||||
}
|
||||
cmd.Env = filtered
|
||||
}
|
||||
cmd.Env = append(cmd.Env, "OPENCODE_PASSWORD="+c.password)
|
||||
}
|
||||
|
||||
// OpenStream opens the single owned `opencode serve` endpoint for either backend
|
||||
// so a caller that needs a URL-bearing, SSE-capable connection (brokered chat)
|
||||
// gets one on the installed V2 CLI too. The V2 server exposes the authenticated
|
||||
// SSE event firehose at /api/event and the /api HTTP surface; the native serve
|
||||
// exposes /event and the translated /api surface. Stage generation keeps using
|
||||
// Open (the unstarted V2 connection plus its `api` subcommand), so this starts
|
||||
// Open (the pinned V2 connection plus its `api` subcommand), so this starts
|
||||
// no process for it and there is never a second transport.
|
||||
func OpenStream(ctx context.Context, executable, directory, backend string) (*Connection, error) {
|
||||
c, err := newConnection(ctx, executable, directory, backend)
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExecutionServiceReferencePinsIdentityAndAuth(t *testing.T) {
|
||||
c, calls := exportAPI(t, `{"data":{"info":{"id":"ses_ok"},"messages":[{"type":"user","text":"execution A"}]}}`, 200)
|
||||
chatCalls := 0
|
||||
chat := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
chatCalls++
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer chat.Close()
|
||||
state := t.TempDir()
|
||||
t.Setenv(OpenCodeServiceStateEnvKey, state)
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
t.Setenv(EndpointEnvKey, chat.URL)
|
||||
t.Setenv(EndpointUsernameEnvKey, "wrong-chat-user")
|
||||
chatPassword := filepath.Join(t.TempDir(), "chat-password")
|
||||
if err := os.WriteFile(chatPassword, []byte("chat-password"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv(EndpointPasswordFileEnvKey, chatPassword)
|
||||
if err := os.Mkdir(filepath.Join(state, "opencode"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(state, "opencode", "service.json")
|
||||
writeService := func(endpoint, password string) {
|
||||
t.Helper()
|
||||
data, _ := json.Marshal(map[string]string{"url": endpoint, "password": password})
|
||||
if err := os.WriteFile(path, data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
writeService(c.URL, c.password)
|
||||
owned, err := Open(context.Background(), "/must-not-run-cli", "/workspace", "v2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, err := owned.Reference()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := os.ReadFile(ref)
|
||||
if strings.Contains(string(data), c.password) || strings.Contains(string(data), `"password"`) {
|
||||
t.Fatal("credential copied into reference")
|
||||
}
|
||||
// Restart recovery remains on A, even when the chat endpoint and the state
|
||||
// discovery directory point elsewhere. Only the pinned private file is read.
|
||||
t.Setenv(OpenCodeServiceStateEnvKey, t.TempDir())
|
||||
recovered, err := FromReference(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := ExportSession(context.Background(), "/must-not-run-cli", "/workspace", "v2", "ses_ok", recovered)
|
||||
if err != nil || len(s.Messages) != 1 || *calls != 1 || chatCalls != 0 {
|
||||
t.Fatalf("export did not stay on execution A: %v", err)
|
||||
}
|
||||
t.Setenv("OPENCODE_PASSWORD", "foreign-password")
|
||||
t.Setenv("OPENCODE_SERVER_PASSWORD", "foreign-server-password")
|
||||
cmd := exec.Command("/must-not-run-cli", "api", "get", "/api/info")
|
||||
recovered.PinCLI(cmd)
|
||||
if strings.Join(cmd.Args[len(cmd.Args)-2:], " ") != "--server "+c.URL {
|
||||
t.Fatal("CLI discovery was not bypassed")
|
||||
}
|
||||
passwords := 0
|
||||
for _, entry := range cmd.Env {
|
||||
if strings.HasPrefix(entry, "OPENCODE_SERVER_PASSWORD=") {
|
||||
t.Fatal("foreign server auth survived")
|
||||
}
|
||||
if strings.HasPrefix(entry, "OPENCODE_PASSWORD=") {
|
||||
passwords++
|
||||
if entry != "OPENCODE_PASSWORD="+c.password {
|
||||
t.Fatal("CLI authentication does not match export")
|
||||
}
|
||||
}
|
||||
}
|
||||
if passwords != 1 {
|
||||
t.Fatal("CLI credential missing or duplicated")
|
||||
}
|
||||
writeService(c.URL, "wrong-password")
|
||||
wrong, err := FromReference(ref)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ExportSession(context.Background(), "/must-not-run-cli", "/workspace", "v2", "ses_ok", wrong); err == nil {
|
||||
t.Fatal("wrong execution credential accepted")
|
||||
}
|
||||
writeService(chat.URL, "chat-password")
|
||||
if _, err := FromReference(ref); err == nil || chatCalls != 0 {
|
||||
t.Fatal("changed service identity followed instead of failing closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutionServiceMissingDoesNotUseChatOrStartCLI(t *testing.T) {
|
||||
t.Setenv(OpenCodeServiceStateEnvKey, t.TempDir())
|
||||
t.Setenv(EndpointEnvKey, "http://127.0.0.1:1")
|
||||
if _, err := Open(context.Background(), "/must-not-run-cli", "/workspace", "v2"); err == nil {
|
||||
t.Fatal("missing execution service accepted")
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ func exportAPI(t *testing.T, body string, status int) (*Connection, *int) {
|
||||
*calls++
|
||||
user, pass, ok := r.BasicAuth()
|
||||
if !ok || user != "opencode" || pass != "test-export-password" {
|
||||
t.Error("missing endpoint authentication")
|
||||
w.WriteHeader(401)
|
||||
return
|
||||
}
|
||||
@@ -119,14 +118,14 @@ func TestV2ExportExistingServiceDiscoveryAndEndpointIsolation(t *testing.T) {
|
||||
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")
|
||||
if _, err := ExportSession(context.Background(), "/never-start-cli", "/workspace", "v2", "ses_ok"); err != nil || *calls != 2 {
|
||||
t.Fatal("chat endpoint redirected execution export")
|
||||
}
|
||||
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 {
|
||||
if _, err := ExportSession(context.Background(), "/never-start-cli", "/workspace", "v2", "ses_ok"); err == nil || *calls != 2 {
|
||||
t.Fatal("public service credential accepted")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -11,52 +12,36 @@ import (
|
||||
// never discovers by starting a CLI, serves a new backend, or pairs credentials.
|
||||
// Callers already holding the exact connection should pass it to ExportSession.
|
||||
func sessionExportConnection(directory string) (*Connection, error) {
|
||||
endpoint := strings.TrimSpace(os.Getenv(EndpointEnvKey))
|
||||
password, err := ReadEndpointCredentialFile(os.Getenv(EndpointPasswordFileEnvKey))
|
||||
path, err := ServiceCredentialPath()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if endpoint == "" || password == "" {
|
||||
path, err := ServiceCredentialPath()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
credential, err := ReadServiceCredential(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot read the local OpenCode endpoint")
|
||||
}
|
||||
var state struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
if json.Unmarshal(data, &state) != nil {
|
||||
return nil, fmt.Errorf("invalid local OpenCode endpoint")
|
||||
}
|
||||
base, err := NormalizeEndpointURL(state.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid local OpenCode endpoint")
|
||||
}
|
||||
if endpoint == "" {
|
||||
endpoint = base
|
||||
} else {
|
||||
configured, err := NormalizeEndpointURL(endpoint)
|
||||
if err != nil || configured != base {
|
||||
return nil, fmt.Errorf("session export endpoint requires its own credential")
|
||||
}
|
||||
}
|
||||
if password == "" {
|
||||
password = credential
|
||||
}
|
||||
}
|
||||
base, err := NormalizeEndpointURL(endpoint)
|
||||
return serviceConnection(path, directory)
|
||||
}
|
||||
|
||||
// serviceConnection reads only the existing CLI-managed service. Chat endpoint
|
||||
// overrides belong to a different transport and must never redirect stage work.
|
||||
func serviceConnection(path, directory string) (*Connection, error) {
|
||||
path, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("invalid local OpenCode credential path")
|
||||
}
|
||||
return &Connection{Backend: "v2", URL: base, Directory: directory, password: password,
|
||||
username: strings.TrimSpace(os.Getenv(EndpointUsernameEnvKey))}, nil
|
||||
if err := checkPrivateFile(path, serviceCredentialLimit); err != nil {
|
||||
return nil, fmt.Errorf("cannot read the local OpenCode service credential")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot read the local OpenCode endpoint")
|
||||
}
|
||||
var state struct{ URL, Password string }
|
||||
if json.Unmarshal(data, &state) != nil || strings.TrimSpace(state.Password) == "" {
|
||||
return nil, fmt.Errorf("invalid local OpenCode endpoint")
|
||||
}
|
||||
base, err := NormalizeEndpointURL(state.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid local OpenCode endpoint")
|
||||
}
|
||||
return &Connection{Backend: "v2", URL: base, Directory: directory, password: strings.TrimSpace(state.Password), credentialFile: path}, nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON retains the complete stored turn, including unknown metadata
|
||||
|
||||
Reference in New Issue
Block a user