forked from argoproj/argo-cd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sessionmanager.go
302 lines (278 loc) · 9.91 KB
/
sessionmanager.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
package session
import (
"context"
"fmt"
"net"
"net/http"
"net/http/httputil"
"os"
"strings"
"time"
"github.com/coreos/go-oidc"
jwt "github.com/dgrijalva/jwt-go"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/argoproj/argo-cd/common"
jwtutil "github.com/argoproj/argo-cd/util/jwt"
passwordutil "github.com/argoproj/argo-cd/util/password"
"github.com/argoproj/argo-cd/util/settings"
)
// SessionManager generates and validates JWT tokens for login sessions.
type SessionManager struct {
settings *settings.ArgoCDSettings
client *http.Client
provider *oidc.Provider
// Does the provider use "offline_access" scope to request a refresh token
// or does it use "access_type=offline" (e.g. Google)?
offlineAsScope bool
}
const (
// SessionManagerClaimsIssuer fills the "iss" field of the token.
SessionManagerClaimsIssuer = "argocd"
// invalidLoginError, for security purposes, doesn't say whether the username or password was invalid. This does not mitigate the potential for timing attacks to determine which is which.
invalidLoginError = "Invalid username or password"
blankPasswordError = "Blank passwords are not allowed"
badUserError = "Bad local superuser username"
)
// NewSessionManager creates a new session manager from ArgoCD settings
func NewSessionManager(settings *settings.ArgoCDSettings) *SessionManager {
s := SessionManager{
settings: settings,
}
tlsConfig := settings.TLSConfig()
if tlsConfig != nil {
tlsConfig.InsecureSkipVerify = true
}
s.client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
if os.Getenv(common.EnvVarSSODebug) == "1" {
s.client.Transport = debugTransport{s.client.Transport}
}
return &s
}
// Create creates a new token for a given subject (user) and returns it as a string.
// Passing a value of `0` for secondsBeforeExpiry creates a token that never expires.
func (mgr *SessionManager) Create(subject string, secondsBeforeExpiry int64) (string, error) {
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
now := time.Now().UTC()
claims := jwt.StandardClaims{
IssuedAt: now.Unix(),
Issuer: SessionManagerClaimsIssuer,
NotBefore: now.Unix(),
Subject: subject,
}
if secondsBeforeExpiry > 0 {
expires := now.Add(time.Duration(secondsBeforeExpiry) * time.Second)
claims.ExpiresAt = expires.Unix()
}
return mgr.signClaims(claims)
}
func (mgr *SessionManager) signClaims(claims jwt.Claims) (string, error) {
log.Infof("Issuing claims: %v", claims)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(mgr.settings.ServerSignature)
}
// Parse tries to parse the provided string and returns the token claims for local superuser login.
func (mgr *SessionManager) Parse(tokenString string) (jwt.Claims, error) {
// Parse takes the token string and a function for looking up the key. The latter is especially
// useful if you use multiple keys for your application. The standard is to use 'kid' in the
// head of the token to identify which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
var claims jwt.MapClaims
token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return mgr.settings.ServerSignature, nil
})
if err != nil {
return nil, err
}
issuedAt := time.Unix(int64(claims["iat"].(float64)), 0)
if issuedAt.Before(mgr.settings.AdminPasswordMtime) {
return nil, fmt.Errorf("Password for superuser has changed since token issued")
}
return token.Claims, nil
}
// VerifyUsernamePassword verifies if a username/password combo is correct
func (mgr *SessionManager) VerifyUsernamePassword(username, password string) error {
if username != common.ArgoCDAdminUsername {
return status.Errorf(codes.Unauthenticated, badUserError)
}
if password == "" {
return status.Errorf(codes.Unauthenticated, blankPasswordError)
}
valid, _ := passwordutil.VerifyPassword(password, mgr.settings.AdminPasswordHash)
if !valid {
return status.Errorf(codes.Unauthenticated, invalidLoginError)
}
return nil
}
// VerifyToken verifies if a token is correct. Tokens can be issued either from us or by dex.
// We choose how to verify based on the issuer.
func (mgr *SessionManager) VerifyToken(tokenString string) (jwt.Claims, error) {
parser := &jwt.Parser{
SkipClaimsValidation: true,
}
var claims jwt.StandardClaims
_, _, err := parser.ParseUnverified(tokenString, &claims)
if err != nil {
return nil, err
}
switch claims.Issuer {
case SessionManagerClaimsIssuer:
// ArgoCD signed token
return mgr.Parse(tokenString)
default:
// Dex signed token
provider, err := mgr.OIDCProvider()
if err != nil {
return nil, err
}
verifier := provider.Verifier(&oidc.Config{ClientID: claims.Audience})
idToken, err := verifier.Verify(context.Background(), tokenString)
if err != nil {
// HACK: if we failed token verification, it's possible the reason was because dex
// restarted and has new JWKS signing keys (we do not back dex with persistent storage
// so keys might be regenerated). Detect this by:
// 1. looking for the specific error message
// 2. re-initializing the OIDC provider
// 3. re-attempting token verification
// NOTE: the error message is sensitive to implementation of verifier.Verify()
if !strings.Contains(err.Error(), "failed to verify signature") {
return nil, err
}
provider, retryErr := mgr.initializeOIDCProvider()
if retryErr != nil {
// return original error if we fail to re-initialize OIDC
return nil, err
}
verifier = provider.Verifier(&oidc.Config{ClientID: claims.Audience})
idToken, err = verifier.Verify(context.Background(), tokenString)
if err != nil {
return nil, err
}
// If we get here, we successfully re-initialized OIDC and after re-initialization,
// the token is now valid.
log.Info("New OIDC settings detected")
}
var claims jwt.MapClaims
err = idToken.Claims(&claims)
return claims, err
}
}
// Username is a helper to extract a human readable username from a context
func Username(ctx context.Context) string {
claims, ok := ctx.Value("claims").(jwt.Claims)
if !ok {
return ""
}
mapClaims, err := jwtutil.MapClaims(claims)
if err != nil {
return ""
}
switch jwtutil.GetField(mapClaims, "iss") {
case SessionManagerClaimsIssuer:
return jwtutil.GetField(mapClaims, "sub")
default:
return jwtutil.GetField(mapClaims, "email")
}
}
// MakeCookieMetadata generates a string representing a Web cookie. Yum!
func MakeCookieMetadata(key, value string, flags ...string) string {
components := []string{
fmt.Sprintf("%s=%s", key, value),
}
components = append(components, flags...)
return strings.Join(components, "; ")
}
// OIDCProvider lazily initializes, memoizes, and returns the OIDC provider.
// We have to initialize the provider lazily since ArgoCD is an OIDC client to itself, which
// presents a chicken-and-egg problem of (1) serving dex over HTTP, and (2) querying the OIDC
// provider (ourselves) to initialize the app.
func (mgr *SessionManager) OIDCProvider() (*oidc.Provider, error) {
if mgr.provider != nil {
return mgr.provider, nil
}
return mgr.initializeOIDCProvider()
}
// initializeOIDCProvider re-initializes the OIDC provider, querying the well known oidc
// configuration path (http://example-argocd.com/api/dex/.well-known/openid-configuration)
func (mgr *SessionManager) initializeOIDCProvider() (*oidc.Provider, error) {
if !mgr.settings.IsSSOConfigured() {
return nil, fmt.Errorf("SSO is not configured")
}
issuerURL := mgr.settings.IssuerURL()
log.Infof("Initializing OIDC provider (issuer: %s)", issuerURL)
ctx := oidc.ClientContext(context.Background(), mgr.client)
provider, err := oidc.NewProvider(ctx, issuerURL)
if err != nil {
return nil, fmt.Errorf("Failed to query provider %q: %v", issuerURL, err)
}
// Returns the scopes the provider supports
// See: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
var s struct {
ScopesSupported []string `json:"scopes_supported"`
}
if err := provider.Claims(&s); err != nil {
return nil, fmt.Errorf("Failed to parse provider scopes_supported: %v", err)
}
log.Infof("OpenID supported scopes: %v", s.ScopesSupported)
offlineAsScope := false
if len(s.ScopesSupported) == 0 {
// scopes_supported is a "RECOMMENDED" discovery claim, not a required
// one. If missing, assume that the provider follows the spec and has
// an "offline_access" scope.
offlineAsScope = true
} else {
// See if scopes_supported has the "offline_access" scope.
for _, scope := range s.ScopesSupported {
if scope == oidc.ScopeOfflineAccess {
offlineAsScope = true
break
}
}
}
mgr.provider = provider
mgr.offlineAsScope = offlineAsScope
return mgr.provider, nil
}
// OfflineAsScope returns whether or not the OIDC provider supports offline as a scope
func (mgr *SessionManager) OfflineAsScope() bool {
_, _ = mgr.OIDCProvider() // forces offlineAsScope to be determined
return mgr.offlineAsScope
}
type debugTransport struct {
t http.RoundTripper
}
func (d debugTransport) RoundTrip(req *http.Request) (*http.Response, error) {
reqDump, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
log.Printf("%s", reqDump)
resp, err := d.t.RoundTrip(req)
if err != nil {
return nil, err
}
respDump, err := httputil.DumpResponse(resp, true)
if err != nil {
_ = resp.Body.Close()
return nil, err
}
log.Printf("%s", respDump)
return resp, nil
}