Skip to content

Commit

Permalink
Gaojing/devicelogin exit when interactivemode never (#145)
Browse files Browse the repository at this point in the history
* device login would exit gracefully when interactiveMode: Never, fixed #92 

Co-authored-by: Jing Gao <jing@JingMS>
  • Loading branch information
everjing and Jing Gao authored Nov 11, 2022
1 parent 5e68a02 commit 908abb3
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
35 changes: 35 additions & 0 deletions pkg/token/deviceloginAndNonInteractive_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package token

import (
"os"
"testing"
)

func TestDeviceloginAndNonInteractive(t *testing.T) {
testData := []struct {
name string
execInfoEnvTest string
options Options
expectedError string
}{
{
name: "KUBERNETES_EXEC_INFO.spec.interactive: false and login mode is devicelogin",
execInfoEnvTest: `{"kind":"ExecCredential","apiVersion":"client.authentication.k8s.io/v1beta1","spec":{"interactive":false}}`,
options: Options{
LoginMethod: DeviceCodeLogin,
},
expectedError: "devicelogin is not supported if interactiveMode is 'never'",
},
}

for _, data := range testData {
t.Run(data.name, func(t *testing.T) {
os.Setenv("KUBERNETES_EXEC_INFO", data.execInfoEnvTest)
defer os.Unsetenv("KUBERNETES_EXEC_INFO")
ecp, err := New(&data.options)
if ecp != nil || err == nil || err.Error() != data.expectedError {
t.Fatalf("expected: return defined error, actual: did not return expected error")
}
})
}
}
10 changes: 10 additions & 0 deletions pkg/token/execCredentialPlugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package token
//go:generate sh -c "mockgen -destination mock_$GOPACKAGE/execCredentialPlugin.go github.com/Azure/kubelogin/pkg/token ExecCredentialPlugin"

import (
"encoding/json"
"fmt"
"os"
"time"

"github.com/Azure/go-autorest/autorest/adal"
"k8s.io/client-go/pkg/apis/clientauthentication"
"k8s.io/klog"
)

Expand All @@ -29,6 +31,14 @@ type execCredentialPlugin struct {
}

func New(o *Options) (ExecCredentialPlugin, error) {
env := os.Getenv(execInfoEnv)
var execCredential clientauthentication.ExecCredential
if err := json.Unmarshal([]byte(env), &execCredential); err != nil {
return nil, fmt.Errorf("cannot convert to ExecCredential: %w", err)
}
if !execCredential.Spec.Interactive && o.LoginMethod == DeviceCodeLogin {
return nil, fmt.Errorf("devicelogin is not supported if interactiveMode is 'never'")
}
klog.V(10).Info(o)
provider, err := newTokenProvider(o)
if err != nil {
Expand Down

0 comments on commit 908abb3

Please # to comment.