-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathauthDb.go
More file actions
464 lines (414 loc) · 12.2 KB
/
authDb.go
File metadata and controls
464 lines (414 loc) · 12.2 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package main
import (
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"time"
"github.com/go-webauthn/webauthn/webauthn"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
const (
bcryptCost = 12
// Settings keys for auth data
passwordHashSettingsKey = "passwordhash"
totpSecretSettingsKey = "totpsecret"
)
// Password functions
// hashPassword creates a bcrypt hash of the password
func hashPassword(password string) (string, error) {
if password == "" {
return "", nil
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
if err != nil {
return "", err
}
return string(hash), nil
}
// checkPasswordHash compares a password against a bcrypt hash
func checkPasswordHash(password, hash string) bool {
if hash == "" {
return false
}
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
}
// getPasswordHash returns the stored password hash from settings table
func (a *goBlog) getPasswordHash() (string, error) {
return a.getSettingValue(passwordHashSettingsKey)
}
// setPasswordHash stores the password hash in settings table
func (a *goBlog) setPasswordHash(hash string) error {
return a.saveSettingValue(passwordHashSettingsKey, hash)
}
// setPassword hashes and stores the password
func (a *goBlog) setPassword(password string) error {
hash, err := hashPassword(password)
if err != nil {
return err
}
return a.setPasswordHash(hash)
}
// checkPassword verifies the password against the stored hash
func (a *goBlog) checkPassword(password string) (bool, error) {
hash, err := a.getPasswordHash()
if err != nil {
return false, err
}
return checkPasswordHash(password, hash), nil
}
// hasPassword checks if a password has been set
func (a *goBlog) hasPassword() (bool, error) {
hash, err := a.getPasswordHash()
if err != nil {
return false, err
}
return hash != "", nil
}
// TOTP functions
// getTOTPSecret returns the stored TOTP secret from settings table
func (a *goBlog) getTOTPSecret() (string, error) {
return a.getSettingValue(totpSecretSettingsKey)
}
// setTOTPSecret stores the TOTP secret in settings table
func (a *goBlog) setTOTPSecret(secret string) error {
return a.saveSettingValue(totpSecretSettingsKey, secret)
}
// hasTOTP checks if TOTP is configured
func (a *goBlog) hasTOTP() (bool, error) {
secret, err := a.getTOTPSecret()
if err != nil {
return false, err
}
return secret != "", nil
}
// deleteTOTP removes the TOTP secret
func (a *goBlog) deleteTOTP() error {
return a.setTOTPSecret("")
}
// Passkey (WebAuthn) functions
// passkey represents a stored WebAuthn credential
type passkey struct {
ID string `json:"id"`
Name string `json:"name"`
Credential string `json:"credential"`
Created time.Time `json:"created"`
}
// getPasskeys returns all stored passkeys
func (a *goBlog) getPasskeys() ([]*passkey, error) {
rows, err := a.db.Query("select id, name, credential, created from passkeys order by created desc")
if err != nil {
return nil, err
}
defer rows.Close()
var passkeys []*passkey
for rows.Next() {
var pk passkey
var createdUnix int64
err = rows.Scan(&pk.ID, &pk.Name, &pk.Credential, &createdUnix)
if err != nil {
return nil, err
}
pk.Created = time.Unix(createdUnix, 0)
passkeys = append(passkeys, &pk)
}
if err = rows.Err(); err != nil {
return nil, err
}
return passkeys, nil
}
// getPasskey returns a specific passkey by ID
func (a *goBlog) getPasskey(id string) (*passkey, error) {
row, err := a.db.QueryRow("select id, name, credential, created from passkeys where id = @id", sql.Named("id", id))
if err != nil {
return nil, err
}
var pk passkey
var createdUnix int64
err = row.Scan(&pk.ID, &pk.Name, &pk.Credential, &createdUnix)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
pk.Created = time.Unix(createdUnix, 0)
return &pk, nil
}
// savePasskey stores a new passkey or updates an existing one
func (a *goBlog) savePasskey(id, name string, cred *webauthn.Credential) error {
credBytes, err := json.Marshal(cred)
if err != nil {
return err
}
_, err = a.db.Exec(
`insert into passkeys (id, name, credential, created) values (@id, @name, @credential, @created)
on conflict (id) do update set name = @name, credential = @credential`,
sql.Named("id", id),
sql.Named("name", name),
sql.Named("credential", string(credBytes)),
sql.Named("created", time.Now().Unix()),
)
return err
}
// renamePasskey updates the name of a passkey
func (a *goBlog) renamePasskey(id, name string) error {
_, err := a.db.Exec(
"update passkeys set name = @name where id = @id",
sql.Named("id", id),
sql.Named("name", name),
)
return err
}
// deletePasskey removes a passkey by ID
func (a *goBlog) deletePasskeyByID(id string) error {
_, err := a.db.Exec("delete from passkeys where id = @id", sql.Named("id", id))
return err
}
// hasPasskeys checks if any passkeys are registered
func (a *goBlog) hasPasskeys() (bool, error) {
row, err := a.db.QueryRow("select count(*) from passkeys")
if err != nil {
return false, err
}
var count int
err = row.Scan(&count)
return count > 0, err
}
// getWebAuthnCredentials returns all WebAuthn credentials for authentication
func (a *goBlog) getWebAuthnCredentials() ([]webauthn.Credential, error) {
passkeys, err := a.getPasskeys()
if err != nil {
return nil, err
}
var creds []webauthn.Credential
for _, pk := range passkeys {
var cred webauthn.Credential
if err := json.Unmarshal([]byte(pk.Credential), &cred); err != nil {
continue // Skip invalid credentials
}
creds = append(creds, cred)
}
return creds, nil
}
// App Password functions
// appPassword represents a stored app password
type appPassword struct {
ID string `json:"id"`
Name string `json:"name"`
Created time.Time `json:"created"`
}
// generateAppPassword creates a secure random app password
func generateAppPassword() (string, error) {
return generateSecurePassword(40)
}
// getAppPasswords returns all stored app passwords
func (a *goBlog) getAppPasswords() ([]*appPassword, error) {
rows, err := a.db.Query("select id, name, created from app_passwords order by created desc")
if err != nil {
return nil, err
}
defer rows.Close()
var passwords []*appPassword
for rows.Next() {
var ap appPassword
var createdUnix int64
err = rows.Scan(&ap.ID, &ap.Name, &createdUnix)
if err != nil {
return nil, err
}
ap.Created = time.Unix(createdUnix, 0)
passwords = append(passwords, &ap)
}
if err = rows.Err(); err != nil {
return nil, err
}
return passwords, nil
}
// getAppPasswordHashes returns all stored app password hashes
func (a *goBlog) getAppPasswordHashes() ([]string, error) {
rows, err := a.db.Query("select hash from app_passwords")
if err != nil {
return nil, err
}
defer rows.Close()
var hashes []string
for rows.Next() {
var hash string
err = rows.Scan(&hash)
if err != nil {
return nil, err
}
hashes = append(hashes, hash)
}
if err = rows.Err(); err != nil {
return nil, err
}
return hashes, nil
}
// createAppPassword creates a new app password and returns the plaintext password (only shown once)
func (a *goBlog) createAppPassword(name string) (id, password string, err error) {
id = uuid.NewString()
password, err = generateAppPassword()
if err != nil {
return "", "", err
}
hash, err := hashPassword(password)
if err != nil {
return "", "", err
}
_, err = a.db.Exec(
"insert into app_passwords (id, name, hash, created) values (@id, @name, @hash, @created)",
sql.Named("id", id),
sql.Named("name", name),
sql.Named("hash", hash),
sql.Named("created", time.Now().Unix()),
)
if err != nil {
return "", "", err
}
return id, password, nil
}
// checkAppPassword verifies a password against stored app passwords
func (a *goBlog) checkAppPassword(password string) (bool, error) {
passwordHashes, err := a.getAppPasswordHashes()
if err != nil {
return false, err
}
for _, hash := range passwordHashes {
if checkPasswordHash(password, hash) {
return true, nil
}
}
return false, nil
}
// deleteAppPassword removes an app password by ID
func (a *goBlog) deleteAppPassword(id string) error {
_, err := a.db.Exec("delete from app_passwords where id = @id", sql.Named("id", id))
return err
}
// Auth migration functions
const authMigratedSettingsKey = "auth_migrated"
// isAuthMigrated checks if auth has been migrated from config to database
func (a *goBlog) isAuthMigrated() bool {
migrated, _ := a.getBooleanSettingValue(authMigratedSettingsKey, false)
return migrated
}
// setAuthMigrated marks that auth has been migrated from config to database
func (a *goBlog) setAuthMigrated() error {
return a.saveBooleanSettingValue(authMigratedSettingsKey, true)
}
// hasDeprecatedConfig checks if deprecated auth config options are still present
func (a *goBlog) hasDeprecatedConfig() bool {
return a.cfg.User.Password != "" || a.cfg.User.TOTP != "" || len(a.cfg.User.AppPasswords) > 0
}
// generateInitialPassword generates a secure random password for first-time setup
func generateInitialPassword() (string, error) {
return generateSecurePassword(20)
}
// migrateAuthFromConfig migrates authentication data from config to database
func (a *goBlog) migrateAuthFromConfig(logging bool) error {
if a.isAuthMigrated() {
return nil // Already migrated
}
// Migrate password if set in config, or generate a new one on first run
hasPwd, _ := a.hasPassword()
if !hasPwd {
if a.cfg.User.Password != "" {
// Migrate password from config
if err := a.setPassword(a.cfg.User.Password); err != nil {
return err
}
if logging {
a.info("Migrated password from config to database")
}
} else {
// Generate a secure initial password on first run
initialPassword, err := generateInitialPassword()
if err != nil {
return err
}
if err := a.setPassword(initialPassword); err != nil {
return err
}
if logging {
a.info("Generated initial password for first-time setup. Please change it via Settings or CLI.",
"username", a.cfg.User.Nick,
"password", initialPassword,
)
}
}
}
// Migrate TOTP if set in config
if a.cfg.User.TOTP != "" {
hasTOTP, _ := a.hasTOTP()
if !hasTOTP {
if err := a.setTOTPSecret(a.cfg.User.TOTP); err != nil {
return err
}
if logging {
a.info("Migrated TOTP from config to database")
}
}
}
// Migrate app passwords if set in config
for _, apw := range a.cfg.User.AppPasswords {
hash, err := hashPassword(apw.Password)
if err != nil {
return err
}
_, err = a.db.Exec(
"insert into app_passwords (id, name, hash, created) values (@id, @name, @hash, @created)",
sql.Named("id", uuid.NewString()),
sql.Named("name", apw.Username),
sql.Named("hash", hash),
sql.Named("created", time.Now().Unix()),
)
if err != nil {
return err
}
if logging {
a.info("Migrated app password from config to database", "name", apw.Username)
}
}
// Migrate legacy passkey to new passkeys table
if err := a.migrateLegacyPasskey(); err != nil {
a.error("Failed to migrate legacy passkey", "err", err)
}
// Mark as migrated
return a.setAuthMigrated()
}
// migrateLegacyPasskey migrates the old single passkey from settings to the new passkeys table
func (a *goBlog) migrateLegacyPasskey() error {
// Check if there's a legacy passkey
jsonStr, err := a.getSettingValue(webauthnCredSettingsKey)
if err != nil || jsonStr == "" {
return nil // No legacy passkey to migrate
}
// Check if passkeys table already has entries
hasPasskeys, _ := a.hasPasskeys()
if hasPasskeys {
// Already have passkeys, just delete the legacy one
if err := a.deleteSettingValue(webauthnCredSettingsKey); err != nil {
a.error("Failed to delete legacy passkey setting", "err", err)
}
return nil
}
// Parse the legacy credential
var cred webauthn.Credential
if err := json.Unmarshal([]byte(jsonStr), &cred); err != nil {
return err
}
// Create a new passkey from the legacy credential
passkeyID := base64.RawURLEncoding.EncodeToString(cred.ID)
if err := a.savePasskey(passkeyID, "Passkey", &cred); err != nil {
return err
}
// Delete the legacy setting
if err := a.deleteSettingValue(webauthnCredSettingsKey); err != nil {
a.error("Failed to delete legacy passkey setting after migration", "err", err)
}
a.info("Migrated legacy passkey to new passkeys table")
return nil
}