| 1 |
package user |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"net/netip" |
| 6 |
"strings" |
| 7 |
"time" |
| 8 |
|
| 9 |
"heckel.io/ntfy/v2/log" |
| 10 |
"heckel.io/ntfy/v2/payments" |
| 11 |
) |
| 12 |
|
| 13 |
// User is a struct that represents a user |
| 14 |
type User struct { |
| 15 |
ID string |
| 16 |
Name string |
| 17 |
Hash string // Password hash (bcrypt) |
| 18 |
Token string // Only set if token was used to log in |
| 19 |
Role Role |
| 20 |
Prefs *Prefs |
| 21 |
Tier *Tier |
| 22 |
Stats *Stats |
| 23 |
Billing *Billing |
| 24 |
SyncTopic string |
| 25 |
Provisioned bool // Whether the user was provisioned by the config file |
| 26 |
Deleted bool // Whether the user was soft-deleted |
| 27 |
} |
| 28 |
|
| 29 |
// TierID returns the ID of the User.Tier, or an empty string if the user has no tier, |
| 30 |
// or if the user itself is nil. |
| 31 |
func (u *User) TierID() string { |
| 32 |
if u == nil || u.Tier == nil { |
| 33 |
return "" |
| 34 |
} |
| 35 |
return u.Tier.ID |
| 36 |
} |
| 37 |
|
| 38 |
// IsAdmin returns true if the user is an admin |
| 39 |
func (u *User) IsAdmin() bool { |
| 40 |
return u != nil && u.Role == RoleAdmin |
| 41 |
} |
| 42 |
|
| 43 |
// IsUser returns true if the user is a regular user, not an admin |
| 44 |
func (u *User) IsUser() bool { |
| 45 |
return u != nil && u.Role == RoleUser |
| 46 |
} |
| 47 |
|
| 48 |
// Auther is an interface for authentication and authorization |
| 49 |
type Auther interface { |
| 50 |
// Authenticate checks a login identifier (username or verified primary email) and password |
| 51 |
// and returns a user if correct. The method returns in constant-ish time, regardless of |
| 52 |
// whether the identifier exists or the password is correct or incorrect. |
| 53 |
Authenticate(identifier, password string) (*User, error) |
| 54 |
|
| 55 |
// Authorize returns nil if the given user has access to the given topic using the desired |
| 56 |
// permission. The user param may be nil to signal an anonymous user. |
| 57 |
Authorize(user *User, topic string, perm Permission) error |
| 58 |
} |
| 59 |
|
| 60 |
// Token represents a user token, including expiry date |
| 61 |
type Token struct { |
| 62 |
Value string |
| 63 |
Label string |
| 64 |
LastAccess time.Time |
| 65 |
LastOrigin netip.Addr |
| 66 |
Expires time.Time |
| 67 |
Provisioned bool |
| 68 |
} |
| 69 |
|
| 70 |
// TokenUpdate holds information about the last access time and origin IP address of a token |
| 71 |
type TokenUpdate struct { |
| 72 |
LastAccess time.Time |
| 73 |
LastOrigin netip.Addr |
| 74 |
} |
| 75 |
|
| 76 |
// MagicLinkKind discriminates the two link-token flows stored in the user_magic_link table. |
| 77 |
type MagicLinkKind string |
| 78 |
|
| 79 |
// Magic link kinds |
| 80 |
const ( |
| 81 |
MagicLinkKindEmailVerify MagicLinkKind = "email_verify" |
| 82 |
MagicLinkKindPasswordReset MagicLinkKind = "password_reset" |
| 83 |
) |
| 84 |
|
| 85 |
// MagicLink is a pending, single-use link token -- either an email verification or a |
| 86 |
// password reset, distinguished by Kind. The raw token travels in the emailed link; |
| 87 |
// only its TokenHash (hex SHA-256) is persisted. |
| 88 |
type MagicLink struct { |
| 89 |
TokenHash string |
| 90 |
Kind MagicLinkKind |
| 91 |
UserID string |
| 92 |
Email string // Address being verified for email_verify; empty (NULL) for password_reset |
| 93 |
Expires int64 |
| 94 |
Created int64 |
| 95 |
} |
| 96 |
|
| 97 |
// Prefs represents a user's configuration settings |
| 98 |
type Prefs struct { |
| 99 |
Language *string `json:"language,omitempty"` |
| 100 |
DateFormat *string `json:"date_format,omitempty"` |
| 101 |
TimeFormat *string `json:"time_format,omitempty"` |
| 102 |
Notification *NotificationPrefs `json:"notification,omitempty"` |
| 103 |
Subscriptions []*Subscription `json:"subscriptions,omitempty"` |
| 104 |
} |
| 105 |
|
| 106 |
// Tier represents a user's account type, including its account limits |
| 107 |
type Tier struct { |
| 108 |
ID string // Tier identifier (ti_...) |
| 109 |
Code string // Code of the tier |
| 110 |
Name string // Name of the tier |
| 111 |
MessageLimit int64 // Daily message limit |
| 112 |
MessageExpiryDuration time.Duration // Cache duration for messages |
| 113 |
EmailLimit int64 // Daily email limit |
| 114 |
CallLimit int64 // Daily phone call limit |
| 115 |
ReservationLimit int64 // Number of topic reservations allowed by user |
| 116 |
AttachmentFileSizeLimit int64 // Max file size per file (bytes) |
| 117 |
AttachmentTotalSizeLimit int64 // Total file size for all files of this user (bytes) |
| 118 |
AttachmentExpiryDuration time.Duration // Duration after which attachments will be deleted |
| 119 |
AttachmentBandwidthLimit int64 // Daily bandwidth limit for the user |
| 120 |
StripeMonthlyPriceID string // Monthly price ID for paid tiers (price_...) |
| 121 |
StripeYearlyPriceID string // Yearly price ID for paid tiers (price_...) |
| 122 |
} |
| 123 |
|
| 124 |
// Context returns fields for the log |
| 125 |
func (t *Tier) Context() log.Context { |
| 126 |
return log.Context{ |
| 127 |
"tier_id": t.ID, |
| 128 |
"tier_code": t.Code, |
| 129 |
"stripe_monthly_price_id": t.StripeMonthlyPriceID, |
| 130 |
"stripe_yearly_price_id": t.StripeYearlyPriceID, |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
// Subscription represents a user's topic subscription |
| 135 |
type Subscription struct { |
| 136 |
BaseURL string `json:"base_url"` |
| 137 |
Topic string `json:"topic"` |
| 138 |
DisplayName *string `json:"display_name"` |
| 139 |
} |
| 140 |
|
| 141 |
// Context returns fields for the log |
| 142 |
func (s *Subscription) Context() log.Context { |
| 143 |
return log.Context{ |
| 144 |
"base_url": s.BaseURL, |
| 145 |
"topic": s.Topic, |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
// NotificationPrefs represents the user's notification settings |
| 150 |
type NotificationPrefs struct { |
| 151 |
Sound *string `json:"sound,omitempty"` |
| 152 |
MinPriority *int `json:"min_priority,omitempty"` |
| 153 |
DeleteAfter *int `json:"delete_after,omitempty"` |
| 154 |
} |
| 155 |
|
| 156 |
// Stats is a struct holding daily user statistics |
| 157 |
type Stats struct { |
| 158 |
Messages int64 |
| 159 |
Emails int64 |
| 160 |
Calls int64 |
| 161 |
} |
| 162 |
|
| 163 |
// Billing is a struct holding a user's billing information |
| 164 |
type Billing struct { |
| 165 |
StripeCustomerID string |
| 166 |
StripeSubscriptionID string |
| 167 |
StripeSubscriptionStatus payments.SubscriptionStatus |
| 168 |
StripeSubscriptionInterval payments.PriceRecurringInterval |
| 169 |
StripeSubscriptionPaidUntil time.Time |
| 170 |
StripeSubscriptionCancelAt time.Time |
| 171 |
} |
| 172 |
|
| 173 |
// Grant is a struct that represents an access control entry to a topic by a user |
| 174 |
type Grant struct { |
| 175 |
TopicPattern string // May include wildcard (*) |
| 176 |
Permission Permission |
| 177 |
Provisioned bool // Whether the grant was provisioned by the config file |
| 178 |
} |
| 179 |
|
| 180 |
// Reservation is a struct that represents the ownership over a topic by a user |
| 181 |
type Reservation struct { |
| 182 |
Topic string |
| 183 |
Owner Permission |
| 184 |
Everyone Permission |
| 185 |
} |
| 186 |
|
| 187 |
// Email is a verified email address on a user account, along with whether it is the user's |
| 188 |
// designated primary (recovery) address. |
| 189 |
type Email struct { |
| 190 |
Address string |
| 191 |
Primary bool |
| 192 |
} |
| 193 |
|
| 194 |
// Emails is a list of verified email addresses for a user. |
| 195 |
type Emails []*Email |
| 196 |
|
| 197 |
// Strings returns just the address strings, in the same order. It is a convenience for callers |
| 198 |
// that only care about the addresses and not the primary flag. |
| 199 |
func (e Emails) Strings() []string { |
| 200 |
addresses := make([]string, len(e)) |
| 201 |
for i, email := range e { |
| 202 |
addresses[i] = email.Address |
| 203 |
} |
| 204 |
return addresses |
| 205 |
} |
| 206 |
|
| 207 |
// Contains reports whether the given address is in the list. |
| 208 |
func (e Emails) Contains(address string) bool { |
| 209 |
for _, email := range e { |
| 210 |
if email.Address == address { |
| 211 |
return true |
| 212 |
} |
| 213 |
} |
| 214 |
return false |
| 215 |
} |
| 216 |
|
| 217 |
// Permission represents a read or write permission to a topic |
| 218 |
type Permission uint8 |
| 219 |
|
| 220 |
// Permissions to a topic |
| 221 |
const ( |
| 222 |
PermissionDenyAll Permission = iota |
| 223 |
PermissionRead |
| 224 |
PermissionWrite |
| 225 |
PermissionReadWrite // 3! |
| 226 |
) |
| 227 |
|
| 228 |
// NewPermission is a helper to create a Permission based on read/write bool values |
| 229 |
func NewPermission(read, write bool) Permission { |
| 230 |
p := uint8(0) |
| 231 |
if read { |
| 232 |
p |= uint8(PermissionRead) |
| 233 |
} |
| 234 |
if write { |
| 235 |
p |= uint8(PermissionWrite) |
| 236 |
} |
| 237 |
return Permission(p) |
| 238 |
} |
| 239 |
|
| 240 |
// ParsePermission parses the string representation and returns a Permission |
| 241 |
func ParsePermission(s string) (Permission, error) { |
| 242 |
switch strings.ToLower(s) { |
| 243 |
case "read-write", "rw": |
| 244 |
return NewPermission(true, true), nil |
| 245 |
case "read-only", "read", "ro": |
| 246 |
return NewPermission(true, false), nil |
| 247 |
case "write-only", "write", "wo": |
| 248 |
return NewPermission(false, true), nil |
| 249 |
case "deny-all", "deny", "none": |
| 250 |
return NewPermission(false, false), nil |
| 251 |
default: |
| 252 |
return NewPermission(false, false), errors.New("invalid permission") |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
// IsRead returns true if readable |
| 257 |
func (p Permission) IsRead() bool { |
| 258 |
return p&PermissionRead != 0 |
| 259 |
} |
| 260 |
|
| 261 |
// IsWrite returns true if writable |
| 262 |
func (p Permission) IsWrite() bool { |
| 263 |
return p&PermissionWrite != 0 |
| 264 |
} |
| 265 |
|
| 266 |
// IsReadWrite returns true if readable and writable |
| 267 |
func (p Permission) IsReadWrite() bool { |
| 268 |
return p.IsRead() && p.IsWrite() |
| 269 |
} |
| 270 |
|
| 271 |
// String returns a string representation of the permission |
| 272 |
func (p Permission) String() string { |
| 273 |
if p.IsReadWrite() { |
| 274 |
return "read-write" |
| 275 |
} else if p.IsRead() { |
| 276 |
return "read-only" |
| 277 |
} else if p.IsWrite() { |
| 278 |
return "write-only" |
| 279 |
} |
| 280 |
return "deny-all" |
| 281 |
} |
| 282 |
|
| 283 |
// Role represents a user's role, either admin or regular user |
| 284 |
type Role string |
| 285 |
|
| 286 |
// User roles |
| 287 |
const ( |
| 288 |
RoleAdmin = Role("admin") // Some queries have these values hardcoded! |
| 289 |
RoleUser = Role("user") |
| 290 |
RoleAnonymous = Role("anonymous") |
| 291 |
) |
| 292 |
|
| 293 |
// Everyone is a special username representing anonymous users |
| 294 |
const ( |
| 295 |
Everyone = "*" |
| 296 |
everyoneID = "u_everyone" |
| 297 |
) |
| 298 |
|
| 299 |
// Config holds the configuration for the user Manager |
| 300 |
type Config struct { |
| 301 |
Filename string // Database filename, e.g. "/var/lib/ntfy/user.db" (SQLite) |
| 302 |
DatabaseURL string // Database connection string (PostgreSQL) |
| 303 |
StartupQueries string // Queries to run on startup, e.g. to create initial users or tiers (SQLite only) |
| 304 |
DefaultAccess Permission // Default permission if no ACL matches |
| 305 |
ProvisionEnabled bool // Hack: Enable auto-provisioning of users and access grants, disabled for "ntfy user" commands |
| 306 |
Users []*User // Predefined users to create on startup |
| 307 |
Access map[string][]*Grant // Predefined access grants to create on startup (username -> []*Grant) |
| 308 |
Tokens map[string][]*Token // Predefined users to create on startup (username -> []*Token) |
| 309 |
QueueWriterInterval time.Duration // Interval for the async queue writer to flush stats and token updates to the database |
| 310 |
BcryptCost int // Cost of generated passwords; lowering makes testing faster |
| 311 |
AccessCacheEnabled bool // Enables the in-memory ACL cache (high volume servers only) |
| 312 |
AccessCacheReloadInterval time.Duration // Reload interval for access cache, relevant for ACL writes from CLI |
| 313 |
ExpiredMagicLinkReapInterval time.Duration // Interval for sweeping expired email-verify/password-reset links |
| 314 |
} |
| 315 |
|
| 316 |
// Error constants used by the package |
| 317 |
var ( |
| 318 |
ErrUnauthenticated = errors.New("unauthenticated") |
| 319 |
ErrUnauthorized = errors.New("unauthorized") |
| 320 |
ErrInvalidArgument = errors.New("invalid argument") |
| 321 |
ErrUserNotFound = errors.New("user not found") |
| 322 |
ErrUserExists = errors.New("user already exists") |
| 323 |
ErrPasswordHashInvalid = errors.New("password hash must be a bcrypt hash, use 'ntfy user hash' to generate") |
| 324 |
ErrPasswordHashWeak = errors.New("password hash too weak, use 'ntfy user hash' to generate") |
| 325 |
ErrTierNotFound = errors.New("tier not found") |
| 326 |
ErrTokenNotFound = errors.New("token not found") |
| 327 |
ErrPhoneNumberNotFound = errors.New("phone number not found") |
| 328 |
ErrTooManyReservations = errors.New("new tier has lower reservation limit") |
| 329 |
ErrPhoneNumberExists = errors.New("phone number already exists") |
| 330 |
ErrEmailNotFound = errors.New("email not found") |
| 331 |
ErrEmailExists = errors.New("email already exists") |
| 332 |
ErrEmailPrimaryElsewhere = errors.New("email is the primary email on another account") |
| 333 |
ErrMagicLinkNotFound = errors.New("magic link not found") |
| 334 |
ErrProvisionedUserChange = errors.New("cannot change or delete provisioned user") |
| 335 |
ErrProvisionedTokenChange = errors.New("cannot change or delete provisioned token") |
| 336 |
) |
| 337 |
|
| 338 |
// queries holds the database-specific SQL queries |
| 339 |
type queries struct { |
| 340 |
// User queries |
| 341 |
selectUserByID string |
| 342 |
selectUserByName string |
| 343 |
selectUserByNameOrPrimaryEmail string |
| 344 |
selectUserByToken string |
| 345 |
selectUserByStripeCustomerID string |
| 346 |
selectUsernames string |
| 347 |
selectUsers string |
| 348 |
selectUserCount string |
| 349 |
selectUserIDFromUsername string |
| 350 |
insertUser string |
| 351 |
updateUserPass string |
| 352 |
updateUserRole string |
| 353 |
updateUserProvisioned string |
| 354 |
updateUserPrefs string |
| 355 |
updateUserStats string |
| 356 |
updateUserStatsResetAll string |
| 357 |
updateUserTier string |
| 358 |
updateUserDeleted string |
| 359 |
deleteUser string |
| 360 |
deleteUserTier string |
| 361 |
deleteUsersMarked string |
| 362 |
deleteUsersProvisioned string |
| 363 |
|
| 364 |
// Access queries |
| 365 |
selectTopicPerms string // Direct-DB authorizeTopicAccess query; used when the in-memory cache is disabled |
| 366 |
selectAccessCacheAll string // Bulk load: (user_name, topic, read, write) for the in-memory ACL cache |
| 367 |
selectAccessCacheUsers func(n int) string // Returns a per-users load query whose IN clause is sized for n usernames |
| 368 |
selectUserAllAccess string |
| 369 |
selectUserAccess string |
| 370 |
selectUserReservations string |
| 371 |
selectUserReservationsCount string |
| 372 |
selectUserReservationsOwner string |
| 373 |
selectUserHasReservation string |
| 374 |
selectOtherAccessCount string |
| 375 |
upsertUserAccess string |
| 376 |
deleteUserAccess string |
| 377 |
deleteUserAccessProvisioned string |
| 378 |
deleteTopicAccess string |
| 379 |
deleteAllAccess string |
| 380 |
|
| 381 |
// Token queries |
| 382 |
selectToken string |
| 383 |
selectTokens string |
| 384 |
selectTokenCount string |
| 385 |
selectAllProvisionedTokens string |
| 386 |
upsertToken string |
| 387 |
updateToken string |
| 388 |
updateTokenLastAccess string |
| 389 |
deleteToken string |
| 390 |
deleteProvisionedToken string |
| 391 |
deleteAllProvisionedTokens string |
| 392 |
deleteAllToken string |
| 393 |
deleteExpiredTokens string |
| 394 |
deleteExcessTokens string |
| 395 |
|
| 396 |
// Tier queries |
| 397 |
insertTier string |
| 398 |
selectTiers string |
| 399 |
selectTierByCode string |
| 400 |
selectTierByPriceID string |
| 401 |
updateTier string |
| 402 |
deleteTier string |
| 403 |
|
| 404 |
// Phone queries |
| 405 |
selectPhoneNumbers string |
| 406 |
insertPhoneNumber string |
| 407 |
deletePhoneNumber string |
| 408 |
|
| 409 |
// Email queries |
| 410 |
selectEmails string |
| 411 |
insertEmail string |
| 412 |
insertEmailIgnore string // Idempotent insert (ON CONFLICT DO NOTHING) used inside VerifyEmail |
| 413 |
deleteEmail string |
| 414 |
selectPrimaryEmail string |
| 415 |
selectUserIDByPrimary string |
| 416 |
updateEmailSetPrimary string |
| 417 |
updateEmailClearPrimary string |
| 418 |
|
| 419 |
// Magic link queries (email verification + password reset) |
| 420 |
insertMagicLink string |
| 421 |
selectMagicLinkByHash string |
| 422 |
deleteMagicLinkByHash string |
| 423 |
deleteMagicLinkEmailVerify string // Delete pending email_verify rows for (user_id, email) |
| 424 |
deleteMagicLinkResetPassword string // Delete the active password_reset row for user_id |
| 425 |
selectPendingEmails string // Pending (unverified) email addresses for a user |
| 426 |
deleteExpiredMagicLinks string |
| 427 |
|
| 428 |
// Billing queries |
| 429 |
updateBilling string |
| 430 |
} |