-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoidc.go
More file actions
217 lines (188 loc) · 4.85 KB
/
oidc.go
File metadata and controls
217 lines (188 loc) · 4.85 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
package main
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log/slog"
"math/big"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
)
type Claims struct {
Email string `json:"email"`
jwt.RegisteredClaims
}
type tokenValidationError struct {
PublicMessage string
}
func (e *tokenValidationError) Error() string {
return e.PublicMessage
}
type jwksDocument struct {
Keys []jwkKey `json:"keys"`
}
type jwkKey struct {
Kid string `json:"kid"`
Kty string `json:"kty"`
Alg string `json:"alg"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
}
type jwkCache struct {
mu sync.RWMutex
keys map[string]*rsa.PublicKey
}
var (
providerHTTPClient = &http.Client{Timeout: 10 * time.Second}
providerKeys jwkCache
)
func buildAuthorizationURL(serviceID string) string {
v := url.Values{}
v.Set("client_id", oidcClientID)
v.Set("redirect_uri", oidcRedirectURL)
v.Set("response_type", "id_token")
v.Set("response_mode", "form_post")
v.Set("scope", "openid email")
v.Set("prompt", "login")
v.Set("nonce", rand.Text())
v.Set("svc", serviceID)
return oidcAuthEndpoint + "?" + v.Encode()
}
func verifyIDToken(ctx context.Context, raw string) (*Claims, error) {
parser := jwt.NewParser(
jwt.WithValidMethods([]string{jwt.SigningMethodRS256.Alg(), jwt.SigningMethodRS384.Alg(), jwt.SigningMethodRS512.Alg()}),
jwt.WithIssuer(oidcIssuer),
jwt.WithAudience(oidcClientID),
jwt.WithExpirationRequired(),
jwt.WithIssuedAt(),
jwt.WithLeeway(30*time.Second),
)
claims := &Claims{}
token, err := parser.ParseWithClaims(raw, claims, keyFunc(ctx))
if err != nil {
return nil, classifyJWTError(err)
}
if !token.Valid {
return nil, &tokenValidationError{PublicMessage: "Invalid JWT"}
}
claims.Email = strings.ToLower(strings.TrimSpace(claims.Email))
if claims.Email == "" {
return nil, &tokenValidationError{PublicMessage: "JWT missing email claim"}
}
return claims, nil
}
func keyFunc(ctx context.Context) jwt.Keyfunc {
return func(token *jwt.Token) (any, error) {
kid, _ := token.Header["kid"].(string)
if kid == "" {
return nil, fmt.Errorf("missing kid")
}
if key := providerKeys.get(kid); key != nil {
return key, nil
}
if err := refreshJWKS(ctx); err != nil {
return nil, err
}
if key := providerKeys.get(kid); key != nil {
return key, nil
}
return nil, fmt.Errorf("unknown kid %q", kid)
}
}
func refreshJWKS(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, oidcJWKSURL, nil)
if err != nil {
return err
}
resp, err := providerHTTPClient.Do(req)
if err != nil {
return err
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("jwks fetch failed with status %s", resp.Status)
}
var doc jwksDocument
if err := json.NewDecoder(resp.Body).Decode(&doc); err != nil {
return err
}
keys := make(map[string]*rsa.PublicKey, len(doc.Keys))
for _, jwk := range doc.Keys {
if jwk.Kty != "RSA" || jwk.Kid == "" {
continue
}
pub, err := rsaKeyFromJWK(jwk)
if err != nil {
slog.Warn("ignoring invalid jwk", slog.String("kid", jwk.Kid), slog.Any("error", err))
continue
}
keys[jwk.Kid] = pub
}
if len(keys) == 0 {
return errors.New("jwks contained no usable rsa keys")
}
providerKeys.set(keys)
return nil
}
func rsaKeyFromJWK(jwk jwkKey) (*rsa.PublicKey, error) {
nb, err := base64.RawURLEncoding.DecodeString(jwk.N)
if err != nil {
return nil, err
}
eb, err := base64.RawURLEncoding.DecodeString(jwk.E)
if err != nil {
return nil, err
}
e := 0
for _, b := range eb {
e = e<<8 | int(b)
}
if e <= 0 {
return nil, errors.New("invalid rsa exponent")
}
return &rsa.PublicKey{
N: new(big.Int).SetBytes(nb),
E: e,
}, nil
}
func classifyJWTError(err error) error {
switch {
case errors.Is(err, jwt.ErrTokenMalformed):
return &tokenValidationError{PublicMessage: "Malformed JWT"}
case errors.Is(err, jwt.ErrTokenSignatureInvalid):
return &tokenValidationError{PublicMessage: "Invalid JWT signature"}
case errors.Is(err, jwt.ErrTokenExpired):
return &tokenValidationError{PublicMessage: "JWT expired"}
case errors.Is(err, jwt.ErrTokenNotValidYet):
return &tokenValidationError{PublicMessage: "JWT not valid yet"}
case errors.Is(err, jwt.ErrTokenInvalidIssuer):
return &tokenValidationError{PublicMessage: "Invalid JWT issuer"}
case errors.Is(err, jwt.ErrTokenInvalidAudience):
return &tokenValidationError{PublicMessage: "Invalid JWT audience"}
case errors.Is(err, jwt.ErrTokenUnverifiable):
return &tokenValidationError{PublicMessage: "Unverifiable JWT"}
default:
return err
}
}
func (c *jwkCache) get(kid string) *rsa.PublicKey {
c.mu.RLock()
defer c.mu.RUnlock()
return c.keys[kid]
}
func (c *jwkCache) set(keys map[string]*rsa.PublicKey) {
c.mu.Lock()
defer c.mu.Unlock()
c.keys = keys
}