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("not opencode")) })) 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") } }