Skip to content

Commit cf3fce2

Browse files
Merge pull request #143 from thaJeztah/fix_ParsePortSpec
nat: ParsePortSpec: validate port before proto
2 parents 210a62a + ccab5a8 commit cf3fce2

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

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: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,38 @@ func TestSplitProtoPort(t *testing.T) {
241241
}
242242
}
243243

244+
func TestParsePortSpecEmptyContainerPort(t *testing.T) {
245+
tests := []struct {
246+
name string
247+
spec string
248+
expError string
249+
}{
250+
{
251+
name: "empty spec",
252+
spec: "",
253+
expError: `no port specified: <empty>`,
254+
},
255+
{
256+
name: "empty container port",
257+
spec: `0.0.0.0:1234-1235:/tcp`,
258+
expError: `no port specified: 0.0.0.0:1234-1235:/tcp<empty>`,
259+
},
260+
{
261+
name: "empty container port and proto",
262+
spec: `0.0.0.0:1234-1235:`,
263+
expError: `no port specified: 0.0.0.0:1234-1235:<empty>`,
264+
},
265+
}
266+
for _, tc := range tests {
267+
t.Run(tc.name, func(t *testing.T) {
268+
_, err := ParsePortSpec(tc.spec)
269+
if err == nil || err.Error() != tc.expError {
270+
t.Fatalf("expected %v, got: %v", tc.expError, err)
271+
}
272+
})
273+
}
274+
}
275+
244276
func TestParsePortSpecFull(t *testing.T) {
245277
portMappings, err := ParsePortSpec("0.0.0.0:1234-1235:3333-3334/tcp")
246278
if err != nil {

0 commit comments

Comments
 (0)