-
Notifications
You must be signed in to change notification settings - Fork 21
/
artifactory.go
632 lines (515 loc) · 18.9 KB
/
artifactory.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
package artifactory
import (
"bytes"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v4"
"github.com/hashicorp/go-version"
"github.com/hashicorp/vault/sdk/helper/template"
"github.com/samber/lo"
)
const (
defaultUserNameTemplate string = `{{ printf "v-%s-%s" (.RoleName | truncate 24) (random 8) }}` // Docs indicate max length is 256
grantTypeClientCredentials string = "client_credentials"
grantTypeRefreshToken string = "refresh_token"
)
var ErrIncompatibleVersion = errors.New("incompatible version")
type baseConfiguration struct {
AccessToken string `json:"access_token"`
ArtifactoryURL string `json:"artifactory_url"`
UseExpiringTokens bool `json:"use_expiring_tokens,omitempty"`
ForceRevocable *bool `json:"force_revocable,omitempty"`
}
type errorResponse struct {
Code string `json:"code"`
Message string `json:"message"`
Detail string `json:"detail"`
}
func (b *backend) RevokeToken(config baseConfiguration, tokenId, accessToken string) error {
if config.AccessToken == "" {
return fmt.Errorf("empty access token not allowed")
}
logger := b.Logger().With("func", "RevokeToken")
u, err := url.Parse(config.ArtifactoryURL)
if err != nil {
logger.Error("could not parse artifactory url", "url", u, "err", err)
return err
}
var resp *http.Response
if b.useNewAccessAPI(config) {
resp, err = b.performArtifactoryDelete(config, "/access/api/v1/tokens/"+tokenId)
if err != nil {
logger.Error("error deleting access token", "tokenId", tokenId, "response", resp, "err", err)
return err
}
} else {
values := url.Values{}
values.Set("token", accessToken)
resp, err = b.performArtifactoryPost(config, u.Path+"/artifactory/api/security/token/revoke", values)
if err != nil {
logger.Error("error deleting token", "tokenId", tokenId, "response", resp, "err", err)
return err
}
}
//noinspection GoUnhandledErrorResult
defer resp.Body.Close()
if resp.StatusCode >= http.StatusBadRequest {
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Error("revokenToken could not read error response body", "err", err)
return fmt.Errorf("could not parse response body. Err: %v", err)
}
logger.Error("revokenToken got non-200 status code", "statusCode", resp.StatusCode, "body", string(body))
return fmt.Errorf("could not revoke tokenID: %v - HTTP response %v", tokenId, body)
}
return nil
}
type CreateTokenRequest struct {
GrantType string `json:"grant_type,omitempty"`
Username string `json:"username,omitempty"`
Scope string `json:"scope,omitempty"`
ExpiresIn int64 `json:"expires_in"`
Refreshable bool `json:"refreshable,omitempty"`
Description string `json:"description,omitempty"`
Audience string `json:"audience,omitempty"`
ForceRevocable bool `json:"force_revocable,omitempty"`
IncludeReferenceToken bool `json:"include_reference_token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
}
type createTokenErrorResponse struct {
Errors []errorResponse `json:"errors"`
}
type TokenExpiredError struct{}
func (e *TokenExpiredError) Error() string {
return "token has expired"
}
func (b *backend) CreateToken(config baseConfiguration, role artifactoryRole) (*createTokenResponse, error) {
request := CreateTokenRequest{
GrantType: role.GrantType,
Username: role.Username,
Scope: role.Scope,
Audience: role.Audience,
Description: role.Description,
Refreshable: role.Refreshable,
IncludeReferenceToken: role.IncludeReferenceToken,
RefreshToken: role.RefreshToken,
}
return b.createToken(config, role.ExpiresIn, request)
}
func (b *backend) RefreshToken(config baseConfiguration, role artifactoryRole) (*createTokenResponse, error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
if role.RefreshToken == "" {
return nil, fmt.Errorf("no refresh token supplied")
}
request := CreateTokenRequest{
GrantType: grantTypeRefreshToken,
RefreshToken: role.RefreshToken,
}
return b.createToken(config, role.ExpiresIn, request)
}
func (b *backend) createToken(config baseConfiguration, expiresIn time.Duration, request CreateTokenRequest) (*createTokenResponse, error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
if request.GrantType == "client_credentials" && len(request.Username) == 0 {
return nil, fmt.Errorf("empty username not allowed, possibly a template error")
}
logger := b.Logger().With("func", "createToken")
// Artifactory will not let you revoke a token that has an expiry unless it also meets
// criteria that can only be set in its configuration file. The version of Artifactory
// I'm testing against will actually delete a token when you ask it to revoke by token_id,
// but the token is still usable even after it's deleted. See RTFACT-15293.
request.ExpiresIn = 0 // never expires
if config.UseExpiringTokens && b.supportForceRevocable(config) && expiresIn > 0 {
request.ExpiresIn = int64(expiresIn.Seconds())
if config.ForceRevocable != nil {
request.ForceRevocable = *config.ForceRevocable
} else {
request.ForceRevocable = true
}
}
u, err := url.Parse(config.ArtifactoryURL)
if err != nil {
logger.Error("could not parse artifactory url", "url", config.ArtifactoryURL, "err", err)
return nil, err
}
path := ""
if b.useNewAccessAPI(config) {
path = "/access/api/v1/tokens"
} else {
path = u.Path + "/artifactory/api/security/token"
}
jsonReq, err := json.Marshal(request)
if err != nil {
return nil, err
}
resp, err := b.performArtifactoryPostWithJSON(config, path, jsonReq)
if err != nil {
logger.Error("error making token request", "response", resp, "err", err)
return nil, err
}
//noinspection GoUnhandledErrorResult
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
e := fmt.Errorf("could not create access token: HTTP response %v", resp.StatusCode)
if resp.StatusCode == http.StatusUnauthorized {
var errResp createTokenErrorResponse
err := json.NewDecoder(resp.Body).Decode(&errResp)
if err != nil {
logger.Error("could not parse error response", "response", resp, "err", err)
return nil, fmt.Errorf("could not create access token. Err: %v", err)
}
errMessages := lo.Reduce(errResp.Errors, func(agg string, e errorResponse, _ int) string {
return fmt.Sprintf("%s, %s", agg, e.Message)
}, "")
expiredTokenRe := regexp.MustCompile(`.*Invalid token, expired.*`)
if expiredTokenRe.MatchString(errMessages) {
return nil, &TokenExpiredError{}
}
}
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Error("createToken could not read error response body", "err", err)
return nil, fmt.Errorf("could not parse response body. Err: %v", e)
}
logger.Error("createToken got non-200 status code", "statusCode", resp.StatusCode, "body", string(body))
return nil, fmt.Errorf("could not create access token. HTTP response: %s", body)
}
var createdToken createTokenResponse
if err := json.NewDecoder(resp.Body).Decode(&createdToken); err != nil {
logger.Error("could not parse response", "response", resp, "err", err)
return nil, fmt.Errorf("could not create access token. Err: %v", err)
}
return &createdToken, nil
}
// supportForceRevocable verifies whether or not the Artifactory version is 7.50.3 or higher.
// The access API changes in v7.50.3 to support force_revocable to allow us to set the expiration for the tokens.
// REF: https://www.jfrog.com/confluence/display/JFROG/JFrog+Platform+REST+API#JFrogPlatformRESTAPI-CreateToken
func (b *backend) supportForceRevocable(config baseConfiguration) bool {
return b.checkVersion("7.50.3", config)
}
// useNewAccessAPI verifies whether or not the Artifactory version is 7.21.1 or higher.
// The access API changed in v7.21.1
// REF: https://www.jfrog.com/confluence/display/JFROG/Artifactory+REST+API#ArtifactoryRESTAPI-AccessTokens
func (b *backend) useNewAccessAPI(config baseConfiguration) bool {
return b.checkVersion("7.21.1", config)
}
// getVersion will fetch the current Artifactory version and store it in the backend
func (b *backend) getVersion(config baseConfiguration) (version string, err error) {
logger := b.Logger().With("func", "getVersion")
resp, err := b.performArtifactoryGet(config, "/artifactory/api/system/version")
if err != nil {
logger.Error("error making system version request", "response", resp, "err", err)
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Error("got non-200 status code", "statusCode", resp.StatusCode)
return "", fmt.Errorf("could not get the system version: HTTP response %v", resp.StatusCode)
}
var systemVersion systemVersionResponse
if err = json.NewDecoder(resp.Body).Decode(&systemVersion); err != nil {
logger.Error("could not parse system version response", "response", resp, "err", err)
return "", err
}
return systemVersion.Version, nil
}
// checkVersion will return a boolean and error to check compatibility before making an API call
// -- This was formerly "checkSystemStatus" but that was hard-coded, that method now calls this one
func (b *backend) checkVersion(ver string, config baseConfiguration) (compatible bool) {
logger := b.Logger().With("func", "checkVersion")
artifactoryVersion, err := b.getVersion(config)
if err != nil {
logger.Error("Unable to get Artifactory Version. Check url and access_token fields. TLS connection verification with Artifactory can be skipped by setting bypass_artifactory_tls_verification field to 'true'", "ver", artifactoryVersion, "err", err)
return
}
v1, err := version.NewVersion(artifactoryVersion)
if err != nil {
logger.Error("could not parse Artifactory system version", "ver", artifactoryVersion, "err", err)
return
}
v2, err := version.NewVersion(ver)
if err != nil {
logger.Error("could not parse provided version", "ver", ver, "err", err)
return
}
if v1.GreaterThanOrEqual(v2) {
compatible = true
}
return
}
// parseJWT will parse a JWT token string from Artifactory and return a *jwt.Token, err
func (b *backend) parseJWT(config baseConfiguration, token string) (jwtToken *jwt.Token, err error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
validate := true
logger := b.Logger().With("func", "parseJWT")
cert, err := b.getRootCert(config)
if err != nil {
if errors.Is(err, ErrIncompatibleVersion) {
logger.Error("outdated artifactory, unable to retrieve root cert, skipping token validation")
validate = false
} else {
logger.Error("error retrieving root cert", "err", err.Error())
return
}
}
// Parse Token
if validate {
jwtToken, err = jwt.Parse(token,
func(token *jwt.Token) (interface{}, error) { return cert.PublicKey, nil },
jwt.WithValidMethods([]string{"RS256"}))
if err != nil {
return
}
if !jwtToken.Valid {
return
}
} else { // SKIP Validation
// -- NOTE THIS IGNORES THE SIGNATURE, which is probably bad,
// but it is artifactory's job to validate the token, right?
// p := jwt.Parser{}
// token, _, err := p.ParseUnverified(oldAccessToken, jwt.MapClaims{})
jwtToken, err = jwt.Parse(token, nil, jwt.WithoutClaimsValidation())
if err != nil {
return
}
}
// If we got here, we should have a jwtToken and nil err
return
}
type TokenInfo struct {
TokenID string `json:"token_id"`
Scope string `json:"scope"`
Username string `json:"username"`
Expires int64 `json:"expires"`
}
// getTokenInfo will parse the provided token to return useful information about it
func (b *backend) getTokenInfo(config baseConfiguration, token string) (info *TokenInfo, err error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
// Parse Current Token (to get tokenID/scope)
jwtToken, err := b.parseJWT(config, token)
if err != nil {
return
}
claims, ok := jwtToken.Claims.(jwt.MapClaims)
if !ok {
return nil, errors.New("error parsing claims in AccessToken")
}
sub := strings.Split(claims["sub"].(string), "/") // sub -> subject (jfac@01fr1x1h805xmg0t17xhqr1v7a/users/admin)
info = &TokenInfo{
TokenID: claims["jti"].(string), // jti -> JFrog Token ID
Scope: claims["scp"].(string), // scp -> scope
Username: strings.Join(sub[2:], "/"), // 3rd+ elements (incase username has / in it)
}
logger := b.Logger().With("func", "getTokenInfo")
// exp -> expires at (unixtime) - may not be present
switch exp := claims["exp"].(type) {
case int64:
info.Expires = exp
case float64:
info.Expires = int64(exp) // close enough this should be int64 anyhow
case json.Number:
v, err := exp.Int64()
if err != nil {
logger.Error("error parsing token exp as json.Number", "err", err)
}
info.Expires = v
}
return
}
// getRootCert will return the Artifactory access root certificate's public key, for validating token signatures
func (b *backend) getRootCert(config baseConfiguration) (cert *x509.Certificate, err error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
// Verify Artifactory version is at 7.12.0 or higher, prior versions will not work
// REF: https://jfrog.com/help/r/jfrog-rest-apis/get-root-certificate
if !b.checkVersion("7.12.0", config) {
return cert, ErrIncompatibleVersion
}
logger := b.Logger().With("func", "getRootCert")
resp, err := b.performArtifactoryGet(config, "/access/api/v1/cert/root")
if err != nil {
logger.Error("error requesting cert/root", "response", resp, "err", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Error("got non-200 status code", "statusCode", resp.StatusCode)
return cert, fmt.Errorf("could not get the certificate: HTTP response %v", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
logger.Error("error reading root cert response body", "err", err)
return
}
// The certificate is base64 encoded DER
binCert := make([]byte, len(body))
n, err := base64.StdEncoding.Decode(binCert, body)
if err != nil {
logger.Error("error decoding body", "err", err)
return
}
cert, err = x509.ParseCertificate(binCert[0:n])
if err != nil {
logger.Error("error parsing certificate", "err", err)
return
}
return
}
type Feature struct {
FeatureId string `json:"featureId"`
}
type Usage struct {
ProductId string `json:"productId"`
Features []Feature `json:"features"`
}
func (b *backend) sendUsage(config baseConfiguration, featureId string) {
logger := b.Logger().With("func", "sendUsage")
if config.AccessToken == "" {
logger.Info("access token is empty in config")
return
}
features := []Feature{
{
FeatureId: featureId,
},
}
usage := Usage{
productId,
features,
}
jsonReq, err := json.Marshal(usage)
if err != nil {
logger.Info("error marshalling call home request", "err", err)
return
}
resp, err := b.performArtifactoryPostWithJSON(config, "artifactory/api/system/usage", jsonReq)
if err != nil {
logger.Info("error making call home request", "response", resp, "err", err)
return
}
//noinspection GoUnhandledErrorResult
defer resp.Body.Close()
}
func (b *backend) performArtifactoryGet(config baseConfiguration, path string) (*http.Response, error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
u, err := parseURLWithDefaultPort(config.ArtifactoryURL)
if err != nil {
return nil, err
}
u.Path = path // replace any path in the URL with the provided path
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", productId)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.AccessToken))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
return b.httpClient.Do(req)
}
// performArtifactoryPost will HTTP POST values to the Artifactory API.
func (b *backend) performArtifactoryPost(config baseConfiguration, path string, values url.Values) (*http.Response, error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
u, err := parseURLWithDefaultPort(config.ArtifactoryURL)
if err != nil {
return nil, err
}
// Replace URL Path
u.Path = path
req, err := http.NewRequest(http.MethodPost, u.String(), strings.NewReader(values.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", productId)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.AccessToken))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
return b.httpClient.Do(req)
}
// performArtifactoryPost will HTTP POST data to the Artifactory API.
func (b *backend) performArtifactoryPostWithJSON(config baseConfiguration, path string, postData []byte) (*http.Response, error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
u, err := parseURLWithDefaultPort(config.ArtifactoryURL)
if err != nil {
return nil, err
}
// Replace URL Path
u.Path = path
postDataBuf := bytes.NewBuffer(postData)
req, err := http.NewRequest(http.MethodPost, u.String(), postDataBuf)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", productId)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.AccessToken))
req.Header.Add("Content-Type", "application/json")
return b.httpClient.Do(req)
}
// performArtifactoryDelete will HTTP DELETE to the Artifactory API.
// The path will be appended to the configured configured URL Path (usually /artifactory)
func (b *backend) performArtifactoryDelete(config baseConfiguration, path string) (*http.Response, error) {
if config.AccessToken == "" {
return nil, fmt.Errorf("empty access token not allowed")
}
u, err := parseURLWithDefaultPort(config.ArtifactoryURL)
if err != nil {
return nil, err
}
// Replace URL Path
u.Path = path
req, err := http.NewRequest(http.MethodDelete, u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", productId)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.AccessToken))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
return b.httpClient.Do(req)
}
func parseURLWithDefaultPort(rawUrl string) (*url.URL, error) {
urlParsed, err := url.ParseRequestURI(rawUrl)
if err != nil {
return nil, err
}
if urlParsed.Port() == "" {
defaultPort, err := net.LookupPort("tcp", urlParsed.Scheme)
if err != nil {
return nil, err
}
urlParsed.Host = fmt.Sprintf("%s:%d", urlParsed.Host, defaultPort)
}
return urlParsed, nil
}
func testUsernameTemplate(testTemplate string) (up template.StringTemplate, err error) {
up, err = template.NewTemplate(template.Template(testTemplate))
if err != nil {
return up, fmt.Errorf("username_template initialization error: %w", err)
}
_, err = up.Generate(UsernameMetadata{})
if err != nil {
return up, fmt.Errorf("username_template failed to generate username: %w", err)
}
return
}