1
0
Fork 0
mirror of https://github.com/binwiederhier/ntfy.git synced 2024-11-10 13:54:16 +01:00
ntfy/server/visitor.go

400 lines
12 KiB
Go
Raw Normal View History

2021-11-01 20:21:38 +01:00
package server
import (
2021-12-25 15:15:05 +01:00
"errors"
2023-01-23 04:21:30 +01:00
"fmt"
"heckel.io/ntfy/log"
"heckel.io/ntfy/user"
"net/netip"
2021-11-01 20:21:38 +01:00
"sync"
"time"
"golang.org/x/time/rate"
"heckel.io/ntfy/util"
2021-11-01 20:21:38 +01:00
)
const (
2023-01-27 04:57:18 +01:00
// oneDay is an approximation of a day as a time.Duration
oneDay = 24 * time.Hour
2021-12-24 00:03:04 +01:00
// visitorExpungeAfter defines how long a visitor is active before it is removed from memory. This number
// has to be very high to prevent e-mail abuse, but it doesn't really affect the other limits anyway, since
// they are replenished faster (typically).
2023-01-27 04:57:18 +01:00
visitorExpungeAfter = oneDay
// visitorDefaultReservationsLimit is the amount of topic names a user without a tier is allowed to reserve.
// This number is zero, and changing it may have unintended consequences in the web app, or otherwise
visitorDefaultReservationsLimit = int64(0)
2021-11-01 20:21:38 +01:00
)
2023-01-27 04:57:18 +01:00
// Constants used to convert a tier-user's MessageLimit (see user.Tier) into adequate request limiter
// values (token bucket).
//
// Example: Assuming a user.Tier's MessageLimit is 10,000:
// - the allowed burst is 500 (= 10,000 * 5%), which is < 1000 (the max)
// - the replenish rate is 2 * 10,000 / 24 hours
const (
visitorMessageToRequestLimitBurstRate = 0.05
visitorMessageToRequestLimitBurstMax = 1000
visitorMessageToRequestLimitReplenishFactor = 2
)
// Constants used to convert a tier-user's EmailLimit (see user.Tier) into adequate email limiter
// values (token bucket). Example: Assuming a user.Tier's EmailLimit is 200, the allowed burst is
// 40 (= 200 * 20%), which is <150 (the max).
const (
visitorEmailLimitBurstRate = 0.2
visitorEmailLimitBurstMax = 150
)
2021-12-25 15:15:05 +01:00
var (
errVisitorLimitReached = errors.New("limit reached")
)
2021-11-01 20:21:38 +01:00
// visitor represents an API user, and its associated rate.Limiter used for rate limiting
type visitor struct {
2022-12-19 15:59:32 +01:00
config *Config
messageCache *messageCache
2023-01-27 15:42:54 +01:00
userManager *user.Manager // May be nil
ip netip.Addr // Visitor IP address
user *user.User // Only set if authenticated user, otherwise nil
emails int64 // Number of emails sent, reset every day
requestLimiter *rate.Limiter // Rate limiter for (almost) all requests (including messages)
2023-01-27 16:06:48 +01:00
messagesLimiter *util.FixedLimiter // Rate limiter for messages
2023-01-27 15:42:54 +01:00
emailsLimiter *rate.Limiter // Rate limiter for emails
subscriptionLimiter util.Limiter // Fixed limiter for active subscriptions (ongoing connections)
bandwidthLimiter util.Limiter // Limiter for attachment bandwidth downloads
accountLimiter *rate.Limiter // Rate limiter for account creation, may be nil
firebase time.Time // Next allowed Firebase message
seen time.Time // Last seen time of this visitor (needed for removal of stale visitors)
2022-12-19 15:59:32 +01:00
mu sync.Mutex
2021-11-01 20:21:38 +01:00
}
2022-12-28 04:14:14 +01:00
type visitorInfo struct {
2023-01-09 21:40:46 +01:00
Limits *visitorLimits
Stats *visitorStats
}
type visitorLimits struct {
Basis visitorLimitBasis
2023-01-27 04:57:18 +01:00
RequestLimitBurst int
RequestLimitReplenish rate.Limit
MessageLimit int64
MessageExpiryDuration time.Duration
EmailLimit int64
EmailLimitBurst int
EmailLimitReplenish rate.Limit
2023-01-09 21:40:46 +01:00
ReservationsLimit int64
AttachmentTotalSizeLimit int64
AttachmentFileSizeLimit int64
AttachmentExpiryDuration time.Duration
AttachmentBandwidthLimit int64
2023-01-09 21:40:46 +01:00
}
type visitorStats struct {
2022-12-19 22:22:13 +01:00
Messages int64
MessagesRemaining int64
Emails int64
EmailsRemaining int64
Reservations int64
ReservationsRemaining int64
2022-12-19 22:22:13 +01:00
AttachmentTotalSize int64
AttachmentTotalSizeRemaining int64
2022-04-03 18:39:52 +02:00
}
2023-01-09 21:40:46 +01:00
// visitorLimitBasis describes how the visitor limits were derived, either from a user's
// IP address (default config), or from its tier
type visitorLimitBasis string
const (
visitorLimitBasisIP = visitorLimitBasis("ip")
visitorLimitBasisTier = visitorLimitBasis("tier")
)
2023-01-03 02:08:37 +01:00
func newVisitor(conf *Config, messageCache *messageCache, userManager *user.Manager, ip netip.Addr, user *user.User) *visitor {
var messages, emails int64
if user != nil {
messages = user.Stats.Messages
emails = user.Stats.Emails
}
v := &visitor{
2022-12-19 15:59:32 +01:00
config: conf,
messageCache: messageCache,
2023-01-09 21:40:46 +01:00
userManager: userManager, // May be nil
2022-12-19 15:59:32 +01:00
ip: ip,
user: user,
emails: emails,
2022-12-19 15:59:32 +01:00
firebase: time.Unix(0, 0),
seen: time.Now(),
subscriptionLimiter: util.NewFixedLimiter(int64(conf.VisitorSubscriptionLimit)),
requestLimiter: nil, // Set in resetLimiters
messagesLimiter: nil, // Set in resetLimiters, may be nil
emailsLimiter: nil, // Set in resetLimiters
bandwidthLimiter: nil, // Set in resetLimiters
accountLimiter: nil, // Set in resetLimiters, may be nil
2021-11-01 20:21:38 +01:00
}
2023-01-27 16:06:48 +01:00
v.resetLimiters(messages)
return v
2021-11-01 20:21:38 +01:00
}
2023-01-23 04:21:30 +01:00
func (v *visitor) String() string {
v.mu.Lock()
defer v.mu.Unlock()
return v.stringNoLock()
}
func (v *visitor) stringNoLock() string {
2023-01-23 04:21:30 +01:00
if v.user != nil && v.user.Billing.StripeCustomerID != "" {
return fmt.Sprintf("%s/%s/%s", v.ip.String(), v.user.ID, v.user.Billing.StripeCustomerID)
} else if v.user != nil {
return fmt.Sprintf("%s/%s", v.ip.String(), v.user.ID)
}
return v.ip.String()
}
2021-11-01 20:21:38 +01:00
func (v *visitor) RequestAllowed() error {
2022-12-18 20:35:05 +01:00
if !v.requestLimiter.Allow() {
2021-12-25 15:15:05 +01:00
return errVisitorLimitReached
2021-12-24 00:03:04 +01:00
}
return nil
}
2022-06-01 02:38:56 +02:00
func (v *visitor) FirebaseAllowed() error {
v.mu.Lock()
defer v.mu.Unlock()
if time.Now().Before(v.firebase) {
return errVisitorLimitReached
}
return nil
}
func (v *visitor) FirebaseTemporarilyDeny() {
v.mu.Lock()
defer v.mu.Unlock()
2022-06-01 05:27:24 +02:00
v.firebase = time.Now().Add(v.config.FirebaseQuotaExceededPenaltyDuration)
2022-06-01 02:38:56 +02:00
}
2023-01-09 02:46:46 +01:00
func (v *visitor) MessageAllowed() error {
2023-01-27 16:06:48 +01:00
if v.messagesLimiter.Allow(1) != nil {
2023-01-09 02:46:46 +01:00
return errVisitorLimitReached
}
return nil
}
2021-12-24 00:03:04 +01:00
func (v *visitor) EmailAllowed() error {
2022-12-19 15:59:32 +01:00
if !v.emailsLimiter.Allow() {
2021-12-25 15:15:05 +01:00
return errVisitorLimitReached
2021-11-01 20:21:38 +01:00
}
return nil
}
2021-12-25 15:15:05 +01:00
func (v *visitor) SubscriptionAllowed() error {
2021-11-01 20:21:38 +01:00
v.mu.Lock()
defer v.mu.Unlock()
2022-12-19 15:59:32 +01:00
if err := v.subscriptionLimiter.Allow(1); err != nil {
2021-12-25 15:15:05 +01:00
return errVisitorLimitReached
2021-11-01 20:21:38 +01:00
}
return nil
}
func (v *visitor) AccountCreationAllowed() error {
2023-01-27 04:57:18 +01:00
if v.accountLimiter == nil || (v.accountLimiter != nil && !v.accountLimiter.Allow()) {
return errVisitorLimitReached
}
return nil
}
2021-11-01 20:21:38 +01:00
func (v *visitor) RemoveSubscription() {
v.mu.Lock()
defer v.mu.Unlock()
2022-12-19 15:59:32 +01:00
v.subscriptionLimiter.Allow(-1)
2021-11-01 20:21:38 +01:00
}
func (v *visitor) Keepalive() {
v.mu.Lock()
defer v.mu.Unlock()
v.seen = time.Now()
}
2022-01-13 03:24:48 +01:00
func (v *visitor) BandwidthLimiter() util.Limiter {
2022-12-19 15:59:32 +01:00
return v.bandwidthLimiter
2022-01-13 00:52:07 +01:00
}
2021-11-01 20:21:38 +01:00
func (v *visitor) Stale() bool {
v.mu.Lock()
defer v.mu.Unlock()
return time.Since(v.seen) > visitorExpungeAfter
}
2022-04-03 18:39:52 +02:00
2023-01-11 04:51:51 +01:00
func (v *visitor) IncrementEmails() {
2022-12-19 15:59:32 +01:00
v.mu.Lock()
defer v.mu.Unlock()
v.emails++
2023-01-27 15:59:16 +01:00
}
func (v *visitor) Stats() *user.Stats {
v.mu.Lock()
defer v.mu.Unlock()
return &user.Stats{
2023-01-27 16:06:48 +01:00
Messages: v.messagesLimiter.Value(),
2023-01-27 15:59:16 +01:00
Emails: v.emails,
}
2022-12-19 15:59:32 +01:00
}
2023-01-11 04:51:51 +01:00
func (v *visitor) ResetStats() {
v.mu.Lock()
defer v.mu.Unlock()
v.emails = 0
2023-01-27 16:06:48 +01:00
v.messagesLimiter.Reset()
2023-01-11 04:51:51 +01:00
}
// SetUser sets the visitors user to the given value
2023-01-23 04:21:30 +01:00
func (v *visitor) SetUser(u *user.User) {
v.mu.Lock()
defer v.mu.Unlock()
shouldResetLimiters := v.user.TierID() != u.TierID() // TierID works with nil receiver
2023-01-23 04:21:30 +01:00
v.user = u
if shouldResetLimiters {
2023-01-27 16:06:48 +01:00
v.resetLimiters(0)
}
}
// MaybeUserID returns the user ID of the visitor (if any). If this is an anonymous visitor,
// an empty string is returned.
func (v *visitor) MaybeUserID() string {
v.mu.Lock()
defer v.mu.Unlock()
if v.user != nil {
return v.user.ID
}
return ""
}
2023-01-27 16:06:48 +01:00
func (v *visitor) resetLimiters(messages int64) {
2023-01-27 04:57:18 +01:00
log.Debug("%s Resetting limiters for visitor", v.stringNoLock())
limits := v.limitsNoLock()
v.requestLimiter = rate.NewLimiter(limits.RequestLimitReplenish, limits.RequestLimitBurst)
2023-01-27 16:06:48 +01:00
v.messagesLimiter = util.NewFixedLimiterWithValue(limits.MessageLimit, messages)
2023-01-27 04:57:18 +01:00
v.emailsLimiter = rate.NewLimiter(limits.EmailLimitReplenish, limits.EmailLimitBurst)
v.bandwidthLimiter = util.NewBytesLimiter(int(limits.AttachmentBandwidthLimit), oneDay)
if v.user == nil {
v.accountLimiter = rate.NewLimiter(rate.Every(v.config.VisitorAccountCreationLimitReplenish), v.config.VisitorAccountCreationLimitBurst)
} else {
v.accountLimiter = nil // Users cannot create accounts when logged in
}
}
2023-01-09 21:40:46 +01:00
func (v *visitor) Limits() *visitorLimits {
2023-01-19 20:03:39 +01:00
v.mu.Lock()
defer v.mu.Unlock()
2023-01-27 04:57:18 +01:00
return v.limitsNoLock()
}
func (v *visitor) limitsNoLock() *visitorLimits {
2023-01-09 21:40:46 +01:00
if v.user != nil && v.user.Tier != nil {
2023-01-27 04:57:18 +01:00
return tierBasedVisitorLimits(v.config, v.user.Tier)
}
return configBasedVisitorLimits(v.config)
}
func tierBasedVisitorLimits(conf *Config, tier *user.Tier) *visitorLimits {
return &visitorLimits{
Basis: visitorLimitBasisTier,
RequestLimitBurst: util.MinMax(int(float64(tier.MessageLimit)*visitorMessageToRequestLimitBurstRate), conf.VisitorRequestLimitBurst, visitorMessageToRequestLimitBurstMax),
RequestLimitReplenish: dailyLimitToRate(tier.MessageLimit * visitorMessageToRequestLimitReplenishFactor),
MessageLimit: tier.MessageLimit,
MessageExpiryDuration: tier.MessageExpiryDuration,
EmailLimit: tier.EmailLimit,
EmailLimitBurst: util.MinMax(int(float64(tier.EmailLimit)*visitorEmailLimitBurstRate), conf.VisitorEmailLimitBurst, visitorEmailLimitBurstMax),
EmailLimitReplenish: dailyLimitToRate(tier.EmailLimit),
ReservationsLimit: tier.ReservationLimit,
AttachmentTotalSizeLimit: tier.AttachmentTotalSizeLimit,
AttachmentFileSizeLimit: tier.AttachmentFileSizeLimit,
AttachmentExpiryDuration: tier.AttachmentExpiryDuration,
AttachmentBandwidthLimit: tier.AttachmentBandwidthLimit,
}
}
func configBasedVisitorLimits(conf *Config) *visitorLimits {
messagesLimit := replenishDurationToDailyLimit(conf.VisitorRequestLimitReplenish) // Approximation!
if conf.VisitorMessageDailyLimit > 0 {
messagesLimit = int64(conf.VisitorMessageDailyLimit)
}
return &visitorLimits{
Basis: visitorLimitBasisIP,
RequestLimitBurst: conf.VisitorRequestLimitBurst,
RequestLimitReplenish: rate.Every(conf.VisitorRequestLimitReplenish),
MessageLimit: messagesLimit,
MessageExpiryDuration: conf.CacheDuration,
EmailLimit: replenishDurationToDailyLimit(conf.VisitorEmailLimitReplenish), // Approximation!
EmailLimitBurst: conf.VisitorEmailLimitBurst,
EmailLimitReplenish: rate.Every(conf.VisitorEmailLimitReplenish),
ReservationsLimit: visitorDefaultReservationsLimit,
AttachmentTotalSizeLimit: conf.VisitorAttachmentTotalSizeLimit,
AttachmentFileSizeLimit: conf.AttachmentFileSizeLimit,
AttachmentExpiryDuration: conf.AttachmentExpiryDuration,
AttachmentBandwidthLimit: conf.VisitorAttachmentDailyBandwidthLimit,
2023-01-09 21:40:46 +01:00
}
}
2022-12-28 04:14:14 +01:00
func (v *visitor) Info() (*visitorInfo, error) {
2022-12-19 15:59:32 +01:00
v.mu.Lock()
2023-01-27 16:06:48 +01:00
messages := v.messagesLimiter.Value()
2022-12-20 03:42:36 +01:00
emails := v.emails
v.mu.Unlock()
2023-01-09 21:40:46 +01:00
var attachmentsBytesUsed int64
2022-12-20 03:42:36 +01:00
var err error
if v.user != nil {
attachmentsBytesUsed, err = v.messageCache.AttachmentBytesUsedByUser(v.user.ID)
2022-12-20 03:42:36 +01:00
} else {
attachmentsBytesUsed, err = v.messageCache.AttachmentBytesUsedBySender(v.ip.String())
}
if err != nil {
return nil, err
}
var reservations int64
2023-01-03 02:08:37 +01:00
if v.user != nil && v.userManager != nil {
2023-01-09 21:40:46 +01:00
reservations, err = v.userManager.ReservationsCount(v.user.Name)
2023-01-03 02:08:37 +01:00
if err != nil {
return nil, err
2023-01-02 02:42:33 +01:00
}
}
2023-01-09 21:40:46 +01:00
limits := v.Limits()
stats := &visitorStats{
Messages: messages,
2023-01-27 04:57:18 +01:00
MessagesRemaining: zeroIfNegative(limits.MessageLimit - messages),
2023-01-09 21:40:46 +01:00
Emails: emails,
2023-01-27 04:57:18 +01:00
EmailsRemaining: zeroIfNegative(limits.EmailLimit - emails),
2023-01-09 21:40:46 +01:00
Reservations: reservations,
ReservationsRemaining: zeroIfNegative(limits.ReservationsLimit - reservations),
AttachmentTotalSize: attachmentsBytesUsed,
AttachmentTotalSizeRemaining: zeroIfNegative(limits.AttachmentTotalSizeLimit - attachmentsBytesUsed),
}
return &visitorInfo{
Limits: limits,
Stats: stats,
}, nil
2022-12-19 22:22:13 +01:00
}
func zeroIfNegative(value int64) int64 {
if value < 0 {
return 0
}
return value
}
func replenishDurationToDailyLimit(duration time.Duration) int64 {
2023-01-27 04:57:18 +01:00
return int64(oneDay / duration)
2022-12-19 22:22:13 +01:00
}
func dailyLimitToRate(limit int64) rate.Limit {
2023-01-27 04:57:18 +01:00
return rate.Limit(limit) * rate.Every(oneDay)
2022-04-03 18:39:52 +02:00
}
2023-01-18 01:40:03 +01:00
2023-01-27 04:57:18 +01:00
func visitorID(ip netip.Addr, u *user.User) string {
if u != nil && u.Tier != nil {
return fmt.Sprintf("user:%s", u.ID)
2023-01-18 01:40:03 +01:00
}
2023-01-27 04:57:18 +01:00
return fmt.Sprintf("ip:%s", ip.String())
2023-01-18 01:40:03 +01:00
}