-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.go
495 lines (427 loc) · 12.4 KB
/
models.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
package config
import (
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"regexp"
"sort"
"strconv"
"strings"
"github.com/wrouesnel/poller_exporter/pkg/certutils"
"github.com/samber/lo"
"github.com/pkg/errors"
"go.uber.org/zap"
)
const (
TLSCertificatePoolMaxNonFileEntryReturn int = 50
)
var (
ErrInvalidInputType = errors.New("invalid input type for decoder")
)
// HTTPStatusRange is a range of HTTP status codes which can be specifid in YAML using human-friendly ranging notation.
type HTTPStatusRange map[int]bool
// FromString initializes a new HTTPStatusRange from the given string specifier
//
//nolint:cyclop
func (hsr *HTTPStatusRange) FromString(ranges string) error {
const HTTPStatusRangeBase int = 10
const HTTPStatusRangeBitSize int = 32
*hsr = make(HTTPStatusRange)
var statusCodes []int
fields := strings.Fields(ranges)
for _, v := range fields {
code, err := strconv.ParseInt(v, HTTPStatusRangeBase, HTTPStatusRangeBitSize)
if err == nil {
statusCodes = append(statusCodes, int(code))
continue
}
// Didn't work, but might be a range
if strings.Count(v, "-") == 0 || strings.Count(v, "-") > 1 {
return errors.New("HTTPStatusRange.FromString: not a valid range")
}
// Is a range.
statusRange := strings.Split(v, "-")
startCode, err := strconv.ParseInt(statusRange[0], HTTPStatusRangeBase, HTTPStatusRangeBitSize)
if err != nil {
return errors.Wrapf(err, "HTTPStatusRange.FromString failed: startCode: %s", v)
}
endCode, err := strconv.ParseInt(statusRange[1], HTTPStatusRangeBase, HTTPStatusRangeBitSize)
if err != nil {
return errors.Wrapf(err, "HTTPStatusRange.FromString failed: endCode: %s", v)
}
// Loop over the codes in sequential order
if startCode < endCode {
for i := startCode; i < endCode+1; i++ {
statusCodes = append(statusCodes, int(i))
}
} else {
for i := startCode; i > endCode-1; i-- {
statusCodes = append(statusCodes, int(i))
}
}
}
for _, v := range statusCodes {
(*hsr)[v] = true
}
return nil
}
// UnmarshalText implements the encoding.TextUnmarshaler.
func (hsr *HTTPStatusRange) UnmarshalText(text []byte) error {
return hsr.FromString(string(text))
}
// MarshalText implements the encoding.TextMarshaler.
func (hsr HTTPStatusRange) MarshalText() ([]byte, error) {
statusCodes := make([]int, 0, len(hsr))
var output []string
for k := range hsr {
statusCodes = append(statusCodes, k)
}
sort.Ints(statusCodes)
// This could probably be neater, but its what you get when you iterate.
idx := 0
for {
start := statusCodes[idx]
prev := start
for {
idx++
if idx >= len(statusCodes) {
break
}
if statusCodes[idx]-prev != 1 {
// Check if it's a single number
if statusCodes[idx-1] == start {
output = append(output, fmt.Sprintf("%d", start))
} else {
output = append(output, fmt.Sprintf("%d-%d", start, statusCodes[idx-1]))
}
break
}
prev = statusCodes[idx]
}
if idx >= len(statusCodes) {
break
}
}
return []byte(strings.Join(output, " ")), nil
}
// HTTPVerb wraps string to ensure that verbs are uppercase. It doesn't check if they're
// valid to allow people to do stupid things with them if they want.
type HTTPVerb string
func (d HTTPVerb) String() string {
return string(d)
}
// MarshalText implements the encoding.TextMarshaler interface.
func (d *HTTPVerb) MarshalText() ([]byte, error) {
return []byte(*d), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (d *HTTPVerb) UnmarshalText(text []byte) error {
*d = HTTPVerb(strings.ToUpper(string(text)))
switch *d {
case http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace:
return nil
default:
return errors.Wrapf(ErrInvalidInputType, "HTTPVerb.UnmarshalText: invalid HTTP verb")
}
}
// Bytes implements a custom []byte slice implemented TextMarshaller so base64
// binary content can be passed n.
type Bytes []byte
// MarshalText implements the encoding.TextMarshaler interface.
func (d *Bytes) MarshalText() ([]byte, error) {
return []byte(base64.StdEncoding.EncodeToString(*d)), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (d *Bytes) UnmarshalText(text []byte) error {
decoded, err := base64.StdEncoding.DecodeString(string(text))
*d = decoded
return errors.Wrapf(err, "Bytes.UnmarshalText: base64 decoding failed")
}
// Regexp encapsulates a regexp.Regexp and makes it YAML marshallable.
type Regexp struct {
*regexp.Regexp
}
// MarshalText implements the encoding.TextMarshaler interface.
func (r *Regexp) MarshalText() ([]byte, error) {
return []byte(r.Regexp.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (r *Regexp) UnmarshalText(text []byte) error {
var err error
r.Regexp, err = regexp.Compile(string(text))
if err != nil {
return errors.Wrapf(err, "UnmarshalText failed: %v", string(text))
}
return nil
}
// URL is a custom URL type that allows validation at configuration load time.
type URL struct {
*url.URL
}
func NewURL(url string) (URL, error) {
u := URL{nil}
err := u.UnmarshalText([]byte(url))
return u, err
}
// UnmarshalYAML implements the yaml.Unmarshaler interface for URLs.
func (u *URL) UnmarshalText(text []byte) error {
urlp, err := url.Parse(string(text))
if err != nil {
return errors.Wrap(err, "URL.UnmarshalText failed")
}
u.URL = urlp
return nil
}
// MarshalYAML implements the yaml.Marshaler interface for URLs.
func (u *URL) MarshalText() ([]byte, error) {
if u.URL != nil {
return []byte(u.String()), nil
}
return []byte(""), nil
}
// TLSCertificateMap encodes a list of certificates and stores them in a hashmap
// for easy lookups. It is similar to the standard library CertPool.
type Sum224 [sha256.Size224]byte
type TLSCertificateMap struct {
certMap map[Sum224]*x509.Certificate
original []string
}
func (t *TLSCertificateMap) GetCerts() []*x509.Certificate {
if t.certMap == nil {
return []*x509.Certificate{}
}
return lo.MapToSlice(t.certMap, func(_ Sum224, v *x509.Certificate) *x509.Certificate {
return v
})
}
func (t *TLSCertificateMap) HasCert(cert *x509.Certificate) bool {
if t.certMap == nil {
return false
}
_, found := t.certMap[sha256.Sum224(cert.Raw)]
return found
}
func (t *TLSCertificateMap) HashCert(cert *x509.Certificate) Sum224 {
return sha256.Sum224(cert.Raw)
}
// AddCert adds a certificate to a pool.
func (t *TLSCertificateMap) AddCert(cert *x509.Certificate) error {
if t.certMap == nil {
t.certMap = make(map[Sum224]*x509.Certificate)
}
// Just allow this. It's not fatal.
if cert == nil {
return nil
}
// Hash the certificate
rawSum224 := sha256.Sum224(cert.Raw)
// Check that the certificate isn't being added twice.
if _, found := t.certMap[rawSum224]; found {
return nil
}
t.certMap[rawSum224] = cert
return nil
}
// MapStructureDecode implements unmarshalling for TLSCertificateMap
// nolint: funlen,cyclop
func (t *TLSCertificateMap) MapStructureDecode(input interface{}) error {
// Get the slice
interfaceSlice, ok := input.([]interface{})
if !ok {
return errors.Wrapf(ErrInvalidInputType, "expected []string got %T", input)
}
// Get the strings
strErrors := lo.Map(interfaceSlice, func(t interface{}, i int) lo.Tuple2[string, bool] {
strValue, ok := t.(string)
return lo.T2(strValue, ok)
})
// Extract errors
err := lo.Reduce[lo.Tuple2[string, bool], error](strErrors, func(r error, t lo.Tuple2[string, bool], _ int) error {
// Return the first error we got if its there
if r != nil {
return r
}
_, ok := lo.Unpack2(t)
if !ok {
return errors.Wrapf(ErrInvalidInputType, "invalid input type in certificate list")
}
return nil
}, nil)
if err != nil {
return errors.Wrapf(err, "TLSCertificatePool.MapStructureDecode")
}
// Flatten the valid list out to []string
caCertSpecEntries := lo.Map(strErrors, func(t lo.Tuple2[string, bool], _ int) string {
value, _ := lo.Unpack2(t)
return value
})
for idx, entry := range caCertSpecEntries {
var pem []byte
itemSample := ""
if _, err := os.Stat(entry); err == nil {
// Is a file
pem, err = ioutil.ReadFile(entry)
if err != nil {
return errors.Wrapf(err, "could not read certificate file: %s", entry)
}
itemSample = entry
} else {
pem = []byte(entry)
if len(entry) < TLSCertificatePoolMaxNonFileEntryReturn {
itemSample = entry
} else {
itemSample = entry[:TLSCertificatePoolMaxNonFileEntryReturn]
}
}
certificates, err := certutils.LoadCertificatesFromPem(pem)
if err != nil {
return errors.Wrapf(ErrInvalidPEMFile, "failed at item %v: %v", idx, itemSample)
}
for idx, cert := range certificates {
if err := t.AddCert(cert); err != nil {
return errors.Wrapf(ErrInvalidPEMFile, "failed at item %v: %v", idx, itemSample)
}
}
}
t.original = caCertSpecEntries
return nil
}
// TLSCertificatePool is our custom type for decoding a certificate pool out of
// YAML.
type TLSCertificatePool struct {
*x509.CertPool
original []string
}
// MapStructureDecode implements the yaml.Unmarshaler interface for tls_cacerts.
//
//nolint:funlen,cyclop
func (t *TLSCertificatePool) MapStructureDecode(input interface{}) error {
// Get the slice
interfaceSlice, ok := input.([]interface{})
if !ok {
return errors.Wrapf(ErrInvalidInputType, "expected []string got %T", input)
}
// Get the strings
strErrors := lo.Map(interfaceSlice, func(t interface{}, i int) lo.Tuple2[string, bool] {
strValue, ok := t.(string)
return lo.T2(strValue, ok)
})
// Extract errors
err := lo.Reduce[lo.Tuple2[string, bool], error](strErrors, func(r error, t lo.Tuple2[string, bool], _ int) error {
// Return the first error we got if its there
if r != nil {
return r
}
_, ok := lo.Unpack2(t)
if !ok {
return errors.Wrapf(ErrInvalidInputType, "invalid input type in certificate list")
}
return nil
}, nil)
if err != nil {
return errors.Wrapf(err, "TLSCertificatePool.MapStructureDecode")
}
// Flatten the valid list out to []string
caCertSpecEntries := lo.Map(strErrors, func(t lo.Tuple2[string, bool], _ int) string {
value, _ := lo.Unpack2(t)
return value
})
// Prescan to check for system cert package request
t.CertPool = nil
for _, entry := range caCertSpecEntries {
if entry == TLSCACertsSystem {
rootCAs, err := x509.SystemCertPool()
if err != nil {
zap.L().Warn("could not fetch system certificate pool", zap.Error(err))
rootCAs = x509.NewCertPool()
}
t.CertPool = rootCAs
break
}
}
if t.CertPool == nil {
t.CertPool = x509.NewCertPool()
}
//nolint:nestif
for idx, entry := range caCertSpecEntries {
var pem []byte
itemSample := ""
if entry == TLSCACertsSystem {
// skip - handled above
continue
} else if _, err := os.Stat(entry); err == nil {
// Is a file
pem, err = ioutil.ReadFile(entry)
if err != nil {
return errors.Wrapf(err, "could not read certificate file: %s", entry)
}
itemSample = entry
} else {
pem = []byte(entry)
if len(entry) < TLSCertificatePoolMaxNonFileEntryReturn {
itemSample = entry
} else {
itemSample = entry[:TLSCertificatePoolMaxNonFileEntryReturn]
}
}
if ok := t.CertPool.AppendCertsFromPEM(pem); !ok {
return errors.Wrapf(ErrInvalidPEMFile, "failed at item %v: %v", idx, itemSample)
}
}
t.original = caCertSpecEntries
return nil
}
// IPNetwork is the config wrapper type for an IP Network.
type IPNetwork struct {
net.IPNet
}
func (ipn *IPNetwork) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
_, ipnet, err := net.ParseCIDR(s)
if err != nil {
return errors.Wrapf(err, "IPNetwork.UnmarshalYAML failed: %s", s)
}
ipn.IPNet = *ipnet
return nil
}
func (ipn IPNetwork) MarshalYAML() (interface{}, error) {
return ipn.String(), nil
}
// ProxyURL is a custom type to validate roxy specifications.
type ProxyURL string
// UnmarshalText implements encoding.UnmarshalText.
func (p *ProxyURL) UnmarshalText(text []byte) error {
s := string(text)
if _, err := url.Parse(s); err != nil {
*p = ProxyURL(s)
return errors.Wrapf(err, "ProxyURL UnmarshalText")
}
switch s {
case ProxyDirect, ProxyEnvironment:
*p = ProxyURL(s)
return nil
default:
return nil
}
}
// UnmarshalText MarshalText encoding.UnmarshalText.
func (p *ProxyURL) MarshalText() ([]byte, error) {
return []byte(*p), nil
}