-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
378 lines (332 loc) · 9.74 KB
/
middleware.go
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
366
367
368
369
370
371
372
373
374
375
376
377
378
package webauthn
import (
"bytes"
"encoding/base64"
"io"
"log"
"net/http"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/gofiber/fiber/v2"
)
type Middleware struct {
config Config
webAuthn *webauthn.WebAuthn
sessions SessionStore
credentials CredentialStore
}
// New creates a new WebAuthn middleware instance
func New(config Config) *Middleware {
// Set default values
config.setDefaults()
// Validate configuration
if err := config.validate(); err != nil {
panic(err)
}
// Initialize WebAuthn with config
w, err := webauthn.New(&webauthn.Config{
RPDisplayName: config.RPDisplayName,
RPID: config.RPID,
RPOrigins: config.RPOrigins,
})
if err != nil {
panic(err)
}
return &Middleware{
config: config,
webAuthn: w,
sessions: NewDefaultSessionStore(),
credentials: config.CredentialStore,
}
}
// BeginRegistration returns a handler for starting the registration process
func (m *Middleware) BeginRegistration() fiber.Handler {
return func(c *fiber.Ctx) error {
// Get user info from request
var req struct {
UserID string `json:"userId"`
Username string `json:"username,omitempty"`
DisplayName string `json:"displayName,omitempty"`
}
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "invalid request body",
})
}
// Create WebAuthn user
user := NewWebAuthnUser(req.UserID, req.Username, req.DisplayName)
// Get existing credentials
existingCreds, err := m.credentials.GetCredentialsByUser(req.UserID)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "failed to get existing credentials",
})
}
// Convert to WebAuthn credentials
var webAuthnCreds []webauthn.Credential
for _, cred := range existingCreds {
webAuthnCreds = append(webAuthnCreds, webauthn.Credential{
ID: cred.ID,
PublicKey: cred.PublicKey,
AttestationType: cred.AttestationType,
Transport: nil,
})
}
user.credentials = webAuthnCreds
// Create registration options
options, sessionData, err := m.webAuthn.BeginRegistration(
user,
webauthn.WithAuthenticatorSelection(protocol.AuthenticatorSelection{
AuthenticatorAttachment: m.config.AuthenticatorAttachment,
UserVerification: m.config.UserVerification,
}),
)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": err.Error(),
})
}
// Store session data
sessionID := generateSessionID()
err = m.sessions.StoreSession(sessionID, &SessionData{
UserID: req.UserID,
Challenge: sessionData.Challenge,
SessionData: *sessionData,
ExpiresAt: time.Now().Add(m.config.Timeout),
})
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "failed to store session",
})
}
// Set session cookie
c.Cookie(&fiber.Cookie{
Name: "webauthn_session",
Value: sessionID,
HTTPOnly: true,
Secure: true,
SameSite: "Strict",
MaxAge: int(m.config.Timeout.Seconds()),
})
return c.JSON(options)
}
}
// FinishRegistration completes the registration ceremony
func (m *Middleware) FinishRegistration() fiber.Handler {
return func(c *fiber.Ctx) error {
// Get session from cookie
sessionID := c.Cookies("webauthn_session")
if sessionID == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "no session found",
})
}
// Get session data
session, err := m.sessions.GetSession(sessionID)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": err.Error(),
})
}
// Create WebAuthn user
user := NewWebAuthnUser(session.UserID, "", "") // Names not needed for finish
// For registration
httpReq := &http.Request{
Method: "POST",
Body: io.NopCloser(bytes.NewReader(c.Body())),
}
credential, err := m.webAuthn.FinishRegistration(user, session.SessionData, httpReq)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": err.Error(),
})
}
// Store the credential
newCred := &Credential{
ID: credential.ID,
PublicKey: credential.PublicKey,
AttestationType: credential.AttestationType,
AAGUID: credential.Authenticator.AAGUID,
SignCount: credential.Authenticator.SignCount,
CreatedAt: time.Now(),
LastUsedAt: time.Now(),
}
if err := m.credentials.StoreCredential(session.UserID, newCred); err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "failed to store credential",
})
}
// Clean up session
if err := m.sessions.DeleteSession(sessionID); err != nil {
// Log error but don't fail the request
log.Printf("Failed to delete session: %v", err)
}
// Remove session cookie
c.Cookie(&fiber.Cookie{
Name: "webauthn_session",
Value: "",
Expires: time.Now().Add(-time.Hour),
HTTPOnly: true,
Secure: true,
SameSite: "Strict",
})
return c.JSON(fiber.Map{
"status": "success",
"credential": fiber.Map{
"id": base64.URLEncoding.EncodeToString(credential.ID),
"type": "public-key",
"aaguid": base64.URLEncoding.EncodeToString(credential.Authenticator.AAGUID),
"signCount": credential.Authenticator.SignCount,
},
})
}
}
// BeginAuthentication initiates the authentication ceremony
func (m *Middleware) BeginAuthentication() fiber.Handler {
return func(c *fiber.Ctx) error {
// Get user info from request
var req struct {
UserID string `json:"userId"`
}
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "invalid request body",
})
}
// Get user's credentials
creds, err := m.credentials.GetCredentialsByUser(req.UserID)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "failed to get user credentials",
})
}
if len(creds) == 0 {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "no credentials found for user",
})
}
// Create WebAuthn user
user := NewWebAuthnUser(req.UserID, "", "")
// Convert to WebAuthn credentials
var webAuthnCreds []webauthn.Credential
for _, cred := range creds {
webAuthnCreds = append(webAuthnCreds, webauthn.Credential{
ID: cred.ID,
PublicKey: cred.PublicKey,
AttestationType: cred.AttestationType,
Transport: nil,
})
}
user.credentials = webAuthnCreds
// Begin authentication
options, sessionData, err := m.webAuthn.BeginLogin(user)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": err.Error(),
})
}
// Store session data
sessionID := generateSessionID()
err = m.sessions.StoreSession(sessionID, &SessionData{
UserID: req.UserID,
Challenge: sessionData.Challenge,
SessionData: *sessionData,
ExpiresAt: time.Now().Add(m.config.Timeout),
})
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "failed to store session",
})
}
// Set session cookie
c.Cookie(&fiber.Cookie{
Name: "webauthn_session",
Value: sessionID,
HTTPOnly: true,
Secure: true,
SameSite: "Strict",
MaxAge: int(m.config.Timeout.Seconds()),
})
return c.JSON(options)
}
}
// FinishAuthentication completes the authentication ceremony
func (m *Middleware) FinishAuthentication() fiber.Handler {
return func(c *fiber.Ctx) error {
// Get session from cookie
sessionID := c.Cookies("webauthn_session")
if sessionID == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "no session found",
})
}
// Get session data
session, err := m.sessions.GetSession(sessionID)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": err.Error(),
})
}
// Create WebAuthn user
user := NewWebAuthnUser(session.UserID, "", "")
// Get user's credentials
creds, err := m.credentials.GetCredentialsByUser(session.UserID)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "failed to get user credentials",
})
}
// Convert to WebAuthn credentials
var webAuthnCreds []webauthn.Credential
for _, cred := range creds {
webAuthnCreds = append(webAuthnCreds, webauthn.Credential{
ID: cred.ID,
PublicKey: cred.PublicKey,
AttestationType: cred.AttestationType,
Transport: nil,
})
}
user.credentials = webAuthnCreds
// For authentication
httpReq := &http.Request{
Method: "POST",
Body: io.NopCloser(bytes.NewReader(c.Body())),
}
credential, err := m.webAuthn.FinishLogin(user, session.SessionData, httpReq)
if err != nil {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": err.Error(),
})
}
// Update credential sign count
for _, cred := range creds {
if bytes.Equal(cred.ID, credential.ID) {
cred.SignCount = credential.Authenticator.SignCount
cred.LastUsedAt = time.Now()
if err := m.credentials.UpdateCredential(cred); err != nil {
log.Printf("Failed to update credential: %v", err)
}
break
}
}
// Clean up session
if err := m.sessions.DeleteSession(sessionID); err != nil {
log.Printf("Failed to delete session: %v", err)
}
// Remove session cookie
c.Cookie(&fiber.Cookie{
Name: "webauthn_session",
Value: "",
Expires: time.Now().Add(-time.Hour),
HTTPOnly: true,
Secure: true,
SameSite: "Strict",
})
return c.JSON(fiber.Map{
"status": "success",
"user": session.UserID,
})
}
}
// Similar handlers for FinishRegistration, BeginAuthentication, and FinishAuthentication...