-
Notifications
You must be signed in to change notification settings - Fork 635
Expand file tree
/
Copy pathtoken_oidc.go
More file actions
336 lines (276 loc) · 11.1 KB
/
token_oidc.go
File metadata and controls
336 lines (276 loc) · 11.1 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
package api
import (
"context"
"crypto/sha256"
"fmt"
"net/http"
"slices"
"strings"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/api/provider"
"github.com/supabase/auth/internal/conf"
"github.com/supabase/auth/internal/metering"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/observability"
"github.com/supabase/auth/internal/storage"
)
// IdTokenGrantParams are the parameters the IdTokenGrant method accepts
type IdTokenGrantParams struct {
IdToken string `json:"id_token"`
AccessToken string `json:"access_token"`
Nonce string `json:"nonce"`
Provider string `json:"provider"`
ClientID string `json:"client_id"`
Issuer string `json:"issuer"`
LinkIdentity bool `json:"link_identity"`
}
func (p *IdTokenGrantParams) getProvider(ctx context.Context, config *conf.GlobalConfiguration, r *http.Request) (*oidc.Provider, bool, string, []string, bool, error) {
log := observability.GetLogEntry(r).Entry
var cfg *conf.OAuthProviderConfiguration
var issuer string
var providerType string
var acceptableClientIDs []string
if p.Issuer != "" {
log.WithField("issuer", p.Issuer).WithField("provider", p.Provider).Info("Issuer provided in request.")
}
switch true {
case p.Provider == "apple" || provider.IsAppleIssuer(p.Issuer):
cfg = &config.External.Apple
providerType = "apple"
detectedIssuer, err := provider.DetectAppleIDTokenIssuer(ctx, p.IdToken)
if err != nil {
return nil, false, "", nil, false, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Unable to detect issuer in ID token for Apple provider").WithInternalError(err)
}
if !provider.IsAppleIssuer(detectedIssuer) {
return nil, false, "", nil, false, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Detected ID token issuer is not an Apple ID token issuer")
}
if p.Issuer != "" && p.Issuer != detectedIssuer {
return nil, false, "", nil, false, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Provided issuer does not match ID token issuer")
}
issuer = detectedIssuer
acceptableClientIDs = append(acceptableClientIDs, config.External.Apple.ClientID...)
if config.External.IosBundleId != "" {
acceptableClientIDs = append(acceptableClientIDs, config.External.IosBundleId)
}
case p.Provider == "google" || p.Issuer == provider.IssuerGoogle:
cfg = &config.External.Google
providerType = "google"
issuer = provider.IssuerGoogle
acceptableClientIDs = append(acceptableClientIDs, config.External.Google.ClientID...)
case p.Provider == "azure" || provider.IsAzureIssuer(p.Issuer):
detectedIssuer, err := provider.DetectAzureIDTokenIssuer(ctx, p.IdToken)
if err != nil {
return nil, false, "", nil, false, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Unable to detect issuer in ID token for Azure provider").WithInternalError(err)
}
if !strings.HasPrefix(detectedIssuer, "https://login.microsoftonline.com/") && !strings.HasPrefix(detectedIssuer, "https://sts.windows.net/") {
return nil, false, "", nil, false, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Detected ID token issuer is not an Azure ID token issuer")
}
if p.Issuer != "" && p.Issuer != detectedIssuer {
return nil, false, "", nil, false, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Provided issuer does not match ID token issuer")
}
issuer = detectedIssuer
cfg = &config.External.Azure
providerType = "azure"
acceptableClientIDs = append(acceptableClientIDs, config.External.Azure.ClientID...)
case p.Provider == "facebook" || p.Issuer == provider.IssuerFacebook:
cfg = &config.External.Facebook
// Facebook (Limited Login) nonce check is not supported
cfg.SkipNonceCheck = true
providerType = "facebook"
issuer = provider.IssuerFacebook
acceptableClientIDs = append(acceptableClientIDs, config.External.Facebook.ClientID...)
case p.Provider == "keycloak" || (config.External.Keycloak.Enabled && config.External.Keycloak.URL != "" && p.Issuer == config.External.Keycloak.URL):
cfg = &config.External.Keycloak
providerType = "keycloak"
issuer = config.External.Keycloak.URL
acceptableClientIDs = append(acceptableClientIDs, config.External.Keycloak.ClientID...)
case p.Provider == "kakao" || p.Issuer == provider.IssuerKakao:
cfg = &config.External.Kakao
providerType = "kakao"
issuer = provider.IssuerKakao
acceptableClientIDs = append(acceptableClientIDs, config.External.Kakao.ClientID...)
case p.Provider == "vercel_marketplace" || p.Issuer == provider.IssuerVercelMarketplace:
cfg = &config.External.VercelMarketplace
providerType = "vercel_marketplace"
issuer = provider.IssuerVercelMarketplace
acceptableClientIDs = append(acceptableClientIDs, config.External.VercelMarketplace.ClientID...)
case p.Provider == "snapchat" || p.Issuer == provider.IssuerSnapchat:
cfg = &config.External.Snapchat
providerType = "snapchat"
issuer = provider.IssuerSnapchat
acceptableClientIDs = append(acceptableClientIDs, config.External.Snapchat.ClientID...)
default:
log.WithField("issuer", p.Issuer).WithField("client_id", p.ClientID).Warn("Use of POST /token with arbitrary issuer and client_id is deprecated for security reasons. Please switch to using the API with provider only!")
allowed := false
if slices.Contains(config.External.AllowedIdTokenIssuers, p.Issuer) {
allowed = true
providerType = p.Issuer
acceptableClientIDs = []string{p.ClientID}
issuer = p.Issuer
}
if !allowed {
return nil, false, "", nil, false, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "Custom OIDC provider %q not allowed", p.Provider)
}
cfg = &conf.OAuthProviderConfiguration{
Enabled: true,
SkipNonceCheck: false,
}
}
if !cfg.Enabled {
return nil, false, "", nil, false, apierrors.NewBadRequestError(apierrors.ErrorCodeProviderDisabled, "Provider (issuer %q) is not enabled", issuer)
}
oidcCtx := ctx
if providerType == "apple" {
oidcCtx = oidc.InsecureIssuerURLContext(ctx, issuer)
}
oidcProvider, err := oidc.NewProvider(oidcCtx, issuer)
if err != nil {
return nil, false, "", nil, cfg.EmailOptional, err
}
return oidcProvider, cfg.SkipNonceCheck, providerType, acceptableClientIDs, cfg.EmailOptional, nil
}
// IdTokenGrant implements the id_token grant type flow
func (a *API) IdTokenGrant(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
log := observability.GetLogEntry(r).Entry
db := a.db.WithContext(ctx)
config := a.config
params := &IdTokenGrantParams{}
if err := retrieveRequestParams(r, params); err != nil {
return err
}
if params.IdToken == "" {
return apierrors.NewOAuthError("invalid request", "id_token required")
}
if params.Provider == "" && (params.ClientID == "" || params.Issuer == "") {
return apierrors.NewOAuthError("invalid request", "provider or client_id and issuer required")
}
if params.LinkIdentity {
if r.Header.Get("Authorization") == "" {
return apierrors.NewOAuthError("invalid request", "Linking requires a valid user access token in Authorization")
}
requireAuthCtx, err := a.requireAuthentication(w, r)
if err != nil {
return err
}
targetUser := getUser(requireAuthCtx)
if targetUser == nil {
return apierrors.NewOAuthError("invalid request", "Linking requires a valid user authentication")
}
// set it so linkIdentityToUser works below
ctx = withTargetUser(ctx, targetUser)
}
oidcProvider, skipNonceCheck, providerType, acceptableClientIDs, emailOptional, err := params.getProvider(ctx, config, r)
if err != nil {
return err
}
var oidcConfig *oidc.Config
if providerType == "apple" {
oidcConfig = &oidc.Config{
SkipClientIDCheck: true,
SkipIssuerCheck: true,
}
}
idToken, userData, err := provider.ParseIDToken(ctx, oidcProvider, oidcConfig, params.IdToken, provider.ParseIDTokenOptions{
SkipAccessTokenCheck: params.AccessToken == "",
AccessToken: params.AccessToken,
})
if err != nil {
return apierrors.NewOAuthError("invalid request", "Bad ID token").WithInternalError(err)
}
userData.Metadata.EmailVerified = false
for _, email := range userData.Emails {
if email.Primary {
userData.Metadata.Email = email.Email
userData.Metadata.EmailVerified = email.Verified
break
} else {
userData.Metadata.Email = email.Email
userData.Metadata.EmailVerified = email.Verified
}
}
if idToken.Subject == "" {
return apierrors.NewOAuthError("invalid request", "Missing sub claim in id_token")
}
correctAudience := false
for _, clientID := range acceptableClientIDs {
if clientID == "" {
continue
}
if slices.Contains(idToken.Audience, clientID) {
correctAudience = true
break
}
}
if !correctAudience {
return apierrors.NewOAuthError("invalid request", fmt.Sprintf("Unacceptable audience in id_token: %v", idToken.Audience))
}
if !skipNonceCheck {
tokenHasNonce := idToken.Nonce != ""
paramsHasNonce := params.Nonce != ""
if tokenHasNonce != paramsHasNonce {
return apierrors.NewOAuthError("invalid request", "Passed nonce and nonce in id_token should either both exist or not.")
} else if tokenHasNonce && paramsHasNonce {
// verify nonce to mitigate replay attacks
hash := fmt.Sprintf("%x", sha256.Sum256([]byte(params.Nonce)))
if hash != idToken.Nonce {
return apierrors.NewOAuthError("invalid nonce", "Nonces mismatch")
}
}
}
if params.AccessToken == "" {
if idToken.AccessTokenHash != "" {
log.Warn("ID token has a at_hash claim, but no access_token parameter was provided. In future versions, access_token will be mandatory as it's security best practice.")
}
} else {
if idToken.AccessTokenHash == "" {
log.Info("ID token does not have a at_hash claim, access_token parameter is unused.")
}
}
var createdUser bool
var token *AccessTokenResponse
var grantParams models.GrantParams
grantParams.FillGrantParams(r)
if !params.LinkIdentity {
if err := a.triggerBeforeUserCreatedExternal(r, db, userData, providerType); err != nil {
return err
}
}
var user *models.User
if err := db.Transaction(func(tx *storage.Connection) error {
var terr error
var decision models.AccountLinkingDecision
if params.LinkIdentity {
user, terr = a.linkIdentityToUser(r, ctx, tx, userData, providerType)
} else {
decision, user, terr = a.createAccountFromExternalIdentity(tx, r, userData, providerType, emailOptional)
}
createdUser = decision == models.CreateAccount
if terr != nil {
return terr
}
token, terr = a.issueRefreshToken(r, w.Header(), tx, user, models.OAuth, grantParams)
if terr != nil {
return terr
}
return nil
}); err != nil {
switch err.(type) {
case *storage.CommitWithError:
return err
case *HTTPError:
return err
default:
return apierrors.NewOAuthError("server_error", "Internal Server Error").WithInternalError(err)
}
}
if createdUser {
if err := a.triggerAfterUserCreated(r, db, user); err != nil {
return err
}
}
metering.RecordLogin(metering.LoginTypeOIDC, token.User.ID, &metering.LoginData{
Provider: providerType,
})
return sendJSON(w, http.StatusOK, token)
}