-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathworkload_identity_flow.go
More file actions
231 lines (196 loc) · 7.11 KB
/
workload_identity_flow.go
File metadata and controls
231 lines (196 loc) · 7.11 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package clients
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/stackitcloud/stackit-sdk-go/core/oidcadapters"
"github.com/stackitcloud/stackit-sdk-go/core/utils"
)
const (
clientIDEnv = "STACKIT_SERVICE_ACCOUNT_EMAIL"
FederatedTokenEnv = "STACKIT_FEDERATED_TOKEN" //nolint:gosec // This is not a secret, just the env variable name
FederatedTokenFileEnv = "STACKIT_FEDERATED_TOKEN_FILE" //nolint:gosec // This is not a secret, just the env variable name
wifTokenEndpointEnv = "STACKIT_IDP_TOKEN_ENDPOINT" //nolint:gosec // This is not a secret, just the env variable name
wifTokenExpirationEnv = "STACKIT_IDP_TOKEN_EXPIRATION_SECONDS" //nolint:gosec // This is not a secret, just the env variable name
wifClientAssertionType = "urn:schwarz:params:oauth:client-assertion-type:workload-jwt"
wifGrantType = "client_credentials"
defaultWifTokenEndpoint = "https://accounts.stackit.cloud/oauth/v2/token" //nolint:gosec // This is not a secret, just the public endpoint for default value
defaultFederatedTokenPath = "/var/run/secrets/stackit.cloud/serviceaccount/token" //nolint:gosec // This is not a secret, just the default path for workload identity token
defaultWifExpirationToken = "1h"
)
var (
_ = utils.GetEnvOrDefault(wifTokenExpirationEnv, defaultWifExpirationToken) // Not used yet
)
var _ AuthFlow = &WorkloadIdentityFederationFlow{}
// WorkloadIdentityFlow handles auth with Workload Identity Federation
type WorkloadIdentityFederationFlow struct {
rt http.RoundTripper
authClient *http.Client
config *WorkloadIdentityFederationFlowConfig
tokenMutex sync.RWMutex
token *TokenResponseBody
// If the current access token would expire in less than TokenExpirationLeeway,
// the client will refresh it early to prevent clock skew or other timing issues.
tokenExpirationLeeway time.Duration
}
// KeyFlowConfig is the flow config
type WorkloadIdentityFederationFlowConfig struct {
TokenUrl string
ClientID string
TokenExpiration string // Not supported yet
BackgroundTokenRefreshContext context.Context // Functionality is enabled if this isn't nil
HTTPTransport http.RoundTripper
AuthHTTPClient *http.Client
FederatedTokenFunction oidcadapters.OIDCTokenFunc // Function to get the federated token
}
// GetConfig returns the flow configuration
func (c *WorkloadIdentityFederationFlow) GetConfig() WorkloadIdentityFederationFlowConfig {
if c.config == nil {
return WorkloadIdentityFederationFlowConfig{}
}
return *c.config
}
// GetAccessToken implements AuthFlow.
func (c *WorkloadIdentityFederationFlow) GetAccessToken() (string, error) {
if c.rt == nil {
return "", fmt.Errorf("nil http round tripper, please run Init()")
}
var accessToken string
c.tokenMutex.RLock()
if c.token != nil {
accessToken = c.token.AccessToken
}
c.tokenMutex.RUnlock()
accessTokenExpired, err := tokenExpired(accessToken, c.tokenExpirationLeeway)
if err != nil {
return "", fmt.Errorf("check access token is expired: %w", err)
}
if !accessTokenExpired {
return accessToken, nil
}
if err = c.createAccessToken(); err != nil {
return "", fmt.Errorf("get new access token: %w", err)
}
c.tokenMutex.RLock()
accessToken = c.token.AccessToken
c.tokenMutex.RUnlock()
return accessToken, nil
}
func (c *WorkloadIdentityFederationFlow) refreshAccessToken() error {
return c.createAccessToken()
}
// RoundTrip implements the http.RoundTripper interface.
// It gets a token, adds it to the request's authorization header, and performs the request.
func (c *WorkloadIdentityFederationFlow) RoundTrip(req *http.Request) (*http.Response, error) {
if c.rt == nil {
return nil, fmt.Errorf("please run Init()")
}
accessToken, err := c.GetAccessToken()
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
return c.rt.RoundTrip(req)
}
// getBackgroundTokenRefreshContext implements AuthFlow.
func (c *WorkloadIdentityFederationFlow) getBackgroundTokenRefreshContext() context.Context {
return c.config.BackgroundTokenRefreshContext
}
func (c *WorkloadIdentityFederationFlow) Init(cfg *WorkloadIdentityFederationFlowConfig) error {
// No concurrency at this point, so no mutex check needed
c.token = &TokenResponseBody{}
c.config = cfg
if c.config.TokenUrl == "" {
c.config.TokenUrl = utils.GetEnvOrDefault(wifTokenEndpointEnv, defaultWifTokenEndpoint)
}
if c.config.ClientID == "" {
c.config.ClientID = utils.GetEnvOrDefault(clientIDEnv, "")
}
if c.config.FederatedTokenFunction == nil {
if token, ok := os.LookupEnv(FederatedTokenEnv); ok {
c.config.FederatedTokenFunction = func(_ context.Context) (string, error) {
return token, nil
}
} else {
c.config.FederatedTokenFunction = oidcadapters.ReadJWTFromFileSystem(utils.GetEnvOrDefault(FederatedTokenFileEnv, defaultFederatedTokenPath))
}
}
c.tokenExpirationLeeway = defaultTokenExpirationLeeway
if c.rt = cfg.HTTPTransport; c.rt == nil {
c.rt = http.DefaultTransport
}
if c.authClient = cfg.AuthHTTPClient; cfg.AuthHTTPClient == nil {
c.authClient = &http.Client{
Transport: c.rt,
Timeout: DefaultClientTimeout,
}
}
err := c.validate()
if err != nil {
return err
}
if c.config.BackgroundTokenRefreshContext != nil {
go continuousRefreshToken(c)
}
return nil
}
// validate the client is configured well
func (c *WorkloadIdentityFederationFlow) validate() error {
if c.config.ClientID == "" {
return fmt.Errorf("client ID cannot be empty")
}
if c.config.TokenUrl == "" {
return fmt.Errorf("token URL cannot be empty")
}
if _, err := c.config.FederatedTokenFunction(context.Background()); err != nil {
return fmt.Errorf("error reading federated token file - %w", err)
}
if c.tokenExpirationLeeway < 0 {
return fmt.Errorf("token expiration leeway cannot be negative")
}
return nil
}
// createAccessToken creates an access token using self signed JWT
func (c *WorkloadIdentityFederationFlow) createAccessToken() error {
clientAssertion, err := c.config.FederatedTokenFunction(context.Background())
if err != nil {
return err
}
res, err := c.requestToken(c.config.ClientID, clientAssertion)
if err != nil {
return err
}
defer func() {
tempErr := res.Body.Close()
if tempErr != nil && err == nil {
err = fmt.Errorf("close request access token response: %w", tempErr)
}
}()
token, err := parseTokenResponse(res)
if err != nil {
return err
}
c.tokenMutex.Lock()
c.token = token
c.tokenMutex.Unlock()
return nil
}
func (c *WorkloadIdentityFederationFlow) requestToken(clientID, assertion string) (*http.Response, error) {
body := url.Values{}
body.Set("grant_type", wifGrantType)
body.Set("client_assertion_type", wifClientAssertionType)
body.Set("client_assertion", assertion)
body.Set("client_id", clientID)
payload := strings.NewReader(body.Encode())
req, err := http.NewRequest(http.MethodPost, c.config.TokenUrl, payload)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
return c.authClient.Do(req)
}