Skip to content

OIDC Authentication Support and Tests #105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
21 changes: 19 additions & 2 deletions pkg/kubernetes/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,26 @@ func (k *Kubernetes) ConfigurationView(minify bool) (string, error) {
Server: k.cfg.Host,
InsecureSkipTLSVerify: k.cfg.Insecure,
}
cfg.AuthInfos["user"] = &clientcmdapi.AuthInfo{
Token: k.cfg.BearerToken,

// Create auth info with appropriate authentication method
authInfo := &clientcmdapi.AuthInfo{}

// If using bearer token
if k.cfg.BearerToken != "" {
authInfo.Token = k.cfg.BearerToken
}

// If using OIDC auth provider
if k.cfg.AuthProvider != nil {
authInfo.AuthProvider = k.cfg.AuthProvider
}

// If using exec provider (for OIDC or other auth methods)
if k.cfg.ExecProvider != nil {
authInfo.Exec = k.cfg.ExecProvider
}

cfg.AuthInfos["user"] = authInfo
cfg.Contexts["context"] = &clientcmdapi.Context{
Cluster: "cluster",
AuthInfo: "user",
Expand Down
161 changes: 160 additions & 1 deletion pkg/kubernetes/configuration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ package kubernetes

import (
"errors"
"k8s.io/client-go/rest"
"os"
"path"
"runtime"
"strings"
"testing"

"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd/api"
v1 "k8s.io/client-go/tools/clientcmd/api/v1"
"sigs.k8s.io/yaml"
)

func TestKubernetes_IsInCluster(t *testing.T) {
Expand Down Expand Up @@ -136,3 +140,158 @@ users:
}
})
}

func TestConfigurationViewWithOIDC(t *testing.T) {
// Save the original InClusterConfig function
originalInClusterConfig := InClusterConfig

// Mock InClusterConfig to return a config with OIDC auth provider
InClusterConfig = func() (*rest.Config, error) {
return &rest.Config{
Host: "https://kubernetes.default.svc",
AuthProvider: &api.AuthProviderConfig{
Name: "oidc",
Config: map[string]string{
"client-id": "test-client",
"client-secret": "test-secret",
"id-token": "test-id-token",
"refresh-token": "test-refresh-token",
"idp-issuer-url": "https://example.org",
},
},
}, nil
}

// Restore the original function when the test completes
defer func() {
InClusterConfig = originalInClusterConfig
}()

// Create a Kubernetes instance with empty kubeconfig to force in-cluster mode
k := &Kubernetes{
Kubeconfig: "",
}

// Initialize cfg directly to prevent nil pointer dereference
k.cfg, _ = InClusterConfig()

// Call ConfigurationView
configYaml, err := k.ConfigurationView(true)
if err != nil {
t.Fatalf("ConfigurationView failed: %v", err)
}

// Parse the YAML
var config v1.Config
if err := yaml.Unmarshal([]byte(configYaml), &config); err != nil {
t.Fatalf("Failed to parse config YAML: %v", err)
}

// Verify the auth provider is included
if len(config.AuthInfos) != 1 {
t.Fatalf("Expected 1 auth info, got %d", len(config.AuthInfos))
}

authInfo := config.AuthInfos[0]
if authInfo.Name != "user" {
t.Errorf("Expected auth info name to be 'user', got '%s'", authInfo.Name)
}

if authInfo.AuthInfo.AuthProvider == nil {
t.Fatalf("Expected auth provider to be present, got nil")
}

if authInfo.AuthInfo.AuthProvider.Name != "oidc" {
t.Errorf("Expected auth provider name to be 'oidc', got '%s'", authInfo.AuthInfo.AuthProvider.Name)
}

// Verify the auth provider config
authProviderConfig := authInfo.AuthInfo.AuthProvider.Config
expectedKeys := []string{"client-id", "client-secret", "id-token", "refresh-token", "idp-issuer-url"}
for _, key := range expectedKeys {
if value, exists := authProviderConfig[key]; !exists {
t.Errorf("Expected auth provider config to have key '%s', but it was missing", key)
} else if key == "client-id" && value != "test-client" {
t.Errorf("Expected auth provider config key '%s' to have value 'test-client', got '%s'", key, value)
}
}
}

func TestConfigurationViewWithExecProvider(t *testing.T) {
// Save the original InClusterConfig function
originalInClusterConfig := InClusterConfig

// Mock InClusterConfig to return a config with ExecProvider
InClusterConfig = func() (*rest.Config, error) {
return &rest.Config{
Host: "https://kubernetes.default.svc",
ExecProvider: &api.ExecConfig{
Command: "aws",
Args: []string{"eks", "get-token", "--cluster-name", "test-cluster"},
Env: []api.ExecEnvVar{
{
Name: "AWS_PROFILE",
Value: "test-profile",
},
},
APIVersion: "client.authentication.k8s.io/v1beta1",
},
}, nil
}

// Restore the original function when the test completes
defer func() {
InClusterConfig = originalInClusterConfig
}()

// Create a Kubernetes instance with empty kubeconfig to force in-cluster mode
k := &Kubernetes{
Kubeconfig: "",
}

// Initialize cfg directly to prevent nil pointer dereference
k.cfg, _ = InClusterConfig()

// Call ConfigurationView
configYaml, err := k.ConfigurationView(true)
if err != nil {
t.Fatalf("ConfigurationView failed: %v", err)
}

// Parse the YAML
var config v1.Config
if err := yaml.Unmarshal([]byte(configYaml), &config); err != nil {
t.Fatalf("Failed to parse config YAML: %v", err)
}

// Verify the exec provider is included
if len(config.AuthInfos) != 1 {
t.Fatalf("Expected 1 auth info, got %d", len(config.AuthInfos))
}

authInfo := config.AuthInfos[0]
if authInfo.Name != "user" {
t.Errorf("Expected auth info name to be 'user', got '%s'", authInfo.Name)
}

if authInfo.AuthInfo.Exec == nil {
t.Fatalf("Expected exec provider to be present, got nil")
}

execConfig := authInfo.AuthInfo.Exec
if execConfig.Command != "aws" {
t.Errorf("Expected exec command to be 'aws', got '%s'", execConfig.Command)
}

if len(execConfig.Args) != 4 || execConfig.Args[0] != "eks" || execConfig.Args[1] != "get-token" {
t.Errorf("Expected exec args to be ['eks', 'get-token', '--cluster-name', 'test-cluster'], got %v", execConfig.Args)
}

if len(execConfig.Env) != 1 || execConfig.Env[0].Name != "AWS_PROFILE" || execConfig.Env[0].Value != "test-profile" {
t.Errorf("Expected exec env to have AWS_PROFILE=test-profile, got %v", execConfig.Env)
}

if execConfig.APIVersion != "client.authentication.k8s.io/v1beta1" {
t.Errorf("Expected exec APIVersion to be 'client.authentication.k8s.io/v1beta1', got '%s'", execConfig.APIVersion)
}
}
23 changes: 16 additions & 7 deletions pkg/kubernetes/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package kubernetes

import (
"context"

"github.com/fsnotify/fsnotify"
"github.com/manusa/kubernetes-mcp-server/pkg/helm"
v1 "k8s.io/api/core/v1"
Expand Down Expand Up @@ -131,13 +132,21 @@ func (k *Kubernetes) Derived(ctx context.Context) *Kubernetes {
}
klog.V(5).Infof("%s header found, using provided bearer token", AuthorizationBearerTokenHeader)
derivedCfg := rest.CopyConfig(k.cfg)
derivedCfg.BearerToken = bearerToken
derivedCfg.BearerTokenFile = ""
derivedCfg.Username = ""
derivedCfg.Password = ""
derivedCfg.AuthProvider = nil
derivedCfg.AuthConfigPersister = nil
derivedCfg.ExecProvider = nil

// If we have a bearer token, use it for authentication
if bearerToken != "" {
derivedCfg.BearerToken = bearerToken
derivedCfg.BearerTokenFile = ""
derivedCfg.Username = ""
derivedCfg.Password = ""

// Only clear auth providers if we're using a bearer token
// This preserves OIDC configuration when no token is provided
derivedCfg.AuthProvider = nil
derivedCfg.AuthConfigPersister = nil
derivedCfg.ExecProvider = nil
}

derivedCfg.Impersonate = rest.ImpersonationConfig{}
clientCmdApiConfig, err := k.clientCmdConfig.RawConfig()
if err != nil {
Expand Down
Loading
Loading