-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathkubernetes_auth.go
97 lines (80 loc) · 2.02 KB
/
kubernetes_auth.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
package vault
import (
"os"
"github.com/pkg/errors"
)
const (
//nolint:gosec // this is not a hardcoded credential
defaultServiceAccountTokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
)
func NewKubernetesAuth(c *Client, role string, opts ...KubernetesAuthOpt) (AuthProvider, error) {
k := &kubernetesAuth{
Client: c,
mountPoint: "kubernetes",
role: role,
jwtPath: defaultServiceAccountTokenPath,
}
for _, opt := range opts {
err := opt(k)
if err != nil {
return nil, err
}
}
return k, nil
}
type kubernetesAuth struct {
Client *Client
mountPoint string
role string
jwt string
jwtPath string
}
func loadJwt(path string) (string, error) {
content, err := os.ReadFile(path)
if err != nil {
return "", errors.Wrap(err, "could not load jwt from file")
}
return string(content), nil
}
type AuthResponse struct {
Auth struct {
ClientToken string `json:"client_token"`
Accessor string `json:"accessor"`
Policies []string `json:"policies"`
LeaseDuration int `json:"lease_duration"`
Renewable bool `json:"renewable"`
Metadata struct {
Role string `json:"role"`
ServiceAccountName string `json:"service_account_name"`
ServiceAccountNamespace string `json:"service_account_namespace"`
ServiceAccountSecretName string `json:"service_account_secret_name"`
ServiceAccountUID string `json:"service_account_uid"`
} `json:"metadata"`
} `json:"auth"`
}
type kubernetesAuthConfig struct {
Role string `json:"role"`
JWT string `json:"jwt"`
}
func (k kubernetesAuth) Auth() (*AuthResponse, error) {
var err error
jwt := k.jwt
if jwt == "" {
jwt, err = loadJwt(k.jwtPath)
if err != nil {
return nil, err
}
}
conf := &kubernetesAuthConfig{
Role: k.role,
JWT: jwt,
}
res := &AuthResponse{}
err = k.Client.Write([]string{"v1", "auth", k.mountPoint, "login"}, conf, res, &RequestOptions{
SkipRenewal: true,
})
if err != nil {
return nil, err
}
return res, nil
}