/
proxmoxcluster_webhook.go
248 lines (209 loc) · 7.59 KB
/
proxmoxcluster_webhook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/*
Copyright 2023-2024 IONOS Cloud.
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 webhook contains webhooks for the custom resources.
package webhook
import (
"context"
"fmt"
"net/netip"
"regexp"
"strings"
infrav1 "github.com/ionos-cloud/cluster-api-provider-proxmox/api/v1alpha1"
"github.com/pkg/errors"
"go4.org/netipx"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
var _ admission.CustomValidator = &ProxmoxCluster{}
// ProxmoxCluster is a type that implements
// the interfaces from the admission package.
type ProxmoxCluster struct{}
// SetupWebhookWithManager sets up the webhook with the
// custom interfaces.
func (p *ProxmoxCluster) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(&infrav1.ProxmoxCluster{}).
WithValidator(p).
Complete()
}
//+kubebuilder:webhook:verbs=create;update,path=/validate-infrastructure-cluster-x-k8s-io-v1alpha1-proxmoxcluster,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,sideEffects=None,groups=infrastructure.cluster.x-k8s.io,resources=proxmoxclusters,versions=v1alpha1,name=validation.proxmoxcluster.infrastructure.cluster.x-k8s.io,admissionReviewVersions=v1
// ValidateCreate implements the creation validation function.
func (*ProxmoxCluster) ValidateCreate(_ context.Context, obj runtime.Object) (warnings admission.Warnings, err error) {
cluster, ok := obj.(*infrav1.ProxmoxCluster)
if !ok {
return warnings, apierrors.NewBadRequest(fmt.Sprintf("expected a ProxmoxCluster but got %T", obj))
}
if hasNoIPPoolConfig(cluster) {
err = errors.New("proxmox cluster must define at least one IP pool config")
warnings = append(warnings, fmt.Sprintf("proxmox cluster must define at least one IP pool config %s", cluster.GetName()))
return warnings, err
}
if err := validateControlPlaneEndpoint(cluster); err != nil {
warnings = append(warnings, fmt.Sprintf("cannot create proxmox cluster %s", cluster.GetName()))
return warnings, err
}
return warnings, nil
}
// ValidateDelete implements the deletion validation function.
func (*ProxmoxCluster) ValidateDelete(_ context.Context, _ runtime.Object) (admission.Warnings, error) {
return nil, nil
}
// ValidateUpdate implements the update validation function.
func (*ProxmoxCluster) ValidateUpdate(_ context.Context, _ runtime.Object, newObj runtime.Object) (warnings admission.Warnings, err error) {
newCluster, ok := newObj.(*infrav1.ProxmoxCluster)
if !ok {
return warnings, apierrors.NewBadRequest(fmt.Sprintf("expected a ProxmoxCluster but got %T", newCluster))
}
if err := validateControlPlaneEndpoint(newCluster); err != nil {
warnings = append(warnings, fmt.Sprintf("cannot update proxmox cluster %s", newCluster.GetName()))
return warnings, err
}
return warnings, nil
}
func validateControlPlaneEndpoint(cluster *infrav1.ProxmoxCluster) error {
ep := cluster.Spec.ControlPlaneEndpoint
gk, name := cluster.GroupVersionKind().GroupKind(), cluster.GetName()
endpoint := ep.Host
addr, err := netip.ParseAddr(endpoint)
/*
No further validation is done on hostnames. Checking DNS records
incures a lot of complexity. To list a few of the problems:
- DNS TTL will lead to incorrect results
- IP addresses can be PTR records
- Both A and AAAA records would need checking
- A record can have multiple entries, each of which need to be checked
- A valid record can start with _, but that is not a valid hostname
- ...
Most importantly, cluster-api does not validate controlPlaneEndpoint
at all.
*/
match := isHostname(endpoint)
if match {
return nil
}
if err != nil {
return apierrors.NewInvalid(
gk,
name,
field.ErrorList{
field.Invalid(
field.NewPath("spec", "controlplaneEndpoint"), endpoint, "provided endpoint address is not a valid IP or FQDN"),
})
}
// If the passed control-plane endppoint is an IPv6 address, wrap it in [], so it can properly pass ParseAddrPort validation
if addr.Is6() {
endpoint = fmt.Sprintf("[%s]", endpoint)
}
ipAddr, err := netip.ParseAddrPort(fmt.Sprintf("%s:%d", endpoint, ep.Port))
if err != nil {
return apierrors.NewInvalid(
gk,
name,
field.ErrorList{
field.Invalid(
field.NewPath("spec", "controlplaneEndpoint"), fmt.Sprintf("%s:%d", endpoint, ep.Port), "provided endpoint is not in a valid IP and port format"),
})
}
// IPv4
if cluster.Spec.IPv4Config != nil {
set, err := buildSetFromAddresses(cluster.Spec.IPv4Config.Addresses)
if err != nil {
return apierrors.NewInvalid(
gk,
name,
field.ErrorList{
field.Invalid(
field.NewPath("spec", "IPv4Config", "addresses"), cluster.Spec.IPv4Config.Addresses, "provided addresses are not valid IP addresses, ranges or CIDRs"),
})
}
if set.Contains(ipAddr.Addr()) {
return apierrors.NewInvalid(
gk,
name,
field.ErrorList{
field.Invalid(
field.NewPath("spec", "IPv4Config", "addresses"), cluster.Spec.IPv4Config.Addresses, "addresses may not contain the endpoint IP"),
})
}
}
// IPV6
if cluster.Spec.IPv6Config != nil {
set6, err := buildSetFromAddresses(cluster.Spec.IPv6Config.Addresses)
if err != nil {
return apierrors.NewInvalid(
gk,
name,
field.ErrorList{
field.Invalid(
field.NewPath("spec", "IPv6Config", "addresses"), cluster.Spec.IPv6Config.Addresses, "provided addresses are not valid IP addresses, ranges or CIDRs"),
})
}
if set6.Contains(ipAddr.Addr()) {
return apierrors.NewInvalid(
gk,
name,
field.ErrorList{
field.Invalid(
field.NewPath("spec", "IPv6Config", "addresses"), cluster.Spec.IPv6Config.Addresses, "addresses may not contain the endpoint IP"),
})
}
}
return nil
}
func buildSetFromAddresses(addresses []string) (*netipx.IPSet, error) {
builder := netipx.IPSetBuilder{}
for _, address := range addresses {
switch {
case strings.Contains(address, "-"):
ipRange, err := netipx.ParseIPRange(address)
if err != nil {
return nil, err
}
builder.AddRange(ipRange)
case strings.Contains(address, "/"):
ipPref, err := netip.ParsePrefix(address)
if err != nil {
return nil, err
}
builder.AddPrefix(ipPref)
default:
ipAddress, err := netip.ParseAddr(address)
if err != nil {
return nil, err
}
builder.Add(ipAddress)
}
}
set, err := builder.IPSet()
if err != nil {
return nil, err
}
return set, nil
}
func hasNoIPPoolConfig(cluster *infrav1.ProxmoxCluster) bool {
return cluster.Spec.IPv4Config == nil && cluster.Spec.IPv6Config == nil
}
func isHostname(h string) bool {
// shortname is up to 253 bytes long
shortname := `([a-z0-9]{1,253}|[a-z0-9][a-z0-9-]{1,251}[a-z0-9])`
// hostname is optional in a domain
hostname := `([a-z0-9]{1,63}|[a-z0-9][a-z0-9-]{1,61}[a-z0-9]\.)?`
domain := `((([a-z0-9]{1,63}|[a-z0-9][a-z0-9-]{1,61}[a-z0-9])\.)+?[a-z]{2,63})`
// make hostname match case insensitive, match complete string
hostmatch := `(?i)^(` + shortname + `|` + hostname + domain + `)$`
match, _ := regexp.Match(hostmatch, []byte(h))
return match
}