Skip to content

Commit e07723c

Browse files
ndeloofglours
authored andcommitted
validate IP address used in port long syntax
Signed-off-by: Nicolas De Loof <[email protected]>
1 parent e0a0232 commit e07723c

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

validation/validation.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package validation
1818

1919
import (
2020
"fmt"
21+
"net"
2122
"strings"
2223

2324
"github.com/compose-spec/compose-go/v2/tree"
@@ -29,6 +30,7 @@ var checks = map[tree.Path]checkerFunc{
2930
"volumes.*": checkVolume,
3031
"configs.*": checkFileObject("file", "environment", "content"),
3132
"secrets.*": checkFileObject("file", "environment"),
33+
"services.*.ports.*": checkIPAddress,
3234
"services.*.develop.watch.*.path": checkPath,
3335
"services.*.deploy.resources.reservations.devices.*": checkDeviceRequest,
3436
"services.*.gpus.*": checkDeviceRequest,
@@ -105,3 +107,13 @@ func checkDeviceRequest(value any, p tree.Path) error {
105107
}
106108
return nil
107109
}
110+
111+
func checkIPAddress(value any, p tree.Path) error {
112+
if v, ok := value.(map[string]any); ok {
113+
ip, ok := v["host_ip"]
114+
if ok && net.ParseIP(ip.(string)) == nil {
115+
return fmt.Errorf("%s: invalid ip address: %s", p, ip)
116+
}
117+
}
118+
return nil
119+
}

validation/validation_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,49 @@ external: true
9494
})
9595
}
9696
}
97+
98+
func TestIPAddress(t *testing.T) {
99+
checker := checks["services.*.ports.*"]
100+
tests := []struct {
101+
name string
102+
input string
103+
err string
104+
}{
105+
{
106+
name: "port long syntax, invalid IP",
107+
input: `
108+
host_ip: notavalidip
109+
target: 1234
110+
published: "1234"
111+
`,
112+
err: "configs.test.ports[0]: invalid ip address: notavalidip",
113+
},
114+
{
115+
name: "port long syntax, no IP",
116+
input: `
117+
target: 1234
118+
published: "1234"
119+
`,
120+
},
121+
{
122+
name: "port long syntax, valid IP",
123+
input: `
124+
host_ip: 192.168.3.4
125+
target: 1234
126+
published: "1234"
127+
`,
128+
},
129+
}
130+
131+
for _, tt := range tests {
132+
var input map[string]any
133+
err := yaml.Unmarshal([]byte(tt.input), &input)
134+
assert.NilError(t, err)
135+
err = checker(input, tree.NewPath("configs.test.ports[0]"))
136+
if tt.err == "" {
137+
assert.NilError(t, err)
138+
} else {
139+
assert.Equal(t, tt.err, err.Error())
140+
}
141+
}
142+
}

0 commit comments

Comments
 (0)