Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
16 changes: 16 additions & 0 deletions cli/command/stack/deploy_composefile.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,29 @@ import (
"github.com/moby/moby/api/types/network"
"github.com/moby/moby/api/types/swarm"
"github.com/moby/moby/client"
"github.com/moby/moby/client/pkg/versions"
)

func deployCompose(ctx context.Context, dockerCli command.Cli, opts *deployOptions, config *composetypes.Config) error {
if err := checkDaemonIsSwarmManager(ctx, dockerCli); err != nil {
return err
}

// The Info call above negotiates the API version. Reject an unsupported
// hardening request before pruning or creating any stack resources.
const noNewPrivilegesAPIVersion = "1.44"
if apiVersion := dockerCli.Client().ClientVersion(); versions.LessThan(apiVersion, noNewPrivilegesAPIVersion) {
for _, svc := range config.Services {
noNewPrivileges, _, err := convert.ParseSecurityOpts(svc.SecurityOpt)
if err != nil {
return fmt.Errorf("service %s: %w", svc.Name, err)
}
if noNewPrivileges {
return fmt.Errorf("service %s: no-new-privileges requires API %s or later (negotiated API %s)", svc.Name, noNewPrivilegesAPIVersion, apiVersion)
}
}
}

namespace := convert.NewNamespace(opts.namespace)

if opts.prune {
Expand Down
138 changes: 138 additions & 0 deletions cli/command/stack/deploy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@ package stack

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"

"github.com/docker/cli/cli/compose/convert"
"github.com/docker/cli/cli/streams"
"github.com/docker/cli/internal/test"
"github.com/moby/moby/api/types/swarm"
"github.com/moby/moby/client"
Expand All @@ -22,6 +29,137 @@ func TestDeployWithEmptyName(t *testing.T) {
assert.ErrorContains(t, cmd.Execute(), `invalid stack name: "' '"`)
}

func TestDeployNoNewPrivileges(t *testing.T) {
const compose = `version: "3.8"
services:
app:
image: example:1
credential_spec:
config: credentials
configs:
credentials:
external: true
`
const secure = " security_opt: [no-new-privileges=true]\n"
for _, tc := range []struct {
name string
version string
options string
override string
update bool
enabled bool
warning string
reject bool
}{
{name: "create", version: "1.44", options: secure, enabled: true},
{name: "update with mixed options", version: "1.44", options: " security_opt: [no-new-privileges, apparmor=example]\n", update: true, enabled: true, warning: "Ignoring unsupported security_opt entries for service \"app\"\n"},
{name: "update clears explicit false", version: "1.44", options: " security_opt: [no-new-privileges=false]\n", update: true},
{name: "old API rejects enabled", version: "1.43", options: secure, reject: true},
{name: "old API accepts interpolated false override", version: "1.43", options: secure, override: "no-new-privileges:${STACK_TEST_NNP}", update: true},
{name: "old API accepts absent option", version: "1.43"},
} {
t.Run(tc.name, func(t *testing.T) {
var spec swarm.ServiceSpec
var written bool
api := dockerTestTransport(func(req *http.Request) (*http.Response, error) {
response := func(status int, body string) (*http.Response, error) {
return &http.Response{
StatusCode: status,
Header: http.Header{"Api-Version": {tc.version}},
Body: io.NopCloser(strings.NewReader(body)),
}, nil
}
path := req.URL.Path
if req.Method == http.MethodHead && path == "/_ping" {
return response(http.StatusOK, "")
}
path, versioned := strings.CutPrefix(path, "/v"+tc.version)
assert.Assert(t, versioned, "expected negotiated API version in %s", req.URL.Path)
if req.Method == http.MethodGet && path == "/info" {
return response(http.StatusOK, `{"Swarm":{"ControlAvailable":true}}`)
}
if tc.reject {
t.Errorf("unexpected request after negotiation: %s %s", req.Method, path)
return nil, fmt.Errorf("unexpected request: %s %s", req.Method, path)
}

switch req.Method + " " + path {
case "GET /networks":
return response(http.StatusOK, `[{"Name":"test_default"}]`)
case "GET /configs":
return response(http.StatusOK, `[{"ID":"credential-id","Spec":{"Name":"credentials"}}]`)
case "GET /services":
if tc.update {
return response(http.StatusOK, `[{"ID":"service-id","Version":{"Index":2},"Spec":{"Name":"test_app","TaskTemplate":{"ContainerSpec":{"Image":"example:1","Privileges":{"NoNewPrivileges":true,"CredentialSpec":{"Config":"credential-id"}}}}}}]`)
}
return response(http.StatusOK, "[]")
case "POST /services/create":
assert.Check(t, !tc.update)
assert.NilError(t, json.NewDecoder(req.Body).Decode(&spec))
written = true
return response(http.StatusCreated, `{"ID":"service-id"}`)
case "POST /services/service-id/update":
assert.Check(t, tc.update)
assert.Check(t, is.Equal(req.URL.Query().Get("version"), "2"))
assert.NilError(t, json.NewDecoder(req.Body).Decode(&spec))
written = true
return response(http.StatusOK, "{}")
default:
return nil, fmt.Errorf("unexpected request: %s %s", req.Method, path)
}
})

apiClient, err := client.New(client.WithHTTPClient(&http.Client{Transport: api}))
assert.NilError(t, err)
dockerCLI := test.NewFakeCli(apiClient)
input := strings.Replace(compose, "configs:\n", tc.options+"configs:\n", 1)
args := []string{"--detach=true", "--resolve-image=never", "--prune"}
if tc.override == "" {
dockerCLI.SetIn(streams.NewIn(io.NopCloser(strings.NewReader(input))))
args = append(args, "-c", "-")
} else {
t.Setenv("STACK_TEST_NNP", "false")
dir := t.TempDir()
base := filepath.Join(dir, "base.yaml")
override := filepath.Join(dir, "override.yaml")
assert.NilError(t, os.WriteFile(base, []byte(input), 0o600))
overrideYAML := fmt.Sprintf("version: '3.8'\nservices:\n app:\n security_opt: [%q]\n", tc.override)
assert.NilError(t, os.WriteFile(override, []byte(overrideYAML), 0o600))
args = append(args, "-c", base, "-c", override)
}
cmd := newDeployCommand(dockerCLI)
cmd.SetArgs(append(args, "test"))
err = cmd.Execute()
if tc.reject {
assert.ErrorContains(t, err, "service app: no-new-privileges requires API 1.44 or later (negotiated API 1.43)")
assert.Check(t, !written)
return
}
assert.NilError(t, err)
assert.Assert(t, written)
container := spec.TaskTemplate.ContainerSpec
assert.DeepEqual(t, container.Privileges, &swarm.Privileges{
NoNewPrivileges: tc.enabled,
CredentialSpec: &swarm.CredentialSpec{Config: "credential-id"},
})
assert.DeepEqual(t, container.Configs, []*swarm.ConfigReference{{
ConfigID: "credential-id",
ConfigName: "credentials",
Runtime: &swarm.ConfigReferenceRuntimeTarget{},
}})
assert.Equal(t, dockerCLI.ErrBuffer().String(), tc.warning)
})
}
}

// dockerTestTransport serves Engine API requests in memory for the deploy test.
type dockerTestTransport func(*http.Request) (*http.Response, error)

// RoundTrip hands the request to the test handler without contacting a daemon.
func (f dockerTestTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}

func TestPruneServices(t *testing.T) {
ctx := context.Background()
namespace := convert.NewNamespace("foo")
Expand Down
11 changes: 11 additions & 0 deletions cli/command/stack/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (

"github.com/distribution/reference"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/compose/convert"
"github.com/docker/cli/cli/compose/loader"
"github.com/docker/cli/cli/compose/schema"
composetypes "github.com/docker/cli/cli/compose/types"
Expand Down Expand Up @@ -44,6 +45,16 @@ func loadComposeFile(streams command.Streams, opts deployOptions) (*composetypes
strings.Join(unsupportedProperties, ", "))
}

for _, svc := range config.Services {
_, unsupported, err := convert.ParseSecurityOpts(svc.SecurityOpt)
if err != nil {
return nil, fmt.Errorf("service %s: %w", svc.Name, err)
}
if unsupported {
_, _ = fmt.Fprintf(streams.Err(), "Ignoring unsupported security_opt entries for service %q\n", svc.Name)
}
}

deprecatedProperties := loader.GetDeprecatedProperties(dicts...)
if len(deprecatedProperties) > 0 {
_, _ = fmt.Fprintf(streams.Err(), "Ignoring deprecated options:\n\n%s\n\n",
Expand Down
22 changes: 22 additions & 0 deletions cli/command/stack/loader_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,39 @@
package stack

import (
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"

"github.com/docker/cli/cli/streams"
"github.com/docker/cli/internal/test"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/fs"
)

func TestLoadComposeFileWarnsAboutUnsupportedSecurityOpts(t *testing.T) {
dockerCLI := test.NewFakeCli(nil)
dockerCLI.SetIn(streams.NewIn(io.NopCloser(strings.NewReader(`version: "3.8"
services:
app:
image: example
security_opt: [no-new-privileges]
other:
image: example
security_opt: [apparmor=example-profile]
links: [app]
`))))
_, err := loadComposeFile(dockerCLI, deployOptions{composefiles: []string{"-"}})
assert.NilError(t, err)
assert.Equal(t, dockerCLI.ErrBuffer().String(),
"Ignoring unsupported options: links\n\n"+
"Ignoring unsupported security_opt entries for service \"other\"\n")
}

func TestGetConfigDetails(t *testing.T) {
content := `
version: "3.0"
Expand Down
34 changes: 34 additions & 0 deletions cli/compose/convert/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/netip"
"os"
"slices"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -102,6 +103,11 @@ func Service(
dnsConfig := convertDNSConfig(service.DNS, service.DNSSearch) // TODO(thaJeztah): change service.DNS to a []netip.Addr

var privileges swarm.Privileges
privileges.NoNewPrivileges, _, err = ParseSecurityOpts(service.SecurityOpt)
if err != nil {
return swarm.ServiceSpec{}, err
}

privileges.CredentialSpec, err = convertCredentialSpec(
namespace, service.CredentialSpec, configs,
)
Expand Down Expand Up @@ -677,6 +683,34 @@ func toNetipAddrSlice(ips []string) []netip.Addr {
return netIPs
}

// ParseSecurityOpts converts no-new-privileges and reports whether any other
// options are unsupported. The last setting wins, including across Compose
// files whose lists have been appended by the loader.
func ParseSecurityOpts(options []string) (noNewPrivileges, unsupported bool, err error) {
const optionName = "no-new-privileges"
for _, option := range options {
if option == optionName {
noNewPrivileges = true
continue
}

name, value, found := strings.Cut(option, "=")
if !found {
name, value, _ = strings.Cut(option, ":")
}
if name != optionName {
unsupported = true
continue
}

noNewPrivileges, err = strconv.ParseBool(value)
if err != nil {
return false, unsupported, errors.New("invalid security_opt: no-new-privileges requires a boolean value")
}
}
return noNewPrivileges, unsupported, nil
}

func convertCredentialSpec(namespace Namespace, spec composetypes.CredentialSpecConfig, refs []*swarm.ConfigReference) (*swarm.CredentialSpec, error) {
var o []string

Expand Down
46 changes: 46 additions & 0 deletions cli/compose/convert/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"testing"
"time"

"github.com/docker/cli/cli/compose/loader"
composetypes "github.com/docker/cli/cli/compose/types"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/moby/moby/api/types/container"
Expand Down Expand Up @@ -437,6 +438,51 @@ func TestConvertCredentialSpec(t *testing.T) {
}
}

func TestConvertServiceNoNewPrivileges(t *testing.T) {
for _, tc := range []struct {
name string
options string
enabled bool
wantErr bool
}{
{name: "absent", options: "[]"},
{name: "bare", options: "[no-new-privileges]", enabled: true},
{name: "equals", options: "[no-new-privileges=TRUE]", enabled: true},
{name: "colon", options: "[no-new-privileges:1]", enabled: true},
{name: "mixed", options: "[no-new-privileges, apparmor=example]", enabled: true},
{name: "explicit false", options: "[no-new-privileges=false]"},
{name: "last setting wins", options: "[no-new-privileges, no-new-privileges:0]"},
{name: "invalid", options: "[no-new-privileges=maybe]", wantErr: true},
{name: "empty", options: "[no-new-privileges=]", wantErr: true},
} {
t.Run(tc.name, func(t *testing.T) {
dict, err := loader.ParseYAML([]byte(`version: "3.8"
services:
app:
image: example
credential_spec:
file: credentials.json
security_opt: ` + tc.options))
assert.NilError(t, err)
cfg, err := loader.Load(composetypes.ConfigDetails{
Version: "3.8",
ConfigFiles: []composetypes.ConfigFile{{Config: dict}},
})
assert.NilError(t, err)
spec, err := Service(NewNamespace("test"), cfg.Services[0], nil, nil, nil, nil)
if tc.wantErr {
assert.ErrorContains(t, err, "no-new-privileges requires a boolean value")
return
}
assert.NilError(t, err)
assert.DeepEqual(t, spec.TaskTemplate.ContainerSpec.Privileges, &swarm.Privileges{
NoNewPrivileges: tc.enabled,
CredentialSpec: &swarm.CredentialSpec{File: "credentials.json"},
})
})
}
}

func TestConvertUpdateConfigOrder(t *testing.T) {
// test default behavior
updateConfig := convertUpdateConfig(&composetypes.UpdateConfig{})
Expand Down
1 change: 0 additions & 1 deletion cli/compose/types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ var UnsupportedProperties = []string{
"pid",
"privileged",
"restart",
"security_opt",
"shm_size",
"userns_mode",
}
Expand Down
6 changes: 6 additions & 0 deletions docs/reference/commandline/stack_deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ Create and update a stack from a `compose` file on the swarm.

The `deploy` command supports Compose file version `3.0` and above.

With Docker Engine 25.0 or later (API 1.44 or later), you can set
`security_opt: [no-new-privileges=true]` on a service to prevent its container
processes from gaining additional privileges. If the negotiated API version is
older than 1.44, the deployment fails before changing any stack resources when
the option is enabled. Other `security_opt` options are ignored with a warning.

```console
$ docker stack deploy --compose-file docker-compose.yml vossibility

Expand Down