forked from opensciencegrid/stashcp
-
Notifications
You must be signed in to change notification settings - Fork 6
/
acquire_token.go
261 lines (235 loc) · 8.06 KB
/
acquire_token.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
package stashcp
import (
"context"
"fmt"
"net/url"
"path"
"strings"
"time"
config "github.com/htcondor/osdf-client/v6/config"
namespaces "github.com/htcondor/osdf-client/v6/namespaces"
log "github.com/sirupsen/logrus"
jwt "github.com/golang-jwt/jwt"
oauth2 "github.com/htcondor/osdf-client/v6/oauth2"
oauth2_upstream "golang.org/x/oauth2"
)
func TokenIsAcceptable(jwtSerialized string, osdfPath string, namespace namespaces.Namespace, isWrite bool) bool {
parser := jwt.Parser{SkipClaimsValidation: true}
token, _, err := parser.ParseUnverified(jwtSerialized, &jwt.MapClaims{})
if err != nil {
log.Warningln("Failed to parse token:", err)
return false
}
// For now, we'll accept any WLCG token
wlcg_ver := (*token.Claims.(*jwt.MapClaims))["wlcg.ver"]
if wlcg_ver == nil {
return false
}
osdfPathCleaned := path.Clean(osdfPath)
if !strings.HasPrefix(osdfPathCleaned, namespace.Path) {
return false
}
// For some issuers, the token base path is distinct from the OSDF base path.
// Example:
// - Issuer base path: `/chtc`
// - Namespace path: `/chtc/PROTECTED`
// In this case, we want to strip out the issuer base path, not the
// namespace one, in order to see if the token has the right privs.
targetResource := path.Clean("/" + osdfPathCleaned[len(namespace.Path):])
if namespace.CredentialGen != nil && namespace.CredentialGen.BasePath != nil && len(*namespace.CredentialGen.BasePath) > 0 {
targetResource = path.Clean("/" + osdfPathCleaned[len(*namespace.CredentialGen.BasePath):])
}
scopes_iface := (*token.Claims.(*jwt.MapClaims))["scope"]
if scopes, ok := scopes_iface.(string); ok {
acceptableScope := false
for _, scope := range strings.Split(scopes, " ") {
scope_info := strings.Split(scope, ":")
scopeOK := false
if isWrite && (scope_info[0] == "storage.modify" || scope_info[0] == "storage.create") {
scopeOK = true
} else if scope_info[0] == "storage.read" {
scopeOK = true
}
if !scopeOK {
continue
}
if len(scope_info) == 1 {
acceptableScope = true
break
}
if strings.HasPrefix(targetResource, scope_info[1]) {
acceptableScope = true
break
}
}
if acceptableScope {
return true
}
}
return false
}
func TokenIsExpired(jwtSerialized string) bool {
parser := jwt.Parser{SkipClaimsValidation: true}
token, _, err := parser.ParseUnverified(jwtSerialized, &jwt.StandardClaims{})
if err != nil {
log.Warningln("Failed to parse token:", err)
return true
}
if claims, ok := token.Claims.(*jwt.StandardClaims); ok {
return claims.Valid() != nil
}
return true
}
func RegisterClient(namespace namespaces.Namespace) (*config.PrefixEntry, error) {
issuer, err := oauth2.GetIssuerMetadata(*namespace.CredentialGen.Issuer)
if err != nil {
return nil, err
}
if issuer.RegistrationURL == "" {
return nil, fmt.Errorf("Issuer %s does not support dynamic client registration", *namespace.CredentialGen.Issuer)
}
drcp := oauth2.DCRPConfig{ClientRegistrationEndpointURL: issuer.RegistrationURL, Metadata: oauth2.Metadata{
RedirectURIs: []string{"https://localhost/osdf-client"},
TokenEndpointAuthMethod: "client_secret_basic",
GrantTypes: []string{"refresh_token", "urn:ietf:params:oauth:grant-type:device_code"},
ResponseTypes: []string{"code"},
ClientName: "OSDF Command Line Client",
Scopes: []string{"offline_access", "wlcg", "storage.read:/", "storage.modify:/", "storage.create:/"},
}}
resp, err := drcp.Register()
if err != nil {
return nil, err
}
newEntry := config.PrefixEntry{
Prefix: namespace.Path,
ClientID: resp.ClientID,
ClientSecret: resp.ClientSecret,
}
return &newEntry, nil
}
// Given a URL and a piece of the namespace, attempt to acquire a valid
// token for that URL.
func AcquireToken(destination *url.URL, namespace namespaces.Namespace, isWrite bool) (string, error) {
log.Debugln("Acquiring a token from configuration and OAuth2")
if namespace.CredentialGen == nil || namespace.CredentialGen.Strategy == nil {
return "", fmt.Errorf("Credential generation scheme unknown for prefix %s", namespace.Path)
}
switch strategy := *namespace.CredentialGen.Strategy; strategy {
case "OAuth2":
case "Vault":
return "", fmt.Errorf("Vault credential generation strategy is not supported")
default:
return "", fmt.Errorf("Unknown credential generation strategy (%s) for prefix %s",
strategy, namespace.Path)
}
issuer := *namespace.CredentialGen.Issuer
if len(issuer) == 0 {
return "", fmt.Errorf("Issuer for prefix %s is unknown", namespace.Path)
}
osdfConfig, err := config.GetConfigContents()
if err != nil {
return "", err
}
prefixIdx := -1
for idx, entry := range osdfConfig.OSDF.OauthClient {
if entry.Prefix == namespace.Path {
prefixIdx = idx
break
}
}
var prefixEntry *config.PrefixEntry
newEntry := false
if prefixIdx < 0 {
log.Infof("Prefix configuration for %s not in configuration file; will request new client", namespace.Path)
prefixEntry, err = RegisterClient(namespace)
if err != nil {
return "", err
}
osdfConfig.OSDF.OauthClient = append(osdfConfig.OSDF.OauthClient, *prefixEntry)
prefixEntry = &osdfConfig.OSDF.OauthClient[len(osdfConfig.OSDF.OauthClient) - 1]
newEntry = true
} else {
prefixEntry = &osdfConfig.OSDF.OauthClient[prefixIdx]
if len(prefixEntry.ClientID) == 0 || len(prefixEntry.ClientSecret) == 0 {
log.Infof("Prefix configuration for %s missing OAuth2 client information", namespace.Path)
prefixEntry, err = RegisterClient(namespace)
if err != nil {
return "", err
}
osdfConfig.OSDF.OauthClient[prefixIdx] = *prefixEntry
newEntry = true
}
}
if newEntry {
if err = config.SaveConfigContents(&osdfConfig); err != nil {
log.Warningln("Failed to save new token to configuration file:", err)
}
}
// For now, a fairly useless token-selection algorithm - take the first in the list.
// In the future, we should:
// - Check scopes
var acceptableToken *config.TokenEntry = nil
acceptableUnexpiredToken := ""
for idx, token := range prefixEntry.Tokens {
if !TokenIsAcceptable(token.AccessToken, destination.Path, namespace, isWrite) {
continue
}
if acceptableToken == nil {
acceptableToken = &prefixEntry.Tokens[idx]
} else if acceptableUnexpiredToken != "" {
// Both tokens are non-empty; let's use them
break
}
if !TokenIsExpired(token.AccessToken) {
acceptableUnexpiredToken = token.AccessToken
}
}
if len(acceptableUnexpiredToken) > 0 {
log.Debugln("Returning an unexpired token from cache")
return acceptableUnexpiredToken, nil
}
if acceptableToken != nil && len(acceptableToken.RefreshToken) > 0 {
// We have a reasonable token; let's try refreshing it.
upstreamToken := oauth2_upstream.Token{
AccessToken: acceptableToken.AccessToken,
RefreshToken: acceptableToken.RefreshToken,
Expiry: time.Unix(0, 0),
}
issuerInfo, err := oauth2.GetIssuerMetadata(issuer)
if err == nil {
upstreamConfig := oauth2_upstream.Config{
ClientID: prefixEntry.ClientID,
ClientSecret: prefixEntry.ClientSecret,
Endpoint: oauth2_upstream.Endpoint{
AuthURL: issuerInfo.AuthURL,
TokenURL: issuerInfo.TokenURL,
}}
ctx := context.Background()
source := upstreamConfig.TokenSource(ctx, &upstreamToken)
newToken, err := source.Token()
if err != nil {
log.Warningln("Failed to renew an expired token:", err)
} else {
acceptableToken.AccessToken = newToken.AccessToken
acceptableToken.Expiration = newToken.Expiry.Unix()
if len(newToken.RefreshToken) != 0 {
acceptableToken.RefreshToken = newToken.RefreshToken
}
if err = config.SaveConfigContents(&osdfConfig); err != nil {
log.Warningln("Failed to save new token to configuration file:", err)
}
return newToken.AccessToken, nil
}
}
}
token, err := oauth2.AcquireToken(issuer, prefixEntry, namespace.CredentialGen, destination.Path, isWrite)
if err != nil {
return "", err
}
Tokens := &prefixEntry.Tokens
*Tokens = append(*Tokens, *token)
if err = config.SaveConfigContents(&osdfConfig); err != nil {
log.Warningln("Failed to save new token to configuration file:", err)
}
return token.AccessToken, nil
}