Correctly check validity of container name

regexp.MatchString() only returns an error if the pattern can't be
parsed. In this case, the pattern is a constant string literal, so
unless there's a programming mistake, the pattern should always be
parsable and there should never be an error.

What really needs to be checked is whether the 'containerName' matched
the pattern or not. That's indicated by the bool return value
'matched'.

https://github.com/containers/toolbox/pull/639
This commit is contained in:
Ondřej Míchal 2020-12-02 14:10:40 +01:00 committed by Debarshi Ray
parent 467492619a
commit 1a5acddca2
5 changed files with 11 additions and 6 deletions

View file

@ -115,7 +115,7 @@ func create(cmd *cobra.Command, args []string) error {
}
if container != "" {
if _, err := utils.IsContainerNameValid(container); err != nil {
if !utils.IsContainerNameValid(container) {
var builder strings.Builder
fmt.Fprintf(&builder, "invalid argument for '%s'\n", containerArg)
fmt.Fprintf(&builder, "Container names must match '%s'\n", utils.ContainerNameRegexp)

View file

@ -86,7 +86,7 @@ func enter(cmd *cobra.Command, args []string) error {
if container != "" {
nonDefaultContainer = true
if _, err := utils.IsContainerNameValid(container); err != nil {
if !utils.IsContainerNameValid(container) {
var builder strings.Builder
fmt.Fprintf(&builder, "invalid argument for '%s'\n", containerArg)
fmt.Fprintf(&builder, "Container names must match '%s'\n", utils.ContainerNameRegexp)

View file

@ -81,7 +81,7 @@ func run(cmd *cobra.Command, args []string) error {
if runFlags.container != "" {
nonDefaultContainer = true
if _, err := utils.IsContainerNameValid(runFlags.container); err != nil {
if !utils.IsContainerNameValid(runFlags.container) {
var builder strings.Builder
fmt.Fprintf(&builder, "invalid argument for '--container'\n")
fmt.Fprintf(&builder, "Container names must match '%s'\n", utils.ContainerNameRegexp)

View file

@ -497,10 +497,15 @@ func PathExists(path string) bool {
}
// IsContainerNameValid checks if the name of a container matches the right pattern
func IsContainerNameValid(containerName string) (bool, error) {
func IsContainerNameValid(containerName string) bool {
pattern := "^" + ContainerNameRegexp + "$"
matched, err := regexp.MatchString(pattern, containerName)
return matched, err
if err != nil {
panicMsg := fmt.Sprintf("failed to parse regular expression for container name: %v", err)
panic(panicMsg)
}
return matched
}
func IsInsideContainer() bool {

View file

@ -16,5 +16,5 @@ load helpers
@test "Try to create a container with invalid custom name" {
run_toolbox 1 -y create "ßpeci@l.Nam€"
is "${lines[0]}" "Error: failed to create container ßpeci@l.Nam€" "Toolbox should fail to create a container with such name"
is "${lines[0]}" "Error: invalid argument for 'CONTAINER'" "Toolbox should fail to create a container with such name"
}