Skip to content

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

fix: various other issues wit v0.26.x (#1564)

Matt78afdeb70d21
diff --git a/backend/internal/core/services/service_group.go b/backend/internal/core/services/service_group.go
index 6a8501f6..f0c108f4 100644
--- a/backend/internal/core/services/service_group.go
+++ b/backend/internal/core/services/service_group.go
@@ -34,7 +34,19 @@ func (svc *GroupService) CreateGroup(ctx Context, name string) (repo.Group, erro
return repo.Group{}, errors.New("user ID cannot be empty when creating a group")
}
- return svc.repos.Groups.GroupCreate(ctx.Context, name, ctx.UID)
+ group, err := svc.repos.Groups.GroupCreate(ctx.Context, name, ctx.UID)
+ if err != nil {
+ return repo.Group{}, err
+ }
+
+ // Unlike registration, this path doesn't seed default locations/tags, so
+ // nothing would lazily create the entity types — leaving the collection
+ // unable to create items or locations until a type was added by hand.
+ if err := ensureDefaultEntityTypes(ctx.Context, svc.repos, group.ID); err != nil {
+ return repo.Group{}, err
+ }
+
+ return group, nil
}
func (svc *GroupService) DeleteGroup(ctx Context) error {
diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.go
index ef22dc24..dd1b4262 100644
--- a/backend/internal/core/services/service_user.go
+++ b/backend/internal/core/services/service_user.go
@@ -220,6 +220,17 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration,
}
locsCreated++
}
+
+ // Seeding locations lazily creates the "Location" entity type, but the
+ // "Item" type isn't created until the first item — leaving the new group
+ // unable to create items via the UI. Ensure both exist up front.
+ if err := ensureDefaultEntityTypes(bootstrapCtx, svc.repos, usr.DefaultGroupID); err != nil {
+ recordServiceSpanError(bootstrapSpan, err)
+ bootstrapSpan.End()
+ recordServiceSpanError(span, err)
+ return repo.UserOut{}, err
+ }
+
bootstrapSpan.SetAttributes(
attribute.Int("tags.created.count", tagsCreated),
attribute.Int("locations.created.count", locsCreated),
@@ -574,6 +585,14 @@ func (svc *UserService) registerOIDCUser(ctx context.Context, issuer, subject, e
}
locsCreated++
}
+
+ // Ensure both default entity types exist (see RegisterUser): seeding
+ // locations only creates the "Location" type, not "Item".
+ if err := ensureDefaultEntityTypes(bootstrapCtx, svc.repos, group.ID); err != nil {
+ recordServiceSpanError(bootstrapSpan, err)
+ log.Err(err).Msg("Failed to ensure default entity types")
+ }
+
bootstrapSpan.SetAttributes(
attribute.Int("tags.created.count", tagsCreated),
attribute.Int("locations.created.count", locsCreated),
diff --git a/backend/internal/core/services/service_user_defaults.go b/backend/internal/core/services/service_user_defaults.go
index bc96595c..870c9556 100644
--- a/backend/internal/core/services/service_user_defaults.go
+++ b/backend/internal/core/services/service_user_defaults.go
@@ -1,11 +1,27 @@
package services
import (
+ "context"
+
+ "github.com/google/uuid"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
)
const defaultLocationGarage = "Garage"
+// ensureDefaultEntityTypes guarantees a freshly created group has the two
+// baseline entity types ("Item" and "Location"). The frontend create dialogs
+// require selecting an existing type, so without these a brand-new group can't
+// create items or locations at all. GetDefault creates each type if missing.
+func ensureDefaultEntityTypes(ctx context.Context, repos *repo.AllRepos, gid uuid.UUID) error {
+ for _, isLocation := range []bool{false, true} {
+ if _, err := repos.EntityTypes.GetDefault(ctx, gid, isLocation); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
func defaultLocations() []repo.EntityCreate {
return []repo.EntityCreate{
{
diff --git a/backend/pkgs/labelmaker/labelmaker.go b/backend/pkgs/labelmaker/labelmaker.go
index 49dc3f0d..23c4f2b4 100644
--- a/backend/pkgs/labelmaker/labelmaker.go
+++ b/backend/pkgs/labelmaker/labelmaker.go
@@ -17,6 +17,7 @@ import (
"strings"
"text/template"
"time"
+ "unicode"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
@@ -429,6 +430,45 @@ func fetchLabelFromURL(w io.Writer, serviceURL string, params *GenerateParameter
return nil
}
+// splitCommandTemplate splits a print-command template into argv tokens on
+// whitespace, treating any `{{ ... }}` template action as opaque so that
+// whitespace *inside* an action (e.g. `{{ .FileName }}`) does not split the
+// token. This lets the admin's spacing define argument boundaries up front,
+// before any user-controlled value is substituted in.
+func splitCommandTemplate(s string) []string {
+ var (
+ parts []string
+ cur strings.Builder
+ inAction bool
+ )
+ runes := []rune(s)
+ for i := 0; i < len(runes); i++ {
+ switch {
+ case !inAction && i+1 < len(runes) && runes[i] == '{' && runes[i+1] == '{':
+ inAction = true
+ cur.WriteRune(runes[i])
+ cur.WriteRune(runes[i+1])
+ i++
+ case inAction && i+1 < len(runes) && runes[i] == '}' && runes[i+1] == '}':
+ inAction = false
+ cur.WriteRune(runes[i])
+ cur.WriteRune(runes[i+1])
+ i++
+ case !inAction && unicode.IsSpace(runes[i]):
+ if cur.Len() > 0 {
+ parts = append(parts, cur.String())
+ cur.Reset()
+ }
+ default:
+ cur.WriteRune(runes[i])
+ }
+ }
+ if cur.Len() > 0 {
+ parts = append(parts, cur.String())
+ }
+ return parts
+}
+
func PrintLabel(cfg *config.Config, params *GenerateParameters) error {
tmpFile := filepath.Join(os.TempDir(), fmt.Sprintf("label-%d.png", time.Now().UnixNano()))
f, err := os.OpenFile(tmpFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
@@ -451,15 +491,13 @@ func PrintLabel(cfg *config.Config, params *GenerateParameters) error {
return fmt.Errorf("no print command specified")
}
- commandTemplate := template.Must(template.New("command").Parse(*cfg.LabelMaker.PrintCommand))
- builder := &strings.Builder{}
additionalInformation := func() string {
if params.AdditionalInformation != nil {
return *params.AdditionalInformation
}
return ""
}()
- if err := commandTemplate.Execute(builder, map[string]string{
+ templateData := map[string]string{
"FileName": f.Name(),
"Width": fmt.Sprintf("%d", params.Width),
"Height": fmt.Sprintf("%d", params.Height),
@@ -474,11 +512,33 @@ func PrintLabel(cfg *config.Config, params *GenerateParameters) error {
"Dpi": fmt.Sprintf("%f", params.Dpi),
"URL": params.URL,
"DynamicLength": fmt.Sprintf("%t", params.DynamicLength),
- }); err != nil {
- return err
}
- commandParts := strings.Fields(builder.String())
+ // SECURITY: split the admin-configured command into argv tokens *before*
+ // substituting any values, then render each token independently. Several of
+ // these fields (TitleText/DescriptionText, derived from item and location
+ // names) are controlled by any authenticated user. If we rendered first and
+ // split on whitespace afterwards, a user could embed spaces in an item name
+ // to smuggle extra arguments into the print binary (argument injection).
+ // Per-token rendering keeps every substituted value confined to the single
+ // argv entry the admin placed it in, regardless of its contents.
+ var commandParts []string
+ for _, rawPart := range splitCommandTemplate(*cfg.LabelMaker.PrintCommand) {
+ tmpl, err := template.New("command").Parse(rawPart)
+ if err != nil {
+ return fmt.Errorf("invalid print command template: %w", err)
+ }
+ builder := &strings.Builder{}
+ if err := tmpl.Execute(builder, templateData); err != nil {
+ return err
+ }
+ // Drop tokens that render empty so an unset placeholder doesn't become a
+ // stray empty argument — matching the previous whitespace-collapsing
+ // behavior without re-splitting rendered output.
+ if rendered := builder.String(); rendered != "" {
+ commandParts = append(commandParts, rendered)
+ }
+ }
if len(commandParts) == 0 {
return nil
}
diff --git a/backend/pkgs/labelmaker/labelmaker_test.go b/backend/pkgs/labelmaker/labelmaker_test.go
index d8e05a96..894cd8a7 100644
--- a/backend/pkgs/labelmaker/labelmaker_test.go
+++ b/backend/pkgs/labelmaker/labelmaker_test.go
@@ -3,6 +3,8 @@ package labelmaker
import (
"os"
"path/filepath"
+ "runtime"
+ "strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -183,3 +185,74 @@ func TestLoadFont_CJKRendering(t *testing.T) {
})
}
}
+
+func TestSplitCommandTemplate(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want []string
+ }{
+ {"empty", "", nil},
+ {"whitespace only", " \t ", nil},
+ {"simple", "lp -d printer file.png", []string{"lp", "-d", "printer", "file.png"}},
+ {"collapses runs", "lp -d printer", []string{"lp", "-d", "printer"}},
+ {
+ "placeholder without inner space",
+ "lp -t {{.TitleText}} {{.FileName}}",
+ []string{"lp", "-t", "{{.TitleText}}", "{{.FileName}}"},
+ },
+ {
+ "placeholder with inner space stays one token",
+ "lp -o {{ .FileName }}",
+ []string{"lp", "-o", "{{ .FileName }}"},
+ },
+ {
+ "placeholder glued to literal stays one token",
+ "convert prefix-{{.TitleText}}-suffix",
+ []string{"convert", "prefix-{{.TitleText}}-suffix"},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.want, splitCommandTemplate(tt.in))
+ })
+ }
+}
+
+// TestPrintLabel_ArgumentInjection is the regression test for the argument
+// injection where a user-controlled item name containing whitespace could
+// smuggle extra argv entries into the print binary. The fix renders each argv
+// token independently, so a malicious TitleText must arrive as a single
+// argument.
+func TestPrintLabel_ArgumentInjection(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("recorder script relies on a POSIX shell")
+ }
+
+ dir := t.TempDir()
+ argsFile := filepath.Join(dir, "args.txt")
+ recorder := filepath.Join(dir, "recorder.sh")
+ script := "#!/bin/sh\n: > '" + argsFile + "'\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> '" + argsFile + "'; done\n"
+ require.NoError(t, os.WriteFile(recorder, []byte(script), 0o700))
+
+ // The admin template separates two arguments: the (attacker-controlled)
+ // title and the generated file name.
+ printCommand := recorder + " {{.TitleText}} {{.FileName}}"
+
+ cfg := &config.Config{}
+ cfg.LabelMaker.PrintCommand = &printCommand
+
+ const maliciousTitle = "evil title --output /etc/passwd"
+ params := NewGenerateParams(400, 200, 10, 5, 32, maliciousTitle, "desc", "http://localhost/item/1", false, nil)
+
+ require.NoError(t, PrintLabel(cfg, &params))
+
+ raw, err := os.ReadFile(argsFile)
+ require.NoError(t, err)
+ got := strings.Split(strings.TrimRight(string(raw), "\n"), "\n")
+
+ // Exactly two arguments: the whole title as one entry, then the file name.
+ require.Len(t, got, 2, "argv must not be split on whitespace inside the title")
+ assert.Equal(t, maliciousTitle, got[0])
+ assert.True(t, strings.HasSuffix(got[1], ".png"), "second arg should be the generated label file, got %q", got[1])
+}