-
Notifications
You must be signed in to change notification settings - Fork 657
Expand file tree
/
Copy pathpasskey_registration.go
More file actions
227 lines (189 loc) · 8.41 KB
/
passkey_registration.go
File metadata and controls
227 lines (189 loc) · 8.41 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
package api
import (
"encoding/json"
"net/http"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/gofrs/uuid"
"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/storage"
"github.com/supabase/auth/internal/utilities"
)
// PasskeyRegistrationOptionsParams is the request body for POST /passkeys/registration/options.
type PasskeyRegistrationOptionsParams struct{}
// PasskeyRegistrationOptionsResponse is the response body for POST /passkeys/registration/options.
type PasskeyRegistrationOptionsResponse struct {
ChallengeID string `json:"challenge_id"`
Options *protocol.PublicKeyCredentialCreationOptions `json:"options"`
ExpiresAt int64 `json:"expires_at"`
}
// PasskeyRegistrationVerifyParams is the request body for POST /passkeys/registration/verify.
type PasskeyRegistrationVerifyParams struct {
ChallengeID string `json:"challenge_id"`
Credential json.RawMessage `json:"credential"`
}
// PasskeyMetadataResponse is the response body for successful passkey creation.
type PasskeyMetadataResponse struct {
ID string `json:"id"`
FriendlyName string `json:"friendly_name,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// PasskeyRegistrationOptions handles POST /passkeys/registration/options.
// Requires authentication. Generates WebAuthn registration options for adding a passkey to an existing account.
func (a *API) PasskeyRegistrationOptions(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
config := a.config
user := getUser(ctx)
db := a.db.WithContext(ctx)
if user.IsSSOUser {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeValidationFailed, "SSO users cannot register passkeys")
}
// Check passkey limit
count, err := models.CountWebAuthnCredentialsByUserID(db, user.ID)
if err != nil {
return apierrors.NewInternalServerError("Database error counting passkeys").WithInternalError(err)
}
if count >= config.Passkey.MaxPasskeysPerUser {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeTooManyPasskeys, "Maximum number of passkeys reached")
}
// Load existing passkeys to build exclusion list
existingCreds, err := models.FindWebAuthnCredentialsByUserID(db, user.ID)
if err != nil {
return apierrors.NewInternalServerError("Database error loading passkeys").WithInternalError(err)
}
excludeList := make([]protocol.CredentialDescriptor, len(existingCreds))
for i, cred := range existingCreds {
excludeList[i] = protocol.CredentialDescriptor{
Type: protocol.PublicKeyCredentialType,
CredentialID: cred.CredentialID,
}
}
webAuthn, err := a.getPasskeyWebAuthn()
if err != nil {
return apierrors.NewInternalServerError("Failed to initialize WebAuthn").WithInternalError(err)
}
webAuthnUser := newWebAuthnUser(user, existingCreds)
options, session, err := webAuthn.BeginRegistration(webAuthnUser, webauthn.WithExclusions(excludeList))
if err != nil {
return apierrors.NewInternalServerError("Failed to generate WebAuthn registration options").WithInternalError(err)
}
expiresAt := time.Now().Add(config.WebAuthn.ChallengeExpiryDuration)
challenge := models.NewWebAuthnChallenge(
&user.ID,
models.WebAuthnChallengeTypeRegistration,
&models.WebAuthnSessionData{SessionData: session},
expiresAt,
)
if err := db.Create(challenge); err != nil {
return apierrors.NewInternalServerError("Database error storing challenge").WithInternalError(err)
}
return sendJSON(w, http.StatusOK, &PasskeyRegistrationOptionsResponse{
ChallengeID: challenge.ID.String(),
Options: &options.Response,
ExpiresAt: expiresAt.Unix(),
})
}
// PasskeyRegistrationVerify handles POST /passkeys/registration/verify.
// Requires authentication. Verifies the WebAuthn credential and creates a passkey for the authenticated user.
func (a *API) PasskeyRegistrationVerify(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
config := a.config
user := getUser(ctx)
db := a.db.WithContext(ctx)
if user.IsSSOUser {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeValidationFailed, "SSO users cannot register passkeys")
}
params := &PasskeyRegistrationVerifyParams{}
body, err := utilities.GetBodyBytes(r)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeBadJSON, "Could not read request body")
}
if err := json.Unmarshal(body, params); err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeBadJSON, "Could not parse request body as JSON: %v", err)
}
if params.ChallengeID == "" {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "challenge_id is required")
}
if params.Credential == nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "credential is required")
}
challengeID, err := uuid.FromString(params.ChallengeID)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "challenge_id must be a valid UUID")
}
// Atomically consume the challenge to prevent replay/race conditions
challenge, err := models.ConsumeWebAuthnChallengeByID(db, challengeID, models.WebAuthnChallengeTypeRegistration, &user.ID)
if err != nil {
if models.IsNotFoundError(err) {
return apierrors.NewBadRequestError(apierrors.ErrorCodeWebAuthnChallengeNotFound, "Challenge not found or already used")
}
return apierrors.NewInternalServerError("Database error consuming challenge").WithInternalError(err)
}
if challenge.IsExpired() {
return apierrors.NewBadRequestError(apierrors.ErrorCodeWebAuthnChallengeExpired, "Challenge has expired")
}
// Parse the credential creation response from the JSON params
parsedResponse, err := parseCredentialCreationResponse(params.Credential)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeWebAuthnVerificationFailed, "Invalid credential response").WithInternalError(err)
}
webAuthn, err := a.getPasskeyWebAuthn()
if err != nil {
return apierrors.NewInternalServerError("Failed to initialize WebAuthn").WithInternalError(err)
}
// Load existing passkeys for the user adapter
existingCreds, err := models.FindWebAuthnCredentialsByUserID(db, user.ID)
if err != nil {
return apierrors.NewInternalServerError("Database error loading passkeys").WithInternalError(err)
}
webAuthnUser := newWebAuthnUser(user, existingCreds)
sessionData := *challenge.SessionData.SessionData
credential, err := webAuthn.CreateCredential(webAuthnUser, sessionData, parsedResponse)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeWebAuthnVerificationFailed, "Credential verification failed").WithInternalError(err)
}
friendlyName := utilities.PasskeyFriendlyName(credential.Authenticator.AAGUID)
passkeyCredential := models.NewWebAuthnCredential(user.ID, credential, friendlyName)
err = db.Transaction(func(tx *storage.Connection) error {
count, terr := models.CountWebAuthnCredentialsByUserID(tx, user.ID)
if terr != nil {
return terr
}
if count >= config.Passkey.MaxPasskeysPerUser {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeTooManyPasskeys, "Maximum number of passkeys reached")
}
if terr := tx.Create(passkeyCredential); terr != nil {
if models.IsUniqueConstraintViolatedError(terr) {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeWebAuthnCredentialExists, "This credential is already registered")
}
return terr
}
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.PasskeyCreatedAction, map[string]any{
"passkey_id": passkeyCredential.ID,
}); terr != nil {
return terr
}
return nil
})
if err != nil {
if httpErr, ok := err.(*apierrors.HTTPError); ok {
return httpErr
}
return apierrors.NewInternalServerError("Database error creating passkey").WithInternalError(err)
}
return sendJSON(w, http.StatusOK, &PasskeyMetadataResponse{
ID: passkeyCredential.ID.String(),
FriendlyName: passkeyCredential.FriendlyName,
CreatedAt: passkeyCredential.CreatedAt,
})
}
// parseCredentialCreationResponse parses a WebAuthn credential creation response from raw JSON.
func parseCredentialCreationResponse(raw json.RawMessage) (*protocol.ParsedCredentialCreationData, error) {
var ccr protocol.CredentialCreationResponse
if err := json.Unmarshal(raw, &ccr); err != nil {
return nil, err
}
return ccr.Parse()
}