Skip to content

Adapting validation for docker container network mode to include ENV_VARS #5589

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 77 additions & 17 deletions pkg/skaffold/schema/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,72 @@ func validateUniqueDependencyAliases(artifacts []*latest.Artifact) (errs []error
return
}

// extractContainerNameFromNetworkMode returns the container name even if it comes from an Env Var. Error if the mode isn't valid
// (only container:<id|name> format allowed)
func extractContainerNameFromNetworkMode(mode string) (string, error) {
if strings.HasPrefix(strings.ToLower(mode), "container:") {
// Up to this point, we know that we can strip until the colon symbol and keep the second part
// this is helpful in case someone sends container not in lowercase
maybeID := strings.SplitN(mode, ":", 2)[1]
id, err := util.ExpandEnvTemplate(maybeID, map[string]string{})
if err != nil {
return "", sErrors.NewError(err,
proto.ActionableErr{
Message: fmt.Sprintf("unable to parse container name %s: %s", mode, err),
ErrCode: proto.StatusCode_TEST_CUSTOM_CMD_PARSE_ERR,
Suggestions: []*proto.Suggestion{
{
SuggestionCode: proto.SuggestionCode_CHECK_CUSTOM_COMMAND,
Action: fmt.Sprintf("Check the content of the environment variable: %s", mode),
},
},
})
}
return id, nil
}
errMsg := fmt.Sprintf("extracting container name from a non valid container network mode '%s'", mode)
return "", sErrors.NewError(fmt.Errorf(errMsg),
proto.ActionableErr{
Message: errMsg,
ErrCode: proto.StatusCode_TEST_CUSTOM_CMD_PARSE_ERR,
Suggestions: []*proto.Suggestion{
{
SuggestionCode: proto.SuggestionCode_CHECK_CUSTOM_COMMAND,
Action: fmt.Sprintf("Check the content of the environment variable: %s", mode),
},
},
})
}

// validateDockerNetworkModeExpression makes sure that the network mode starts with "container:" followed by a valid container name
func validateDockerNetworkModeExpression(image string, expr string) error {
id, err := extractContainerNameFromNetworkMode(expr)
if err != nil {
return err
}
return validateDockerContainerExpression(image, id)
}

// validateDockerContainerExpression makes sure that the container name pass in matches Docker's regular expression for containers
func validateDockerContainerExpression(image string, id string) error {
containerRegExp := regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9_.-]*$")
if !containerRegExp.MatchString(id) {
errMsg := fmt.Sprintf("artifact %s has invalid container name '%s'", image, id)
return sErrors.NewError(fmt.Errorf(errMsg),
proto.ActionableErr{
Message: errMsg,
ErrCode: proto.StatusCode_INIT_DOCKER_NETWORK_INVALID_CONTAINER_NAME,
Suggestions: []*proto.Suggestion{
{
SuggestionCode: proto.SuggestionCode_FIX_DOCKER_NETWORK_CONTAINER_NAME,
Action: "Please fix the docker network container name and try again",
},
},
})
}
return nil
}

// validateDockerNetworkMode makes sure that networkMode is one of `bridge`, `none`, `container:<name|id>`, or `host` if set.
func validateDockerNetworkMode(artifacts []*latest.Artifact) (errs []error) {
for _, a := range artifacts {
Expand All @@ -229,23 +295,11 @@ func validateDockerNetworkMode(artifacts []*latest.Artifact) (errs []error) {
if mode == "none" || mode == "bridge" || mode == "host" {
continue
}
containerRegExp := regexp.MustCompile("^container:[a-zA-Z0-9][a-zA-Z0-9_.-]*$")
if containerRegExp.MatchString(mode) {
networkModeErr := validateDockerNetworkModeExpression(a.ImageName, a.DockerArtifact.NetworkMode)
if networkModeErr == nil {
continue
}

errMsg := fmt.Sprintf("artifact %s has invalid networkMode '%s'", a.ImageName, mode)
errs = append(errs, sErrors.NewError(fmt.Errorf(errMsg),
proto.ActionableErr{
Message: errMsg,
ErrCode: proto.StatusCode_INIT_DOCKER_NETWORK_INVALID_CONTAINER_NAME,
Suggestions: []*proto.Suggestion{
{
SuggestionCode: proto.SuggestionCode_FIX_DOCKER_NETWORK_CONTAINER_NAME,
Action: "Please fix the docker network container name and try again",
},
},
}))
errs = append(errs, networkModeErr)
}
return
}
Expand All @@ -270,7 +324,13 @@ func validateDockerNetworkContainerExists(artifacts []*latest.Artifact, runCtx d
mode := strings.ToLower(a.DockerArtifact.NetworkMode)
prefix := "container:"
if strings.HasPrefix(mode, prefix) {
id := strings.TrimPrefix(mode, prefix)
// We've already validated the container's name in validateDockerNetworkMode.
// We can just extract it and check whether it exists
id, err := extractContainerNameFromNetworkMode(a.DockerArtifact.NetworkMode)
if err != nil {
errs = append(errs, err)
return errs
}
containers, err := client.ContainerList(ctx, types.ContainerListOptions{})
if err != nil {
errs = append(errs, sErrors.NewError(err,
Expand All @@ -288,7 +348,7 @@ func validateDockerNetworkContainerExists(artifacts []*latest.Artifact, runCtx d
}
for _, c := range containers {
// Comparing ID seeking for <id>
if c.ID == id {
if strings.HasPrefix(c.ID, id) {
return errs
}
for _, name := range c.Names {
Expand Down
155 changes: 155 additions & 0 deletions pkg/skaffold/schema/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/util"
"github.com/GoogleContainerTools/skaffold/testutil"
)

Expand Down Expand Up @@ -264,6 +265,7 @@ func TestValidateNetworkMode(t *testing.T) {
description string
artifacts []*latest.Artifact
shouldErr bool
env []string
}{
{
description: "not a docker artifact",
Expand Down Expand Up @@ -314,6 +316,21 @@ func TestValidateNetworkMode(t *testing.T) {
},
shouldErr: true,
},
{
description: "empty container's network stack in env var",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:{{.CONTAINER}}",
},
},
},
},
env: []string{"CONTAINER="},
shouldErr: true,
},
{
description: "wrong container's network stack '-not-valid'",
artifacts: []*latest.Artifact{
Expand All @@ -328,6 +345,21 @@ func TestValidateNetworkMode(t *testing.T) {
},
shouldErr: true,
},
{
description: "wrong container's network stack '-not-valid' in env var",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:{{.CONTAINER}}",
},
},
},
},
env: []string{"CONTAINER=-not-valid"},
shouldErr: true,
},
{
description: "wrong container's network stack 'fussball'",
artifacts: []*latest.Artifact{
Expand All @@ -342,6 +374,21 @@ func TestValidateNetworkMode(t *testing.T) {
},
shouldErr: true,
},
{
description: "wrong container's network stack 'fussball' in env var",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:{{.CONTAINER}}",
},
},
},
},
env: []string{"CONTAINER=fußball"},
shouldErr: true,
},
{
description: "container's network stack 'unique'",
artifacts: []*latest.Artifact{
Expand All @@ -355,6 +402,20 @@ func TestValidateNetworkMode(t *testing.T) {
},
},
},
{
description: "container's network stack 'unique' in env var",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:{{.CONTAINER}}",
},
},
},
},
env: []string{"CONTAINER=unique"},
},
{
description: "container's network stack 'unique-id.123'",
artifacts: []*latest.Artifact{
Expand All @@ -368,6 +429,20 @@ func TestValidateNetworkMode(t *testing.T) {
},
},
},
{
description: "container's network stack 'unique-id.123' in env var",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:{{.CONTAINER}}",
},
},
},
},
env: []string{"CONTAINER=unique-id.123"},
},
{
description: "none",
artifacts: []*latest.Artifact{
Expand Down Expand Up @@ -426,6 +501,7 @@ func TestValidateNetworkMode(t *testing.T) {
testutil.Run(t, test.description, func(t *testutil.T) {
// disable yamltags validation
t.Override(&validateYamltags, func(interface{}) error { return nil })
t.Override(&util.OSEnviron, func() []string { return test.env })

err := Process(
[]*latest.SkaffoldConfig{{
Expand Down Expand Up @@ -456,6 +532,7 @@ func TestValidateNetworkModeDockerContainerExists(t *testing.T) {
artifacts []*latest.Artifact
clientResponse []types.Container
shouldErr bool
env []string
}{
{
description: "no running containers",
Expand Down Expand Up @@ -510,6 +587,24 @@ func TestValidateNetworkModeDockerContainerExists(t *testing.T) {
},
},
},
{
description: "existing running container referenced by first id chars",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:123",
},
},
},
},
clientResponse: []types.Container{
{
ID: "1234567890",
},
},
},
{
description: "existing running container referenced by name",
artifacts: []*latest.Artifact{
Expand All @@ -529,11 +624,71 @@ func TestValidateNetworkModeDockerContainerExists(t *testing.T) {
},
},
},
{
description: "non existing running container referenced by id in envvar",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:{{ .CONTAINER }}",
},
},
},
},
clientResponse: []types.Container{
{
ID: "non-foo",
},
},
env: []string{"CONTAINER=foo"},
shouldErr: true,
},
{
description: "existing running container referenced by id in envvar",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:{{ .CONTAINER }}",
},
},
},
},
clientResponse: []types.Container{
{
ID: "foo",
},
},
env: []string{"CONTAINER=foo"},
},
{
description: "existing running container referenced by name in envvar",
artifacts: []*latest.Artifact{
{
ImageName: "image/container",
ArtifactType: latest.ArtifactType{
DockerArtifact: &latest.DockerArtifact{
NetworkMode: "Container:{{ .CONTAINER }}",
},
},
},
},
clientResponse: []types.Container{
{
ID: "non-foo",
Names: []string{"/foo"},
},
},
env: []string{"CONTAINER=foo"},
},
}
for _, test := range tests {
testutil.Run(t, test.description, func(t *testutil.T) {
// disable yamltags validation
t.Override(&validateYamltags, func(interface{}) error { return nil })
t.Override(&util.OSEnviron, func() []string { return test.env })
t.Override(&docker.NewAPIClient, func(docker.Config) (docker.LocalDaemon, error) {
fakeClient := &fakeCommonAPIClient{
CommonAPIClient: &testutil.FakeAPIClient{
Expand Down