-
Notifications
You must be signed in to change notification settings - Fork 8
/
key_flow.go
414 lines (373 loc) · 10.9 KB
/
key_flow.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
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package clients
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/MicahParks/keyfunc"
"github.com/SchwarzIT/community-stackit-go-client/pkg/env"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"github.com/pkg/errors"
)
const (
// Key Flow optional env variable (1)
ServiceAccountKey = "STACKIT_SERVICE_ACCOUNT_KEY"
PrivateKey = "STACKIT_PRIVATE_KEY"
// Key Flow optional env variable (2) using file paths
ServiceAccountKeyPath = "STACKIT_SERVICE_ACCOUNT_KEY_PATH"
PrivateKeyPath = "STACKIT_PRIVATE_KEY_PATH"
)
var tokenAPI = env.URLs(
"token",
"https://api.stackit.cloud/service-account/token",
"https://api-qa.stackit.cloud/service-account/token",
"https://api-dev.stackit.cloud/service-account/token",
)
var jsksAPI = env.URLs(
"jswks",
"https://api.stackit.cloud/service-account/.well-known/jwks.json",
"https://api-qa.stackit.cloud/service-account/.well-known/jwks.json",
"https://api-dev.stackit.cloud/service-account/.well-known/jwks.json",
)
const (
PrivateKeyBlockType = "PRIVATE KEY"
)
// KeyFlow handles auth with SA key
type KeyFlow struct {
client *http.Client
config *KeyFlowConfig
key *ServiceAccountKeyPrivateResponse
privateKey *rsa.PrivateKey
privateKeyPEM []byte
token *TokenResponseBody
}
// KeyFlowConfig is the flow config
type KeyFlowConfig struct {
ServiceAccountKeyPath string
PrivateKeyPath string
ServiceAccountKey []byte
PrivateKey []byte
Environment env.Environment
ClientRetry *RetryConfig
}
// TokenResponseBody is the API response
// when requesting a new token
type TokenResponseBody struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
TokenType string `json:"token_type"`
}
// ServiceAccountKeyPrivateResponse is the API response
// when creating a new SA key
type ServiceAccountKeyPrivateResponse struct {
Active bool `json:"active"`
CreatedAt time.Time `json:"createdAt"`
Credentials struct {
Aud string `json:"aud"`
Iss string `json:"iss"`
Kid string `json:"kid"`
PrivateKey *string `json:"privateKey,omitempty"`
Sub uuid.UUID `json:"sub"`
} `json:"credentials"`
ID uuid.UUID `json:"id"`
KeyAlgorithm string `json:"keyAlgorithm"`
KeyOrigin string `json:"keyOrigin"`
KeyType string `json:"keyType"`
PublicKey string `json:"publicKey"`
ValidUntil *time.Time `json:"validUntil,omitempty"`
}
// GetEnvironment returns the defined API environment
func (c *KeyFlow) GetEnvironment() env.Environment {
if c.config == nil {
return ""
}
return c.config.Environment
}
// GetConfig returns the flow configuration
func (c *KeyFlow) GetConfig() KeyFlowConfig {
if c.config == nil {
return KeyFlowConfig{}
}
return *c.config
}
// GetServiceAccountEmail returns the service account email
func (c *KeyFlow) GetServiceAccountEmail() string {
if c.key == nil {
return ""
}
return c.key.Credentials.Iss
}
// Init intializes the flow
func (c *KeyFlow) Init(ctx context.Context, cfg ...KeyFlowConfig) error {
c.client = &http.Client{}
c.token = new(TokenResponseBody)
c.processConfig(cfg...)
c.configureHTTPClient(ctx)
if c.config.ClientRetry == nil {
c.config.ClientRetry = NewRetryConfig()
}
if err := c.validateConfig(); err != nil {
return err
}
if err := c.loadFiles(); err != nil {
return err
}
return nil
}
// Clone creates a clone of the client
func (c *KeyFlow) Clone() interface{} {
sc := *c
nc := &sc
cl := *nc.client
cf := *nc.config
ke := *nc.key
to := *nc.token
nc.client = &cl
nc.config = &cf
nc.key = &ke
nc.token = &to
return c
}
// Do performs the reuqest
func (c *KeyFlow) Do(req *http.Request) (*http.Response, error) {
accessToken, err := c.GetAccessToken()
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
return do(c.client, req, c.config.ClientRetry)
}
// GetAccessToken returns short-lived access token
func (c *KeyFlow) GetAccessToken() (string, error) {
accessTokenIsValid, err := c.validateToken(c.token.AccessToken)
if err != nil {
return "", errors.Wrap(err, "failed initial validation")
}
if accessTokenIsValid {
return c.token.AccessToken, nil
}
if err := c.recreateAccessToken(); err != nil {
return "", errors.Wrap(err, "failed during token recreation")
}
return c.token.AccessToken, nil
}
// Flow Configuration
// processConfig processes the given configuration
func (c *KeyFlow) processConfig(cfg ...KeyFlowConfig) {
c.config = c.getConfigFromEnvironment()
for _, m := range cfg {
c.config = c.mergeConfigs(&m, c.config)
}
}
// getConfigFromEnvironment returns a KeyFlowConfig populated with environment variables.
func (c *KeyFlow) getConfigFromEnvironment() *KeyFlowConfig {
return &KeyFlowConfig{
ServiceAccountKeyPath: os.Getenv(ServiceAccountKeyPath),
PrivateKeyPath: os.Getenv(PrivateKeyPath),
ServiceAccountKey: []byte(os.Getenv(ServiceAccountKey)),
PrivateKey: []byte(os.Getenv(PrivateKey)),
Environment: env.Parse(os.Getenv(Environment)),
}
}
// mergeConfigs returns a new KeyFlowConfig that combines the values of cfg and currentCfg.
func (c *KeyFlow) mergeConfigs(cfg, currentCfg *KeyFlowConfig) *KeyFlowConfig {
merged := *currentCfg
if cfg.ServiceAccountKeyPath != "" {
merged.ServiceAccountKeyPath = cfg.ServiceAccountKeyPath
}
if cfg.PrivateKeyPath != "" {
merged.PrivateKeyPath = cfg.PrivateKeyPath
}
if len(cfg.ServiceAccountKey) != 0 {
merged.ServiceAccountKey = cfg.ServiceAccountKey
}
if len(cfg.PrivateKey) != 0 {
merged.PrivateKey = cfg.PrivateKey
}
if cfg.Environment != "" {
merged.Environment = cfg.Environment
}
return &merged
}
// configureHTTPClient configures the HTTP client
func (c *KeyFlow) configureHTTPClient(ctx context.Context) {
client := &http.Client{}
client.Timeout = DefaultClientTimeout
c.client = client
}
// validate the client is configured well
func (c *KeyFlow) validateConfig() error {
if len(c.config.ServiceAccountKey) == 0 && c.config.ServiceAccountKeyPath == "" {
return errors.New("Service Account Key or Key path must be specified")
}
if len(c.config.PrivateKey) == 0 && c.config.PrivateKeyPath == "" {
return errors.New("Private Key or Private Key path must be specified")
}
return nil
}
// loadFiles checks if files need to be loaded from specified paths
// and sets them accordingly
func (c *KeyFlow) loadFiles() error {
if len(c.config.ServiceAccountKey) == 0 {
b, err := os.ReadFile(c.config.ServiceAccountKeyPath)
if err != nil {
return err
}
c.config.ServiceAccountKey = b
}
if len(c.config.PrivateKey) == 0 {
b, err := os.ReadFile(c.config.PrivateKeyPath)
if err != nil {
return err
}
c.config.PrivateKey = b
}
c.key = new(ServiceAccountKeyPrivateResponse)
err := json.Unmarshal(c.config.ServiceAccountKey, c.key)
if err != nil {
return err
}
c.privateKey, err = jwt.ParseRSAPrivateKeyFromPEM(c.config.PrivateKey)
if err != nil {
return err
}
// Encode the private key in PEM format
privKeyPEM := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(c.privateKey),
}
c.privateKeyPEM = pem.EncodeToMemory(privKeyPEM)
return nil
}
// Flow auth functions
// recreateAccessToken is used to create a new access token
// when the existing one isn't valid anymore
func (c *KeyFlow) recreateAccessToken() error {
refreshTokenIsValid, err := c.validateToken(c.token.RefreshToken)
if err != nil {
return err
}
if refreshTokenIsValid {
return c.createAccessTokenWithRefreshToken()
}
return c.createAccessToken()
}
// createAccessToken creates an access token using self signed JWT
func (c *KeyFlow) createAccessToken() error {
grant := "urn:ietf:params:oauth:grant-type:jwt-bearer"
assertion, err := c.generateSelfSignedJWT()
if err != nil {
return err
}
res, err := c.requestToken(grant, assertion)
if err != nil {
return err
}
return c.parseTokenResponse(res)
}
// createAccessTokenWithRefreshToken creates an access token using
// an existing pre-validated refresh token
func (c *KeyFlow) createAccessTokenWithRefreshToken() error {
res, err := c.requestToken("refresh_token", c.token.RefreshToken)
if err != nil {
return err
}
return c.parseTokenResponse(res)
}
// generateSelfSignedJWT generates JWT token
func (c *KeyFlow) generateSelfSignedJWT() (string, error) {
claims := jwt.MapClaims{
"iss": c.key.Credentials.Iss,
"sub": c.key.Credentials.Sub,
"jti": uuid.New(),
"aud": c.key.Credentials.Aud,
"iat": jwt.NewNumericDate(time.Now()),
"exp": jwt.NewNumericDate(time.Now().Add(10 * time.Minute)),
}
token := jwt.NewWithClaims(jwt.SigningMethodRS512, claims)
token.Header["kid"] = c.key.Credentials.Kid
tokenString, err := token.SignedString(c.privateKey)
if err != nil {
return "", err
}
return tokenString, nil
}
// requestToken makes a request to the SA token API
func (c *KeyFlow) requestToken(grant, assertion string) (*http.Response, error) {
body := url.Values{}
body.Set("grant_type", grant)
body.Set("assertion", assertion)
payload := strings.NewReader(body.Encode())
req, err := http.NewRequest(http.MethodPost, tokenAPI.GetURL(c.GetEnvironment()), payload)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
return do(&http.Client{}, req, c.config.ClientRetry)
}
// parseTokenResponse parses the response from the server
func (c *KeyFlow) parseTokenResponse(res *http.Response) error {
if res == nil {
return errors.New("received bad response from API")
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("received: %+v", res)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
c.token = new(TokenResponseBody)
return json.Unmarshal(body, c.token)
}
// validateToken returns true if tokeb is valid
func (c *KeyFlow) validateToken(token string) (bool, error) {
if token == "" {
return false, nil
}
if _, err := c.parseToken(token); err != nil {
return false, err
}
return true, nil
}
// parseToken parses and validates a JWT token
func (c *KeyFlow) parseToken(token string) (*jwt.Token, error) {
b, err := c.getJwksJSON(token)
if err != nil {
return nil, err
}
var jwksBytes = json.RawMessage(b)
jwks, err := keyfunc.NewJSON(jwksBytes)
if err != nil {
return nil, err
}
return jwt.Parse(token, jwks.Keyfunc)
}
func (c *KeyFlow) getJwksJSON(token string) ([]byte, error) {
req, err := http.NewRequest("GET", jsksAPI.GetURL(c.GetEnvironment()), nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", "Bearer "+token)
res, err := do(&http.Client{}, req, c.config.ClientRetry)
if err != nil {
return nil, err
}
if res.StatusCode == 200 {
return io.ReadAll(res.Body)
} else {
return nil, fmt.Errorf("error: %s", res.Status)
}
}