Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

feat: add configurable security options for generic notifiers (#1335)

Mattcee159f18e55
diff --git a/backend/app/api/app.go b/backend/app/api/app.go
index b9630fde..0479b310 100644
--- a/backend/app/api/app.go
+++ b/backend/app/api/app.go
@@ -1,6 +1,8 @@
package main
import (
+ "time"
+
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
"github.com/sysadminsmedia/homebox/backend/internal/core/services/reporting/eventbus"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
@@ -10,13 +12,14 @@ import (
)
type app struct {
- conf *config.Config
- mailer mailer.Mailer
- db *ent.Client
- repos *repo.AllRepos
- services *services.AllServices
- bus *eventbus.EventBus
- authLimiter *authRateLimiter
+ conf *config.Config
+ mailer mailer.Mailer
+ db *ent.Client
+ repos *repo.AllRepos
+ services *services.AllServices
+ bus *eventbus.EventBus
+ authLimiter *authRateLimiter
+ notifierTestLimiter *simpleRateLimiter
}
func new(conf *config.Config) *app {
@@ -33,6 +36,7 @@ func new(conf *config.Config) *app {
}
s.authLimiter = newAuthRateLimiter(s.conf.Auth.RateLimit)
+ s.notifierTestLimiter = newSimpleRateLimiter(10, time.Minute) // 10 requests per minute
return s
}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_notifiers.go b/backend/app/api/handlers/v1/v1_ctrl_notifiers.go
index 35665b83..52a47fa4 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_notifiers.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_notifiers.go
@@ -8,6 +8,7 @@ import (
"github.com/hay-kot/httpkit/errchain"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
"github.com/sysadminsmedia/homebox/backend/internal/web/adapters"
)
@@ -41,6 +42,12 @@ func (ctrl *V1Controller) HandleGetUserNotifiers() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleCreateNotifier() errchain.HandlerFunc {
fn := func(r *http.Request, in repo.NotifierCreate) (repo.NotifierOut, error) {
auth := services.NewContext(r.Context())
+
+ // Validate notifier URL against block/allow lists
+ if err := ctrl.validateNotifierURL(in.URL); err != nil {
+ return repo.NotifierOut{}, validate.NewRequestError(err, http.StatusBadRequest)
+ }
+
return ctrl.repo.Notifiers.Create(auth, auth.GID, auth.UID, in)
}
@@ -76,6 +83,14 @@ func (ctrl *V1Controller) HandleDeleteNotifier() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleUpdateNotifier() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID, in repo.NotifierUpdate) (repo.NotifierOut, error) {
auth := services.NewContext(r.Context())
+
+ // Validate notifier URL against block/allow lists if URL is being updated
+ if in.URL != nil {
+ if err := ctrl.validateNotifierURL(*in.URL); err != nil {
+ return repo.NotifierOut{}, validate.NewRequestError(err, http.StatusBadRequest)
+ }
+ }
+
return ctrl.repo.Notifiers.Update(auth, auth.UID, ID, in)
}
@@ -97,9 +112,19 @@ func (ctrl *V1Controller) HandlerNotifierTest() errchain.HandlerFunc {
}
fn := func(r *http.Request, q body) (any, error) {
+ // Validate notifier URL against block/allow lists
+ if err := ctrl.validateNotifierURL(q.URL); err != nil {
+ return nil, validate.NewRequestError(err, http.StatusBadRequest)
+ }
+
err := shoutrrr.Send(q.URL, "Test message from Homebox")
return nil, err
}
return adapters.Action(fn, http.StatusOK)
}
+
+// validateNotifierURL validates a notifier URL against the configured block/allow lists
+func (ctrl *V1Controller) validateNotifierURL(url string) error {
+ return validate.ValidateNotifierURL(url, &ctrl.config.Notifier)
+}
diff --git a/backend/app/api/main.go b/backend/app/api/main.go
index a1f0c261..0b28c089 100644
--- a/backend/app/api/main.go
+++ b/backend/app/api/main.go
@@ -176,6 +176,7 @@ func run(cfg *config.Config) error {
app.repos,
services.WithAutoIncrementAssetID(cfg.Options.AutoIncrementAssetID),
services.WithCurrencies(currencies),
+ services.WithNotifierConfig(&cfg.Notifier),
)
// =========================================================================
diff --git a/backend/app/api/middleware.go b/backend/app/api/middleware.go
index 72c58d80..35d33e42 100644
--- a/backend/app/api/middleware.go
+++ b/backend/app/api/middleware.go
@@ -212,10 +212,12 @@ func (a *app) mwTenant(next errchain.Handler) errchain.Handler {
// authRateLimiter tracks authentication attempts per client and applies a backoff when limits are exceeded.
type authRateLimiter struct {
- cfg config.AuthRateLimit
- mu sync.Mutex
- state map[string]*authAttempt
- nowFn func() time.Time
+ cfg config.AuthRateLimit
+ mu sync.Mutex
+ state map[string]*authAttempt
+ nowFn func() time.Time
+ stopCleanup chan struct{}
+ stopOnce sync.Once
}
// authAttempt struct represents the state of authentication attempts for a client.
@@ -241,13 +243,63 @@ func newAuthRateLimiter(cfg config.AuthRateLimit) *authRateLimiter {
cfg.Window = time.Minute
}
- return &authRateLimiter{
- cfg: cfg,
- state: make(map[string]*authAttempt),
- nowFn: time.Now,
+ limiter := &authRateLimiter{
+ cfg: cfg,
+ state: make(map[string]*authAttempt),
+ nowFn: time.Now,
+ stopCleanup: make(chan struct{}),
+ }
+
+ // Start background cleanup goroutine
+ go limiter.cleanupLoop()
+
+ return limiter
+}
+
+// cleanupLoop periodically removes stale entries from the state map.
+func (l *authRateLimiter) cleanupLoop() {
+ // Run cleanup every window period (or at least every 5 minutes)
+ cleanupInterval := l.cfg.Window
+ if cleanupInterval > 5*time.Minute {
+ cleanupInterval = 5 * time.Minute
+ }
+
+ ticker := time.NewTicker(cleanupInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ l.cleanup()
+ case <-l.stopCleanup:
+ return
+ }
+ }
+}
+
+// cleanup removes stale entries that are outside the window.
+func (l *authRateLimiter) cleanup() {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ now := l.nowFn()
+ for key, attempt := range l.state {
+ // Remove entries that are:
+ // 1. Outside the window AND
+ // 2. No longer locked (or lock has expired)
+ if now.Sub(attempt.lastAttempt) > l.cfg.Window && now.After(attempt.lockedUntil) {
+ delete(l.state, key)
+ }
}
}
+// Stop gracefully stops the cleanup goroutine.
+func (l *authRateLimiter) Stop() {
+ l.stopOnce.Do(func() {
+ close(l.stopCleanup)
+ })
+}
+
// mwAuthRateLimit enforces request throttling for authentication endpoints with an exponential backoff.
func (a *app) mwAuthRateLimit(next errchain.Handler) errchain.Handler {
return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
@@ -360,3 +412,145 @@ func (l *authRateLimiter) clientIP(r *http.Request) string {
return r.RemoteAddr
}
+
+// simpleRateLimiter provides token bucket rate limiting per client IP.
+type simpleRateLimiter struct {
+ mu sync.Mutex
+ limiters map[string]*rateLimiterEntry
+ rate int // requests allowed
+ window time.Duration // time window
+ stopCleanup chan struct{}
+ stopOnce sync.Once
+}
+
+type rateLimiterEntry struct {
+ tokens int
+ lastRefill time.Time
+}
+
+// newSimpleRateLimiter creates a new rate limiter with the specified rate and window.
+func newSimpleRateLimiter(rate int, window time.Duration) *simpleRateLimiter {
+ rl := &simpleRateLimiter{
+ limiters: make(map[string]*rateLimiterEntry),
+ rate: rate,
+ window: window,
+ stopCleanup: make(chan struct{}),
+ }
+
+ // Start background cleanup goroutine
+ go rl.cleanupLoop()
+
+ return rl
+}
+
+// cleanupLoop periodically removes stale entries from the limiters map.
+func (rl *simpleRateLimiter) cleanupLoop() {
+ // Run cleanup every 2x the window period (or at least every 5 minutes)
+ cleanupInterval := rl.window * 2
+ if cleanupInterval < 5*time.Minute {
+ cleanupInterval = 5 * time.Minute
+ }
+
+ ticker := time.NewTicker(cleanupInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ rl.cleanup()
+ case <-rl.stopCleanup:
+ return
+ }
+ }
+}
+
+// cleanup removes stale entries that haven't been accessed recently.
+func (rl *simpleRateLimiter) cleanup() {
+ rl.mu.Lock()
+ defer rl.mu.Unlock()
+
+ now := time.Now()
+ // Remove entries that haven't been accessed in 2x the window period
+ staleThreshold := rl.window * 2
+
+ for key, entry := range rl.limiters {
+ if now.Sub(entry.lastRefill) > staleThreshold {
+ delete(rl.limiters, key)
+ }
+ }
+}
+
+// Stop gracefully stops the cleanup goroutine.
+func (rl *simpleRateLimiter) Stop() {
+ rl.stopOnce.Do(func() {
+ close(rl.stopCleanup)
+ })
+}
+
+// allow checks if the request should be allowed based on the rate limit.
+func (rl *simpleRateLimiter) allow(clientIP string) bool {
+ rl.mu.Lock()
+ defer rl.mu.Unlock()
+
+ now := time.Now()
+ entry, exists := rl.limiters[clientIP]
+
+ if !exists {
+ // First request from this IP
+ rl.limiters[clientIP] = &rateLimiterEntry{
+ tokens: rl.rate - 1,
+ lastRefill: now,
+ }
+ return true
+ }
+
+ // Refill tokens based on elapsed time
+ elapsed := now.Sub(entry.lastRefill)
+ if elapsed >= rl.window {
+ // Full refill
+ entry.tokens = rl.rate - 1
+ entry.lastRefill = now
+ return true
+ }
+
+ // Check if tokens are available
+ if entry.tokens > 0 {
+ entry.tokens--
+ return true
+ }
+
+ return false
+}
+
+// getClientIP extracts the client IP from the request.
+func (rl *simpleRateLimiter) getClientIP(r *http.Request) string {
+ if ip := r.Header.Get("X-Real-IP"); ip != "" {
+ return ip
+ }
+
+ if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
+ parts := strings.Split(ip, ",")
+ return strings.TrimSpace(parts[0])
+ }
+
+ host, _, err := net.SplitHostPort(r.RemoteAddr)
+ if err == nil {
+ return host
+ }
+
+ return r.RemoteAddr
+}
+
+// middleware wraps the rate limiter as an errchain middleware.
+func (rl *simpleRateLimiter) middleware(next errchain.Handler) errchain.Handler {
+ return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
+ clientIP := rl.getClientIP(r)
+
+ if !rl.allow(clientIP) {
+ w.Header().Set("Retry-After", strconv.Itoa(int(rl.window.Seconds())))
+ return validate.NewRequestError(errors.New("rate limit exceeded"), http.StatusTooManyRequests)
+ }
+
+ return next.ServeHTTP(w, r)
+ })
+}
diff --git a/backend/app/api/middleware_ratelimit_test.go b/backend/app/api/middleware_ratelimit_test.go
new file mode 100644
index 00000000..3dec7e7c
--- /dev/null
+++ b/backend/app/api/middleware_ratelimit_test.go
@@ -0,0 +1,271 @@
+package main
+
+import (
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
+)
+
+func TestSimpleRateLimiter(t *testing.T) {
+ // Create a rate limiter that allows 3 requests per 10 seconds
+ limiter := newSimpleRateLimiter(3, 10*time.Second)
+ clientIP := "192.168.1.1"
+
+ // First 3 requests should succeed
+ for i := 0; i < 3; i++ {
+ if !limiter.allow(clientIP) {
+ t.Errorf("Request %d should have been allowed", i+1)
+ }
+ }
+
+ // 4th request should be blocked
+ if limiter.allow(clientIP) {
+ t.Error("4th request should have been blocked")
+ }
+
+ // Different client should not be affected
+ otherClient := "192.168.1.2"
+ if !limiter.allow(otherClient) {
+ t.Error("Different client should be allowed")
+ }
+}
+
+func TestSimpleRateLimiterRefill(t *testing.T) {
+ // Create a rate limiter that allows 2 requests per 100ms
+ limiter := newSimpleRateLimiter(2, 100*time.Millisecond)
+ clientIP := "192.168.1.1"
+
+ // Use up the tokens
+ if !limiter.allow(clientIP) {
+ t.Error("First request should be allowed")
+ }
+ if !limiter.allow(clientIP) {
+ t.Error("Second request should be allowed")
+ }
+ if limiter.allow(clientIP) {
+ t.Error("Third request should be blocked")
+ }
+
+ // Wait for refill
+ time.Sleep(150 * time.Millisecond)
+
+ // Should be allowed again after refill
+ if !limiter.allow(clientIP) {
+ t.Error("Request after refill should be allowed")
+ }
+}
+
+func TestSimpleRateLimiterConcurrent(t *testing.T) {
+ limiter := newSimpleRateLimiter(10, time.Second)
+ clientIP := "192.168.1.1"
+
+ var allowed int32
+ done := make(chan bool)
+
+ // Spawn multiple goroutines trying to access the limiter
+ for i := 0; i < 20; i++ {
+ go func() {
+ if limiter.allow(clientIP) {
+ atomic.AddInt32(&allowed, 1)
+ }
+ done <- true
+ }()
+ }
+
+ // Wait for all goroutines
+ for i := 0; i < 20; i++ {
+ <-done
+ }
+
+ // Should allow exactly 10 requests
+ allowedCount := atomic.LoadInt32(&allowed)
+ if allowedCount != 10 {
+ t.Errorf("Expected 10 allowed requests, got %d", allowedCount)
+ }
+}
+
+func TestSimpleRateLimiterCleanup(t *testing.T) {
+ // Create a rate limiter with a short window
+ limiter := newSimpleRateLimiter(5, 100*time.Millisecond)
+ defer limiter.Stop()
+
+ // Add entries for multiple IPs
+ ips := []string{"192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4", "192.168.1.5"}
+ for _, ip := range ips {
+ limiter.allow(ip)
+ }
+
+ // Verify entries exist
+ limiter.mu.Lock()
+ initialCount := len(limiter.limiters)
+ limiter.mu.Unlock()
+
+ if initialCount != len(ips) {
+ t.Errorf("Expected %d entries, got %d", len(ips), initialCount)
+ }
+
+ // Wait for stale threshold (2x window = 200ms + buffer)
+ time.Sleep(250 * time.Millisecond)
+
+ // Trigger cleanup manually
+ limiter.cleanup()
+
+ // Verify stale entries are removed
+ limiter.mu.Lock()
+ finalCount := len(limiter.limiters)
+ limiter.mu.Unlock()
+
+ if finalCount != 0 {
+ t.Errorf("Expected 0 entries after cleanup, got %d", finalCount)
+ }
+}
+
+func TestSimpleRateLimiterCleanupPreservesActive(t *testing.T) {
+ limiter := newSimpleRateLimiter(5, 100*time.Millisecond)
+ defer limiter.Stop()
+
+ activeIP := "192.168.1.1"
+ staleIP := "192.168.1.2"
+
+ // Create a stale entry
+ limiter.allow(staleIP)
+
+ // Wait for it to become stale
+ time.Sleep(250 * time.Millisecond)
+
+ // Create an active entry
+ limiter.allow(activeIP)
+
+ // Trigger cleanup
+ limiter.cleanup()
+
+ // Verify active entry is preserved and stale is removed
+ limiter.mu.Lock()
+ defer limiter.mu.Unlock()
+
+ if _, exists := limiter.limiters[activeIP]; !exists {
+ t.Error("Active entry should be preserved")
+ }
+
+ if _, exists := limiter.limiters[staleIP]; exists {
+ t.Error("Stale entry should be removed")
+ }
+}
+
+func TestSimpleRateLimiterStop(t *testing.T) {
+ limiter := newSimpleRateLimiter(5, time.Second)
+
+ // Stop the limiter
+ limiter.Stop()
+
+ // Verify the cleanup goroutine exits (this test passes if no panic occurs)
+ time.Sleep(10 * time.Millisecond)
+}
+
+func TestAuthRateLimiterCleanup(t *testing.T) {
+ cfg := config.AuthRateLimit{
+ Enabled: true,
+ MaxAttempts: 3,
+ BaseBackoff: 10 * time.Millisecond,
+ MaxBackoff: 100 * time.Millisecond,
+ Window: 50 * time.Millisecond,
+ }
+
+ limiter := newAuthRateLimiter(cfg)
+ defer limiter.Stop()
+
+ // Add multiple failed attempts for different keys
+ keys := []string{"key1", "key2", "key3", "key4", "key5"}
+ now := time.Now()
+
+ for _, key := range keys {
+ limiter.record(key, now, false)
+ }
+
+ // Verify entries exist
+ limiter.mu.Lock()
+ initialCount := len(limiter.state)
+ limiter.mu.Unlock()
+
+ if initialCount != len(keys) {
+ t.Errorf("Expected %d entries, got %d", len(keys), initialCount)
+ }
+
+ // Wait for entries to become stale (window = 50ms + buffer)
+ time.Sleep(100 * time.Millisecond)
+
+ // Trigger cleanup
+ limiter.cleanup()
+
+ // Verify stale entries are removed
+ limiter.mu.Lock()
+ finalCount := len(limiter.state)
+ limiter.mu.Unlock()
+
+ if finalCount != 0 {
+ t.Errorf("Expected 0 entries after cleanup, got %d", finalCount)
+ }
+}
+
+func TestAuthRateLimiterCleanupPreservesLocked(t *testing.T) {
+ cfg := config.AuthRateLimit{
+ Enabled: true,
+ MaxAttempts: 2,
+ BaseBackoff: 200 * time.Millisecond,
+ MaxBackoff: 1 * time.Second,
+ Window: 50 * time.Millisecond,
+ }
+
+ limiter := newAuthRateLimiter(cfg)
+ defer limiter.Stop()
+
+ lockedKey := "locked"
+ staleKey := "stale"
+ now := limiter.nowFn()
+
+ // Create a locked entry (exceed max attempts)
+ for i := 0; i < cfg.MaxAttempts+1; i++ {
+ limiter.record(lockedKey, now, false)
+ }
+
+ // Create a stale entry
+ limiter.record(staleKey, now, false)
+
+ // Wait for entries to be outside the window but locked entry still locked
+ time.Sleep(100 * time.Millisecond)
+
+ // Trigger cleanup
+ limiter.cleanup()
+
+ // Verify locked entry is preserved and stale is removed
+ limiter.mu.Lock()
+ defer limiter.mu.Unlock()
+
+ if _, exists := limiter.state[lockedKey]; !exists {
+ t.Error("Locked entry should be preserved during lockout period")
+ }
+
+ if _, exists := limiter.state[staleKey]; exists {
+ t.Error("Stale entry should be removed")
+ }
+}
+
+func TestAuthRateLimiterStop(t *testing.T) {
+ cfg := config.AuthRateLimit{
+ Enabled: true,
+ MaxAttempts: 5,
+ BaseBackoff: 10 * time.Millisecond,
+ MaxBackoff: 100 * time.Millisecond,
+ Window: time.Second,
+ }
+
+ limiter := newAuthRateLimiter(cfg)
+
+ // Stop the limiter
+ limiter.Stop()
+
+ // Verify the cleanup goroutine exits (this test passes if no panic occurs)
+ time.Sleep(10 * time.Millisecond)
+}
diff --git a/backend/app/api/routes.go b/backend/app/api/routes.go
index c0d26b23..e88c63d6 100644
--- a/backend/app/api/routes.go
+++ b/backend/app/api/routes.go
@@ -184,7 +184,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
r.Post("/notifiers", chain.ToHandlerFunc(v1Ctrl.HandleCreateNotifier(), userMW...))
r.Put("/notifiers/{id}", chain.ToHandlerFunc(v1Ctrl.HandleUpdateNotifier(), userMW...))
r.Delete("/notifiers/{id}", chain.ToHandlerFunc(v1Ctrl.HandleDeleteNotifier(), userMW...))
- r.Post("/notifiers/test", chain.ToHandlerFunc(v1Ctrl.HandlerNotifierTest(), userMW...))
+ r.Post("/notifiers/test", chain.ToHandlerFunc(v1Ctrl.HandlerNotifierTest(), append(userMW, a.notifierTestLimiter.middleware)...))
// Asset-Like endpoints
assetMW := []errchain.Middleware{
diff --git a/backend/internal/core/services/all.go b/backend/internal/core/services/all.go
index 0609080a..03135fad 100644
--- a/backend/internal/core/services/all.go
+++ b/backend/internal/core/services/all.go
@@ -4,6 +4,7 @@ package services
import (
"github.com/sysadminsmedia/homebox/backend/internal/core/currencies"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
)
type AllServices struct {
@@ -19,6 +20,7 @@ type OptionsFunc func(*options)
type options struct {
autoIncrementAssetID bool
currencies []currencies.Currency
+ notifierConfig *config.NotifierConf
}
func WithAutoIncrementAssetID(v bool) func(*options) {
@@ -33,6 +35,23 @@ func WithCurrencies(v []currencies.Currency) func(*options) {
}
}
+func WithNotifierConfig(v *config.NotifierConf) func(*options) {
+ return func(o *options) {
+ if v != nil {
+ o.notifierConfig = v
+ }
+ }
+}
+
+// defaultNotifierConf returns a NotifierConf with safe defaults matching the conf tags.
+// This ensures SSRF protections are enabled when WithNotifierConfig is not provided.
+func defaultNotifierConf() *config.NotifierConf {
+ return &config.NotifierConf{
+ BlockBogonNets: true, // default:true per conf tag
+ BlockCloudMetadata: true, // default:true per conf tag
+ }
+}
+
func New(repos *repo.AllRepos, opts ...OptionsFunc) *AllServices {
if repos == nil {
panic("repos cannot be nil")
@@ -48,6 +67,7 @@ func New(repos *repo.AllRepos, opts ...OptionsFunc) *AllServices {
options := &options{
autoIncrementAssetID: true,
currencies: defaultCurrencies,
+ notifierConfig: defaultNotifierConf(),
}
for _, opt := range opts {
@@ -61,7 +81,11 @@ func New(repos *repo.AllRepos, opts ...OptionsFunc) *AllServices {
repo: repos,
autoIncrementAssetID: options.autoIncrementAssetID,
},
- BackgroundService: &BackgroundService{repos, Latest{}},
- Currencies: currencies.NewCurrencyService(options.currencies),
+ BackgroundService: &BackgroundService{
+ repos: repos,
+ latest: Latest{},
+ notifierConfig: options.notifierConfig,
+ },
+ Currencies: currencies.NewCurrencyService(options.currencies),
}
}
diff --git a/backend/internal/core/services/service_background.go b/backend/internal/core/services/service_background.go
index aa31a085..75eaefab 100644
--- a/backend/internal/core/services/service_background.go
+++ b/backend/internal/core/services/service_background.go
@@ -11,9 +11,10 @@ import (
"github.com/containrrr/shoutrrr"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
- "github.com/samber/lo"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
"github.com/sysadminsmedia/homebox/backend/internal/data/types"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
)
type Latest struct {
@@ -21,8 +22,9 @@ type Latest struct {
Date string `json:"date"`
}
type BackgroundService struct {
- repos *repo.AllRepos
- latest Latest
+ repos *repo.AllRepos
+ latest Latest
+ notifierConfig *config.NotifierConf
}
func (svc *BackgroundService) SendNotifiersToday(ctx context.Context) error {
@@ -50,14 +52,18 @@ func (svc *BackgroundService) SendNotifiersToday(ctx context.Context) error {
continue
}
- notifiers, err := svc.repos.Notifiers.GetByGroup(ctx, group.ID)
+ notifiers, err := svc.repos.Notifiers.GetActiveByGroup(ctx, group.ID)
if err != nil {
return err
}
- urls := lo.Map(notifiers, func(n repo.NotifierOut, _ int) string {
- return n.URL
- })
+ if len(notifiers) == 0 {
+ log.Debug().
+ Str("group_name", group.Name).
+ Str("group_id", group.ID.String()).
+ Msg("No active notifiers configured")
+ continue
+ }
bldr := strings.Builder{}
@@ -73,8 +79,19 @@ func (svc *BackgroundService) SendNotifiersToday(ctx context.Context) error {
}
var sendErrs []error
- for i := range urls {
- err := shoutrrr.Send(urls[i], bldr.String())
+ for i := range notifiers {
+ // Validate notifier URL before sending
+ if err := validate.ValidateNotifierURL(notifiers[i].URL, svc.notifierConfig); err != nil {
+ log.Error().
+ Err(err).
+ Str("notifier_id", notifiers[i].ID.String()).
+ Str("notifier_name", notifiers[i].Name).
+ Msg("notifier URL failed validation, skipping")
+ sendErrs = append(sendErrs, fmt.Errorf("notifier %s failed validation: %w", notifiers[i].Name, err))
+ continue
+ }
+
+ err := shoutrrr.Send(notifiers[i].URL, bldr.String())
if err != nil {
sendErrs = append(sendErrs, err)
diff --git a/backend/internal/sys/config/conf.go b/backend/internal/sys/config/conf.go
index 09534159..a498e2f0 100644
--- a/backend/internal/sys/config/conf.go
+++ b/backend/internal/sys/config/conf.go
@@ -32,6 +32,7 @@ type Config struct {
Thumbnail Thumbnail `yaml:"thumbnail"`
Barcode BarcodeAPIConf `yaml:"barcode"`
Auth AuthConfig `yaml:"auth"`
+ Notifier NotifierConf `yaml:"notifier"`
}
type Options struct {
diff --git a/backend/internal/sys/config/conf_notifier.go b/backend/internal/sys/config/conf_notifier.go
new file mode 100644
index 00000000..95d49872
--- /dev/null
+++ b/backend/internal/sys/config/conf_notifier.go
@@ -0,0 +1,18 @@
+package config
+
+type NotifierConf struct {
+ // AllowNets will allow specific networks through for generic notifiers.
+ // If this is filled, only these networks will be allowed through.
+ AllowNets []string `yaml:"allow_nets"`
+ // BlockNets will block specific networks from generic notifiers.
+ // If this is filled, these networks will be blocked from generic notifiers.
+ BlockNets []string `yaml:"block_nets"`
+ // BlockLocalhost will prevent generic notifiers from sending to localhost.
+ BlockLocalhost bool `yaml:"block_localhost" conf:"default:false"`
+ // BlockLocalNets will prevent generic notifiers from sending to local networks. (RFC1918)
+ BlockLocalNets bool `yaml:"block_local_nets" conf:"default:false"`
+ // BlockBogonNets will prevent generic notifiers from sending to bogon networks. (Reserved IPs)
+ BlockBogonNets bool `yaml:"block_bogon_nets" conf:"default:true"`
+ // BlockCloudMetadata will prevent generic notifiers from sending to known cloud metadata IPs.
+ BlockCloudMetadata bool `yaml:"block_cloud_metadata" conf:"default:true"`
+}
diff --git a/backend/internal/sys/validate/notifier_url.go b/backend/internal/sys/validate/notifier_url.go
new file mode 100644
index 00000000..0583d102
--- /dev/null
+++ b/backend/internal/sys/validate/notifier_url.go
@@ -0,0 +1,253 @@
+package validate
+
+import (
+ "fmt"
+ "net"
+ "net/url"
+ "strings"
+
+ "github.com/rs/zerolog/log"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
+)
+
+// ValidateNotifierURL validates a notifier URL against the configured block/allow lists.
+// This only applies to generic:// notifier URLs which can make arbitrary HTTP requests.
+func ValidateNotifierURL(notifierURL string, cfg *config.NotifierConf) error {
+ // Only validate generic notifiers
+ if !isGenericNotifier(notifierURL) {
+ return nil
+ }
+
+ // Defensively guard against nil cfg
+ if cfg == nil {
+ return fmt.Errorf("notifier configuration is nil, cannot validate URL")
+ }
+
+ // Extract the actual URL from the generic:// wrapper
+ actualURL, err := extractGenericURL(notifierURL)
+ if err != nil {
+ return fmt.Errorf("invalid generic notifier URL: %w", err)
+ }
+
+ // Parse the URL to extract the hostname
+ parsedURL, err := url.Parse(actualURL)
+ if err != nil {
+ return fmt.Errorf("invalid URL in generic notifier: %w", err)
+ }
+
+ host := parsedURL.Hostname()
+ if host == "" {
+ return fmt.Errorf("no hostname found in URL")
+ }
+
+ // Resolve the hostname to an IP address
+ // NOTE: DNS responses can change after validation; consider re-validating at request time.
+ ips, err := net.LookupIP(host)
+ if err != nil {
+ return fmt.Errorf("failed to resolve hostname: %w", err)
+ }
+
+ if len(ips) == 0 {
+ return fmt.Errorf("hostname did not resolve to any IP addresses")
+ }
+
+ // If AllowNets is configured, only allow IPs in those networks
+ if len(cfg.AllowNets) > 0 {
+ for _, ip := range ips {
+ allowed := false
+ for _, allowNet := range cfg.AllowNets {
+ _, ipNet, err := net.ParseCIDR(allowNet)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("cidr", allowNet).
+ Str("config", "AllowNets").
+ Msg("invalid CIDR in notifier AllowNets configuration, skipping")
+ continue // Skip invalid CIDR
+ }
+ if ipNet.Contains(ip) {
+ allowed = true
+ break
+ }
+ }
+ if !allowed {
+ return fmt.Errorf("IP %s is not in the allowed networks", ip.String())
+ }
+ }
+ // If explicitly allowed, skip other checks
+ return nil
+ }
+
+ // Check BlockNets - block specific networks if configured
+ if len(cfg.BlockNets) > 0 {
+ for _, ip := range ips {
+ for _, blockNet := range cfg.BlockNets {
+ _, ipNet, err := net.ParseCIDR(blockNet)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("cidr", blockNet).
+ Str("config", "BlockNets").
+ Msg("invalid CIDR in notifier BlockNets configuration, skipping")
+ continue // Skip invalid CIDR
+ }
+ if ipNet.Contains(ip) {
+ return fmt.Errorf("IP %s is in a blocked network (%s)", ip.String(), blockNet)
+ }
+ }
+ }
+ }
+
+ for _, ip := range ips {
+ // Block localhost if configured
+ if cfg.BlockLocalhost && isLocalhost(ip) {
+ return fmt.Errorf("localhost addresses are blocked")
+ }
+
+ // Block RFC1918 private networks if configured
+ if cfg.BlockLocalNets && isPrivateNetwork(ip) {
+ return fmt.Errorf("private network addresses (RFC1918) are blocked")
+ }
+
+ // Block bogon networks (reserved IPs) if configured
+ if cfg.BlockBogonNets && isBogonNetwork(ip) {
+ return fmt.Errorf("bogon/reserved network addresses are blocked")
+ }
+
+ // Block cloud metadata endpoints if configured
+ if cfg.BlockCloudMetadata && isCloudMetadata(ip) {
+ return fmt.Errorf("cloud metadata endpoints are blocked")
+ }
+ }
+
+ return nil
+}
+
+// isGenericNotifier checks if the URL is a generic notifier that needs validation
+func isGenericNotifier(notifierURL string) bool {
+ return strings.HasPrefix(notifierURL, "generic://") ||
+ strings.HasPrefix(notifierURL, "generic+https://") ||
+ strings.HasPrefix(notifierURL, "generic+http://")
+}
+
+// extractGenericURL extracts the actual HTTP(S) URL from a generic notifier URL
+func extractGenericURL(notifierURL string) (string, error) {
+ if strings.HasPrefix(notifierURL, "generic://") {
+ return strings.TrimPrefix(notifierURL, "generic://"), nil
+ }
+ if strings.HasPrefix(notifierURL, "generic+https://") {
+ return strings.TrimPrefix(notifierURL, "generic+"), nil
+ }
+ if strings.HasPrefix(notifierURL, "generic+http://") {
+ return strings.TrimPrefix(notifierURL, "generic+"), nil
+ }
+ return "", fmt.Errorf("not a generic notifier URL")
+}
+
+// isLocalhost checks if an IP is a localhost address
+func isLocalhost(ip net.IP) bool {
+ return ip.IsLoopback()
+}
+
+// isPrivateNetwork checks if an IP is in private address space.
+// This uses the standard library's IsPrivate() which covers:
+// - IPv4: RFC1918 (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
+// - IPv6: Unique Local Addresses (fc00::/7)
+func isPrivateNetwork(ip net.IP) bool {
+ return ip.IsPrivate()
+}
+
+// isBogonNetwork checks if an IP is in reserved/bogon address space
+func isBogonNetwork(ip net.IP) bool {
+ // Separate IPv4 and IPv6 bogon ranges to avoid cross-version matching
+ ipv4BogonNetworks := []string{
+ "0.0.0.0/8", // Current network
+ "100.64.0.0/10", // Shared Address Space (RFC6598)
+ "169.254.0.0/16", // Link-local
+ "192.0.0.0/24", // IETF Protocol Assignments
+ "192.0.2.0/24", // TEST-NET-1
+ "198.18.0.0/15", // Benchmarking
+ "198.51.100.0/24", // TEST-NET-2
+ "203.0.113.0/24", // TEST-NET-3
+ "224.0.0.0/4", // Multicast
+ "240.0.0.0/4", // Reserved
+ "255.255.255.255/32", // Broadcast
+ }
+
+ ipv6BogonNetworks := []string{
+ "::/128", // Unspecified
+ "::1/128", // Loopback
+ "::ffff:0:0/96", // IPv4-mapped
+ "100::/64", // Discard prefix
+ "2001::/32", // TEREDO
+ "2001:10::/28", // ORCHID
+ "2001:db8::/32", // Documentation
+ "fc00::/7", // Unique local
+ "fe80::/10", // Link-local
+ "ff00::/8", // Multicast
+ }
+
+ // Determine if IP is IPv4 or IPv6 and check against appropriate list
+ ipv4 := ip.To4()
+ if ipv4 != nil {
+ // This is an IPv4 address, check against IPv4 bogon ranges
+ for _, cidr := range ipv4BogonNetworks {
+ _, ipNet, err := net.ParseCIDR(cidr)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("cidr", cidr).
+ Str("check", "IPv4BogonNetworks").
+ Msg("invalid CIDR in hardcoded bogon networks")
+ continue
+ }
+ if ipNet.Contains(ip) {
+ return true
+ }
+ }
+ } else {
+ // This is an IPv6 address, check against IPv6 bogon ranges
+ for _, cidr := range ipv6BogonNetworks {
+ _, ipNet, err := net.ParseCIDR(cidr)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("cidr", cidr).
+ Str("check", "IPv6BogonNetworks").
+ Msg("invalid CIDR in hardcoded bogon networks")
+ continue
+ }
+ if ipNet.Contains(ip) {
+ return true
+ }
+ }
+ }
+
+ return false
+}
+
+// isCloudMetadata checks if an IP is a known cloud metadata endpoint
+func isCloudMetadata(ip net.IP) bool {
+ metadataAddresses := []string{
+ "169.254.169.254/32", // AWS, Azure, GCP, Oracle Cloud
+ "169.254.169.253/32", // AWS IMDSv2 alternative
+ "fd00:ec2::254/128", // AWS IPv6 metadata
+ }
+
+ for _, cidr := range metadataAddresses {
+ _, ipNet, err := net.ParseCIDR(cidr)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("cidr", cidr).
+ Str("check", "CloudMetadata").
+ Msg("invalid CIDR in hardcoded cloud metadata addresses")
+ continue
+ }
+ if ipNet.Contains(ip) {
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/backend/internal/sys/validate/notifier_url_test.go b/backend/internal/sys/validate/notifier_url_test.go
new file mode 100644
index 00000000..5168499c
--- /dev/null
+++ b/backend/internal/sys/validate/notifier_url_test.go
@@ -0,0 +1,489 @@
+package validate
+
+import (
+ "testing"
+
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
+)
+
+func TestValidateNotifierURL(t *testing.T) {
+ tests := []struct {
+ name string
+ url string
+ config config.NotifierConf
+ expectError bool
+ }{
+ {
+ name: "non-generic notifier passes validation",
+ url: "discord://token@id",
+ config: config.NotifierConf{
+ BlockLocalhost: true,
+ },
+ expectError: false,
+ },
+ {
+ name: "generic notifier with public IP passes",
+ url: "generic://https://example.com/webhook",
+ config: config.NotifierConf{
+ BlockLocalhost: true,
+ BlockLocalNets: true,
+ BlockBogonNets: true,
+ BlockCloudMetadata: true,
+ },
+ expectError: false,
+ },
+ {
+ name: "generic notifier with localhost blocked",
+ url: "generic://http://localhost:8080/webhook",
+ config: config.NotifierConf{
+ BlockLocalhost: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "generic notifier with 127.0.0.1 blocked",
+ url: "generic://http://127.0.0.1:8080/webhook",
+ config: config.NotifierConf{
+ BlockLocalhost: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "generic notifier with private network blocked",
+ url: "generic://http://192.168.1.1/webhook",
+ config: config.NotifierConf{
+ BlockLocalNets: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "generic notifier with 10.0.0.0/8 blocked",
+ url: "generic://http://10.0.0.1/webhook",
+ config: config.NotifierConf{
+ BlockLocalNets: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "generic notifier with 172.16.0.0/12 blocked",
+ url: "generic://http://172.16.0.1/webhook",
+ config: config.NotifierConf{
+ BlockLocalNets: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "generic notifier with cloud metadata blocked",
+ url: "generic://http://169.254.169.254/latest/meta-data",
+ config: config.NotifierConf{
+ BlockCloudMetadata: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "generic notifier with link-local blocked by bogon",
+ url: "generic://http://169.254.1.1/webhook",
+ config: config.NotifierConf{
+ BlockBogonNets: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "generic+https notifier with localhost blocked",
+ url: "generic+https://127.0.0.1/webhook",
+ config: config.NotifierConf{
+ BlockLocalhost: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "generic+http notifier with private net blocked",
+ url: "generic+http://192.168.1.100/webhook",
+ config: config.NotifierConf{
+ BlockLocalNets: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "allow list permits private IP",
+ url: "generic://http://192.168.1.1/webhook",
+ config: config.NotifierConf{
+ AllowNets: []string{"192.168.1.0/24"},
+ BlockLocalNets: true,
+ },
+ expectError: false,
+ },
+ {
+ name: "allow list blocks non-matching IP",
+ url: "generic://http://10.0.0.1/webhook",
+ config: config.NotifierConf{
+ AllowNets: []string{"192.168.1.0/24"},
+ },
+ expectError: true,
+ },
+ {
+ name: "localhost_allowed_when_not_blocked",
+ url: "generic://http://localhost:8080/webhook",
+ config: config.NotifierConf{
+ BlockLocalhost: false,
+ },
+ expectError: false,
+ },
+ {
+ name: "block_nets blocks specific network",
+ url: "generic://http://192.168.1.1/webhook",
+ config: config.NotifierConf{
+ BlockNets: []string{"192.168.1.0/24"},
+ },
+ expectError: true,
+ },
+ {
+ name: "block_nets allows non-matching network",
+ url: "generic://http://10.0.0.1/webhook",
+ config: config.NotifierConf{
+ BlockNets: []string{"192.168.1.0/24"},
+ },
+ expectError: false,
+ },
+ {
+ name: "block_nets with multiple networks",
+ url: "generic://http://172.16.0.1/webhook",
+ config: config.NotifierConf{
+ BlockNets: []string{"192.168.0.0/16", "172.16.0.0/12", "10.0.0.0/8"},
+ },
+ expectError: true,
+ },
+ {
+ name: "block_nets does not affect non-generic notifiers",
+ url: "discord://token@id",
+ config: config.NotifierConf{
+ BlockNets: []string{"0.0.0.0/0"},
+ },
+ expectError: false,
+ },
+ {
+ name: "allow_nets takes precedence over block_nets",
+ url: "generic://http://192.168.1.1/webhook",
+ config: config.NotifierConf{
+ AllowNets: []string{"192.168.1.0/24"},
+ BlockNets: []string{"192.168.1.0/24"},
+ },
+ expectError: false,
+ },
+ // IPv6 test cases
+ {
+ name: "ipv6_loopback_blocked_when_localhost_blocked",
+ url: "generic://http://[::1]:8080/webhook",
+ config: config.NotifierConf{
+ BlockLocalhost: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "ipv6_loopback_allowed_when_localhost_not_blocked",
+ url: "generic://http://[::1]:8080/webhook",
+ config: config.NotifierConf{
+ BlockLocalhost: false,
+ },
+ expectError: false,
+ },
+ {
+ name: "ipv6_ula_blocked_by_bogon_nets",
+ url: "generic://http://[fd00::1]/webhook",
+ config: config.NotifierConf{
+ BlockBogonNets: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "ipv6_ula_allowed_when_bogon_nets_not_blocked",
+ url: "generic://http://[fd00::1]/webhook",
+ config: config.NotifierConf{
+ BlockBogonNets: false,
+ },
+ expectError: false,
+ },
+ {
+ name: "ipv6_ula_allowed_via_allow_nets",
+ url: "generic://http://[fd00::1]/webhook",
+ config: config.NotifierConf{
+ AllowNets: []string{"fd00::/8"},
+ BlockBogonNets: true,
+ },
+ expectError: false,
+ },
+ {
+ name: "ipv6_link_local_blocked_by_bogon_nets",
+ url: "generic://http://[fe80::1]/webhook",
+ config: config.NotifierConf{
+ BlockBogonNets: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "ipv6_link_local_allowed_when_bogon_nets_not_blocked",
+ url: "generic://http://[fe80::1]/webhook",
+ config: config.NotifierConf{
+ BlockBogonNets: false,
+ },
+ expectError: false,
+ },
+ {
+ name: "ipv6_aws_metadata_blocked_when_cloud_metadata_blocked",
+ url: "generic://http://[fd00:ec2::254]/webhook",
+ config: config.NotifierConf{
+ BlockCloudMetadata: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "ipv6_aws_metadata_allowed_when_cloud_metadata_not_blocked",
+ url: "generic://http://[fd00:ec2::254]/webhook",
+ config: config.NotifierConf{
+ BlockCloudMetadata: false,
+ },
+ expectError: false,
+ },
+ {
+ name: "ipv6_block_nets_blocks_specific_ipv6_network",
+ url: "generic://http://[2001:db8::1]/webhook",
+ config: config.NotifierConf{
+ BlockNets: []string{"2001:db8::/32"},
+ },
+ expectError: true,
+ },
+ {
+ name: "ipv6_block_nets_allows_non_matching_ipv6",
+ url: "generic://http://[2001:db8::1]/webhook",
+ config: config.NotifierConf{
+ BlockNets: []string{"2001:db9::/32"},
+ },
+ expectError: false,
+ },
+ {
+ name: "ipv6_ula_blocked_by_local_nets",
+ url: "generic://http://[fd00::1]/webhook",
+ config: config.NotifierConf{
+ BlockLocalNets: true,
+ },
+ expectError: true,
+ },
+ {
+ name: "ipv6_ula_allowed_when_local_nets_not_blocked",
+ url: "generic://http://[fd00::1]/webhook",
+ config: config.NotifierConf{
+ BlockLocalNets: false,
+ },
+ expectError: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateNotifierURL(tt.url, &tt.config)
+ if tt.expectError && err == nil {
+ t.Errorf("expected error but got none")
+ }
+ if !tt.expectError && err != nil {
+ t.Errorf("expected no error but got: %v", err)
+ }
+ })
+ }
+}
+
+func TestIsGenericNotifier(t *testing.T) {
+ tests := []struct {
+ name string
+ url string
+ expected bool
+ }{
+ {"generic://", "generic://http://example.com", true},
+ {"generic+https://", "generic+https://example.com", true},
+ {"generic+http://", "generic+http://example.com", true},
+ {"discord://", "discord://token@id", false},
+ {"slack://", "slack://token@channel", false},
+ {"smtp://", "smtp://user:pass@host:587", false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := isGenericNotifier(tt.url)
+ if result != tt.expected {
+ t.Errorf("expected %v but got %v", tt.expected, result)
+ }
+ })
+ }
+}
+
+func TestExtractGenericURL(t *testing.T) {
+ tests := []struct {
+ name string
+ url string
+ expected string
+ expectError bool
+ }{
+ {
+ name: "generic://",
+ url: "generic://http://example.com/webhook",
+ expected: "http://example.com/webhook",
+ expectError: false,
+ },
+ {
+ name: "generic+https://",
+ url: "generic+https://example.com/webhook",
+ expected: "https://example.com/webhook",
+ expectError: false,
+ },
+ {
+ name: "generic+http://",
+ url: "generic+http://example.com/webhook",
+ expected: "http://example.com/webhook",
+ expectError: false,
+ },
+ {
+ name: "not generic",
+ url: "discord://token@id",
+ expected: "",
+ expectError: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result, err := extractGenericURL(tt.url)
+ if tt.expectError && err == nil {
+ t.Errorf("expected error but got none")
+ }
+ if !tt.expectError && err != nil {
+ t.Errorf("expected no error but got: %v", err)
+ }
+ if result != tt.expected {
+ t.Errorf("expected %v but got %v", tt.expected, result)
+ }
+ })
+ }
+}
+
+func TestValidateNotifierURL_InvalidCIDR_AllowNets(t *testing.T) {
+ // Test with invalid CIDR in AllowNets - should skip invalid and check valid ones
+ tests := []struct {
+ name string
+ url string
+ config config.NotifierConf
+ expectError bool
+ description string
+ }{
+ {
+ name: "invalid CIDR in AllowNets is skipped",
+ url: "generic://http://192.168.1.100/webhook",
+ config: config.NotifierConf{
+ AllowNets: []string{
+ "invalid-cidr", // Invalid - should be logged and skipped
+ "192.168.1.0/24", // Valid - should match
+ },
+ },
+ expectError: false,
+ description: "IP should be allowed by valid CIDR despite invalid CIDR present",
+ },
+ {
+ name: "all CIDRs invalid in AllowNets",
+ url: "generic://http://192.168.1.100/webhook",
+ config: config.NotifierConf{
+ AllowNets: []string{
+ "invalid-cidr-1",
+ "not-a-cidr",
+ "999.999.999.999/32",
+ },
+ },
+ expectError: true,
+ description: "IP should be blocked when all AllowNets CIDRs are invalid",
+ },
+ {
+ name: "mixed valid and invalid CIDRs",
+ url: "generic://http://10.0.0.100/webhook",
+ config: config.NotifierConf{
+ AllowNets: []string{
+ "invalid",
+ "10.0.0.0/24",
+ "also-invalid",
+ },
+ },
+ expectError: false,
+ description: "Valid CIDR should work despite surrounding invalid CIDRs",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateNotifierURL(tt.url, &tt.config)
+ if tt.expectError && err == nil {
+ t.Errorf("%s: expected error but got none", tt.description)
+ }
+ if !tt.expectError && err != nil {
+ t.Errorf("%s: expected no error but got: %v", tt.description, err)
+ }
+ })
+ }
+}
+
+func TestValidateNotifierURL_InvalidCIDR_BlockNets(t *testing.T) {
+ // Test with invalid CIDR in BlockNets - should skip invalid and check valid ones
+ tests := []struct {
+ name string
+ url string
+ config config.NotifierConf
+ expectError bool
+ description string
+ }{
+ {
+ name: "invalid CIDR in BlockNets is skipped",
+ url: "generic://http://192.168.1.100/webhook",
+ config: config.NotifierConf{
+ BlockNets: []string{
+ "invalid-cidr", // Invalid - should be logged and skipped
+ "10.0.0.0/8", // Valid but doesn't match
+ },
+ },
+ expectError: false,
+ description: "IP should pass when invalid CIDR is skipped and valid one doesn't match",
+ },
+ {
+ name: "invalid CIDR doesn't prevent valid blocking",
+ url: "generic://http://192.168.1.100/webhook",
+ config: config.NotifierConf{
+ BlockNets: []string{
+ "not-a-cidr",
+ "192.168.1.0/24", // Valid - should block
+ "also-invalid",
+ },
+ },
+ expectError: true,
+ description: "Valid blocking CIDR should work despite invalid CIDRs",
+ },
+ {
+ name: "all CIDRs invalid in BlockNets",
+ url: "generic://http://192.168.1.100/webhook",
+ config: config.NotifierConf{
+ BlockNets: []string{
+ "invalid-1",
+ "invalid-2",
+ "999.999.999.999/32",
+ },
+ },
+ expectError: false,
+ description: "IP should pass when all BlockNets CIDRs are invalid",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateNotifierURL(tt.url, &tt.config)
+ if tt.expectError && err == nil {
+ t.Errorf("%s: expected error but got none", tt.description)
+ }
+ if !tt.expectError && err != nil {
+ t.Errorf("%s: expected no error but got: %v", tt.description, err)
+ }
+ })
+ }
+}
diff --git a/docs/src/content/docs/en/quick-start/configure/index.mdx b/docs/src/content/docs/en/quick-start/configure/index.mdx
index 65ee8933..c0e78f35 100644
--- a/docs/src/content/docs/en/quick-start/configure/index.mdx
+++ b/docs/src/content/docs/en/quick-start/configure/index.mdx
@@ -84,6 +84,12 @@ import {Tabs, TabItem} from "@astrojs/starlight/components";
| HBOX_THUMBNAIL_WIDTH | 500 | width for generated thumbnails in pixels |
| HBOX_THUMBNAIL_HEIGHT | 500 | height for generated thumbnails in pixels |
| HBOX_BARCODE_TOKEN_BARCODESPIDER | | API token for BarcodeSpider.com service used for barcode product lookups. If not set, barcode product lookups will not be performed. |
+| HBOX_NOTIFIER_ALLOW_NETS | | comma-separated list of CIDR networks to allow for generic notifiers (e.g., `192.168.1.0/24,10.0.0.0/8`). If set, only these networks will be allowed and all block rules are bypassed. |
+| HBOX_NOTIFIER_BLOCK_NETS | | comma-separated list of CIDR networks to block for generic notifiers (e.g., `192.168.1.0/24,10.0.0.0/8`). Provides fine-grained blocking without enabling blanket rules. |
+| HBOX_NOTIFIER_BLOCK_LOCALHOST | false | block generic notifiers from sending to localhost/loopback addresses (127.0.0.1, ::1) |
+| HBOX_NOTIFIER_BLOCK_LOCAL_NETS | false | block generic notifiers from sending to RFC1918 private networks (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) |
+| HBOX_NOTIFIER_BLOCK_BOGON_NETS | true | block generic notifiers from sending to bogon/reserved networks (link-local, multicast, broadcast, etc.) |
+| HBOX_NOTIFIER_BLOCK_CLOUD_METADATA | true | block generic notifiers from sending to cloud metadata endpoints (169.254.169.254, fd00:ec2::254) |
</TabItem>
<TabItem label="CLI Options">
@@ -133,6 +139,12 @@ OPTIONS
--mailer-port <int>
--mailer-username <string>
--mode <string> (default: development)
+ --notifier-allow-nets <string>
+ --notifier-block-nets <string>
+ --notifier-block-bogon-nets <bool> (default: true)
+ --notifier-block-cloud-metadata <bool> (default: true)
+ --notifier-block-local-nets <bool> (default: false)
+ --notifier-block-localhost <bool> (default: false)
--oidc-allowed-groups <string>
--oidc-auto-redirect <bool> (default: false)
--oidc-button-text <string> (default: Sign in with OIDC)
diff --git a/docs/src/content/docs/en/user-guide/notifiers.mdx b/docs/src/content/docs/en/user-guide/notifiers.mdx
new file mode 100644
index 00000000..16bfb2b5
--- /dev/null
+++ b/docs/src/content/docs/en/user-guide/notifiers.mdx
@@ -0,0 +1,317 @@
+---
+title: Notifiers
+---
+
+## Overview
+
+Homebox supports sending notifications for scheduled maintenance reminders using [Shoutrrr](https://containrrr.dev/shoutrrr/), which provides integrations with many popular notification services like Discord, Slack, Telegram, and more.
+
+## Supported Services
+
+Homebox supports all notification services provided by Shoutrrr, including:
+
+- **Bark** - iOS notification app
+- **Discord** - Popular chat platform
+- **Email (SMTP)** - Standard email notifications
+- **Gotify** - Self-hosted notification server
+- **Google Chat** - Google Workspace chat
+- **IFTTT** - If This Then That automation
+- **Join** - Android notification service
+- **Mattermost** - Open-source team collaboration
+- **Matrix** - Decentralized communication protocol
+- **Ntfy** - Simple HTTP-based notification service
+- **OpsGenie** - Incident management platform
+- **Pushbullet** - Cross-platform notifications
+- **Pushover** - Push notifications for iOS and Android
+- **RocketChat** - Open-source team chat
+- **Slack** - Team collaboration platform
+- **Teams** - Microsoft Teams
+- **Telegram** - Messaging platform
+- **Zulip** - Team chat platform
+- **Generic Webhook** - Custom HTTP endpoints
+
+For detailed configuration for each service, see the [Shoutrrr documentation](https://containrrr.dev/shoutrrr/v0.8/services/overview/).
+
+## Configuring Notifiers
+### Common Examples
+
+#### Discord
+
+```
+discord://webhook_token@webhook_id
+```
+
+To get these values:
+1. In Discord, go to Server Settings → Integrations → Webhooks
+2. Create or edit a webhook
+3. Copy the webhook URL: `https://discord.com/api/webhooks/WEBHOOK_ID/WEBHOOK_TOKEN`
+4. Format as: `discord://WEBHOOK_TOKEN@WEBHOOK_ID`
+
+#### Slack
+
+```
+slack://token@channel
+```
+
+Or for webhook URLs:
+```
+slack://webhook_token@webhook_token_b/webhook_token_c
+```
+
+#### Telegram
+
+```
+telegram://bot_token@telegram?chats=chat_id
+```
+
+#### Email (SMTP)
+
+```
+smtp://username:password@host:port/[email protected]&[email protected]
+```
+
+#### Ntfy
+
+```
+ntfy://ntfy.sh/your-topic
+```
+
+For self-hosted ntfy:
+```
+ntfy://your-ntfy.domain.com/your-topic
+```
+
+#### Generic Webhook
+
+For custom HTTP webhooks:
+
+```
+generic://https://your-webhook-endpoint.com/path
+```
+
+Or explicitly specify HTTP method:
+```
+generic+https://your-webhook-endpoint.com/path
+generic+http://your-webhook-endpoint.com/path
+```
+
+## Security Considerations for Generic Webhooks
+
+Generic webhooks allow Homebox to make HTTP requests to arbitrary URLs. To prevent Server-Side Request Forgery (SSRF) attacks and protect your internal network, Homebox provides several configuration options to restrict where generic notifiers can send requests.
+
+:::caution[Security Notice]
+Generic webhooks (`generic://`, `generic+https://`, `generic+http://`) can be used to make requests to any accessible network endpoint. Configure the security settings below to protect your internal infrastructure.
+:::
+
+### Configuration Options
+
+All security options apply only to generic webhook notifiers. Other notification services (Discord, Slack, etc.) are not affected by these settings.
+
+#### Allow List (Recommended)
+
+The most secure approach is to use an allow list. When configured, **only** the specified networks are allowed, and all block rules are bypassed.
+
+```bash
+HBOX_NOTIFIER_ALLOW_NETS="192.168.1.0/24,10.0.50.0/24"
+```
+
+**Use Case:** You have specific internal webhook endpoints at known IP ranges and want to only allow those.
+
+#### Block Localhost
+
+Prevents generic notifiers from making requests to localhost/loopback addresses (127.0.0.1, ::1).
+
+```bash
+HBOX_NOTIFIER_BLOCK_LOCALHOST=true
+```
+
+**Default:** `false`
+
+**Use Case:** Prevent access to services running on the same host as Homebox (e.g., admin panels, development servers).
+
+#### Block Local Networks (RFC1918)
+
+Prevents generic notifiers from making requests to private network ranges:
+- 10.0.0.0/8
+- 172.16.0.0/12
+- 192.168.0.0/16
+
+```bash
+HBOX_NOTIFIER_BLOCK_LOCAL_NETS=true
+```
+
+**Default:** `false`
+
+**Use Case:** Block access to all internal network services to prevent SSRF attacks against internal infrastructure.
+
+#### Block Bogon Networks
+
+Prevents generic notifiers from making requests to reserved/special-use IP ranges including:
+- Link-local addresses (169.254.0.0/16)
+- Multicast addresses
+- Broadcast addresses
+- Reserved IP ranges
+- Documentation/test networks
+
+```bash
+HBOX_NOTIFIER_BLOCK_BOGON_NETS=true
+```
+
+**Default:** `true` (enabled by default)
+
+**Use Case:** Prevent access to special-use addresses that should never be accessed in production.
+
+#### Block Cloud Metadata Endpoints
+
+Prevents generic notifiers from accessing cloud provider metadata endpoints:
+- 169.254.169.254 (AWS, Azure, GCP, Oracle Cloud)
+- 169.254.169.253 (AWS IMDSv2)
+- fd00:ec2::254 (AWS IPv6)
+
+```bash
+HBOX_NOTIFIER_BLOCK_CLOUD_METADATA=true
+```
+
+**Default:** `true` (enabled by default)
+
+**Use Case:** Critical security measure when running Homebox in cloud environments. Prevents attackers from accessing cloud metadata that often contains sensitive credentials and configuration.
+
+#### Block Specific Networks
+
+Allows you to block specific network ranges using CIDR notation. This provides fine-grained control without needing to enable the blanket `BLOCK_LOCAL_NETS` or `BLOCK_BOGON_NETS` options.
+
+```bash
+HBOX_NOTIFIER_BLOCK_NETS="192.168.1.0/24,172.16.0.0/12,10.10.0.0/16"
+```
+
+**Default:** (empty, no networks blocked)
+
+**Use Case:** Selectively block specific internal subnets while allowing others. For example:
+- Block development/staging environments while allowing production webhook endpoints
+- Block specific office networks that shouldn't be accessible
+- Enforce organizational security policies that restrict certain network ranges
+
+**Examples:**
+
+Block a single IP:
+```bash
+HBOX_NOTIFIER_BLOCK_NETS="192.168.1.100/32"
+```
+
+Block multiple networks:
+```bash
+HBOX_NOTIFIER_BLOCK_NETS="192.168.0.0/16,172.16.0.0/12,10.10.0.0/16"
+```
+
+**Note:** `HBOX_NOTIFIER_ALLOW_NETS` takes precedence over `HBOX_NOTIFIER_BLOCK_NETS`. If an IP is in the allow list, it will not be blocked even if it matches a network in the block list.
+
+### Recommended Security Configurations
+
+#### Public Internet Deployment
+
+For Homebox instances accessible from the internet, use strict security settings:
+
+```bash
+HBOX_NOTIFIER_BLOCK_LOCALHOST=true
+HBOX_NOTIFIER_BLOCK_LOCAL_NETS=true
+HBOX_NOTIFIER_BLOCK_BOGON_NETS=true
+HBOX_NOTIFIER_BLOCK_CLOUD_METADATA=true
+```
+
+#### Internal Network with Specific Webhooks
+
+For internal deployments where you want to allow specific webhook endpoints:
+
+```bash
+HBOX_NOTIFIER_ALLOW_NETS="192.168.1.100/32,10.0.20.0/24"
+```
+
+Note: When using the allow list, all block rules are bypassed. Only the specified networks will be permitted.
+
+#### Selective Network Blocking
+
+For environments where you want to block specific networks without blocking all private networks:
+
+```bash
+HBOX_NOTIFIER_BLOCK_NETS="192.168.1.0/24,10.10.0.0/16"
+HBOX_NOTIFIER_BLOCK_LOCALHOST=true
+HBOX_NOTIFIER_BLOCK_BOGON_NETS=true
+HBOX_NOTIFIER_BLOCK_CLOUD_METADATA=true
+```
+
+**Use Case:** You want to allow webhooks to most of your internal network (e.g., 10.0.0.0/8), but block specific subnets like development (10.10.0.0/16) or guest networks (192.168.1.0/24).
+
+#### Development Environment
+
+For development environments where you need more flexibility:
+
+```bash
+HBOX_NOTIFIER_BLOCK_LOCALHOST=false
+HBOX_NOTIFIER_BLOCK_LOCAL_NETS=false
+HBOX_NOTIFIER_BLOCK_BOGON_NETS=true
+HBOX_NOTIFIER_BLOCK_CLOUD_METADATA=true
+```
+
+## How Notifications Work
+
+### Scheduled Maintenance Reminders
+
+When you create maintenance entries with scheduled dates, Homebox will:
+
+1. Check daily for maintenance scheduled for today
+2. For each group with scheduled maintenance, collect all active notifiers
+3. Send a notification listing all maintenance items due today
+4. Only active notifiers will receive notifications
+
+### Message Format
+
+Notifications are sent in the following format:
+
+```
+Homebox Maintenance for (YYYY-MM-DD):
+ - Maintenance Item 1
+ - Maintenance Item 2
+ - Maintenance Item 3
+```
+
+## Troubleshooting
+
+### Test Button Fails
+
+If the test button fails:
+
+1. **Check the URL format** - Each service has specific URL format requirements. Refer to the [Shoutrrr documentation](https://containrrr.dev/shoutrrr/v0.8/services/overview/).
+2. **Verify credentials** - Ensure tokens, API keys, and passwords are correct
+3. **Check security settings** - For generic webhooks, ensure your URL isn't blocked by security configuration
+4. **Review logs** - Check Homebox logs for specific error messages
+
+### Notifications Not Being Sent
+
+If scheduled notifications aren't being sent:
+
+1. **Verify the notifier is active** - Toggle the "Active" switch in the notifier configuration
+2. **Check maintenance schedule** - Ensure maintenance items have scheduled dates set
+3. **Verify date** - Notifications are sent on the scheduled date at the configured time
+4. **Check logs** - Review Homebox logs for error messages during notification attempts
+
+### Generic Webhook Blocked
+
+If your generic webhook is being blocked by security settings:
+
+1. **Check the resolved IP** - The target hostname resolves to an IP that's in a blocked range
+2. **Review security configuration** - Adjust block settings or use the allow list
+3. **Use allow list** - The most reliable way to permit specific endpoints
+
+Example error messages:
+- "localhost addresses are blocked"
+- "private network addresses (RFC1918) are blocked"
+- "bogon/reserved network addresses are blocked"
+- "cloud metadata endpoints are blocked"
+- "IP X.X.X.X is not in the allowed networks"
+
+
+
+
+
+
+