Skip to content

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

chore: config redactions, stronger protections

Matthew Kilgoref51bae8bf41c
diff --git a/backend/app/api/demo.go b/backend/app/api/demo.go
index 5899b031..10208dec 100644
--- a/backend/app/api/demo.go
+++ b/backend/app/api/demo.go
@@ -3,6 +3,7 @@ package main
import (
"context"
"errors"
+ "os"
"strings"
"time"
@@ -11,6 +12,18 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
)
+const (
+ // demoPasswordEnv is the env var operators set when running demo mode in
+ // production, overriding the hardcoded development default below.
+ demoPasswordEnv = "HBOX_DEMO_PASSWORD"
+ // demoPasswordDefault is the password used when demo mode runs outside
+ // production. Public knowledge — never used unless cfg.Mode is development.
+ demoPasswordDefault = "demo"
+ // demoPasswordMinLength is the minimum acceptable length for a demo
+ // password supplied via demoPasswordEnv in production mode.
+ demoPasswordMinLength = 12
+)
+
func (a *app) SetupDemo() error {
csvText := `HB.import_ref,HB.location,HB.tags,HB.quantity,HB.name,HB.description,HB.insured,HB.serial_number,HB.model_number,HB.manufacturer,HB.notes,HB.purchase_from,HB.purchase_price,HB.purchase_date,HB.lifetime_warranty,HB.warranty_expires,HB.warranty_details,HB.sold_to,HB.sold_price,HB.sold_date,HB.sold_notes
,Garage,IOT;Home Assistant; Z-Wave,1,Zooz Universal Relay ZEN17,"Zooz 700 Series Z-Wave Universal Relay ZEN17 for Awnings, Garage Doors, Sprinklers, and More | 2 NO-C-NC Relays (20A, 10A) | Signal Repeater | Hub Required (Compatible with SmartThings and Hubitat)",,,ZEN17,Zooz,,Amazon,39.95,10/13/2021,,,,,,,
@@ -24,10 +37,15 @@ func (a *app) SetupDemo() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
+ demoPassword := os.Getenv(demoPasswordEnv)
+ if demoPassword == "" {
+ demoPassword = demoPasswordDefault
+ }
+
registration := services.UserRegistration{
Name: "Demo",
- Password: "demo",
+ Password: demoPassword,
}
// If demo user already exists, skip all demo seeding tasks
diff --git a/backend/app/api/handlers/v1/v1_ctrl_maint_entry.go b/backend/app/api/handlers/v1/v1_ctrl_maint_entry.go
index 1d027f3d..acccd1ba 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_maint_entry.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_maint_entry.go
@@ -42,7 +42,7 @@ func (ctrl *V1Controller) HandleMaintenanceLogGet() errchain.HandlerFunc {
func (ctrl *V1Controller) HandleMaintenanceEntryCreate() errchain.HandlerFunc {
fn := func(r *http.Request, itemID uuid.UUID, body repo.MaintenanceEntryCreate) (repo.MaintenanceEntry, error) {
auth := services.NewContext(r.Context())
- return ctrl.repo.MaintEntry.Create(auth, itemID, body)
+ return ctrl.repo.MaintEntry.Create(auth, auth.GID, itemID, body)
}
return adapters.ActionID("id", fn, http.StatusCreated)
diff --git a/backend/app/api/main.go b/backend/app/api/main.go
index d45cdf48..690a64b9 100644
--- a/backend/app/api/main.go
+++ b/backend/app/api/main.go
@@ -122,6 +122,19 @@ func run(cfg *config.Config) error {
}
hasher.SetAPIKeyPepper([]byte(cfg.Auth.APIKeyPepper))
+ // Demo mode seeds a known user ([email protected]). In production mode the
+ // hardcoded "demo" password would be publicly guessable, so require an
+ // explicit non-trivial HBOX_DEMO_PASSWORD before letting the app start.
+ if cfg.Demo && cfg.Mode == config.ModeProduction {
+ if len(os.Getenv(demoPasswordEnv)) < demoPasswordMinLength {
+ return fmt.Errorf(
+ "refusing to start: demo mode enabled in production but %s is unset or shorter than %d characters. "+
+ "Set %s to a strong password or disable demo mode (HBOX_DEMO=false)",
+ demoPasswordEnv, demoPasswordMinLength, demoPasswordEnv,
+ )
+ }
+ }
+
// =========================================================================
// Initialize OpenTelemetry
otelProvider, err := otel.NewProvider(context.Background(), &cfg.Otel, version)
diff --git a/backend/app/api/recurring.go b/backend/app/api/recurring.go
index 4e68b64d..7c7e2172 100644
--- a/backend/app/api/recurring.go
+++ b/backend/app/api/recurring.go
@@ -136,8 +136,14 @@ func registerRecurringTasks(app *app, cfg *config.Config, runner *graceful.Runne
if cfg.Debug.Enabled {
runner.AddFunc("debug", func(ctx context.Context) error {
+ // Bind to loopback only. pprof/expvar are unauthenticated and would
+ // otherwise expose heap snapshots, goroutine dumps, and runtime
+ // variables to anyone who can reach Web.Host (typically 0.0.0.0 in
+ // a container). Operators who need remote access should tunnel via
+ // SSH, e.g. `ssh -L 4000:127.0.0.1:4000 host`.
+ addr := fmt.Sprintf("127.0.0.1:%s", cfg.Debug.Port)
debugserver := http.Server{
- Addr: fmt.Sprintf("%s:%s", cfg.Web.Host, cfg.Debug.Port),
+ Addr: addr,
Handler: app.debugRouter(),
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
@@ -149,7 +155,7 @@ func registerRecurringTasks(app *app, cfg *config.Config, runner *graceful.Runne
_ = debugserver.Shutdown(context.Background())
}()
- log.Info().Msgf("Debug server is running on %s:%s", cfg.Web.Host, cfg.Debug.Port)
+ log.Info().Msgf("Debug server is running on %s (loopback only)", addr)
return debugserver.ListenAndServe()
})
// Print the configuration to the console
diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.go
index 53042ff3..257994b3 100644
--- a/backend/internal/core/services/service_user.go
+++ b/backend/internal/core/services/service_user.go
@@ -25,8 +25,14 @@ var (
ErrorInvalidToken = errors.New("invalid token")
ErrorMailerNotConfigured = errors.New("password reset by email is unavailable: SMTP is not configured")
ErrorPasswordResetInvalid = errors.New("password reset link is invalid or has expired")
+ ErrorPasswordTooShort = fmt.Errorf("password must be at least %d characters", PasswordMinLength)
)
+// PasswordMinLength is the minimum length enforced server-side for any flow
+// that sets a user password (registration, reset, change). Matches the value
+// already documented by the password reset handler's OpenAPI spec.
+const PasswordMinLength = 6
+
type UserService struct {
repos *repo.AllRepos
mailer *mailer.Mailer
@@ -62,10 +68,20 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
))
defer span.End()
+ // Reject too-short (and empty) passwords before any DB work. The reset and
+ // change-password flows enforce the same floor; registration was the gap.
+ if len(data.Password) < PasswordMinLength {
+ span.SetAttributes(attribute.String("registration.outcome", "password_too_short"))
+ return repo.UserOut{}, ErrorPasswordTooShort
+ }
+
+ // Don't log the raw invitation token — it's a single-use credential that
+ // grants group membership and is replayable from log aggregators until it
+ // expires. The boolean is enough for diagnostics.
log.Debug().
Str("name", data.Name).
Str("email", data.Email).
- Str("groupToken", data.GroupToken).
+ Bool("hasGroupToken", data.GroupToken != "").
Msg("Registering new user")
var (
@@ -585,8 +601,20 @@ func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthT
out, err := svc.createSessionToken(ctx, dbToken.ID, false)
if err != nil {
recordServiceSpanError(span, err)
+ return out, err
}
- return out, err
+
+ // Invalidate the just-rotated token so a leaked refresh request can't
+ // continue to authenticate alongside the freshly issued one. Done after
+ // createSessionToken succeeds — order matters: if the delete ran first and
+ // the new-token issuance failed, the caller would be logged out instead of
+ // just missing a refresh. Delete failures are non-fatal: the new token is
+ // already valid, and the old hash will expire on its own.
+ if delErr := svc.repos.AuthTokens.DeleteToken(ctx, hash); delErr != nil {
+ recordServiceSpanError(span, delErr)
+ log.Warn().Err(delErr).Msg("RenewToken: failed to delete prior session token")
+ }
+ return out, nil
}
// DeleteSelf deletes the user that is currently logged based of the provided UUID
@@ -643,6 +671,29 @@ func (svc *UserService) ChangePassword(ctx Context, current string, new string)
return false
}
+ // Revoke every other session for this user. The current request's token
+ // is preserved so the caller stays logged in; every other device, browser,
+ // or stolen cookie is invalidated atomically with the password change.
+ // If the request was authed via API key (no session token in context),
+ // fall back to a full revoke — there's nothing to preserve.
+ currentRaw := UseTokenCtx(ctx.Context)
+ var revokeErr error
+ var revoked int
+ if currentRaw != "" {
+ revoked, revokeErr = svc.repos.AuthTokens.DeleteAllByUserExceptToken(ctx.Context, ctx.UID, hasher.HashToken(currentRaw))
+ } else {
+ revoked, revokeErr = svc.repos.AuthTokens.DeleteAllByUser(ctx.Context, ctx.UID)
+ }
+ if revokeErr != nil {
+ // The password is already changed — surface the partial-success state
+ // in telemetry but still return success to the caller. The caller's
+ // password is updated; other sessions will expire on their own.
+ recordServiceSpanError(span, revokeErr)
+ span.SetAttributes(attribute.String("change_password.outcome", "revoke_failed"))
+ log.Warn().Err(revokeErr).Msg("password changed but failed to revoke other sessions")
+ }
+ span.SetAttributes(attribute.Int("change_password.sessions_revoked", revoked))
+
span.SetAttributes(attribute.String("change_password.outcome", "success"))
return true
}
diff --git a/backend/internal/core/services/service_user_session_test.go b/backend/internal/core/services/service_user_session_test.go
new file mode 100644
index 00000000..ae2cf5e2
--- /dev/null
+++ b/backend/internal/core/services/service_user_session_test.go
@@ -0,0 +1,147 @@
+package services
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/authroles"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher"
+)
+
+// countUserSessions counts user-role auth tokens for uid. createSessionToken
+// issues two rows per session (user + attachment); for session-revocation
+// assertions we only care about the user-role rows since they're the bearer
+// principal everywhere except the attachment download URL.
+func countUserSessions(t *testing.T, ctx context.Context, uid uuid.UUID) int {
+ t.Helper()
+ c, err := tClient.AuthTokens.Query().
+ Where(
+ authtokens.HasUserWith(user.ID(uid)),
+ authtokens.HasRolesWith(authroles.RoleEQ(authroles.RoleUser)),
+ ).
+ Count(ctx)
+ require.NoError(t, err)
+ return c
+}
+
+// M1: RenewToken must invalidate the token it rotated, leaving only the new
+// one valid afterward. Without this guarantee a leaked refresh request keeps
+// the prior bearer alive in parallel with its replacement.
+func TestRenewToken_InvalidatesPriorToken(t *testing.T) {
+ ctx := context.Background()
+ usr := newTestUserWithPassword(t, "renew-pw-1")
+
+ old, err := tSvc.User.createSessionToken(ctx, usr.ID, false)
+ require.NoError(t, err)
+ require.Equal(t, 1, countUserSessions(t, ctx, usr.ID))
+
+ renewed, err := tSvc.User.RenewToken(ctx, old.Raw)
+ require.NoError(t, err)
+ assert.NotEqual(t, old.Raw, renewed.Raw, "RenewToken should mint a fresh raw token")
+
+ // Exactly one session token remains, and it's the new one.
+ assert.Equal(t, 1, countUserSessions(t, ctx, usr.ID), "old token should be revoked")
+
+ // The new token authenticates.
+ _, err = tRepos.AuthTokens.GetUserFromToken(ctx, hasher.HashToken(renewed.Raw))
+ assert.NoError(t, err)
+
+ // The old token does NOT authenticate.
+ _, err = tRepos.AuthTokens.GetUserFromToken(ctx, hasher.HashToken(old.Raw))
+ require.Error(t, err)
+}
+
+// M2: ChangePassword must revoke every session for the user except the one
+// making the request. Other devices / stolen cookies are killed atomically
+// with the password change; the caller stays logged in.
+func TestChangePassword_RevokesOtherSessions_KeepsCurrent(t *testing.T) {
+ ctx := context.Background()
+ usr := newTestUserWithPassword(t, "old-cp-pw")
+
+ current, err := tSvc.User.createSessionToken(ctx, usr.ID, false)
+ require.NoError(t, err)
+ _, err = tSvc.User.createSessionToken(ctx, usr.ID, false)
+ require.NoError(t, err)
+ _, err = tSvc.User.createSessionToken(ctx, usr.ID, false)
+ require.NoError(t, err)
+ require.Equal(t, 3, countUserSessions(t, ctx, usr.ID))
+
+ // Mark the request context as authed via the "current" session token so
+ // ChangePassword preserves it.
+ reqCtx := SetUserCtx(ctx, &usr, current.Raw)
+ svcCtx := Context{Context: reqCtx, UID: usr.ID, GID: usr.DefaultGroupID, User: &usr}
+
+ ok := tSvc.User.ChangePassword(svcCtx, "old-cp-pw", "new-cp-pw")
+ require.True(t, ok, "ChangePassword should succeed with correct current password")
+
+ // Only the current session survives.
+ assert.Equal(t, 1, countUserSessions(t, ctx, usr.ID), "exactly one session (current) should remain")
+
+ // Current token still authenticates.
+ _, err = tRepos.AuthTokens.GetUserFromToken(ctx, hasher.HashToken(current.Raw))
+ assert.NoError(t, err, "current session must remain valid")
+
+ // Login works with the new password and not the old.
+ _, err = tSvc.User.Login(ctx, usr.Email, "new-cp-pw", false)
+ require.NoError(t, err)
+ _, err = tSvc.User.Login(ctx, usr.Email, "old-cp-pw", false)
+ require.ErrorIs(t, err, ErrorInvalidLogin)
+}
+
+// M2 fallback: when there's no session token in context (e.g. API-key auth),
+// ChangePassword must still revoke every session token — nothing to preserve.
+func TestChangePassword_NoSessionToken_RevokesAll(t *testing.T) {
+ ctx := context.Background()
+ usr := newTestUserWithPassword(t, "no-sess-pw")
+
+ _, err := tSvc.User.createSessionToken(ctx, usr.ID, false)
+ require.NoError(t, err)
+ _, err = tSvc.User.createSessionToken(ctx, usr.ID, false)
+ require.NoError(t, err)
+ require.Equal(t, 2, countUserSessions(t, ctx, usr.ID))
+
+ svcCtx := Context{Context: ctx, UID: usr.ID, GID: usr.DefaultGroupID, User: &usr}
+
+ ok := tSvc.User.ChangePassword(svcCtx, "no-sess-pw", "no-sess-pw-new")
+ require.True(t, ok)
+
+ assert.Equal(t, 0, countUserSessions(t, ctx, usr.ID), "all sessions should be revoked when no current session is in context")
+}
+
+// M4: RegisterUser must reject passwords shorter than PasswordMinLength.
+func TestRegisterUser_RejectsShortPassword(t *testing.T) {
+ ctx := context.Background()
+ short := strings.Repeat("a", PasswordMinLength-1)
+
+ _, err := tSvc.User.RegisterUser(ctx, UserRegistration{
+ Name: "Short Pwd User",
+ Email: fk.Email(),
+ Password: short,
+ })
+ require.ErrorIs(t, err, ErrorPasswordTooShort)
+}
+
+func TestRegisterUser_RejectsEmptyPassword(t *testing.T) {
+ _, err := tSvc.User.RegisterUser(context.Background(), UserRegistration{
+ Name: "Empty Pwd User",
+ Email: fk.Email(),
+ Password: "",
+ })
+ require.ErrorIs(t, err, ErrorPasswordTooShort)
+}
+
+func TestRegisterUser_AcceptsMinLengthPassword(t *testing.T) {
+ usr, err := tSvc.User.RegisterUser(context.Background(), UserRegistration{
+ Name: "Min Pwd User",
+ Email: fk.Email(),
+ Password: strings.Repeat("a", PasswordMinLength),
+ })
+ require.NoError(t, err)
+ assert.NotEqual(t, uuid.Nil, usr.ID)
+}
diff --git a/backend/internal/data/repo/repo_authz.go b/backend/internal/data/repo/repo_authz.go
new file mode 100644
index 00000000..591f3f02
--- /dev/null
+++ b/backend/internal/data/repo/repo_authz.go
@@ -0,0 +1,111 @@
+package repo
+
+import (
+ "context"
+
+ "github.com/google/uuid"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/entity"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/entitytemplate"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/entitytype"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag"
+)
+
+// dedupNonNil returns the unique non-zero IDs in ids, preserving order. It is
+// used by the assert* helpers so callers don't need to filter inputs before
+// asking whether a set of UUIDs is reachable inside a tenant group.
+func dedupNonNil(ids []uuid.UUID) []uuid.UUID {
+ if len(ids) == 0 {
+ return nil
+ }
+ seen := make(map[uuid.UUID]struct{}, len(ids))
+ out := make([]uuid.UUID, 0, len(ids))
+ for _, id := range ids {
+ if id == uuid.Nil {
+ continue
+ }
+ if _, ok := seen[id]; ok {
+ continue
+ }
+ seen[id] = struct{}{}
+ out = append(out, id)
+ }
+ return out
+}
+
+// assertEntityInGroup returns an ent.NotFoundError when id is set but does not
+// resolve to an entity inside gid. A zero id is a no-op so callers can pass
+// optional ParentID / DefaultLocationID values unconditionally. Returning the
+// not-found error (rather than a distinct sentinel) preserves existing 404
+// handling at the API edge and avoids leaking cross-tenant existence.
+func assertEntityInGroup(ctx context.Context, c *ent.EntityClient, gid, id uuid.UUID) error {
+ if id == uuid.Nil {
+ return nil
+ }
+ exists, err := c.Query().
+ Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).
+ Exist(ctx)
+ if err != nil {
+ return err
+ }
+ if !exists {
+ return &ent.NotFoundError{}
+ }
+ return nil
+}
+
+// assertEntityTypeInGroup is the EntityType analog of assertEntityInGroup.
+func assertEntityTypeInGroup(ctx context.Context, c *ent.EntityTypeClient, gid, id uuid.UUID) error {
+ if id == uuid.Nil {
+ return nil
+ }
+ exists, err := c.Query().
+ Where(entitytype.ID(id), entitytype.HasGroupWith(group.ID(gid))).
+ Exist(ctx)
+ if err != nil {
+ return err
+ }
+ if !exists {
+ return &ent.NotFoundError{}
+ }
+ return nil
+}
+
+// assertEntityTemplateInGroup is the EntityTemplate analog. id may be the zero
+// UUID (no-op).
+func assertEntityTemplateInGroup(ctx context.Context, c *ent.EntityTemplateClient, gid, id uuid.UUID) error {
+ if id == uuid.Nil {
+ return nil
+ }
+ exists, err := c.Query().
+ Where(entitytemplate.ID(id), entitytemplate.HasGroupWith(group.ID(gid))).
+ Exist(ctx)
+ if err != nil {
+ return err
+ }
+ if !exists {
+ return &ent.NotFoundError{}
+ }
+ return nil
+}
+
+// assertTagsInGroup verifies that every supplied tag id belongs to gid.
+// Duplicate and zero ids are tolerated. The count comparison after Where(IDIn)
+// catches both "tag does not exist" and "tag exists in another group".
+func assertTagsInGroup(ctx context.Context, c *ent.TagClient, gid uuid.UUID, ids []uuid.UUID) error {
+ cleaned := dedupNonNil(ids)
+ if len(cleaned) == 0 {
+ return nil
+ }
+ count, err := c.Query().
+ Where(tag.IDIn(cleaned...), tag.HasGroupWith(group.ID(gid))).
+ Count(ctx)
+ if err != nil {
+ return err
+ }
+ if count != len(cleaned) {
+ return &ent.NotFoundError{}
+ }
+ return nil
+}
diff --git a/backend/internal/data/repo/repo_authz_test.go b/backend/internal/data/repo/repo_authz_test.go
new file mode 100644
index 00000000..a4583410
--- /dev/null
+++ b/backend/internal/data/repo/repo_authz_test.go
@@ -0,0 +1,150 @@
+package repo
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/ent"
+ "github.com/sysadminsmedia/homebox/backend/internal/data/types"
+)
+
+func nowDate() types.Date {
+ return types.DateFromTime(time.Now())
+}
+
+// makeForeignGroup creates a second tenant group with its own item entity type
+// and tag, returning the group ID, a tag ID, and an entity type ID that all
+// belong to that foreign group. Callers use these IDs to assert that the
+// primary tGroup write paths refuse to attach foreign-tenant references.
+func makeForeignGroup(t *testing.T) (gid uuid.UUID, foreignTagID uuid.UUID, foreignTypeID uuid.UUID) {
+ t.Helper()
+ ctx := context.Background()
+
+ other, err := tRepos.Groups.GroupCreate(ctx, "authz-foreign-"+uuid.NewString(), uuid.Nil)
+ require.NoError(t, err)
+
+ otherType, err := tRepos.EntityTypes.GetDefault(ctx, other.ID, false)
+ require.NoError(t, err)
+
+ otherTag, err := tRepos.Tags.Create(ctx, other.ID, TagCreate{Name: "foreign-tag-" + uuid.NewString()})
+ require.NoError(t, err)
+
+ return other.ID, otherTag.ID, otherType.ID
+}
+
+func Test_EntityCreate_RejectsForeignParent(t *testing.T) {
+ itemET := useItemEntityType(t)
+
+ foreignGID, _, foreignTypeID := makeForeignGroup(t)
+ foreignParent, err := tRepos.Entities.Create(context.Background(), foreignGID, EntityCreate{
+ Name: "foreign-parent",
+ EntityTypeID: foreignTypeID,
+ })
+ require.NoError(t, err)
+
+ _, err = tRepos.Entities.Create(context.Background(), tGroup.ID, EntityCreate{
+ Name: "victim",
+ EntityTypeID: itemET.ID,
+ ParentID: foreignParent.ID,
+ })
+ require.Error(t, err)
+ assert.True(t, ent.IsNotFound(err), "expected NotFound for cross-group ParentID, got %T: %v", err, err)
+}
+
+func Test_EntityCreate_RejectsForeignEntityType(t *testing.T) {
+ _, _, foreignTypeID := makeForeignGroup(t)
+
+ _, err := tRepos.Entities.Create(context.Background(), tGroup.ID, EntityCreate{
+ Name: "victim",
+ EntityTypeID: foreignTypeID,
+ })
+ require.Error(t, err)
+ assert.True(t, ent.IsNotFound(err), "expected NotFound for cross-group EntityTypeID, got %T: %v", err, err)
+}
+
+func Test_EntityCreate_RejectsForeignTag(t *testing.T) {
+ itemET := useItemEntityType(t)
+ _, foreignTagID, _ := makeForeignGroup(t)
+
+ _, err := tRepos.Entities.Create(context.Background(), tGroup.ID, EntityCreate{
+ Name: "victim",
+ EntityTypeID: itemET.ID,
+ TagIDs: []uuid.UUID{foreignTagID},
+ })
+ require.Error(t, err)
+ assert.True(t, ent.IsNotFound(err), "expected NotFound for cross-group TagIDs, got %T: %v", err, err)
+}
+
+func Test_EntityPatch_RejectsForeignTag(t *testing.T) {
+ itemET := useItemEntityType(t)
+ _, foreignTagID, _ := makeForeignGroup(t)
+
+ // Create a victim entity inside tGroup first.
+ victim, err := tRepos.Entities.Create(context.Background(), tGroup.ID, EntityCreate{
+ Name: "victim-patch",
+ EntityTypeID: itemET.ID,
+ })
+ require.NoError(t, err)
+
+ err = tRepos.Entities.Patch(context.Background(), tGroup.ID, victim.ID, EntityPatch{
+ TagIDs: []uuid.UUID{foreignTagID},
+ })
+ require.Error(t, err)
+ assert.True(t, ent.IsNotFound(err), "expected NotFound for cross-group tag in Patch, got %T: %v", err, err)
+}
+
+func Test_MaintEntryCreate_RejectsForeignItem(t *testing.T) {
+ itemET := useItemEntityType(t)
+ foreignGID, _, _ := makeForeignGroup(t)
+ foreignType, err := tRepos.EntityTypes.GetDefault(context.Background(), foreignGID, false)
+ require.NoError(t, err)
+
+ foreignItem, err := tRepos.Entities.Create(context.Background(), foreignGID, EntityCreate{
+ Name: "foreign-item",
+ EntityTypeID: foreignType.ID,
+ })
+ require.NoError(t, err)
+
+ // Caller is in tGroup but supplies a foreign item ID — must be rejected
+ // before any maintenance row is written against B's item.
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, foreignItem.ID, MaintenanceEntryCreate{
+ CompletedDate: nowDate(),
+ Name: "should-be-rejected",
+ })
+ require.Error(t, err)
+ assert.True(t, ent.IsNotFound(err), "expected NotFound for cross-group MaintEntry.Create, got %T: %v", err, err)
+
+ // Confirm the legitimate tGroup item path still works.
+ ownItem, err := tRepos.Entities.Create(context.Background(), tGroup.ID, EntityCreate{
+ Name: "own-item",
+ EntityTypeID: itemET.ID,
+ })
+ require.NoError(t, err)
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, ownItem.ID, MaintenanceEntryCreate{
+ CompletedDate: nowDate(),
+ Name: "legit",
+ })
+ require.NoError(t, err)
+}
+
+func Test_EntityTemplateCreate_RejectsForeignDefaultLocation(t *testing.T) {
+ foreignGID, _, _ := makeForeignGroup(t)
+ foreignContainerType, err := tRepos.EntityTypes.GetDefault(context.Background(), foreignGID, true)
+ require.NoError(t, err)
+ foreignLoc, err := tRepos.Entities.Create(context.Background(), foreignGID, EntityCreate{
+ Name: "foreign-loc",
+ EntityTypeID: foreignContainerType.ID,
+ })
+ require.NoError(t, err)
+
+ _, err = tRepos.EntityTemplates.Create(context.Background(), tGroup.ID, EntityTemplateCreate{
+ Name: "victim-template",
+ DefaultLocationID: foreignLoc.ID,
+ })
+ require.Error(t, err)
+ assert.True(t, ent.IsNotFound(err), "expected NotFound for cross-group DefaultLocationID, got %T: %v", err, err)
+}
diff --git a/backend/internal/data/repo/repo_entities.go b/backend/internal/data/repo/repo_entities.go
index b9f88973..64e8feb4 100644
--- a/backend/internal/data/repo/repo_entities.go
+++ b/backend/internal/data/repo/repo_entities.go
@@ -993,6 +993,23 @@ func (r *EntityRepository) Create(ctx context.Context, gid uuid.UUID, data Entit
return EntityOut{}, err
}
+ // Reject cross-group UUIDs in the request body before any write hits the DB.
+ // Without these checks, an authenticated caller in group A could reparent
+ // onto group B's location, attach group B's tags, or set a group B
+ // entity type — corrupting tenant trees and confirming cross-group UUIDs.
+ if err := assertEntityInGroup(ctx, r.db.Entity, gid, data.ParentID); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+ if err := assertEntityTypeInGroup(ctx, r.db.EntityType, gid, data.EntityTypeID); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+ if err := assertTagsInGroup(ctx, r.db.Tag, gid, data.TagIDs); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+
q := r.db.Entity.Create().
SetImportRef(data.ImportRef).
SetName(data.Name).
@@ -1069,6 +1086,21 @@ func (r *EntityRepository) CreateFromTemplate(ctx context.Context, gid uuid.UUID
return EntityOut{}, err
}
+ // Same group-ownership checks as Create. Done before opening the tx so a
+ // rejected request doesn't leave a dangling transaction.
+ if err := assertEntityInGroup(ctx, r.db.Entity, gid, data.ParentID); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+ if err := assertEntityTypeInGroup(ctx, r.db.EntityType, gid, data.EntityTypeID); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+ if err := assertTagsInGroup(ctx, r.db.Tag, gid, data.TagIDs); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+
tx, err := r.db.Tx(ctx)
if err != nil {
recordSpanError(span, err)
@@ -1422,6 +1454,22 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, dat
return EntityOut{}, err
}
+ // See EntityRepository.Create for the rationale on these cross-group
+ // reference checks. Applied before the update so a rejected request never
+ // mutates the row.
+ if err := assertEntityInGroup(ctx, r.db.Entity, gid, data.ParentID); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+ if err := assertEntityTypeInGroup(ctx, r.db.EntityType, gid, data.EntityTypeID); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+ if err := assertTagsInGroup(ctx, r.db.Tag, gid, data.TagIDs); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+
q := r.db.Entity.Update().Where(entity.ID(data.ID), entity.HasGroupWith(group.ID(gid))).
SetName(data.Name).
SetDescription(data.Description).
@@ -1668,6 +1716,25 @@ func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data En
))
defer span.End()
+ // See EntityRepository.Create for the rationale on these cross-group
+ // reference checks. data.TagIDs == nil means "leave tags alone"; a non-nil
+ // (possibly empty) slice means "set tags to this exact list", and only the
+ // latter needs validation.
+ if err := assertEntityInGroup(ctx, r.db.Entity, gid, data.ParentID); err != nil {
+ recordSpanError(span, err)
+ return err
+ }
+ if err := assertEntityTypeInGroup(ctx, r.db.EntityType, gid, data.EntityTypeID); err != nil {
+ recordSpanError(span, err)
+ return err
+ }
+ if data.TagIDs != nil {
+ if err := assertTagsInGroup(ctx, r.db.Tag, gid, data.TagIDs); err != nil {
+ recordSpanError(span, err)
+ return err
+ }
+ }
+
tx, err := r.db.Tx(ctx)
if err != nil {
recordSpanError(span, err)
@@ -2402,8 +2469,11 @@ func (r *EntityRepository) CreateContainer(ctx context.Context, gid uuid.UUID, d
if data.ParentID != uuid.Nil {
validateCtx, validateSpan := entityTracer().Start(ctx, "repo.EntityRepository.CreateContainer.validateParent")
+ // HasGroupWith filter scopes the parent lookup to this tenant — without
+ // it a caller could reparent under another group's location and surface
+ // it back via the "parent not found" branch as an existence oracle.
parentEntity, err := r.db.Entity.Query().
- Where(entity.ID(data.ParentID)).
+ Where(entity.ID(data.ParentID), entity.HasGroupWith(group.ID(gid))).
WithEntityType().
Only(validateCtx)
if err != nil {
@@ -2423,6 +2493,11 @@ func (r *EntityRepository) CreateContainer(ctx context.Context, gid uuid.UUID, d
validateSpan.End()
}
+ if err := assertEntityTypeInGroup(ctx, r.db.EntityType, gid, data.EntityTypeID); err != nil {
+ recordSpanError(span, err)
+ return EntityOut{}, err
+ }
+
q := r.db.Entity.Create().
SetName(data.Name).
SetDescription(data.Description).
@@ -2469,8 +2544,9 @@ func (r *EntityRepository) UpdateContainer(ctx context.Context, gid, id uuid.UUI
if data.ParentID != uuid.Nil {
validateCtx, validateSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateContainer.validateParent")
+ // Same tenant-scope reasoning as CreateContainer above.
parentEntity, err := r.db.Entity.Query().
- Where(entity.ID(data.ParentID)).
+ Where(entity.ID(data.ParentID), entity.HasGroupWith(group.ID(gid))).
WithEntityType().
Only(validateCtx)
if err != nil {
diff --git a/backend/internal/data/repo/repo_entities_test.go b/backend/internal/data/repo/repo_entities_test.go
index 5604acdc..3f8d2221 100644
--- a/backend/internal/data/repo/repo_entities_test.go
+++ b/backend/internal/data/repo/repo_entities_test.go
@@ -628,7 +628,7 @@ func TestEntityRepository_WipeInventory(t *testing.T) {
require.NoError(t, err)
// Create maintenance entries
- _, err = tRepos.MaintEntry.Create(context.Background(), entity1.ID, MaintenanceEntryCreate{
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, entity1.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Test Maintenance 1",
Description: "Test maintenance entry",
@@ -636,7 +636,7 @@ func TestEntityRepository_WipeInventory(t *testing.T) {
})
require.NoError(t, err)
- _, err = tRepos.MaintEntry.Create(context.Background(), entity2.ID, MaintenanceEntryCreate{
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, entity2.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Test Maintenance 2",
Description: "Another test maintenance entry",
@@ -702,7 +702,7 @@ func TestEntityRepository_WipeInventory_OnlyItems(t *testing.T) {
e, err := tRepos.Entities.Create(context.Background(), tGroup.ID, ef)
require.NoError(t, err)
- _, err = tRepos.MaintEntry.Create(context.Background(), e.ID, MaintenanceEntryCreate{
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, e.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Test Maintenance",
Description: "Test maintenance entry",
diff --git a/backend/internal/data/repo/repo_entity_templates.go b/backend/internal/data/repo/repo_entity_templates.go
index aa5e8ffd..2c9268b3 100644
--- a/backend/internal/data/repo/repo_entity_templates.go
+++ b/backend/internal/data/repo/repo_entity_templates.go
@@ -265,6 +265,10 @@ func (r *EntityTemplatesRepository) GetOne(ctx context.Context, gid uuid.UUID, i
// Create creates a new template
func (r *EntityTemplatesRepository) Create(ctx context.Context, gid uuid.UUID, data EntityTemplateCreate) (EntityTemplateOut, error) {
+ if err := assertEntityInGroup(ctx, r.db.Entity, gid, data.DefaultLocationID); err != nil {
+ return EntityTemplateOut{}, err
+ }
+
q := r.db.EntityTemplate.Create().
SetName(data.Name).
SetDescription(data.Description).
@@ -315,6 +319,10 @@ func (r *EntityTemplatesRepository) Create(ctx context.Context, gid uuid.UUID, d
// Update updates an existing template
func (r *EntityTemplatesRepository) Update(ctx context.Context, gid uuid.UUID, data EntityTemplateUpdate) (EntityTemplateOut, error) {
+ if err := assertEntityInGroup(ctx, r.db.Entity, gid, data.DefaultLocationID); err != nil {
+ return EntityTemplateOut{}, err
+ }
+
// Verify template belongs to group
template, err := r.db.EntityTemplate.Query().
Where(
diff --git a/backend/internal/data/repo/repo_entity_types.go b/backend/internal/data/repo/repo_entity_types.go
index a78ea716..74972394 100644
--- a/backend/internal/data/repo/repo_entity_types.go
+++ b/backend/internal/data/repo/repo_entity_types.go
@@ -98,6 +98,12 @@ func (r *EntityTypeRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]Ent
// Create creates a new entity type for a group.
func (r *EntityTypeRepository) Create(ctx context.Context, gid uuid.UUID, data EntityTypeCreate) (EntityTypeSummary, error) {
+ if data.DefaultTemplateID != nil {
+ if err := assertEntityTemplateInGroup(ctx, r.db.EntityTemplate, gid, *data.DefaultTemplateID); err != nil {
+ return EntityTypeSummary{}, err
+ }
+ }
+
q := r.db.EntityType.Create().
SetName(data.Name).
SetIsLocation(data.IsLocation).
@@ -119,6 +125,12 @@ func (r *EntityTypeRepository) Create(ctx context.Context, gid uuid.UUID, data E
// Update updates an existing entity type.
func (r *EntityTypeRepository) Update(ctx context.Context, gid uuid.UUID, data EntityTypeUpdate) (EntityTypeSummary, error) {
+ if data.DefaultTemplateID != nil {
+ if err := assertEntityTemplateInGroup(ctx, r.db.EntityTemplate, gid, *data.DefaultTemplateID); err != nil {
+ return EntityTypeSummary{}, err
+ }
+ }
+
q := r.db.EntityType.Update().
Where(
entitytype.ID(data.ID),
diff --git a/backend/internal/data/repo/repo_maintenance_entry.go b/backend/internal/data/repo/repo_maintenance_entry.go
index 26630130..930d9ba2 100644
--- a/backend/internal/data/repo/repo_maintenance_entry.go
+++ b/backend/internal/data/repo/repo_maintenance_entry.go
@@ -99,7 +99,21 @@ func (r *MaintenanceEntryRepository) GetScheduled(ctx context.Context, gid uuid.
return mapEachMaintenanceEntry(entries), nil
}
-func (r *MaintenanceEntryRepository) Create(ctx context.Context, itemID uuid.UUID, input MaintenanceEntryCreate) (MaintenanceEntry, error) {
+func (r *MaintenanceEntryRepository) Create(ctx context.Context, gid, itemID uuid.UUID, input MaintenanceEntryCreate) (MaintenanceEntry, error) {
+ // Verify the target item belongs to the caller's group before creating an
+ // entry against it. Without this check, a caller in group A could POST a
+ // maintenance entry to any item UUID guessed in group B; the entry would
+ // then surface in B's maintenance log with no audit trail.
+ owned, err := r.db.Entity.Query().
+ Where(entity.ID(itemID), entity.HasGroupWith(group.ID(gid))).
+ Exist(ctx)
+ if err != nil {
+ return MaintenanceEntry{}, err
+ }
+ if !owned {
+ return MaintenanceEntry{}, &ent.NotFoundError{}
+ }
+
item, err := r.db.MaintenanceEntry.Create().
SetEntityID(itemID).
SetDate(input.CompletedDate.Time()).
diff --git a/backend/internal/data/repo/repo_maintenance_entry_test.go b/backend/internal/data/repo/repo_maintenance_entry_test.go
index 71302a80..7f1ff739 100644
--- a/backend/internal/data/repo/repo_maintenance_entry_test.go
+++ b/backend/internal/data/repo/repo_maintenance_entry_test.go
@@ -61,7 +61,7 @@ func TestMaintenanceEntryRepository_GetLog(t *testing.T) {
}
for _, entry := range created {
- _, err := tRepos.MaintEntry.Create(context.Background(), item.ID, entry)
+ _, err := tRepos.MaintEntry.Create(context.Background(), tGroup.ID, item.ID, entry)
if err != nil {
t.Fatalf("failed to create maintenance entry: %v", err)
}
diff --git a/backend/internal/data/repo/repo_tokens.go b/backend/internal/data/repo/repo_tokens.go
index 1b22eae8..66bac6b4 100644
--- a/backend/internal/data/repo/repo_tokens.go
+++ b/backend/internal/data/repo/repo_tokens.go
@@ -164,6 +164,29 @@ func (r *TokenRepository) DeleteAllByUser(ctx context.Context, userID uuid.UUID)
return deleted, nil
}
+// DeleteAllByUserExceptToken revokes every session token for userID except the
+// one identified by exceptHash. Used by the self-service ChangePassword flow
+// so the caller's current session keeps working while every other session
+// (laptop, phone, attacker-held cookie) is invalidated immediately.
+func (r *TokenRepository) DeleteAllByUserExceptToken(ctx context.Context, userID uuid.UUID, exceptHash []byte) (int, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.DeleteAllByUserExceptToken",
+ trace.WithAttributes(attribute.String("user.id", userID.String())))
+ defer span.End()
+
+ deleted, err := r.db.AuthTokens.Delete().
+ Where(
+ authtokens.HasUserWith(user.ID(userID)),
+ authtokens.TokenNEQ(exceptHash),
+ ).
+ Exec(ctx)
+ if err != nil {
+ recordSpanError(span, err)
+ return 0, err
+ }
+ span.SetAttributes(attribute.Int("tokens.deleted.count", deleted))
+ return deleted, nil
+}
+
// DeleteToken remove a single token from the database - equivalent to revoke or logout
func (r *TokenRepository) DeleteToken(ctx context.Context, token []byte) error {
ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.DeleteToken",
diff --git a/backend/internal/data/repo/repo_wipe_integration_test.go b/backend/internal/data/repo/repo_wipe_integration_test.go
index 7fbbe462..9642ce73 100644
--- a/backend/internal/data/repo/repo_wipe_integration_test.go
+++ b/backend/internal/data/repo/repo_wipe_integration_test.go
@@ -75,7 +75,7 @@ func TestWipeInventory_Integration(t *testing.T) {
require.NoError(t, err)
// 4. Create maintenance entries
- _, err = tRepos.MaintEntry.Create(context.Background(), entity1.ID, MaintenanceEntryCreate{
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, entity1.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Laptop cleaning",
Description: "Cleaned keyboard and screen",
@@ -83,7 +83,7 @@ func TestWipeInventory_Integration(t *testing.T) {
})
require.NoError(t, err)
- _, err = tRepos.MaintEntry.Create(context.Background(), entity2.ID, MaintenanceEntryCreate{
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, entity2.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Drill maintenance",
Description: "Oiled motor",
@@ -91,7 +91,7 @@ func TestWipeInventory_Integration(t *testing.T) {
})
require.NoError(t, err)
- _, err = tRepos.MaintEntry.Create(context.Background(), entity3.ID, MaintenanceEntryCreate{
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, entity3.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "Monitor calibration",
Description: "Color calibration",
@@ -164,7 +164,7 @@ func TestWipeInventory_SelectiveWipe(t *testing.T) {
})
require.NoError(t, err)
- _, err = tRepos.MaintEntry.Create(context.Background(), e.ID, MaintenanceEntryCreate{
+ _, err = tRepos.MaintEntry.Create(context.Background(), tGroup.ID, e.ID, MaintenanceEntryCreate{
CompletedDate: types.DateFromTime(time.Now()),
Name: "System update",
Description: "OS update",
diff --git a/backend/internal/sys/config/conf.go b/backend/internal/sys/config/conf.go
index 8b75035d..7567c5c0 100644
--- a/backend/internal/sys/config/conf.go
+++ b/backend/internal/sys/config/conf.go
@@ -5,12 +5,40 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net/url"
"os"
"time"
"github.com/ardanlabs/conf/v3"
)
+// redactedValue is the sentinel substituted for any sensitive field when the
+// configuration is serialized (e.g. via Print). It must not match any plausible
+// real value.
+const redactedValue = "[REDACTED]"
+
+// redactURLUserinfo returns raw with any password component of an embedded
+// userinfo section replaced by the redaction sentinel. The username is left
+// visible so operators can still recognize which account is configured. Inputs
+// that are not parseable URLs, or that contain no password, are returned
+// unchanged.
+func redactURLUserinfo(raw string) string {
+ if raw == "" {
+ return raw
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.User == nil {
+ return raw
+ }
+ if _, hasPassword := u.User.Password(); !hasPassword {
+ return raw
+ }
+ // Plain "REDACTED" is used here (rather than redactedValue) so it survives
+ // URL percent-encoding without becoming "%5BREDACTED%5D".
+ u.User = url.UserPassword(u.User.Username(), "REDACTED")
+ return u.String()
+}
+
const (
ModeDevelopment = "development"
ModeProduction = "production"
@@ -100,11 +128,29 @@ type OIDCConf struct {
RequestTimeout time.Duration `yaml:"request_timeout" conf:"default:30s"`
}
+func (c OIDCConf) MarshalJSON() ([]byte, error) {
+ type alias OIDCConf
+ a := alias(c)
+ if a.ClientSecret != "" {
+ a.ClientSecret = redactedValue
+ }
+ return json.Marshal(a)
+}
+
type BarcodeAPIConf struct {
TokenBarcodespider string `yaml:"token_barcodespider"`
OpenFoodFactsContact string `yaml:"openfoodfacts_contact"`
}
+func (c BarcodeAPIConf) MarshalJSON() ([]byte, error) {
+ type alias BarcodeAPIConf
+ a := alias(c)
+ if a.TokenBarcodespider != "" {
+ a.TokenBarcodespider = redactedValue
+ }
+ return json.Marshal(a)
+}
+
type AuthConfig struct {
RateLimit AuthRateLimit `yaml:"rate_limit"`
// APIKeyPepper is a server-side secret HMAC-keyed into stored API key hashes.
@@ -114,6 +160,15 @@ type AuthConfig struct {
APIKeyPepper string `yaml:"api_key_pepper" conf:"mask"`
}
+func (c AuthConfig) MarshalJSON() ([]byte, error) {
+ type alias AuthConfig
+ a := alias(c)
+ if a.APIKeyPepper != "" {
+ a.APIKeyPepper = redactedValue
+ }
+ return json.Marshal(a)
+}
+
type AuthRateLimit struct {
Enabled bool `yaml:"enabled" conf:"default:true"`
Window time.Duration `yaml:"window" conf:"default:1m"`
@@ -145,8 +200,10 @@ func New(buildstr string, description string) (*Config, error) {
return &cfg, nil
}
-// Print prints the configuration to stdout as a json indented string
-// This is useful for debugging. If the marshaller errors out, it will panic.
+// Print prints the configuration to stdout as an indented JSON document.
+// Sensitive fields (secrets, tokens, passwords, embedded URL credentials) are
+// redacted via each sub-struct's MarshalJSON. Useful for debugging operator
+// configuration without leaking credentials to logs.
func (c *Config) Print() {
res, err := json.MarshalIndent(c, "", " ")
if err != nil {
diff --git a/backend/internal/sys/config/conf_database.go b/backend/internal/sys/config/conf_database.go
index 91a0edd1..a031aaf7 100644
--- a/backend/internal/sys/config/conf_database.go
+++ b/backend/internal/sys/config/conf_database.go
@@ -1,5 +1,7 @@
package config
+import "encoding/json"
+
const (
DriverSqlite3 = "sqlite3"
DriverPostgres = "postgres"
@@ -11,6 +13,13 @@ type Storage struct {
ConnString string `yaml:"conn_string" conf:"default:file:///./"`
}
+func (s Storage) MarshalJSON() ([]byte, error) {
+ type alias Storage
+ a := alias(s)
+ a.ConnString = redactURLUserinfo(a.ConnString)
+ return json.Marshal(a)
+}
+
type Database struct {
Driver string `yaml:"driver" conf:"default:sqlite3"`
Username string `yaml:"username"`
@@ -25,3 +34,13 @@ type Database struct {
SqlitePath string `yaml:"sqlite_path" conf:"default:./.data/homebox.db?_pragma=busy_timeout=999&_pragma=journal_mode=WAL&_fk=1&_time_format=sqlite"`
PubSubConnString string `yaml:"pubsub_conn_string" conf:"default:mem://{{ .Topic }}"`
}
+
+func (d Database) MarshalJSON() ([]byte, error) {
+ type alias Database
+ a := alias(d)
+ if a.Password != "" {
+ a.Password = redactedValue
+ }
+ a.PubSubConnString = redactURLUserinfo(a.PubSubConnString)
+ return json.Marshal(a)
+}
diff --git a/backend/internal/sys/config/conf_mailer.go b/backend/internal/sys/config/conf_mailer.go
index 1335a964..b418b740 100644
--- a/backend/internal/sys/config/conf_mailer.go
+++ b/backend/internal/sys/config/conf_mailer.go
@@ -1,5 +1,7 @@
package config
+import "encoding/json"
+
type MailerConf struct {
Host string `conf:""`
Port int `conf:""`
@@ -8,6 +10,15 @@ type MailerConf struct {
From string `conf:""`
}
+func (m MailerConf) MarshalJSON() ([]byte, error) {
+ type alias MailerConf
+ a := alias(m)
+ if a.Password != "" {
+ a.Password = redactedValue
+ }
+ return json.Marshal(a)
+}
+
// Ready is a simple check to ensure that the configuration is not empty.
// or with it's default state.
func (mc *MailerConf) Ready() bool {
diff --git a/backend/internal/sys/config/conf_otel.go b/backend/internal/sys/config/conf_otel.go
index 4cd6ced1..bba33976 100644
--- a/backend/internal/sys/config/conf_otel.go
+++ b/backend/internal/sys/config/conf_otel.go
@@ -1,5 +1,7 @@
package config
+import "encoding/json"
+
// OTelConfig contains OpenTelemetry configuration options.
// All standard OpenTelemetry environment variables are also supported via the SDK.
type OTelConfig struct {
@@ -51,3 +53,12 @@ type OTelConfig struct {
// ProxyEnabled enables the telemetry proxy endpoint for frontend tracing
ProxyEnabled bool `yaml:"proxy_enabled" conf:"default:true"`
}
+
+func (o OTelConfig) MarshalJSON() ([]byte, error) {
+ type alias OTelConfig
+ a := alias(o)
+ if a.Headers != "" {
+ a.Headers = redactedValue
+ }
+ return json.Marshal(a)
+}
diff --git a/backend/internal/sys/config/conf_redact_test.go b/backend/internal/sys/config/conf_redact_test.go
new file mode 100644
index 00000000..3a430081
--- /dev/null
+++ b/backend/internal/sys/config/conf_redact_test.go
@@ -0,0 +1,145 @@
+package config
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+const sentinel = redactedValue
+
+func Test_AuthConfig_RedactsAPIKeyPepper(t *testing.T) {
+ c := AuthConfig{APIKeyPepper: "super-secret-pepper"}
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ assert.NotContains(t, string(out), "super-secret-pepper")
+ assert.Contains(t, string(out), sentinel)
+}
+
+func Test_AuthConfig_EmptyAPIKeyPepperStaysEmpty(t *testing.T) {
+ c := AuthConfig{}
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ assert.NotContains(t, string(out), sentinel)
+}
+
+func Test_OIDCConf_RedactsClientSecret(t *testing.T) {
+ c := OIDCConf{ClientID: "public-client-id", ClientSecret: "shh"}
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ assert.Contains(t, string(out), "public-client-id")
+ assert.NotContains(t, string(out), `"shh"`)
+ assert.Contains(t, string(out), sentinel)
+}
+
+func Test_MailerConf_RedactsPassword(t *testing.T) {
+ c := MailerConf{Host: "smtp.example.com", Username: "u", Password: "pw", From: "f"}
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ assert.NotContains(t, string(out), `"pw"`)
+ assert.Contains(t, string(out), `"u"`)
+ assert.Contains(t, string(out), sentinel)
+}
+
+func Test_Database_RedactsPasswordAndPubSubCreds(t *testing.T) {
+ c := Database{
+ Driver: "postgres",
+ Username: "homebox",
+ Password: "dbpass",
+ Host: "db",
+ Port: "5432",
+ Database: "homebox",
+ PubSubConnString: "postgres://pubuser:pubpass@db:5432/homebox?sslmode=disable",
+ }
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ s := string(out)
+ assert.NotContains(t, s, "dbpass")
+ assert.NotContains(t, s, "pubpass")
+ assert.Contains(t, s, "pubuser", "username portion should remain visible")
+ assert.Contains(t, s, sentinel)
+}
+
+func Test_Database_LeavesUncredentialedPubSubAlone(t *testing.T) {
+ c := Database{PubSubConnString: "mem://{{ .Topic }}"}
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ assert.Contains(t, string(out), "mem://")
+}
+
+func Test_Storage_RedactsConnStringUserinfo(t *testing.T) {
+ c := Storage{ConnString: "s3://AKIA:[email protected]/path"}
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ assert.NotContains(t, string(out), "secret@bucket")
+ assert.Contains(t, string(out), "REDACTED")
+}
+
+func Test_BarcodeAPIConf_RedactsToken(t *testing.T) {
+ c := BarcodeAPIConf{TokenBarcodespider: "token-xyz", OpenFoodFactsContact: "[email protected]"}
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ assert.NotContains(t, string(out), "token-xyz")
+ assert.Contains(t, string(out), "[email protected]")
+ assert.Contains(t, string(out), sentinel)
+}
+
+func Test_OTelConfig_RedactsHeaders(t *testing.T) {
+ c := OTelConfig{Headers: "Authorization=Bearer hunter2,X-Other=val"}
+
+ out, err := json.Marshal(c)
+ require.NoError(t, err)
+
+ assert.NotContains(t, string(out), "hunter2")
+ assert.Contains(t, string(out), sentinel)
+}
+
+func Test_Config_FullMarshalRedactsAllSecrets(t *testing.T) {
+ c := &Config{
+ Auth: AuthConfig{APIKeyPepper: "pepper-secret"},
+ OIDC: OIDCConf{ClientSecret: "oidc-secret"},
+ Mailer: MailerConf{Password: "mailer-secret"},
+ Storage: Storage{ConnString: "s3://k:s3secret@b/p"},
+ Database: Database{
+ Password: "db-secret",
+ PubSubConnString: "postgres://u:pubsecret@h/d",
+ },
+ Barcode: BarcodeAPIConf{TokenBarcodespider: "bs-secret"},
+ Otel: OTelConfig{Headers: "Authorization=Bearer otel-secret"},
+ }
+
+ out, err := json.MarshalIndent(c, "", " ")
+ require.NoError(t, err)
+
+ for _, secret := range []string{
+ "pepper-secret",
+ "oidc-secret",
+ "mailer-secret",
+ "s3secret",
+ "db-secret",
+ "pubsecret",
+ "bs-secret",
+ "otel-secret",
+ } {
+ assert.Falsef(t, strings.Contains(string(out), secret), "expected %q to be redacted in output", secret)
+ }
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index 4f7fa53e..0301ac50 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -13,7 +13,6 @@ services:
- linux/arm64
- linux/arm
environment:
- - HBOX_DEBUG=true
- HBOX_LOGGER_LEVEL=-1
ports:
- 3100:7745
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 0478edd9..35183356 100644
--- a/docs/src/content/docs/en/quick-start/configure/index.mdx
+++ b/docs/src/content/docs/en/quick-start/configure/index.mdx
@@ -21,7 +21,7 @@ import {Tabs, TabItem} from "@astrojs/starlight/components";
| HBOX_LOG_LEVEL | `info` | log level to use, can be one of `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic` |
| HBOX_LOG_FORMAT | `text` | log format to use, can be one of: `text`, `json` |
| HBOX_MAILER_HOST | | email host to use, if not set no email provider will be used |
-| HBOX_MAILER_PORT | 587 | email port to use |
+| HBOX_MAILER_PORT | | email port to use (no default — typically `587` for STARTTLS or `465` for implicit TLS) |
| HBOX_MAILER_USERNAME | | email user to use |
| HBOX_MAILER_PASSWORD | | email password to use |
| HBOX_MAILER_FROM | | email from address to use |
@@ -45,14 +45,16 @@ import {Tabs, TabItem} from "@astrojs/starlight/components";
| HBOX_OPTIONS_ALLOW_LOCAL_LOGIN | true | allow users to login with username/password when OIDC is enabled |
| HBOX_OPTIONS_TRUST_PROXY | false | trust proxy headers for determining request scheme (X-Forwarded-Proto) |
| HBOX_OPTIONS_HOSTNAME | | override hostname used for OIDC redirect URLs and other absolute URLs |
+| HBOX_AUTH_API_KEY_PEPPER | | **Required.** Server-side secret HMAC-keyed into stored API key hashes; the binary refuses to start if this is shorter than 32 bytes. Generate with `openssl rand -base64 48`. Must stay stable across restarts — rotating it invalidates every issued API key. |
| HBOX_AUTH_RATE_LIMIT_ENABLED | true | enable rate limiting for authentication attempts |
| HBOX_AUTH_RATE_LIMIT_MAX_ATTEMPTS | 5 | maximum number of failed authentication attempts before rate limiting |
| HBOX_AUTH_RATE_LIMIT_WINDOW | 1m | time window for rate limiting |
| HBOX_AUTH_RATE_LIMIT_BASE_BACKOFF | 10s | base backoff duration for rate limiting |
| HBOX_AUTH_RATE_LIMIT_MAX_BACKOFF | 5m | maximum backoff duration for rate limiting |
-| HBOX_DEBUG_ENABLED | false | enable debug mode |
-| HBOX_DEBUG_PORT | 4000 | port to run debug server on |
-| HBOX_DEMO | | enable demo mode |
+| HBOX_DEBUG_ENABLED | false | enable debug mode (exposes pprof + expvar handlers and prints the loaded configuration to stdout with secrets redacted). The debug listener binds to loopback only (127.0.0.1); tunnel via SSH if remote access is needed. |
+| HBOX_DEBUG_PORT | 4000 | port to run debug server on (always bound to 127.0.0.1) |
+| HBOX_DEMO | false | enable demo mode, which seeds a `[email protected]` user and sample inventory on first boot. When `HBOX_MODE=production` the app refuses to start with demo enabled unless `HBOX_DEMO_PASSWORD` is also set (the public `demo/demo` default would otherwise be guessable on a reachable host). |
+| HBOX_DEMO_PASSWORD | | password for the seeded demo user. Required (minimum 12 characters) when `HBOX_DEMO=true` and `HBOX_MODE=production`. In development mode an unset value falls back to the public default `demo`. |
| HBOX_OIDC_ENABLED | false | enable OpenID Connect (OIDC) authentication |
| HBOX_OIDC_ISSUER_URL | | OIDC provider issuer URL (required when OIDC is enabled) |
| HBOX_OIDC_CLIENT_ID | | OIDC client ID (required when OIDC is enabled) |
@@ -84,13 +86,29 @@ 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, BarcodeSpider lookups will not be performed. |
-| HBOX_BARCODE_OPENFOODFACTS_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_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 | | 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) |
+| 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 |
+| HBOX_OTEL_SERVICE_VERSION | | service version reported to the telemetry backend (defaults to the build version when unset) |
+| HBOX_OTEL_EXPORTER | otlp | exporter type: `otlp`, `stdout`, or `none` |
+| HBOX_OTEL_ENDPOINT | | OTLP exporter endpoint including host and port, e.g. `localhost:4317` for gRPC or `http://localhost:4318` for HTTP |
+| HBOX_OTEL_PATH_PREFIX | | optional URL path prefix appended to the OTLP HTTP exporter endpoint |
+| HBOX_OTEL_PROTOCOL | grpc | OTLP protocol: `grpc` or `http` |
+| HBOX_OTEL_INSECURE | false | disable TLS for the OTLP exporter connection |
+| HBOX_OTEL_HEADERS | | additional headers to send with OTLP requests as comma-separated `key=value` pairs (e.g. an auth header for a managed backend; treated as a secret and redacted from debug output) |
+| HBOX_OTEL_SAMPLE_RATE | 1.0 | trace sampling rate from `0.0` (no traces) to `1.0` (all traces) |
+| HBOX_OTEL_ENABLE_METRICS | true | enable OpenTelemetry metrics collection |
+| HBOX_OTEL_METRICS_INTERVAL | 15s | interval at which metrics are exported (e.g. `15s`, `1m`) |
+| HBOX_OTEL_ENABLE_LOGGING | true | bridge zerolog into the OpenTelemetry logs pipeline |
+| HBOX_OTEL_ENABLE_DATABASE_TRACING | true | emit spans for database operations |
+| HBOX_OTEL_ENABLE_HTTP_TRACING | true | emit spans for HTTP requests |
+| HBOX_OTEL_PROXY_ENABLED | true | enable the in-process telemetry proxy endpoint that forwards frontend trace data to the configured exporter |
</TabItem>
<TabItem label="CLI Options">
@@ -98,12 +116,13 @@ import {Tabs, TabItem} from "@astrojs/starlight/components";
Usage: homebox [options...] [arguments...]
OPTIONS
+ --auth-api-key-pepper <string>
--auth-rate-limit-base-backoff <duration> (default: 10s)
--auth-rate-limit-enabled <bool> (default: true)
--auth-rate-limit-max-attempts <int> (default: 5)
--auth-rate-limit-max-backoff <duration> (default: 5m)
--auth-rate-limit-window <duration> (default: 1m)
- --barcode-openfoodfacts-contact <string>
+ --barcode-open-food-facts-contact <string>
--barcode-token-barcodespider <string>
--database-database <string>
--database-driver <string> (default: sqlite3)
@@ -170,6 +189,22 @@ OPTIONS
--options-github-release-check <bool> (default: true)
--options-hostname <string>
--options-trust-proxy <bool> (default: false)
+ --otel-enable-database-tracing <bool> (default: true)
+ --otel-enable-http-tracing <bool> (default: true)
+ --otel-enable-logging <bool> (default: true)
+ --otel-enable-metrics <bool> (default: true)
+ --otel-enabled <bool> (default: false)
+ --otel-endpoint <string>
+ --otel-exporter <string> (default: otlp)
+ --otel-headers <string>
+ --otel-insecure <bool> (default: false)
+ --otel-metrics-interval <string> (default: 15s)
+ --otel-path-prefix <string>
+ --otel-protocol <string> (default: grpc)
+ --otel-proxy-enabled <bool> (default: true)
+ --otel-sample-rate <float> (default: 1.0)
+ --otel-service-name <string> (default: homebox)
+ --otel-service-version <string>
--storage-conn-string <string> (default: file:///./)
--storage-prefix-path <string> (default: .data)
--thumbnail-enabled <bool> (default: true)