forked from openfaas/go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiam_auth.go
83 lines (69 loc) · 2.2 KB
/
iam_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
package sdk
import (
"fmt"
"net/http"
"os"
"path"
"sync"
)
// A TokenSource is anything that can return an OIDC ID token that can be exchanged for
// an OpenFaaS token.
type TokenSource interface {
// Token returns a token or an error.
Token() (string, error)
}
// TokenAuth bearer token authentication for OpenFaaS deployments with OpenFaaS IAM
// enabled.
type TokenAuth struct {
// TokenURL represents the OpenFaaS gateways token endpoint URL.
TokenURL string
// TokenSource used to get an ID token that can be exchanged for an OpenFaaS ID token.
TokenSource TokenSource
lock sync.Mutex // guards token
token *Token
}
// Set Authorization Bearer header on request.
// Set validates the token expiry on each call. If it's expired it will exchange
// an ID token from the TokenSource for a new OpenFaaS token.
func (a *TokenAuth) Set(req *http.Request) error {
a.lock.Lock()
defer a.lock.Unlock()
if a.token == nil || a.token.Expired() {
idToken, err := a.TokenSource.Token()
if err != nil {
return err
}
token, err := ExchangeIDToken(a.TokenURL, idToken)
if err != nil {
return err
}
a.token = token
}
req.Header.Add("Authorization", "Bearer "+a.token.IDToken)
return nil
}
// A TokenSource to get ID token by reading a Kubernetes projected service account token
// from /var/secrets/tokens/openfaas-token or the path set by the token_mount_path environment
// variable.
type ServiceAccountTokenSource struct{}
// Token returns a Kubernetes projected service account token read from
// /var/secrets/tokens/openfaas-token or the path set by the token_mount_path
// environment variable.
func (ts *ServiceAccountTokenSource) Token() (string, error) {
tokenMountPath := getEnv("token_mount_path", "/var/secrets/tokens")
if len(tokenMountPath) == 0 {
return "", fmt.Errorf("invalid token_mount_path specified for reading the service account token")
}
idTokenPath := path.Join(tokenMountPath, "openfaas-token")
idToken, err := os.ReadFile(idTokenPath)
if err != nil {
return "", fmt.Errorf("unable to load service account token: %s", err)
}
return string(idToken), nil
}
func getEnv(key, defaultVal string) string {
if v, ok := os.LookupEnv(key); ok {
return v
}
return defaultVal
}