-
Notifications
You must be signed in to change notification settings - Fork 81
/
kubectl.go
116 lines (103 loc) 路 3.25 KB
/
kubectl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package google
import (
"encoding/base64"
"encoding/json"
"fmt"
"net"
"net/http"
"strings"
"github.com/appscode/go/log"
"github.com/appscode/guard/util/kubeconfig"
"github.com/pkg/errors"
"github.com/skratchdot/open-golang/open"
"golang.org/x/net/context"
"golang.org/x/oauth2"
goauth "golang.org/x/oauth2/google"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
var gauthConfig oauth2.Config
func IssueToken() error {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err
}
defer listener.Close()
log.Infoln("Oauth2 callback receiver listening on", listener.Addr())
// https://developers.google.com/identity/protocols/OpenIDConnect#validatinganidtoken
gauthConfig = oauth2.Config{
Endpoint: goauth.Endpoint,
ClientID: GoogleOauth2ClientID,
ClientSecret: GoogleOauth2ClientSecret,
Scopes: []string{"openid", "profile", "email"},
RedirectURL: "http://" + listener.Addr().String(),
}
// PromptSelectAccount allows a user who has multiple accounts at the authorization server
// to select amongst the multiple accounts that they may have current sessions for.
// eg: https://developers.google.com/identity/protocols/OpenIDConnect
promptSelectAccount := oauth2.SetAuthURLParam("prompt", "select_account")
codeURL := gauthConfig.AuthCodeURL("/", promptSelectAccount)
log.Infoln("Auhtorization code URL:", codeURL)
open.Start(codeURL)
http.HandleFunc("/", handleGoogleAuth)
return http.Serve(listener, nil)
}
// https://developers.google.com/identity/protocols/OAuth2InstalledApp
func handleGoogleAuth(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
if code == "" {
return
}
token, err := gauthConfig.Exchange(context.Background(), code)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("x-content-type-options", "nosniff")
w.WriteHeader(http.StatusOK)
err = addAuthInfo(token.Extra("id_token").(string), token.RefreshToken)
if err != nil {
w.Write([]byte(fmt.Sprintf("Error: %v", err)))
return
} else {
w.Write([]byte("Configuration has been written to " + kubeconfig.Path()))
return
}
}
func addAuthInfo(idToken, refreshToken string) error {
authInfo := &clientcmdapi.AuthInfo{
AuthProvider: &clientcmdapi.AuthProviderConfig{
Name: "oidc",
Config: map[string]string{
"client-id": GoogleOauth2ClientID,
"client-secret": GoogleOauth2ClientSecret,
"id-token": idToken,
"idp-issuer-url": "https://accounts.google.com",
"refresh-token": refreshToken,
},
},
}
email, err := getEmailFromIdToken(idToken)
if err != nil {
return errors.Wrap(err, "failed to retrieve email from idToken")
}
return kubeconfig.AddAuthInfo(email, authInfo)
}
func getEmailFromIdToken(idToken string) (string, error) {
parts := strings.Split(idToken, ".")
if len(parts) < 2 {
return "", fmt.Errorf("oidc: malformed jwt, expected 3 parts got %d", len(parts))
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", fmt.Errorf("oidc: malformed jwt payload: %v", err)
}
c := struct {
Email string `json:"email"`
}{}
err = json.Unmarshal(payload, &c)
if err != nil {
return "", err
}
return c.Email, nil
}