-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathlogin.go
More file actions
1385 lines (1213 loc) · 55.5 KB
/
Copy pathlogin.go
File metadata and controls
1385 lines (1213 loc) · 55.5 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
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020-2026 the Pinniped contributors. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package oidcclient implements a CLI OIDC login flow.
package oidcclient
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net"
"net/http"
"net/url"
"os"
"slices"
"sort"
"strings"
"sync"
"time"
coreosoidc "github.com/coreos/go-oidc/v3/oidc"
"github.com/go-logr/logr"
"github.com/pkg/browser"
"golang.org/x/oauth2"
"golang.org/x/term"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
idpdiscoveryv1alpha1 "go.pinniped.dev/generated/latest/apis/supervisor/idpdiscovery/v1alpha1"
oidcapi "go.pinniped.dev/generated/latest/apis/supervisor/oidc"
"go.pinniped.dev/internal/federationdomain/upstreamprovider"
"go.pinniped.dev/internal/httputil/httperr"
"go.pinniped.dev/internal/httputil/roundtripper"
"go.pinniped.dev/internal/httputil/securityheader"
"go.pinniped.dev/internal/net/phttp"
"go.pinniped.dev/internal/plog"
"go.pinniped.dev/internal/upstreamoidc"
"go.pinniped.dev/pkg/oidcclient/nonce"
"go.pinniped.dev/pkg/oidcclient/oidctypes"
"go.pinniped.dev/pkg/oidcclient/pkce"
"go.pinniped.dev/pkg/oidcclient/state"
)
const (
// minIDTokenValidity is the minimum amount of time that a cached ID token must be still be valid to be considered.
// This is non-zero to ensure that most of the time, your ID token won't expire in the middle of a multistep k8s
// API operation.
minIDTokenValidity = 10 * time.Minute
// minAccessTokenValidity is the minimum amount of time that a cached access token must be still be valid
// to be considered.
// This is non-zero to ensure that most of the time, your access token won't expire before we submit it for
// RFC8693 token exchange.
minAccessTokenValidity = 10 * time.Second
// httpRequestTimeout is the timeout for operations that involve one (or a few) non-interactive HTTPS requests.
// Since these don't involve any user interaction, they should always be roughly as fast as network latency.
httpRequestTimeout = 60 * time.Second
// overallTimeout is the overall time that a login is allowed to take. This includes several user interactions, so
// we set this to be relatively long.
overallTimeout = 90 * time.Minute
usernamePrompt = "Username: "
passwordPrompt = "Password: "
// For CLI-based auth, such as with LDAP upstream identity providers, the user may use these environment variables
// to avoid getting interactively prompted for username and password.
defaultUsernameEnvVarName = "PINNIPED_USERNAME"
defaultPasswordEnvVarName = "PINNIPED_PASSWORD" //nolint:gosec // this is not a credential
httpLocationHeaderName = "Location"
)
// stdin returns the file descriptor for stdin as an int.
func stdin() int {
//nolint:gosec // casting like this is the documented way to pass file descriptors to the term package
return int(os.Stdin.Fd())
}
type handlerState struct {
// Basic parameters.
ctx context.Context
logger Logger
issuer string
clientID string
scopes []string
cache SessionCache
out io.Writer // this is stderr except in unit tests
loggerOptionsCount int
// Tracking the usage of some other functional options.
upstreamIdentityProviderName string
upstreamIdentityProviderType idpdiscoveryv1alpha1.IDPType
cliToSendCredentials bool
loginFlow idpdiscoveryv1alpha1.IDPFlow
skipBrowser bool
skipPrintLoginURL bool
requestedAudience string
httpClient *http.Client
requireIDTokenOnRefresh bool
// Parameters of the localhost listener.
listenAddr string
callbackPath string
// Generated parameters of a login flow.
provider *coreosoidc.Provider
idpDiscovery *idpdiscoveryv1alpha1.IDPDiscoveryResponse
oauth2Config *oauth2.Config
useFormPost bool
state state.State
nonce nonce.Nonce
pkce pkce.Code
// External calls for things.
generateState func() (state.State, error)
generatePKCE func() (pkce.Code, error)
generateNonce func() (nonce.Nonce, error)
openURL func(string) error
getEnv func(key string) string
listen func(string, string) (net.Listener, error)
stdinIsTTY func() bool
getProvider func(*oauth2.Config, *coreosoidc.Provider, *http.Client) upstreamprovider.UpstreamOIDCIdentityProviderI
validateIDToken func(ctx context.Context, provider *coreosoidc.Provider, audience string, token string) (*coreosoidc.IDToken, error)
promptForValue func(ctx context.Context, promptLabel string, out io.Writer) (string, error)
promptForSecret func(promptLabel string, out io.Writer) (string, error)
callbacks chan callbackResult
}
type callbackResult struct {
token *oidctypes.Token
err error
}
// Option is an optional configuration for Login().
type Option func(*handlerState) error
// WithContext specifies a specific context.Context under which to perform the login. If this option is not specified,
// login happens under context.Background().
func WithContext(ctx context.Context) Option {
return func(h *handlerState) error {
h.ctx = ctx
return nil
}
}
type Logger interface {
Error(msg string, err error, keysAndValues ...any)
Info(msg string, keysAndValues ...any)
}
type logrLoggerWrapper struct {
logger logr.Logger
}
var _ Logger = (*logrLoggerWrapper)(nil)
func (l *logrLoggerWrapper) Error(msg string, err error, keysAndValues ...any) {
l.logger.V(plog.KlogLevelDebug).Error(err, msg, keysAndValues...)
}
func (l *logrLoggerWrapper) Info(msg string, keysAndValues ...any) {
l.logger.V(plog.KlogLevelDebug).Info(msg, keysAndValues...)
}
type emptyLogger struct{}
var _ Logger = (*emptyLogger)(nil)
func (e emptyLogger) Error(_ string, _ error, _ ...any) {
// NOOP
}
func (e emptyLogger) Info(_ string, _ ...any) {
// NOOP
}
// WithLogger specifies a PLogger to use with the login.
// If not specified this will default to a no-op logger.
//
// Deprecated: Use WithLoginLogger instead.
// This option will be removed in a future version of Pinniped.
// If this option is used along with WithLoginLogger, it will cause an error.
func WithLogger(logger logr.Logger) Option {
return func(h *handlerState) error {
h.logger = &logrLoggerWrapper{logger: logger}
h.loggerOptionsCount++
return nil
}
}
// WithLoginLogger specifies a Logger to use.
// If not specified this will default to a no-op logger.
func WithLoginLogger(logger Logger) Option {
return func(h *handlerState) error {
h.logger = logger
h.loggerOptionsCount++
return nil
}
}
// WithListenPort specifies a TCP listen port on localhost, which will be used for the redirect_uri and to handle the
// authorization code callback. By default, a random high port will be chosen which requires the authorization server
// to support wildcard port numbers as described by https://tools.ietf.org/html/rfc8252#section-7.3:
//
// The authorization server MUST allow any port to be specified at the
// time of the request for loopback IP redirect URIs, to accommodate
// clients that obtain an available ephemeral port from the operating
// system at the time of the request.
func WithListenPort(port uint16) Option {
return func(h *handlerState) error {
h.listenAddr = net.JoinHostPort("localhost", fmt.Sprint(port))
return nil
}
}
// WithScopes sets the OAuth2 scopes to request during login. If not specified, it defaults to
// "offline_access openid email profile".
func WithScopes(scopes []string) Option {
return func(h *handlerState) error {
h.scopes = scopes
return nil
}
}
// WithSkipBrowserOpen causes the login to only print the authorize URL, but skips attempting to
// open the user's default web browser.
func WithSkipBrowserOpen() Option {
return func(h *handlerState) error {
h.skipBrowser = true
return nil
}
}
// WithSkipListen causes the login to skip starting the localhost listener, forcing the manual copy/paste login flow.
func WithSkipListen() Option {
return func(h *handlerState) error {
h.listen = func(string, string) (net.Listener, error) { return nil, nil }
return nil
}
}
// WithSkipPrintLoginURL causes the login to skip printing the login URL when the browser opens to that URL.
func WithSkipPrintLoginURL() Option {
return func(h *handlerState) error {
h.skipPrintLoginURL = true
return nil
}
}
// SessionCacheKey contains the data used to select a valid session cache entry.
type SessionCacheKey struct {
Issuer string `json:"issuer"`
ClientID string `json:"clientID"`
Scopes []string `json:"scopes"`
RedirectURI string `json:"redirect_uri"`
UpstreamProviderName string `json:"upstream_provider_name,omitempty"`
}
type SessionCache interface {
GetToken(SessionCacheKey) *oidctypes.Token
PutToken(SessionCacheKey, *oidctypes.Token)
}
// WithSessionCache sets the session cache backend for storing and retrieving previously-issued ID tokens and refresh tokens.
func WithSessionCache(cache SessionCache) Option {
return func(h *handlerState) error {
h.cache = cache
return nil
}
}
// WithClient sets the HTTP client used to make CLI-to-provider requests.
func WithClient(httpClient *http.Client) Option {
return func(h *handlerState) error {
h.httpClient = httpClient
return nil
}
}
// WithRequestAudience causes the login flow to perform an additional token exchange using the RFC8693 flow.
func WithRequestAudience(audience string) Option {
return func(h *handlerState) error {
h.requestedAudience = audience
return nil
}
}
// WithRequireIDTokenOnRefresh controls whether the refresh token flow requires the provider to return an id_token.
// Set to false for providers that omit id_token in their refresh response.
// Defaults to true for backward compatibility.
func WithRequireIDTokenOnRefresh(require bool) Option {
return func(h *handlerState) error {
h.requireIDTokenOnRefresh = require
return nil
}
}
// WithCLISendingCredentials causes the login flow to use CLI-based prompts for username and password and causes the
// call to the Issuer's authorize endpoint to be made directly (no web browser) with the username and password on custom
// HTTP headers. This is only intended to be used when the issuer is a Pinniped Supervisor and the upstream identity
// provider type supports this style of authentication. Currently, this is supported by LDAPIdentityProviders, ActiveDirectoryIdentityProviders,
// and by OIDCIdentityProviders which optionally enable the resource owner password credentials grant flow.
// This should never be used with non-Supervisor issuers because it will send the user's password to the authorization
// endpoint as a custom header, which would be ignored but could potentially get logged somewhere by the issuer.
//
// Deprecated: this option will be removed in a future version of Pinniped. See the WithLoginFlow() option instead.
// If this option is used along with the WithLoginFlow() option, it will cause an error.
func WithCLISendingCredentials() Option {
return func(h *handlerState) error {
h.cliToSendCredentials = true
return nil
}
}
// WithLoginFlow chooses the login flow.
// When the argument is equal to idpdiscoveryv1alpha1.IDPFlowCLIPassword, it causes the login flow to use CLI-based
// prompts for username and password and causes the call to the Issuer's authorize endpoint to be made directly (no web
// browser) with the username and password on custom HTTP headers. This is only intended to be used when the issuer is a
// Pinniped Supervisor and the upstream identity provider type supports this style of authentication. Currently, this is
// supported by LDAPIdentityProviders, ActiveDirectoryIdentityProviders, and by OIDCIdentityProviders which optionally
// enable the resource owner password credentials grant flow. This should never be used with non-Supervisor issuers
// because it will send the user's password to the authorization endpoint as a custom header, which would be ignored but
// could potentially get logged somewhere by the issuer.
// When the argument is equal to idpdiscoveryv1alpha1.IDPFlowBrowserAuthcode, it will attempt to open a web browser
// and perform the OIDC authcode flow.
// When not used, the default when the issuer is a Pinniped Supervisor will be determined automatically,
// and the default for non-Supervisor issuers will be the browser authcode flow.
func WithLoginFlow(loginFlow idpdiscoveryv1alpha1.IDPFlow, flowSource string) Option {
return func(h *handlerState) error {
switch loginFlow {
case idpdiscoveryv1alpha1.IDPFlowCLIPassword,
idpdiscoveryv1alpha1.IDPFlowBrowserAuthcode:
default:
return fmt.Errorf(
"WithLoginFlow error: loginFlow '%s' from '%s' must be '%s' or '%s'",
loginFlow,
flowSource,
idpdiscoveryv1alpha1.IDPFlowCLIPassword,
idpdiscoveryv1alpha1.IDPFlowBrowserAuthcode,
)
}
h.loginFlow = loginFlow
return nil
}
}
// WithUpstreamIdentityProvider causes the specified name and type to be sent as custom query parameters to the
// issuer's authorize endpoint. This is only intended to be used when the issuer is a Pinniped Supervisor, in which
// case it provides a mechanism to choose among several upstream identity providers.
// Other issuers will ignore these custom query parameters.
func WithUpstreamIdentityProvider(upstreamName, upstreamType string) Option {
return func(h *handlerState) error {
h.upstreamIdentityProviderName = upstreamName
// Do not perform validation on this cast.
// If possible, dynamic validation against a Pinniped Supervisor's supported IDP types will be performed.
h.upstreamIdentityProviderType = idpdiscoveryv1alpha1.IDPType(upstreamType)
return nil
}
}
// nopCache is a SessionCache that doesn't actually do anything.
type nopCache struct{}
func (*nopCache) GetToken(SessionCacheKey) *oidctypes.Token { return nil }
func (*nopCache) PutToken(SessionCacheKey, *oidctypes.Token) {}
type auditIDLoggerFunc func(path string, statusCode int, auditID string)
func logFailedRequest(path string, statusCode int, auditID string) {
plog.Info("Received auditID for failed request",
"path", path,
"statusCode", statusCode,
"auditID", auditID)
}
// maybePrintAuditID will choose to log the auditID when certain failure cases are detected,
// to give a breadcrumb for an admin to follow.
// Older Supervisors and other OIDC identity providers may not provide this header.
func maybePrintAuditID(rt http.RoundTripper, logFunc auditIDLoggerFunc) http.RoundTripper {
return roundtripper.WrapFunc(rt, func(r *http.Request) (*http.Response, error) {
response, responseErr := rt.RoundTrip(r)
if response == nil ||
responseErr != nil ||
response.Header.Get("audit-ID") == "" ||
response.Request == nil ||
response.Request.URL == nil {
return response, responseErr
}
auditID := response.Header.Get("audit-ID")
// Use the request from the response in case other round-trippers modified the request
path := response.Request.URL.Path
switch statusCode := response.StatusCode; {
case statusCode < http.StatusMultipleChoices: // (-inf,300)
break // noop
case response.StatusCode < http.StatusBadRequest: // [300,400)
// Rejected oauth2/authorize redirects from audit-enabled Supervisors will ALWAYS include
// the "error" parameter since it is required.
// See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1 for more details.
location, err := url.Parse(response.Header.Get(httpLocationHeaderName))
if err != nil || location == nil || location.Query().Get("error") == "" {
break
}
logFunc(path, statusCode, auditID)
default: // [400,inf)
// failing discovery, oauth2/authorize, or oauth2/token responses from audit-enabled Supervisors.
logFunc(path, statusCode, auditID)
}
return response, responseErr
})
}
// Login performs an OAuth2/OIDC authorization code login using a localhost listener.
func Login(issuer string, clientID string, opts ...Option) (*oidctypes.Token, error) {
h := handlerState{
issuer: issuer,
clientID: clientID,
listenAddr: "localhost:0",
scopes: []string{oidcapi.ScopeOfflineAccess, oidcapi.ScopeOpenID, oidcapi.ScopeEmail, oidcapi.ScopeProfile},
cache: &nopCache{},
callbackPath: "/callback",
ctx: context.Background(),
logger: &emptyLogger{},
callbacks: make(chan callbackResult, 2),
httpClient: phttp.Default(nil),
requireIDTokenOnRefresh: true,
// Default implementations of external dependencies (to be mocked in tests).
generateState: state.Generate,
generateNonce: nonce.Generate,
generatePKCE: pkce.Generate,
openURL: browser.OpenURL,
getEnv: os.Getenv,
listen: net.Listen,
stdinIsTTY: func() bool { return term.IsTerminal(stdin()) },
getProvider: func(config *oauth2.Config, provider *coreosoidc.Provider, client *http.Client) upstreamprovider.UpstreamOIDCIdentityProviderI {
// can't use upstreamoidc.New here since it does not set the Name
return &upstreamoidc.ProviderConfig{
Name: issuer, // use the issuer as the Name
Config: config,
Provider: provider,
Client: client,
}
},
validateIDToken: func(ctx context.Context, provider *coreosoidc.Provider, audience string, token string) (*coreosoidc.IDToken, error) {
return provider.Verifier(&coreosoidc.Config{ClientID: audience}).Verify(ctx, token)
},
promptForValue: promptForValue,
promptForSecret: promptForSecret,
out: os.Stderr,
}
for _, opt := range opts {
if err := opt(&h); err != nil {
return nil, err
}
}
h.httpClient.Transport = maybePrintAuditID(h.httpClient.Transport, logFailedRequest)
if h.cliToSendCredentials {
if h.loginFlow != "" {
return nil, fmt.Errorf("do not use deprecated option WithCLISendingCredentials when using option WithLoginFlow")
}
h.loginFlow = idpdiscoveryv1alpha1.IDPFlowCLIPassword
}
if h.loggerOptionsCount > 1 {
return nil, fmt.Errorf("please use only one mechanism to specify the logger")
}
// Copy the configured HTTP client to set a request timeout (the Go default client has no timeout configured).
httpClientWithTimeout := *h.httpClient
httpClientWithTimeout.Timeout = httpRequestTimeout
h.httpClient = &httpClientWithTimeout
// Always set a long, but non-infinite timeout for this operation.
ctx, cancel := context.WithTimeout(h.ctx, overallTimeout)
defer cancel()
ctx = coreosoidc.ClientContext(ctx, h.httpClient)
h.ctx = ctx
// Initialize login parameters.
var err error
h.state, err = h.generateState()
if err != nil {
return nil, err
}
h.nonce, err = h.generateNonce()
if err != nil {
return nil, err
}
h.pkce, err = h.generatePKCE()
if err != nil {
return nil, err
}
// Do the basic login to get an access and ID token issued to our main client ID.
token, err := h.baseLogin()
if err != nil {
return nil, err
}
// Perform the RFC8693 token exchange, if needed. Note that the new ID token returned by this exchange
// does not need to be cached because the new ID token is intended to be a very short-lived token.
if h.needRFC8693TokenExchange(token) {
token, err = h.tokenExchangeRFC8693(token)
if err != nil {
return nil, fmt.Errorf("failed to exchange token: %w", err)
}
}
return token, nil
}
func (h *handlerState) needRFC8693TokenExchange(token *oidctypes.Token) bool {
// Need a new ID token if there is a requested audience value and any of the following are true...
return h.requestedAudience != "" &&
// we don't have an ID token (maybe it expired or was otherwise removed from the session cache)
(token.IDToken == nil ||
// or, our current ID token has a different audience
h.requestedAudience != token.IDToken.Claims["aud"])
}
func (h *handlerState) tokenValidForNearFuture(token *oidctypes.Token) (bool, string) {
if token == nil {
return false, ""
}
// If we plan to do an RFC8693 token exchange, then we need an access token that will still be valid when we do the
// exchange (which will happen momentarily). Otherwise, we need an ID token that will be valid for a little while
// (long enough for multistep k8s API operations).
if h.needRFC8693TokenExchange(token) {
return !accessTokenExpiredOrCloseToExpiring(token.AccessToken), "access_token"
}
return !idTokenExpiredOrCloseToExpiring(token.IDToken), "id_token"
}
func accessTokenExpiredOrCloseToExpiring(accessToken *oidctypes.AccessToken) bool {
return accessToken == nil || time.Until(accessToken.Expiry.Time) <= minAccessTokenValidity
}
func idTokenExpiredOrCloseToExpiring(idToken *oidctypes.IDToken) bool {
return idToken == nil || time.Until(idToken.Expiry.Time) <= minIDTokenValidity
}
func (h *handlerState) baseLogin() (*oidctypes.Token, error) {
// Check the cache for a previous session issued with the same parameters.
sort.Strings(h.scopes)
cacheKey := SessionCacheKey{
Issuer: h.issuer,
ClientID: h.clientID,
Scopes: h.scopes,
RedirectURI: (&url.URL{Scheme: "http", Host: h.listenAddr, Path: h.callbackPath}).String(),
// When using a Supervisor with multiple IDPs, the cache keys need to be different for each IDP
// so a user can have multiple sessions going for each IDP at the same time.
// When using a non-Supervisor OIDC provider, then this value will be blank, so it won't be part of the key.
UpstreamProviderName: h.upstreamIdentityProviderName,
}
// If the cached tokens include the token type that we need, and that token is still valid for a bit,
// return the cached tokens immediately and skip the rest of the flow.
cached := h.cache.GetToken(cacheKey)
if valid, whichTokenWasValid := h.tokenValidForNearFuture(cached); valid {
h.logger.Info("Pinniped: Found unexpired cached token.", "type", whichTokenWasValid)
return cached, nil
}
// Perform OIDC discovery.
if err := h.initOIDCDiscovery(); err != nil {
return nil, err
}
// If there was a cached refresh token, attempt to use the refresh flow instead of a fresh login.
if cached != nil && cached.RefreshToken != nil && cached.RefreshToken.Token != "" {
freshToken, err := h.handleRefresh(h.ctx, cached.RefreshToken)
if err != nil {
return nil, err
}
// If we got a fresh token, update the cache and return it. Otherwise, fall through to the full login flow.
if freshToken != nil {
h.cache.PutToken(cacheKey, freshToken)
return freshToken, nil
}
}
// We couldn't refresh, so now we need to perform a fresh login attempt.
// Prepare the common options for the authorization URL. We don't have the redirect URL yet though.
authorizeOptions := []oauth2.AuthCodeOption{
oauth2.AccessTypeOffline,
h.nonce.Param(),
h.pkce.Challenge(),
h.pkce.Method(),
}
loginFlow, pinnipedSupervisorOptions, err := h.maybePerformPinnipedSupervisorValidations()
if err != nil {
return nil, err
}
h.loginFlow = loginFlow
authorizeOptions = slices.Concat(authorizeOptions, pinnipedSupervisorOptions)
// Preserve the legacy behavior where browser-based auth is preferred
authFunc := h.webBrowserBasedAuth
// Choose the appropriate authorization and authcode exchange strategy.
// Use a switch so that lint will make sure we have full coverage.
switch h.loginFlow {
case idpdiscoveryv1alpha1.IDPFlowCLIPassword:
authFunc = h.cliBasedAuth
case idpdiscoveryv1alpha1.IDPFlowBrowserAuthcode:
// NOOP
}
// Perform the authorize request and authcode exchange to get back OIDC tokens.
token, err := authFunc(&authorizeOptions)
// If we got tokens, put them in the cache.
if err == nil {
h.cache.PutToken(cacheKey, token)
}
return token, err
}
// maybePerformPinnipedSupervisorValidations will return the flow and some authorization options.
// When the IDP name is unset, it will assume that the server is not a Pinniped Supervisor, and will return immediately.
// Otherwise, when the flow is unset, it will infer the flow from the server, or when the flow is set, it will return that flow unchanged.
// It will also perform additional validations if the issuer is a Pinniped Supervisor.
func (h *handlerState) maybePerformPinnipedSupervisorValidations() (idpdiscoveryv1alpha1.IDPFlow, []oauth2.AuthCodeOption, error) {
loginFlow := h.loginFlow
if h.upstreamIdentityProviderName == "" {
return loginFlow, nil, nil
}
if h.idpDiscovery == nil {
return "", nil, fmt.Errorf("upstream identity provider name %q was specified, but OIDC issuer %q does not "+
"offer Pinniped-style IDP discovery, so it does not appear to be a Pinniped Supervisor; "+
"specifying an upstream identity provider name is only meant to be used with Pinniped Supervisors",
h.upstreamIdentityProviderName, h.issuer)
}
// Legacy Pinniped Supervisors do not provide this information. Only run this validation when the information was provided.
if len(h.idpDiscovery.PinnipedSupportedIDPTypes) > 0 {
var supportedIDPTypes []idpdiscoveryv1alpha1.IDPType
for _, idpType := range h.idpDiscovery.PinnipedSupportedIDPTypes {
supportedIDPTypes = append(supportedIDPTypes, idpType.Type)
}
// Sort by name for repeatability
slices.Sort(supportedIDPTypes)
if !slices.Contains(supportedIDPTypes, h.upstreamIdentityProviderType) {
convertIDPListToQuotedStringList := func() []string {
temp := make([]string, 0, len(supportedIDPTypes))
for _, idpType := range supportedIDPTypes {
temp = append(temp, fmt.Sprintf("%q", idpType))
}
return temp
}
return "", nil, fmt.Errorf("unable to find upstream identity provider with type %q, this Pinniped Supervisor supports IDP types [%s]",
h.upstreamIdentityProviderType,
strings.Join(convertIDPListToQuotedStringList(), ", "))
}
}
// Find the IDP from discovery by the specified name, type, and maybe flow.
foundIDPIndex := slices.IndexFunc(h.idpDiscovery.PinnipedIDPs, func(idp idpdiscoveryv1alpha1.PinnipedIDP) bool {
return idp.Name == h.upstreamIdentityProviderName &&
idp.Type == h.upstreamIdentityProviderType &&
(loginFlow == "" || slices.Contains(idp.Flows, loginFlow))
})
// If the IDP was not found...
if foundIDPIndex < 0 {
pinnipedIDPsString, err := json.Marshal(h.idpDiscovery.PinnipedIDPs)
if err != nil {
// This should never happen. Not unit tested.
return "", nil, fmt.Errorf("error marshalling IDP discovery response: %w", err)
}
if loginFlow == "" {
return "", nil, fmt.Errorf(
"unable to find upstream identity provider with name %q and type %q. Found these providers: %s",
h.upstreamIdentityProviderName,
h.upstreamIdentityProviderType,
pinnipedIDPsString,
)
}
return "", nil, fmt.Errorf(
"unable to find upstream identity provider with name %q and type %q and flow %q. Found these providers: %s",
h.upstreamIdentityProviderName,
h.upstreamIdentityProviderType,
loginFlow,
pinnipedIDPsString,
)
}
// If the caller has not requested a specific flow, but has requested a specific IDP, infer the authentication flow
// from the found IDP's discovery information.
if loginFlow == "" {
foundIDP := h.idpDiscovery.PinnipedIDPs[foundIDPIndex]
if len(foundIDP.Flows) == 0 {
// Note that this should not really happen because the Supervisor's IDP discovery endpoint has always listed flows.
return "", nil, fmt.Errorf("unable to infer flow for upstream identity provider with name %q and type %q "+
"because there were no flows discovered for that provider",
h.upstreamIdentityProviderName,
h.upstreamIdentityProviderType,
)
}
// The order of the flows returned by the server indicates the server's flow preference,
// so always use the first flow for that IDP from the discovery response.
loginFlow = foundIDP.Flows[0]
}
authorizeOptions := make([]oauth2.AuthCodeOption, 0, 2)
authorizeOptions = append(authorizeOptions,
oauth2.SetAuthURLParam(oidcapi.AuthorizeUpstreamIDPNameParamName, h.upstreamIdentityProviderName),
)
authorizeOptions = append(authorizeOptions,
oauth2.SetAuthURLParam(oidcapi.AuthorizeUpstreamIDPTypeParamName, string(h.upstreamIdentityProviderType)),
)
return loginFlow, authorizeOptions, nil
}
// Make a direct call to the authorize endpoint, including the user's username and password on custom http headers,
// and parse the authcode from the response. Exchange the authcode for tokens. Return the tokens or an error.
func (h *handlerState) cliBasedAuth(authorizeOptions *[]oauth2.AuthCodeOption) (*oidctypes.Token, error) {
// Ask the user for their username and password, or get them from env vars.
username, password, err := h.getUsernameAndPassword()
if err != nil {
return nil, err
}
// Make a callback URL even though we won't be listening on this port, because providing a redirect URL is
// required for OIDC authorize endpoints, and it must match the allowed redirect URL of the OIDC client
// registered on the server. The Supervisor oauth client does not have "localhost" in the allowed redirect
// URI list, so use 127.0.0.1.
localhostAddr := strings.ReplaceAll(h.listenAddr, "localhost", "127.0.0.1")
h.oauth2Config.RedirectURL = (&url.URL{
Scheme: "http",
Host: localhostAddr,
Path: h.callbackPath,
}).String()
// Now that we have a redirect URL, we can build the authorize URL.
authorizeURL := h.oauth2Config.AuthCodeURL(h.state.String(), *authorizeOptions...)
// Don't follow redirects automatically because we want to handle redirects here.
var sawRedirect bool
h.httpClient.CheckRedirect = func(_ *http.Request, _via []*http.Request) error {
sawRedirect = true
return http.ErrUseLastResponse
}
// Send an authorize request.
authCtx, authorizeCtxCancelFunc := context.WithTimeout(h.ctx, httpRequestTimeout)
defer authorizeCtxCancelFunc()
authReq, err := http.NewRequestWithContext(authCtx, http.MethodGet, authorizeURL, nil)
if err != nil {
return nil, fmt.Errorf("could not build authorize request: %w", err)
}
authReq.Header.Set(oidcapi.AuthorizeUsernameHeaderName, username)
authReq.Header.Set(oidcapi.AuthorizePasswordHeaderName, password)
authRes, err := h.httpClient.Do(authReq)
if err != nil {
return nil, fmt.Errorf("authorization response error: %w", err)
}
_ = authRes.Body.Close() // don't need the response body, and okay if it fails to close
// A successful authorization always results in a redirect (we are flexible on the exact status code).
if !sawRedirect {
return nil, fmt.Errorf(
"error getting authorization: expected to be redirected, but response status was %s", authRes.Status)
}
rawLocation := authRes.Header.Get(httpLocationHeaderName)
location, err := url.Parse(rawLocation)
if err != nil {
// This shouldn't be possible in practice because httpClient.Do() already parses the Location header.
return nil, fmt.Errorf("error getting authorization: could not parse redirect location: %w", err)
}
// Check that the redirect was to the expected location.
if location.Scheme != "http" || location.Host != localhostAddr || location.Path != h.callbackPath {
return nil, fmt.Errorf("error getting authorization: redirected to the wrong location: %s", rawLocation)
}
// Validate OAuth2 state and fail if it's incorrect (to block CSRF).
if err := h.state.Validate(location.Query().Get("state")); err != nil {
return nil, fmt.Errorf("missing or invalid state parameter in authorization response: %s", rawLocation)
}
// Get the auth code or return the error from the server.
authCode := location.Query().Get("code")
if authCode == "" {
// Check for error response parameters. See https://openid.net/specs/openid-connect-core-1_0.html#AuthError.
requiredErrorCode := location.Query().Get("error")
optionalErrorDescription := location.Query().Get("error_description")
if optionalErrorDescription == "" {
return nil, fmt.Errorf("login failed with code %q", requiredErrorCode)
}
return nil, fmt.Errorf("login failed with code %q: %s", requiredErrorCode, optionalErrorDescription)
}
// Exchange the authorization code for access, ID, and refresh tokens and perform required
// validations on the returned ID token.
tokenCtx, tokenCtxCancelFunc := context.WithTimeout(h.ctx, httpRequestTimeout)
defer tokenCtxCancelFunc()
token, err := h.redeemAuthCode(tokenCtx, authCode)
if err != nil {
return nil, fmt.Errorf("could not complete authorization code exchange: %w", err)
}
return token, nil
}
// Prompt for the user's username and password, or read them from env vars if they are available.
func (h *handlerState) getUsernameAndPassword() (string, string, error) {
var err error
if h.upstreamIdentityProviderName != "" {
_, _ = fmt.Fprintf(h.out, "\nLog in to %s\n\n", h.upstreamIdentityProviderName)
}
username := h.getEnv(defaultUsernameEnvVarName)
if username == "" {
username, err = h.promptForValue(h.ctx, usernamePrompt, h.out)
if err != nil {
return "", "", fmt.Errorf("error prompting for username: %w", err)
}
} else {
h.logger.Info("Pinniped: Read username from environment variable", "name", defaultUsernameEnvVarName)
}
password := h.getEnv(defaultPasswordEnvVarName)
if password == "" {
password, err = h.promptForSecret(passwordPrompt, h.out)
if err != nil {
return "", "", fmt.Errorf("error prompting for password: %w", err)
}
} else {
h.logger.Info("Pinniped: Read password from environment variable", "name", defaultPasswordEnvVarName)
}
return username, password, nil
}
// Open a web browser, or ask the user to open a web browser, to visit the authorize endpoint.
// Create a localhost callback listener which exchanges the authcode for tokens. Return the tokens or an error.
func (h *handlerState) webBrowserBasedAuth(authorizeOptions *[]oauth2.AuthCodeOption) (*oidctypes.Token, error) {
// Attempt to open a local TCP listener, logging but otherwise ignoring any error.
listener, err := h.listen("tcp", h.listenAddr)
if err != nil {
h.logger.Error("could not open callback listener", err)
}
// If the listener failed to start and stdin is not a TTY, then we have no hope of succeeding,
// since we won't be able to receive the web callback and we can't prompt for the manual auth code.
if listener == nil && !h.stdinIsTTY() {
return nil, fmt.Errorf("login failed: must have either a localhost listener or stdin must be a TTY")
}
// Update the OAuth2 redirect_uri to match the actual listener address (if there is one), or just use
// a fake ":0" port if there is no listener running.
redirectURI := url.URL{Scheme: "http", Path: h.callbackPath}
if listener == nil {
redirectURI.Host = "127.0.0.1:0"
} else {
redirectURI.Host = listener.Addr().String()
}
h.oauth2Config.RedirectURL = redirectURI.String()
// If the server supports it, request response_mode=form_post.
authParams := *authorizeOptions
if h.useFormPost {
authParams = append(authParams, oauth2.SetAuthURLParam("response_mode", "form_post"))
}
// Now that we have a redirect URL with the listener port, we can build the authorize URL.
authorizeURL := h.oauth2Config.AuthCodeURL(h.state.String(), authParams...)
// If there is a listener running, start serving the callback handler in a background goroutine.
if listener != nil {
shutdown := h.serve(listener)
defer shutdown()
}
// Open the authorize URL in the users browser, logging but otherwise ignoring any error.
// Keep track of whether the browser was opened.
openedBrowser := false
if !h.skipBrowser {
if err := h.openURL(authorizeURL); err != nil {
h.logger.Error("could not open browser", err)
} else {
openedBrowser = true
}
}
// Allow optionally skipping printing the login URL, for example because printing it may confuse
// a console-based UI program like k9s which invoked this. If the browser was opened, the browser
// already has the URL. If the browser did not open, then the user has no way to login without the URL,
// so print it anyway, even though it may confuse apps like k9s.
printAuthorizeURL := !openedBrowser || !h.skipPrintLoginURL
// Prompt the user to visit the authorize URL, and to paste a manually-copied auth code (if possible).
ctx, cancel := context.WithCancel(h.ctx)
cleanupPrompt := h.promptForWebLogin(ctx, authorizeURL, printAuthorizeURL)
defer func() {
cancel()
cleanupPrompt()
}()
// Wait for either the web callback, a pasted auth code, or a timeout.
select {
case <-h.ctx.Done():
return nil, fmt.Errorf("timed out waiting for token callback: %w", h.ctx.Err())
case callback := <-h.callbacks:
if callback.err != nil {
return nil, fmt.Errorf("error handling callback: %w", callback.err)
}
return callback.token, nil
}
}
// promptForWebLogin prints a login URL to the screen, if needed. It will also print the "paste yor authorization code"
// prompt to the screen and wait for user input, if needed. It can be cancelled by the context provided.
// It returns a function which should be invoked by the caller to perform some cleanup.
func (h *handlerState) promptForWebLogin(ctx context.Context, authorizeURL string, printAuthorizeURL bool) func() {
if !printAuthorizeURL {
return func() {}
}
_, _ = fmt.Fprintf(h.out, "Log in by visiting this link:\n\n %s\n\n", authorizeURL)
// If stdin is not a TTY, don't prompt for the manual paste, since we have no way of reading it.
if !h.stdinIsTTY() {
return func() {}
}
// If the server didn't support response_mode=form_post, don't bother prompting for the manual
// code because the user isn't going to have any easy way to manually copy it anyway.
if !h.useFormPost {
return func() {}
}
// Launch the manual auth code prompt in a background goroutine, which will be cancelled
// if the parent context is cancelled (when the login succeeds or times out).
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer func() {
// Always emit a newline so the kubectl output is visually separated from the login prompts.
_, _ = fmt.Fprintln(h.out)
wg.Done()
}()
code, err := h.promptForValue(ctx, " Optionally, paste your authorization code: ", h.out)
if err != nil {
// Print a visual marker to show the the prompt is no longer waiting for user input, plus a trailing
// newline that simulates the user having pressed "enter".
_, _ = fmt.Fprint(h.out, "[...]\n")
h.callbacks <- callbackResult{err: fmt.Errorf("failed to prompt for manual authorization code: %v", err)}
return
}
// When a code is pasted, redeem it for a token and return the results on the callback channel.
token, err := h.redeemAuthCode(ctx, code)
h.callbacks <- callbackResult{token: token, err: err}
}()
return wg.Wait
}
// promptForValue interactively prompts the user for a plaintext value and reads their input.
// If the context is canceled, it will return an error immediately.
// This can be replaced by a mock implementation for unit tests.
func promptForValue(ctx context.Context, promptLabel string, out io.Writer) (string, error) {
if !term.IsTerminal(stdin()) {
return "", errors.New("stdin is not connected to a terminal")
}
_, err := fmt.Fprint(out, promptLabel)
if err != nil {
return "", fmt.Errorf("could not print prompt to stderr: %w", err)
}
type readResult struct {
text string
err error
}
readResults := make(chan readResult)
go func() {