Skip to content

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

feat: implement authentication rate limiting and security headers middleware

Matthew Kilgore34bbfd148d23
diff --git a/backend/app/api/app.go b/backend/app/api/app.go
index 31910750..b9630fde 100644
--- a/backend/app/api/app.go
+++ b/backend/app/api/app.go
@@ -10,12 +10,13 @@ import (
)
type app struct {
- conf *config.Config
- mailer mailer.Mailer
- db *ent.Client
- repos *repo.AllRepos
- services *services.AllServices
- bus *eventbus.EventBus
+ conf *config.Config
+ mailer mailer.Mailer
+ db *ent.Client
+ repos *repo.AllRepos
+ services *services.AllServices
+ bus *eventbus.EventBus
+ authLimiter *authRateLimiter
}
func new(conf *config.Config) *app {
@@ -31,5 +32,7 @@ func new(conf *config.Config) *app {
From: s.conf.Mailer.From,
}
+ s.authLimiter = newAuthRateLimiter(s.conf.Auth.RateLimit)
+
return s
}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_auth.go b/backend/app/api/handlers/v1/v1_ctrl_auth.go
index 50468970..88b04238 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_auth.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_auth.go
@@ -196,6 +196,7 @@ func (ctrl *V1Controller) setCookies(w http.ResponseWriter, domain, token string
Secure: ctrl.cookieSecure,
HttpOnly: true,
Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
// Set HTTP only cookie
@@ -207,6 +208,7 @@ func (ctrl *V1Controller) setCookies(w http.ResponseWriter, domain, token string
Secure: ctrl.cookieSecure,
HttpOnly: true,
Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
// Set Fake Session cookie
@@ -218,6 +220,7 @@ func (ctrl *V1Controller) setCookies(w http.ResponseWriter, domain, token string
Secure: ctrl.cookieSecure,
HttpOnly: false,
Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
// Set attachment token cookie (accessible to frontend, not HttpOnly)
@@ -230,6 +233,7 @@ func (ctrl *V1Controller) setCookies(w http.ResponseWriter, domain, token string
Secure: ctrl.cookieSecure,
HttpOnly: false,
Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
}
}
@@ -243,6 +247,7 @@ func (ctrl *V1Controller) unsetCookies(w http.ResponseWriter, domain string) {
Secure: ctrl.cookieSecure,
HttpOnly: true,
Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
http.SetCookie(w, &http.Cookie{
@@ -253,6 +258,7 @@ func (ctrl *V1Controller) unsetCookies(w http.ResponseWriter, domain string) {
Secure: ctrl.cookieSecure,
HttpOnly: true,
Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
// Set Fake Session cookie
@@ -264,6 +270,7 @@ func (ctrl *V1Controller) unsetCookies(w http.ResponseWriter, domain string) {
Secure: ctrl.cookieSecure,
HttpOnly: false,
Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
// Unset attachment token cookie
@@ -275,6 +282,7 @@ func (ctrl *V1Controller) unsetCookies(w http.ResponseWriter, domain string) {
Secure: ctrl.cookieSecure,
HttpOnly: false,
Path: "/",
+ SameSite: http.SameSiteLaxMode,
})
}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_items_attachments.go b/backend/app/api/handlers/v1/v1_ctrl_items_attachments.go
index 882d80c2..f4701358 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_items_attachments.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_items_attachments.go
@@ -30,6 +30,14 @@ type (
}
)
+func sanitizeAttachmentName(name string) string {
+ name = filepath.Base(name)
+ name = strings.ReplaceAll(name, "..", "")
+ name = strings.ReplaceAll(name, "/", "")
+ name = strings.ReplaceAll(name, "\\", "")
+ return name
+}
+
// HandleItemAttachmentCreate godocs
//
// @Summary Create Item Attachment
@@ -77,6 +85,8 @@ func (ctrl *V1Controller) HandleItemAttachmentCreate() errchain.HandlerFunc {
return server.JSON(w, http.StatusUnprocessableEntity, errs)
}
+ attachmentName = sanitizeAttachmentName(attachmentName)
+
attachmentType := r.FormValue("type")
if attachmentType == "" {
// Attempt to auto-detect the type of the file
diff --git a/backend/app/api/main.go b/backend/app/api/main.go
index b3d8ccd0..a1f0c261 100644
--- a/backend/app/api/main.go
+++ b/backend/app/api/main.go
@@ -188,6 +188,9 @@ func run(cfg *config.Config) error {
middleware.RequestID,
middleware.RealIP,
mid.Logger(logger),
+ mid.SecurityHeaders(),
+ // Restrict the max body size to the upload limit + 1MB (for overhead)
+ mid.MaxBodySize(cfg.Web.MaxUploadSize+1),
middleware.Recoverer,
middleware.StripSlashes,
)
diff --git a/backend/app/api/middleware.go b/backend/app/api/middleware.go
index 1525f480..72c58d80 100644
--- a/backend/app/api/middleware.go
+++ b/backend/app/api/middleware.go
@@ -3,16 +3,22 @@ package main
import (
"context"
"errors"
+ "net"
"net/http"
"net/url"
+ "strconv"
"strings"
+ "sync"
+ "time"
- "github.com/google/uuid"
- "github.com/hay-kot/httpkit/errchain"
v1 "github.com/sysadminsmedia/homebox/backend/app/api/handlers/v1"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
"github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
+
+ "github.com/google/uuid"
+ "github.com/hay-kot/httpkit/errchain"
)
type tokenHasKey struct {
@@ -203,3 +209,154 @@ func (a *app) mwTenant(next errchain.Handler) errchain.Handler {
return next.ServeHTTP(w, r)
})
}
+
+// 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
+}
+
+// authAttempt struct represents the state of authentication attempts for a client.
+type authAttempt struct {
+ attempts int
+ lastAttempt time.Time
+ lockedUntil time.Time
+}
+
+// newAuthRateLimiter creates a new authRateLimiter instance.
+func newAuthRateLimiter(cfg config.AuthRateLimit) *authRateLimiter {
+ // Sanity defaults to avoid zero values creating odd behavior.
+ if cfg.MaxAttempts <= 0 {
+ cfg.MaxAttempts = 5
+ }
+ if cfg.BaseBackoff <= 0 {
+ cfg.BaseBackoff = 2 * time.Second
+ }
+ if cfg.MaxBackoff <= 0 {
+ cfg.MaxBackoff = 2 * time.Minute
+ }
+ if cfg.Window <= 0 {
+ cfg.Window = time.Minute
+ }
+
+ return &authRateLimiter{
+ cfg: cfg,
+ state: make(map[string]*authAttempt),
+ nowFn: time.Now,
+ }
+}
+
+// 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 {
+ limiter := a.authLimiter
+ if limiter == nil || !limiter.cfg.Enabled {
+ return next.ServeHTTP(w, r)
+ }
+
+ key := limiter.keyForRequest(r)
+ now := limiter.nowFn()
+
+ if retryAfter, allowed := limiter.shouldAllow(key, now); !allowed {
+ seconds := int(retryAfter.Round(time.Second).Seconds())
+ if seconds < 0 {
+ seconds = 0
+ }
+ w.Header().Set("Retry-After", strconv.Itoa(seconds))
+ return validate.NewRequestError(errors.New("too many authentication attempts"), http.StatusTooManyRequests)
+ }
+
+ err := next.ServeHTTP(w, r)
+ limiter.record(key, now, err == nil)
+ return err
+ })
+}
+
+// shouldAllow checks if the client should be allowed to authenticate based on the configured rate limit.
+func (l *authRateLimiter) shouldAllow(key string, now time.Time) (time.Duration, bool) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ attempt, ok := l.state[key]
+ if !ok {
+ return 0, true
+ }
+
+ if now.Sub(attempt.lastAttempt) > l.cfg.Window {
+ delete(l.state, key)
+ return 0, true
+ }
+
+ if now.Before(attempt.lockedUntil) {
+ return time.Until(attempt.lockedUntil), false
+ }
+
+ return 0, true
+}
+
+// record updates the authentication attempt state for the given client.
+func (l *authRateLimiter) record(key string, now time.Time, success bool) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ if success {
+ delete(l.state, key)
+ return
+ }
+
+ attempt, ok := l.state[key]
+ if !ok {
+ l.state[key] = &authAttempt{attempts: 1, lastAttempt: now}
+ return
+ }
+
+ if now.Sub(attempt.lastAttempt) > l.cfg.Window {
+ attempt.attempts = 0
+ attempt.lockedUntil = time.Time{}
+ }
+
+ attempt.attempts++
+ attempt.lastAttempt = now
+
+ if attempt.attempts > l.cfg.MaxAttempts {
+ over := attempt.attempts - l.cfg.MaxAttempts
+ delay := l.cfg.BaseBackoff
+ for i := 1; i < over; i++ {
+ delay *= 2
+ if delay >= l.cfg.MaxBackoff {
+ delay = l.cfg.MaxBackoff
+ break
+ }
+ }
+ if delay > l.cfg.MaxBackoff {
+ delay = l.cfg.MaxBackoff
+ }
+ attempt.lockedUntil = now.Add(delay)
+ }
+}
+
+// keyForRequest returns a unique key for the given request.
+func (l *authRateLimiter) keyForRequest(r *http.Request) string {
+ return l.clientIP(r) + "|" + r.URL.Path
+}
+
+// clientIP returns the client IP address for the given request.
+func (l *authRateLimiter) clientIP(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
+}
diff --git a/backend/app/api/routes.go b/backend/app/api/routes.go
index 185338c0..c0d26b23 100644
--- a/backend/app/api/routes.go
+++ b/backend/app/api/routes.go
@@ -73,11 +73,11 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
}
r.Post("/users/register", chain.ToHandlerFunc(v1Ctrl.HandleUserRegistration()))
- r.Post("/users/login", chain.ToHandlerFunc(v1Ctrl.HandleAuthLogin(providers...)))
+ r.Post("/users/login", chain.ToHandlerFunc(v1Ctrl.HandleAuthLogin(providers...), a.mwAuthRateLimit))
if a.conf.OIDC.Enabled {
- r.Get("/users/login/oidc", chain.ToHandlerFunc(v1Ctrl.HandleOIDCLogin()))
- r.Get("/users/login/oidc/callback", chain.ToHandlerFunc(v1Ctrl.HandleOIDCCallback()))
+ r.Get("/users/login/oidc", chain.ToHandlerFunc(v1Ctrl.HandleOIDCLogin(), a.mwAuthRateLimit))
+ r.Get("/users/login/oidc/callback", chain.ToHandlerFunc(v1Ctrl.HandleOIDCCallback(), a.mwAuthRateLimit))
}
userMW := []errchain.Middleware{
diff --git a/backend/internal/sys/config/conf.go b/backend/internal/sys/config/conf.go
index 8d37570e..0b34fdcf 100644
--- a/backend/internal/sys/config/conf.go
+++ b/backend/internal/sys/config/conf.go
@@ -31,6 +31,7 @@ type Config struct {
LabelMaker LabelMakerConf `yaml:"labelmaker"`
Thumbnail Thumbnail `yaml:"thumbnail"`
Barcode BarcodeAPIConf `yaml:"barcode"`
+ Auth AuthConfig `yaml:"auth"`
}
type Options struct {
@@ -101,6 +102,18 @@ type BarcodeAPIConf struct {
TokenBarcodespider string `yaml:"token_barcodespider"`
}
+type AuthConfig struct {
+ RateLimit AuthRateLimit `yaml:"rate_limit"`
+}
+
+type AuthRateLimit struct {
+ Enabled bool `yaml:"enabled" conf:"default:true"`
+ Window time.Duration `yaml:"window" conf:"default:1m"`
+ MaxAttempts int `yaml:"max_attempts" conf:"default:5"`
+ BaseBackoff time.Duration `yaml:"base_backoff" conf:"default:10s"`
+ MaxBackoff time.Duration `yaml:"max_backoff" conf:"default:5m"`
+}
+
// New parses the CLI/Config file and returns a Config struct. If the file argument is an empty string, the
// file is not read. If the file is not empty, the file is read and the Config struct is returned.
func New(buildstr string, description string) (*Config, error) {
diff --git a/backend/internal/web/mid/security.go b/backend/internal/web/mid/security.go
new file mode 100644
index 00000000..0f196f5c
--- /dev/null
+++ b/backend/internal/web/mid/security.go
@@ -0,0 +1,36 @@
+package mid
+
+import (
+ "net/http"
+)
+
+// SecurityHeaders is a middleware that will set security headers on the response
+// It includes recommended headers from OWASP that are safe for self-hosted applications.
+// Reference: https://owasp.org/www-project-secure-headers/
+func SecurityHeaders() func(http.Handler) http.Handler {
+ return func(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Origin-Embedder-Policy", "require-corp")
+ w.Header().Set("Content-Origin-Opener-Policy", "same-origin")
+ w.Header().Set("Content-Origin-Resource-Policy", "same-site")
+ w.Header().Set("Permissions-Policy", "accelerometer=(), autoplay=(), camera=(self), cross-origin-isolated=(), display-capture=(), encrypted-media=(), fullscreen=(), geolocation=(), gyroscope=(), keyboard-map=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), screen-wake-lock=(), sync-xhr=(self), usb=(), web-share=(), xr-spatial-tracking=(), clipboard-read=(), clipboard-write=(self), gamepad=(), hid=(), idle-detection=(), interest-cohort=(), serial=(), unload=()")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("X-Frame-Options", "DENY")
+ w.Header().Set("X-Permitted-Cross-Domain-Policies", "none")
+ h.ServeHTTP(w, r)
+ })
+ }
+}
+
+// MaxBodySize is a middleware that limits the size of the request body.
+// If the request body exceeds the specified maxBytes, the middleware will
+// return a 413 Request Entity Too Large response.
+func MaxBodySize(maxBytes int64) func(http.Handler) http.Handler {
+ return func(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, maxBytes*1024*1024) // maxBytes in MB
+ h.ServeHTTP(w, r)
+ })
+ }
+}
diff --git a/backend/pkgs/hasher/password.go b/backend/pkgs/hasher/password.go
index 796cf201..7a10fb03 100644
--- a/backend/pkgs/hasher/password.go
+++ b/backend/pkgs/hasher/password.go
@@ -34,7 +34,13 @@ func init() { // nolint: gochecknoinits
disableHas := os.Getenv("UNSAFE_DISABLE_PASSWORD_PROJECTION") == "yes_i_am_sure"
if disableHas {
- fmt.Println("WARNING: Password protection is disabled. This is unsafe in production.")
+ // Print a big ol warning in red
+ fmt.Println("\\[\\033[0;31m\\]", "=======================================================================")
+ fmt.Println("\\[\\033[0;31m\\]", "WARNING: Password protection is disabled. This is unsafe in production.")
+ fmt.Println("\\[\\033[0;31m\\]", "You should never, ever use this in production. It is only for development and testing purposes.")
+ fmt.Println("\\[\\033[0;31m\\]", "DO NOT USE THIS IN PRODUCTION!")
+ fmt.Println("\\[\\033[0;31m\\]", "Remove UNSAFE_DISABLE_PASSWORD_PROJECTION to disable this warning.")
+ fmt.Println("\\[\\033[0;31m\\]", "=======================================================================")
enabled = false
}
}