Debian Codegraph @

user/manager.go

raw
1 // Package user deals with authentication and authorization against topics
2 package user
3
4 import (
5 "crypto/subtle"
6 "database/sql"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "net/netip"
11 "slices"
12 "strings"
13 "sync"
14 "time"
15
16 "golang.org/x/crypto/bcrypt"
17 "heckel.io/ntfy/v2/db"
18 "heckel.io/ntfy/v2/log"
19 "heckel.io/ntfy/v2/payments"
20 "heckel.io/ntfy/v2/util"
21 )
22
23 const (
24 tierIDPrefix = "ti_"
25 tierIDLength = 8
26 syncTopicPrefix = "st_"
27 syncTopicLength = 16
28 userIDPrefix = "u_"
29 userIDLength = 12
30 userAuthIntentionalSlowDownHash = "$2a$10$YFCQvqQDwIIwnJM1xkAYOeih0dg17UVGanaTStnrSzC8NCWxcLDwy" // Cost should match DefaultUserPasswordBcryptCost
31 userHardDeleteAfterDuration = 7 * 24 * time.Hour
32 tokenPrefix = "tk_"
33 tokenLength = 32
34 tokenMaxCount = 60 // Only keep this many tokens in the table per user
35 tag = "user_manager"
36 schemaStore = "user" // Store name in the schema_version table (see db/schema)
37 )
38
39 // Default constants that may be overridden by configs
40 const (
41 DefaultUserStatsQueueWriterInterval = 33 * time.Second
42 DefaultUserPasswordBcryptCost = 10
43 DefaultAccessCacheEnabled = false
44 DefaultAccessCacheReloadInterval = 87 * time.Second
45 DefaultExpiredMagicLinkReapInterval = time.Hour // How often expired email-verify/password-reset links are swept
46 )
47
48 var (
49 errNoTokenProvided = errors.New("no token provided")
50 errTopicOwnedByOthers = errors.New("topic owned by others")
51 errNoRows = errors.New("no rows found")
52 )
53
54 // Manager handles user authentication, authorization, and management
55 type Manager struct {
56 config *Config
57 db *db.DB
58 queries queries
59 statsQueue map[string]*Stats // "Queue" to asynchronously write user stats to the database (UserID -> Stats)
60 tokenQueue map[string]*TokenUpdate // "Queue" to asynchronously write token access stats to the database (Token ID -> TokenUpdate)
61 accessCache *accessCache // In-memory snapshot of user_access; refreshed by maybeReloadAccessCache after every ACL mutation
62 quit chan struct{} // Closed by Close() to signal background goroutines to stop
63 mu sync.Mutex
64 }
65
66 var _ Auther = (*Manager)(nil)
67
68 func newManager(d *db.DB, queries queries, config *Config) (*Manager, error) {
69 if config.BcryptCost <= 0 {
70 config.BcryptCost = DefaultUserPasswordBcryptCost
71 }
72 if config.QueueWriterInterval.Seconds() <= 0 {
73 config.QueueWriterInterval = DefaultUserStatsQueueWriterInterval
74 }
75 if config.AccessCacheReloadInterval <= 0 {
76 config.AccessCacheReloadInterval = DefaultAccessCacheReloadInterval
77 }
78 if config.ExpiredMagicLinkReapInterval <= 0 {
79 config.ExpiredMagicLinkReapInterval = DefaultExpiredMagicLinkReapInterval
80 }
81 manager := &Manager{
82 config: config,
83 db: d,
84 statsQueue: make(map[string]*Stats),
85 tokenQueue: make(map[string]*TokenUpdate),
86 quit: make(chan struct{}),
87 queries: queries,
88 }
89 if err := manager.maybeProvisionUsersAccessAndTokens(); err != nil {
90 return nil, err
91 }
92 if config.AccessCacheEnabled {
93 manager.accessCache = newAccessCache()
94 if err := manager.maybeReloadAccessCache(); err != nil {
95 return nil, err
96 }
97 go manager.asyncAccessCacheReloadLoop(manager.config.AccessCacheReloadInterval)
98 }
99 go manager.asyncQueueWriteLoop(manager.config.QueueWriterInterval)
100 go manager.asyncExpiredMagicLinkReapLoop(manager.config.ExpiredMagicLinkReapInterval)
101 return manager, nil
102 }
103
104 // maybeReloadAccessCache refreshes the in-memory access cache from the
105 // primary database. No-op when the cache is disabled. With no usernames it
106 // does a full bulk reload; with one or more it refreshes only those users'
107 // slices in a single DB round-trip via an IN clause.
108 func (a *Manager) maybeReloadAccessCache(usernames ...string) error {
109 if a.accessCache == nil {
110 return nil
111 }
112 if len(usernames) == 0 {
113 return a.accessCache.Reload(a.db, a.queries.selectAccessCacheAll)
114 }
115 return a.accessCache.Reload(a.db, a.queries.selectAccessCacheUsers(len(usernames)), usernames...)
116 }
117
118 // asyncAccessCacheReloadLoop periodically bulk-reloads the access cache so that
119 // writes made by other processes against the same database (most notably the
120 // `ntfy access` CLI subcommand running while a server holds the cache) become
121 // visible within the configured interval. This Manager's own mutations do
122 // not depend on the poller -- they refresh affected users synchronously.
123 func (a *Manager) asyncAccessCacheReloadLoop(interval time.Duration) {
124 ticker := time.NewTicker(interval)
125 defer ticker.Stop()
126 for {
127 select {
128 case <-a.quit:
129 return
130 case <-ticker.C:
131 if err := a.maybeReloadAccessCache(); err != nil {
132 log.Tag(tag).Err(err).Warn("Reloading ACL cache failed")
133 }
134 }
135 }
136 }
137
138 // asyncExpiredMagicLinkReapLoop periodically deletes expired email-verification and
139 // password-reset links so the user_magic_link table does not accumulate dead rows. Expiry is
140 // already enforced on read, so this is housekeeping only; it replaces the old in-memory
141 // expireLoop that lived in mail.Sender.
142 func (a *Manager) asyncExpiredMagicLinkReapLoop(interval time.Duration) {
143 ticker := time.NewTicker(interval)
144 defer ticker.Stop()
145 for {
146 select {
147 case <-a.quit:
148 return
149 case <-ticker.C:
150 if err := a.deleteExpiredMagicLinks(); err != nil {
151 log.Tag(tag).Err(err).Warn("Reaping expired magic links failed")
152 }
153 }
154 }
155 }
156
157 // Authenticate checks a login identifier (a username or a verified primary email) and password, and
158 // returns a User if correct and not marked as deleted. The identifier is resolved in a single query
159 // via userByNameOrEmail, so a user can log in with either their username or their primary
160 // email. The method returns in constant-ish time (one query, one bcrypt compare), regardless of
161 // whether the identifier exists or the password is correct or incorrect.
162 func (a *Manager) Authenticate(identifier, password string) (*User, error) {
163 if identifier == Everyone {
164 return nil, ErrUnauthenticated
165 }
166 user, err := a.userByNameOrEmail(identifier)
167 if err != nil {
168 log.Tag(tag).Field("user_name", identifier).Err(err).Trace("Authentication of user failed (1)")
169 bcrypt.CompareHashAndPassword([]byte(userAuthIntentionalSlowDownHash), []byte("intentional slow-down to avoid timing attacks"))
170 return nil, ErrUnauthenticated
171 } else if user.Deleted {
172 log.Tag(tag).Field("user_name", identifier).Trace("Authentication of user failed (2): user marked deleted")
173 bcrypt.CompareHashAndPassword([]byte(userAuthIntentionalSlowDownHash), []byte("intentional slow-down to avoid timing attacks"))
174 return nil, ErrUnauthenticated
175 } else if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password)); err != nil {
176 log.Tag(tag).Field("user_name", identifier).Err(err).Trace("Authentication of user failed (3)")
177 return nil, ErrUnauthenticated
178 }
179 return user, nil
180 }
181
182 // AuthenticateToken checks if the token exists and returns the associated User if it does.
183 // The method sets the User.Token value to the token that was used for authentication.
184 func (a *Manager) AuthenticateToken(token string) (*User, error) {
185 if len(token) != tokenLength {
186 return nil, ErrUnauthenticated
187 }
188 user, err := a.userByToken(token)
189 if err != nil {
190 log.Tag(tag).Field("token", token).Err(err).Trace("Authentication of token failed")
191 return nil, ErrUnauthenticated
192 }
193 user.Token = token
194 return user, nil
195 }
196
197 // AddUser adds a user with the given username, password and role
198 func (a *Manager) AddUser(username, password string, role Role, hashed bool) error {
199 hash, err := a.maybeHashPassword(password, hashed)
200 if err != nil {
201 return err
202 }
203 return db.ExecTx(a.db, func(tx *sql.Tx) error {
204 return a.addUserTx(tx, username, hash, role, false)
205 })
206 }
207
208 // addUserTx adds a user with the given username, password hash and role to the database
209 func (a *Manager) addUserTx(tx *sql.Tx, username, hash string, role Role, provisioned bool) error {
210 if !AllowedUsername(username) || !AllowedRole(role) {
211 return ErrInvalidArgument
212 }
213 userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
214 syncTopic := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength)
215 now := time.Now().Unix()
216 if _, err := tx.Exec(a.queries.insertUser, userID, username, hash, string(role), syncTopic, provisioned, now); err != nil {
217 if isUniqueConstraintError(err) {
218 return ErrUserExists
219 }
220 return err
221 }
222 return nil
223 }
224
225 // RemoveUser deletes the user with the given username. The function returns nil on success, even
226 // if the user did not exist in the first place.
227 func (a *Manager) RemoveUser(username string) error {
228 if err := a.CanChangeUser(username); err != nil {
229 return err
230 }
231 err := db.ExecTx(a.db, func(tx *sql.Tx) error {
232 return a.removeUserTx(tx, username)
233 })
234 if err != nil {
235 return err
236 }
237 // Reload user-specific parts of the access cache
238 return a.maybeReloadAccessCache(username, Everyone)
239 }
240
241 // removeUserTx deletes the user with the given username
242 func (a *Manager) removeUserTx(tx *sql.Tx, username string) error {
243 if !AllowedUsername(username) {
244 return ErrInvalidArgument
245 }
246 // Rows in user_access, user_token, etc. are deleted via foreign keys
247 if _, err := tx.Exec(a.queries.deleteUser, username); err != nil {
248 return err
249 }
250 return nil
251 }
252
253 // MarkUserRemoved sets the deleted flag on the user, and deletes all access tokens. This prevents
254 // successful auth via Authenticate. A background process will delete the user at a later date.
255 func (a *Manager) MarkUserRemoved(user *User) error {
256 if !AllowedUsername(user.Name) {
257 return ErrInvalidArgument
258 }
259 err := db.ExecTx(a.db, func(tx *sql.Tx) error {
260 if err := a.resetUserAccessTx(tx, user.Name); err != nil {
261 return err
262 }
263 if _, err := tx.Exec(a.queries.deleteAllToken, user.ID); err != nil {
264 return err
265 }
266 deletedTime := time.Now().Add(userHardDeleteAfterDuration).Unix()
267 if _, err := tx.Exec(a.queries.updateUserDeleted, deletedTime, user.ID); err != nil {
268 return err
269 }
270 return nil
271 })
272 if err != nil {
273 return err
274 }
275 // Reload user-specific parts of the access cache
276 return a.maybeReloadAccessCache(user.Name, Everyone)
277 }
278
279 // RemoveDeletedUsers deletes all users that have been marked deleted
280 func (a *Manager) RemoveDeletedUsers() error {
281 res, err := a.db.Exec(a.queries.deleteUsersMarked, time.Now().Unix())
282 if err != nil {
283 return err
284 }
285 affected, err := res.RowsAffected()
286 if err != nil {
287 return err
288 } else if affected == 0 {
289 return nil
290 }
291 // Full cache reload, because we don't know which users were affected.
292 return a.maybeReloadAccessCache()
293 }
294
295 // ChangePassword changes a user's password
296 func (a *Manager) ChangePassword(username, password string, hashed bool) error {
297 if err := a.CanChangeUser(username); err != nil {
298 return err
299 }
300 hash, err := a.maybeHashPassword(password, hashed)
301 if err != nil {
302 return err
303 }
304 return db.ExecTx(a.db, func(tx *sql.Tx) error {
305 return a.changePasswordHashTx(tx, username, hash)
306 })
307 }
308
309 // changePasswordHashTx changes a user's password hash in the database
310 func (a *Manager) changePasswordHashTx(tx *sql.Tx, username, hash string) error {
311 if _, err := tx.Exec(a.queries.updateUserPass, hash, username); err != nil {
312 return err
313 }
314 return nil
315 }
316
317 // ChangeRole changes a user's role. When a role is changed from RoleUser to RoleAdmin,
318 // all existing access control entries (Grant) are removed, since they are no longer needed.
319 func (a *Manager) ChangeRole(username string, role Role) error {
320 if err := a.CanChangeUser(username); err != nil {
321 return err
322 }
323 err := db.ExecTx(a.db, func(tx *sql.Tx) error {
324 return a.changeRoleTx(tx, username, role)
325 })
326 if err != nil {
327 return err
328 }
329 // Full cache reload: Role changes are extremely rare.
330 return a.maybeReloadAccessCache()
331 }
332
333 // changeRoleTx changes a user's role
334 func (a *Manager) changeRoleTx(tx *sql.Tx, username string, role Role) error {
335 if !AllowedUsername(username) || !AllowedRole(role) {
336 return ErrInvalidArgument
337 }
338 if _, err := tx.Exec(a.queries.updateUserRole, string(role), username); err != nil {
339 return err
340 }
341 // If changing to admin, remove all access entries
342 if role == RoleAdmin {
343 if err := a.resetUserAccessTx(tx, username); err != nil {
344 return err
345 }
346 }
347 return nil
348 }
349
350 // CanChangeUser checks if the user with the given username can be changed.
351 // This is used to prevent changes to provisioned users, which are defined in the config file.
352 func (a *Manager) CanChangeUser(username string) error {
353 user, err := a.User(username)
354 if err != nil {
355 return err
356 } else if user.Provisioned {
357 return ErrProvisionedUserChange
358 }
359 return nil
360 }
361
362 // changeProvisionedTx changes the provisioned status of a user
363 func (a *Manager) changeProvisionedTx(tx *sql.Tx, username string, provisioned bool) error {
364 if _, err := tx.Exec(a.queries.updateUserProvisioned, provisioned, username); err != nil {
365 return err
366 }
367 return nil
368 }
369
370 // ChangeSettings persists the user settings
371 func (a *Manager) ChangeSettings(userID string, prefs *Prefs) error {
372 b, err := json.Marshal(prefs)
373 if err != nil {
374 return err
375 }
376 if _, err := a.db.Exec(a.queries.updateUserPrefs, string(b), userID); err != nil {
377 return err
378 }
379 return nil
380 }
381
382 // ChangeTier changes a user's tier using the tier code. This function does not delete reservations, messages,
383 // or attachments, even if the new tier has lower limits in this regard. That has to be done elsewhere.
384 func (a *Manager) ChangeTier(username, tier string) error {
385 if !AllowedUsername(username) {
386 return ErrInvalidArgument
387 }
388 t, err := a.Tier(tier)
389 if err != nil {
390 return err
391 }
392 return db.ExecTx(a.db, func(tx *sql.Tx) error {
393 if err := a.checkReservationsLimitTx(tx, username, t.ReservationLimit); err != nil {
394 return err
395 }
396 if _, err := tx.Exec(a.queries.updateUserTier, tier, username); err != nil {
397 return err
398 }
399 return nil
400 })
401 }
402
403 // ResetTier removes the tier from the given user
404 func (a *Manager) ResetTier(username string) error {
405 if !AllowedUsername(username) && username != Everyone && username != "" {
406 return ErrInvalidArgument
407 }
408 return db.ExecTx(a.db, func(tx *sql.Tx) error {
409 if err := a.checkReservationsLimitTx(tx, username, 0); err != nil {
410 return err
411 }
412 if _, err := tx.Exec(a.queries.deleteUserTier, username); err != nil {
413 return err
414 }
415 return nil
416 })
417 }
418
419 func (a *Manager) checkReservationsLimitTx(tx *sql.Tx, username string, reservationsLimit int64) error {
420 u, err := a.userTx(tx, username)
421 if err != nil {
422 return err
423 }
424 if u.Tier != nil && reservationsLimit < u.Tier.ReservationLimit {
425 reservations, err := a.reservationsTx(tx, username)
426 if err != nil {
427 return err
428 } else if int64(len(reservations)) > reservationsLimit {
429 return ErrTooManyReservations
430 }
431 }
432 return nil
433 }
434
435 // ResetStats resets all user stats in the user database. This touches all users.
436 func (a *Manager) ResetStats() error {
437 a.mu.Lock() // Includes database query to avoid races!
438 defer a.mu.Unlock()
439 if _, err := a.db.Exec(a.queries.updateUserStatsResetAll); err != nil {
440 return err
441 }
442 a.statsQueue = make(map[string]*Stats)
443 return nil
444 }
445
446 // EnqueueUserStats adds the user to a queue which writes out user stats (messages, emails, ..) in
447 // batches at a regular interval
448 func (a *Manager) EnqueueUserStats(userID string, stats *Stats) {
449 a.mu.Lock()
450 defer a.mu.Unlock()
451 a.statsQueue[userID] = stats
452 }
453
454 func (a *Manager) asyncQueueWriteLoop(interval time.Duration) {
455 ticker := time.NewTicker(interval)
456 defer ticker.Stop()
457 for {
458 select {
459 case <-a.quit:
460 return
461 case <-ticker.C:
462 if err := a.writeUserStatsQueue(); err != nil {
463 log.Tag(tag).Err(err).Warn("Writing user stats queue failed")
464 }
465 if err := a.writeTokenUpdateQueue(); err != nil {
466 log.Tag(tag).Err(err).Warn("Writing token update queue failed")
467 }
468 }
469 }
470 }
471
472 func (a *Manager) writeUserStatsQueue() error {
473 a.mu.Lock()
474 if len(a.statsQueue) == 0 {
475 a.mu.Unlock()
476 log.Tag(tag).Trace("No user stats updates to commit")
477 return nil
478 }
479 statsQueue := a.statsQueue
480 a.statsQueue = make(map[string]*Stats)
481 a.mu.Unlock()
482
483 return db.ExecTx(a.db, func(tx *sql.Tx) error {
484 log.Tag(tag).Debug("Writing user stats queue for %d user(s)", len(statsQueue))
485 for userID, update := range statsQueue {
486 log.
487 Tag(tag).
488 Fields(log.Context{
489 "user_id": userID,
490 "messages_count": update.Messages,
491 "emails_count": update.Emails,
492 "calls_count": update.Calls,
493 }).
494 Trace("Updating stats for user %s", userID)
495 if _, err := tx.Exec(a.queries.updateUserStats, update.Messages, update.Emails, update.Calls, userID); err != nil {
496 return err
497 }
498 }
499 return nil
500 })
501 }
502
503 // User returns the user with the given username if it exists, or ErrUserNotFound otherwise
504 func (a *Manager) User(username string) (*User, error) {
505 return a.userTx(a.db, username)
506 }
507
508 func (a *Manager) userTx(tx db.Querier, username string) (*User, error) {
509 rows, err := tx.Query(a.queries.selectUserByName, username)
510 if err != nil {
511 return nil, err
512 }
513 return a.readUser(rows)
514 }
515
516 // UserByID returns the user with the given ID if it exists, or ErrUserNotFound otherwise
517 func (a *Manager) UserByID(id string) (*User, error) {
518 rows, err := a.db.Query(a.queries.selectUserByID, id)
519 if err != nil {
520 return nil, err
521 }
522 return a.readUser(rows)
523 }
524
525 // UserByEmailOrUsername resolves an identifier to a single user, trying it first as a primary
526 // email address and then as a username. A verified, owned email takes precedence over a
527 // freely-chosen username, so a look-alike username cannot shadow the email's real owner. Returns
528 // ErrUserNotFound if neither matches.
529 func (a *Manager) UserByEmailOrUsername(identifier string) (*User, error) {
530 if userID, err := a.UserIDByPrimaryEmail(identifier); err == nil {
531 if u, err := a.UserByID(userID); err == nil {
532 return u, nil
533 }
534 }
535 return a.User(identifier)
536 }
537
538 // userByNameOrEmail resolves a login identifier to a single user in one query, matching it
539 // against the username first and a verified primary email address second. This is the INVERSE
540 // precedence of UserByEmailOrUsername (used by password reset): at login a freely-chosen username
541 // must win over a look-alike primary email, so a user whose username happens to equal another
542 // account's email is not locked out of their own account. Because Authenticate still gates the match
543 // on a password check, returning the username owner here never grants access to the email owner's
544 // account. Returns ErrUserNotFound if neither matches.
545 func (a *Manager) userByNameOrEmail(identifier string) (*User, error) {
546 rows, err := a.db.Query(a.queries.selectUserByNameOrPrimaryEmail, identifier, identifier, identifier)
547 if err != nil {
548 return nil, err
549 }
550 return a.readUser(rows)
551 }
552
553 // userByToken returns the user with the given token if it exists and is not expired, or ErrUserNotFound otherwise
554 func (a *Manager) userByToken(token string) (*User, error) {
555 rows, err := a.db.Query(a.queries.selectUserByToken, token, time.Now().Unix())
556 if err != nil {
557 return nil, err
558 }
559 return a.readUser(rows)
560 }
561
562 // UserByStripeCustomer returns the user with the given Stripe customer ID if it exists, or ErrUserNotFound otherwise
563 func (a *Manager) UserByStripeCustomer(customerID string) (*User, error) {
564 rows, err := a.db.Query(a.queries.selectUserByStripeCustomerID, customerID)
565 if err != nil {
566 return nil, err
567 }
568 return a.readUser(rows)
569 }
570
571 // Users returns a list of users. It loads all users in a single query
572 // rather than one query per user to avoid N+1 performance issues.
573 func (a *Manager) Users() ([]*User, error) {
574 rows, err := a.db.ReadOnly().Query(a.queries.selectUsers)
575 if err != nil {
576 return nil, err
577 }
578 return a.readUsers(rows)
579 }
580
581 // UsersCount returns the number of users in the database
582 func (a *Manager) UsersCount() (int64, error) {
583 rows, err := a.db.ReadOnly().Query(a.queries.selectUserCount)
584 if err != nil {
585 return 0, err
586 }
587 defer rows.Close()
588 if !rows.Next() {
589 return 0, errNoRows
590 }
591 var count int64
592 if err := rows.Scan(&count); err != nil {
593 return 0, err
594 }
595 return count, nil
596 }
597
598 func (a *Manager) readUser(rows *sql.Rows) (*User, error) {
599 defer rows.Close()
600 if !rows.Next() {
601 return nil, ErrUserNotFound
602 }
603 user, err := a.scanUser(rows)
604 if err != nil {
605 return nil, err
606 }
607 return user, nil
608 }
609
610 func (a *Manager) readUsers(rows *sql.Rows) ([]*User, error) {
611 defer rows.Close()
612 users := make([]*User, 0)
613 for rows.Next() {
614 user, err := a.scanUser(rows)
615 if err != nil {
616 return nil, err
617 }
618 users = append(users, user)
619 }
620 return users, nil
621 }
622
623 func (a *Manager) scanUser(rows *sql.Rows) (*User, error) {
624 var id, username, hash, role, prefs, syncTopic string
625 var provisioned bool
626 var stripeCustomerID, stripeSubscriptionID, stripeSubscriptionStatus, stripeSubscriptionInterval, stripeMonthlyPriceID, stripeYearlyPriceID, tierID, tierCode, tierName sql.NullString
627 var messages, emails, calls int64
628 var messagesLimit, messagesExpiryDuration, emailsLimit, callsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit, stripeSubscriptionPaidUntil, stripeSubscriptionCancelAt, deleted sql.NullInt64
629 if err := rows.Scan(&id, &username, &hash, &role, &prefs, &syncTopic, &provisioned, &messages, &emails, &calls, &stripeCustomerID, &stripeSubscriptionID, &stripeSubscriptionStatus, &stripeSubscriptionInterval, &stripeSubscriptionPaidUntil, &stripeSubscriptionCancelAt, &deleted, &tierID, &tierCode, &tierName, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &callsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripeMonthlyPriceID, &stripeYearlyPriceID); err != nil {
630 return nil, err
631 } else if err := rows.Err(); err != nil {
632 return nil, err
633 }
634 user := &User{
635 ID: id,
636 Name: username,
637 Hash: hash,
638 Role: Role(role),
639 Prefs: &Prefs{},
640 SyncTopic: syncTopic,
641 Provisioned: provisioned,
642 Stats: &Stats{
643 Messages: messages,
644 Emails: emails,
645 Calls: calls,
646 },
647 Billing: &Billing{
648 StripeCustomerID: stripeCustomerID.String, // May be empty
649 StripeSubscriptionID: stripeSubscriptionID.String, // May be empty
650 StripeSubscriptionStatus: payments.SubscriptionStatus(stripeSubscriptionStatus.String), // May be empty
651 StripeSubscriptionInterval: payments.PriceRecurringInterval(stripeSubscriptionInterval.String), // May be empty
652 StripeSubscriptionPaidUntil: time.Unix(stripeSubscriptionPaidUntil.Int64, 0), // May be zero
653 StripeSubscriptionCancelAt: time.Unix(stripeSubscriptionCancelAt.Int64, 0), // May be zero
654 },
655 Deleted: deleted.Valid,
656 }
657 if err := json.Unmarshal([]byte(prefs), user.Prefs); err != nil {
658 return nil, err
659 }
660 if tierCode.Valid {
661 // See readTier() when this is changed!
662 user.Tier = &Tier{
663 ID: tierID.String,
664 Code: tierCode.String,
665 Name: tierName.String,
666 MessageLimit: messagesLimit.Int64,
667 MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
668 EmailLimit: emailsLimit.Int64,
669 CallLimit: callsLimit.Int64,
670 ReservationLimit: reservationsLimit.Int64,
671 AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
672 AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
673 AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
674 AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
675 StripeMonthlyPriceID: stripeMonthlyPriceID.String, // May be empty
676 StripeYearlyPriceID: stripeYearlyPriceID.String, // May be empty
677 }
678 }
679 return user, nil
680 }
681
682 func (a *Manager) maybeHashPassword(password string, hashed bool) (string, error) {
683 if hashed {
684 if err := ValidPasswordHash(password, a.config.BcryptCost); err != nil {
685 return "", err
686 }
687 return password, nil
688 }
689 return HashPassword(password, a.config.BcryptCost)
690 }
691
692 // Authorize returns nil if the given user has access to the given topic using the desired
693 // permission. The user param may be nil to signal an anonymous user.
694 func (a *Manager) Authorize(user *User, topic string, perm Permission) error {
695 if user != nil && user.Role == RoleAdmin {
696 return nil // Admin can do everything
697 }
698 // A user always has full access to their own sync topic, which the apps use
699 // to sync subscriptions/settings across devices. Without this, an
700 // auth-default-access of "deny-all" locks the user out of their own sync
701 // topic (no ACL entry is created for it at user creation). See #733.
702 if user != nil && user.SyncTopic != "" && subtle.ConstantTimeCompare([]byte(topic), []byte(user.SyncTopic)) == 1 {
703 return nil
704 }
705 username := Everyone
706 if user != nil {
707 username = user.Name
708 }
709 // Select the read/write permissions for this user/topic combo.
710 read, write, found, err := a.authorizeTopicAccess(username, topic)
711 if err != nil {
712 return err
713 } else if !found {
714 return a.resolvePerms(a.config.DefaultAccess, perm)
715 }
716 return a.resolvePerms(NewPermission(read, write), perm)
717 }
718
719 func (a *Manager) resolvePerms(base, perm Permission) error {
720 if perm == PermissionRead && base.IsRead() {
721 return nil
722 } else if perm == PermissionWrite && base.IsWrite() {
723 return nil
724 }
725 return ErrUnauthorized
726 }
727
728 // AllowAccess adds or updates an entry in the access control list for a specific user. It controls
729 // read/write access to a topic. The parameter topicPattern may include wildcards (*). The ACL entry
730 // owner may either be a user (username), or the system (empty).
731 func (a *Manager) AllowAccess(username string, topicPattern string, permission Permission) error {
732 err := db.ExecTx(a.db, func(tx *sql.Tx) error {
733 return a.allowAccessTx(tx, username, topicPattern, permission, false)
734 })
735 if err != nil {
736 return err
737 }
738 // Only this user's row set changed; refresh their slice only.
739 return a.maybeReloadAccessCache(username)
740 }
741
742 func (a *Manager) allowAccessTx(tx *sql.Tx, username string, topicPattern string, permission Permission, provisioned bool) error {
743 if !AllowedUsername(username) && username != Everyone {
744 return ErrInvalidArgument
745 } else if !AllowedTopicPattern(topicPattern) {
746 return ErrInvalidArgument
747 }
748 _, err := tx.Exec(a.queries.upsertUserAccess, username, toSQLWildcard(topicPattern), permission.IsRead(), permission.IsWrite(), "", "", provisioned)
749 return err
750 }
751
752 // ResetAccess removes an access control list entry for a specific username/topic, or (if topic is
753 // empty) for an entire user. The parameter topicPattern may include wildcards (*).
754 func (a *Manager) ResetAccess(username string, topicPattern string) error {
755 err := db.ExecTx(a.db, func(tx *sql.Tx) error {
756 return a.resetAccessTx(tx, username, topicPattern)
757 })
758 if err != nil {
759 return err
760 }
761 // Empty username -> deleteAllAccess affected every user, bulk reload.
762 // Otherwise refresh the named user plus Everyone, since resetUserAccessTx
763 // and deleteTopicAccess both touch rows owned by the user (typically the
764 // Everyone row from their reservations).
765 if username == "" {
766 return a.maybeReloadAccessCache()
767 }
768 return a.maybeReloadAccessCache(username, Everyone)
769 }
770
771 func (a *Manager) resetAccessTx(tx *sql.Tx, username string, topicPattern string) error {
772 if !AllowedUsername(username) && username != Everyone && username != "" {
773 return ErrInvalidArgument
774 } else if !AllowedTopicPattern(topicPattern) && topicPattern != "" {
775 return ErrInvalidArgument
776 }
777 if username == "" && topicPattern == "" {
778 _, err := tx.Exec(a.queries.deleteAllAccess)
779 return err
780 } else if topicPattern == "" {
781 return a.resetUserAccessTx(tx, username)
782 }
783 return a.resetTopicAccessTx(tx, username, topicPattern)
784 }
785
786 // DefaultAccess returns the default read/write access if no access control entry matches
787 func (a *Manager) DefaultAccess() Permission {
788 return a.config.DefaultAccess
789 }
790
791 // AllowReservation tests if a user may create an access control entry for the given topic.
792 // If there are any ACL entries that are not owned by the user, an error is returned.
793 func (a *Manager) AllowReservation(username string, topic string) error {
794 if (!AllowedUsername(username) && username != Everyone) || !AllowedTopic(topic) {
795 return ErrInvalidArgument
796 }
797 otherCount, err := a.otherAccessCount(username, topic)
798 if err != nil {
799 return err
800 }
801 if otherCount > 0 {
802 return errTopicOwnedByOthers
803 }
804 return nil
805 }
806
807 // authorizeTopicAccess returns the read/write permissions for the given username and topic.
808 // The found return value indicates whether an ACL entry was found at all.
809 //
810 // Priority:
811 // - Specific user beats Everyone
812 // - Longer pattern beats shorter (a more specific rule beats a more general one,
813 // e.g. "test*" > "*")
814 // - Write beats read at equal length
815 //
816 // When AccessCacheEnabled is true (config), the lookup is served entirely from
817 // the in-memory snapshot maintained by accessCache. Otherwise the original SQL
818 // query is executed against the database on every call.
819 func (a *Manager) authorizeTopicAccess(usernameOrEveryone, topic string) (read, write, found bool, err error) {
820 if a.accessCache != nil {
821 read, write, found = a.accessCache.Lookup(usernameOrEveryone, topic)
822 return read, write, found, nil
823 }
824 rows, err := a.db.ReadOnly().Query(a.queries.selectTopicPerms, Everyone, usernameOrEveryone, topic)
825 if err != nil {
826 return false, false, false, err
827 }
828 defer rows.Close()
829 if !rows.Next() {
830 return false, false, false, nil
831 }
832 if err := rows.Scan(&read, &write); err != nil {
833 return false, false, false, err
834 } else if err := rows.Err(); err != nil {
835 return false, false, false, err
836 }
837 return read, write, true, nil
838 }
839
840 // AllGrants returns all user-specific access control entries, mapped to their respective user IDs
841 func (a *Manager) AllGrants() (map[string][]Grant, error) {
842 rows, err := a.db.ReadOnly().Query(a.queries.selectUserAllAccess)
843 if err != nil {
844 return nil, err
845 }
846 defer rows.Close()
847 grants := make(map[string][]Grant, 0)
848 for rows.Next() {
849 var userID, topic string
850 var read, write, provisioned bool
851 if err := rows.Scan(&userID, &topic, &read, &write, &provisioned); err != nil {
852 return nil, err
853 } else if err := rows.Err(); err != nil {
854 return nil, err
855 }
856 if _, ok := grants[userID]; !ok {
857 grants[userID] = make([]Grant, 0)
858 }
859 grants[userID] = append(grants[userID], Grant{
860 TopicPattern: fromSQLWildcard(topic),
861 Permission: NewPermission(read, write),
862 Provisioned: provisioned,
863 })
864 }
865 return grants, nil
866 }
867
868 // Grants returns all user-specific access control entries
869 func (a *Manager) Grants(username string) ([]Grant, error) {
870 rows, err := a.db.ReadOnly().Query(a.queries.selectUserAccess, username)
871 if err != nil {
872 return nil, err
873 }
874 defer rows.Close()
875 grants := make([]Grant, 0)
876 for rows.Next() {
877 var topic string
878 var read, write, provisioned bool
879 if err := rows.Scan(&topic, &read, &write, &provisioned); err != nil {
880 return nil, err
881 } else if err := rows.Err(); err != nil {
882 return nil, err
883 }
884 grants = append(grants, Grant{
885 TopicPattern: fromSQLWildcard(topic),
886 Permission: NewPermission(read, write),
887 Provisioned: provisioned,
888 })
889 }
890 return grants, nil
891 }
892
893 // AddReservation creates two access control entries for the given topic: one with full read/write
894 // access for the given user, and one for Everyone with the given permission. Both entries are
895 // created atomically in a single transaction. If limit is > 0, the reservation count is checked
896 // inside the transaction and ErrTooManyReservations is returned if the limit would be exceeded.
897 func (a *Manager) AddReservation(username string, topic string, everyone Permission, limit int64) error {
898 if !AllowedUsername(username) || username == Everyone || !AllowedTopic(topic) {
899 return ErrInvalidArgument
900 }
901 err := db.ExecTx(a.db, func(tx *sql.Tx) error {
902 if limit > 0 {
903 hasReservation, err := a.hasReservationTx(tx, username, topic)
904 if err != nil {
905 return err
906 }
907 if !hasReservation {
908 count, err := a.reservationsCountTx(tx, username)
909 if err != nil {
910 return err
911 }
912 if count >= limit {
913 return ErrTooManyReservations
914 }
915 }
916 }
917 if _, err := tx.Exec(a.queries.upsertUserAccess, username, toSQLWildcard(topic), true, true, username, username, false); err != nil {
918 return err
919 }
920 if _, err := tx.Exec(a.queries.upsertUserAccess, Everyone, toSQLWildcard(topic), everyone.IsRead(), everyone.IsWrite(), username, username, false); err != nil {
921 return err
922 }
923 return nil
924 })
925 if err != nil {
926 return err
927 }
928 // Both user's and Everyone's rows changed.
929 return a.maybeReloadAccessCache(username, Everyone)
930 }
931
932 // RemoveReservations deletes the access control entries associated with the given username/topic,
933 // as well as all entries with Everyone/topic. All deletions are performed atomically in a single
934 // transaction.
935 func (a *Manager) RemoveReservations(username string, topics ...string) error {
936 if !AllowedUsername(username) || username == Everyone || len(topics) == 0 {
937 return ErrInvalidArgument
938 }
939 for _, topic := range topics {
940 if !AllowedTopic(topic) {
941 return ErrInvalidArgument
942 }
943 }
944 err := db.ExecTx(a.db, func(tx *sql.Tx) error {
945 for _, topic := range topics {
946 if err := a.removeReservationAccessTx(tx, username, topic); err != nil {
947 return err
948 }
949 }
950 return nil
951 })
952 if err != nil {
953 return err
954 }
955 // Mirror the DB: rows for this user and any Everyone rows owned by this
956 // user are gone. Refresh both slices.
957 return a.maybeReloadAccessCache(username, Everyone)
958 }
959
960 // Reservations returns all user-owned topics, and the associated everyone-access
961 func (a *Manager) Reservations(username string) ([]Reservation, error) {
962 // Read from the primary, not a replica: this backs GET /account, which the web app refetches
963 // immediately after a sync event. Replication lag would otherwise show stale data.
964 return a.reservationsTx(a.db, username)
965 }
966
967 func (a *Manager) reservationsTx(tx db.Querier, username string) ([]Reservation, error) {
968 rows, err := tx.Query(a.queries.selectUserReservations, Everyone, username)
969 if err != nil {
970 return nil, err
971 }
972 defer rows.Close()
973 reservations := make([]Reservation, 0)
974 for rows.Next() {
975 var topic string
976 var ownerRead, ownerWrite bool
977 var everyoneRead, everyoneWrite sql.NullBool
978 if err := rows.Scan(&topic, &ownerRead, &ownerWrite, &everyoneRead, &everyoneWrite); err != nil {
979 return nil, err
980 } else if err := rows.Err(); err != nil {
981 return nil, err
982 }
983 reservations = append(reservations, Reservation{
984 Topic: fromSQLWildcard(topic),
985 Owner: NewPermission(ownerRead, ownerWrite),
986 Everyone: NewPermission(everyoneRead.Bool, everyoneWrite.Bool),
987 })
988 }
989 return reservations, nil
990 }
991
992 // HasReservation returns true if the given topic access is owned by the user
993 func (a *Manager) HasReservation(username, topic string) (bool, error) {
994 return a.hasReservationTx(a.db, username, topic)
995 }
996
997 func (a *Manager) hasReservationTx(tx db.Querier, username, topic string) (bool, error) {
998 rows, err := tx.Query(a.queries.selectUserHasReservation, username, escapeUnderscore(topic))
999 if err != nil {
1000 return false, err
1001 }
1002 defer rows.Close()
1003 if !rows.Next() {
1004 return false, errNoRows
1005 }
1006 var count int64
1007 if err := rows.Scan(&count); err != nil {
1008 return false, err
1009 }
1010 return count > 0, nil
1011 }
1012
1013 // ReservationsCount returns the number of reservations owned by this user
1014 func (a *Manager) ReservationsCount(username string) (int64, error) {
1015 return a.reservationsCountTx(a.db, username)
1016 }
1017
1018 func (a *Manager) reservationsCountTx(tx db.Querier, username string) (int64, error) {
1019 rows, err := tx.Query(a.queries.selectUserReservationsCount, username)
1020 if err != nil {
1021 return 0, err
1022 }
1023 defer rows.Close()
1024 if !rows.Next() {
1025 return 0, errNoRows
1026 }
1027 var count int64
1028 if err := rows.Scan(&count); err != nil {
1029 return 0, err
1030 }
1031 return count, nil
1032 }
1033
1034 // ReservationOwner returns user ID of the user that owns this topic, or an empty string if it's not owned by anyone
1035 func (a *Manager) ReservationOwner(topic string) (string, error) {
1036 rows, err := a.db.Query(a.queries.selectUserReservationsOwner, escapeUnderscore(topic))
1037 if err != nil {
1038 return "", err
1039 }
1040 defer rows.Close()
1041 if !rows.Next() {
1042 return "", nil
1043 }
1044 var ownerUserID string
1045 if err := rows.Scan(&ownerUserID); err != nil {
1046 return "", err
1047 }
1048 return ownerUserID, nil
1049 }
1050
1051 // RemoveExcessReservations removes reservations that exceed the given limit for the user.
1052 // It returns the list of topics whose reservations were removed. The read and removal are
1053 // performed atomically in a single transaction to avoid issues with stale replica data.
1054 func (a *Manager) RemoveExcessReservations(username string, limit int64) ([]string, error) {
1055 removedTopics, err := db.QueryTx(a.db, func(tx *sql.Tx) ([]string, error) {
1056 reservations, err := a.reservationsTx(tx, username)
1057 if err != nil {
1058 return nil, err
1059 }
1060 if int64(len(reservations)) <= limit {
1061 return []string{}, nil
1062 }
1063 removedTopics := make([]string, 0)
1064 for i := int64(len(reservations)) - 1; i >= limit; i-- {
1065 topic := reservations[i].Topic
1066 if err := a.removeReservationAccessTx(tx, username, topic); err != nil {
1067 return nil, err
1068 }
1069 removedTopics = append(removedTopics, topic)
1070 }
1071 return removedTopics, nil
1072 })
1073 if err != nil {
1074 return nil, err
1075 }
1076 if len(removedTopics) > 0 {
1077 // removeReservationAccessTx deletes rows owned by this user and the
1078 // matching Everyone rows, so we refresh the access cache.
1079 if err := a.maybeReloadAccessCache(username, Everyone); err != nil {
1080 return nil, err
1081 }
1082 }
1083 return removedTopics, nil
1084 }
1085
1086 // otherAccessCount returns the number of access entries for the given topic that are not owned by the user
1087 func (a *Manager) otherAccessCount(username, topic string) (int, error) {
1088 rows, err := a.db.Query(a.queries.selectOtherAccessCount, escapeUnderscore(topic), escapeUnderscore(topic), username)
1089 if err != nil {
1090 return 0, err
1091 }
1092 defer rows.Close()
1093 if !rows.Next() {
1094 return 0, errNoRows
1095 }
1096 var count int
1097 if err := rows.Scan(&count); err != nil {
1098 return 0, err
1099 }
1100 return count, nil
1101 }
1102
1103 func (a *Manager) removeReservationAccessTx(tx *sql.Tx, username, topic string) error {
1104 if err := a.resetTopicAccessTx(tx, username, topic); err != nil {
1105 return err
1106 }
1107 return a.resetTopicAccessTx(tx, Everyone, topic)
1108 }
1109
1110 func (a *Manager) resetUserAccessTx(tx *sql.Tx, username string) error {
1111 if !AllowedUsername(username) && username != Everyone {
1112 return ErrInvalidArgument
1113 }
1114 _, err := tx.Exec(a.queries.deleteUserAccess, username, username)
1115 return err
1116 }
1117
1118 func (a *Manager) resetTopicAccessTx(tx *sql.Tx, username, topicPattern string) error {
1119 if !AllowedUsername(username) && username != Everyone && username != "" {
1120 return ErrInvalidArgument
1121 } else if !AllowedTopicPattern(topicPattern) && topicPattern != "" {
1122 return ErrInvalidArgument
1123 }
1124 _, err := tx.Exec(a.queries.deleteTopicAccess, username, username, toSQLWildcard(topicPattern))
1125 return err
1126 }
1127
1128 // CreateToken generates a random token for the given user and returns it. The token expires
1129 // after a fixed duration unless ChangeToken is called. This function also prunes tokens for the
1130 // given user, if there are too many of them.
1131 func (a *Manager) CreateToken(userID, label string, expires time.Time, origin netip.Addr, provisioned bool) (*Token, error) {
1132 return db.QueryTx(a.db, func(tx *sql.Tx) (*Token, error) {
1133 return a.createTokenTx(tx, userID, GenerateToken(), label, time.Now(), origin, expires, tokenMaxCount, provisioned)
1134 })
1135 }
1136
1137 // createTokenTx creates a new token and prunes excess tokens if the count exceeds maxTokenCount.
1138 // If maxTokenCount is 0, no pruning is performed.
1139 func (a *Manager) createTokenTx(tx *sql.Tx, userID, token, label string, lastAccess time.Time, lastOrigin netip.Addr, expires time.Time, maxTokenCount int, provisioned bool) (*Token, error) {
1140 if _, err := tx.Exec(a.queries.upsertToken, userID, token, label, lastAccess.Unix(), lastOrigin.String(), expires.Unix(), provisioned); err != nil {
1141 return nil, err
1142 }
1143 if maxTokenCount > 0 {
1144 var tokenCount int
1145 if err := tx.QueryRow(a.queries.selectTokenCount, userID).Scan(&tokenCount); err != nil {
1146 return nil, err
1147 }
1148 if tokenCount > maxTokenCount {
1149 // This pruning logic is done in two queries for efficiency. The SELECT above is a lookup
1150 // on two indices, whereas the query below is a full table scan.
1151 if _, err := tx.Exec(a.queries.deleteExcessTokens, userID, userID, maxTokenCount); err != nil {
1152 return nil, err
1153 }
1154 }
1155 }
1156 return &Token{
1157 Value: token,
1158 Label: label,
1159 LastAccess: lastAccess,
1160 LastOrigin: lastOrigin,
1161 Expires: expires,
1162 Provisioned: provisioned,
1163 }, nil
1164 }
1165
1166 // ChangeToken updates a token's label and/or expiry date
1167 func (a *Manager) ChangeToken(userID, token string, label *string, expires *time.Time) (*Token, error) {
1168 if token == "" {
1169 return nil, errNoTokenProvided
1170 }
1171 if err := a.canChangeToken(userID, token); err != nil {
1172 return nil, err
1173 }
1174 t, err := a.Token(userID, token)
1175 if err != nil {
1176 return nil, err
1177 }
1178 if label != nil {
1179 t.Label = *label
1180 }
1181 if expires != nil {
1182 t.Expires = *expires
1183 }
1184 if _, err := a.db.Exec(a.queries.updateToken, t.Label, t.Expires.Unix(), userID, token); err != nil {
1185 return nil, err
1186 }
1187 return t, nil
1188 }
1189
1190 // RemoveToken deletes the token defined in User.Token
1191 func (a *Manager) RemoveToken(userID, token string) error {
1192 if err := a.canChangeToken(userID, token); err != nil {
1193 return err
1194 }
1195 if token == "" {
1196 return errNoTokenProvided
1197 }
1198 if _, err := a.db.Exec(a.queries.deleteToken, userID, token); err != nil {
1199 return err
1200 }
1201 return nil
1202 }
1203
1204 // canChangeToken checks if the token can be changed. If the token is provisioned, it cannot be changed.
1205 func (a *Manager) canChangeToken(userID, token string) error {
1206 t, err := a.Token(userID, token)
1207 if err != nil {
1208 return err
1209 } else if t.Provisioned {
1210 return ErrProvisionedTokenChange
1211 }
1212 return nil
1213 }
1214
1215 // Token returns a specific token for a user
1216 func (a *Manager) Token(userID, token string) (*Token, error) {
1217 rows, err := a.db.ReadOnly().Query(a.queries.selectToken, userID, token)
1218 if err != nil {
1219 return nil, err
1220 }
1221 defer rows.Close()
1222 return a.readToken(rows)
1223 }
1224
1225 // Tokens returns all existing tokens for the user with the given user ID
1226 func (a *Manager) Tokens(userID string) ([]*Token, error) {
1227 // Primary read: backs GET /account (read-your-writes after a sync event).
1228 rows, err := a.db.Query(a.queries.selectTokens, userID)
1229 if err != nil {
1230 return nil, err
1231 }
1232 defer rows.Close()
1233 tokens := make([]*Token, 0)
1234 for {
1235 token, err := a.readToken(rows)
1236 if errors.Is(err, ErrTokenNotFound) {
1237 break
1238 } else if err != nil {
1239 return nil, err
1240 }
1241 tokens = append(tokens, token)
1242 }
1243 return tokens, nil
1244 }
1245
1246 func (a *Manager) allProvisionedTokens() ([]*Token, error) {
1247 rows, err := a.db.ReadOnly().Query(a.queries.selectAllProvisionedTokens)
1248 if err != nil {
1249 return nil, err
1250 }
1251 defer rows.Close()
1252 tokens := make([]*Token, 0)
1253 for {
1254 token, err := a.readToken(rows)
1255 if errors.Is(err, ErrTokenNotFound) {
1256 break
1257 } else if err != nil {
1258 return nil, err
1259 }
1260 tokens = append(tokens, token)
1261 }
1262 return tokens, nil
1263 }
1264
1265 // RemoveExpiredTokens deletes all expired tokens from the database
1266 func (a *Manager) RemoveExpiredTokens() error {
1267 if _, err := a.db.Exec(a.queries.deleteExpiredTokens, time.Now().Unix()); err != nil {
1268 return err
1269 }
1270 return nil
1271 }
1272
1273 // EnqueueTokenUpdate adds the token update to a queue which writes out token access times
1274 // in batches at a regular interval
1275 func (a *Manager) EnqueueTokenUpdate(tokenID string, update *TokenUpdate) {
1276 a.mu.Lock()
1277 defer a.mu.Unlock()
1278 a.tokenQueue[tokenID] = update
1279 }
1280
1281 func (a *Manager) writeTokenUpdateQueue() error {
1282 a.mu.Lock()
1283 if len(a.tokenQueue) == 0 {
1284 a.mu.Unlock()
1285 log.Tag(tag).Trace("No token updates to commit")
1286 return nil
1287 }
1288 tokenQueue := a.tokenQueue
1289 a.tokenQueue = make(map[string]*TokenUpdate)
1290 a.mu.Unlock()
1291
1292 return db.ExecTx(a.db, func(tx *sql.Tx) error {
1293 log.Tag(tag).Debug("Writing token update queue for %d token(s)", len(tokenQueue))
1294 for tokenID, update := range tokenQueue {
1295 log.Tag(tag).Trace("Updating token %s with last access time %v", tokenID, update.LastAccess.Unix())
1296 if err := a.updateTokenLastAccessTx(tx, tokenID, update.LastAccess.Unix(), update.LastOrigin.String()); err != nil {
1297 return err
1298 }
1299 }
1300 return nil
1301 })
1302 }
1303
1304 func (a *Manager) updateTokenLastAccessTx(tx *sql.Tx, token string, lastAccess int64, lastOrigin string) error {
1305 if _, err := tx.Exec(a.queries.updateTokenLastAccess, lastAccess, lastOrigin, token); err != nil {
1306 return err
1307 }
1308 return nil
1309 }
1310
1311 func (a *Manager) readToken(rows *sql.Rows) (*Token, error) {
1312 var token, label, lastOrigin string
1313 var lastAccess, expires int64
1314 var provisioned bool
1315 if !rows.Next() {
1316 return nil, ErrTokenNotFound
1317 }
1318 if err := rows.Scan(&token, &label, &lastAccess, &lastOrigin, &expires, &provisioned); err != nil {
1319 return nil, err
1320 } else if err := rows.Err(); err != nil {
1321 return nil, err
1322 }
1323 lastOriginIP, err := netip.ParseAddr(lastOrigin)
1324 if err != nil {
1325 lastOriginIP = netip.IPv4Unspecified()
1326 }
1327 return &Token{
1328 Value: token,
1329 Label: label,
1330 LastAccess: time.Unix(lastAccess, 0),
1331 LastOrigin: lastOriginIP,
1332 Expires: time.Unix(expires, 0),
1333 Provisioned: provisioned,
1334 }, nil
1335 }
1336
1337 // AddTier creates a new tier in the database
1338 func (a *Manager) AddTier(tier *Tier) error {
1339 if tier.ID == "" {
1340 tier.ID = util.RandomStringPrefix(tierIDPrefix, tierIDLength)
1341 }
1342 if _, err := a.db.Exec(a.queries.insertTier, tier.ID, tier.Code, tier.Name, tier.MessageLimit, int64(tier.MessageExpiryDuration.Seconds()), tier.EmailLimit, tier.CallLimit, tier.ReservationLimit, tier.AttachmentFileSizeLimit, tier.AttachmentTotalSizeLimit, int64(tier.AttachmentExpiryDuration.Seconds()), tier.AttachmentBandwidthLimit, nullString(tier.StripeMonthlyPriceID), nullString(tier.StripeYearlyPriceID)); err != nil {
1343 return err
1344 }
1345 return nil
1346 }
1347
1348 // UpdateTier updates a tier's properties in the database
1349 func (a *Manager) UpdateTier(tier *Tier) error {
1350 if _, err := a.db.Exec(a.queries.updateTier, tier.Name, tier.MessageLimit, int64(tier.MessageExpiryDuration.Seconds()), tier.EmailLimit, tier.CallLimit, tier.ReservationLimit, tier.AttachmentFileSizeLimit, tier.AttachmentTotalSizeLimit, int64(tier.AttachmentExpiryDuration.Seconds()), tier.AttachmentBandwidthLimit, nullString(tier.StripeMonthlyPriceID), nullString(tier.StripeYearlyPriceID), tier.Code); err != nil {
1351 return err
1352 }
1353 return nil
1354 }
1355
1356 // RemoveTier deletes the tier with the given code
1357 func (a *Manager) RemoveTier(code string) error {
1358 if !AllowedTier(code) {
1359 return ErrInvalidArgument
1360 }
1361 // This fails if any user has this tier
1362 if _, err := a.db.Exec(a.queries.deleteTier, code); err != nil {
1363 return err
1364 }
1365 return nil
1366 }
1367
1368 // Tiers returns a list of all Tier structs
1369 func (a *Manager) Tiers() ([]*Tier, error) {
1370 rows, err := a.db.ReadOnly().Query(a.queries.selectTiers)
1371 if err != nil {
1372 return nil, err
1373 }
1374 defer rows.Close()
1375 tiers := make([]*Tier, 0)
1376 for {
1377 tier, err := a.readTier(rows)
1378 if errors.Is(err, ErrTierNotFound) {
1379 break
1380 } else if err != nil {
1381 return nil, err
1382 }
1383 tiers = append(tiers, tier)
1384 }
1385 return tiers, nil
1386 }
1387
1388 // Tier returns a Tier based on the code, or ErrTierNotFound if it does not exist
1389 func (a *Manager) Tier(code string) (*Tier, error) {
1390 rows, err := a.db.Query(a.queries.selectTierByCode, code)
1391 if err != nil {
1392 return nil, err
1393 }
1394 defer rows.Close()
1395 return a.readTier(rows)
1396 }
1397
1398 // TierByStripePrice returns a Tier based on the Stripe price ID, or ErrTierNotFound if it does not exist
1399 func (a *Manager) TierByStripePrice(priceID string) (*Tier, error) {
1400 rows, err := a.db.Query(a.queries.selectTierByPriceID, priceID, priceID)
1401 if err != nil {
1402 return nil, err
1403 }
1404 defer rows.Close()
1405 return a.readTier(rows)
1406 }
1407
1408 func (a *Manager) readTier(rows *sql.Rows) (*Tier, error) {
1409 var id, code, name string
1410 var stripeMonthlyPriceID, stripeYearlyPriceID sql.NullString
1411 var messagesLimit, messagesExpiryDuration, emailsLimit, callsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit sql.NullInt64
1412 if !rows.Next() {
1413 return nil, ErrTierNotFound
1414 }
1415 if err := rows.Scan(&id, &code, &name, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &callsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripeMonthlyPriceID, &stripeYearlyPriceID); err != nil {
1416 return nil, err
1417 } else if err := rows.Err(); err != nil {
1418 return nil, err
1419 }
1420 // When changed, note readUser() as well
1421 return &Tier{
1422 ID: id,
1423 Code: code,
1424 Name: name,
1425 MessageLimit: messagesLimit.Int64,
1426 MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
1427 EmailLimit: emailsLimit.Int64,
1428 CallLimit: callsLimit.Int64,
1429 ReservationLimit: reservationsLimit.Int64,
1430 AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
1431 AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
1432 AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
1433 AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
1434 StripeMonthlyPriceID: stripeMonthlyPriceID.String, // May be empty
1435 StripeYearlyPriceID: stripeYearlyPriceID.String, // May be empty
1436 }, nil
1437 }
1438
1439 // PhoneNumbers returns all phone numbers for the user with the given user ID
1440 func (a *Manager) PhoneNumbers(userID string) ([]string, error) {
1441 // Primary read: backs GET /account (read-your-writes after a sync event).
1442 rows, err := a.db.Query(a.queries.selectPhoneNumbers, userID)
1443 if err != nil {
1444 return nil, err
1445 }
1446 defer rows.Close()
1447 phoneNumbers := make([]string, 0)
1448 for {
1449 phoneNumber, err := a.readPhoneNumber(rows)
1450 if errors.Is(err, ErrPhoneNumberNotFound) {
1451 break
1452 } else if err != nil {
1453 return nil, err
1454 }
1455 phoneNumbers = append(phoneNumbers, phoneNumber)
1456 }
1457 return phoneNumbers, nil
1458 }
1459
1460 // AddPhoneNumber adds a phone number to the user with the given user ID
1461 func (a *Manager) AddPhoneNumber(userID, phoneNumber string) error {
1462 if _, err := a.db.Exec(a.queries.insertPhoneNumber, userID, phoneNumber); err != nil {
1463 if isUniqueConstraintError(err) {
1464 return ErrPhoneNumberExists
1465 }
1466 return err
1467 }
1468 return nil
1469 }
1470
1471 // RemovePhoneNumber deletes a phone number from the user with the given user ID
1472 func (a *Manager) RemovePhoneNumber(userID, phoneNumber string) error {
1473 _, err := a.db.Exec(a.queries.deletePhoneNumber, userID, phoneNumber)
1474 return err
1475 }
1476
1477 func (a *Manager) readPhoneNumber(rows *sql.Rows) (string, error) {
1478 var phoneNumber string
1479 if !rows.Next() {
1480 return "", ErrPhoneNumberNotFound
1481 }
1482 if err := rows.Scan(&phoneNumber); err != nil {
1483 return "", err
1484 } else if err := rows.Err(); err != nil {
1485 return "", err
1486 }
1487 return phoneNumber, nil
1488 }
1489
1490 // Emails returns all verified email addresses for the user with the given user ID, each carrying
1491 // whether it is the primary (recovery) address. Because the primary flag is included, callers that
1492 // need it (e.g. the account view) do not need a separate PrimaryEmail call.
1493 func (a *Manager) Emails(userID string) (Emails, error) {
1494 // Primary read: backs GET /account (read-your-writes after a sync event).
1495 rows, err := a.db.Query(a.queries.selectEmails, userID)
1496 if err != nil {
1497 return nil, err
1498 }
1499 defer rows.Close()
1500 emails := make(Emails, 0)
1501 for {
1502 email, err := a.readEmail(rows)
1503 if errors.Is(err, ErrEmailNotFound) {
1504 break
1505 } else if err != nil {
1506 return nil, err
1507 }
1508 emails = append(emails, email)
1509 }
1510 return emails, nil
1511 }
1512
1513 // AddEmail adds a verified email address to the user with the given user ID
1514 func (a *Manager) AddEmail(userID, email string) error {
1515 if _, err := a.db.Exec(a.queries.insertEmail, userID, email); err != nil {
1516 if isUniqueConstraintError(err) {
1517 return ErrEmailExists
1518 }
1519 return err
1520 }
1521 return nil
1522 }
1523
1524 // RemoveEmail deletes a verified email address from the user with the given user ID.
1525 // Removing the primary email leaves the account with no primary -- there is deliberately
1526 // no auto-promotion of another verified address; the user is nudged to pick a new one.
1527 func (a *Manager) RemoveEmail(userID, email string) error {
1528 _, err := a.db.Exec(a.queries.deleteEmail, userID, email)
1529 return err
1530 }
1531
1532 // PrimaryEmail returns the user's primary (recovery) email address, or an empty string if
1533 // the user has not designated one.
1534 func (a *Manager) PrimaryEmail(userID string) (string, error) {
1535 var email sql.NullString
1536 // Primary read: backs GET /account (read-your-writes after a sync event).
1537 err := a.db.QueryRow(a.queries.selectPrimaryEmail, userID).Scan(&email)
1538 if errors.Is(err, sql.ErrNoRows) {
1539 return "", nil
1540 } else if err != nil {
1541 return "", err
1542 }
1543 return email.String, nil
1544 }
1545
1546 // UserIDByPrimaryEmail returns the ID of the (at most one) account for which the given address
1547 // is the primary email. Returns ErrUserNotFound if no account claims it as primary. Used by the
1548 // password-reset request flow to resolve an email identifier to a single account.
1549 func (a *Manager) UserIDByPrimaryEmail(email string) (string, error) {
1550 var userID string
1551 err := a.db.ReadOnly().QueryRow(a.queries.selectUserIDByPrimary, email).Scan(&userID)
1552 if errors.Is(err, sql.ErrNoRows) {
1553 return "", ErrUserNotFound
1554 } else if err != nil {
1555 return "", err
1556 }
1557 return userID, nil
1558 }
1559
1560 // PendingEmails returns the user's unverified (pending) email addresses, i.e. addresses with
1561 // an outstanding email-verification magic link.
1562 func (a *Manager) PendingEmails(userID string) ([]string, error) {
1563 // Primary read: backs GET /account (read-your-writes after a sync event).
1564 rows, err := a.db.Query(a.queries.selectPendingEmails, string(MagicLinkKindEmailVerify), userID)
1565 if err != nil {
1566 return nil, err
1567 }
1568 defer rows.Close()
1569 emails := make([]string, 0)
1570 for rows.Next() {
1571 var email string
1572 if err := rows.Scan(&email); err != nil {
1573 return nil, err
1574 }
1575 emails = append(emails, email)
1576 }
1577 if err := rows.Err(); err != nil {
1578 return nil, err
1579 }
1580 return emails, nil
1581 }
1582
1583 // SetPrimaryEmail marks a verified email address as the user's primary (recovery) email,
1584 // clearing any previous primary in the same transaction. Returns ErrEmailNotFound if the
1585 // address is not verified on the account, or ErrEmailPrimaryElsewhere if it is already the
1586 // primary email on another account (enforced by the global partial unique index).
1587 func (a *Manager) SetPrimaryEmail(userID, email string) error {
1588 return db.ExecTx(a.db, func(tx *sql.Tx) error {
1589 if _, err := tx.Exec(a.queries.updateEmailClearPrimary, userID); err != nil {
1590 return err
1591 }
1592 res, err := tx.Exec(a.queries.updateEmailSetPrimary, userID, email)
1593 if err != nil {
1594 if isUniqueConstraintError(err) {
1595 return ErrEmailPrimaryElsewhere
1596 }
1597 return err
1598 }
1599 affected, err := res.RowsAffected()
1600 if err != nil {
1601 return err
1602 }
1603 if affected == 0 {
1604 return ErrEmailNotFound // Address not verified on this account
1605 }
1606 return nil
1607 })
1608 }
1609
1610 // AddMagicLink generates a fresh magic-link token of the given kind, stores it (hashed, replacing
1611 // any existing link in the same scope), and returns the RAW token for use in the emailed link.
1612 // Only the hash is persisted; the raw token is never stored. email is the address being verified
1613 // for email_verify, and "" for password_reset.
1614 //
1615 // The scope replaced is, for email_verify, the (user_id, email) pair (one pending verification per
1616 // address); for password_reset, the user_id (one active reset per account). The replace-delete and
1617 // the insert run in one transaction so a re-request atomically supersedes the old token.
1618 func (a *Manager) AddMagicLink(kind MagicLinkKind, userID, email string, ttl time.Duration) (string, error) {
1619 token := generateLinkToken()
1620 now := time.Now()
1621 m := &MagicLink{
1622 TokenHash: hashToken(token),
1623 Kind: kind,
1624 UserID: userID,
1625 Email: email,
1626 Expires: now.Add(ttl).Unix(),
1627 Created: now.Unix(),
1628 }
1629 err := db.ExecTx(a.db, func(tx *sql.Tx) error {
1630 switch m.Kind {
1631 case MagicLinkKindEmailVerify:
1632 if _, err := tx.Exec(a.queries.deleteMagicLinkEmailVerify, string(MagicLinkKindEmailVerify), m.UserID, m.Email); err != nil {
1633 return err
1634 }
1635 case MagicLinkKindPasswordReset:
1636 if _, err := tx.Exec(a.queries.deleteMagicLinkResetPassword, string(MagicLinkKindPasswordReset), m.UserID); err != nil {
1637 return err
1638 }
1639 default:
1640 return ErrInvalidArgument
1641 }
1642 if _, err := tx.Exec(a.queries.insertMagicLink, m.TokenHash, string(m.Kind), m.UserID, nullString(m.Email), m.Expires, m.Created); err != nil {
1643 return err
1644 }
1645 return nil
1646 })
1647 if err != nil {
1648 return "", err
1649 }
1650 return token, nil
1651 }
1652
1653 // MagicLinkByToken looks up a magic link by its raw token (hashing it first). See MagicLinkByHash.
1654 func (a *Manager) MagicLinkByToken(rawToken string) (*MagicLink, error) {
1655 return a.MagicLinkByHash(hashToken(rawToken))
1656 }
1657
1658 // MagicLinkByHash looks up a magic link by the hex SHA-256 of its raw token, returning
1659 // ErrMagicLinkNotFound if none exists. Callers must assert the returned Kind matches the flow
1660 // they serve and check Expires themselves.
1661 func (a *Manager) MagicLinkByHash(tokenHash string) (*MagicLink, error) {
1662 var m MagicLink
1663 var kind string
1664 var email sql.NullString
1665 err := a.db.ReadOnly().QueryRow(a.queries.selectMagicLinkByHash, tokenHash).Scan(&m.TokenHash, &kind, &m.UserID, &email, &m.Expires, &m.Created)
1666 if errors.Is(err, sql.ErrNoRows) {
1667 return nil, ErrMagicLinkNotFound
1668 } else if err != nil {
1669 return nil, err
1670 }
1671 m.Kind = MagicLinkKind(kind)
1672 m.Email = email.String
1673 return &m, nil
1674 }
1675
1676 // DeleteMagicLinkByToken deletes a magic link identified by its raw token (single-use consume).
1677 // Used to enforce single use after a reset is performed (email verification deletes the row
1678 // inside VerifyEmail's transaction).
1679 func (a *Manager) DeleteMagicLinkByToken(rawToken string) error {
1680 _, err := a.db.Exec(a.queries.deleteMagicLinkByHash, hashToken(rawToken))
1681 return err
1682 }
1683
1684 // DeleteEmailVerification removes any pending email verification for (userID, email). Used when
1685 // an unverified (pending) address is cancelled/deleted from the account.
1686 func (a *Manager) DeleteEmailVerification(userID, email string) error {
1687 _, err := a.db.Exec(a.queries.deleteMagicLinkEmailVerify, string(MagicLinkKindEmailVerify), userID, email)
1688 return err
1689 }
1690
1691 // VerifyEmail consumes an email-verification magic link, identified by its raw token: after
1692 // validating the token (kind + expiry), it deletes the link, adds the address to the user's
1693 // verified emails, and -- if the user has no primary email yet and the address is not already
1694 // primary on another account -- promotes the new address to primary. All mutations run in one
1695 // transaction. A primary collision simply leaves the address verified but non-primary. Provisioned
1696 // users never get a primary (the recovery email is meaningless for them -- they can't reset).
1697 // Returns the consumed link.
1698 func (a *Manager) VerifyEmail(rawToken string) (*MagicLink, error) {
1699 tokenHash := hashToken(rawToken)
1700 m, err := a.MagicLinkByHash(tokenHash)
1701 if err != nil {
1702 return nil, err
1703 }
1704 if m.Kind != MagicLinkKindEmailVerify || time.Now().Unix() > m.Expires {
1705 return nil, ErrMagicLinkNotFound
1706 }
1707 err = db.ExecTx(a.db, func(tx *sql.Tx) error {
1708 // Single use: delete the link, then add the (idempotent) verified address
1709 if _, err := tx.Exec(a.queries.deleteMagicLinkByHash, tokenHash); err != nil {
1710 return err
1711 }
1712 if _, err := tx.Exec(a.queries.insertEmailIgnore, m.UserID, m.Email); err != nil {
1713 return err
1714 }
1715 // Promote to primary only if the user has none yet and the address is globally free.
1716 // We check with SELECTs rather than catching a unique violation, because Postgres aborts
1717 // the whole transaction on any constraint error (which would undo the verified-email add).
1718 var primary sql.NullString
1719 err := tx.QueryRow(a.queries.selectPrimaryEmail, m.UserID).Scan(&primary)
1720 if err != nil && !errors.Is(err, sql.ErrNoRows) {
1721 return err
1722 }
1723 if primary.String != "" {
1724 return nil // User already has a primary -- leave it
1725 }
1726 // If the address is already another account's primary, leave it a verified secondary here
1727 var ownerUserID string
1728 if err = tx.QueryRow(a.queries.selectUserIDByPrimary, m.Email).Scan(&ownerUserID); err == nil {
1729 return nil // Address is primary elsewhere -> not promoted
1730 } else if !errors.Is(err, sql.ErrNoRows) {
1731 return err // Real query error
1732 }
1733 // Address is globally free -> promote it to this user's primary
1734 if _, err := tx.Exec(a.queries.updateEmailSetPrimary, m.UserID, m.Email); err != nil {
1735 return err
1736 }
1737 return nil
1738 })
1739 if err != nil {
1740 return nil, err
1741 }
1742 return m, nil
1743 }
1744
1745 // ResetPassword consumes a password-reset magic link, identified by its raw token: after
1746 // validating the token (kind + expiry), it sets the user's password and deletes the link in one
1747 // transaction. Existing access tokens are intentionally left valid (only the password changes).
1748 // Returns ErrMagicLinkNotFound if the token is invalid, expired, or not a reset token.
1749 func (a *Manager) ResetPassword(rawToken, newPassword string) error {
1750 m, err := a.MagicLinkByHash(hashToken(rawToken))
1751 if err != nil {
1752 return err
1753 }
1754 if m.Kind != MagicLinkKindPasswordReset || time.Now().Unix() > m.Expires {
1755 return ErrMagicLinkNotFound
1756 }
1757 u, err := a.UserByID(m.UserID)
1758 if err != nil {
1759 return err
1760 }
1761 if u.Provisioned {
1762 return ErrProvisionedUserChange // Provisioned users get their password from the config file, not reset
1763 }
1764 hash, err := HashPassword(newPassword, a.config.BcryptCost)
1765 if err != nil {
1766 return err
1767 }
1768 return db.ExecTx(a.db, func(tx *sql.Tx) error {
1769 if err := a.changePasswordHashTx(tx, u.Name, hash); err != nil {
1770 return err
1771 }
1772 if _, err := tx.Exec(a.queries.deleteMagicLinkByHash, m.TokenHash); err != nil {
1773 return err
1774 }
1775 return nil
1776 })
1777 }
1778
1779 // deleteExpiredMagicLinks removes magic links whose expiry has passed. Expiry is also enforced
1780 // on read, so this is purely housekeeping to bound table growth; it runs from the reaper loop.
1781 func (a *Manager) deleteExpiredMagicLinks() error {
1782 _, err := a.db.Exec(a.queries.deleteExpiredMagicLinks, time.Now().Unix())
1783 return err
1784 }
1785
1786 func (a *Manager) readEmail(rows *sql.Rows) (*Email, error) {
1787 var address string
1788 var primary bool
1789 if !rows.Next() {
1790 return nil, ErrEmailNotFound
1791 }
1792 if err := rows.Scan(&address, &primary); err != nil {
1793 return nil, err
1794 } else if err := rows.Err(); err != nil {
1795 return nil, err
1796 }
1797 return &Email{Address: address, Primary: primary}, nil
1798 }
1799
1800 // ChangeBilling updates a user's billing fields
1801 func (a *Manager) ChangeBilling(username string, billing *Billing) error {
1802 if _, err := a.db.Exec(a.queries.updateBilling, nullString(billing.StripeCustomerID), nullString(billing.StripeSubscriptionID), nullString(string(billing.StripeSubscriptionStatus)), nullString(string(billing.StripeSubscriptionInterval)), nullInt64(billing.StripeSubscriptionPaidUntil.Unix()), nullInt64(billing.StripeSubscriptionCancelAt.Unix()), username); err != nil {
1803 return err
1804 }
1805 return nil
1806 }
1807
1808 // maybeProvisionUsersAccessAndTokens provisions users, access control entries, and tokens based on the config.
1809 func (a *Manager) maybeProvisionUsersAccessAndTokens() error {
1810 if !a.config.ProvisionEnabled {
1811 return nil
1812 }
1813 // If there is nothing to provision, remove any previously provisioned items using
1814 // cheap targeted queries, avoiding the expensive Users() call that loads all users.
1815 if len(a.config.Users) == 0 && len(a.config.Access) == 0 && len(a.config.Tokens) == 0 {
1816 return a.removeAllProvisioned()
1817 }
1818 // If there are provisioned users, do it the slow way
1819 existingUsers, err := a.Users()
1820 if err != nil {
1821 return err
1822 }
1823 provisionUsernames := util.Map(a.config.Users, func(u *User) string {
1824 return u.Name
1825 })
1826 existingTokens, err := a.allProvisionedTokens()
1827 if err != nil {
1828 return err
1829 }
1830 return db.ExecTx(a.db, func(tx *sql.Tx) error {
1831 if err := a.maybeProvisionUsers(tx, provisionUsernames, existingUsers); err != nil {
1832 return fmt.Errorf("failed to provision users: %v", err)
1833 }
1834 if err := a.maybeProvisionGrants(tx); err != nil {
1835 return fmt.Errorf("failed to provision grants: %v", err)
1836 }
1837 if err := a.maybeProvisionTokens(tx, provisionUsernames, existingTokens); err != nil {
1838 return fmt.Errorf("failed to provision tokens: %v", err)
1839 }
1840 return nil
1841 })
1842 }
1843
1844 // removeAllProvisioned removes all provisioned users, access entries, and tokens. This is the fast path
1845 // for when there is nothing to provision, avoiding the expensive Users() call.
1846 func (a *Manager) removeAllProvisioned() error {
1847 return db.ExecTx(a.db, func(tx *sql.Tx) error {
1848 if _, err := tx.Exec(a.queries.deleteUserAccessProvisioned); err != nil {
1849 return err
1850 }
1851 if _, err := tx.Exec(a.queries.deleteAllProvisionedTokens); err != nil {
1852 return err
1853 }
1854 if _, err := tx.Exec(a.queries.deleteUsersProvisioned); err != nil {
1855 return err
1856 }
1857 return nil
1858 })
1859 }
1860
1861 // maybeProvisionUsers checks if the users in the config are provisioned, and adds or updates them.
1862 // It also removes users that are provisioned, but not in the config anymore.
1863 func (a *Manager) maybeProvisionUsers(tx *sql.Tx, provisionUsernames []string, existingUsers []*User) error {
1864 // Remove users that are provisioned, but not in the config anymore
1865 for _, user := range existingUsers {
1866 if user.Name == Everyone {
1867 continue
1868 } else if user.Provisioned && !util.Contains(provisionUsernames, user.Name) {
1869 if err := a.removeUserTx(tx, user.Name); err != nil {
1870 return fmt.Errorf("failed to remove provisioned user %s: %v", user.Name, err)
1871 }
1872 }
1873 }
1874 // Add or update provisioned users
1875 for _, user := range a.config.Users {
1876 if user.Name == Everyone {
1877 continue
1878 }
1879 existingUser, exists := util.Find(existingUsers, func(u *User) bool {
1880 return u.Name == user.Name
1881 })
1882 if !exists {
1883 if err := a.addUserTx(tx, user.Name, user.Hash, user.Role, true); err != nil && !errors.Is(err, ErrUserExists) {
1884 return fmt.Errorf("failed to add provisioned user %s: %v", user.Name, err)
1885 }
1886 } else {
1887 if !existingUser.Provisioned {
1888 if err := a.changeProvisionedTx(tx, user.Name, true); err != nil {
1889 return fmt.Errorf("failed to change provisioned status for user %s: %v", user.Name, err)
1890 }
1891 }
1892 if existingUser.Hash != user.Hash {
1893 if err := a.changePasswordHashTx(tx, user.Name, user.Hash); err != nil {
1894 return fmt.Errorf("failed to change password for provisioned user %s: %v", user.Name, err)
1895 }
1896 }
1897 if existingUser.Role != user.Role {
1898 if err := a.changeRoleTx(tx, user.Name, user.Role); err != nil {
1899 return fmt.Errorf("failed to change role for provisioned user %s: %v", user.Name, err)
1900 }
1901 }
1902 }
1903 }
1904 return nil
1905 }
1906
1907 // maybeProvisionGrants removes all provisioned grants, and (re-)adds the grants from the config.
1908 //
1909 // Unlike users and tokens, grants can be just re-added, because they do not carry any state (such as last
1910 // access time) or do not have dependent resources (such as grants or tokens).
1911 func (a *Manager) maybeProvisionGrants(tx *sql.Tx) error {
1912 // Remove all provisioned grants
1913 if _, err := tx.Exec(a.queries.deleteUserAccessProvisioned); err != nil {
1914 return err
1915 }
1916 // (Re-)add provisioned grants
1917 for username, grants := range a.config.Access {
1918 user, exists := util.Find(a.config.Users, func(u *User) bool {
1919 return u.Name == username
1920 })
1921 if !exists && username != Everyone {
1922 return fmt.Errorf("user %s is not a provisioned user, refusing to add ACL entry", username)
1923 } else if user != nil && user.Role == RoleAdmin {
1924 return fmt.Errorf("adding access control entries is not allowed for admin roles for user %s", username)
1925 }
1926 for _, grant := range grants {
1927 if err := a.resetAccessTx(tx, username, grant.TopicPattern); err != nil {
1928 return fmt.Errorf("failed to reset access for user %s and topic %s: %v", username, grant.TopicPattern, err)
1929 }
1930 if err := a.allowAccessTx(tx, username, grant.TopicPattern, grant.Permission, true); err != nil {
1931 return err
1932 }
1933 }
1934 }
1935 return nil
1936 }
1937
1938 func (a *Manager) maybeProvisionTokens(tx *sql.Tx, provisionUsernames []string, existingTokens []*Token) error {
1939 // Remove tokens that are provisioned, but not in the config anymore
1940 var provisionTokens []string
1941 for _, userTokens := range a.config.Tokens {
1942 for _, token := range userTokens {
1943 provisionTokens = append(provisionTokens, token.Value)
1944 }
1945 }
1946 for _, existingToken := range existingTokens {
1947 if !slices.Contains(provisionTokens, existingToken.Value) {
1948 if _, err := tx.Exec(a.queries.deleteProvisionedToken, existingToken.Value); err != nil {
1949 return fmt.Errorf("failed to remove provisioned token %s: %v", existingToken.Value, err)
1950 }
1951 }
1952 }
1953 // (Re-)add provisioned tokens
1954 for username, tokens := range a.config.Tokens {
1955 if !slices.Contains(provisionUsernames, username) && username != Everyone {
1956 return fmt.Errorf("user %s is not a provisioned user, refusing to add tokens", username)
1957 }
1958 var userID string
1959 if err := tx.QueryRow(a.queries.selectUserIDFromUsername, username).Scan(&userID); err != nil {
1960 return fmt.Errorf("failed to find provisioned user %s for provisioned tokens: %v", username, err)
1961 }
1962 for _, token := range tokens {
1963 if _, err := a.createTokenTx(tx, userID, token.Value, token.Label, time.Unix(0, 0), netip.IPv4Unspecified(), time.Unix(0, 0), 0, true); err != nil {
1964 return err
1965 }
1966 }
1967 }
1968 return nil
1969 }
1970
1971 // Close stops background goroutines and closes the underlying database.
1972 func (a *Manager) Close() error {
1973 select {
1974 case <-a.quit:
1975 // Already closed
1976 default:
1977 close(a.quit)
1978 }
1979 return a.db.Close()
1980 }
1981
1982 // isUniqueConstraintError checks if the error is a unique constraint violation for both SQLite and PostgreSQL
1983 func isUniqueConstraintError(err error) bool {
1984 errStr := err.Error()
1985 return strings.Contains(errStr, "UNIQUE constraint failed") || strings.Contains(errStr, "23505")
1986 }