Skip to content

Commit a7c1cb4

Browse files
committed
testing: address G115 integer overflow conversion warnings and re-enable linter
Each G115 (gosec) integer overflow conversion has been evaluated and annotated with an inline //nolint:gosec comment explaining why the conversion is safe: - opts/swarmopts/port.go: port numbers are in [0, 65535], within uint32 - cli/command/service/logs.go: replica count is far below math.MaxInt - cli/compose/convert/service.go: healthcheck retries and restart policy MaximumRetryCount are small, non-negative values - cli/command/container/cp.go: len() is always non-negative - cli/command/container/opts.go: ioMaxBandwidth is validated non-negative - cli/command/container/stats_helpers.go: time diff between reads is positive - cli/command/image/tree.go: terminal width fits well within int range - cli/command/service/progress/progress.go: replica/running/job counts are far below math.MaxInt; mappedSlot is a positive slot number Remove the global G115 exclusion from .golangci.yml now that all cases have been individually addressed. Fixes #5584
1 parent 499a4c5 commit a7c1cb4

File tree

9 files changed

+16
-17
lines changed

9 files changed

+16
-17
lines changed

.golangci.yml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,6 @@ linters:
109109
gosec:
110110
excludes:
111111
- G104 # G104: Errors unhandled; (TODO: reduce unhandled errors, or explicitly ignore)
112-
- G115 # G115: integer overflow conversion; (TODO: verify these: https://github.com/docker/cli/issues/5584)
113112
- G306 # G306: Expect WriteFile permissions to be 0600 or less (too restrictive; also flags "0o644" permissions)
114113
- G307 # G307: Deferring unsafe method "*os.File" on type "Close" (also EXC0008); (TODO: evaluate these and fix where needed: G307: Deferring unsafe method "*os.File" on type "Close")
115114

cli/command/container/cp.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ func copyProgress(ctx context.Context, dst io.Writer, header string, total *int6
108108
}
109109

110110
// Write to the buffer first to avoid flickering and context switching
111-
fmt.Fprint(buf, aec.Column(uint(len(header)+1)))
111+
fmt.Fprint(buf, aec.Column(uint(len(header)+1))) //nolint:gosec // G115: len() is always non-negative, safe to convert to uint
112112
fmt.Fprint(buf, aec.EraseLine(aec.EraseModes.Tail))
113113
fmt.Fprint(buf, progressHumanSize(n))
114114

cli/command/container/opts.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -635,7 +635,7 @@ func parse(flags *pflag.FlagSet, copts *containerOptions, serverOS string) (*con
635635
BlkioDeviceReadIOps: copts.deviceReadIOps.GetList(),
636636
BlkioDeviceWriteIOps: copts.deviceWriteIOps.GetList(),
637637
IOMaximumIOps: copts.ioMaxIOps,
638-
IOMaximumBandwidth: uint64(copts.ioMaxBandwidth),
638+
IOMaximumBandwidth: uint64(copts.ioMaxBandwidth), //nolint:gosec // G115: ioMaxBandwidth is validated to be non-negative
639639
Ulimits: copts.ulimits.GetList(),
640640
DeviceCgroupRules: copts.deviceCgroupRules.GetSlice(),
641641
Devices: deviceMappings,

cli/command/container/stats_helpers.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ func calculateCPUPercentUnix(previousCPU container.CPUStats, curCPUStats contain
185185

186186
func calculateCPUPercentWindows(v *container.StatsResponse) float64 {
187187
// Max number of 100ns intervals between the previous time read and now
188-
possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) // Start with number of ns intervals
188+
possIntervals := uint64(v.Read.Sub(v.PreRead).Nanoseconds()) //nolint:gosec // G115: time difference between CPU stat reads is always positive
189189
possIntervals /= 100 // Convert to number of 100ns intervals
190190
possIntervals *= uint64(v.NumProcs) // Multiply by the number of processors
191191

cli/command/image/tree.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ func printImageTree(outs command.Streams, view treeView) {
349349
// available for image names and removes any columns that would be too narrow
350350
// to display their content.
351351
func adjustColumns(width uint, columns []imgColumn, images []topImage) []imgColumn {
352-
nameWidth := int(width)
352+
nameWidth := int(width) //nolint:gosec // G115: terminal width is a small value well within int range
353353
if nameWidth > 0 {
354354
for idx, h := range columns {
355355
if h.Width == 0 {

cli/command/service/logs.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ func runLogs(ctx context.Context, dockerCli command.Cli, opts *logsOptions) erro
127127
if service.Service.Spec.Mode.Replicated != nil && service.Service.Spec.Mode.Replicated.Replicas != nil {
128128
// if replicas are initialized, figure out if we need to pad them
129129
replicas := *service.Service.Spec.Mode.Replicated.Replicas
130-
maxLength = getMaxLength(int(replicas))
130+
maxLength = getMaxLength(int(replicas)) //nolint:gosec // G115: replica count is far below math.MaxInt in practice
131131
}
132132

133133
// we can't prettify tty logs. tell the user that this is the case.

cli/command/service/progress/progress.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ func (u *replicatedProgressUpdater) update(service swarm.Service, tasks []swarm.
301301
u.slotMap = make(map[int]int)
302302

303303
// Draw progress bars in order
304-
writeOverallProgress(u.progressOut, 0, int(replicas), rollback)
304+
writeOverallProgress(u.progressOut, 0, int(replicas), rollback) //nolint:gosec // G115: replica count is far below math.MaxInt in practice
305305

306306
if replicas <= maxProgressBars {
307307
for i := uint64(1); i <= replicas; i++ {
@@ -340,7 +340,7 @@ func (u *replicatedProgressUpdater) update(service swarm.Service, tasks []swarm.
340340
}
341341

342342
if !u.done {
343-
writeOverallProgress(u.progressOut, int(running), int(replicas), rollback)
343+
writeOverallProgress(u.progressOut, int(running), int(replicas), rollback) //nolint:gosec // G115: running/replica counts are far below math.MaxInt in practice
344344

345345
if running == replicas {
346346
u.done = true
@@ -383,7 +383,7 @@ func (*replicatedProgressUpdater) tasksBySlot(tasks []swarm.Task, activeNodes ma
383383
}
384384

385385
func (u *replicatedProgressUpdater) writeTaskProgress(task swarm.Task, mappedSlot int, replicas uint64) {
386-
if u.done || replicas > maxProgressBars || uint64(mappedSlot) > replicas {
386+
if u.done || replicas > maxProgressBars || uint64(mappedSlot) > replicas { //nolint:gosec // G115: mappedSlot is a positive task slot number, safe to convert to uint64
387387
return
388388
}
389389

@@ -572,8 +572,8 @@ type replicatedJobProgressUpdater struct {
572572
}
573573

574574
func newReplicatedJobProgressUpdater(service swarm.Service, progressOut progress.Output) *replicatedJobProgressUpdater {
575-
concurrent := int(*service.Spec.Mode.ReplicatedJob.MaxConcurrent)
576-
total := int(*service.Spec.Mode.ReplicatedJob.TotalCompletions)
575+
concurrent := int(*service.Spec.Mode.ReplicatedJob.MaxConcurrent) //nolint:gosec // G115: job concurrency count is far below math.MaxInt in practice
576+
total := int(*service.Spec.Mode.ReplicatedJob.TotalCompletions) //nolint:gosec // G115: job total completions count is far below math.MaxInt in practice
577577

578578
return &replicatedJobProgressUpdater{
579579
progressOut: progressOut,

cli/compose/convert/service.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -460,7 +460,7 @@ func convertHealthcheck(healthcheck *composetypes.HealthCheckConfig) (*container
460460
startInterval = time.Duration(*healthcheck.StartInterval)
461461
}
462462
if healthcheck.Retries != nil {
463-
retries = int(*healthcheck.Retries)
463+
retries = int(*healthcheck.Retries) //nolint:gosec // G115: healthcheck retry count is a small value, safe to convert
464464
}
465465
return &container.HealthConfig{
466466
Test: healthcheck.Test,
@@ -487,7 +487,7 @@ func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*
487487
Condition: swarm.RestartPolicyConditionAny,
488488
}, nil
489489
case policy.IsOnFailure():
490-
attempts := uint64(policy.MaximumRetryCount)
490+
attempts := uint64(policy.MaximumRetryCount) //nolint:gosec // G115: MaximumRetryCount is a non-negative value, safe to convert
491491
return &swarm.RestartPolicy{
492492
Condition: swarm.RestartPolicyConditionOnFailure,
493493
MaxAttempts: &attempts,

opts/swarmopts/port.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ func (p *PortOpt) Set(value string) error {
8080
return fmt.Errorf("invalid target port (%s): value must be an integer: %w", val, err)
8181
}
8282

83-
pConfig.TargetPort = uint32(tPort)
83+
pConfig.TargetPort = uint32(tPort) //nolint:gosec // G115: port numbers are in range [0, 65535], within uint32 bounds
8484
case portOptPublishedPort:
8585
pPort, err := strconv.ParseUint(val, 10, 16)
8686
if err != nil {
@@ -91,7 +91,7 @@ func (p *PortOpt) Set(value string) error {
9191
return fmt.Errorf("invalid published port (%s): value must be an integer: %w", val, err)
9292
}
9393

94-
pConfig.PublishedPort = uint32(pPort)
94+
pConfig.PublishedPort = uint32(pPort) //nolint:gosec // G115: port numbers are in range [0, 65535], within uint32 bounds
9595
default:
9696
return fmt.Errorf("invalid field key: %s", key)
9797
}
@@ -176,8 +176,8 @@ func ConvertPortToPortConfig(
176176
ports = append(ports, swarm.PortConfig{
177177
// TODO Name: ?
178178
Protocol: portProto.Proto(),
179-
TargetPort: uint32(portProto.Num()),
180-
PublishedPort: uint32(p.Num()),
179+
TargetPort: uint32(portProto.Num()), //nolint:gosec // G115: port numbers are in range [0, 65535], within uint32 bounds
180+
PublishedPort: uint32(p.Num()), //nolint:gosec // G115: port numbers are in range [0, 65535], within uint32 bounds
181181
PublishMode: swarm.PortConfigPublishModeIngress,
182182
})
183183
}

0 commit comments

Comments
 (0)