Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions pkg/auth/auth_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package auth
import (
"errors"
"fmt"
"net"
"net/url"
"reflect"
"strings"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -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
}
Expand All @@ -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 {
Expand All @@ -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
}

Expand All @@ -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:
Expand Down
90 changes: 90 additions & 0 deletions pkg/auth/auth_check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
6 changes: 5 additions & 1 deletion pkg/cmd/agentstudio/agentstudio.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
47 changes: 47 additions & 0 deletions pkg/cmd/agentstudio/routing_integration_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
85 changes: 85 additions & 0 deletions pkg/cmd/factory/agent_studio_route.go
Original file line number Diff line number Diff line change
@@ -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)
Comment thread
leonardocuco marked this conversation as resolved.
Resolved
}

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