-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathoidc_credential.go
More file actions
206 lines (175 loc) · 5.36 KB
/
Copy pathoidc_credential.go
File metadata and controls
206 lines (175 loc) · 5.36 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
package oidc
import (
"context"
"fmt"
"net/http"
"net/url"
"sync"
"time"
"github.com/elazarl/goproxy"
"github.com/dependabot/proxy/internal/config"
"github.com/dependabot/proxy/internal/helpers"
"github.com/dependabot/proxy/internal/logging"
)
type OIDCParameters interface {
Name() string
}
type AzureOIDCParameters struct {
TenantID string
ClientID string
}
func (a *AzureOIDCParameters) Name() string {
return "azure"
}
type JFrogOIDCParameters struct {
JFrogURL string
ProviderName string
Audience string
IdentityMappingName string
}
func (j *JFrogOIDCParameters) Name() string {
return "jfrog"
}
type AWSOIDCParameters struct {
Region string
AccountID string
RoleName string
Audience string
Domain string
DomainOwner string
}
func (a *AWSOIDCParameters) Name() string {
return "aws"
}
type OIDCCredential struct {
parameters OIDCParameters
cachedToken string
tokenExpiry time.Time
isRejected bool
mutex sync.RWMutex
}
func (c *OIDCCredential) Provider() string {
return c.parameters.Name()
}
func CreateOIDCCredential(cred config.Credential) (*OIDCCredential, error) {
if !IsOIDCConfigured() {
return nil, fmt.Errorf("OIDC is not configured")
}
var parameters OIDCParameters
// azure values
tenantID := cred.GetString("tenant-id")
clientID := cred.GetString("client-id")
// jfrog values
feedUrl := cred.GetString("url")
jfrogOidcProviderName := cred.GetString("jfrog-oidc-provider-name")
// aws values
awsRegion := cred.GetString("aws-region")
accountID := cred.GetString("account-id")
roleName := cred.GetString("role-name")
domain := cred.GetString("domain")
domainOwner := cred.GetString("domain-owner")
switch {
case tenantID != "" && clientID != "":
parameters = &AzureOIDCParameters{
TenantID: tenantID,
ClientID: clientID,
}
case jfrogOidcProviderName != "" && feedUrl != "":
// jfrog domain is extracted from feed url
jfrogUrlParsed, err := url.Parse(feedUrl)
if err != nil {
return nil, fmt.Errorf("invalid jfrog url: %w", err)
}
parameters = &JFrogOIDCParameters{
// required
JFrogURL: fmt.Sprintf("%s://%s", jfrogUrlParsed.Scheme, jfrogUrlParsed.Host),
ProviderName: jfrogOidcProviderName,
// optional
Audience: cred.GetString("audience"),
IdentityMappingName: cred.GetString("identity-mapping-name"),
}
case awsRegion != "" && accountID != "" && roleName != "" && domain != "" && domainOwner != "":
audience := cred.GetString("audience")
if audience == "" {
audience = "sts.amazonaws.com" // defaults to this
}
parameters = &AWSOIDCParameters{
Region: awsRegion,
AccountID: accountID,
RoleName: roleName,
Audience: audience,
Domain: domain,
DomainOwner: domainOwner,
}
}
if parameters == nil {
return nil, fmt.Errorf("OIDC parameters were not specified")
}
return &OIDCCredential{
parameters: parameters,
}, nil
}
// GetOrRefreshOIDCToken gets a cached token or fetches a new one if expired
func GetOrRefreshOIDCToken(cred *OIDCCredential, ctx context.Context) (string, error) {
if cred.isRejected {
return "", fmt.Errorf("credential has been rejected due to previous authentication failure")
}
cred.mutex.RLock()
if cred.cachedToken != "" && time.Now().Before(cred.tokenExpiry) {
token := cred.cachedToken
cred.mutex.RUnlock()
return token, nil
}
cred.mutex.RUnlock()
cred.mutex.Lock()
defer cred.mutex.Unlock()
if cred.cachedToken != "" && time.Now().Before(cred.tokenExpiry) {
return cred.cachedToken, nil
}
var oidcAccessToken *OIDCAccessToken
var err error
switch params := cred.parameters.(type) {
case *AzureOIDCParameters:
oidcAccessToken, err = GetAzureAccessTokenForDevOps(ctx, *params)
case *JFrogOIDCParameters:
oidcAccessToken, err = GetJFrogAccessTokenForDevOps(ctx, *params)
case *AWSOIDCParameters:
oidcAccessToken, err = GetAWSAccessTokenForDevOps(ctx, *params)
default:
return "", fmt.Errorf("unsupported OIDC provider: %s", cred.Provider())
}
if err != nil {
cred.isRejected = true
return "", fmt.Errorf("failed to get %s access token: %w", cred.Provider(), err)
}
cred.cachedToken = oidcAccessToken.Token
cred.tokenExpiry = time.Now().Add(oidcAccessToken.ExpiresIn).Add(-time.Minute * 5) // refresh 5 minutes before expiry
return oidcAccessToken.Token, nil
}
// TryAuthOIDCRequestWithPrefix tries to authenticate the request using OIDC credentials if available
func TryAuthOIDCRequestWithPrefix(mutex *sync.RWMutex, oidcCredentials map[string]*OIDCCredential, req *http.Request, ctx *goproxy.ProxyCtx) bool {
// Find matching credential while holding the lock, then release before token refresh
var matchedCred *OIDCCredential
if len(oidcCredentials) > 0 {
mutex.RLock()
for key, oidcCred := range oidcCredentials {
// Match by URL or host
if helpers.UrlMatchesRequest(req, key, true) || helpers.CheckHost(req, key) {
matchedCred = oidcCred
break
}
}
mutex.RUnlock()
}
if matchedCred != nil {
token, err := GetOrRefreshOIDCToken(matchedCred, req.Context())
if err != nil {
logging.RequestLogf(ctx, "* failed to get %s token via OIDC for %s: %v", matchedCred.Provider(), req.URL.Hostname(), err)
} else {
logging.RequestLogf(ctx, "* authenticating request with OIDC token (host: %s)", req.URL.Hostname())
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
return true
}
}
return false
}