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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions helm/kagent-tools/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
175 changes: 175 additions & 0 deletions internal/commands/commandstest/passthrough.go
Original file line number Diff line number Diff line change
@@ -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 <token>", 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")
}
}
147 changes: 147 additions & 0 deletions internal/commands/commandstest/suite.go
Original file line number Diff line number Diff line change
@@ -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()
}
59 changes: 59 additions & 0 deletions internal/mcp/passthrough.go
Original file line number Diff line number Diff line change
@@ -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 <token>" 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 <token>" 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 ""
}
Loading
Loading