forked from hashicorp/consul
-
Notifications
You must be signed in to change notification settings - Fork 0
/
structs.go
697 lines (615 loc) · 20 KB
/
structs.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package extauthz
import (
"fmt"
"strconv"
"strings"
"time"
envoy_cluster_v3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
envoy_core_v3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
envoy_endpoint_v3 "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
envoy_listener_v3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
envoy_http_ext_authz_v3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ext_authz/v3"
envoy_ext_authz_v3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/ext_authz/v3"
envoy_http_v3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
envoy_upstreams_http_v3 "github.com/envoyproxy/go-control-plane/envoy/extensions/upstreams/http/v3"
envoy_type_matcher_v3 "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3"
envoy_type_v3 "github.com/envoyproxy/go-control-plane/envoy/type/v3"
"github.com/hashicorp/go-multierror"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/hernad/consul/acl"
"github.com/hernad/consul/api"
cmn "github.com/hernad/consul/envoyextensions/extensioncommon"
)
const (
LocalExtAuthzClusterName = "local_ext_authz"
defaultMetadataNS = "consul"
defaultStatPrefix = "response"
defaultStatusOnError = 403
localhost = "localhost"
localhostIPv4 = "127.0.0.1"
localhostIPv6 = "::1"
)
type extAuthzConfig struct {
BootstrapMetadataLabelsKey string
ClearRouteCache *bool
GrpcService *GrpcService
HttpService *HttpService
IncludePeerCertificate *bool
MetadataContextNamespaces []string
StatusOnError *int
StatPrefix string
WithRequestBody *BufferSettings
failureModeAllow bool
}
func (c *extAuthzConfig) normalize() {
if c.StatPrefix == "" {
c.StatPrefix = defaultStatPrefix
}
if c.isGRPC() {
c.GrpcService.normalize()
}
if c.isHTTP() {
c.HttpService.normalize()
}
}
func (c *extAuthzConfig) validate() error {
c.normalize()
var resultErr error
if c.isGRPC() == c.isHTTP() {
resultErr = multierror.Append(resultErr, fmt.Errorf("exactly one of GrpcService or HttpService must be set"))
}
var field string
var validate func() error
if c.isHTTP() {
field = "HttpService"
validate = c.HttpService.validate
} else {
field = "GrpcService"
validate = c.GrpcService.validate
}
if err := validate(); err != nil {
resultErr = multierror.Append(resultErr, fmt.Errorf("failed to validate Config.%s: %w", field, err))
}
if c.StatusOnError != nil {
if _, ok := envoy_type_v3.StatusCode_name[int32(*c.StatusOnError)]; !ok {
resultErr = multierror.Append(resultErr, fmt.Errorf("failed to validate Config.StatusOnError:"+
"status code %d is not supported by Envoy, please refer to the Envoy documentation for supported status codes",
*c.StatusOnError))
}
}
return resultErr
}
func (c extAuthzConfig) envoyGrpcService(cfg *cmn.RuntimeConfig) (*envoy_core_v3.GrpcService, error) {
target := c.GrpcService.Target
clusterName, err := c.getClusterName(cfg, target)
if err != nil {
return nil, err
}
var initialMetadata []*envoy_core_v3.HeaderValue
for _, meta := range c.GrpcService.InitialMetadata {
initialMetadata = append(initialMetadata, meta.toEnvoy())
}
return &envoy_core_v3.GrpcService{
TargetSpecifier: &envoy_core_v3.GrpcService_EnvoyGrpc_{
EnvoyGrpc: &envoy_core_v3.GrpcService_EnvoyGrpc{
ClusterName: clusterName,
Authority: c.GrpcService.Authority,
},
},
Timeout: target.timeoutDurationPB(),
InitialMetadata: initialMetadata,
}, nil
}
func (c extAuthzConfig) envoyHttpService(cfg *cmn.RuntimeConfig) (*envoy_http_ext_authz_v3.HttpService, error) {
clusterName, err := c.getClusterName(cfg, c.HttpService.Target)
if err != nil {
return nil, err
}
return &envoy_http_ext_authz_v3.HttpService{
ServerUri: &envoy_core_v3.HttpUri{
Uri: clusterName, // not used by Envoy, set to cluster
HttpUpstreamType: &envoy_core_v3.HttpUri_Cluster{Cluster: clusterName},
Timeout: c.HttpService.Target.timeoutDurationPB(),
},
PathPrefix: c.HttpService.PathPrefix,
AuthorizationRequest: c.HttpService.AuthorizationRequest.toEnvoy(),
AuthorizationResponse: c.HttpService.AuthorizationResponse.toEnvoy(),
}, nil
}
// getClusterName returns the name of the cluster for the external authorization service.
// If the extension is configured with an upstream ext-authz service then the name of the cluster for
// that upstream is returned. If the extension is configured with a URI, the only allowed host is `localhost`
// and the extension will insert a new cluster with the name "local_ext_authz", so we use that name.
func (c extAuthzConfig) getClusterName(cfg *cmn.RuntimeConfig, target *Target) (string, error) {
var err error
clusterName := LocalExtAuthzClusterName
if target.isService() {
if clusterName, err = target.clusterName(cfg); err != nil {
return "", err
}
}
return clusterName, nil
}
func (c extAuthzConfig) isGRPC() bool {
return c.GrpcService != nil
}
func (c extAuthzConfig) isHTTP() bool {
return c.HttpService != nil
}
// toEnvoyCluster returns an Envoy cluster for connecting to the ext_authz service.
// If the extension is configured with the ext_authz service locally via the URI set to localhost,
// this func will return a new cluster definition that will allow the proxy to connect to the ext_authz
// service running on localhost on the configured port.
//
// If the extension is configured with the ext_authz service as an upstream there is no need to insert
// a new cluster so this method returns nil.
func (c *extAuthzConfig) toEnvoyCluster(_ *cmn.RuntimeConfig) (*envoy_cluster_v3.Cluster, error) {
var target *Target
if c.isHTTP() {
target = c.HttpService.Target
} else {
target = c.GrpcService.Target
}
// If the target is an upstream we do not need to create a cluster. We will use the cluster of the upstream.
if target.isService() {
return nil, nil
}
host, port, err := target.addr()
if err != nil {
return nil, err
}
clusterType := &envoy_cluster_v3.Cluster_Type{Type: envoy_cluster_v3.Cluster_STATIC}
if host == localhost {
// If the host is "localhost" use a STRICT_DNS cluster type to perform DNS lookup.
clusterType = &envoy_cluster_v3.Cluster_Type{Type: envoy_cluster_v3.Cluster_STRICT_DNS}
}
var typedExtProtoOpts map[string]*anypb.Any
if c.isGRPC() {
// By default HTTP/1.1 is used for the transport protocol. gRPC requires that we explicitly configure HTTP/2
httpProtoOpts := &envoy_upstreams_http_v3.HttpProtocolOptions{
UpstreamProtocolOptions: &envoy_upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig_{
ExplicitHttpConfig: &envoy_upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig{
ProtocolConfig: &envoy_upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig_Http2ProtocolOptions{},
},
},
}
httpProtoOptsAny, err := anypb.New(httpProtoOpts)
if err != nil {
return nil, err
}
typedExtProtoOpts = make(map[string]*anypb.Any)
typedExtProtoOpts["envoy.extensions.upstreams.http.v3.HttpProtocolOptions"] = httpProtoOptsAny
}
return &envoy_cluster_v3.Cluster{
Name: LocalExtAuthzClusterName,
ClusterDiscoveryType: clusterType,
ConnectTimeout: target.timeoutDurationPB(),
LoadAssignment: &envoy_endpoint_v3.ClusterLoadAssignment{
ClusterName: LocalExtAuthzClusterName,
Endpoints: []*envoy_endpoint_v3.LocalityLbEndpoints{
{
LbEndpoints: []*envoy_endpoint_v3.LbEndpoint{{
HostIdentifier: &envoy_endpoint_v3.LbEndpoint_Endpoint{
Endpoint: &envoy_endpoint_v3.Endpoint{
Address: &envoy_core_v3.Address{
Address: &envoy_core_v3.Address_SocketAddress{
SocketAddress: &envoy_core_v3.SocketAddress{
Address: host,
PortSpecifier: &envoy_core_v3.SocketAddress_PortValue{
PortValue: uint32(port),
},
},
},
},
},
},
}},
},
},
},
TypedExtensionProtocolOptions: typedExtProtoOpts,
}, nil
}
func (c extAuthzConfig) toEnvoyHttpFilter(cfg *cmn.RuntimeConfig) (*envoy_http_v3.HttpFilter, error) {
extAuthzFilter := &envoy_http_ext_authz_v3.ExtAuthz{
StatPrefix: c.StatPrefix,
WithRequestBody: c.WithRequestBody.toEnvoy(),
TransportApiVersion: envoy_core_v3.ApiVersion_V3,
MetadataContextNamespaces: append(c.MetadataContextNamespaces, defaultMetadataNS),
FailureModeAllow: c.failureModeAllow,
BootstrapMetadataLabelsKey: c.BootstrapMetadataLabelsKey,
}
if c.isHTTP() {
httpSvc, err := c.envoyHttpService(cfg)
if err != nil {
return nil, err
}
extAuthzFilter.Services = &envoy_http_ext_authz_v3.ExtAuthz_HttpService{HttpService: httpSvc}
} else {
grpcSvc, err := c.envoyGrpcService(cfg)
if err != nil {
return nil, err
}
extAuthzFilter.Services = &envoy_http_ext_authz_v3.ExtAuthz_GrpcService{GrpcService: grpcSvc}
}
if c.ClearRouteCache != nil {
extAuthzFilter.ClearRouteCache = *c.ClearRouteCache
}
if c.IncludePeerCertificate != nil {
extAuthzFilter.IncludePeerCertificate = *c.IncludePeerCertificate
}
if c.StatusOnError != nil {
extAuthzFilter.StatusOnError = &envoy_type_v3.HttpStatus{
Code: envoy_type_v3.StatusCode(*c.StatusOnError),
}
}
return cmn.MakeEnvoyHTTPFilter("envoy.filters.http.ext_authz", extAuthzFilter)
}
func (c extAuthzConfig) toEnvoyNetworkFilter(cfg *cmn.RuntimeConfig) (*envoy_listener_v3.Filter, error) {
grpcSvc, err := c.envoyGrpcService(cfg)
if err != nil {
return nil, err
}
extAuthzFilter := &envoy_ext_authz_v3.ExtAuthz{
GrpcService: grpcSvc,
StatPrefix: c.StatPrefix,
TransportApiVersion: envoy_core_v3.ApiVersion_V3,
FailureModeAllow: c.failureModeAllow,
}
if c.IncludePeerCertificate != nil {
extAuthzFilter.IncludePeerCertificate = *c.IncludePeerCertificate
}
return cmn.MakeFilter("envoy.filters.network.ext_authz", extAuthzFilter)
}
type validator interface {
validate() error
}
type AuthorizationRequest struct {
AllowedHeaders ListStringMatcher
HeadersToAdd []*HeaderValue
}
func (r *AuthorizationRequest) toEnvoy() *envoy_http_ext_authz_v3.AuthorizationRequest {
if r == nil {
return nil
}
if len(r.AllowedHeaders) == 0 && len(r.HeadersToAdd) == 0 {
return nil
}
req := &envoy_http_ext_authz_v3.AuthorizationRequest{
AllowedHeaders: r.AllowedHeaders.toEnvoy(),
}
for _, header := range r.HeadersToAdd {
req.HeadersToAdd = append(req.HeadersToAdd, header.toEnvoy())
}
return req
}
func (r *AuthorizationRequest) validate() error {
var resultErr error
if r == nil {
return resultErr
}
if err := r.AllowedHeaders.validate(); err != nil {
resultErr = multierror.Append(resultErr, fmt.Errorf("validation failed for AuthorizationRequest.AllowedHeaders: %w", err))
}
return resultErr
}
type AuthorizationResponse struct {
AllowedUpstreamHeaders ListStringMatcher
AllowedUpstreamHeadersToAppend ListStringMatcher
AllowedClientHeaders ListStringMatcher
AllowedClientHeadersOnSuccess ListStringMatcher
DynamicMetadataFromHeaders ListStringMatcher
}
func (r *AuthorizationResponse) toEnvoy() *envoy_http_ext_authz_v3.AuthorizationResponse {
if r == nil {
return nil
}
return &envoy_http_ext_authz_v3.AuthorizationResponse{
AllowedUpstreamHeaders: r.AllowedUpstreamHeaders.toEnvoy(),
AllowedUpstreamHeadersToAppend: r.AllowedUpstreamHeadersToAppend.toEnvoy(),
AllowedClientHeaders: r.AllowedClientHeaders.toEnvoy(),
AllowedClientHeadersOnSuccess: r.AllowedClientHeadersOnSuccess.toEnvoy(),
DynamicMetadataFromHeaders: r.DynamicMetadataFromHeaders.toEnvoy(),
}
}
func (r *AuthorizationResponse) validate() error {
var resultErr error
if r == nil {
return resultErr
}
for field, matchers := range r.fieldMap() {
if err := matchers.validate(); err != nil {
resultErr = multierror.Append(resultErr, fmt.Errorf("validation failed for AuthorizationResponse.%s: %w", field, err))
}
}
return resultErr
}
func (r *AuthorizationResponse) fieldMap() map[string]ListStringMatcher {
if r == nil {
return nil
}
return map[string]ListStringMatcher{
"AllowedUpstreamHeaders": r.AllowedUpstreamHeaders,
"AllowedUpstreamHeadersToAppend": r.AllowedUpstreamHeadersToAppend,
"AllowedClientHeaders": r.AllowedClientHeaders,
"AllowedClientHeadersOnSuccess": r.AllowedClientHeadersOnSuccess,
"DynamicMetadataFromHeaders": r.DynamicMetadataFromHeaders,
}
}
type BufferSettings struct {
MaxRequestBytes *int64
AllowPartialMessage *bool
PackAsBytes *bool
}
func (b *BufferSettings) toEnvoy() *envoy_http_ext_authz_v3.BufferSettings {
if b == nil {
return nil
}
if b.AllowPartialMessage == nil &&
b.MaxRequestBytes == nil &&
b.PackAsBytes == nil {
return nil
}
bufSet := &envoy_http_ext_authz_v3.BufferSettings{}
if b.AllowPartialMessage != nil {
bufSet.AllowPartialMessage = *b.AllowPartialMessage
}
if b.MaxRequestBytes != nil {
bufSet.MaxRequestBytes = uint32(*b.MaxRequestBytes)
}
if b.PackAsBytes != nil {
bufSet.PackAsBytes = *b.PackAsBytes
}
return bufSet
}
type GrpcService struct {
Target *Target
Authority string
InitialMetadata []*HeaderValue
}
func (v *GrpcService) normalize() {
if v == nil {
return
}
v.Target.normalize()
}
func (v *GrpcService) validate() error {
var resultErr error
if v == nil {
return resultErr
}
if v.Target == nil {
resultErr = multierror.Append(resultErr, fmt.Errorf("GrpcService.Target must be set"))
}
if err := v.Target.validate(); err != nil {
resultErr = multierror.Append(resultErr, err)
}
return resultErr
}
type HeaderValue struct {
Key string
Value string
}
func (h *HeaderValue) toEnvoy() *envoy_core_v3.HeaderValue {
if h == nil {
return nil
}
return &envoy_core_v3.HeaderValue{Key: h.Key, Value: h.Value}
}
type HttpService struct {
Target *Target
PathPrefix string
AuthorizationRequest *AuthorizationRequest
AuthorizationResponse *AuthorizationResponse
}
func (v *HttpService) normalize() {
if v == nil {
return
}
v.Target.normalize()
}
func (v *HttpService) validate() error {
var resultErr error
if v == nil {
return resultErr
}
if v.Target == nil {
resultErr = multierror.Append(resultErr, fmt.Errorf("HttpService.Target must be set"))
}
for _, val := range []validator{v.Target, v.AuthorizationRequest, v.AuthorizationResponse} {
if err := val.validate(); err != nil {
resultErr = multierror.Append(resultErr, err)
}
}
return resultErr
}
type ListStringMatcher []*StringMatcher
func (l ListStringMatcher) toEnvoy() *envoy_type_matcher_v3.ListStringMatcher {
if len(l) < 1 {
return nil
}
matchers := &envoy_type_matcher_v3.ListStringMatcher{}
for _, matcher := range l {
matchers.Patterns = append(matchers.Patterns, matcher.toEnvoy())
}
return matchers
}
func (l ListStringMatcher) validate() error {
var resultErr error
if len(l) < 1 {
return nil
}
for idx, matcher := range l {
if err := matcher.validate(); err != nil {
resultErr = multierror.Append(resultErr, fmt.Errorf("validation failed for matcher at index %d: %w", idx, err))
}
}
return resultErr
}
type StringMatcher struct {
Contains string
Exact string
IgnoreCase bool
Prefix string
SafeRegex string
Suffix string
}
func (s *StringMatcher) toEnvoy() *envoy_type_matcher_v3.StringMatcher {
if s == nil {
return nil
}
switch {
case s.Contains != "":
return &envoy_type_matcher_v3.StringMatcher{
MatchPattern: &envoy_type_matcher_v3.StringMatcher_Contains{Contains: s.Contains},
IgnoreCase: s.IgnoreCase,
}
case s.Exact != "":
return &envoy_type_matcher_v3.StringMatcher{
MatchPattern: &envoy_type_matcher_v3.StringMatcher_Exact{Exact: s.Exact},
IgnoreCase: s.IgnoreCase,
}
case s.Prefix != "":
return &envoy_type_matcher_v3.StringMatcher{
MatchPattern: &envoy_type_matcher_v3.StringMatcher_Prefix{Prefix: s.Prefix},
IgnoreCase: s.IgnoreCase,
}
case s.SafeRegex != "":
return &envoy_type_matcher_v3.StringMatcher{
MatchPattern: &envoy_type_matcher_v3.StringMatcher_SafeRegex{
SafeRegex: &envoy_type_matcher_v3.RegexMatcher{
EngineType: &envoy_type_matcher_v3.RegexMatcher_GoogleRe2{},
Regex: s.SafeRegex,
},
},
}
case s.Suffix != "":
return &envoy_type_matcher_v3.StringMatcher{
MatchPattern: &envoy_type_matcher_v3.StringMatcher_Suffix{Suffix: s.Suffix},
IgnoreCase: s.IgnoreCase,
}
default:
return nil
}
}
func (s *StringMatcher) validate() error {
if s == nil {
return nil
}
set := 0
for _, s := range []string{s.Contains, s.Exact, s.Prefix, s.SafeRegex, s.Suffix} {
if s != "" {
set++
}
}
if set != 1 {
return fmt.Errorf("exactly one of Contains, Exact, Prefix, SafeRegex or Suffix must be set")
}
return nil
}
type Target struct {
Service api.CompoundServiceName
URI string
Timeout string
timeout *time.Duration
host string
port int
}
// addr returns the host and port for the target when the target is a URI.
// It returns a non-nil error if the target is not a URI.
func (t Target) addr() (string, int, error) {
if !t.isURI() {
return "", 0, fmt.Errorf("target is not configured with a URI, set Target.URI")
}
return t.host, t.port, nil
}
// clusterName returns the cluster name for the target when the target is an upstream service.
// It searches through the upstreams in the provided runtime configuration and returns the name
// of the cluster for the first upstream service that matches the target service.
// It returns a non-nil error if a matching cluster is not found or if the target is not an
// upstream service.
func (t Target) clusterName(cfg *cmn.RuntimeConfig) (string, error) {
if !t.isService() {
return "", fmt.Errorf("target is not configured with an upstream service, set Target.Service")
}
for service, upstream := range cfg.Upstreams {
if service == t.Service {
for sni := range upstream.SNIs {
return sni, nil
}
}
}
return "", fmt.Errorf("no upstream definition found for service %q", t.Service.Name)
}
func (t Target) isService() bool {
return t.Service.Name != ""
}
func (t Target) isURI() bool {
return t.URI != ""
}
func (t *Target) normalize() {
if t == nil {
return
}
t.Service.Namespace = acl.NamespaceOrDefault(t.Service.Namespace)
t.Service.Partition = acl.PartitionOrDefault(t.Service.Partition)
}
// timeoutDurationPB returns the target's timeout as a *durationpb.Duration.
// It returns nil if the timeout has not been explicitly set.
func (t *Target) timeoutDurationPB() *durationpb.Duration {
if t == nil || t.timeout == nil {
return nil
}
return durationpb.New(*t.timeout)
}
func (t *Target) validate() error {
var err, resultErr error
if t == nil {
return resultErr
}
if t.isURI() == t.isService() {
resultErr = multierror.Append(resultErr, fmt.Errorf("exactly one of Target.Service or Target.URI must be set"))
}
if t.isURI() {
t.host, t.port, err = parseAddr(t.URI)
if err == nil {
switch t.host {
case localhost, localhostIPv4, localhostIPv6:
default:
resultErr = multierror.Append(resultErr,
fmt.Errorf("invalid host for Target.URI %q: expected %q, %q, or %q", t.URI, localhost, localhostIPv4, localhostIPv6))
}
} else {
resultErr = multierror.Append(resultErr, fmt.Errorf("invalid format for Target.URI %q: expected host:port", t.URI))
}
}
if t.Timeout != "" {
if d, err := time.ParseDuration(t.Timeout); err == nil {
t.timeout = &d
} else {
resultErr = multierror.Append(resultErr, fmt.Errorf("failed to parse Target.Timeout %q as a duration: %w", t.Timeout, err))
}
}
return resultErr
}
func parseAddr(s string) (host string, port int, err error) {
// Strip the protocol if one was provided
if _, addr, hasProto := strings.Cut(s, "://"); hasProto {
s = addr
}
idx := strings.LastIndex(s, ":")
switch idx {
case -1, len(s) - 1:
err = fmt.Errorf("invalid input format %q: expected host:port", s)
case 0:
host = localhost
port, err = strconv.Atoi(s[idx+1:])
default:
host = s[:idx]
port, err = strconv.Atoi(s[idx+1:])
}
return
}