Broker chat from an operator's own OpenCode endpoint and adopt existing sessions
Add an opt-in way to broker chat from an operator-supplied OpenCode service instead of the instance the server spawns for itself, and a way to adopt a session that already exists on that endpoint so it appears in chat_sessions and can be continued from the app. - Endpoint selection: the `-opencode-endpoint` server flag (defaulting to `PIPELINES_OPENCODE_ENDPOINT`) opts in; precedence is explicit flag > explicit environment > the endpoint recorded on a previous run, with the spawned instance as the default. opencode.OpenEndpoint validates the reference once (http(s), host, no userinfo/query/fragment/path), detects the backend from its own /api/info (v2) or /global/health (v1) contract, and requires a streamable text/event-stream event path. It owns no process (Close is a no-op) and never calls startServe; every failure names the endpoint and disables chat rather than silently falling back. An authenticated endpoint takes an optional password only through the private file PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE, with PIPELINES_OPENCODE_ENDPOINT_USERNAME overriding the detected default. - Persistence: the validated choice is recorded in an additive single-row server_settings table so a restart with no flag/environment reuses it; an unreachable recorded endpoint disables chat with a clear message and no fallback. - chat_adopt: a new protocol request (ChatAdoptRequest) with handleChatAdopt in internal/server/chat.go. It refuses a nil broker/registry/payload and a blank or foreign-shaped id before any endpoint call, reads the endpoint via the shared Chat.Session (which reuses Sessions/decodeChatSessions), records through the existing RecordOperatorSession with the endpoint's directory and title verbatim, and echoes the adopted session plus its registry row like chat_create. A missing id is refused naming the id and records nothing; an endpoint record with an empty directory is refused rather than substituting the server's working directory or home. - CLI: `pipelines chat-adopt <session-id> [--json]` (usage, notes, help inventory, dispatch) with docs/cli.md updated under Chat sessions. - Autostart preserves the endpoint variables (and the password-file reference, never an inline secret) via serviceEnvironmentKeys. Checks before committing: - Package location: the change is user-facing chat behaviour, so the packaged authoring skill reference internal/author/skill/references/operations.md is updated in the same change (Brokered OpenCode chat section) with a dated verification-evidence entry and the not-deployed state. No new reference file is added, so internal/author/install.go's managed inventory is unchanged. - Packaged templates: this repository packages no template set for this behaviour and none references the chat endpoint, so no template needs updating. - Verification: `go build ./...`, `go vet` on the touched packages, `gofmt -l` clean and `go test ./...` all pass. The unit tests cover the endpoint validation/precedence, the adopt happy path and refusals, the recorded endpoint round-trip, the protocol round-trip and the CLI dispatch. The live scratch-server check against the operator's real endpoint was not run in this change. Nothing unrelated is staged; docs left stale (README and other shared documents) are not edited here and are for a single folding writer.
This commit is contained in:
@@ -154,6 +154,27 @@ func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.Ch
|
||||
return decodeChatSession(data)
|
||||
}
|
||||
|
||||
// Session returns the endpoint's own record of one session so a caller can adopt
|
||||
// an existing session with the directory and title the endpoint reports, never a
|
||||
// guessed directory. found is false when the endpoint does not list id. It
|
||||
// reuses Sessions/decodeChatSessions, so no second session decoder or endpoint is
|
||||
// introduced; it performs at most one bounded endpoint read.
|
||||
func (c *Chat) Session(ctx context.Context, id string) (protocol.ChatSession, bool, error) {
|
||||
if !ValidSessionID(id) {
|
||||
return protocol.ChatSession{}, false, fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
sessions, err := c.Sessions(ctx)
|
||||
if err != nil {
|
||||
return protocol.ChatSession{}, false, err
|
||||
}
|
||||
for _, session := range sessions {
|
||||
if session.ID == id {
|
||||
return session, true, nil
|
||||
}
|
||||
}
|
||||
return protocol.ChatSession{}, false, nil
|
||||
}
|
||||
|
||||
// Reply posts a permission decision, mirroring the documented endpoint.
|
||||
func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
|
||||
if !sessionID.MatchString(request.SessionID) {
|
||||
|
||||
@@ -28,16 +28,20 @@ type Connection struct {
|
||||
Backend, Executable, Directory string
|
||||
URL string
|
||||
password string
|
||||
process *exec.Cmd
|
||||
done chan error
|
||||
models map[string]map[string]string
|
||||
responses map[string][]byte
|
||||
formatChecked bool
|
||||
formatSupported bool
|
||||
FormatProbe *FormatProbe
|
||||
LastHTTPStatus int
|
||||
LastHTTPOperation string
|
||||
MessageReadbackDiagnostic string
|
||||
// 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.
|
||||
username string
|
||||
process *exec.Cmd
|
||||
done chan error
|
||||
models map[string]map[string]string
|
||||
responses map[string][]byte
|
||||
formatChecked bool
|
||||
formatSupported bool
|
||||
FormatProbe *FormatProbe
|
||||
LastHTTPStatus int
|
||||
LastHTTPOperation string
|
||||
MessageReadbackDiagnostic string
|
||||
}
|
||||
|
||||
// Reference records only our ephemeral loopback service credentials, never provider auth.
|
||||
@@ -204,6 +208,9 @@ func newConnection(ctx context.Context, executable, directory, backend string) (
|
||||
// authenticates the fixed "opencode" user regardless of
|
||||
// OPENCODE_SERVER_USERNAME, verified against the installed 2.0.20 binary.
|
||||
func (c *Connection) serverUser() string {
|
||||
if c.username != "" {
|
||||
return c.username
|
||||
}
|
||||
if c.Backend == "v2" {
|
||||
return "opencode"
|
||||
}
|
||||
@@ -280,22 +287,12 @@ func (c *Connection) startServe(ctx context.Context) error {
|
||||
// healthy one.
|
||||
func (c *Connection) checkHealth(ctx context.Context) error {
|
||||
if c.Backend == "v2" {
|
||||
info, err := c.Native(ctx, "get", "/api/info", nil)
|
||||
var result struct {
|
||||
Version string `json:"version"`
|
||||
URLs []string `json:"urls"`
|
||||
}
|
||||
if err != nil || json.Unmarshal(info, &result) != nil || result.Version == "" {
|
||||
if err := c.probeHealth(ctx, "v2"); err != nil {
|
||||
return fmt.Errorf("OpenCode serve did not return the expected V2 info contract")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
health, err := c.Native(ctx, "get", "/global/health", nil)
|
||||
var result struct {
|
||||
Healthy bool `json:"healthy"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err != nil || json.Unmarshal(health, &result) != nil || !result.Healthy || result.Version == "" {
|
||||
if err := c.probeHealth(ctx, "v1"); err != nil {
|
||||
return fmt.Errorf("OpenCode serve did not return the expected native health contract")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Environment keys for the operator-supplied OpenCode endpoint. The endpoint
|
||||
// itself is opt-in: when none of the flag, these variables or the recorded
|
||||
// setting is present the server keeps today's spawned default. The password is
|
||||
// accepted only through a private file reference (never inline), mirroring the
|
||||
// ntfy token-file rule; an optional username overrides the detected default.
|
||||
const (
|
||||
EndpointEnvKey = "PIPELINES_OPENCODE_ENDPOINT"
|
||||
EndpointPasswordFileEnvKey = "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE"
|
||||
EndpointUsernameEnvKey = "PIPELINES_OPENCODE_ENDPOINT_USERNAME"
|
||||
)
|
||||
|
||||
// endpointProbeTimeout bounds each startup probe (health and SSE) so an
|
||||
// unreachable endpoint fails fast instead of hanging server startup.
|
||||
const endpointProbeTimeout = 5 * time.Second
|
||||
|
||||
// endpointPasswordFileLimit bounds the credential file read.
|
||||
const endpointPasswordFileLimit = 4096
|
||||
|
||||
// ResolveEndpointRef picks the operator's OpenCode endpoint reference by
|
||||
// precedence: explicit flag > explicit environment > the endpoint recorded on a
|
||||
// previous run. An empty result means no endpoint is configured, so the caller
|
||||
// keeps today's spawned-instance default. It is the single precedence resolver
|
||||
// used by the server and its tests so the choice cannot drift.
|
||||
func ResolveEndpointRef(flagValue, envValue, recorded string) string {
|
||||
for _, value := range []string{flagValue, envValue, recorded} {
|
||||
if value = strings.TrimSpace(value); value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// NormalizeEndpointURL validates an operator-supplied endpoint the way the other
|
||||
// endpoint references are validated: an http(s) URL with a non-empty host, no
|
||||
// userinfo, no query, no fragment and an empty or "/" path. Anything else is a
|
||||
// clear error naming the endpoint rather than a silently guessed base.
|
||||
func NormalizeEndpointURL(raw string) (string, error) {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") ||
|
||||
u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") {
|
||||
return "", fmt.Errorf("invalid OpenCode endpoint %q: use an http(s) URL with a host and no credentials, query, fragment or path", raw)
|
||||
}
|
||||
return strings.TrimRight(u.String(), "/"), nil
|
||||
}
|
||||
|
||||
// ReadEndpointCredentialFile reads the optional endpoint password from a private
|
||||
// file reference, mirroring the ntfy token-file rule: a regular, single-owner
|
||||
// 0600 file with a bounded read. An empty path yields no password, so an endpoint
|
||||
// that authenticates with the default user only keeps working.
|
||||
func ReadEndpointCredentialFile(path string) (string, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", nil
|
||||
}
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot read the OpenCode endpoint password file")
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size() > endpointPasswordFileLimit {
|
||||
return "", fmt.Errorf("invalid OpenCode endpoint password file")
|
||||
}
|
||||
if stat, ok := info.Sys().(*syscall.Stat_t); !ok || stat.Uid != uint32(os.Getuid()) {
|
||||
return "", fmt.Errorf("the OpenCode endpoint password file belongs to another user")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("cannot read the OpenCode endpoint password file")
|
||||
}
|
||||
return strings.TrimSpace(string(data)), nil
|
||||
}
|
||||
|
||||
// OpenEndpoint opens an operator-supplied OpenCode endpoint without owning a
|
||||
// process: the returned Connection has no owned process (Close is a no-op), so
|
||||
// nothing local is ever spawned, and it is never used to reach a different
|
||||
// instance. The endpoint reference is validated once here (URL shape, then the
|
||||
// backend-specific health contract, then a streamable event path) and every
|
||||
// failure names the endpoint; there is no fallback and no retry loop.
|
||||
func OpenEndpoint(ctx context.Context, rawURL, password string) (*Connection, error) {
|
||||
base, err := NormalizeEndpointURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn := &Connection{
|
||||
URL: base,
|
||||
password: password,
|
||||
username: strings.TrimSpace(os.Getenv(EndpointUsernameEnvKey)),
|
||||
models: map[string]map[string]string{},
|
||||
responses: map[string][]byte{},
|
||||
}
|
||||
probeCtx, cancel := context.WithTimeout(ctx, endpointProbeTimeout)
|
||||
defer cancel()
|
||||
switch {
|
||||
case conn.probeHealth(probeCtx, "v2") == nil:
|
||||
conn.Backend = "v2"
|
||||
case conn.probeHealth(probeCtx, "v1") == nil:
|
||||
conn.Backend = "v1"
|
||||
default:
|
||||
return nil, fmt.Errorf("OpenCode endpoint %s is unreachable or is not an OpenCode service", base)
|
||||
}
|
||||
// Require a streamable event endpoint before the endpoint is accepted: a
|
||||
// healthy service without SSE cannot broker chat, so it is a clear refusal,
|
||||
// never a silent fallback to another instance.
|
||||
streamCtx, cancelStream := context.WithTimeout(ctx, endpointProbeTimeout)
|
||||
defer cancelStream()
|
||||
body, err := conn.EventStream(streamCtx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("OpenCode endpoint %s exposes no streamable event endpoint: %w", base, err)
|
||||
}
|
||||
body.Close()
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// probeHealth checks one backend family's readiness contract through the same
|
||||
// authenticated request path the adapter uses, so a reachable but unauthorized
|
||||
// endpoint is not mistaken for a healthy one. checkHealth and OpenEndpoint share
|
||||
// it, so the endpoint contract is defined once.
|
||||
func (c *Connection) probeHealth(ctx context.Context, backend string) error {
|
||||
previous := c.Backend
|
||||
c.Backend = backend
|
||||
defer func() { c.Backend = previous }()
|
||||
if backend == "v2" {
|
||||
info, err := c.nativeRequest(ctx, "get", "/api/info", nil, "")
|
||||
var result struct {
|
||||
Version string `json:"version"`
|
||||
URLs []string `json:"urls"`
|
||||
}
|
||||
if err != nil || json.Unmarshal(info, &result) != nil || result.Version == "" {
|
||||
return fmt.Errorf("no V2 info contract")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
health, err := c.nativeRequest(ctx, "get", "/global/health", nil, "")
|
||||
var result struct {
|
||||
Healthy bool `json:"healthy"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if err != nil || json.Unmarshal(health, &result) != nil || !result.Healthy || result.Version == "" {
|
||||
return fmt.Errorf("no native health contract")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestResolveEndpointRef pins the precedence the server and its tests share:
|
||||
// explicit flag beats explicit environment beats the recorded setting, and an
|
||||
// all-empty input means no endpoint is configured (today's spawned default).
|
||||
func TestResolveEndpointRef(t *testing.T) {
|
||||
cases := []struct {
|
||||
flag, env, recorded, want string
|
||||
}{
|
||||
{"http://flag", "http://env", "http://recorded", "http://flag"},
|
||||
{"", "http://env", "http://recorded", "http://env"},
|
||||
{"", "", "http://recorded", "http://recorded"},
|
||||
{" ", " ", " ", ""},
|
||||
{"", "", "", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ResolveEndpointRef(tc.flag, tc.env, tc.recorded); got != tc.want {
|
||||
t.Fatalf("ResolveEndpointRef(%q,%q,%q) = %q, want %q", tc.flag, tc.env, tc.recorded, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeEndpointURLRejectsMalformed pins the validation idiom: only an
|
||||
// http(s) URL with a host and no credentials, query, fragment or path is
|
||||
// accepted, and every rejection names the endpoint.
|
||||
func TestNormalizeEndpointURLRejectsMalformed(t *testing.T) {
|
||||
bad := []string{
|
||||
"ftp://host", "host:1234", "http://", "http:///path",
|
||||
"http://user:pass@host", "http://host/?q=1", "http://host/#frag",
|
||||
"http://host/base", "http://host/base/", "",
|
||||
}
|
||||
for _, raw := range bad {
|
||||
if got, err := NormalizeEndpointURL(raw); err == nil {
|
||||
t.Fatalf("NormalizeEndpointURL(%q) = %q, want error", raw, got)
|
||||
} else if raw != "" && !strings.Contains(err.Error(), raw) && !strings.Contains(err.Error(), "invalid OpenCode endpoint") {
|
||||
// The error always names the endpoint or states the rule.
|
||||
t.Fatalf("NormalizeEndpointURL(%q) error %v does not name the endpoint", raw, err)
|
||||
}
|
||||
}
|
||||
for raw, want := range map[string]string{
|
||||
"http://host:1234": "http://host:1234",
|
||||
"https://host/": "https://host",
|
||||
"http://127.0.0.1:4096/": "http://127.0.0.1:4096",
|
||||
} {
|
||||
got, err := NormalizeEndpointURL(raw)
|
||||
if err != nil || got != want {
|
||||
t.Fatalf("NormalizeEndpointURL(%q) = %q,%v want %q", raw, got, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// v2Endpoint serves the V2 contract: /api/info and a text/event-stream
|
||||
// /api/event. user/pass assert the fixed basic-auth user unless overridden.
|
||||
func v2Endpoint(t *testing.T, wantUser string) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if wantUser != "" {
|
||||
if user, _, _ := r.BasicAuth(); user != wantUser {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/info":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"version":"2.0.20","urls":[]}`))
|
||||
case "/api/event":
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// v1Endpoint serves the native contract: /global/health and /event.
|
||||
func v1Endpoint(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/global/health":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"healthy":true,"version":"1.0.0"}`))
|
||||
case "/event":
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// TestOpenEndpointDetectsBackendsAndOwnsNoProcess pins that the explicit path
|
||||
// returns a connection with no owned process (Close is a no-op and no local
|
||||
// serve is ever spawned), detecting each backend from its own health contract.
|
||||
func TestOpenEndpointDetectsBackendsAndOwnsNoProcess(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
srv *httptest.Server
|
||||
backend string
|
||||
}{
|
||||
{"v2", v2Endpoint(t, "opencode"), "v2"},
|
||||
{"v1", v1Endpoint(t), "v1"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
conn, err := OpenEndpoint(ctx, tc.srv.URL, "")
|
||||
if err != nil {
|
||||
t.Fatalf("OpenEndpoint: %v", err)
|
||||
}
|
||||
if conn.Backend != tc.backend || conn.URL != tc.srv.URL {
|
||||
t.Fatalf("connection = %+v, want backend %s at %s", conn, tc.backend, tc.srv.URL)
|
||||
}
|
||||
if conn.process != nil {
|
||||
t.Fatalf("an operator endpoint owns a process: %+v", conn.process)
|
||||
}
|
||||
// startServe sets both process and done; neither may be set on the
|
||||
// explicit path, so no local serve was ever spawned.
|
||||
if conn.done != nil {
|
||||
t.Fatalf("an operator endpoint owns a process waiter: %+v", conn.done)
|
||||
}
|
||||
conn.Close() // must be a no-op
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenEndpointValidationFailuresAreClearAndNeverFallBack pins that
|
||||
// unreachable hosts, a reachable non-OpenCode service, a health-ok endpoint
|
||||
// without SSE and an auth mismatch each fail naming the endpoint and do not
|
||||
// silently return a usable connection.
|
||||
func TestOpenEndpointValidationFailuresAreClearAndNeverFallBack(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
nonOpenCode := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = w.Write([]byte("<html>not opencode</html>"))
|
||||
}))
|
||||
t.Cleanup(nonOpenCode.Close)
|
||||
|
||||
noSSE := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/info" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"version":"2.0.20"}`))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"ok":true}`))
|
||||
}))
|
||||
t.Cleanup(noSSE.Close)
|
||||
|
||||
authMismatch := v2Endpoint(t, "someone-else")
|
||||
|
||||
// A port that is closed: two backends fail fast (bounded by the probe context).
|
||||
unreachable := "http://127.0.0.1:1"
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
url string
|
||||
want string
|
||||
}{
|
||||
{"non-opencode", nonOpenCode.URL, nonOpenCode.URL},
|
||||
{"no sse", noSSE.URL, noSSE.URL},
|
||||
{"auth mismatch", authMismatch.URL, authMismatch.URL},
|
||||
{"unreachable", unreachable, unreachable},
|
||||
{"malformed", "ftp://host", "ftp://host"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
conn, err := OpenEndpoint(ctx, tc.url, "")
|
||||
if err == nil {
|
||||
t.Fatalf("OpenEndpoint(%q) succeeded: %+v", tc.url, conn)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("error %v does not name the endpoint %q", err, tc.want)
|
||||
}
|
||||
if conn != nil {
|
||||
t.Fatalf("a failed endpoint returned a connection: %+v", conn)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenEndpointUsernameOverride pins that PIPELINES_OPENCODE_ENDPOINT_USERNAME
|
||||
// overrides the detected default user on an operator endpoint.
|
||||
func TestOpenEndpointUsernameOverride(t *testing.T) {
|
||||
t.Setenv(EndpointUsernameEnvKey, "custom-user")
|
||||
srv := v2Endpoint(t, "custom-user")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
conn, err := OpenEndpoint(ctx, srv.URL, "s3cret")
|
||||
if err != nil {
|
||||
t.Fatalf("OpenEndpoint with username override: %v", err)
|
||||
}
|
||||
if conn.serverUser() != "custom-user" {
|
||||
t.Fatalf("serverUser = %q, want custom-user", conn.serverUser())
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatSessionReadsEndpointRecord pins that Chat.Session reuses the existing
|
||||
// session list/decode: it returns the endpoint's own record for a listed id and
|
||||
// found=false for an id the endpoint does not report, without inventing a
|
||||
// directory.
|
||||
func TestChatSessionReadsEndpointRecord(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/api/session" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":[{"id":"ses_abc","title":"mine","location":{"directory":"/work/mine"}}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
session, found, err := chat.Session(ctx, "ses_abc")
|
||||
if err != nil || !found {
|
||||
t.Fatalf("Session(ses_abc) = %+v,%v,%v want found", session, found, err)
|
||||
}
|
||||
if session.Directory != "/work/mine" || session.Title != "mine" {
|
||||
t.Fatalf("session record = %+v, want the endpoint's own directory/title", session)
|
||||
}
|
||||
if _, found, err := chat.Session(ctx, "ses_missing"); err != nil || found {
|
||||
t.Fatalf("Session(ses_missing) = found %v, err %v; want not found", found, err)
|
||||
}
|
||||
if _, _, err := chat.Session(ctx, "not-a-session"); err == nil {
|
||||
t.Fatal("Session accepted a foreign-shaped id")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReadEndpointCredentialFile pins the file-reference rule: an empty path
|
||||
// yields no password, a 0600 regular file is read, and a broader permission or a
|
||||
// directory is refused.
|
||||
func TestReadEndpointCredentialFile(t *testing.T) {
|
||||
if got, err := ReadEndpointCredentialFile(""); err != nil || got != "" {
|
||||
t.Fatalf("empty path = %q,%v want no password", got, err)
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "endpoint-password")
|
||||
if err := os.WriteFile(path, []byte("secret\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := ReadEndpointCredentialFile(path); err != nil || got != "secret" {
|
||||
t.Fatalf("read = %q,%v want secret", got, err)
|
||||
}
|
||||
if err := os.Chmod(path, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ReadEndpointCredentialFile(path); err == nil {
|
||||
t.Fatal("a world-readable password file was accepted")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user