diff --git a/pkg/cidata/template.go b/pkg/cidata/template.go index aedc5caaa3b..2a18ba43862 100644 --- a/pkg/cidata/template.go +++ b/pkg/cidata/template.go @@ -11,6 +11,7 @@ import ( "github.com/lima-vm/lima/pkg/iso9660util" "github.com/containerd/containerd/identifiers" + "github.com/lima-vm/lima/pkg/osutil" "github.com/lima-vm/lima/pkg/textutil" ) @@ -92,8 +93,8 @@ func ValidateTemplateArgs(args TemplateArgs) error { if err := identifiers.Validate(args.Name); err != nil { return err } - if err := identifiers.Validate(args.User); err != nil { - return err + if !osutil.ValidateUsername(args.User) { + return errors.New("field User must be valid linux username") } if args.User == "root" { return errors.New("field User must not be \"root\"") diff --git a/pkg/osutil/user.go b/pkg/osutil/user.go index 98a987b7fea..7896d5e43e2 100644 --- a/pkg/osutil/user.go +++ b/pkg/osutil/user.go @@ -40,6 +40,10 @@ var regexUsername = regexp.MustCompile("^[a-z_][a-z0-9_-]*$") // regexPath detects valid Linux path. var regexPath = regexp.MustCompile("^[/a-zA-Z0-9_-]+$") +func ValidateUsername(name string) bool { + return regexUsername.MatchString(name) +} + func LookupUser(name string) (User, error) { if users == nil { users = make(map[string]User) @@ -111,7 +115,7 @@ func LimaUser(warn bool) (*user.User, error) { cache.Do(func() { cache.u, cache.err = user.Current() if cache.err == nil { - if !regexUsername.MatchString(cache.u.Username) { + if !ValidateUsername(cache.u.Username) { warning := fmt.Sprintf("local user %q is not a valid Linux username (must match %q); using %q username instead", cache.u.Username, regexUsername.String(), fallbackUser) cache.warnings = append(cache.warnings, warning) diff --git a/pkg/osutil/user_test.go b/pkg/osutil/user_test.go index 860f0a71db2..e68375acddb 100644 --- a/pkg/osutil/user_test.go +++ b/pkg/osutil/user_test.go @@ -13,15 +13,11 @@ func TestLimaUserWarn(t *testing.T) { assert.NilError(t, err) } -func validUsername(username string) bool { - return regexUsername.MatchString(username) -} - func TestLimaUsername(t *testing.T) { user, err := LimaUser(false) assert.NilError(t, err) // check for reasonable unix user name - assert.Assert(t, validUsername(user.Username), user.Username) + assert.Assert(t, ValidateUsername(user.Username), user.Username) } func TestLimaUserUid(t *testing.T) {