diff --git a/helm/kagent-tools/values.yaml b/helm/kagent-tools/values.yaml index 45755f3..c815e08 100644 --- a/helm/kagent-tools/values.yaml +++ b/helm/kagent-tools/values.yaml @@ -55,8 +55,11 @@ tools: cpu: 1000m memory: 512Mi k8s: - # When true: a Bearer token in the Authorization header on each request is passed to kubectl; fails if missing - # When false: kubectl uses in-cluster ServiceAccount. + # When true: the Bearer token in the Authorization header of each request authenticates every CLI that + # reaches the cluster (kubectl, helm, istioctl, cilium, kubectl argo rollouts), through a per-call kubeconfig; + # such calls fail if it is missing. Calls that stay local (helm repo add/update, istioctl manifest/waypoint + # generate, the argo plugin version check) need no token. Kubescape (client-go) is not covered. + # When false: the CLIs use the in-cluster ServiceAccount. tokenPassthrough: false prometheus: url: "prometheus.kagent.svc.cluster.local:9090" diff --git a/internal/commands/commandstest/passthrough.go b/internal/commands/commandstest/passthrough.go new file mode 100644 index 0000000..a538c8b --- /dev/null +++ b/internal/commands/commandstest/passthrough.go @@ -0,0 +1,175 @@ +// Package commandstest provides test helpers for code that runs CLIs through +// commands.CommandBuilder with a passthrough token: they check that the token +// reaches the CLI only through the per-call kubeconfig that Execute writes, +// never on argv. +package commandstest + +import ( + "context" + "net/http" + "os" + "path/filepath" + "sync" + "testing" + + "github.com/kagent-dev/tools/internal/cmd" + sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "k8s.io/client-go/tools/clientcmd" +) + +// BaseKubeconfig is the configured kubeconfig the per-call kubeconfig is +// derived from in these tests. +const BaseKubeconfig = `apiVersion: v1 +kind: Config +clusters: +- name: test-cluster + cluster: + server: https://127.0.0.1:6443 + insecure-skip-tls-verify: true +contexts: +- name: test-context + context: + cluster: test-cluster + user: server-identity +current-context: test-context +users: +- name: server-identity + user: + token: server-identity-token-must-not-be-used +` + +// BaseServer is the cluster server of BaseKubeconfig. +const BaseServer = "https://127.0.0.1:6443" + +// RequestWithBearerToken returns a tool request carrying +// "Authorization: Bearer ", as the HTTP transport delivers it. +func RequestWithBearerToken(token string) *sdkmcp.CallToolRequest { + h := http.Header{} + h.Set("Authorization", "Bearer "+token) + return &sdkmcp.CallToolRequest{Extra: &sdkmcp.RequestExtra{Header: h}} +} + +// Kubeconfig records what the last command saw in its --kubeconfig while it +// ran (the file is removed again before the call returns), and the paths and +// tokens of every command that was given one. +type Kubeconfig struct { + mu sync.Mutex + paths []string + tokens []string + path string + fileMode os.FileMode + dirMode os.FileMode + tokenMode os.FileMode + token string + inline string // a token written into the kubeconfig itself (must stay empty) + server string +} + +// Path returns the --kubeconfig path the last command was given, or "". +func (k *Kubeconfig) Path() string { + k.mu.Lock() + defer k.mu.Unlock() + return k.path +} + +// Tokens returns, for every command given a --kubeconfig, the token its +// kubeconfig's token file held ("" for a kubeconfig without one). +func (k *Kubeconfig) Tokens() []string { + k.mu.Lock() + defer k.mu.Unlock() + return append([]string(nil), k.tokens...) +} + +// kubeconfigCapturingExecutor reads the per-call kubeconfig during Exec, then +// forwards the call to the next executor without the --kubeconfig pair, so a +// mock's expectations are the arguments a caller asked for. +type kubeconfigCapturingExecutor struct { + t *testing.T + next cmd.ShellExecutor + seen *Kubeconfig +} + +func (e *kubeconfigCapturingExecutor) Exec(ctx context.Context, command string, args ...string) ([]byte, error) { + var rest []string + for i := 0; i < len(args); i++ { + if args[i] == "--kubeconfig" && i+1 < len(args) { + e.capture(args[i+1]) + i++ + continue + } + rest = append(rest, args[i]) + } + return e.next.Exec(ctx, command, rest...) +} + +func (e *kubeconfigCapturingExecutor) capture(path string) { + e.seen.mu.Lock() + defer e.seen.mu.Unlock() + seen := e.seen + seen.paths = append(seen.paths, path) + seen.path, seen.token, seen.inline, seen.server = path, "", "", "" + seen.fileMode, seen.dirMode, seen.tokenMode = 0, 0, 0 + defer func() { seen.tokens = append(seen.tokens, seen.token) }() + fi, err := os.Stat(path) + require.NoError(e.t, err, "per-call kubeconfig must exist while the command runs") + e.seen.fileMode = fi.Mode().Perm() + di, err := os.Stat(filepath.Dir(path)) + require.NoError(e.t, err) + e.seen.dirMode = di.Mode().Perm() + + cfg, err := clientcmd.LoadFromFile(path) + require.NoError(e.t, err) + ctx := cfg.Contexts[cfg.CurrentContext] + require.NotNil(e.t, ctx) + e.seen.server = cfg.Clusters[ctx.Cluster].Server + user := cfg.AuthInfos[ctx.AuthInfo] + require.NotNil(e.t, user) + e.seen.inline = user.Token + if user.TokenFile == "" { + // The configured kubeconfig, not a per-call one: nothing more to read. + return + } + ti, err := os.Stat(user.TokenFile) + require.NoError(e.t, err) + e.seen.tokenMode = ti.Mode().Perm() + b, err := os.ReadFile(user.TokenFile) + require.NoError(e.t, err) + e.seen.token = string(b) +} + +// WithPassthroughKubeconfig configures BaseKubeconfig through $KUBECONFIG and +// returns a context whose shell executor records the --kubeconfig a command was +// given before delegating to next (typically a cmd.MockShellExecutor). +func WithPassthroughKubeconfig(t *testing.T, ctx context.Context, next cmd.ShellExecutor) (context.Context, *Kubeconfig) { + t.Helper() + path := filepath.Join(t.TempDir(), "config") + require.NoError(t, os.WriteFile(path, []byte(BaseKubeconfig), 0o600)) + t.Setenv("KUBECONFIG", path) + seen := &Kubeconfig{} + return cmd.WithShellExecutor(ctx, &kubeconfigCapturingExecutor{t: t, next: next, seen: seen}), seen +} + +// AssertTokenOnlyInKubeconfig checks that token reached the command only +// through the per-call kubeconfig, never on argv, and that the files are gone. +func AssertTokenOnlyInKubeconfig(t *testing.T, args []string, seen *Kubeconfig, token string) { + t.Helper() + for _, a := range args { + assert.NotContains(t, a, token, "token must not be on argv") + assert.NotEqual(t, "--token", a) + } + seen.mu.Lock() + defer seen.mu.Unlock() + require.NotEmpty(t, seen.path, "the command must be given a per-call --kubeconfig") + assert.Equal(t, token, seen.token, "token file must hold the caller's token") + assert.Empty(t, seen.inline, "kubeconfig must reference the token, not contain it") + assert.Equal(t, BaseServer, seen.server, "cluster must come from the base kubeconfig") + assert.Equal(t, os.FileMode(0o600), seen.fileMode) + assert.Equal(t, os.FileMode(0o600), seen.tokenMode) + assert.Equal(t, os.FileMode(0o700), seen.dirMode) + for _, path := range seen.paths { + _, err := os.Stat(filepath.Dir(path)) + assert.True(t, os.IsNotExist(err), "per-call kubeconfig directory must be removed after the call") + } +} diff --git a/internal/commands/commandstest/suite.go b/internal/commands/commandstest/suite.go new file mode 100644 index 0000000..2c1f531 --- /dev/null +++ b/internal/commands/commandstest/suite.go @@ -0,0 +1,147 @@ +package commandstest + +import ( + "context" + "strings" + "testing" + + "github.com/kagent-dev/tools/internal/cmd" + mcp "github.com/kagent-dev/tools/internal/mcp" + sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// PassthroughTestToken is the bearer token the passthrough tests send. +const PassthroughTestToken = "test-token" + +// Exec is a command a tool is expected to run, as the caller asked for it +// (without the --kubeconfig pair), and the output the mock returns for it. +type Exec struct { + Command string + Args []string + Output string +} + +// ToolCall invokes one tool handler for the passthrough tests. +type ToolCall struct { + Name string + Execs []Exec + Run func(ctx context.Context, req *sdkmcp.CallToolRequest) (*sdkmcp.CallToolResult, error) +} + +// Call builds a ToolCall for a typed handler with input in that is expected to +// run execs. +func Call[In, Out any](name string, h func(context.Context, *sdkmcp.CallToolRequest, In) (*sdkmcp.CallToolResult, Out, error), in In, execs ...Exec) ToolCall { + return ToolCall{ + Name: name, + Execs: execs, + Run: func(ctx context.Context, req *sdkmcp.CallToolRequest) (*sdkmcp.CallToolResult, error) { + res, _, err := h(ctx, req, in) + return res, err + }, + } +} + +// RunTokenPassthroughTests checks a provider's TOKEN_PASSTHROUGH behaviour: +// +// - cluster calls, passthrough on, bearer token: every command runs with a +// per-call kubeconfig that carries the caller's token, never on argv; +// - cluster calls, passthrough on, no bearer token: an error result, and no +// command runs; +// - local calls (no cluster access), passthrough on, no bearer token: the +// commands run, without a per-call kubeconfig; +// - all calls, passthrough off, bearer token: the token is ignored. +func RunTokenPassthroughTests(t *testing.T, cluster, local []ToolCall) { + t.Helper() + const token = PassthroughTestToken + + run := func(t *testing.T, c ToolCall, passthrough string, req *sdkmcp.CallToolRequest) ([]cmd.MockCall, *Kubeconfig) { + t.Helper() + t.Setenv(mcp.TokenPassthroughEnv, passthrough) + mock := cmd.NewMockShellExecutor() + for _, e := range c.Execs { + mock.AddCommandString(e.Command, e.Args, e.Output, nil) + } + ctx, seen := WithPassthroughKubeconfig(t, context.Background(), mock) + res, err := c.Run(ctx, req) + require.NoError(t, err) + require.NotNil(t, res) + require.False(t, res.IsError, resultText(res)) + callLog := mock.GetCallLog() + require.Len(t, callLog, len(c.Execs)) + for i, e := range c.Execs { + assert.Equal(t, e.Command, callLog[i].Command) + assert.Equal(t, e.Args, callLog[i].Args) + } + return callLog, seen + } + + t.Run("cluster tools authenticate as the caller", func(t *testing.T) { + for _, c := range cluster { + t.Run(c.Name, func(t *testing.T) { + callLog, seen := run(t, c, "true", RequestWithBearerToken(token)) + want := make([]string, len(c.Execs)) + for i := range want { + want[i] = token + } + assert.Equal(t, want, seen.Tokens(), "every command must get a per-call kubeconfig with the caller's token") + for _, call := range callLog { + AssertTokenOnlyInKubeconfig(t, call.Args, seen, token) + } + }) + } + }) + + t.Run("cluster tools refuse to run without a bearer token", func(t *testing.T) { + for _, c := range cluster { + t.Run(c.Name, func(t *testing.T) { + t.Setenv(mcp.TokenPassthroughEnv, "true") + mock := cmd.NewMockShellExecutor() + ctx := cmd.WithShellExecutor(context.Background(), mock) + res, err := c.Run(ctx, &sdkmcp.CallToolRequest{}) + require.NoError(t, err) + require.NotNil(t, res) + assert.True(t, res.IsError, "missing token must be an error result") + assert.Contains(t, resultText(res), mcp.ErrBearerTokenRequired.Error()) + assert.Empty(t, mock.GetCallLog(), "no command may run without the caller's token") + }) + } + }) + + t.Run("local tools need no token", func(t *testing.T) { + for _, c := range local { + t.Run(c.Name, func(t *testing.T) { + _, seen := run(t, c, "true", &sdkmcp.CallToolRequest{}) + assert.Empty(t, seen.Tokens(), "no per-call kubeconfig for a command that does not reach the cluster") + }) + } + }) + + t.Run("passthrough off ignores the request's token", func(t *testing.T) { + for _, c := range append(append([]ToolCall(nil), cluster...), local...) { + t.Run(c.Name, func(t *testing.T) { + callLog, seen := run(t, c, "false", RequestWithBearerToken(token)) + assert.Empty(t, seen.Tokens(), "no per-call kubeconfig with passthrough off") + for _, call := range callLog { + for _, a := range call.Args { + assert.NotContains(t, a, token) + } + } + }) + } + }) +} + +func resultText(res *sdkmcp.CallToolResult) string { + if res == nil { + return "" + } + var b strings.Builder + for _, c := range res.Content { + if tc, ok := c.(*sdkmcp.TextContent); ok { + b.WriteString(tc.Text) + } + } + return b.String() +} diff --git a/internal/mcp/passthrough.go b/internal/mcp/passthrough.go new file mode 100644 index 0000000..bb4d8af --- /dev/null +++ b/internal/mcp/passthrough.go @@ -0,0 +1,59 @@ +package mcp + +import ( + "errors" + "net/http" + "os" + "strings" +) + +// TokenPassthroughEnv names the environment variable that turns on bearer-token +// passthrough. When it is "true", every tool that talks to the cluster through a +// CLI authenticates as the caller, with the bearer token of the MCP request, +// instead of with the server's own kubeconfig. +const TokenPassthroughEnv = "TOKEN_PASSTHROUGH" + +// ErrBearerTokenRequired is returned when passthrough is on and the request +// carries no bearer token. Falling back to the server's identity would let a +// caller act with credentials that are not theirs, so the call is refused. +var ErrBearerTokenRequired = errors.New("Bearer token required when TOKEN_PASSTHROUGH is true") + +// TokenPassthroughEnabled reports whether TOKEN_PASSTHROUGH is "true". +func TokenPassthroughEnabled() bool { + return os.Getenv(TokenPassthroughEnv) == "true" +} + +// PassthroughToken returns the token a cluster-facing CLI call must use, with +// passthrough read from TOKEN_PASSTHROUGH. See ResolvePassthroughToken. +func PassthroughToken(headers http.Header) (string, error) { + return ResolvePassthroughToken(TokenPassthroughEnabled(), headers) +} + +// ResolvePassthroughToken returns the token a cluster-facing CLI call must use: +// +// - passthrough on and an "Authorization: Bearer " header: the token; +// - passthrough on and no usable bearer token: ErrBearerTokenRequired; +// - passthrough off: "" (the configured kubeconfig is used, and any token in +// the request is ignored). +// +// The token is meant for commands.CommandBuilder.WithToken, which hands it to +// the CLI through a per-call kubeconfig, never on argv. +func ResolvePassthroughToken(passthrough bool, headers http.Header) (string, error) { + if !passthrough { + return "", nil + } + token := bearerToken(headers) + if token == "" { + return "", ErrBearerTokenRequired + } + return token, nil +} + +// bearerToken returns the token of an "Authorization: Bearer " header, +// or "" when there is none or the header uses another scheme. +func bearerToken(headers http.Header) string { + if auth := headers.Get("Authorization"); strings.HasPrefix(auth, "Bearer ") { + return strings.TrimPrefix(auth, "Bearer ") + } + return "" +} diff --git a/internal/mcp/passthrough_test.go b/internal/mcp/passthrough_test.go new file mode 100644 index 0000000..d6d2b3c --- /dev/null +++ b/internal/mcp/passthrough_test.go @@ -0,0 +1,110 @@ +package mcp + +import ( + "errors" + "net/http" + "os" + "testing" +) + +func TestResolvePassthroughToken(t *testing.T) { + header := func(kv ...string) http.Header { + h := http.Header{} + for i := 0; i+1 < len(kv); i += 2 { + h.Add(kv[i], kv[i+1]) + } + return h + } + + tests := []struct { + name string + passthrough bool + headers http.Header + wantToken string + wantErr error + }{ + // Passthrough on: the caller's bearer token, or a refusal. + {name: "on/bearer", passthrough: true, headers: header("Authorization", "Bearer test-token"), wantToken: "test-token"}, + {name: "on/nil headers", passthrough: true, headers: nil, wantErr: ErrBearerTokenRequired}, + {name: "on/no authorization header", passthrough: true, headers: header("X-Other", "value"), wantErr: ErrBearerTokenRequired}, + {name: "on/empty authorization header", passthrough: true, headers: header("Authorization", ""), wantErr: ErrBearerTokenRequired}, + {name: "on/bearer without token", passthrough: true, headers: header("Authorization", "Bearer "), wantErr: ErrBearerTokenRequired}, + {name: "on/bearer without separator", passthrough: true, headers: header("Authorization", "Bearer"), wantErr: ErrBearerTokenRequired}, + {name: "on/basic scheme", passthrough: true, headers: header("Authorization", "Basic dGVzdDp0ZXN0"), wantErr: ErrBearerTokenRequired}, + {name: "on/lower-case scheme", passthrough: true, headers: header("Authorization", "bearer test-token"), wantErr: ErrBearerTokenRequired}, + {name: "on/token without scheme", passthrough: true, headers: header("Authorization", "test-token"), wantErr: ErrBearerTokenRequired}, + {name: "on/first of several values", passthrough: true, headers: header("Authorization", "Bearer first-token", "Authorization", "Bearer second-token"), wantToken: "first-token"}, + + // Passthrough off: never a token, whatever the request carries. + {name: "off/bearer", passthrough: false, headers: header("Authorization", "Bearer test-token")}, + {name: "off/nil headers", passthrough: false, headers: nil}, + {name: "off/no authorization header", passthrough: false, headers: header("X-Other", "value")}, + {name: "off/bearer without token", passthrough: false, headers: header("Authorization", "Bearer ")}, + {name: "off/basic scheme", passthrough: false, headers: header("Authorization", "Basic dGVzdDp0ZXN0")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + token, err := ResolvePassthroughToken(tt.passthrough, tt.headers) + if !errors.Is(err, tt.wantErr) || (err == nil) != (tt.wantErr == nil) { + t.Fatalf("err = %v, want %v", err, tt.wantErr) + } + if token != tt.wantToken { + t.Fatalf("token = %q, want %q", token, tt.wantToken) + } + if err != nil && err.Error() != "Bearer token required when TOKEN_PASSTHROUGH is true" { + t.Fatalf("error text = %q, want the message kubectl tools have always returned", err.Error()) + } + }) + } +} + +func TestTokenPassthroughEnabled(t *testing.T) { + for _, tt := range []struct { + value string + set bool + want bool + }{ + {value: "true", set: true, want: true}, + {value: "false", set: true, want: false}, + {value: "TRUE", set: true, want: false}, + {value: "1", set: true, want: false}, + {value: "", set: true, want: false}, + {set: false, want: false}, + } { + name := "unset" + if tt.set { + name = "set to " + tt.value + } + t.Run(name, func(t *testing.T) { + // t.Setenv restores the original value after the test, also + // when the variable is then unset. + t.Setenv(TokenPassthroughEnv, tt.value) + if !tt.set { + if err := os.Unsetenv(TokenPassthroughEnv); err != nil { + t.Fatal(err) + } + } + if got := TokenPassthroughEnabled(); got != tt.want { + t.Fatalf("TokenPassthroughEnabled() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPassthroughTokenReadsEnvironment(t *testing.T) { + headers := http.Header{} + headers.Set("Authorization", "Bearer test-token") + + t.Setenv(TokenPassthroughEnv, "true") + if token, err := PassthroughToken(headers); err != nil || token != "test-token" { + t.Fatalf("passthrough on: got (%q, %v), want (%q, nil)", token, err, "test-token") + } + if _, err := PassthroughToken(nil); !errors.Is(err, ErrBearerTokenRequired) { + t.Fatalf("passthrough on without header: err = %v, want %v", err, ErrBearerTokenRequired) + } + + t.Setenv(TokenPassthroughEnv, "false") + if token, err := PassthroughToken(headers); err != nil || token != "" { + t.Fatalf("passthrough off: got (%q, %v), want (\"\", nil)", token, err) + } +} diff --git a/pkg/argo/argo.go b/pkg/argo/argo.go index 6e19e4f..93b9097 100644 --- a/pkg/argo/argo.go +++ b/pkg/argo/argo.go @@ -35,7 +35,7 @@ func handleVerifyArgoRolloutsControllerInstall(ctx context.Context, request *sdk } cmd := []string{"get", "pods", "-n", ns, "-l", label, "-o", "jsonpath={.items[*].status.phase}"} - output, err := runArgoRolloutCommand(ctx, cmd) + output, err := runArgoRolloutCommand(ctx, mcp.Header(request), cmd) if err != nil { return mcp.TextError("Error: " + err.Error()) } @@ -71,8 +71,10 @@ func handleVerifyArgoRolloutsControllerInstall(ctx context.Context, request *sdk type verifyKubectlPluginInstallInput struct{} func handleVerifyKubectlPluginInstall(ctx context.Context, request *sdkmcp.CallToolRequest, in verifyKubectlPluginInstallInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { + // Only reports the plugin's own version, so the caller's token is neither + // needed nor used. args := []string{"argo", "rollouts", "version"} - output, err := runArgoRolloutCommand(ctx, args) + output, err := runArgoRolloutCommandWithToken(ctx, "", args) if err != nil { return mcp.TextResult("Kubectl Argo Rollouts plugin is not installed: " + err.Error()) } @@ -84,11 +86,26 @@ func handleVerifyKubectlPluginInstall(ctx context.Context, request *sdkmcp.CallT return mcp.TextResult(output) } -func runArgoRolloutCommand(ctx context.Context, args []string) (string, error) { +// runArgoRolloutCommand runs a kubectl (or kubectl argo rollouts) command that +// talks to the cluster. With TOKEN_PASSTHROUGH it authenticates as the caller, +// with the bearer token from headers, and is refused without one. +func runArgoRolloutCommand(ctx context.Context, headers http.Header, args []string) (string, error) { + token, err := mcp.PassthroughToken(headers) + if err != nil { + return "", err + } + return runArgoRolloutCommandWithToken(ctx, token, args) +} + +// runArgoRolloutCommandWithToken runs the command with the configured +// kubeconfig or, when token is set, with a per-call kubeconfig that +// authenticates with token. +func runArgoRolloutCommandWithToken(ctx context.Context, token string, args []string) (string, error) { kubeconfigPath := utils.GetKubeconfig() return commands.NewCommandBuilder("kubectl"). WithArgs(args...). WithKubeconfig(kubeconfigPath). + WithToken(token). Execute(ctx) } @@ -112,7 +129,7 @@ func handlePromoteRollout(ctx context.Context, request *sdkmcp.CallToolRequest, cmd = append(cmd, "--full") } - output, err := runArgoRolloutCommand(ctx, cmd) + output, err := runArgoRolloutCommand(ctx, mcp.Header(request), cmd) if err != nil { return mcp.TextError("Error promoting rollout: " + err.Error()) } @@ -136,7 +153,7 @@ func handlePauseRollout(ctx context.Context, request *sdkmcp.CallToolRequest, in } cmd = append(cmd, in.RolloutName) - output, err := runArgoRolloutCommand(ctx, cmd) + output, err := runArgoRolloutCommand(ctx, mcp.Header(request), cmd) if err != nil { return mcp.TextError("Error pausing rollout: " + err.Error()) } @@ -163,7 +180,7 @@ func handleSetRolloutImage(ctx context.Context, request *sdkmcp.CallToolRequest, cmd = append(cmd, "-n", in.Namespace) } - output, err := runArgoRolloutCommand(ctx, cmd) + output, err := runArgoRolloutCommand(ctx, mcp.Header(request), cmd) if err != nil { return mcp.TextError("Error setting rollout image: " + err.Error()) } @@ -239,7 +256,7 @@ func getLatestVersion(ctx context.Context) string { return "0.5.0" } -func configureGatewayPlugin(ctx context.Context, version, namespace string) GatewayPluginStatus { +func configureGatewayPlugin(ctx context.Context, token, version, namespace string) GatewayPluginStatus { arch, err := getSystemArchitecture() if err != nil { return GatewayPluginStatus{ @@ -283,7 +300,7 @@ data: // Apply the ConfigMap cmdArgs := []string{"apply", "-f", tmpFile.Name()} - output, err := runArgoRolloutCommand(ctx, cmdArgs) + output, err := runArgoRolloutCommandWithToken(ctx, token, cmdArgs) if err != nil { return GatewayPluginStatus{ Installed: false, @@ -315,9 +332,16 @@ func handleVerifyGatewayPlugin(ctx context.Context, request *sdkmcp.CallToolRequ shouldInstall = *in.ShouldInstall } + // Resolved once for both the check and the install, so a missing token is + // reported as such rather than as a ConfigMap that could not be applied. + token, err := mcp.PassthroughToken(mcp.Header(request)) + if err != nil { + return mcp.TextError(err.Error()) + } + // Check if ConfigMap exists and is configured cmd := []string{"get", "configmap", "argo-rollouts-config", "-n", namespace, "-o", "yaml"} - output, err := runArgoRolloutCommand(ctx, cmd) + output, err := runArgoRolloutCommandWithToken(ctx, token, cmd) if err == nil && strings.Contains(output, "argoproj-labs/gatewayAPI") { status := GatewayPluginStatus{ Installed: true, @@ -335,7 +359,7 @@ func handleVerifyGatewayPlugin(ctx context.Context, request *sdkmcp.CallToolRequ } // Configure plugin - status := configureGatewayPlugin(ctx, version, namespace) + status := configureGatewayPlugin(ctx, token, version, namespace) return mcp.TextResult(status.String()) } @@ -355,8 +379,15 @@ func handleCheckPluginLogs(ctx context.Context, request *sdkmcp.CallToolRequest, } _ = in.Timeout + // A missing token is a tool error, not a plugin status: resolve it before + // the command, whose failures are reported in the status. + token, err := mcp.PassthroughToken(mcp.Header(request)) + if err != nil { + return mcp.TextError(err.Error()) + } + cmd := []string{"logs", "-n", namespace, "-l", "app.kubernetes.io/name=argo-rollouts", "--tail", "100"} - output, err := runArgoRolloutCommand(ctx, cmd) + output, err := runArgoRolloutCommandWithToken(ctx, token, cmd) if err != nil { status := GatewayPluginStatus{ Installed: false, @@ -410,7 +441,7 @@ func handleListRollouts(ctx context.Context, request *sdkmcp.CallToolRequest, in cmd = append(cmd, "-n", ns) } - output, err := runArgoRolloutCommand(ctx, cmd) + output, err := runArgoRolloutCommand(ctx, mcp.Header(request), cmd) if err != nil { return mcp.TextError("Error listing rollouts: " + err.Error()) } diff --git a/pkg/argo/argo_test.go b/pkg/argo/argo_test.go index 53e5d0b..c5c86e9 100644 --- a/pkg/argo/argo_test.go +++ b/pkg/argo/argo_test.go @@ -97,7 +97,7 @@ func TestConfigureGatewayPlugin(t *testing.T) { mock.AddPartialMatcherString("kubectl", []string{"apply", "-f"}, "configmap/argo-rollouts-config created", nil) ctx := cmd.WithShellExecutor(context.Background(), mock) - status := configureGatewayPlugin(ctx, "0.5.0", "argo-rollouts") + status := configureGatewayPlugin(ctx, "", "0.5.0", "argo-rollouts") assert.True(t, status.Installed) assert.Equal(t, "0.5.0", status.Version) assert.NotEmpty(t, status.Architecture) @@ -108,7 +108,7 @@ func TestConfigureGatewayPlugin(t *testing.T) { mock.AddPartialMatcherString("kubectl", []string{"apply", "-f"}, "", assert.AnError) ctx := cmd.WithShellExecutor(context.Background(), mock) - status := configureGatewayPlugin(ctx, "0.5.0", "argo-rollouts") + status := configureGatewayPlugin(ctx, "", "0.5.0", "argo-rollouts") assert.False(t, status.Installed) assert.Contains(t, status.ErrorMessage, "Error applying Gateway API plugin config") }) diff --git a/pkg/argo/token_passthrough_test.go b/pkg/argo/token_passthrough_test.go new file mode 100644 index 0000000..8c8ddb8 --- /dev/null +++ b/pkg/argo/token_passthrough_test.go @@ -0,0 +1,39 @@ +package argo + +import ( + "testing" + + "github.com/kagent-dev/tools/internal/commands/commandstest" +) + +func kubectlExec(output string, args ...string) commandstest.Exec { + return commandstest.Exec{Command: "kubectl", Args: args, Output: output} +} + +// TestArgoTokenPassthrough covers every argo tool: those that reach the cluster +// authenticate as the caller under TOKEN_PASSTHROUGH; the plugin version check +// only runs the local kubectl plugin and needs no token. +func TestArgoTokenPassthrough(t *testing.T) { + noInstall := false + cluster := []commandstest.ToolCall{ + commandstest.Call("argo_verify_argo_rollouts_controller_install", handleVerifyArgoRolloutsControllerInstall, verifyArgoRolloutsControllerInstallInput{}, + kubectlExec("Running", "get", "pods", "-n", "argo-rollouts", "-l", "app.kubernetes.io/component=rollouts-controller", "-o", "jsonpath={.items[*].status.phase}")), + commandstest.Call("argo_rollouts_list", handleListRollouts, listRolloutsInput{}, + kubectlExec("ok", "argo", "rollouts", "list", "rollouts", "-n", "argo-rollouts")), + commandstest.Call("argo_check_plugin_logs", handleCheckPluginLogs, checkPluginLogsInput{}, + kubectlExec("ok", "logs", "-n", "argo-rollouts", "-l", "app.kubernetes.io/name=argo-rollouts", "--tail", "100")), + commandstest.Call("argo_promote_rollout", handlePromoteRollout, promoteRolloutInput{RolloutName: "app"}, + kubectlExec("ok", "argo", "rollouts", "promote", "app")), + commandstest.Call("argo_pause_rollout", handlePauseRollout, pauseRolloutInput{RolloutName: "app"}, + kubectlExec("ok", "argo", "rollouts", "pause", "app")), + commandstest.Call("argo_set_rollout_image", handleSetRolloutImage, setRolloutImageInput{RolloutName: "app", ContainerImage: "app=nginx:1.27"}, + kubectlExec("ok", "argo", "rollouts", "set", "image", "app", "app=nginx:1.27")), + commandstest.Call("argo_verify_gateway_plugin", handleVerifyGatewayPlugin, verifyGatewayPluginInput{ShouldInstall: &noInstall}, + kubectlExec("trafficRouterPlugins: argoproj-labs/gatewayAPI", "get", "configmap", "argo-rollouts-config", "-n", "argo-rollouts", "-o", "yaml")), + } + local := []commandstest.ToolCall{ + commandstest.Call("argo_verify_kubectl_plugin_install", handleVerifyKubectlPluginInstall, verifyKubectlPluginInstallInput{}, + kubectlExec("kubectl-argo-rollouts: v1.8.0", "argo", "rollouts", "version")), + } + commandstest.RunTokenPassthroughTests(t, cluster, local) +} diff --git a/pkg/cilium/cilium.go b/pkg/cilium/cilium.go index b293e5d..7ab6870 100644 --- a/pkg/cilium/cilium.go +++ b/pkg/cilium/cilium.go @@ -3,6 +3,7 @@ package cilium import ( "context" "fmt" + "net/http" "strings" "github.com/kagent-dev/tools/internal/commands" @@ -212,21 +213,29 @@ type updateServiceInput struct { NodeName string `json:"node_name" jsonschema:"The name of the node to update the service on"` } -func runCiliumCliWithContext(ctx context.Context, args ...string) (string, error) { +// runCiliumCliWithContext runs a cilium CLI command against the cluster. With +// TOKEN_PASSTHROUGH it authenticates as the caller, with the bearer token from +// headers, and is refused without one. +func runCiliumCliWithContext(ctx context.Context, headers http.Header, args ...string) (string, error) { + token, err := mcp.PassthroughToken(headers) + if err != nil { + return "", err + } kubeconfigPath := utils.GetKubeconfig() return commands.NewCommandBuilder("cilium"). WithArgs(args...). WithKubeconfig(kubeconfigPath). + WithToken(token). Execute(ctx) } func handleCiliumStatusAndVersion(ctx context.Context, request *sdkmcp.CallToolRequest, in noInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { - status, err := runCiliumCliWithContext(ctx, "status") + status, err := runCiliumCliWithContext(ctx, mcp.Header(request), "status") if err != nil { return mcp.TextError("Error getting Cilium status: " + err.Error()) } - version, err := runCiliumCliWithContext(ctx, "version") + version, err := runCiliumCliWithContext(ctx, mcp.Header(request), "version") if err != nil { return mcp.TextError("Error getting Cilium version: " + err.Error()) } @@ -247,7 +256,7 @@ func handleUpgradeCilium(ctx context.Context, request *sdkmcp.CallToolRequest, i args = append(args, "--datapath-mode", datapathMode) } - output, err := runCiliumCliWithContext(ctx, args...) + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), args...) if err != nil { return mcp.TextError("Error upgrading Cilium: " + err.Error()) } @@ -271,7 +280,7 @@ func handleInstallCilium(ctx context.Context, request *sdkmcp.CallToolRequest, i args = append(args, "--datapath-mode", datapathMode) } - output, err := runCiliumCliWithContext(ctx, args...) + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), args...) if err != nil { return mcp.TextError("Error installing Cilium: " + err.Error()) } @@ -280,7 +289,7 @@ func handleInstallCilium(ctx context.Context, request *sdkmcp.CallToolRequest, i } func handleUninstallCilium(ctx context.Context, request *sdkmcp.CallToolRequest, in noInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { - output, err := runCiliumCliWithContext(ctx, "uninstall") + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), "uninstall") if err != nil { return mcp.TextError("Error uninstalling Cilium: " + err.Error()) } @@ -301,7 +310,7 @@ func handleConnectToRemoteCluster(ctx context.Context, request *sdkmcp.CallToolR args = append(args, "--destination-context", destContext) } - output, err := runCiliumCliWithContext(ctx, args...) + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), args...) if err != nil { return mcp.TextError("Error connecting to remote cluster: " + err.Error()) } @@ -318,7 +327,7 @@ func handleDisconnectRemoteCluster(ctx context.Context, request *sdkmcp.CallTool args := []string{"clustermesh", "disconnect", "--destination-cluster", clusterName} - output, err := runCiliumCliWithContext(ctx, args...) + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), args...) if err != nil { return mcp.TextError("Error disconnecting from remote cluster: " + err.Error()) } @@ -327,7 +336,7 @@ func handleDisconnectRemoteCluster(ctx context.Context, request *sdkmcp.CallTool } func handleListBGPPeers(ctx context.Context, request *sdkmcp.CallToolRequest, in noInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { - output, err := runCiliumCliWithContext(ctx, "bgp", "peers") + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), "bgp", "peers") if err != nil { return mcp.TextError("Error listing BGP peers: " + err.Error()) } @@ -336,7 +345,7 @@ func handleListBGPPeers(ctx context.Context, request *sdkmcp.CallToolRequest, in } func handleListBGPRoutes(ctx context.Context, request *sdkmcp.CallToolRequest, in noInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { - output, err := runCiliumCliWithContext(ctx, "bgp", "routes") + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), "bgp", "routes") if err != nil { return mcp.TextError("Error listing BGP routes: " + err.Error()) } @@ -345,7 +354,7 @@ func handleListBGPRoutes(ctx context.Context, request *sdkmcp.CallToolRequest, i } func handleShowClusterMeshStatus(ctx context.Context, request *sdkmcp.CallToolRequest, in noInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { - output, err := runCiliumCliWithContext(ctx, "clustermesh", "status") + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), "clustermesh", "status") if err != nil { return mcp.TextError("Error getting cluster mesh status: " + err.Error()) } @@ -354,7 +363,7 @@ func handleShowClusterMeshStatus(ctx context.Context, request *sdkmcp.CallToolRe } func handleShowFeaturesStatus(ctx context.Context, request *sdkmcp.CallToolRequest, in noInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { - output, err := runCiliumCliWithContext(ctx, "features", "status") + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), "features", "status") if err != nil { return mcp.TextError("Error getting features status: " + err.Error()) } @@ -374,7 +383,7 @@ func handleToggleHubble(ctx context.Context, request *sdkmcp.CallToolRequest, in action = "disable" } - output, err := runCiliumCliWithContext(ctx, "hubble", action) + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), "hubble", action) if err != nil { return mcp.TextError("Error toggling Hubble: " + err.Error()) } @@ -394,7 +403,7 @@ func handleToggleClusterMesh(ctx context.Context, request *sdkmcp.CallToolReques action = "disable" } - output, err := runCiliumCliWithContext(ctx, "clustermesh", action) + output, err := runCiliumCliWithContext(ctx, mcp.Header(request), "clustermesh", action) if err != nil { return mcp.TextError("Error toggling cluster mesh: " + err.Error()) } @@ -506,21 +515,30 @@ func RegisterTools(s *sdkmcp.Server, readOnly bool) { // -- Debug Tools -- -func getCiliumPodNameWithContext(ctx context.Context, nodeName string) (string, error) { +func getCiliumPodNameWithContext(ctx context.Context, token, nodeName string) (string, error) { args := []string{"get", "pods", "-n", "kube-system", "--selector=k8s-app=cilium", fmt.Sprintf("--field-selector=spec.nodeName=%s", nodeName), "-o", "jsonpath={.items[0].metadata.name}"} kubeconfigPath := utils.GetKubeconfig() return commands.NewCommandBuilder("kubectl"). WithArgs(args...). WithKubeconfig(kubeconfigPath). + WithToken(token). Execute(ctx) } -func runCiliumDbgCommand(ctx context.Context, command, nodeName string) (string, error) { - return runCiliumDbgCommandWithContext(ctx, command, nodeName) +func runCiliumDbgCommand(ctx context.Context, headers http.Header, command, nodeName string) (string, error) { + return runCiliumDbgCommandWithContext(ctx, headers, command, nodeName) } -func runCiliumDbgCommandWithContext(ctx context.Context, command, nodeName string) (string, error) { - podName, err := getCiliumPodNameWithContext(ctx, nodeName) +// runCiliumDbgCommandWithContext runs cilium-dbg in the node's cilium pod +// through kubectl exec. With TOKEN_PASSTHROUGH both the pod lookup and the exec +// authenticate as the caller, with the bearer token from headers, and neither +// runs without one. +func runCiliumDbgCommandWithContext(ctx context.Context, headers http.Header, command, nodeName string) (string, error) { + token, err := mcp.PassthroughToken(headers) + if err != nil { + return "", err + } + podName, err := getCiliumPodNameWithContext(ctx, token, nodeName) if err != nil { return "", err } @@ -530,6 +548,7 @@ func runCiliumDbgCommandWithContext(ctx context.Context, command, nodeName strin return commands.NewCommandBuilder("kubectl"). WithArgs(args...). WithKubeconfig(kubeconfigPath). + WithToken(token). Execute(ctx) } @@ -551,7 +570,7 @@ func handleGetEndpointDetails(ctx context.Context, request *sdkmcp.CallToolReque return mcp.TextError("either endpoint_id or labels must be provided") } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get endpoint details: %v", err)) } @@ -567,7 +586,7 @@ func handleGetEndpointLogs(ctx context.Context, request *sdkmcp.CallToolRequest, } cmd := fmt.Sprintf("endpoint logs %s", endpointID) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get endpoint logs: %v", err)) } @@ -583,7 +602,7 @@ func handleGetEndpointHealth(ctx context.Context, request *sdkmcp.CallToolReques } cmd := fmt.Sprintf("endpoint health %s", endpointID) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get endpoint health: %v", err)) } @@ -604,7 +623,7 @@ func handleManageEndpointLabels(ctx context.Context, request *sdkmcp.CallToolReq } cmd := fmt.Sprintf("endpoint labels %s --%s %s", endpointID, action, labels) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to manage endpoint labels: %v", err)) } @@ -624,7 +643,7 @@ func handleManageEndpointConfiguration(ctx context.Context, request *sdkmcp.Call } command := fmt.Sprintf("endpoint config %s %s", endpointID, config) - output, err := runCiliumDbgCommand(ctx, command, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), command, nodeName) if err != nil { return mcp.TextError("Error managing endpoint configuration: " + err.Error()) } @@ -641,7 +660,7 @@ func handleDisconnectEndpoint(ctx context.Context, request *sdkmcp.CallToolReque } cmd := fmt.Sprintf("endpoint disconnect %s", endpointID) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to disconnect endpoint: %v", err)) } @@ -651,7 +670,7 @@ func handleDisconnectEndpoint(ctx context.Context, request *sdkmcp.CallToolReque func handleGetEndpointsList(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "endpoint list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "endpoint list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get endpoints list: %v", err)) } @@ -661,7 +680,7 @@ func handleGetEndpointsList(ctx context.Context, request *sdkmcp.CallToolRequest func handleListIdentities(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "identity list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "identity list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list identities: %v", err)) } @@ -677,7 +696,7 @@ func handleGetIdentityDetails(ctx context.Context, request *sdkmcp.CallToolReque } cmd := fmt.Sprintf("identity get %s", identityID) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get identity details: %v", err)) } @@ -701,7 +720,7 @@ func handleShowConfigurationOptions(ctx context.Context, request *sdkmcp.CallToo cmd = "config" } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to show configuration options: %v", err)) } @@ -726,7 +745,7 @@ func handleToggleConfigurationOption(ctx context.Context, request *sdkmcp.CallTo } cmd := fmt.Sprintf("config %s=%s", option, valueStr) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to toggle configuration option: %v", err)) } @@ -736,7 +755,7 @@ func handleToggleConfigurationOption(ctx context.Context, request *sdkmcp.CallTo func handleRequestDebuggingInformation(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "debuginfo", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "debuginfo", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to request debugging information: %v", err)) } @@ -746,7 +765,7 @@ func handleRequestDebuggingInformation(ctx context.Context, request *sdkmcp.Call func handleDisplayEncryptionState(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "encrypt status", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "encrypt status", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to display encryption state: %v", err)) } @@ -756,7 +775,7 @@ func handleDisplayEncryptionState(ctx context.Context, request *sdkmcp.CallToolR func handleFlushIPsecState(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "encrypt flush -f", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "encrypt flush -f", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to flush IPsec state: %v", err)) } @@ -772,7 +791,7 @@ func handleListEnvoyConfig(ctx context.Context, request *sdkmcp.CallToolRequest, } cmd := fmt.Sprintf("envoy admin %s", resourceName) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list Envoy config: %v", err)) } @@ -793,7 +812,7 @@ func handleFQDNCache(ctx context.Context, request *sdkmcp.CallToolRequest, in fq cmd = "fqdn cache list" } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to manage FQDN cache: %v", err)) } @@ -803,7 +822,7 @@ func handleFQDNCache(ctx context.Context, request *sdkmcp.CallToolRequest, in fq func handleShowDNSNames(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "fqdn names", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "fqdn names", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to show DNS names: %v", err)) } @@ -813,7 +832,7 @@ func handleShowDNSNames(ctx context.Context, request *sdkmcp.CallToolRequest, in func handleListIPAddresses(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "ip list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "ip list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list IP addresses: %v", err)) } @@ -834,7 +853,7 @@ func handleShowIPCacheInformation(ctx context.Context, request *sdkmcp.CallToolR return mcp.TextError("either cidr or labels must be provided") } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to show IP cache information: %v", err)) } @@ -850,7 +869,7 @@ func handleDeleteKeyFromKVStore(ctx context.Context, request *sdkmcp.CallToolReq } cmd := fmt.Sprintf("kvstore delete %s", key) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to delete key from kvstore: %v", err)) } @@ -866,7 +885,7 @@ func handleGetKVStoreKey(ctx context.Context, request *sdkmcp.CallToolRequest, i } cmd := fmt.Sprintf("kvstore get %s", key) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get key from kvstore: %v", err)) } @@ -883,7 +902,7 @@ func handleSetKVStoreKey(ctx context.Context, request *sdkmcp.CallToolRequest, i } cmd := fmt.Sprintf("kvstore set %s=%s", key, value) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to set key in kvstore: %v", err)) } @@ -893,7 +912,7 @@ func handleSetKVStoreKey(ctx context.Context, request *sdkmcp.CallToolRequest, i func handleShowLoadInformation(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "loadinfo", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "loadinfo", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to show load information: %v", err)) } @@ -903,7 +922,7 @@ func handleShowLoadInformation(ctx context.Context, request *sdkmcp.CallToolRequ func handleListLocalRedirectPolicies(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "lrp list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "lrp list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list local redirect policies: %v", err)) } @@ -919,7 +938,7 @@ func handleListBPFMapEvents(ctx context.Context, request *sdkmcp.CallToolRequest } cmd := fmt.Sprintf("map events %s", mapName) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list BPF map events: %v", err)) } @@ -935,7 +954,7 @@ func handleGetBPFMap(ctx context.Context, request *sdkmcp.CallToolRequest, in bp } cmd := fmt.Sprintf("map get %s", mapName) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get BPF map: %v", err)) } @@ -945,7 +964,7 @@ func handleGetBPFMap(ctx context.Context, request *sdkmcp.CallToolRequest, in bp func handleListBPFMaps(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "map list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "map list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list BPF maps: %v", err)) } @@ -963,7 +982,7 @@ func handleListMetrics(ctx context.Context, request *sdkmcp.CallToolRequest, in cmd = "metrics list" } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list metrics: %v", err)) } @@ -973,7 +992,7 @@ func handleListMetrics(ctx context.Context, request *sdkmcp.CallToolRequest, in func handleListClusterNodes(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "node list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "node list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list cluster nodes: %v", err)) } @@ -983,7 +1002,7 @@ func handleListClusterNodes(ctx context.Context, request *sdkmcp.CallToolRequest func handleListNodeIds(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "nodeid list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "nodeid list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list node IDs: %v", err)) } @@ -1001,7 +1020,7 @@ func handleDisplayPolicyNodeInformation(ctx context.Context, request *sdkmcp.Cal cmd = "policy get" } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to display policy node information: %v", err)) } @@ -1022,7 +1041,7 @@ func handleDeletePolicyRules(ctx context.Context, request *sdkmcp.CallToolReques return mcp.TextError("either labels or all=true must be provided") } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to delete policy rules: %v", err)) } @@ -1032,7 +1051,7 @@ func handleDeletePolicyRules(ctx context.Context, request *sdkmcp.CallToolReques func handleDisplaySelectors(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "policy selectors", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "policy selectors", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to display selectors: %v", err)) } @@ -1042,7 +1061,7 @@ func handleDisplaySelectors(ctx context.Context, request *sdkmcp.CallToolRequest func handleListXDPCIDRFilters(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "prefilter list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "prefilter list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list XDP CIDR filters: %v", err)) } @@ -1065,7 +1084,7 @@ func handleUpdateXDPCIDRFilters(ctx context.Context, request *sdkmcp.CallToolReq cmd = fmt.Sprintf("prefilter update --cidr %s", cidrPrefixes) } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to update XDP CIDR filters: %v", err)) } @@ -1088,7 +1107,7 @@ func handleDeleteXDPCIDRFilters(ctx context.Context, request *sdkmcp.CallToolReq cmd = fmt.Sprintf("prefilter delete --cidr %s", cidrPrefixes) } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to delete XDP CIDR filters: %v", err)) } @@ -1108,7 +1127,7 @@ func handleValidateCiliumNetworkPolicies(ctx context.Context, request *sdkmcp.Ca cmd += " --enable-k8s-api-discovery" } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to validate Cilium network policies: %v", err)) } @@ -1118,7 +1137,7 @@ func handleValidateCiliumNetworkPolicies(ctx context.Context, request *sdkmcp.Ca func handleListPCAPRecorders(ctx context.Context, request *sdkmcp.CallToolRequest, in nodeNameInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { nodeName := in.NodeName - output, err := runCiliumDbgCommand(ctx, "recorder list", nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), "recorder list", nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list PCAP recorders: %v", err)) } @@ -1134,7 +1153,7 @@ func handleGetPCAPRecorder(ctx context.Context, request *sdkmcp.CallToolRequest, } cmd := fmt.Sprintf("recorder get %s", recorderID) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get PCAP recorder: %v", err)) } @@ -1150,7 +1169,7 @@ func handleDeletePCAPRecorder(ctx context.Context, request *sdkmcp.CallToolReque } cmd := fmt.Sprintf("recorder delete %s", recorderID) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to delete PCAP recorder: %v", err)) } @@ -1175,7 +1194,7 @@ func handleUpdatePCAPRecorder(ctx context.Context, request *sdkmcp.CallToolReque } cmd := fmt.Sprintf("recorder update %s --filters %s --caplen %s --id %s", recorderID, filters, caplen, id) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to update PCAP recorder: %v", err)) } @@ -1193,7 +1212,7 @@ func handleListServices(ctx context.Context, request *sdkmcp.CallToolRequest, in cmd = "service list" } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to list services: %v", err)) } @@ -1209,7 +1228,7 @@ func handleGetServiceInformation(ctx context.Context, request *sdkmcp.CallToolRe } cmd := fmt.Sprintf("service get %s", serviceID) - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get service information: %v", err)) } @@ -1230,7 +1249,7 @@ func handleDeleteService(ctx context.Context, request *sdkmcp.CallToolRequest, i return mcp.TextError("either service_id or all=true must be provided") } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to delete service: %v", err)) } @@ -1301,7 +1320,7 @@ func handleUpdateService(ctx context.Context, request *sdkmcp.CallToolRequest, i cmd += " --local-redirect" } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to update service: %v", err)) } @@ -1341,7 +1360,7 @@ func handleGetDaemonStatus(ctx context.Context, request *sdkmcp.CallToolRequest, cmd += " --brief" } - output, err := runCiliumDbgCommand(ctx, cmd, nodeName) + output, err := runCiliumDbgCommand(ctx, mcp.Header(request), cmd, nodeName) if err != nil { return mcp.TextError(fmt.Sprintf("Failed to get daemon status: %v", err)) } diff --git a/pkg/cilium/cilium_test.go b/pkg/cilium/cilium_test.go index 40a81fa..b4b5966 100644 --- a/pkg/cilium/cilium_test.go +++ b/pkg/cilium/cilium_test.go @@ -196,7 +196,7 @@ func TestRunCiliumCliWithContext(t *testing.T) { mock := cmd.NewMockShellExecutor() mock.AddCommandString("cilium", []string{"test"}, "success", nil) ctx = cmd.WithShellExecutor(ctx, mock) - result, err := runCiliumCliWithContext(ctx, "test") + result, err := runCiliumCliWithContext(ctx, nil, "test") require.NoError(t, err) assert.Equal(t, "success", result) }) @@ -204,7 +204,7 @@ func TestRunCiliumCliWithContext(t *testing.T) { mock := cmd.NewMockShellExecutor() mock.AddCommandString("cilium", []string{"test"}, "", fmt.Errorf("test error")) ctx = cmd.WithShellExecutor(ctx, mock) - _, err := runCiliumCliWithContext(ctx, "test") + _, err := runCiliumCliWithContext(ctx, nil, "test") require.Error(t, err) assert.Contains(t, err.Error(), "test error") }) diff --git a/pkg/cilium/token_passthrough_test.go b/pkg/cilium/token_passthrough_test.go new file mode 100644 index 0000000..4843be8 --- /dev/null +++ b/pkg/cilium/token_passthrough_test.go @@ -0,0 +1,48 @@ +package cilium + +import ( + "testing" + + "github.com/kagent-dev/tools/internal/commands/commandstest" +) + +func ciliumExec(args ...string) commandstest.Exec { + return commandstest.Exec{Command: "cilium", Args: args, Output: "ok"} +} + +// ciliumDbgExecs are the two kubectl calls behind a cilium-dbg tool: the +// node's cilium pod lookup and the exec into it. Both must authenticate as the +// caller. +func ciliumDbgExecs(nodeName string, dbgArgs ...string) []commandstest.Exec { + const pod = "cilium-test" + return []commandstest.Exec{ + { + Command: "kubectl", + Args: []string{"get", "pods", "-n", "kube-system", "--selector=k8s-app=cilium", "--field-selector=spec.nodeName=" + nodeName, "-o", "jsonpath={.items[0].metadata.name}"}, + Output: pod, + }, + { + Command: "kubectl", + Args: append([]string{"exec", "-n", "kube-system", pod, "--", "cilium-dbg"}, dbgArgs...), + Output: "ok", + }, + } +} + +// TestCiliumTokenPassthrough covers both ways cilium tools reach the cluster, +// the cilium CLI and cilium-dbg through kubectl exec, for read and write +// tools. Every cilium tool talks to the cluster, so none runs without a token +// under TOKEN_PASSTHROUGH. +func TestCiliumTokenPassthrough(t *testing.T) { + enable := true + cluster := []commandstest.ToolCall{ + commandstest.Call("cilium_status_and_version", handleCiliumStatusAndVersion, noInput{}, ciliumExec("status"), ciliumExec("version")), + commandstest.Call("cilium_list_bgp_peers", handleListBGPPeers, noInput{}, ciliumExec("bgp", "peers")), + commandstest.Call("cilium_install_cilium", handleInstallCilium, installCiliumInput{ClusterName: "test"}, ciliumExec("install", "--set", "cluster.name=test")), + commandstest.Call("cilium_uninstall_cilium", handleUninstallCilium, noInput{}, ciliumExec("uninstall")), + commandstest.Call("cilium_toggle_hubble", handleToggleHubble, enableToggleInput{Enable: &enable}, ciliumExec("hubble", "enable")), + commandstest.Call("cilium_get_endpoints_list", handleGetEndpointsList, nodeNameInput{NodeName: "node-1"}, ciliumDbgExecs("node-1", "endpoint", "list")...), + commandstest.Call("cilium_delete_service", handleDeleteService, deleteServiceInput{All: true, NodeName: "node-1"}, ciliumDbgExecs("node-1", "service", "delete", "--all")...), + } + commandstest.RunTokenPassthroughTests(t, cluster, nil) +} diff --git a/pkg/helm/helm.go b/pkg/helm/helm.go index ff31dc1..c4ffae3 100644 --- a/pkg/helm/helm.go +++ b/pkg/helm/helm.go @@ -3,6 +3,7 @@ package helm import ( "context" "fmt" + "net/http" "strings" "time" @@ -76,7 +77,7 @@ func handleHelmListReleases(ctx context.Context, request *sdkmcp.CallToolRequest args = append(args, "-o", in.Output) } - result, err := runHelmCommand(ctx, args) + result, err := runHelmCommand(ctx, mcp.Header(request), args) if err != nil { // Check if it's a structured error if toolErr, ok := err.(*errors.ToolError); ok { @@ -93,13 +94,34 @@ func handleHelmListReleases(ctx context.Context, request *sdkmcp.CallToolRequest return mcp.TextResult(result) } -func runHelmCommand(ctx context.Context, args []string) (string, error) { +// runHelmCommand runs a helm command that talks to the cluster. With +// TOKEN_PASSTHROUGH it authenticates as the caller, with the bearer token from +// headers, and is refused without one. +func runHelmCommand(ctx context.Context, headers http.Header, args []string) (string, error) { + token, err := mcp.PassthroughToken(headers) + if err != nil { + return "", err + } + return runHelmWithToken(ctx, token, args) +} + +// runHelmLocalCommand runs a helm command that only touches the local helm +// configuration (repo add, repo update), so it neither needs nor uses the +// caller's token. +func runHelmLocalCommand(ctx context.Context, args []string) (string, error) { + return runHelmWithToken(ctx, "", args) +} + +// runHelmWithToken runs the command with the configured kubeconfig or, when token is +// set, with a per-call kubeconfig that authenticates with token. +func runHelmWithToken(ctx context.Context, token string, args []string) (string, error) { kubeconfigPath := utils.GetKubeconfig() // Add timeout for helm upgrade commands cmdBuilder := commands.NewCommandBuilder("helm"). WithArgs(args...). - WithKubeconfig(kubeconfigPath) + WithKubeconfig(kubeconfigPath). + WithToken(token) // Only add timeout for upgrade commands if len(args) > 0 && args[0] == "upgrade" { @@ -144,7 +166,7 @@ func handleHelmGetRelease(ctx context.Context, request *sdkmcp.CallToolRequest, args := []string{"get", in.Resource, in.Name, "-n", in.Namespace} - result, err := runHelmCommand(ctx, args) + result, err := runHelmCommand(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("Helm get command failed: %v", err)) } @@ -223,7 +245,7 @@ func handleHelmUpgradeRelease(ctx context.Context, request *sdkmcp.CallToolReque args = append(args, "--wait") } - result, err := runHelmCommand(ctx, args) + result, err := runHelmCommand(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("Helm upgrade command failed: %v", err)) } @@ -254,7 +276,7 @@ func handleHelmUninstall(ctx context.Context, request *sdkmcp.CallToolRequest, i args = append(args, "--wait") } - result, err := runHelmCommand(ctx, args) + result, err := runHelmCommand(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("Helm uninstall command failed: %v", err)) } @@ -285,7 +307,7 @@ func handleHelmRepoAdd(ctx context.Context, request *sdkmcp.CallToolRequest, in args := []string{"repo", "add", in.Name, in.URL} - result, err := runHelmCommand(ctx, args) + result, err := runHelmLocalCommand(ctx, args) if err != nil { return mcp.TextError(fmt.Sprintf("Helm repo add command failed: %v", err)) } @@ -299,7 +321,7 @@ type helmRepoUpdateInput struct{} func handleHelmRepoUpdate(ctx context.Context, request *sdkmcp.CallToolRequest, in helmRepoUpdateInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { args := []string{"repo", "update"} - result, err := runHelmCommand(ctx, args) + result, err := runHelmLocalCommand(ctx, args) if err != nil { return mcp.TextError(fmt.Sprintf("Helm repo update command failed: %v", err)) } diff --git a/pkg/helm/token_passthrough_test.go b/pkg/helm/token_passthrough_test.go new file mode 100644 index 0000000..b338e69 --- /dev/null +++ b/pkg/helm/token_passthrough_test.go @@ -0,0 +1,28 @@ +package helm + +import ( + "testing" + + "github.com/kagent-dev/tools/internal/commands/commandstest" +) + +func helmExec(args ...string) commandstest.Exec { + return commandstest.Exec{Command: "helm", Args: args, Output: "ok"} +} + +// TestHelmTokenPassthrough covers every helm tool: those that reach the cluster +// authenticate as the caller under TOKEN_PASSTHROUGH; repo add and repo update +// only touch the local helm configuration and need no token. +func TestHelmTokenPassthrough(t *testing.T) { + cluster := []commandstest.ToolCall{ + commandstest.Call("helm_list_releases", handleHelmListReleases, helmListReleasesInput{AllNamespaces: true}, helmExec("list", "-A")), + commandstest.Call("helm_get_release", handleHelmGetRelease, helmGetReleaseInput{Name: "app", Namespace: "default"}, helmExec("get", "all", "app", "-n", "default")), + commandstest.Call("helm_upgrade", handleHelmUpgradeRelease, helmUpgradeReleaseInput{Name: "app", Chart: "repo/chart", Namespace: "default"}, helmExec("upgrade", "app", "repo/chart", "-n", "default", "--timeout", "30s")), + commandstest.Call("helm_uninstall", handleHelmUninstall, helmUninstallInput{Name: "app", Namespace: "default"}, helmExec("uninstall", "app", "-n", "default")), + } + local := []commandstest.ToolCall{ + commandstest.Call("helm_repo_add", handleHelmRepoAdd, helmRepoAddInput{Name: "example", URL: "https://charts.example.com"}, helmExec("repo", "add", "example", "https://charts.example.com")), + commandstest.Call("helm_repo_update", handleHelmRepoUpdate, helmRepoUpdateInput{}, helmExec("repo", "update")), + } + commandstest.RunTokenPassthroughTests(t, cluster, local) +} diff --git a/pkg/istio/istio.go b/pkg/istio/istio.go index ef3731b..0828344 100644 --- a/pkg/istio/istio.go +++ b/pkg/istio/istio.go @@ -3,6 +3,7 @@ package istio import ( "context" "fmt" + "net/http" "strings" "github.com/kagent-dev/tools/internal/commands" @@ -28,7 +29,7 @@ func handleIstioProxyStatus(ctx context.Context, request *sdkmcp.CallToolRequest args = append(args, in.PodName) } - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl proxy-status failed: %v", err)) } @@ -36,11 +37,31 @@ func handleIstioProxyStatus(ctx context.Context, request *sdkmcp.CallToolRequest return mcp.TextResult(result) } -func runIstioCtl(ctx context.Context, args []string) (string, error) { +// runIstioCtl runs an istioctl command that talks to the cluster. With +// TOKEN_PASSTHROUGH it authenticates as the caller, with the bearer token from +// headers, and is refused without one. +func runIstioCtl(ctx context.Context, headers http.Header, args []string) (string, error) { + token, err := mcp.PassthroughToken(headers) + if err != nil { + return "", err + } + return runIstioCtlWithToken(ctx, token, args) +} + +// runIstioCtlLocal runs an istioctl command that only renders YAML (manifest +// generate, waypoint generate), so it neither needs nor uses the caller's token. +func runIstioCtlLocal(ctx context.Context, args []string) (string, error) { + return runIstioCtlWithToken(ctx, "", args) +} + +// runIstioCtlWithToken runs the command with the configured kubeconfig or, when token is +// set, with a per-call kubeconfig that authenticates with token. +func runIstioCtlWithToken(ctx context.Context, token string, args []string) (string, error) { kubeconfigPath := utils.GetKubeconfig() return commands.NewCommandBuilder("istioctl"). WithArgs(args...). WithKubeconfig(kubeconfigPath). + WithToken(token). Execute(ctx) } @@ -68,7 +89,7 @@ func handleIstioProxyConfig(ctx context.Context, request *sdkmcp.CallToolRequest args = append(args, in.PodName) } - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl proxy-config failed: %v", err)) } @@ -88,7 +109,7 @@ func handleIstioInstall(ctx context.Context, request *sdkmcp.CallToolRequest, in args := []string{"install", "--set", fmt.Sprintf("profile=%s", in.Profile), "-y"} - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl install failed: %v", err)) } @@ -108,7 +129,7 @@ func handleIstioGenerateManifest(ctx context.Context, request *sdkmcp.CallToolRe args := []string{"manifest", "generate", "--set", fmt.Sprintf("profile=%s", in.Profile)} - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtlLocal(ctx, args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl manifest generate failed: %v", err)) } @@ -131,7 +152,7 @@ func handleIstioAnalyzeClusterConfiguration(ctx context.Context, request *sdkmcp args = append(args, "-n", in.Namespace) } - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl analyze failed: %v", err)) } @@ -151,7 +172,7 @@ func handleIstioVersion(ctx context.Context, request *sdkmcp.CallToolRequest, in args = append(args, "--short") } - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl version failed: %v", err)) } @@ -165,7 +186,7 @@ type istioRemoteClustersInput struct{} func handleIstioRemoteClusters(ctx context.Context, request *sdkmcp.CallToolRequest, in istioRemoteClustersInput) (*sdkmcp.CallToolResult, mcp.TextOutput, error) { args := []string{"remote-clusters"} - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl remote-clusters failed: %v", err)) } @@ -188,7 +209,7 @@ func handleWaypointList(ctx context.Context, request *sdkmcp.CallToolRequest, in args = append(args, "-n", in.Namespace) } - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl waypoint list failed: %v", err)) } @@ -227,7 +248,7 @@ func handleWaypointGenerate(ctx context.Context, request *sdkmcp.CallToolRequest args = append(args, "--for", in.TrafficType) } - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtlLocal(ctx, args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl waypoint generate failed: %v", err)) } @@ -252,7 +273,7 @@ func handleWaypointApply(ctx context.Context, request *sdkmcp.CallToolRequest, i args = append(args, "--enroll-namespace") } - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl waypoint apply failed: %v", err)) } @@ -285,7 +306,7 @@ func handleWaypointDelete(ctx context.Context, request *sdkmcp.CallToolRequest, args = append(args, "-n", in.Namespace) - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl waypoint delete failed: %v", err)) } @@ -312,7 +333,7 @@ func handleWaypointStatus(ctx context.Context, request *sdkmcp.CallToolRequest, args = append(args, "-n", in.Namespace) - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl waypoint status failed: %v", err)) } @@ -337,7 +358,7 @@ func handleZtunnelConfig(ctx context.Context, request *sdkmcp.CallToolRequest, i args = append(args, "-n", in.Namespace) } - result, err := runIstioCtl(ctx, args) + result, err := runIstioCtl(ctx, mcp.Header(request), args) if err != nil { return mcp.TextError(fmt.Sprintf("istioctl ztunnel config failed: %v", err)) } diff --git a/pkg/istio/istio_test.go b/pkg/istio/istio_test.go index 944aa22..3e6af15 100644 --- a/pkg/istio/istio_test.go +++ b/pkg/istio/istio_test.go @@ -298,7 +298,7 @@ func TestRunIstioCtl(t *testing.T) { mock.AddCommandString("istioctl", []string{"version"}, "1.18.0", nil) ctx := cmd.WithShellExecutor(context.Background(), mock) - result, err := runIstioCtl(ctx, []string{"version"}) + result, err := runIstioCtl(ctx, nil, []string{"version"}) require.NoError(t, err) assert.Equal(t, "1.18.0", result) diff --git a/pkg/istio/token_passthrough_test.go b/pkg/istio/token_passthrough_test.go new file mode 100644 index 0000000..2f31eb1 --- /dev/null +++ b/pkg/istio/token_passthrough_test.go @@ -0,0 +1,35 @@ +package istio + +import ( + "testing" + + "github.com/kagent-dev/tools/internal/commands/commandstest" +) + +func istioctlExec(args ...string) commandstest.Exec { + return commandstest.Exec{Command: "istioctl", Args: args, Output: "ok"} +} + +// TestIstioTokenPassthrough covers every istio tool: those that reach the +// cluster authenticate as the caller under TOKEN_PASSTHROUGH; manifest +// generate and waypoint generate only render YAML and need no token. +func TestIstioTokenPassthrough(t *testing.T) { + cluster := []commandstest.ToolCall{ + commandstest.Call("istio_proxy_status", handleIstioProxyStatus, istioProxyStatusInput{}, istioctlExec("proxy-status")), + commandstest.Call("istio_proxy_config", handleIstioProxyConfig, istioProxyConfigInput{PodName: "pod", Namespace: "default"}, istioctlExec("proxy-config", "all", "pod.default")), + commandstest.Call("istio_analyze_cluster_configuration", handleIstioAnalyzeClusterConfiguration, istioAnalyzeClusterConfigurationInput{}, istioctlExec("analyze")), + commandstest.Call("istio_version", handleIstioVersion, istioVersionInput{}, istioctlExec("version")), + commandstest.Call("istio_remote_clusters", handleIstioRemoteClusters, istioRemoteClustersInput{}, istioctlExec("remote-clusters")), + commandstest.Call("istio_list_waypoints", handleWaypointList, waypointListInput{}, istioctlExec("waypoint", "list")), + commandstest.Call("istio_waypoint_status", handleWaypointStatus, waypointStatusInput{Namespace: "default"}, istioctlExec("waypoint", "status", "-n", "default")), + commandstest.Call("istio_ztunnel_config", handleZtunnelConfig, ztunnelConfigInput{}, istioctlExec("ztunnel", "config", "all")), + commandstest.Call("istio_install_istio", handleIstioInstall, istioInstallInput{}, istioctlExec("install", "--set", "profile=default", "-y")), + commandstest.Call("istio_apply_waypoint", handleWaypointApply, waypointApplyInput{Namespace: "default"}, istioctlExec("waypoint", "apply", "-n", "default")), + commandstest.Call("istio_delete_waypoint", handleWaypointDelete, waypointDeleteInput{Namespace: "default", All: true}, istioctlExec("waypoint", "delete", "--all", "-n", "default")), + } + local := []commandstest.ToolCall{ + commandstest.Call("istio_generate_manifest", handleIstioGenerateManifest, istioGenerateManifestInput{}, istioctlExec("manifest", "generate", "--set", "profile=default")), + commandstest.Call("istio_generate_waypoint", handleWaypointGenerate, waypointGenerateInput{Namespace: "default"}, istioctlExec("waypoint", "generate", "waypoint", "-n", "default", "--for", "all")), + } + commandstest.RunTokenPassthroughTests(t, cluster, local) +} diff --git a/pkg/k8s/k8s.go b/pkg/k8s/k8s.go index 5ca121d..53fe883 100644 --- a/pkg/k8s/k8s.go +++ b/pkg/k8s/k8s.go @@ -30,11 +30,11 @@ type K8sTool struct { } func NewK8sTool(llmModel llms.Model) *K8sTool { - return &K8sTool{llmModel: llmModel, tokenPassthrough: os.Getenv("TOKEN_PASSTHROUGH") == "true"} + return &K8sTool{llmModel: llmModel, tokenPassthrough: mcp.TokenPassthroughEnabled()} } func NewK8sToolWithConfig(kubeconfig string, llmModel llms.Model) *K8sTool { - return &K8sTool{kubeconfig: kubeconfig, llmModel: llmModel, tokenPassthrough: os.Getenv("TOKEN_PASSTHROUGH") == "true"} + return &K8sTool{kubeconfig: kubeconfig, llmModel: llmModel, tokenPassthrough: mcp.TokenPassthroughEnabled()} } // runKubectlCommandWithCacheInvalidation runs a kubectl command and invalidates cache if it's a modification operation @@ -807,26 +807,9 @@ func (k *K8sTool) handleGenerateResource(ctx context.Context, request *sdkmcp.Ca return mcp.TextResult(responseText) } -// extractBearerToken extracts the Bearer token from the Authorization header -func extractBearerToken(headers http.Header) string { - if auth := headers.Get("Authorization"); auth != "" { - if strings.HasPrefix(auth, "Bearer ") { - return strings.TrimPrefix(auth, "Bearer ") - } - } - return "" -} - // tokenForKubectl returns the token to pass to kubectl and an error if passthrough is true but token is missing. func (k *K8sTool) tokenForKubectl(headers http.Header) (string, error) { - token := extractBearerToken(headers) - if k.tokenPassthrough && token == "" { - return "", fmt.Errorf("Bearer token required when TOKEN_PASSTHROUGH is true") - } - if k.tokenPassthrough { - return token, nil - } - return "", nil // do not use token when passthrough is false + return mcp.ResolvePassthroughToken(k.tokenPassthrough, headers) } // runKubectlCommand is a helper function to execute kubectl commands diff --git a/pkg/k8s/k8s_test.go b/pkg/k8s/k8s_test.go index 6d6eab6..a8a14b5 100644 --- a/pkg/k8s/k8s_test.go +++ b/pkg/k8s/k8s_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/kagent-dev/tools/internal/cmd" + "github.com/kagent-dev/tools/internal/commands/commandstest" sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -1138,7 +1139,7 @@ func TestBearerTokenPassthrough(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `NAME READY STATUS RESTARTS AGE` mock.AddCommandString("kubectl", []string{"get", "pods", "-o", "wide"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("test-token-123") @@ -1151,14 +1152,14 @@ func TestBearerTokenPassthrough(t *testing.T) { callLog := mock.GetCallLog() require.Len(t, callLog, 1) assert.Equal(t, "kubectl", callLog[0].Command) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "test-token-123") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "test-token-123") }) t.Run("scale deployment with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/test-deployment scaled` mock.AddCommandString("kubectl", []string{"scale", "deployment", "test-deployment", "--replicas", "5", "-n", "default"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("my-auth-token") @@ -1170,7 +1171,7 @@ func TestBearerTokenPassthrough(t *testing.T) { // The token reaches kubectl only through the per-call kubeconfig callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "my-auth-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "my-auth-token") }) t.Run("get pod logs with bearer token", func(t *testing.T) { @@ -1178,7 +1179,7 @@ func TestBearerTokenPassthrough(t *testing.T) { expectedOutput := `log line 1 log line 2` mock.AddCommandString("kubectl", []string{"logs", "test-pod", "-n", "default", "--tail", "50"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("logs-token") @@ -1189,14 +1190,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "logs-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "logs-token") }) t.Run("delete resource with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/test-deployment deleted` mock.AddCommandString("kubectl", []string{"delete", "deployment", "test-deployment", "-n", "default"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("delete-token") @@ -1207,14 +1208,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "delete-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "delete-token") }) t.Run("patch resource with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/test-deployment patched` mock.AddCommandString("kubectl", []string{"patch", "deployment", "test-deployment", "--type=strategic", "-p", `{"spec":{"replicas":5}}`, "-n", "default"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("patch-token") @@ -1225,14 +1226,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "patch-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "patch-token") }) t.Run("describe resource with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `Name: test-deployment` mock.AddCommandString("kubectl", []string{"describe", "deployment", "test-deployment", "-n", "default"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("describe-token") @@ -1243,14 +1244,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "describe-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "describe-token") }) t.Run("rollout with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/myapp restarted` mock.AddCommandString("kubectl", []string{"rollout", "restart", "deployment/myapp", "-n", "default"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("rollout-token") @@ -1261,14 +1262,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "rollout-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "rollout-token") }) t.Run("get events with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `{"items": []}` mock.AddCommandString("kubectl", []string{"get", "events", "-o", "json", "--all-namespaces"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("events-token") @@ -1279,14 +1280,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "events-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "events-token") }) t.Run("exec command with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `total 8` mock.AddCommandString("kubectl", []string{"exec", "mypod", "-n", "default", "--", "ls -la"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("exec-token") @@ -1297,14 +1298,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "exec-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "exec-token") }) t.Run("annotate resource with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/test-deployment annotated` mock.AddCommandString("kubectl", []string{"annotate", "deployment", "test-deployment", "key1=value1"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("annotate-token") @@ -1315,14 +1316,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "annotate-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "annotate-token") }) t.Run("label resource with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/test-deployment labeled` mock.AddCommandString("kubectl", []string{"label", "deployment", "test-deployment", "env=prod"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("label-token") @@ -1333,14 +1334,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "label-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "label-token") }) t.Run("api resources with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `NAME SHORTNAMES APIVERSION NAMESPACED KIND` mock.AddCommandString("kubectl", []string{"api-resources"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("api-token") @@ -1351,14 +1352,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "api-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "api-token") }) t.Run("cluster configuration with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `{"current-context": "default"}` mock.AddCommandString("kubectl", []string{"config", "view", "-o", "json"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("config-token") @@ -1369,14 +1370,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "config-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "config-token") }) t.Run("remove annotation with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/test-deployment annotated` mock.AddCommandString("kubectl", []string{"annotate", "deployment", "test-deployment", "key1-"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("remove-anno-token") @@ -1387,14 +1388,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "remove-anno-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "remove-anno-token") }) t.Run("remove label with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/test-deployment labeled` mock.AddCommandString("kubectl", []string{"label", "deployment", "test-deployment", "env-"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("remove-label-token") @@ -1405,14 +1406,14 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "remove-label-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "remove-label-token") }) t.Run("create resource from URL with bearer token", func(t *testing.T) { mock := cmd.NewMockShellExecutor() expectedOutput := `deployment.apps/test-deployment created` mock.AddCommandString("kubectl", []string{"create", "-f", "https://example.com/manifest.yaml", "-n", "default"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("url-token") @@ -1423,7 +1424,7 @@ log line 2` callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "url-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "url-token") }) t.Run("apply manifest with bearer token", func(t *testing.T) { @@ -1435,7 +1436,7 @@ metadata: expectedOutput := `pod/test-pod created` // Use partial matcher since temp file name is dynamic mock.AddPartialMatcherString("kubectl", []string{"apply", "-f"}, expectedOutput, nil) - ctx, seen := withPassthroughKubeconfig(t, ctx, mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, ctx, mock) k8sTool := newTestK8sToolWithPassthrough(true) req := requestWithBearerToken("apply-token") @@ -1446,7 +1447,7 @@ metadata: callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "apply-token") + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, "apply-token") }) t.Run("returns error when passthrough true and authorization header missing", func(t *testing.T) { diff --git a/pkg/k8s/token_passthrough_test.go b/pkg/k8s/token_passthrough_test.go index 4db8bfc..3ca38f6 100644 --- a/pkg/k8s/token_passthrough_test.go +++ b/pkg/k8s/token_passthrough_test.go @@ -2,13 +2,11 @@ package k8s import ( "context" - "os" - "path/filepath" "strings" - "sync" "testing" "github.com/kagent-dev/tools/internal/cmd" + "github.com/kagent-dev/tools/internal/commands/commandstest" mcp "github.com/kagent-dev/tools/internal/mcp" sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/stretchr/testify/assert" @@ -16,131 +14,15 @@ import ( "go.opentelemetry.io/otel" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/sdk/trace/tracetest" - "k8s.io/client-go/tools/clientcmd" ) -// baseKubeconfig is the configured kubeconfig the per-call kubeconfig is -// derived from in these tests. -const baseKubeconfig = `apiVersion: v1 -kind: Config -clusters: -- name: test-cluster - cluster: - server: https://127.0.0.1:6443 - insecure-skip-tls-verify: true -contexts: -- name: test-context - context: - cluster: test-cluster - user: server-identity -current-context: test-context -users: -- name: server-identity - user: - token: server-identity-token-must-not-be-used -` - -// passthroughKubeconfig records what a kubectl call saw in its --kubeconfig -// while it ran: the file is removed again before the call returns. -type passthroughKubeconfig struct { - mu sync.Mutex - path string - fileMode os.FileMode - dirMode os.FileMode - tokenMode os.FileMode - token string - inline string // a token written into the kubeconfig itself (must stay empty) - server string -} - -// kubeconfigCapturingExecutor reads the per-call kubeconfig during Exec, then -// forwards the call to the mock without the --kubeconfig pair, so the mock's -// expectations are the arguments a caller asked for. -type kubeconfigCapturingExecutor struct { - t *testing.T - next cmd.ShellExecutor - seen *passthroughKubeconfig -} - -func (e *kubeconfigCapturingExecutor) Exec(ctx context.Context, command string, args ...string) ([]byte, error) { - var rest []string - for i := 0; i < len(args); i++ { - if args[i] == "--kubeconfig" && i+1 < len(args) { - e.capture(args[i+1]) - i++ - continue - } - rest = append(rest, args[i]) - } - return e.next.Exec(ctx, command, rest...) -} - -func (e *kubeconfigCapturingExecutor) capture(path string) { - e.seen.mu.Lock() - defer e.seen.mu.Unlock() - e.seen.path = path - fi, err := os.Stat(path) - require.NoError(e.t, err, "per-call kubeconfig must exist while the command runs") - e.seen.fileMode = fi.Mode().Perm() - di, err := os.Stat(filepath.Dir(path)) - require.NoError(e.t, err) - e.seen.dirMode = di.Mode().Perm() - - cfg, err := clientcmd.LoadFromFile(path) - require.NoError(e.t, err) - ctx := cfg.Contexts[cfg.CurrentContext] - require.NotNil(e.t, ctx) - e.seen.server = cfg.Clusters[ctx.Cluster].Server - user := cfg.AuthInfos[ctx.AuthInfo] - require.NotNil(e.t, user) - e.seen.inline = user.Token - ti, err := os.Stat(user.TokenFile) - require.NoError(e.t, err) - e.seen.tokenMode = ti.Mode().Perm() - b, err := os.ReadFile(user.TokenFile) - require.NoError(e.t, err) - e.seen.token = string(b) -} - -// withPassthroughKubeconfig configures a base kubeconfig and installs an -// executor that records the per-call kubeconfig before delegating to mock. -func withPassthroughKubeconfig(t *testing.T, ctx context.Context, mock cmd.ShellExecutor) (context.Context, *passthroughKubeconfig) { - t.Helper() - path := filepath.Join(t.TempDir(), "config") - require.NoError(t, os.WriteFile(path, []byte(baseKubeconfig), 0o600)) - t.Setenv("KUBECONFIG", path) - seen := &passthroughKubeconfig{} - return cmd.WithShellExecutor(ctx, &kubeconfigCapturingExecutor{t: t, next: mock, seen: seen}), seen -} - -// assertTokenOnlyInKubeconfig checks that token reached kubectl only through -// the per-call kubeconfig, never on argv, and that the files are gone. -func assertTokenOnlyInKubeconfig(t *testing.T, args []string, seen *passthroughKubeconfig, token string) { - t.Helper() - for _, a := range args { - assert.NotContains(t, a, token, "token must not be on argv") - assert.NotEqual(t, "--token", a) - } - seen.mu.Lock() - defer seen.mu.Unlock() - require.NotEmpty(t, seen.path, "kubectl must be given a per-call --kubeconfig") - assert.Equal(t, token, seen.token, "token file must hold the caller's token") - assert.Empty(t, seen.inline, "kubeconfig must reference the token, not contain it") - assert.Equal(t, "https://127.0.0.1:6443", seen.server, "cluster must come from the base kubeconfig") - assert.Equal(t, os.FileMode(0o600), seen.fileMode) - assert.Equal(t, os.FileMode(0o600), seen.tokenMode) - assert.Equal(t, os.FileMode(0o700), seen.dirMode) - _, err := os.Stat(filepath.Dir(seen.path)) - assert.True(t, os.IsNotExist(err), "per-call kubeconfig directory must be removed after the call") -} - // TestBearerTokenNotInFailedResult covers the reported leak: a failing kubectl // call's tool result must not contain the caller's token. func TestBearerTokenNotInFailedResult(t *testing.T) { const token = "eyJhbGciOiJSUzI1NiJ9.leak-check-token.sig" mock := cmd.NewMockShellExecutor() mock.AddPartialMatcherString("kubectl", []string{"get", "secrets"}, `Error from server (Forbidden): secrets is forbidden`, assert.AnError) - ctx, seen := withPassthroughKubeconfig(t, context.Background(), mock) + ctx, seen := commandstest.WithPassthroughKubeconfig(t, context.Background(), mock) exp := tracetest.NewInMemoryExporter() tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp)) @@ -176,7 +58,7 @@ func TestBearerTokenNotInFailedResult(t *testing.T) { } callLog := mock.GetCallLog() require.Len(t, callLog, 1) - assertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, token) + commandstest.AssertTokenOnlyInKubeconfig(t, callLog[0].Args, seen, token) spans := exp.GetSpans() names := map[string]bool{}