Debian Codegraph @

server/config.go

raw
1 package server
2
3 import (
4 "crypto/sha256"
5 "encoding/json"
6 "fmt"
7 "io/fs"
8 "net/netip"
9 "reflect"
10 "text/template"
11 "time"
12
13 "heckel.io/ntfy/v2/ban"
14 "heckel.io/ntfy/v2/user"
15 )
16
17 // Defines default config settings (excluding limits, see below)
18 const (
19 DefaultListenHTTP = ":80"
20 DefaultCacheDuration = 12 * time.Hour
21 DefaultCacheBatchTimeout = time.Duration(0)
22 DefaultKeepaliveInterval = 45 * time.Second // Not too frequently to save battery (Android read timeout used to be 77s!)
23 DefaultManagerInterval = time.Minute
24 DefaultManagerBatchSize = 30000
25 DefaultDelayedSenderInterval = 10 * time.Second
26 DefaultMessageDelayMin = 10 * time.Second
27 DefaultMessageDelayMax = 3 * 24 * time.Hour
28 DefaultFirebaseKeepaliveInterval = 3 * time.Hour // ~control topic (Android), not too frequently to save battery
29 DefaultFirebasePollInterval = 20 * time.Minute // ~poll topic (iOS), max. 2-3 times per hour (see docs)
30 DefaultFirebaseQuotaExceededPenaltyDuration = 10 * time.Minute // Time that over-users are locked out of Firebase if it returns "quota exceeded"
31 DefaultStripePriceCacheDuration = 3 * time.Hour // Time to keep Stripe prices cached in memory before a refresh is needed
32 )
33
34 // Platform-specific default paths (set in config_unix.go or config_windows.go)
35 var (
36 DefaultConfigFile string
37 DefaultTemplateDir string
38 )
39
40 // Defines default Web Push settings
41 const (
42 DefaultWebPushExpiryWarningDuration = 55 * 24 * time.Hour
43 DefaultWebPushExpiryDuration = 60 * 24 * time.Hour
44 )
45
46 // Defines default abuse ban-feed settings (see BanFile, BanWindow, BanThreshold, BanWeights)
47 const (
48 DefaultBanWindow = 10 * time.Minute
49 DefaultBanThreshold = 100 // Weighted strikes per BanWindow before a prefix is banned
50 )
51
52 // DefaultBanWeights is the ban-feed's default per-code strike weights: the auth-failure flood bans fast,
53 // and everything else defaults to weight 1 (no "*" rule needed; see BanWeights.WeightFor).
54 var DefaultBanWeights = []string{
55 banWeight(errHTTPTooManyRequestsLimitAuthFailure, 10), // brute-force auth flood -> ban fast
56 }
57
58 // banWeight formats a "CODE:WEIGHT" ban-feed default from an ntfy error, so the codes stay in sync with
59 // the errHTTP definitions instead of being duplicated as string literals.
60 func banWeight(err *errHTTP, weight int) string {
61 return fmt.Sprintf("%d:%d", err.Code, weight)
62 }
63
64 // Defines all global and per-visitor limits
65 // - message size limit: the max number of bytes for a message
66 // - total topic limit: max number of topics overall
67 // - various attachment limits
68 const (
69 DefaultMessageSizeLimit = 4096 // Bytes; note that FCM/APNS have a limit of ~4 KB for the entire message
70 DefaultTotalTopicLimit = 15000
71 DefaultAttachmentTotalSizeLimit = int64(5 * 1024 * 1024 * 1024) // 5 GB
72 DefaultAttachmentFileSizeLimit = int64(15 * 1024 * 1024) // 15 MB
73 DefaultAttachmentExpiryDuration = 3 * time.Hour
74 DefaultAttachmentOrphanGracePeriod = time.Hour // Don't delete orphaned objects younger than this to avoid races with in-flight uploads
75
76 )
77
78 // Defines all per-visitor limits
79 // - per visitor subscription limit: max number of subscriptions (active HTTP connections) per per-visitor/IP
80 // - per visitor request limit: max number of PUT/GET/.. requests (here: 60 requests bucket, replenished at a rate of one per 5 seconds)
81 // - per visitor email limit: max number of emails (here: 16 email bucket, replenished at a rate of one per hour)
82 // - per visitor attachment size limit: total per-visitor attachment size in bytes to be stored on the server
83 // - per visitor attachment daily bandwidth limit: number of bytes that can be transferred to/from the server
84 const (
85 DefaultVisitorSubscriptionLimit = 30
86 DefaultVisitorRequestLimitBurst = 60
87 DefaultVisitorRequestLimitReplenish = 5 * time.Second
88 DefaultVisitorMessageDailyLimit = 0
89 DefaultVisitorEmailLimitBurst = 16
90 DefaultVisitorEmailLimitReplenish = time.Hour
91 DefaultVisitorTopicCreationLimitBurst = 100
92 DefaultVisitorTopicCreationLimitReplenish = time.Minute
93 DefaultVisitorAccountCreationLimitBurst = 6 // Shared by signup and password-reset requests (same per-visitor bucket)
94 DefaultVisitorAccountCreationLimitReplenish = 24 * time.Hour
95 DefaultVisitorAuthFailureLimitBurst = 30
96 DefaultVisitorAuthFailureLimitReplenish = time.Minute
97 DefaultVisitorAttachmentTotalSizeLimit = 100 * 1024 * 1024 // 100 MB
98 DefaultVisitorAttachmentDailyBandwidthLimit = 500 * 1024 * 1024 // 500 MB
99 DefaultVisitorPrefixBitsIPv4 = 32 // Use the entire IPv4 address for rate limiting
100 DefaultVisitorPrefixBitsIPv6 = 64 // Use /64 for IPv6 rate limiting
101 )
102
103 var (
104 // DefaultVisitorStatsResetTime defines the time at which visitor stats are reset (wall clock only)
105 DefaultVisitorStatsResetTime = time.Date(0, 0, 0, 0, 0, 0, 0, time.UTC)
106
107 // DefaultDisallowedTopics defines the topics that are forbidden, because they are used elsewhere. This array can be
108 // extended using the server.yml config. If updated, also update in Android and web app.
109 DefaultDisallowedTopics = []string{"docs", "static", "file", "app", "metrics", "account", "settings", "signup", "login", "v1"}
110 )
111
112 // Config is the main config struct for the application. Use New to instantiate a default config struct.
113 type Config struct {
114 File string // Config file, only used for testing
115 BaseURL string
116 ListenHTTP string
117 ListenHTTPS string
118 ListenUnix string
119 ListenUnixMode fs.FileMode
120 KeyFile string
121 CertFile string
122 DatabaseURL string // PostgreSQL connection string (e.g. "postgres://user:pass@host:5432/ntfy")
123 DatabaseReplicaURLs []string // PostgreSQL read replica connection strings
124 FirebaseKeyFile string
125 CacheFile string
126 CacheDuration time.Duration
127 CacheStartupQueries string
128 CacheBatchSize int
129 CacheBatchTimeout time.Duration
130 AuthFile string
131 AuthStartupQueries string
132 AuthDefault user.Permission
133 AuthUsers []*user.User `hash:"-"`
134 AuthAccess map[string][]*user.Grant
135 AuthTokens map[string][]*user.Token `hash:"-"`
136 AuthBcryptCost int
137 AuthStatsQueueWriterInterval time.Duration
138 AuthAccessCacheEnabled bool // Enables the in-memory ACL cache (high volume servers only)
139 AuthAccessCacheReloadInterval time.Duration // Reload interval for access cache, relevant for ACL writes from CLI
140 AttachmentCacheDir string
141 AttachmentTotalSizeLimit int64
142 AttachmentFileSizeLimit int64
143 AttachmentExpiryDuration time.Duration
144 AttachmentOrphanGracePeriod time.Duration
145 TemplateDir string // Directory to load named templates from
146 KeepaliveInterval time.Duration
147 ManagerInterval time.Duration
148 ManagerBatchSize int
149 DisallowedTopics []string
150 WebRoot string // empty to disable
151 DelayedSenderInterval time.Duration
152 FirebaseKeepaliveInterval time.Duration
153 FirebasePollInterval time.Duration
154 FirebaseQuotaExceededPenaltyDuration time.Duration
155 UpstreamBaseURL string
156 UpstreamAccessToken string `hash:"-"`
157 SMTPSenderAddr string
158 SMTPSenderUser string
159 SMTPSenderPass string `hash:"-"`
160 SMTPSenderFrom string
161 SMTPSenderVerify bool
162 SMTPServerListen string
163 SMTPServerDomain string
164 SMTPServerAddrPrefix string
165 TwilioAccount string
166 TwilioAuthToken string `hash:"-"`
167 TwilioPhoneNumber string
168 TwilioCallsBaseURL string
169 TwilioVerifyBaseURL string
170 TwilioVerifyService string
171 TwilioCallFormat *template.Template
172 MetricsListenHTTP string
173 ProfileListenHTTP string
174 MessageDelayMin time.Duration
175 MessageDelayMax time.Duration
176 MessageSizeLimit int
177 TotalTopicLimit int
178 TotalAttachmentSizeLimit int64
179 VisitorSubscriptionLimit int
180 VisitorAttachmentTotalSizeLimit int64
181 VisitorAttachmentDailyBandwidthLimit int64
182 VisitorRequestLimitBurst int
183 VisitorRequestLimitReplenish time.Duration
184 VisitorRequestExemptPrefixes []netip.Prefix
185 VisitorMessageDailyLimit int
186 VisitorEmailLimitBurst int
187 VisitorEmailLimitReplenish time.Duration
188 VisitorTopicCreationLimitBurst int // Burst of new topic creations per visitor
189 VisitorTopicCreationLimitReplenish time.Duration // Interval at which topic-creation tokens are refilled
190 VisitorAccountCreationLimitBurst int
191 VisitorAccountCreationLimitReplenish time.Duration
192 VisitorAuthFailureLimitBurst int
193 VisitorAuthFailureLimitReplenish time.Duration
194 VisitorStatsResetTime time.Time // Time of the day at which to reset visitor stats
195 VisitorSubscriberRateLimiting bool // Enable subscriber-based rate limiting for UnifiedPush topics
196 VisitorPrefixBitsIPv4 int // Number of bits for IPv4 rate limiting (default: 32)
197 VisitorPrefixBitsIPv6 int // Number of bits for IPv6 rate limiting (default: 64)
198 BehindProxy bool // If true, the server will trust the proxy client IP header to determine the client IP address (IPv4 and IPv6 supported)
199 ProxyForwardedHeader string // The header field to read the real/client IP address from, if BehindProxy is true, defaults to "X-Forwarded-For" (IPv4 and IPv6 supported)
200 ProxyTrustedPrefixes []netip.Prefix // List of trusted proxy networks (IPv4 or IPv6) that will be stripped from the Forwarded header if BehindProxy is true
201 StripeSecretKey string `hash:"-"`
202 StripeWebhookKey string `hash:"-"`
203 StripePriceCacheDuration time.Duration
204 BillingContact string
205 EnableSignup bool // Enable creation of accounts via API and UI
206 EnableLogin bool
207 RequireLogin bool
208 EnableReservations bool // Allow users with role "user" to own/reserve topics
209 EnableMetrics bool
210 AccessControlAllowOrigin string // CORS header field to restrict access from web clients
211 WebPushPrivateKey string `hash:"-"`
212 WebPushPublicKey string
213 WebPushFile string
214 WebPushEmailAddress string
215 WebPushStartupQueries string
216 WebPushExpiryDuration time.Duration
217 WebPushExpiryWarningDuration time.Duration
218 BanFile string // Abuse ban-feed: file that fail2ban tails; empty string disables the feature
219 BanWindow time.Duration // Abuse ban-feed: rolling window over which weighted strikes are counted
220 BanThreshold int // Abuse ban-feed: weighted strikes per window before a prefix is banned
221 BanWeights ban.Weights // Abuse ban-feed: code matcher -> strike weight (see ban.ParseWeights, ban.Weights.WeightFor)
222 BuildVersion string // Injected by App
223 BuildDate string // Injected by App
224 BuildCommit string // Injected by App
225 }
226
227 // NewConfig instantiates a default new server config
228 func NewConfig() *Config {
229 return &Config{
230 File: DefaultConfigFile, // Only used for testing
231 BaseURL: "",
232 ListenHTTP: DefaultListenHTTP,
233 ListenHTTPS: "",
234 ListenUnix: "",
235 ListenUnixMode: 0,
236 KeyFile: "",
237 CertFile: "",
238 DatabaseURL: "",
239 FirebaseKeyFile: "",
240 CacheFile: "",
241 CacheDuration: DefaultCacheDuration,
242 CacheStartupQueries: "",
243 CacheBatchSize: 0,
244 CacheBatchTimeout: 0,
245 AuthFile: "",
246 AuthStartupQueries: "",
247 AuthDefault: user.PermissionReadWrite,
248 AuthBcryptCost: user.DefaultUserPasswordBcryptCost,
249 AuthStatsQueueWriterInterval: user.DefaultUserStatsQueueWriterInterval,
250 AuthAccessCacheEnabled: user.DefaultAccessCacheEnabled,
251 AuthAccessCacheReloadInterval: user.DefaultAccessCacheReloadInterval,
252 AttachmentCacheDir: "",
253 AttachmentTotalSizeLimit: DefaultAttachmentTotalSizeLimit,
254 AttachmentFileSizeLimit: DefaultAttachmentFileSizeLimit,
255 AttachmentExpiryDuration: DefaultAttachmentExpiryDuration,
256 AttachmentOrphanGracePeriod: DefaultAttachmentOrphanGracePeriod,
257 TemplateDir: DefaultTemplateDir,
258 KeepaliveInterval: DefaultKeepaliveInterval,
259 ManagerInterval: DefaultManagerInterval,
260 ManagerBatchSize: DefaultManagerBatchSize,
261 DisallowedTopics: DefaultDisallowedTopics,
262 WebRoot: "/",
263 DelayedSenderInterval: DefaultDelayedSenderInterval,
264 FirebaseKeepaliveInterval: DefaultFirebaseKeepaliveInterval,
265 FirebasePollInterval: DefaultFirebasePollInterval,
266 FirebaseQuotaExceededPenaltyDuration: DefaultFirebaseQuotaExceededPenaltyDuration,
267 UpstreamBaseURL: "",
268 UpstreamAccessToken: "",
269 SMTPSenderAddr: "",
270 SMTPSenderUser: "",
271 SMTPSenderPass: "",
272 SMTPSenderFrom: "",
273 SMTPSenderVerify: false,
274 SMTPServerListen: "",
275 SMTPServerDomain: "",
276 SMTPServerAddrPrefix: "",
277 TwilioCallsBaseURL: "https://api.twilio.com", // Override for tests
278 TwilioAccount: "",
279 TwilioAuthToken: "",
280 TwilioPhoneNumber: "",
281 TwilioVerifyBaseURL: "https://verify.twilio.com", // Override for tests
282 TwilioVerifyService: "",
283 TwilioCallFormat: nil,
284 MessageSizeLimit: DefaultMessageSizeLimit,
285 MessageDelayMin: DefaultMessageDelayMin,
286 MessageDelayMax: DefaultMessageDelayMax,
287 TotalTopicLimit: DefaultTotalTopicLimit,
288 TotalAttachmentSizeLimit: 0,
289 VisitorSubscriptionLimit: DefaultVisitorSubscriptionLimit,
290 VisitorSubscriberRateLimiting: false,
291 VisitorAttachmentTotalSizeLimit: DefaultVisitorAttachmentTotalSizeLimit,
292 VisitorAttachmentDailyBandwidthLimit: DefaultVisitorAttachmentDailyBandwidthLimit,
293 VisitorRequestLimitBurst: DefaultVisitorRequestLimitBurst,
294 VisitorRequestLimitReplenish: DefaultVisitorRequestLimitReplenish,
295 VisitorRequestExemptPrefixes: make([]netip.Prefix, 0),
296 VisitorMessageDailyLimit: DefaultVisitorMessageDailyLimit,
297 VisitorEmailLimitBurst: DefaultVisitorEmailLimitBurst,
298 VisitorEmailLimitReplenish: DefaultVisitorEmailLimitReplenish,
299 VisitorTopicCreationLimitBurst: DefaultVisitorTopicCreationLimitBurst,
300 VisitorTopicCreationLimitReplenish: DefaultVisitorTopicCreationLimitReplenish,
301 VisitorAccountCreationLimitBurst: DefaultVisitorAccountCreationLimitBurst,
302 VisitorAccountCreationLimitReplenish: DefaultVisitorAccountCreationLimitReplenish,
303 VisitorAuthFailureLimitBurst: DefaultVisitorAuthFailureLimitBurst,
304 VisitorAuthFailureLimitReplenish: DefaultVisitorAuthFailureLimitReplenish,
305 VisitorStatsResetTime: DefaultVisitorStatsResetTime,
306 VisitorPrefixBitsIPv4: DefaultVisitorPrefixBitsIPv4, // Default: use full IPv4 address
307 VisitorPrefixBitsIPv6: DefaultVisitorPrefixBitsIPv6, // Default: use /64 for IPv6
308 BehindProxy: false, // If true, the server will trust the proxy client IP header to determine the client IP address
309 ProxyForwardedHeader: "X-Forwarded-For", // Default header for reverse proxy client IPs
310 StripeSecretKey: "",
311 StripeWebhookKey: "",
312 StripePriceCacheDuration: DefaultStripePriceCacheDuration,
313 BillingContact: "",
314 EnableSignup: false,
315 EnableLogin: false,
316 EnableReservations: false,
317 RequireLogin: false,
318 AccessControlAllowOrigin: "*",
319 WebPushPrivateKey: "",
320 WebPushPublicKey: "",
321 WebPushFile: "",
322 WebPushEmailAddress: "",
323 WebPushExpiryDuration: DefaultWebPushExpiryDuration,
324 WebPushExpiryWarningDuration: DefaultWebPushExpiryWarningDuration,
325 BanFile: "",
326 BanWindow: DefaultBanWindow,
327 BanThreshold: DefaultBanThreshold,
328 BanWeights: nil,
329 BuildVersion: "",
330 BuildDate: "",
331 BuildCommit: "",
332 }
333 }
334
335 // Hash computes an SHA-256 hash of the configuration. This is used to detect
336 // configuration changes for the web app version check feature. It uses reflection
337 // to include all JSON-serializable fields automatically.
338 func (c *Config) Hash() string {
339 v := reflect.ValueOf(*c)
340 t := v.Type()
341 var result string
342 for i := 0; i < v.NumField(); i++ {
343 field := v.Field(i)
344 fieldName := t.Field(i).Name
345 // Secrets must not feed the hash
346 if t.Field(i).Tag.Get("hash") == "-" {
347 continue
348 }
349 // Try to marshal the field and skip if it fails (e.g. *template.Template, netip.Prefix)
350 if b, err := json.Marshal(field.Interface()); err == nil {
351 result += fmt.Sprintf("%s:%s|", fieldName, string(b))
352 }
353 }
354 return fmt.Sprintf("%x", sha256.Sum256([]byte(result)))
355 }