Files
alan 0ba1204895 chat: attach to the operator's own OpenCode by pairing, fall back honestly
Brokered chat accepted an operator-supplied endpoint (-opencode-endpoint /
PIPELINES_OPENCODE_ENDPOINT) but failed closed against the operator's running
V2 service: that API authenticates every request with HTTP Basic auth (fixed
user "opencode" plus a password), the broker had no credential, so the health
probe answered 401 and startup logged "OpenCode endpoint ... is unreachable or
is not an OpenCode service", disabling chat entirely.

Established from the installed binary (opencode v2.0.20), not from docs:
`opencode --help` advertises `api`, `pair`, `serve`, `service` and `auth`;
`GET /api/info` is unauthenticated-401 with www-authenticate Basic realm
"Secure Area"; Basic auth user `opencode` with the password from
~/.local/state/opencode/service.json answers 200; `POST /api/pair` returns a
code and `GET /auth/connect/{code}` returns a token that is then accepted as
the Basic password.

- internal/opencode/pair.go (new): PairEndpoint does the pair exchange over the
  shared nativeRequest transport (same auth, bounds and JSON checks);
  ReadServiceCredential reads the operator's local service password under the
  private-file rule; OpenEndpointAttached resolves the credential in precedence
  order - explicit password file, a paired token stored by an earlier run, then
  a fresh pairing bootstrapped by the local service credential - stores the
  token owner-only and re-pairs once when a stored token is refused (401).
- internal/opencode/endpoint.go: OpenEndpoint wraps probeEndpoint, which returns
  the connection even on failure; Connection.unauthorized (set on HTTP 401 by
  the request paths, cleared per probe) distinguishes an authentication refusal
  from any other refusal.
- cmd/pipelines-server/main.go: the endpoint attach uses OpenEndpointAttached
  with the paired-credential file beside the pipeline database. An endpoint that
  cannot be attached logs a line naming it and falls back to the server's own
  OpenCode instance instead of leaving chat refused.
- internal/protocol/status.go, internal/server/websocket.go: get_status gains an
  opencode object (health = endpoint | fallback | spawned | unavailable, plus
  the endpoint url), the honest status evidence for the fallback. No credential
  is ever placed there.
- Tests: internal/opencode/pair_test.go, internal/protocol/status_test.go and a
  TestStatusReportsOpenCodeAttachment case in internal/server/status_test.go.

Repository checks: go build ./..., go vet ./... and gofmt -l . clean;
go test ./internal/... ./cmd/... green.

Packaged templates and skill references: the repository has no template tree
that mentions the OpenCode endpoint, and no packaged reference file is added, so
internal/author/install.go's managed inventory is unchanged. The packaged
authoring reference internal/author/skill/references/operations.md (the endpoint
paragraph around line 289, the "clear refusal and no fallback" wording and the
password-file/username-only credential story, and the missing opencode status
field) is now stale; per the maintenance convention the item does not edit the
shared document and instead records the stale points, with the exact wording
they should take, in docs/notes/chat-persistence.md for the docs-fold writer.
2026-10-18 00:55:26 +01:00

257 lines
8.7 KiB
Go

package opencode
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// pairService is a minimal V2 OpenCode service: it accepts the fixed "opencode"
// basic-auth user with either the bootstrap service password or a token it has
// paired, issues single-use pair codes, exchanges them for tokens, and counts
// pair calls so a test can prove a stored token is reused rather than re-paired.
type pairService struct {
mu sync.Mutex
password string
tokens map[string]bool
codes map[string]bool
pairs int
seq int
}
func newPairService(t *testing.T, password string) (*pairService, *httptest.Server) {
t.Helper()
s := &pairService{password: password, tokens: map[string]bool{}, codes: map[string]bool{}}
srv := httptest.NewServer(http.HandlerFunc(s.handle))
t.Cleanup(srv.Close)
return s, srv
}
func (s *pairService) authorized(r *http.Request) bool {
user, pass, ok := r.BasicAuth()
if !ok || user != "opencode" {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
return pass == s.password || s.tokens[pass]
}
func (s *pairService) handle(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/pair" && r.Method == http.MethodPost:
if !s.authorized(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
s.mu.Lock()
s.seq++
code := "code" + string(rune('0'+s.seq))
s.codes[code] = true
s.pairs++
s.mu.Unlock()
writeJSON(w, map[string]any{"code": code, "expires_in": 300})
case strings.HasPrefix(r.URL.Path, "/auth/connect/"):
code := strings.TrimPrefix(r.URL.Path, "/auth/connect/")
s.mu.Lock()
ok := s.codes[code]
delete(s.codes, code)
token := "token" + string(rune('0'+s.seq))
if ok {
s.tokens[token] = true
}
s.mu.Unlock()
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
writeJSON(w, map[string]any{"token": token})
case r.URL.Path == "/api/info":
if !s.authorized(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
writeJSON(w, map[string]any{"version": "2.0.20", "urls": []string{}})
case r.URL.Path == "/api/event":
if !s.authorized(r) {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(http.StatusOK)
default:
w.WriteHeader(http.StatusNotFound)
}
}
func (s *pairService) pairCalls() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.pairs
}
func writeJSON(w http.ResponseWriter, body any) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(body)
}
// TestPairEndpointExchangesCodeForToken pins the pairing contract the installed
// 2.0.20 service exposes: POST /api/pair (authenticated) issues a single-use
// code and GET /auth/connect/{code} returns the token used as the basic
// password.
func TestPairEndpointExchangesCodeForToken(t *testing.T) {
service, srv := newPairService(t, "service-password")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
token, err := PairEndpoint(ctx, srv.URL, "service-password")
if err != nil {
t.Fatalf("PairEndpoint: %v", err)
}
if token == "" {
t.Fatal("PairEndpoint returned an empty token")
}
if service.pairCalls() != 1 {
t.Fatalf("pair calls = %d, want 1", service.pairCalls())
}
if _, err := PairEndpoint(ctx, srv.URL, ""); err == nil {
t.Fatal("PairEndpoint with no bootstrap password succeeded")
}
}
// TestOpenEndpointAttachedPairsStoresAndReuses pins the whole point: with no
// explicit password the broker pairs once, stores the token in an owner-only
// file beside the other configuration, and a later start reuses it instead of
// pairing again.
func TestOpenEndpointAttachedPairsStoresAndReuses(t *testing.T) {
service, srv := newPairService(t, "service-password")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
credentialPath := filepath.Join(t.TempDir(), "opencode-endpoint.json")
first, err := OpenEndpointAttached(ctx, srv.URL, "", "service-password", credentialPath)
if err != nil {
t.Fatalf("first attach: %v", err)
}
if first.Mode != "paired" {
t.Fatalf("first attach mode = %q, want paired", first.Mode)
}
first.Connection.Close()
info, err := os.Stat(credentialPath)
if err != nil {
t.Fatalf("paired credential was not stored: %v", err)
}
if info.Mode().Perm() != 0600 {
t.Fatalf("stored credential mode = %v, want 0600", info.Mode().Perm())
}
if service.pairCalls() != 1 {
t.Fatalf("pair calls after first attach = %d, want 1", service.pairCalls())
}
second, err := OpenEndpointAttached(ctx, srv.URL, "", "service-password", credentialPath)
if err != nil {
t.Fatalf("second attach: %v", err)
}
if second.Mode != "paired-stored" {
t.Fatalf("second attach mode = %q, want paired-stored", second.Mode)
}
second.Connection.Close()
if service.pairCalls() != 1 {
t.Fatalf("a reused token triggered a re-pair: pair calls = %d, want 1", service.pairCalls())
}
}
// TestOpenEndpointAttachedRepairsRefusedStoredCredential pins the recovery: a
// token the service has refused is cleared and replaced by one fresh pairing,
// never left to fail closed.
func TestOpenEndpointAttachedRepairsRefusedStoredCredential(t *testing.T) {
service, srv := newPairService(t, "service-password")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
credentialPath := filepath.Join(t.TempDir(), "opencode-endpoint.json")
if err := WritePairedCredential(credentialPath, srv.URL, "stale-token"); err != nil {
t.Fatalf("seed stale credential: %v", err)
}
attach, err := OpenEndpointAttached(ctx, srv.URL, "", "service-password", credentialPath)
if err != nil {
t.Fatalf("attach after refusal: %v", err)
}
attach.Connection.Close()
if attach.Mode != "paired" {
t.Fatalf("attach mode = %q, want paired after a refused stored token", attach.Mode)
}
if service.pairCalls() != 1 {
t.Fatalf("pair calls = %d, want exactly one re-pair", service.pairCalls())
}
token, found, err := ReadPairedCredential(credentialPath, srv.URL)
if err != nil || !found || token == "stale-token" {
t.Fatalf("stored credential after repair = %q,%v,%v want a fresh token", token, found, err)
}
}
// TestOpenEndpointAttachedExplicitPasswordSkipsPairing pins that an explicit
// password (the operator's password-file reference) is used as given and no
// pairing is attempted.
func TestOpenEndpointAttachedExplicitPasswordSkipsPairing(t *testing.T) {
service, srv := newPairService(t, "service-password")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
attach, err := OpenEndpointAttached(ctx, srv.URL, "service-password", "service-password", filepath.Join(t.TempDir(), "unused.json"))
if err != nil {
t.Fatalf("attach with explicit password: %v", err)
}
attach.Connection.Close()
if attach.Mode != "password-file" {
t.Fatalf("attach mode = %q, want password-file", attach.Mode)
}
if service.pairCalls() != 0 {
t.Fatalf("an explicit password triggered a pairing: pair calls = %d", service.pairCalls())
}
}
// TestReadServiceCredential pins the bootstrap read: the service state file is
// held to the private-file rule and only its password is returned.
func TestReadServiceCredential(t *testing.T) {
path := filepath.Join(t.TempDir(), "service.json")
if err := os.WriteFile(path, []byte(`{"url":"http://0.0.0.0:49374","password":"bootstrap"}`), 0600); err != nil {
t.Fatal(err)
}
if got, err := ReadServiceCredential(path); err != nil || got != "bootstrap" {
t.Fatalf("ReadServiceCredential = %q,%v want bootstrap", got, err)
}
if err := os.Chmod(path, 0644); err != nil {
t.Fatal(err)
}
if _, err := ReadServiceCredential(path); err == nil {
t.Fatal("a world-readable service credential was accepted")
}
if got, err := ReadServiceCredential(""); err != nil || got != "" {
t.Fatalf("empty path = %q,%v want no credential", got, err)
}
}
// TestReadPairedCredentialIsEndpointScoped pins that a token paired for one
// endpoint is never offered to another.
func TestReadPairedCredentialIsEndpointScoped(t *testing.T) {
path := filepath.Join(t.TempDir(), "opencode-endpoint.json")
if err := WritePairedCredential(path, "http://127.0.0.1:1", "token"); err != nil {
t.Fatal(err)
}
if _, found, err := ReadPairedCredential(path, "http://127.0.0.1:2"); err != nil || found {
t.Fatalf("foreign endpoint = found %v, err %v; want not found", found, err)
}
if token, found, err := ReadPairedCredential(path, "http://127.0.0.1:1"); err != nil || !found || token != "token" {
t.Fatalf("matching endpoint = %q,%v,%v want token", token, found, err)
}
if _, found, err := ReadPairedCredential(filepath.Join(t.TempDir(), "absent.json"), "http://127.0.0.1:1"); err != nil || found {
t.Fatalf("absent file = found %v, err %v; want not found", found, err)
}
}