Skip to content

Commit 6f9901c

Browse files
committed
nat: ParsePortSpec: validate port before proto
commit f388222 made an optimization to handle validating the proto before parsing port-numbers, but as a result changed the error returned if the port was missing. This patch moves the check for empty container ports to the start to keep the old behavior. The error-message(s) can probably be improved a bit, but this keeps the existing output. Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
1 parent 34239ab commit 6f9901c

2 files changed

Lines changed: 35 additions & 3 deletions

File tree

nat/nat.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,10 @@ func splitParts(rawport string) (hostIP, hostPort, containerPort string) {
173173
func ParsePortSpec(rawPort string) ([]PortMapping, error) {
174174
ip, hostPort, containerPort := splitParts(rawPort)
175175
proto, containerPort := SplitProtoPort(containerPort)
176+
if containerPort == "" {
177+
return nil, fmt.Errorf("no port specified: %s<empty>", rawPort)
178+
}
179+
176180
proto = strings.ToLower(proto)
177181
if err := validateProto(proto); err != nil {
178182
return nil, err
@@ -189,9 +193,6 @@ func ParsePortSpec(rawPort string) ([]PortMapping, error) {
189193
if ip != "" && net.ParseIP(ip) == nil {
190194
return nil, errors.New("invalid IP address: " + ip)
191195
}
192-
if containerPort == "" {
193-
return nil, fmt.Errorf("no port specified: %s<empty>", rawPort)
194-
}
195196

196197
startPort, endPort, err := ParsePortRange(containerPort)
197198
if err != nil {

nat/nat_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,37 @@ func TestSplitProtoPort(t *testing.T) {
240240
})
241241
}
242242
}
243+
func TestParsePortSpecEmptyContainerPort(t *testing.T) {
244+
tests := []struct {
245+
name string
246+
spec string
247+
expError string
248+
}{
249+
{
250+
name: "empty spec",
251+
spec: "",
252+
expError: `no port specified: <empty>`,
253+
},
254+
{
255+
name: "empty container port",
256+
spec: `0.0.0.0:1234-1235:/tcp`,
257+
expError: `no port specified: 0.0.0.0:1234-1235:/tcp<empty>`,
258+
},
259+
{
260+
name: "empty container port and proto",
261+
spec: `0.0.0.0:1234-1235:`,
262+
expError: `no port specified: 0.0.0.0:1234-1235:<empty>`,
263+
},
264+
}
265+
for _, tc := range tests {
266+
t.Run(tc.name, func(t *testing.T) {
267+
_, err := ParsePortSpec(tc.spec)
268+
if err == nil || err.Error() != tc.expError {
269+
t.Fatalf("expected %v, got: %v", tc.expError, err)
270+
}
271+
})
272+
}
273+
}
243274

244275
func TestParsePortSpecFull(t *testing.T) {
245276
portMappings, err := ParsePortSpec("0.0.0.0:1234-1235:3333-3334/tcp")

0 commit comments

Comments
 (0)