Skip to content

Commit f9851ac

Browse files
weltekialexellis
authored andcommitted
Add ServiceAccountTokenSource
Add an implementation of the TokenSource interface to read Kubernetes service account tokens form disk. Signed-off-by: Han Verstraete (OpenFaaS Ltd) <[email protected]>
1 parent 7e08ee3 commit f9851ac

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

auth.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package sdk
22

33
import (
4+
"fmt"
45
"net/http"
6+
"os"
7+
"path"
58
"sync"
69
)
710

@@ -60,3 +63,33 @@ func (a *TokenAuth) Set(req *http.Request) error {
6063
req.Header.Add("Authorization", "Bearer "+a.token.IDToken)
6164
return nil
6265
}
66+
67+
// A TokenSource to get ID token by reading a Kubernetes projected service account token
68+
// from /var/secrets/tokens/openfaas-token or the path set by the token_mount_path environment
69+
// variable.
70+
type ServiceAccountTokenSource struct{}
71+
72+
// Token returns a Kubernetes projected service account token read from
73+
// /var/secrets/tokens/openfaas-token or the path set by the token_mount_path
74+
// environment variable.
75+
func (ts *ServiceAccountTokenSource) Token() (string, error) {
76+
tokenMountPath := getEnv("token_mount_path", "/var/secrets/tokens")
77+
if len(tokenMountPath) == 0 {
78+
return "", fmt.Errorf("invalid token_mount_path specified for reading the service account token")
79+
}
80+
81+
idTokenPath := path.Join(tokenMountPath, "openfaas-token")
82+
idToken, err := os.ReadFile(idTokenPath)
83+
if err != nil {
84+
return "", fmt.Errorf("unable to load service account token: %s", err)
85+
}
86+
87+
return string(idToken), nil
88+
}
89+
90+
func getEnv(key, defaultVal string) string {
91+
if v, ok := os.LookupEnv(key); ok {
92+
return v
93+
}
94+
return defaultVal
95+
}

0 commit comments

Comments
 (0)