Debian Codegraph @

command/oauth/cmd.go

raw symbols SCIP
1 package oauth
2
3 import (
4 "crypto/sha256"
5 "crypto/x509"
6 "encoding/base64"
7 "encoding/json"
8 "encoding/pem"
9 "fmt"
10 "io/ioutil"
11 "net"
12 "net/http"
13 "net/http/httptest"
14 "net/url"
15 "os"
16 "path"
17 "strconv"
18 "strings"
19 "time"
20
21 "github.com/pkg/errors"
22 "github.com/smallstep/cli/command"
23 "github.com/smallstep/cli/crypto/randutil"
24 "github.com/smallstep/cli/errs"
25 "github.com/smallstep/cli/exec"
26 "github.com/smallstep/cli/flags"
27 "github.com/smallstep/cli/jose"
28 "github.com/smallstep/cli/utils"
29 "github.com/urfave/cli"
30 )
31
32 // These are the OAuth2.0 client IDs from the Step CLI. This application is
33 // using the OAuth2.0 flow for installed applications described on
34 // https://developers.google.com/identity/protocols/OAuth2InstalledApp
35 //
36 // The Step CLI app and these client IDs do not have any APIs or services are
37 // enabled and it should be only used for OAuth 2.0 authorization.
38 //
39 // Due to the fact that the app cannot keep the client_secret confidential,
40 // incremental authorization with installed apps are not supported by Google.
41 //
42 // Google is also distributing the client ID and secret on the cloud SDK
43 // available here https://cloud.google.com/sdk/docs/quickstarts
44 const (
45 defaultClientID = "1087160488420-8qt7bavg3qesdhs6it824mhnfgcfe8il.apps.googleusercontent.com"
46 defaultClientNotSoSecret = "udTrOT3gzrO7W9fDPgZQLfYJ"
47
48 // The URN for getting verification token offline
49 oobCallbackUrn = "urn:ietf:wg:oauth:2.0:oob"
50 // The URN for token request grant type jwt-bearer
51 jwtBearerUrn = "urn:ietf:params:oauth:grant-type:jwt-bearer"
52 )
53
54 type token struct {
55 AccessToken string `json:"access_token"`
56 IDToken string `json:"id_token"`
57 RefreshToken string `json:"refresh_token"`
58 ExpiresIn int `json:"expires_in"`
59 TokenType string `json:"token_type"`
60 Err string `json:"error,omitempty"`
61 ErrDesc string `json:"error_description,omitempty"`
62 }
63
64 func init() {
65 cmd := cli.Command{
66 Name: "oauth",
67 Usage: "authorization and single sign-on using OAuth & OIDC",
68 UsageText: `**step oauth**
69 [**--provider**=<provider>] [**--client-id**=<client-id> **--client-secret**=<client-secret>]
70 [**--scope**=<scope> ...] [**--bare** [**--oidc**]] [**--header** [**--oidc**]] [**--prompt**=<prompt>]
71
72 **step oauth**
73 **--authorization-endpoint**=<authorization-endpoint>
74 **--token-endpoint**=<token-endpoint>
75 **--client-id**=<client-id> **--client-secret**=<client-secret>
76 [**--scope**=<scope> ...] [**--bare** [**--oidc**]] [**--header** [**--oidc**]] [**--prompt**=<prompt>]
77
78 **step oauth** [**--account**=<account>]
79 [**--authorization-endpoint**=<authorization-endpoint>]
80 [**--token-endpoint**=<token-endpoint>]
81 [**--scope**=<scope> ...] [**--bare** [**--oidc**]] [**--header** [**--oidc**]] [**--prompt**=<prompt>]
82
83 **step oauth** **--account**=<account> **--jwt**
84 [**--scope**=<scope> ...] [**--header**] [**-bare**] [**--prompt**=<prompt>]`,
85 Description: `**step oauth** command implements the OAuth 2.0 authorization flow.
86
87 OAuth is an open standard for access delegation, commonly used as a way for
88 Internet users to grant websites or applications access to their information on
89 other websites but without giving them the passwords. This mechanism is used by
90 companies such as Amazon, Google, Facebook, Microsoft and Twitter to permit the
91 users to share information about their accounts with third party applications or
92 websites. Learn more at https://en.wikipedia.org/wiki/OAuth.
93
94 This command by default performs he authorization flow with a preconfigured
95 Google application, but a custom one can be set combining the flags
96 **--client-id**, **--client-secret**, and **--provider**. The provider value
97 must be set to the OIDC discovery document (.well-known/openid-configuration)
98 endpoint. If Google is used this flag is not necessary, but the appropriate
99 value would be be https://accounts.google.com or
100 https://accounts.google.com/.well-known/openid-configuration
101
102 ## EXAMPLES
103
104 Do the OAuth 2.0 flow using the default client:
105 '''
106 $ step oauth
107 '''
108
109 Redirect to localhost instead of 127.0.0.1:
110 '''
111 $ step oauth --listen localhost:0
112 '''
113
114 Redirect to a fixed port instead of random one:
115 '''
116 $ step oauth --listen :10000
117 '''
118
119 Get just the access token:
120 '''
121 $ step oauth --bare
122 '''
123
124 Get just the OIDC token:
125 '''
126 $ step oauth --oidc --bare
127 '''
128
129 Use a custom OAuth2.0 server:
130 '''
131 $ step oauth --client-id my-client-id --client-secret my-client-secret \
132 --provider https://example.org
133 '''`,
134 Flags: []cli.Flag{
135 cli.StringFlag{
136 Name: "provider, idp",
137 Usage: "OAuth provider for authentication",
138 Value: "google",
139 },
140 cli.StringFlag{
141 Name: "email, e",
142 Usage: "Email to authenticate",
143 },
144 cli.BoolFlag{
145 Name: "console, c",
146 Usage: "Complete the flow while remaining only inside the terminal",
147 },
148 cli.StringFlag{
149 Name: "client-id",
150 Usage: "OAuth Client ID",
151 },
152 cli.StringFlag{
153 Name: "client-secret",
154 Usage: "OAuth Client Secret",
155 },
156 cli.StringFlag{
157 Name: "account",
158 Usage: "JSON file containing account details",
159 },
160 cli.StringFlag{
161 Name: "authorization-endpoint",
162 Usage: "OAuth Authorization Endpoint",
163 },
164 cli.StringFlag{
165 Name: "token-endpoint",
166 Usage: "OAuth Token Endpoint",
167 },
168 cli.BoolFlag{
169 Name: "header",
170 Usage: "Output HTTP Authorization Header (suitable for use with curl)",
171 },
172 cli.BoolFlag{
173 Name: "oidc",
174 Usage: "Output OIDC Token instead of OAuth Access Token",
175 },
176 cli.BoolFlag{
177 Name: "bare",
178 Usage: "Only output the token",
179 },
180 cli.StringSliceFlag{
181 Name: "scope",
182 Usage: "OAuth scopes",
183 },
184 cli.StringFlag{
185 Name: "prompt",
186 Usage: `Whether the Authorization Server prompts the End-User for reauthentication and consent.
187 OpenID standard defines the following values, but your provider may support some or none of them:
188
189 **none**
190 : The Authorization Server MUST NOT display any authentication or consent user interface pages.
191 An error is returned if an End-User is not already authenticated or the Client does not have
192 pre-configured consent for the requested Claims or does not fulfill other conditions for
193 processing the request.
194
195 **login**
196 : The Authorization Server SHOULD prompt the End-User for reauthentication. If it cannot
197 reauthenticate the End-User, it MUST return an error, typically login_required.
198
199 **consent**
200 : The Authorization Server SHOULD prompt the End-User for consent before returning information
201 to the Client. If it cannot obtain consent, it MUST return an error, typically consent_required.
202
203 **select_account**
204 : The Authorization Server SHOULD prompt the End-User to select a user account. This enables an
205 End-User who has multiple accounts at the Authorization Server to select amongst the multiple
206 accounts that they might have current sessions for. If it cannot obtain an account selection
207 choice made by the End-User, it MUST return an error, typically account_selection_required.
208 `,
209 },
210 cli.BoolFlag{
211 Name: "jwt",
212 Usage: "Generate a JWT Auth token instead of an OAuth Token (only works with service accounts)",
213 },
214 cli.StringFlag{
215 Name: "listen",
216 Usage: "Callback listener <address> (e.g. \":10000\")",
217 },
218 cli.BoolFlag{
219 Name: "implicit",
220 Usage: "Uses the implicit flow to authenticate the user. Requires **--insecure** and **--client-id** flags.",
221 Hidden: true,
222 },
223 cli.BoolFlag{
224 Name: "insecure",
225 Usage: "Allows the use of insecure flows.",
226 Hidden: true,
227 },
228 cli.StringFlag{
229 Name: "browser",
230 Usage: "Path to browser for OAuth flow (macOS only).",
231 Hidden: true,
232 },
233 flags.RedirectURL,
234 },
235 Action: oauthCmd,
236 }
237
238 command.Register(cmd)
239 }
240
241 func oauthCmd(c *cli.Context) error {
242 opts := &options{
243 Provider: c.String("provider"),
244 Email: c.String("email"),
245 Console: c.Bool("console"),
246 Implicit: c.Bool("implicit"),
247 CallbackListener: c.String("listen"),
248 TerminalRedirect: c.String("redirect-url"),
249 Browser: c.String("browser"),
250 }
251 if err := opts.Validate(); err != nil {
252 return err
253 }
254 if (opts.Provider != "google" || c.IsSet("authorization-endpoint")) && !c.IsSet("client-id") {
255 return errors.New("flag '--client-id' required with '--provider'")
256 }
257
258 var clientID, clientSecret string
259 if opts.Implicit {
260 if !c.Bool("insecure") {
261 return errs.RequiredInsecureFlag(c, "implicit")
262 }
263 if !c.IsSet("client-id") {
264 return errs.RequiredWithFlag(c, "implicit", "client-id")
265 }
266 } else {
267 clientID = defaultClientID
268 clientSecret = defaultClientNotSoSecret
269 }
270 if c.IsSet("client-id") {
271 clientID = c.String("client-id")
272 clientSecret = c.String("client-secret")
273 }
274
275 authzEp := ""
276 tokenEp := ""
277 if c.IsSet("authorization-endpoint") {
278 if !c.IsSet("token-endpoint") {
279 return errors.New("flag '--authorization-endpoint' requires flag '--token-endpoint'")
280 }
281 opts.Provider = ""
282 authzEp = c.String("authorization-endpoint")
283 tokenEp = c.String("token-endpoint")
284 }
285
286 do2lo := false
287 issuer := ""
288 // This code supports Google service accounts. Probably maybe also support JWKs?
289 if c.IsSet("account") {
290 opts.Provider = ""
291 filename := c.String("account")
292 b, err := ioutil.ReadFile(filename)
293 if err != nil {
294 return errors.Wrapf(err, "error reading account from %s", filename)
295 }
296 account := make(map[string]interface{})
297 if err = json.Unmarshal(b, &account); err != nil {
298 return errors.Wrapf(err, "error reading %s: unsupported format", filename)
299 }
300
301 if _, ok := account["installed"]; ok {
302 details := account["installed"].(map[string]interface{})
303 authzEp = details["auth_uri"].(string)
304 tokenEp = details["token_uri"].(string)
305 clientID = details["client_id"].(string)
306 clientSecret = details["client_secret"].(string)
307 } else if accountType, ok := account["type"]; ok && "service_account" == accountType {
308 authzEp = account["auth_uri"].(string)
309 tokenEp = account["token_uri"].(string)
310 clientID = account["private_key_id"].(string)
311 clientSecret = account["private_key"].(string)
312 issuer = account["client_email"].(string)
313 do2lo = true
314 } else {
315 return errors.Wrapf(err, "error reading %s: unsupported account type", filename)
316 }
317 }
318
319 scope := "openid email"
320 if c.IsSet("scope") {
321 scope = strings.Join(c.StringSlice("scope"), " ")
322 }
323 prompt := ""
324 if c.IsSet("prompt") {
325 prompt = c.String("prompt")
326 }
327
328 o, err := newOauth(opts.Provider, clientID, clientSecret, authzEp, tokenEp, scope, prompt, opts)
329 if err != nil {
330 return err
331 }
332
333 var tok *token
334 if do2lo {
335 if c.Bool("jwt") {
336 tok, err = o.DoJWTAuthorization(issuer, scope)
337 } else {
338 tok, err = o.DoTwoLeggedAuthorization(issuer)
339 }
340 } else if opts.Console {
341 tok, err = o.DoManualAuthorization()
342 } else {
343 tok, err = o.DoLoopbackAuthorization()
344 }
345
346 if err != nil {
347 return err
348 }
349
350 if c.Bool("header") {
351 if c.Bool("oidc") {
352 fmt.Println("Authorization: Bearer", tok.IDToken)
353 } else {
354 fmt.Println("Authorization: Bearer", tok.AccessToken)
355 }
356 } else {
357 if c.Bool("bare") {
358 if c.Bool("oidc") {
359 fmt.Println(tok.IDToken)
360 } else {
361 fmt.Println(tok.AccessToken)
362 }
363 } else {
364 b, err := json.MarshalIndent(tok, "", " ")
365 if err != nil {
366 return errors.Wrapf(err, "error marshaling token data")
367 }
368 fmt.Println(string(b))
369 }
370 }
371
372 return nil
373 }
374
375 type options struct {
376 Provider string
377 Email string
378 Console bool
379 Implicit bool
380 CallbackListener string
381 TerminalRedirect string
382 Browser string
383 }
384
385 // Validate validates the options.
386 func (o *options) Validate() error {
387 if o.Provider != "google" && !strings.HasPrefix(o.Provider, "https://") {
388 return errors.New("use a valid provider: google")
389 }
390 if o.CallbackListener != "" {
391 if _, _, err := net.SplitHostPort(o.CallbackListener); err != nil {
392 return errors.Wrapf(err, "invalid value '%s' for flag '--listen'", o.CallbackListener)
393 }
394 }
395 return nil
396 }
397
398 type oauth struct {
399 provider string
400 clientID string
401 clientSecret string
402 scope string
403 prompt string
404 loginHint string
405 redirectURI string
406 tokenEndpoint string
407 authzEndpoint string
408 userInfoEndpoint string // For testing
409 state string
410 codeChallenge string
411 nonce string
412 implicit bool
413 CallbackListener string
414 terminalRedirect string
415 browser string
416 errCh chan error
417 tokCh chan *token
418 }
419
420 func newOauth(provider, clientID, clientSecret, authzEp, tokenEp, scope string, prompt string, opts *options) (*oauth, error) {
421 state, err := randutil.Alphanumeric(32)
422 if err != nil {
423 return nil, err
424 }
425
426 challenge, err := randutil.Alphanumeric(64)
427 if err != nil {
428 return nil, err
429 }
430
431 nonce, err := randutil.Hex(64) // 256 bits
432 if err != nil {
433 return nil, err
434 }
435
436 switch provider {
437 case "google":
438 return &oauth{
439 provider: provider,
440 clientID: clientID,
441 clientSecret: clientSecret,
442 scope: scope,
443 prompt: prompt,
444 authzEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
445 tokenEndpoint: "https://www.googleapis.com/oauth2/v4/token",
446 userInfoEndpoint: "https://www.googleapis.com/oauth2/v3/userinfo",
447 loginHint: opts.Email,
448 state: state,
449 codeChallenge: challenge,
450 nonce: nonce,
451 implicit: opts.Implicit,
452 CallbackListener: opts.CallbackListener,
453 terminalRedirect: opts.TerminalRedirect,
454 browser: opts.Browser,
455 errCh: make(chan error),
456 tokCh: make(chan *token),
457 }, nil
458 default:
459 userinfoEp := ""
460 if authzEp == "" && tokenEp == "" {
461 d, err := disco(provider)
462 if err != nil {
463 return nil, err
464 }
465
466 if _, ok := d["authorization_endpoint"]; !ok {
467 return nil, errors.New("missing 'authorization_endpoint' in provider metadata")
468 }
469 if _, ok := d["token_endpoint"]; !ok {
470 return nil, errors.New("missing 'token_endpoint' in provider metadata")
471 }
472 authzEp = d["authorization_endpoint"].(string)
473 tokenEp = d["token_endpoint"].(string)
474 userinfoEp = d["token_endpoint"].(string)
475 }
476 return &oauth{
477 provider: provider,
478 clientID: clientID,
479 clientSecret: clientSecret,
480 scope: scope,
481 prompt: prompt,
482 authzEndpoint: authzEp,
483 tokenEndpoint: tokenEp,
484 userInfoEndpoint: userinfoEp,
485 loginHint: opts.Email,
486 state: state,
487 codeChallenge: challenge,
488 nonce: nonce,
489 implicit: opts.Implicit,
490 CallbackListener: opts.CallbackListener,
491 terminalRedirect: opts.TerminalRedirect,
492 browser: opts.Browser,
493 errCh: make(chan error),
494 tokCh: make(chan *token),
495 }, nil
496 }
497 }
498
499 func disco(provider string) (map[string]interface{}, error) {
500 url, err := url.Parse(provider)
501 if err != nil {
502 return nil, err
503 }
504 // TODO: OIDC and OAuth specify two different ways of constructing this
505 // URL. This is the OIDC way. Probably want to try both. See
506 // https://tools.ietf.org/html/rfc8414#section-5
507 if !strings.Contains(url.Path, "/.well-known/openid-configuration") {
508 url.Path = path.Join(url.Path, "/.well-known/openid-configuration")
509 }
510 resp, err := http.Get(url.String())
511 if err != nil {
512 return nil, errors.Wrapf(err, "error retrieving %s", url.String())
513 }
514 defer resp.Body.Close()
515 b, err := ioutil.ReadAll(resp.Body)
516 if err != nil {
517 return nil, errors.Wrapf(err, "error retrieving %s", url.String())
518 }
519 details := make(map[string]interface{})
520 if err = json.Unmarshal(b, &details); err != nil {
521 return nil, errors.Wrapf(err, "error reading %s: unsupported format", url.String())
522 }
523 return details, err
524 }
525
526 // NewServer creates http server
527 func (o *oauth) NewServer() (*httptest.Server, error) {
528 if o.CallbackListener == "" {
529 return httptest.NewServer(o), nil
530 }
531 host, port, err := net.SplitHostPort(o.CallbackListener)
532 if err != nil {
533 return nil, err
534 }
535 if host == "" {
536 host = "127.0.0.1"
537 }
538 l, err := net.Listen("tcp", net.JoinHostPort(host, port))
539 if err != nil {
540 return nil, errors.Wrapf(err, "error listening on %s", o.CallbackListener)
541 }
542 srv := &httptest.Server{
543 Listener: l,
544 Config: &http.Server{Handler: o},
545 }
546 srv.Start()
547
548 // Update host to use for example localhost
549 if host != "127.0.0.1" {
550 _, p, err := net.SplitHostPort(l.Addr().String())
551 if err != nil {
552 return nil, errors.Wrapf(err, "error parsing %s", l.Addr().String())
553 }
554 srv.URL = "http://" + host + ":" + p
555 }
556
557 return srv, nil
558 }
559
560 // DoLoopbackAuthorization performs the log in into the identity provider
561 // opening a browser and using a redirect_uri in a loopback IP address
562 // (http://127.0.0.1:port or http://[::1]:port).
563 func (o *oauth) DoLoopbackAuthorization() (*token, error) {
564 srv, err := o.NewServer()
565 if err != nil {
566 return nil, err
567 }
568 o.redirectURI = srv.URL
569 defer srv.Close()
570
571 // Get auth url and open it in a browser
572 authURL, err := o.Auth()
573 if err != nil {
574 return nil, err
575 }
576
577 if err := exec.OpenInBrowser(authURL, o.browser); err != nil {
578 fmt.Fprintln(os.Stderr, "Cannot open a web browser on your platform.")
579 fmt.Fprintln(os.Stderr)
580 fmt.Fprintln(os.Stderr, "Open a local web browser and visit:")
581 fmt.Fprintln(os.Stderr)
582 fmt.Fprintln(os.Stderr, authURL)
583 fmt.Fprintln(os.Stderr)
584 } else {
585 fmt.Fprintln(os.Stderr, "Your default web browser has been opened to visit:")
586 fmt.Fprintln(os.Stderr)
587 fmt.Fprintln(os.Stderr, authURL)
588 fmt.Fprintln(os.Stderr)
589 }
590
591 // Wait for response and return the token
592 select {
593 case tok := <-o.tokCh:
594 return tok, nil
595 case err := <-o.errCh:
596 return nil, err
597 case <-time.After(2 * time.Minute):
598 return nil, errors.New("oauth command timed out, please try again")
599 }
600 }
601
602 // DoManualAuthorization performs the log in into the identity provider
603 // allowing the user to open a browser on a different system and then entering
604 // the authorization code on the Step CLI.
605 func (o *oauth) DoManualAuthorization() (*token, error) {
606 o.redirectURI = oobCallbackUrn
607 authURL, err := o.Auth()
608 if err != nil {
609 return nil, err
610 }
611
612 fmt.Fprintln(os.Stderr, "Open a local web browser and visit:")
613 fmt.Fprintln(os.Stderr)
614 fmt.Fprintln(os.Stderr, authURL)
615 fmt.Fprintln(os.Stderr)
616
617 // Read from the command line
618 fmt.Fprint(os.Stderr, "Enter verification code: ")
619 code, err := utils.ReadString(os.Stdin)
620 if err != nil {
621 return nil, errors.WithStack(err)
622 }
623
624 tok, err := o.Exchange(o.tokenEndpoint, code)
625 if err != nil {
626 return nil, err
627 }
628 if tok.Err != "" || tok.ErrDesc != "" {
629 return nil, errors.Errorf("Error exchanging authorization code: %s. %s", tok.Err, tok.ErrDesc)
630 }
631 return tok, nil
632 }
633
634 // DoTwoLeggedAuthorization performs two-legged OAuth using the jwt-bearer
635 // grant type.
636 func (o *oauth) DoTwoLeggedAuthorization(issuer string) (*token, error) {
637 pemBytes := []byte(o.clientSecret)
638 block, _ := pem.Decode(pemBytes)
639 if block == nil {
640 return nil, fmt.Errorf("failed to read private key pem block")
641 }
642 priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
643 if err != nil {
644 return nil, errors.Wrap(err, "error parsing private key")
645 }
646
647 // Add claims
648 now := int(time.Now().Unix())
649 c := map[string]interface{}{
650 "aud": o.tokenEndpoint,
651 "nbf": now,
652 "iat": now,
653 "exp": now + 3600,
654 "iss": issuer,
655 "scope": o.scope,
656 }
657
658 so := new(jose.SignerOptions)
659 so.WithType("JWT")
660 so.WithHeader("kid", o.clientID)
661
662 // Sign JWT
663 signer, err := jose.NewSigner(jose.SigningKey{
664 Algorithm: "RS256",
665 Key: priv,
666 }, so)
667 if err != nil {
668 return nil, errors.Wrapf(err, "error creating JWT signer")
669 }
670
671 raw, err := jose.Signed(signer).Claims(c).CompactSerialize()
672 if err != nil {
673 return nil, errors.Wrapf(err, "error serializing JWT")
674 }
675
676 // Construct the POST request to fetch the OAuth token.
677 params := url.Values{
678 "assertion": []string{string(raw)},
679 "grant_type": []string{jwtBearerUrn},
680 }
681
682 // Send the POST request and return token.
683 resp, err := http.PostForm(o.tokenEndpoint, params)
684 if err != nil {
685 return nil, errors.Wrapf(err, "error from token endpoint")
686 }
687 defer resp.Body.Close()
688
689 var tok token
690 if err := json.NewDecoder(resp.Body).Decode(&tok); err != nil {
691 return nil, errors.WithStack(err)
692 }
693
694 return &tok, nil
695 }
696
697 // DoJWTAuthorization generates a JWT instead of an OAuth token. Only works for
698 // certain APIs. See https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth.
699 func (o *oauth) DoJWTAuthorization(issuer, aud string) (*token, error) {
700 pemBytes := []byte(o.clientSecret)
701 block, _ := pem.Decode(pemBytes)
702 if block == nil {
703 return nil, fmt.Errorf("failed to read private key pem block")
704 }
705 priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
706 if err != nil {
707 return nil, errors.Wrap(err, "error parsing private key")
708 }
709
710 // Add claims
711 now := int(time.Now().Unix())
712 c := map[string]interface{}{
713 "aud": aud,
714 "nbf": now,
715 "iat": now,
716 "exp": now + 3600,
717 "iss": issuer,
718 "sub": issuer,
719 }
720
721 so := new(jose.SignerOptions)
722 so.WithType("JWT")
723 so.WithHeader("kid", o.clientID)
724
725 // Sign JWT
726 signer, err := jose.NewSigner(jose.SigningKey{
727 Algorithm: "RS256",
728 Key: priv,
729 }, so)
730 if err != nil {
731 return nil, errors.Wrapf(err, "error creating JWT signer")
732 }
733
734 raw, err := jose.Signed(signer).Claims(c).CompactSerialize()
735 if err != nil {
736 return nil, errors.Wrapf(err, "error serializing JWT")
737 }
738
739 tok := &token{string(raw), "", "", 3600, "Bearer", "", ""}
740 return tok, nil
741 }
742
743 // ServeHTTP is the handler that performs the OAuth 2.0 dance and returns the
744 // tokens using channels.
745 func (o *oauth) ServeHTTP(w http.ResponseWriter, req *http.Request) {
746 if req.URL.Path != "/" {
747 http.NotFound(w, req)
748 return
749 }
750
751 q := req.URL.Query()
752 errStr := q.Get("error")
753 if errStr != "" {
754 o.badRequest(w, "Failed to authenticate: "+errStr)
755 return
756 }
757
758 if o.implicit {
759 o.implicitHandler(w, req)
760 return
761 }
762
763 code, state := q.Get("code"), q.Get("state")
764 if code == "" || state == "" {
765 fmt.Fprintf(os.Stderr, "Invalid request received: http://%s%s\n", req.RemoteAddr, req.URL.String())
766 fmt.Fprintf(os.Stderr, "You may have an app or browser plugin that needs to be turned off\n")
767 http.Error(w, "400 bad request", http.StatusBadRequest)
768 return
769 }
770
771 if code == "" {
772 o.badRequest(w, "Failed to authenticate: missing or invalid code")
773 return
774 }
775
776 if state == "" || state != o.state {
777 o.badRequest(w, "Failed to authenticate: missing or invalid state")
778 return
779 }
780
781 tok, err := o.Exchange(o.tokenEndpoint, code)
782 if err != nil {
783 o.badRequest(w, "Failed exchanging authorization code: "+err.Error())
784 return
785 }
786 if tok.Err != "" || tok.ErrDesc != "" {
787 o.badRequest(w, fmt.Sprintf("Failed exchanging authorization code: %s. %s", tok.Err, tok.ErrDesc))
788 return
789 }
790
791 if o.terminalRedirect != "" {
792 http.Redirect(w, req, o.terminalRedirect, 302)
793 } else {
794 o.success(w)
795 }
796 o.tokCh <- tok
797 }
798
799 func (o *oauth) implicitHandler(w http.ResponseWriter, req *http.Request) {
800 q := req.URL.Query()
801 if hash := q.Get("urlhash"); hash == "true" {
802 state := q.Get("state")
803 if state == "" || state != o.state {
804 o.badRequest(w, "Failed to authenticate: missing or invalid state")
805 return
806 }
807 accessToken := q.Get("access_token")
808 if accessToken == "" {
809 o.badRequest(w, "Failed to authenticate: missing access token")
810 return
811 }
812
813 if o.terminalRedirect != "" {
814 http.Redirect(w, req, o.terminalRedirect, 302)
815 } else {
816 o.success(w)
817 }
818
819 expiresIn, _ := strconv.Atoi(q.Get("expires_in"))
820 o.tokCh <- &token{
821 AccessToken: accessToken,
822 IDToken: q.Get("id_token"),
823 RefreshToken: q.Get("refresh_token"),
824 ExpiresIn: expiresIn,
825 TokenType: q.Get("token_type"),
826 }
827 return
828 }
829
830 w.WriteHeader(http.StatusOK)
831 w.Header().Add("Content-Type", "text/html; charset=utf-8")
832 w.Write([]byte(`<html><head><title>Processing OAuth Request</title>`))
833 w.Write([]byte(`</head>`))
834 w.Write([]byte(`<script type="text/javascript">`))
835 w.Write([]byte(fmt.Sprintf(`function redirect(){var hash = window.location.hash.substr(1); document.location.href = "%s?urlhash=true&"+hash;}`, o.redirectURI)))
836 w.Write([]byte(`if (window.addEventListener) window.addEventListener("load", redirect, false); else if (window.attachEvent) window.attachEvent("onload", redirect); else window.onload = redirect;`))
837 w.Write([]byte("</script>"))
838 w.Write([]byte(`<body><p style='font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 22px; color: #333; width: 400px; margin: 0 auto; text-align: center; line-height: 1.7; padding: 20px;'>`))
839 w.Write([]byte(`<strong style='font-size: 28px; color: #000;'>Success</strong><br />`))
840 w.Write([]byte(`Click <a href="javascript:redirect();">here</a> if your browser does not automatically redirect you`))
841 w.Write([]byte(`</p></body></html>`))
842 }
843
844 // Auth returns the OAuth 2.0 authentication url.
845 func (o *oauth) Auth() (string, error) {
846 u, err := url.Parse(o.authzEndpoint)
847 if err != nil {
848 return "", errors.WithStack(err)
849 }
850
851 q := u.Query()
852 q.Add("client_id", o.clientID)
853 q.Add("redirect_uri", o.redirectURI)
854 if o.implicit {
855 q.Add("response_type", "id_token token")
856 } else {
857 q.Add("response_type", "code")
858 q.Add("code_challenge_method", "S256")
859 s256 := sha256.Sum256([]byte(o.codeChallenge))
860 q.Add("code_challenge", base64.RawURLEncoding.EncodeToString(s256[:]))
861 }
862 q.Add("scope", o.scope)
863 if o.prompt != "" {
864 q.Add("prompt", o.prompt)
865 }
866 q.Add("state", o.state)
867 q.Add("nonce", o.nonce)
868 if o.loginHint != "" {
869 q.Add("login_hint", o.loginHint)
870 }
871 u.RawQuery = q.Encode()
872 return u.String(), nil
873 }
874
875 // Exchange exchanges the authorization code for refresh and access tokens.
876 func (o *oauth) Exchange(tokenEndpoint, code string) (*token, error) {
877 data := url.Values{}
878 data.Set("code", code)
879 data.Set("client_id", o.clientID)
880 data.Set("client_secret", o.clientSecret)
881 data.Set("redirect_uri", o.redirectURI)
882 data.Set("grant_type", "authorization_code")
883 data.Set("code_verifier", o.codeChallenge)
884
885 resp, err := http.PostForm(tokenEndpoint, data)
886 if err != nil {
887 return nil, errors.WithStack(err)
888 }
889 defer resp.Body.Close()
890
891 var tok token
892 if err := json.NewDecoder(resp.Body).Decode(&tok); err != nil {
893 return nil, errors.WithStack(err)
894 }
895
896 return &tok, nil
897 }
898
899 func (o *oauth) success(w http.ResponseWriter) {
900 w.WriteHeader(http.StatusOK)
901 w.Header().Add("Content-Type", "text/plain; charset=utf-8")
902 w.Write([]byte(`<html><head><title>OAuth Request Successful</title>`))
903 w.Write([]byte(`</head><body><p style='font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 22px; color: #333; width: 400px; margin: 0 auto; text-align: center; line-height: 1.7; padding: 20px;'>`))
904 w.Write([]byte(`<strong style='font-size: 28px; color: #000;'>Success</strong><br />Look for the token on the command line`))
905 w.Write([]byte(`</p></body></html>`))
906 }
907
908 func (o *oauth) badRequest(w http.ResponseWriter, msg string) {
909 w.WriteHeader(http.StatusBadRequest)
910 w.Header().Add("Content-Type", "text/plain; charset=utf-8")
911 w.Write([]byte(`<html><head><title>OAuth Request Unsuccessful</title>`))
912 w.Write([]byte(`</head><body><p style='font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; font-size: 22px; color: #333; width: 400px; margin: 0 auto; text-align: center; line-height: 1.7; padding: 20px;'>`))
913 w.Write([]byte(`<strong style='font-size: 28px; color: red;'>Failure</strong><br />`))
914 w.Write([]byte(msg))
915 w.Write([]byte(`</p></body></html>`))
916 o.errCh <- errors.New(msg)
917 }