Commit d9ac6d02c2d9e4659b8200d8ee0d44290f4014d6

Parents: a23de8fd5bb1483f7b4eff31352a7ae0056498ea

From: Moritz Poldrack <git@moritz.sh>
Date: Sat Dec 23 21:27:24 2023 +0700

fix token validation

		

Stats

configuration.go +13/-2
just-do-it.go +7/-11
options.go +3/-1
token.go +15/-6

Changeset

  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
diff --git a/configuration.go b/configuration.go
index e0f50fe6c2b8bd3d94ec1097dd76e0f20eb5d1e1..2ad1121e38799983294f06245b431e7f04e77675 100644
--- a/configuration.go
+++ b/configuration.go
@@ -4,6 +4,7 @@ // SPDX-FileCopyrightText: © Moritz Poldrack
 // SPDX-License-Identifier: MPL-2.0
 
 import (
+	"context"
 	"encoding/json"
 	"fmt"
 	"net/http"
@@ -12,6 +13,7 @@ 	"path/filepath"
 	"slices"
 	"sync"
 
+	"github.com/lestrrat-go/jwx/v2/jwk"
 	"golang.org/x/oauth2"
 )
 
@@ -24,8 +26,9 @@ 	oauthCfg    *oauth2.Config
 	scopes      []string
 
 	// validators
-	validators    map[string]validator
+	validators    map[string]*validator
 	validatorsMtx sync.RWMutex
+	jwtKeyCache   *jwk.Cache
 
 	// options
 	options option
@@ -63,6 +66,12 @@ 	if err != nil {
 		return nil, fmt.Errorf("failed to parse config: %w", err)
 	}
 
+	jwkcache := jwk.NewCache(context.Background())
+	jwkcache.Register(cfg.JwksURI)
+	if _, err := jwkcache.Refresh(context.Background(), cfg.JwksURI); err != nil {
+		return nil, fmt.Errorf("failed to get JWKs: %w", err)
+	}
+
 	svcConfig := &Configuration{
 		cfg: cfg,
 		oauthCfg: &oauth2.Config{
@@ -72,8 +81,10 @@ 				DeviceAuthURL: cfg.DeviceAuthorizationEndpoint,
 				TokenURL:      cfg.TokenEndpoint,
 				AuthStyle:     0,
 			},
+			RedirectURL: callbackURL,
 		},
-		validators: make(map[string]validator),
+		validators:  make(map[string]*validator),
+		jwtKeyCache: jwkcache,
 	}
 	svcConfig.scopes = cfg.ScopesSupported
 	svcConfig.oauthCfg.Scopes = cfg.ScopesSupported
diff --git a/just-do-it.go b/just-do-it.go
index b7319f8f7e7be5ce1163276385d8818119f965ab..763135868865a4c31a353275cf5d3bf132a289ee 100644
--- a/just-do-it.go
+++ b/just-do-it.go
@@ -5,7 +5,6 @@ // SPDX-License-Identifier: MPL-2.0
 
 import (
 	"context"
-	"crypto/sha256"
 	"fmt"
 	"math/rand"
 	"time"
@@ -16,25 +15,22 @@
 // GetAuthorizationURL returns the authorization URL. Redirect your user to the
 // returned URL and be happy.
 func (cfg *Configuration) GetAuthorizationURL() string {
-	verifier := oauth2.GenerateVerifier()
-	options := []oauth2.AuthCodeOption{
-		oauth2.S256ChallengeOption(verifier),
-	}
-	hasher := sha256.New()
-	fmt.Fprintf(hasher, "%s%b", verifier, rand.Int63())
-
-	state := string(hasher.Sum(nil))
+	var state string
+	options := []oauth2.AuthCodeOption{}
 
 	if cfg.options.has(OptionDisableCSRFProtection) {
 		state = "state"
-		options = nil
 	} else {
+		verifier := oauth2.GenerateVerifier()
+		state := fmt.Sprintf("%x", rand.Int63())
+
 		cfg.validatorsMtx.Lock()
-		cfg.validators[state] = validator{
+		cfg.validators[state] = &validator{
 			validator: verifier,
 			expires:   time.Now().Add(5 * time.Minute),
 		}
 		cfg.validatorsMtx.Unlock()
+		options = append(options, oauth2.SetAuthURLParam("state", state), oauth2.S256ChallengeOption(verifier))
 	}
 
 	if cfg.options.has(OptionRequestOfflineToken) {
diff --git a/options.go b/options.go
index 09323d3dbd54679a373239b022ca0de624a1e968..44a52a8614a478e870720c9d8f94b3b44e29a303 100644
--- a/options.go
+++ b/options.go
@@ -10,7 +10,7 @@ 	return o&opt == opt
 }
 
 const (
-	// OptionNoScopeValidation disables the scope validation. This is
+	// OptionSkipScopeValidation disables the scope validation. This is
 	// intended to only be used if a known non-standard compliant service
 	// *has* to be used.
 	OptionSkipScopeValidation option = 1 << iota
@@ -22,4 +22,6 @@ 	// OptionRequestOfflineToken sends a request for an offline token. This
 	// is only useful if the token is used without user-interaction to
 	// authenticate with another system.
 	OptionRequestOfflineToken
+	// OptionSkipTokenValidation skips the validation of the returned JWT.
+	OptionSkipTokenValidation
 )
diff --git a/token.go b/token.go
index b25be9fad2f14e47f84222e296b517b9ca1c18c6..33aa993472f93093f478e9a4284f9075cf2b5ac6 100644
--- a/token.go
+++ b/token.go
@@ -47,24 +47,33 @@ 	idToken openid.Token
 }
 
 func (cfg *Configuration) newToken(tok *oauth2.Token) *Token {
+	result := &Token{
+		source: cfg.oauthCfg.TokenSource(context.Background(), tok),
+	}
+
 	token := fmt.Sprint(tok.Extra("id_token"))
+	keyset, err := cfg.jwtKeyCache.Get(context.Background(), cfg.cfg.JwksURI)
+	if err != nil {
+		return result
+	}
 	idToken, err := jwt.Parse(
 		[]byte(token),
 		jwt.WithToken(openid.New()),
+		jwt.WithVerify(!cfg.options.has(OptionSkipTokenValidation)),
+		jwt.WithKeySet(keyset),
 	)
 	if err == nil {
-		return nil
+		return result
 	}
 
 	oidToken, ok := idToken.(openid.Token)
 	if !ok {
-		return nil
+		return result
 	}
 
-	return &Token{
-		source:  cfg.oauthCfg.TokenSource(context.Background(), tok),
-		idToken: oidToken,
-	}
+	result.idToken = oidToken
+
+	return result
 }
 
 func (t *Token) Token() (*oauth2.Token, error) {