diff --git a/pkg/auth/auth_check.go b/pkg/auth/auth_check.go index f7857c67..4b869207 100644 --- a/pkg/auth/auth_check.go +++ b/pkg/auth/auth_check.go @@ -3,6 +3,9 @@ package auth import ( "errors" "fmt" + "net" + "net/url" + "reflect" "strings" "github.com/spf13/cobra" @@ -94,6 +97,13 @@ func WithRemediation(err error) error { // CheckACLs check if the current profile has the right ACLs to execute the command func CheckACLs(cmd *cobra.Command, f *cmdutil.Factory) error { + baseURLFlag := cmd.Flags().Lookup("base-url") + if baseURLFlag == nil { + baseURLFlag = cmd.InheritedFlags().Lookup("base-url") + } + if baseURLFlag != nil && baseURLFlag.Changed && f.AgentStudioBaseURL == "" { + return errors.New("--base-url cannot be empty") + } if cmd.Annotations == nil { return nil } @@ -103,6 +113,24 @@ func CheckACLs(cmd *cobra.Command, f *cmdutil.Factory) error { return nil } neededACLs := strings.Split(aclsAsString, ",") + if f.AgentStudioBaseURL != "" { + if _, err := cmdutil.ParseAgentStudioURL(f.AgentStudioBaseURL); err != nil { + return err + } + flag := cmd.Flags().Lookup("search-hosts") + if flag == nil { + flag = cmd.InheritedFlags().Lookup("search-hosts") + } + hosts := f.Config.Profile().GetSearchHosts() + if flag == nil || !flag.Changed || len(hosts) == 0 || !reflect.DeepEqual(hosts, f.Config.Profile().SearchHosts) { + return errors.New("--base-url requires explicit --search-hosts for the API key ACL preflight (and no conflicting ALGOLIA_SEARCH_HOSTS)") + } + for _, host := range hosts { + if !validAgentStudioPreflightHost(host) { + return errors.New("invalid --search-hosts for Agent Studio ACL preflight; use HTTPS or loopback HTTP hosts without credentials, paths, or queries") + } + } + } client, err := f.SearchClient() if err != nil { @@ -125,6 +153,9 @@ func CheckACLs(cmd *cobra.Command, f *cmdutil.Factory) error { } apiKey, err := client.GetApiKey(client.NewApiGetApiKeyRequest(key)) if err != nil { + if f.AgentStudioBaseURL != "" { + return errors.New(cmdutil.RedactCredential(err.Error(), key)) + } return err } @@ -141,6 +172,22 @@ func CheckACLs(cmd *cobra.Command, f *cmdutil.Factory) error { return nil } +func validAgentStudioPreflightHost(host string) bool { + host = strings.TrimSpace(host) + if !strings.Contains(host, "://") { + host = "https://" + host + } + u, err := url.Parse(host) + if err != nil || u.Host == "" || u.Hostname() == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || (u.Scheme != "https" && u.Scheme != "http") { + return false + } + if u.Scheme == "http" { + ip := net.ParseIP(u.Hostname()) + return u.Hostname() == "localhost" || (ip != nil && ip.IsLoopback()) + } + return true +} + func IsAuthCheckEnabled(cmd *cobra.Command) bool { switch cmd.Name() { case "help", "powershell", cobra.ShellCompRequestCmd, cobra.ShellCompNoDescRequestCmd: diff --git a/pkg/auth/auth_check_test.go b/pkg/auth/auth_check_test.go index fac8075a..e8421e34 100644 --- a/pkg/auth/auth_check_test.go +++ b/pkg/auth/auth_check_test.go @@ -168,3 +168,93 @@ See https://www.algolia.com/doc/guides/security/api-keys/#rights-and-restriction }) } } + +func TestAgentStudioOverrideRequiresExplicitValidSearchHosts(t *testing.T) { + for _, tc := range []struct { + name, flag string + wantErr bool + }{ + {name: "missing", wantErr: true}, + {name: "empty", flag: "", wantErr: true}, + {name: "invalid", flag: "not a host", wantErr: true}, + {name: "credentials", flag: "https://user:secret@example.com", wantErr: true}, + {name: "path", flag: "https://example.com/path", wantErr: true}, + {name: "remote http", flag: "http://remote.example", wantErr: true}, + {name: "explicit https", flag: "https://search.example", wantErr: false}, + {name: "loopback http", flag: "http://127.0.0.1:8080", wantErr: false}, + } { + t.Run(tc.name, func(t *testing.T) { + r := &httpmock.Registry{} + r.Register(httpmock.REST("GET", "1/keys"), httpmock.JSONResponse(search.ListApiKeysResponse{})) + f, _ := test.NewFactory(false, r, nil, "") + f.AgentStudioBaseURL = "http://localhost:8000" + cmd := &cobra.Command{Annotations: map[string]string{"acls": "settings"}} + cmd.Flags().StringSliceVar(&f.Config.Profile().SearchHosts, "search-hosts", nil, "") + if tc.name != "missing" { + require.NoError(t, cmd.Flags().Set("search-hosts", tc.flag)) + } + err := CheckACLs(cmd, f) + if tc.wantErr { + require.Error(t, err) + assert.NotContains(t, err.Error(), "secret") + assert.Empty(t, r.Requests) + } else { + require.NoError(t, err) + r.Verify(t) + } + }) + } +} + +func TestAgentStudioInvalidBaseURLFailsBeforeACLRequest(t *testing.T) { + r := &httpmock.Registry{} + f, _ := test.NewFactory(false, r, nil, "") + f.AgentStudioBaseURL = "https://user:url-secret@example.com" + cmd := &cobra.Command{Annotations: map[string]string{"acls": "settings"}} + cmd.Flags().StringSliceVar(&f.Config.Profile().SearchHosts, "search-hosts", nil, "") + require.NoError(t, cmd.Flags().Set("search-hosts", "https://search.example")) + err := CheckACLs(cmd, f) + require.Error(t, err) + assert.NotContains(t, err.Error(), "url-secret") + assert.Empty(t, r.Requests) +} + +func TestAgentStudioPreflightRedactsAPIKeyFromErrors(t *testing.T) { + r := &httpmock.Registry{} + r.Register(httpmock.REST("GET", "1/keys"), httpmock.ErrorResponse()) + r.Register(httpmock.REST("GET", "1/keys/api-secret"), httpmock.ErrorResponseWithBody(map[string]string{"message": "invalid api-secret"})) + f, _ := test.NewFactory(false, r, nil, "") + f.Config.Profile().APIKey = "api-secret" + f.AgentStudioBaseURL = "http://localhost:8000" + cmd := &cobra.Command{Annotations: map[string]string{"acls": "settings"}} + cmd.Flags().StringSliceVar(&f.Config.Profile().SearchHosts, "search-hosts", nil, "") + require.NoError(t, cmd.Flags().Set("search-hosts", "https://search.example")) + err := CheckACLs(cmd, f) + require.Error(t, err) + assert.NotContains(t, err.Error(), "api-secret") +} + +func TestAgentStudioEmptyBaseURLDoesNotFallBack(t *testing.T) { + r := &httpmock.Registry{} + f, _ := test.NewFactory(false, r, nil, "") + cmd := &cobra.Command{Annotations: map[string]string{"acls": "settings"}} + cmd.Flags().StringVar(&f.AgentStudioBaseURL, "base-url", "", "") + require.NoError(t, cmd.Flags().Set("base-url", "")) + err := CheckACLs(cmd, f) + require.Error(t, err) + assert.Empty(t, r.Requests) +} + +func TestAgentStudioOverrideRejectsConflictingSearchHostsEnvironment(t *testing.T) { + t.Setenv("ALGOLIA_SEARCH_HOSTS", "https://unexpected.example") + r := &httpmock.Registry{} + f, _ := test.NewFactory(false, r, nil, "") + f.AgentStudioBaseURL = "http://localhost:8000" + cmd := &cobra.Command{Annotations: map[string]string{"acls": "settings"}} + cmd.Flags().StringSliceVar(&f.Config.Profile().SearchHosts, "search-hosts", nil, "") + require.NoError(t, cmd.Flags().Set("search-hosts", "https://explicit.example")) + err := CheckACLs(cmd, f) + require.Error(t, err) + assert.Contains(t, err.Error(), "ALGOLIA_SEARCH_HOSTS") + assert.Empty(t, r.Requests) +} diff --git a/pkg/cmd/agentstudio/agentstudio.go b/pkg/cmd/agentstudio/agentstudio.go index 3de920f3..637f4b87 100644 --- a/pkg/cmd/agentstudio/agentstudio.go +++ b/pkg/cmd/agentstudio/agentstudio.go @@ -14,8 +14,12 @@ func NewAgentStudioCmd(f *cmdutil.Factory) *cobra.Command { cmd := &cobra.Command{ Use: "agentstudio", Short: "Manage Algolia Agent Studio", - Long: "Manage Algolia Agent Studio resources.", + Long: "Manage Algolia Agent Studio resources.\n\n" + + "When --base-url is set, specify --search-hosts explicitly for the API key ACL preflight. " + + "Both destinations receive the configured application credentials. " + + "The base URL path replaces the SDK's /agent-studio prefix; use /agent-studio for a proxy that expects it.", } + cmd.PersistentFlags().StringVar(&f.AgentStudioBaseURL, "base-url", "", "Agent Studio API base URL (HTTPS or loopback HTTP), including any proxy path prefix") cmd.AddCommand(agents.NewAgentsCmd(f)) cmd.AddCommand(conversations.NewConversationsCmd(f)) diff --git a/pkg/cmd/agentstudio/routing_integration_test.go b/pkg/cmd/agentstudio/routing_integration_test.go new file mode 100644 index 00000000..09209ca3 --- /dev/null +++ b/pkg/cmd/agentstudio/routing_integration_test.go @@ -0,0 +1,47 @@ +package agentstudio_test + +import ( + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/algolia/cli/pkg/auth" + "github.com/algolia/cli/pkg/cmd/factory" + "github.com/algolia/cli/pkg/cmd/root" + "github.com/algolia/cli/pkg/config" + "github.com/algolia/cli/pkg/iostreams" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCommandRoutesWithExplicitACLPreflight(t *testing.T) { + var searchPaths, agentPaths []string + search := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + searchPaths = append(searchPaths, r.URL.Path) + assert.Equal(t, "test-key", r.Header.Get("X-Algolia-API-Key")) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"keys":[]}`) + })) + defer search.Close() + agent := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + agentPaths = append(agentPaths, r.URL.Path) + assert.Equal(t, "test-key", r.Header.Get("X-Algolia-API-Key")) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"data":[],"pagination":{"page":1,"limit":20,"totalCount":0,"totalPages":0}}`) + })) + defer agent.Close() + cfg := &config.Config{} + cfg.CurrentProfile.ApplicationID = "TESTAPP" + cfg.CurrentProfile.APIKey = "test-key" + f := factory.New("test", cfg) + f.IOStreams, _, _, _ = iostreams.Test() + cmd := root.NewRootCmd(f) + cmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { return auth.CheckACLs(cmd, f) } + cmd.SetArgs([]string{"--application-id", "TESTAPP", "--api-key", "test-key", "agentstudio", "--base-url", agent.URL, "agents", "list", "--search-hosts", search.URL}) + _, err := cmd.ExecuteC() + require.NoError(t, err) + assert.Equal(t, []string{"/1/keys"}, searchPaths) + assert.Equal(t, []string{"/1/agents"}, agentPaths) +} diff --git a/pkg/cmd/factory/agent_studio_route.go b/pkg/cmd/factory/agent_studio_route.go new file mode 100644 index 00000000..292194a5 --- /dev/null +++ b/pkg/cmd/factory/agent_studio_route.go @@ -0,0 +1,85 @@ +package factory + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/algolia/algoliasearch-client-go/v4/algolia/transport" + + "github.com/algolia/cli/pkg/cmdutil" +) + +type agentStudioRequester struct { + target *url.URL + next transport.Requester + apiKey string +} + +type agentStudioHTTPClient struct{ client *http.Client } + +func (r agentStudioHTTPClient) Request(req *http.Request, _, _ time.Duration) (*http.Response, error) { + return r.client.Do(req) +} + +func newAgentStudioRequester(target *url.URL, apiKey string) agentStudioRequester { + client := transport.DefaultHTTPClient(nil) + client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse } + return agentStudioRequester{target: target, next: agentStudioHTTPClient{client: client}, apiKey: apiKey} +} + +func (r agentStudioRequester) Request(req *http.Request, timeout, connectTimeout time.Duration) (*http.Response, error) { + if !strings.HasPrefix(req.URL.Path, "/agent-studio/") { + return nil, fmt.Errorf("unexpected Agent Studio API path") + } + clone := req.Clone(req.Context()) + clone.URL.Scheme = r.target.Scheme + clone.URL.Host = r.target.Host + clone.URL.Path = strings.TrimRight(r.target.Path, "/") + strings.TrimPrefix(req.URL.Path, "/agent-studio") + clone.URL.RawPath = strings.TrimRight(r.target.EscapedPath(), "/") + + strings.TrimPrefix(req.URL.EscapedPath(), "/agent-studio") + clone.Host = r.target.Host + res, err := r.next.Request(clone, timeout, connectTimeout) + if err != nil { + return res, r.redact(err) + } + if res != nil && res.StatusCode >= 300 && res.Body != nil { + body, readErr := io.ReadAll(io.LimitReader(res.Body, maxAgentStudioErrorBody)) + closeErr := res.Body.Close() + if readErr != nil { + return nil, r.redact(readErr) + } + if closeErr != nil { + return nil, r.redact(closeErr) + } + redacted := cmdutil.RedactCredential(string(body), r.apiKey) + res.Body = io.NopCloser(bytes.NewBufferString(redacted)) + res.ContentLength = int64(len(redacted)) + if res.Header != nil { + res.Header.Set("Content-Length", strconv.Itoa(len(redacted))) + } + } + return res, nil +} + +const maxAgentStudioErrorBody = 1 << 20 + +// redactedError hides the API key in the message but keeps the original error +// in the chain, so the SDK's errors.As/errors.Is checks for timeouts and +// cancellation still work. +type redactedError struct { + msg string + err error +} + +func (e redactedError) Error() string { return e.msg } +func (e redactedError) Unwrap() error { return e.err } + +func (r agentStudioRequester) redact(err error) error { + return redactedError{msg: cmdutil.RedactCredential(err.Error(), r.apiKey), err: err} +} diff --git a/pkg/cmd/factory/agent_studio_route_test.go b/pkg/cmd/factory/agent_studio_route_test.go new file mode 100644 index 00000000..bf4d1f96 --- /dev/null +++ b/pkg/cmd/factory/agent_studio_route_test.go @@ -0,0 +1,189 @@ +package factory + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/algolia/cli/pkg/cmdutil" + "github.com/algolia/cli/pkg/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type captureRequester struct{ url string } + +func (c *captureRequester) Request(req *http.Request, _, _ time.Duration) (*http.Response, error) { + c.url = req.URL.String() + return &http.Response{StatusCode: 200, Header: make(http.Header)}, nil +} + +func TestAgentStudioRouting(t *testing.T) { + for _, tc := range []struct{ base, input, want string }{ + {"http://localhost:8000", "https://example.test/agent-studio/1/agents?limit=5", "http://localhost:8000/1/agents?limit=5"}, + {"https://review.example/agent-studio", "https://example.test/agent-studio/1/providers", "https://review.example/agent-studio/1/providers"}, + {"https://review.example/prefix", "https://example.test/agent-studio/1/agents/a/conversations", "https://review.example/prefix/1/agents/a/conversations"}, + } { + t.Run(tc.want, func(t *testing.T) { + target, err := cmdutil.ParseAgentStudioURL(tc.base) + require.NoError(t, err) + capture := &captureRequester{} + requester := agentStudioRequester{target: target, next: capture} + req, err := http.NewRequest(http.MethodGet, tc.input, nil) + require.NoError(t, err) + _, err = requester.Request(req, 0, 0) + require.NoError(t, err) + assert.Equal(t, tc.want, capture.url) + }) + } +} + +func TestAgentStudioRoutingPreservesEncodedPath(t *testing.T) { + target, err := cmdutil.ParseAgentStudioURL("https://review.example/prefix") + require.NoError(t, err) + capture := &captureRequester{} + req, err := http.NewRequest(http.MethodGet, "https://example.test/agent-studio/1/agents/a%2Fb", nil) + require.NoError(t, err) + _, err = agentStudioRequester{target: target, next: capture}.Request(req, 0, 0) + require.NoError(t, err) + assert.Equal(t, "https://review.example/prefix/1/agents/a%2Fb", capture.url) +} + +type failingRequester struct{ err error } + +func (f failingRequester) Request(*http.Request, time.Duration, time.Duration) (*http.Response, error) { + return nil, f.err +} + +func TestAgentStudioRequesterKeepsErrorChainAndRedacts(t *testing.T) { + target, err := cmdutil.ParseAgentStudioURL("https://review.example") + require.NoError(t, err) + req, err := http.NewRequest(http.MethodGet, "https://example.test/agent-studio/1/agents", nil) + require.NoError(t, err) + _, err = agentStudioRequester{target: target, apiKey: "secret-key", next: failingRequester{ + err: fmt.Errorf("dial secret-key: %w", context.DeadlineExceeded), + }}.Request(req, 0, 0) + require.Error(t, err) + assert.ErrorIs(t, err, context.DeadlineExceeded) + assert.NotContains(t, err.Error(), "secret-key") +} + +func TestAgentStudioRoutingRejectsInvalidURL(t *testing.T) { + for _, input := range []string{"not-a-url", "ftp://example.com", "http://example.com?key=secret", "https://user:secret@example.com", "https://example.com/#secret", "http://remote.example"} { + t.Run(input, func(t *testing.T) { + _, err := cmdutil.ParseAgentStudioURL(input) + require.Error(t, err) + assert.NotContains(t, err.Error(), "secret") + }) + } +} + +func TestAgentStudioClientRoutesSDKRequests(t *testing.T) { + paths := []string{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.Path) + assert.Equal(t, "test-key", r.Header.Get("X-Algolia-API-Key")) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{ "data": [], "pagination": {"page": 1, "limit": 20, "totalCount": 0, "totalPages": 0} }`) + })) + defer server.Close() + cfg := &config.Config{} + cfg.CurrentProfile.ApplicationID = "TESTAPP" + cfg.CurrentProfile.APIKey = "test-key" + f := New("test", cfg) + f.AgentStudioBaseURL = server.URL + client, err := f.AgentStudioClient() + require.NoError(t, err) + _, err = client.ListAgents(client.NewApiListAgentsRequest()) + require.NoError(t, err) + _, err = client.ListProviders(client.NewApiListProvidersRequest()) + require.NoError(t, err) + _, err = client.ListAgentConversations(client.NewApiListAgentConversationsRequest("agent-id")) + require.NoError(t, err) + assert.Equal(t, []string{"/1/agents", "/1/providers", "/1/agents/agent-id/conversations"}, paths) +} + +func TestAgentStudioRequesterRejectsRedirects(t *testing.T) { + redirected := false + destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { redirected = true })) + defer destination.Close() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, destination.URL, http.StatusFound) })) + defer server.Close() + target, err := cmdutil.ParseAgentStudioURL(server.URL) + require.NoError(t, err) + req, err := http.NewRequest(http.MethodGet, "https://example.test/agent-studio/1/agents", nil) + require.NoError(t, err) + req.Header.Set("X-Algolia-API-Key", "test-key") + res, err := newAgentStudioRequester(target, "test-key").Request(req, 0, 0) + require.NoError(t, err) + defer res.Body.Close() + assert.Equal(t, http.StatusFound, res.StatusCode) + assert.False(t, redirected) +} + +func TestAgentStudioDefaultRoutingUnchanged(t *testing.T) { + cfg := &config.Config{} + cfg.CurrentProfile.ApplicationID = "TESTAPP" + cfg.CurrentProfile.APIKey = "test-key" + cfg.CurrentProfile.SearchHosts = []string{"https://search-override.example"} + f := New("test", cfg) + client, err := f.AgentStudioClient() + require.NoError(t, err) + assert.Nil(t, client.GetConfiguration().Requester) + assert.Len(t, client.GetConfiguration().Hosts, 5) +} + +func TestAgentStudioURLValidationErrorDoesNotLeakCredentials(t *testing.T) { + cfg := &config.Config{} + cfg.CurrentProfile.ApplicationID = "TESTAPP" + cfg.CurrentProfile.APIKey = "api-secret" + f := New("test", cfg) + f.AgentStudioBaseURL = "https://username:url-secret@example.com" + _, err := f.AgentStudioClient() + require.Error(t, err) + assert.NotContains(t, err.Error(), "url-secret") + assert.NotContains(t, err.Error(), "api-secret") +} + +func TestAgentStudioClientPropagatesDeniedResponseWithoutKey(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + _, _ = io.WriteString(w, `{"message":"missing required ACL"}`) + })) + defer server.Close() + cfg := &config.Config{} + cfg.CurrentProfile.ApplicationID = "TESTAPP" + cfg.CurrentProfile.APIKey = "api-secret" + f := New("test", cfg) + f.AgentStudioBaseURL = server.URL + client, err := f.AgentStudioClient() + require.NoError(t, err) + _, err = client.ListAgents(client.NewApiListAgentsRequest()) + require.Error(t, err) + assert.Contains(t, err.Error(), "missing required ACL") + assert.NotContains(t, err.Error(), "api-secret") +} + +func TestAgentStudioClientRedactsAPIKeyFromErrorResponse(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + _, _ = io.WriteString(w, `{"message":"invalid key api-secret"}`) + })) + defer server.Close() + cfg := &config.Config{} + cfg.CurrentProfile.ApplicationID = "TESTAPP" + cfg.CurrentProfile.APIKey = "api-secret" + f := New("test", cfg) + f.AgentStudioBaseURL = server.URL + client, err := f.AgentStudioClient() + require.NoError(t, err) + _, err = client.ListAgents(client.NewApiListAgentsRequest()) + require.Error(t, err) + assert.NotContains(t, err.Error(), "api-secret") +} diff --git a/pkg/cmd/factory/default.go b/pkg/cmd/factory/default.go index 1c157e90..3976e4f0 100644 --- a/pkg/cmd/factory/default.go +++ b/pkg/cmd/factory/default.go @@ -169,6 +169,14 @@ func agentStudioClient(f *cmdutil.Factory, appVersion string) func() (*agentStud ExposeIntermediateNetworkErrors: true, }, } + if f.AgentStudioBaseURL != "" { + target, err := cmdutil.ParseAgentStudioURL(f.AgentStudioBaseURL) + if err != nil { + return nil, err + } + clientConf.Hosts = []transport.StatefulHost{transport.NewStatefulHost(target.Scheme, target.Host, call.IsReadWrite)} + clientConf.Requester = newAgentStudioRequester(target, apiKey) + } return agentStudio.NewClientWithConfig(clientConf) } diff --git a/pkg/cmdutil/agent_studio_url.go b/pkg/cmdutil/agent_studio_url.go new file mode 100644 index 00000000..c4365346 --- /dev/null +++ b/pkg/cmdutil/agent_studio_url.go @@ -0,0 +1,36 @@ +package cmdutil + +import ( + "encoding/json" + "fmt" + "net" + "net/url" + "strings" +) + +// ParseAgentStudioURL validates a custom Agent Studio endpoint without exposing its contents. +func ParseAgentStudioURL(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil || u.Host == "" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" || (u.Scheme != "http" && u.Scheme != "https") || u.RawPath != "" { + return nil, fmt.Errorf("invalid Agent Studio base URL: use an HTTP(S) URL without credentials, query, or fragment") + } + if u.Scheme == "http" { + ip := net.ParseIP(u.Hostname()) + if u.Hostname() != "localhost" && (ip == nil || !ip.IsLoopback()) { + return nil, fmt.Errorf("agent studio HTTP URLs are limited to localhost") + } + } + return u, nil +} + +// RedactCredential removes raw and common encoded forms of a secret from an error. +func RedactCredential(s, key string) string { + if key == "" { + return s + } + encoded, _ := json.Marshal(key) + for _, secret := range []string{key, url.QueryEscape(key), url.PathEscape(key), string(encoded[1 : len(encoded)-1])} { + s = strings.ReplaceAll(s, secret, "[REDACTED]") + } + return s +} diff --git a/pkg/cmdutil/factory.go b/pkg/cmdutil/factory.go index bdbefc72..de83e3bf 100644 --- a/pkg/cmdutil/factory.go +++ b/pkg/cmdutil/factory.go @@ -16,12 +16,13 @@ import ( ) type Factory struct { - IOStreams *iostreams.IOStreams - Config config.IConfig - SearchClient func() (*search.APIClient, error) - CrawlerClient func() (*crawler.Client, error) - CompositionClient func() (*composition.APIClient, error) - AgentStudioClient func() (*agentStudio.APIClient, error) + IOStreams *iostreams.IOStreams + Config config.IConfig + SearchClient func() (*search.APIClient, error) + CrawlerClient func() (*crawler.Client, error) + CompositionClient func() (*composition.APIClient, error) + AgentStudioClient func() (*agentStudio.APIClient, error) + AgentStudioBaseURL string // Prompter is the interactive input source used by commands that support // an --interactive mode. Defaulted to a real SurveyPrompter in factory.New;