From aa5ed3c2fd9f66e6c475fac066d5ce216f2315f1 Mon Sep 17 00:00:00 2001 From: AnAverageBeing Date: Sat, 5 Dec 2026 08:54:26 +0000 Subject: [PATCH] fix(scale): reject negative replica counts from CLI flags The compose file loader already refuses a negative `scale:` or `deploy.replicas:` with "must be greater than or equal to 0", but the CLI accepted the same value through a flag: $ docker compose scale web=-1 $ docker compose up --scale web=-1 -d $ docker compose create --scale web=-1 Those all exited 0. A negative count is not merely redundant with zero: reconcile.go treats only `expectedScale == 0` as the scale-to-nothing case, so -1 falls through to planning pre-start hook runners for a service that will have no replicas. Validate both entry points: - ScaleOptions.Validate() so api.Compose.Scale refuses it too, matching CreateOptions.Validate and UpOptions.Validate, which both run before their Run() body. - the CLI parsers, so the user gets the error before any project load or remote-stack prompt. Both raise api.InvalidOptionError, the existing type for this case. Also give `create --scale web=abc` a proper message instead of the raw strconv error from the branch directly above. Fixes #14482 Signed-off-by: AnAverageBeing --- cmd/compose/create.go | 8 ++- cmd/compose/scale.go | 6 ++ cmd/compose/scale_test.go | 131 ++++++++++++++++++++++++++++++++++++++ cmd/compose/up_test.go | 3 + pkg/api/api.go | 17 +++++ pkg/compose/scale.go | 3 + pkg/compose/scale_test.go | 31 +++++++++ 7 files changed, 198 insertions(+), 1 deletion(-) create mode 100644 cmd/compose/scale_test.go diff --git a/cmd/compose/create.go b/cmd/compose/create.go index ba81a40a06d..81cff9e4129 100644 --- a/cmd/compose/create.go +++ b/cmd/compose/create.go @@ -213,7 +213,13 @@ func applyScaleOpts(project *types.Project, opts []string) error { } replicas, err := strconv.Atoi(val) if err != nil { - return err + return fmt.Errorf("invalid --scale option %q: %w", scale, err) + } + if replicas < 0 { + return &api.InvalidOptionError{ + Option: "scale", + Reason: fmt.Sprintf("%s: replica count must be greater than or equal to 0", scale), + } } err = setServiceScale(project, name, replicas) if err != nil { diff --git a/cmd/compose/scale.go b/cmd/compose/scale.go index ae474079a6d..55ea7ebc9f5 100644 --- a/cmd/compose/scale.go +++ b/cmd/compose/scale.go @@ -116,6 +116,12 @@ func parseServicesReplicasArgs(args []string) (map[string]int, error) { if err != nil { return nil, fmt.Errorf("invalid scale specifier: can't parse replica value as int: %v", arg) } + if intValue < 0 { + return nil, &api.InvalidOptionError{ + Option: "scale", + Reason: fmt.Sprintf("%s: replica count must be greater than or equal to 0", arg), + } + } serviceReplicaTuples[key] = intValue } return serviceReplicaTuples, nil diff --git a/cmd/compose/scale_test.go b/cmd/compose/scale_test.go new file mode 100644 index 00000000000..104e551a489 --- /dev/null +++ b/cmd/compose/scale_test.go @@ -0,0 +1,131 @@ +/* + Copyright 2020 Docker Compose CLI authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package compose + +import ( + "errors" + "testing" + + "github.com/docker/compose/v5/pkg/api" + "gotest.tools/v3/assert" +) + +func TestParseServicesReplicasArgs(t *testing.T) { + tests := []struct { + name string + args []string + want map[string]int + wantErr string + }{ + { + name: "single service", + args: []string{"web=2"}, + want: map[string]int{"web": 2}, + }, + { + name: "multiple services", + args: []string{"web=2", "db=1"}, + want: map[string]int{"web": 2, "db": 1}, + }, + { + name: "zero replicas is allowed", + args: []string{"web=0"}, + want: map[string]int{"web": 0}, + }, + { + name: "negative replicas is rejected", + args: []string{"web=-1"}, + wantErr: "invalid option (scale): web=-1: replica count must be greater than or equal to 0", + }, + { + name: "one negative among valid services is rejected", + args: []string{"web=2", "db=-3"}, + wantErr: "invalid option (scale): db=-3: replica count must be greater than or equal to 0", + }, + { + name: "missing equals sign", + args: []string{"web"}, + wantErr: "invalid scale specifier: web", + }, + { + name: "empty value", + args: []string{"web="}, + wantErr: "invalid scale specifier: web=", + }, + { + name: "non numeric value", + args: []string{"web=abc"}, + wantErr: "invalid scale specifier: can't parse replica value as int: web=abc", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := parseServicesReplicasArgs(tt.args) + if tt.wantErr != "" { + assert.ErrorContains(t, err, tt.wantErr) + assert.Assert(t, got == nil, "a rejected specifier must not return partial results") + return + } + assert.NilError(t, err) + assert.DeepEqual(t, got, tt.want) + }) + } +} + +// TestParseServicesReplicasArgsNegativeIsInvalidOption pins the error kind the +// rest of the package relies on, so the CLI failure is indistinguishable from +// the same rejection made through the SDK options. +func TestParseServicesReplicasArgsNegativeIsInvalidOption(t *testing.T) { + _, err := parseServicesReplicasArgs([]string{"web=-1"}) + assert.Assert(t, errors.Is(err, api.ErrInvalidOption)) + + var invalid *api.InvalidOptionError + assert.Assert(t, errors.As(err, &invalid)) + assert.Equal(t, invalid.Option, "scale") +} + +// TestScaleOptionsValidate covers the SDK path, which bypasses the CLI parser +// entirely. api.Compose.Scale must refuse a negative count before touching the +// project model. +func TestScaleOptionsValidate(t *testing.T) { + tests := []struct { + name string + replicas map[string]int + wantErr bool + }{ + {name: "empty is valid", replicas: nil}, + {name: "positive is valid", replicas: map[string]int{"web": 2}}, + {name: "zero is valid", replicas: map[string]int{"web": 0}}, + {name: "negative is rejected", replicas: map[string]int{"web": -1}, wantErr: true}, + {name: "one negative among valid is rejected", replicas: map[string]int{"web": 2, "db": -1}, wantErr: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := api.ScaleOptions{Replicas: tt.replicas}.Validate() + if !tt.wantErr { + assert.NilError(t, err) + return + } + assert.Assert(t, errors.Is(err, api.ErrInvalidOption)) + var invalid *api.InvalidOptionError + assert.Assert(t, errors.As(err, &invalid)) + assert.Equal(t, invalid.Option, "Replicas") + }) + } +} diff --git a/cmd/compose/up_test.go b/cmd/compose/up_test.go index fbce5a6f030..b7971c0e825 100644 --- a/cmd/compose/up_test.go +++ b/cmd/compose/up_test.go @@ -82,6 +82,9 @@ func TestApplyScaleOpt(t *testing.T) { err = applyScaleOpts(&p, []string{"=2"}) assert.Error(t, err, `invalid --scale option "=2". Should be SERVICE=NUM`) + + err = applyScaleOpts(&p, []string{"foo=-1"}) + assert.ErrorContains(t, err, `invalid option (scale): foo=-1: replica count must be greater than or equal to 0`) } func TestUpOptions_OnExit(t *testing.T) { diff --git a/pkg/api/api.go b/pkg/api/api.go index 11c3bdcd3fc..f51635a3ccf 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -254,6 +254,23 @@ type ScaleOptions struct { Services []string } +// Validate checks that every requested replica count is non-negative. The +// compose file loader already rejects a negative `scale:` or `deploy.replicas:` +// (see checkServiceScale in compose-go), so an operation must not accept +// through its options what it would reject through a file. Zero is valid and +// scales a service down to nothing. +func (o ScaleOptions) Validate() error { + for name, replicas := range o.Replicas { + if replicas < 0 { + return &InvalidOptionError{ + Option: "Replicas", + Reason: fmt.Sprintf("service %q must have a replica count greater than or equal to 0, got %d", name, replicas), + } + } + } + return nil +} + type WaitOptions struct { // Services passed in the command line to be waited Services []string diff --git a/pkg/compose/scale.go b/pkg/compose/scale.go index d82133c1c29..f6ae878d9d5 100644 --- a/pkg/compose/scale.go +++ b/pkg/compose/scale.go @@ -27,6 +27,9 @@ import ( ) func (s *composeService) Scale(ctx context.Context, project *types.Project, options api.ScaleOptions) error { + if err := options.Validate(); err != nil { + return err + } return Run(ctx, tracing.SpanWrapFunc("project/scale", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error { if err := applyReplicas(project, options.Replicas); err != nil { return err diff --git a/pkg/compose/scale_test.go b/pkg/compose/scale_test.go index 21a48e11766..5fa7940e482 100644 --- a/pkg/compose/scale_test.go +++ b/pkg/compose/scale_test.go @@ -16,9 +16,12 @@ limitations under the License. package compose import ( + "context" + "errors" "testing" "github.com/compose-spec/compose-go/v2/types" + "github.com/docker/compose/v5/pkg/api" "gotest.tools/v3/assert" ) @@ -40,3 +43,31 @@ func TestApplyReplicas(t *testing.T) { err = applyReplicas(project, map[string]int{"unknown": 1}) assert.ErrorContains(t, err, "no such service: unknown") } + +// TestScaleRejectsNegativeReplicasBeforeSideEffects asserts the SDK entry point +// refuses a negative replica count itself, before it mutates the project model +// or reaches the backend. The CLI parser is not in this path. +func TestScaleRejectsNegativeReplicasBeforeSideEffects(t *testing.T) { + project := &types.Project{ + Services: types.Services{ + "web": types.ServiceConfig{Name: "web"}, + }, + } + + svc := &composeService{} + err := svc.Scale(context.Background(), project, api.ScaleOptions{ + Replicas: map[string]int{"web": -1}, + }) + + assert.Assert(t, err != nil, "a negative replica count must be refused") + assert.Assert(t, errors.Is(err, api.ErrInvalidOption)) + + var invalid *api.InvalidOptionError + assert.Assert(t, errors.As(err, &invalid)) + assert.Equal(t, invalid.Option, "Replicas") + + // The project model must be untouched: SetScale must not have run. + service, err := project.GetService("web") + assert.NilError(t, err) + assert.Assert(t, service.Scale == nil, "Scale must not be applied when the options are invalid") +}