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) } }