-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathoidc.go
More file actions
365 lines (308 loc) · 10.4 KB
/
Copy pathoidc.go
File metadata and controls
365 lines (308 loc) · 10.4 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
// Copyright (c) 2024-2026, s0up and the autobrr contributors.
// SPDX-License-Identifier: GPL-2.0-or-later
package auth
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"slices"
"strings"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/go-jose/go-jose/v4"
"github.com/rs/zerolog/log"
"golang.org/x/oauth2"
"github.com/autobrr/netronome/internal/config"
)
type OIDCConfig struct {
provider *oidc.Provider
OAuth2Config oauth2.Config
verifier *oidc.IDTokenVerifier
}
type Claims struct {
Subject string `json:"sub"`
Name string `json:"name"`
Username string `json:"preferred_username"`
}
type IDTokenClaims struct {
Subject string `json:"sub"`
Name string `json:"name"`
Username string `json:"preferred_username"`
Expiry int64 `json:"exp"`
}
// PKCEParams holds PKCE parameters for OAuth2 flow
type PKCEParams struct {
CodeVerifier string
CodeChallenge string
}
// GeneratePKCEParams generates PKCE code verifier and challenge
func GeneratePKCEParams() (*PKCEParams, error) {
// Generate 43-128 character random string for code verifier
verifierBytes := make([]byte, 96) // 96 bytes = 128 base64url characters
if _, err := rand.Read(verifierBytes); err != nil {
return nil, fmt.Errorf("failed to generate PKCE code verifier: %w", err)
}
codeVerifier := base64.RawURLEncoding.EncodeToString(verifierBytes)
// Generate code challenge using SHA256
challengeBytes := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(challengeBytes[:])
return &PKCEParams{
CodeVerifier: codeVerifier,
CodeChallenge: codeChallenge,
}, nil
}
// isJWE checks if a token is in JWE format (5 parts separated by dots)
func isJWE(token string) bool {
parts := strings.Split(token, ".")
return len(parts) == 5
}
// decryptJWE attempts to decrypt a JWE token using the client secret as the key
func (c *OIDCConfig) decryptJWE(jweToken string) (string, error) {
// Parse the JWE token
jwe, err := jose.ParseEncrypted(jweToken, []jose.KeyAlgorithm{jose.DIRECT, jose.A128KW, jose.A192KW, jose.A256KW}, []jose.ContentEncryption{jose.A128GCM, jose.A192GCM, jose.A256GCM})
if err != nil {
return "", fmt.Errorf("failed to parse JWE token: %w", err)
}
// Try to decrypt with client secret as key
clientSecret := c.OAuth2Config.ClientSecret
if clientSecret == "" {
return "", fmt.Errorf("client secret required for JWE decryption")
}
// Convert client secret to appropriate key length for AES
key := []byte(clientSecret)
if len(key) < 16 {
// Pad with zeros if too short
padded := make([]byte, 16)
copy(padded, key)
key = padded
} else if len(key) > 32 {
// Truncate if too long
key = key[:32]
} else if len(key) > 16 && len(key) < 24 {
// Pad to 24 bytes
padded := make([]byte, 24)
copy(padded, key)
key = padded
} else if len(key) > 24 && len(key) < 32 {
// Pad to 32 bytes
padded := make([]byte, 32)
copy(padded, key)
key = padded
}
// Attempt decryption
decrypted, err := jwe.Decrypt(key)
if err != nil {
// Try SHA256 hash of client secret as key (common pattern)
hasher := sha256.New()
hasher.Write([]byte(clientSecret))
hashedKey := hasher.Sum(nil)
// Try with full hash (32 bytes)
decrypted, err = jwe.Decrypt(hashedKey)
if err != nil {
// Try with truncated hash (16 bytes)
decrypted, err = jwe.Decrypt(hashedKey[:16])
if err != nil {
return "", fmt.Errorf("failed to decrypt JWE token with client secret or hash: %w", err)
}
}
}
log.Debug().Msg("Successfully decrypted JWE token")
return string(decrypted), nil
}
const (
oidcInitMaxAttempts = 10
oidcInitRetryDelay = 5 * time.Second
)
func NewOIDC(ctx context.Context, cfg config.OIDCConfig) (*OIDCConfig, error) {
if cfg.Issuer == "" {
log.Debug().Msg("Using built-in authentication")
return nil, nil
}
log.Debug().Str("issuer", cfg.Issuer).Msg("Initializing OIDC provider")
var (
endpoints oauth2.Endpoint
provider *oidc.Provider
lastErr error
)
for attempt := 1; attempt <= oidcInitMaxAttempts; attempt++ {
endpoints, _, lastErr = getProviderEndpoints(ctx, http.DefaultClient, cfg.Issuer)
if lastErr != nil {
log.Warn().Err(lastErr).Int("attempt", attempt).Int("max", oidcInitMaxAttempts).
Str("issuer", cfg.Issuer).Msg("Failed to discover OIDC provider endpoints")
if attempt < oidcInitMaxAttempts {
time.Sleep(oidcInitRetryDelay)
}
continue
}
provider, lastErr = oidc.NewProvider(ctx, cfg.Issuer)
if lastErr != nil {
log.Warn().Err(lastErr).Int("attempt", attempt).Int("max", oidcInitMaxAttempts).
Str("issuer", cfg.Issuer).Msg("Failed to initialize OIDC provider")
if attempt < oidcInitMaxAttempts {
time.Sleep(oidcInitRetryDelay)
}
continue
}
break
}
if lastErr != nil {
log.Error().Err(lastErr).Str("issuer", cfg.Issuer).Msg("Failed to initialize OIDC provider after all attempts")
return nil, fmt.Errorf("failed to initialize OIDC provider after %d attempts: %w", oidcInitMaxAttempts, lastErr)
}
scopes := cfg.Scopes
if len(scopes) == 0 {
scopes = []string{oidc.ScopeOpenID, "profile"}
} else if !containsScope(scopes, oidc.ScopeOpenID) {
scopes = append(scopes, oidc.ScopeOpenID)
}
config := oauth2.Config{
ClientID: cfg.ClientID,
ClientSecret: cfg.ClientSecret,
RedirectURL: cfg.RedirectURL,
Endpoint: endpoints,
Scopes: scopes,
}
log.Trace().
Str("clientID", config.ClientID).
Str("redirectURL", config.RedirectURL).
Str("authURL", endpoints.AuthURL).
Str("tokenURL", endpoints.TokenURL).
Strs("scopes", config.Scopes).
Msg("OIDC configuration created")
return &OIDCConfig{
provider: provider,
OAuth2Config: config,
verifier: provider.Verifier(&oidc.Config{ClientID: config.ClientID}),
}, nil
}
func getProviderEndpoints(ctx context.Context, client *http.Client, issuer string) (oauth2.Endpoint, string, error) {
issuer = strings.TrimRight(issuer, "/")
wellKnown := issuer + "/.well-known/openid-configuration"
if strings.Contains(issuer, "/.well-known/openid-configuration") {
wellKnown = issuer
}
log.Trace().Str("well_known_url", wellKnown).Msg("Fetching OIDC discovery document")
req, err := http.NewRequestWithContext(ctx, "GET", wellKnown, nil)
if err != nil {
return oauth2.Endpoint{}, "", fmt.Errorf("creating discovery request: %w", err)
}
resp, err := client.Do(req)
if err != nil {
return oauth2.Endpoint{}, "", fmt.Errorf("fetching discovery document: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return oauth2.Endpoint{}, "", fmt.Errorf("reading discovery document: %w", err)
}
var discovery struct {
Issuer string `json:"issuer"`
AuthURL string `json:"authorization_endpoint"`
TokenURL string `json:"token_endpoint"`
UserinfoURL string `json:"userinfo_endpoint"`
JWKSURL string `json:"jwks_uri"`
}
if err := json.Unmarshal(body, &discovery); err != nil {
return oauth2.Endpoint{}, "", fmt.Errorf("parsing discovery document: %w", err)
}
log.Debug().
Str("issuer", discovery.Issuer).
Str("auth_url", discovery.AuthURL).
Str("token_url", discovery.TokenURL).
Msg("OIDC discovery successful")
return oauth2.Endpoint{
AuthURL: discovery.AuthURL,
TokenURL: discovery.TokenURL,
}, discovery.UserinfoURL, nil
}
func containsScope(scopes []string, target string) bool {
return slices.Contains(scopes, target)
}
// AuthURLWithPKCE generates an authorization URL with PKCE parameters
func (c *OIDCConfig) AuthURLWithPKCE(state string, pkce *PKCEParams) string {
return c.OAuth2Config.AuthCodeURL(state,
oauth2.SetAuthURLParam("code_challenge", pkce.CodeChallenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"))
}
// ExchangeCodeWithPKCE exchanges authorization code for tokens using PKCE
func (c *OIDCConfig) ExchangeCodeWithPKCE(ctx context.Context, code string, codeVerifier string) (*oauth2.Token, error) {
return c.OAuth2Config.Exchange(ctx, code,
oauth2.SetAuthURLParam("code_verifier", codeVerifier))
}
func (c *OIDCConfig) RefreshToken(ctx context.Context, refreshToken string) (*oauth2.Token, error) {
if refreshToken == "" {
return nil, errors.New("refresh token required")
}
source := c.OAuth2Config.TokenSource(ctx, &oauth2.Token{
RefreshToken: refreshToken,
Expiry: time.Now().Add(-time.Hour),
})
return source.Token()
}
func (c *OIDCConfig) VerifyToken(ctx context.Context, token string) error {
_, err := c.VerifyTokenWithClaims(ctx, token)
return err
}
func (c *OIDCConfig) VerifyTokenWithClaims(ctx context.Context, token string) (*IDTokenClaims, error) {
// Check if token is JWE and decrypt if necessary
verifyToken := token
if isJWE(token) {
log.Debug().Msg("Detected JWE token, attempting decryption")
decrypted, err := c.decryptJWE(token)
if err != nil {
log.Error().Err(err).Msg("Failed to decrypt JWE token")
return nil, fmt.Errorf("failed to decrypt JWE token: %w", err)
}
verifyToken = decrypted
log.Debug().Msg("JWE token decrypted successfully")
}
idToken, err := c.verifier.Verify(ctx, verifyToken)
if err != nil {
return nil, fmt.Errorf("invalid token: %w", err)
}
var claims IDTokenClaims
if err := idToken.Claims(&claims); err != nil {
return nil, fmt.Errorf("failed to parse claims: %w", err)
}
if claims.Subject == "" {
return nil, errors.New("token missing subject claim")
}
now := time.Now()
if claims.Expiry == 0 {
// If expiry is missing, set it to 24 hours from the current time
claims.Expiry = now.Add(24 * time.Hour).Unix()
}
if now.After(time.Unix(claims.Expiry, 0)) {
return nil, errors.New("token has expired")
}
return &claims, nil
}
func (c *OIDCConfig) GetClaims(ctx context.Context, token string) (*Claims, error) {
// Check if token is JWE and decrypt if necessary
var verifyToken string = token
if isJWE(token) {
log.Debug().Msg("Detected JWE token in GetClaims, attempting decryption")
decrypted, err := c.decryptJWE(token)
if err != nil {
log.Error().Err(err).Msg("Failed to decrypt JWE token in GetClaims")
return nil, fmt.Errorf("failed to decrypt JWE token: %w", err)
}
verifyToken = decrypted
log.Debug().Msg("JWE token decrypted successfully in GetClaims")
}
idToken, err := c.verifier.Verify(ctx, verifyToken)
if err != nil {
return nil, fmt.Errorf("invalid token: %w", err)
}
var claims Claims
if err := idToken.Claims(&claims); err != nil {
return nil, fmt.Errorf("failed to parse claims: %w", err)
}
return &claims, nil
}