-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathservers.go
876 lines (742 loc) · 25.4 KB
/
servers.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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
package config
import (
"encoding/json"
"fmt"
"maps"
"strconv"
"strings"
gotemplate "text/template"
"github.com/nginxinc/nginx-gateway-fabric/internal/framework/helpers"
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/nginx/config/http"
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/nginx/config/policies"
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/nginx/config/shared"
"github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/state/dataplane"
)
var serversTemplate = gotemplate.Must(gotemplate.New("servers").Parse(serversTemplateText))
const (
// HeaderMatchSeparator is the separator for constructing header-based match for NJS.
HeaderMatchSeparator = ":"
rootPath = "/"
)
// httpBaseHeaders contains the constant headers set in each HTTP server block.
var httpBaseHeaders = []http.Header{
{
Name: "Host",
Value: "$gw_api_compliant_host",
},
{
Name: "X-Forwarded-For",
Value: "$proxy_add_x_forwarded_for",
},
{
Name: "Upgrade",
Value: "$http_upgrade",
},
{
Name: "Connection",
Value: "$connection_upgrade",
},
}
// grpcBaseHeaders contains the constant headers set in each gRPC server block.
var grpcBaseHeaders = []http.Header{
{
Name: "Host",
Value: "$gw_api_compliant_host",
},
{
Name: "X-Forwarded-For",
Value: "$proxy_add_x_forwarded_for",
},
{
Name: "Authority",
Value: "$gw_api_compliant_host",
},
}
func (g GeneratorImpl) newExecuteServersFunc(generator policies.Generator) executeFunc {
return func(configuration dataplane.Configuration) []executeResult {
return g.executeServers(configuration, generator)
}
}
func (g GeneratorImpl) executeServers(conf dataplane.Configuration, generator policies.Generator) []executeResult {
servers, httpMatchPairs := createServers(conf.HTTPServers, conf.SSLServers, conf.TLSPassthroughServers, generator)
serverConfig := http.ServerConfig{
Servers: servers,
IPFamily: getIPFamily(conf.BaseHTTPConfig),
Plus: g.plus,
}
serverResult := executeResult{
dest: httpConfigFile,
data: helpers.MustExecuteTemplate(serversTemplate, serverConfig),
}
// create httpMatchPair conf
httpMatchConf, err := json.Marshal(httpMatchPairs)
if err != nil {
// panic is safe here because we should never fail to marshal the match unless we constructed it incorrectly.
panic(fmt.Errorf("could not marshal http match pairs: %w", err))
}
httpMatchResult := executeResult{
dest: httpMatchVarsFile,
data: httpMatchConf,
}
includeFileResults := createIncludeFileResults(servers)
allResults := make([]executeResult, 0, len(includeFileResults)+2)
allResults = append(allResults, includeFileResults...)
allResults = append(allResults, serverResult, httpMatchResult)
return allResults
}
// getIPFamily returns whether the server should be configured for IPv4, IPv6, or both.
func getIPFamily(baseHTTPConfig dataplane.BaseHTTPConfig) shared.IPFamily {
switch baseHTTPConfig.IPFamily {
case dataplane.IPv4:
return shared.IPFamily{IPv4: true}
case dataplane.IPv6:
return shared.IPFamily{IPv6: true}
}
return shared.IPFamily{IPv4: true, IPv6: true}
}
func createIncludeFileResults(servers []http.Server) []executeResult {
uniqueIncludes := make(map[string][]byte)
for _, server := range servers {
for _, include := range server.Includes {
uniqueIncludes[include.Name] = include.Content
}
for _, loc := range server.Locations {
for _, include := range loc.Includes {
uniqueIncludes[include.Name] = include.Content
}
}
}
results := make([]executeResult, 0, len(uniqueIncludes))
for filename, contents := range uniqueIncludes {
results = append(results, executeResult{
dest: filename,
data: contents,
})
}
return results
}
func createServers(
httpServers,
sslServers []dataplane.VirtualServer,
tlsPassthroughServers []dataplane.Layer4VirtualServer,
generator policies.Generator,
) ([]http.Server, httpMatchPairs) {
servers := make([]http.Server, 0, len(httpServers)+len(sslServers))
finalMatchPairs := make(httpMatchPairs)
sharedTLSPorts := make(map[int32]struct{})
for _, passthroughServer := range tlsPassthroughServers {
sharedTLSPorts[passthroughServer.Port] = struct{}{}
}
for idx, s := range httpServers {
serverID := fmt.Sprintf("%d", idx)
httpServer, matchPairs := createServer(s, serverID, generator)
servers = append(servers, httpServer)
maps.Copy(finalMatchPairs, matchPairs)
}
for idx, s := range sslServers {
serverID := fmt.Sprintf("SSL_%d", idx)
sslServer, matchPairs := createSSLServer(s, serverID, generator)
if _, portInUse := sharedTLSPorts[s.Port]; portInUse {
sslServer.Listen = getSocketNameHTTPS(s.Port)
sslServer.IsSocket = true
}
servers = append(servers, sslServer)
maps.Copy(finalMatchPairs, matchPairs)
}
return servers, finalMatchPairs
}
func createSSLServer(
virtualServer dataplane.VirtualServer,
serverID string,
generator policies.Generator,
) (http.Server, httpMatchPairs) {
listen := fmt.Sprint(virtualServer.Port)
if virtualServer.IsDefault {
return http.Server{
IsDefaultSSL: true,
Listen: listen,
}, nil
}
locs, matchPairs, grpc := createLocations(&virtualServer, serverID, generator)
server := http.Server{
ServerName: virtualServer.Hostname,
SSL: &http.SSL{
Certificate: generatePEMFileName(virtualServer.SSL.KeyPairID),
CertificateKey: generatePEMFileName(virtualServer.SSL.KeyPairID),
},
Locations: locs,
GRPC: grpc,
Listen: listen,
}
server.Includes = createIncludesFromPolicyGenerateResult(
generator.GenerateForServer(virtualServer.Policies, server),
)
return server, matchPairs
}
func createServer(
virtualServer dataplane.VirtualServer,
serverID string,
generator policies.Generator,
) (http.Server, httpMatchPairs) {
listen := fmt.Sprint(virtualServer.Port)
if virtualServer.IsDefault {
return http.Server{
IsDefaultHTTP: true,
Listen: listen,
}, nil
}
locs, matchPairs, grpc := createLocations(&virtualServer, serverID, generator)
server := http.Server{
ServerName: virtualServer.Hostname,
Locations: locs,
Listen: listen,
GRPC: grpc,
}
server.Includes = createIncludesFromPolicyGenerateResult(
generator.GenerateForServer(virtualServer.Policies, server),
)
return server, matchPairs
}
// rewriteConfig contains the configuration for a location to rewrite paths,
// as specified in a URLRewrite filter.
type rewriteConfig struct {
// InternalRewrite rewrites an internal URI to the original URI (ex: /coffee_prefix_route0 -> /coffee)
InternalRewrite string
// MainRewrite rewrites the original URI to the new URI (ex: /coffee -> /beans)
MainRewrite string
}
type httpMatchPairs map[string][]routeMatch
func createLocations(
server *dataplane.VirtualServer,
serverID string,
generator policies.Generator,
) ([]http.Location, httpMatchPairs, bool) {
maxLocs, pathsAndTypes := getMaxLocationCountAndPathMap(server.PathRules)
locs := make([]http.Location, 0, maxLocs)
matchPairs := make(httpMatchPairs)
var rootPathExists bool
var grpc bool
for pathRuleIdx, rule := range server.PathRules {
matches := make([]routeMatch, 0, len(rule.MatchRules))
if rule.Path == rootPath {
rootPathExists = true
}
if rule.GRPC {
grpc = true
}
extLocations := initializeExternalLocations(rule, pathsAndTypes)
for i := range extLocations {
extLocations[i].Includes = createIncludesFromPolicyGenerateResult(
generator.GenerateForLocation(rule.Policies, extLocations[i]),
)
}
if !needsInternalLocations(rule) {
for _, r := range rule.MatchRules {
extLocations = updateLocations(r.Filters, extLocations, r, server.Port, rule.Path, rule.GRPC)
}
locs = append(locs, extLocations...)
continue
}
internalLocations := make([]http.Location, 0, len(rule.MatchRules))
for matchRuleIdx, r := range rule.MatchRules {
intLocation, match := initializeInternalLocation(pathRuleIdx, matchRuleIdx, r.Match, grpc)
intLocation.Includes = createIncludesFromPolicyGenerateResult(
generator.GenerateForInternalLocation(rule.Policies),
)
intLocation = updateLocation(
r.Filters,
intLocation,
r,
server.Port,
rule.Path,
rule.GRPC,
)
internalLocations = append(internalLocations, intLocation)
matches = append(matches, match)
}
httpMatchKey := serverID + "_" + strconv.Itoa(pathRuleIdx)
for i := range extLocations {
// FIXME(sberman): De-dupe matches and associated locations
// so we don't need nginx/njs to perform unnecessary matching.
// https://github.com/nginxinc/nginx-gateway-fabric/issues/662
extLocations[i].HTTPMatchKey = httpMatchKey
matchPairs[extLocations[i].HTTPMatchKey] = matches
}
locs = append(locs, extLocations...)
locs = append(locs, internalLocations...)
}
if !rootPathExists {
locs = append(locs, createDefaultRootLocation())
}
return locs, matchPairs, grpc
}
func needsInternalLocations(rule dataplane.PathRule) bool {
if len(rule.MatchRules) > 1 {
return true
}
return len(rule.MatchRules) == 1 && !isPathOnlyMatch(rule.MatchRules[0].Match)
}
func createIncludesFromPolicyGenerateResult(resFiles []policies.File) []http.Include {
if len(resFiles) == 0 {
return nil
}
includes := make([]http.Include, 0, len(resFiles))
for _, file := range resFiles {
includes = append(includes, http.Include{
Name: includesFolder + "/" + file.Name,
Content: file.Content,
})
}
return includes
}
// pathAndTypeMap contains a map of paths and any path types defined for that path
// for example, {/foo: {exact: {}, prefix: {}}}.
type pathAndTypeMap map[string]map[dataplane.PathType]struct{}
// To calculate the maximum number of locations, we need to take into account the following:
// 1. Each match rule for a path rule will have one location.
// 2. Each path rule may have an additional location if it contains non-path-only matches.
// 3. Each prefix path rule may have an additional location if it doesn't contain trailing slash.
// 4. There may be an additional location for the default root path.
// We also return a map of all paths and their types.
func getMaxLocationCountAndPathMap(pathRules []dataplane.PathRule) (int, pathAndTypeMap) {
maxLocs := 1
pathsAndTypes := make(pathAndTypeMap)
for _, rule := range pathRules {
maxLocs += len(rule.MatchRules) + 2
if pathsAndTypes[rule.Path] == nil {
pathsAndTypes[rule.Path] = map[dataplane.PathType]struct{}{
rule.PathType: {},
}
} else {
pathsAndTypes[rule.Path][rule.PathType] = struct{}{}
}
}
return maxLocs, pathsAndTypes
}
func initializeExternalLocations(
rule dataplane.PathRule,
pathsAndTypes pathAndTypeMap,
) []http.Location {
extLocations := make([]http.Location, 0, 2)
locType := getLocationTypeForPathRule(rule)
externalLocPath := createPath(rule)
// If the path type is Prefix and doesn't contain a trailing slash, then we need a second location
// that handles the Exact prefix case (if it doesn't already exist), and the first location is updated
// to handle the trailing slash prefix case (if it doesn't already exist)
if isNonSlashedPrefixPath(rule.PathType, externalLocPath) {
// if Exact path and/or trailing slash Prefix path already exists, this means some routing rule
// configures it. The routing rule location has priority over this location, so we don't try to
// overwrite it and we don't add a duplicate location to NGINX because that will cause an NGINX config error.
_, exactPathExists := pathsAndTypes[rule.Path][dataplane.PathTypeExact]
var trailingSlashPrefixPathExists bool
if pathTypes, exists := pathsAndTypes[rule.Path+"/"]; exists {
_, trailingSlashPrefixPathExists = pathTypes[dataplane.PathTypePrefix]
}
if exactPathExists && trailingSlashPrefixPathExists {
return []http.Location{}
}
if !trailingSlashPrefixPathExists {
externalLocTrailing := http.Location{
Path: externalLocPath + "/",
Type: locType,
}
extLocations = append(extLocations, externalLocTrailing)
}
if !exactPathExists {
externalLocExact := http.Location{
Path: exactPath(externalLocPath),
Type: locType,
}
extLocations = append(extLocations, externalLocExact)
}
} else {
externalLoc := http.Location{
Path: externalLocPath,
Type: locType,
}
extLocations = []http.Location{externalLoc}
}
return extLocations
}
func getLocationTypeForPathRule(rule dataplane.PathRule) http.LocationType {
if needsInternalLocations(rule) {
return http.RedirectLocationType
}
return http.ExternalLocationType
}
func initializeInternalLocation(
pathruleIdx,
matchRuleIdx int,
match dataplane.Match,
grpc bool,
) (http.Location, routeMatch) {
path := fmt.Sprintf("%s-rule%d-route%d", http.InternalRoutePathPrefix, pathruleIdx, matchRuleIdx)
return createMatchLocation(path, grpc), createRouteMatch(match, path)
}
// updateLocation updates a location with any relevant configurations, like proxy_pass, filters, tls settings, etc.
func updateLocation(
filters dataplane.HTTPFilters,
location http.Location,
matchRule dataplane.MatchRule,
listenerPort int32,
path string,
grpc bool,
) http.Location {
if filters.InvalidFilter != nil {
location.Return = &http.Return{Code: http.StatusInternalServerError}
return location
}
if filters.RequestRedirect != nil {
ret := createReturnValForRedirectFilter(filters.RequestRedirect, listenerPort)
location.Return = ret
return location
}
rewrites := createRewritesValForRewriteFilter(filters.RequestURLRewrite, path)
proxySetHeaders := generateProxySetHeaders(&matchRule.Filters, grpc)
responseHeaders := generateResponseHeaders(&matchRule.Filters)
if rewrites != nil {
if location.Type == http.InternalLocationType && rewrites.InternalRewrite != "" {
location.Rewrites = append(location.Rewrites, rewrites.InternalRewrite)
}
if rewrites.MainRewrite != "" {
location.Rewrites = append(location.Rewrites, rewrites.MainRewrite)
}
}
location.ProxySetHeaders = proxySetHeaders
location.ProxySSLVerify = createProxyTLSFromBackends(matchRule.BackendGroup.Backends)
proxyPass := createProxyPass(
matchRule.BackendGroup,
matchRule.Filters.RequestURLRewrite,
generateProtocolString(location.ProxySSLVerify, grpc),
grpc,
)
location.ResponseHeaders = responseHeaders
location.ProxyPass = proxyPass
location.GRPC = grpc
return location
}
// updateLocations updates the existing locations with any relevant configurations, like proxy_pass,
// filters, tls settings, etc.
func updateLocations(
filters dataplane.HTTPFilters,
buildLocations []http.Location,
matchRule dataplane.MatchRule,
listenerPort int32,
path string,
grpc bool,
) []http.Location {
updatedLocations := make([]http.Location, len(buildLocations))
for i, loc := range buildLocations {
updatedLocations[i] = updateLocation(filters, loc, matchRule, listenerPort, path, grpc)
}
return updatedLocations
}
func generateProtocolString(ssl *http.ProxySSLVerify, grpc bool) string {
if !grpc {
if ssl != nil {
return "https"
}
return "http"
}
if ssl != nil {
return "grpcs"
}
return "grpc"
}
func createProxyTLSFromBackends(backends []dataplane.Backend) *http.ProxySSLVerify {
if len(backends) == 0 {
return nil
}
for _, b := range backends {
proxyVerify := createProxySSLVerify(b.VerifyTLS)
if proxyVerify != nil {
// If any backend has a backend TLS policy defined, then we use that for the proxy SSL verification.
// We require that all backends in a group have the same backend TLS policy.
// Verification that all backends in a group have the same backend TLS policy is done in the graph package.
return proxyVerify
}
}
return nil
}
func createProxySSLVerify(v *dataplane.VerifyTLS) *http.ProxySSLVerify {
if v == nil {
return nil
}
var trustedCert string
if v.CertBundleID != "" {
trustedCert = generateCertBundleFileName(v.CertBundleID)
} else {
trustedCert = v.RootCAPath
}
return &http.ProxySSLVerify{
TrustedCertificate: trustedCert,
Name: v.Hostname,
}
}
func createReturnValForRedirectFilter(filter *dataplane.HTTPRequestRedirectFilter, listenerPort int32) *http.Return {
if filter == nil {
return nil
}
hostname := "$host"
if filter.Hostname != nil {
hostname = *filter.Hostname
}
code := http.StatusFound
if filter.StatusCode != nil {
code = http.StatusCode(*filter.StatusCode)
}
port := listenerPort
if filter.Port != nil {
port = *filter.Port
}
hostnamePort := fmt.Sprintf("%s:%d", hostname, port)
scheme := "$scheme"
if filter.Scheme != nil {
scheme = *filter.Scheme
// Don't specify the port in the return url if the scheme is
// well known and the port is already set to the correct well known port
if (port == 80 && scheme == "http") || (port == 443 && scheme == "https") {
hostnamePort = hostname
}
if filter.Port == nil {
// Don't specify the port in the return url if the scheme is
// well known and the port is not specified by the user
if scheme == "http" || scheme == "https" {
hostnamePort = hostname
}
}
}
return &http.Return{
Code: code,
Body: fmt.Sprintf("%s://%s$request_uri", scheme, hostnamePort),
}
}
func createRewritesValForRewriteFilter(filter *dataplane.HTTPURLRewriteFilter, path string) *rewriteConfig {
if filter == nil {
return nil
}
rewrites := &rewriteConfig{}
if filter.Path != nil {
rewrites.InternalRewrite = "^ $request_uri"
switch filter.Path.Type {
case dataplane.ReplaceFullPath:
rewrites.MainRewrite = fmt.Sprintf("^ %s break", filter.Path.Replacement)
case dataplane.ReplacePrefixMatch:
filterPrefix := filter.Path.Replacement
if filterPrefix == "" {
filterPrefix = "/"
}
// capture everything after the configured prefix
regex := fmt.Sprintf("^%s(.*)$", path)
// replace the configured prefix with the filter prefix and append what was captured
replacement := fmt.Sprintf("%s$1", filterPrefix)
// if configured prefix does not end in /, but replacement prefix does end in /,
// then make sure that we *require* but *don't capture* a trailing slash in the request,
// otherwise we'll get duplicate slashes in the full replacement
if strings.HasSuffix(filterPrefix, "/") && !strings.HasSuffix(path, "/") {
regex = fmt.Sprintf("^%s(?:/(.*))?$", path)
}
// if configured prefix ends in / we won't capture it for a request (since it's not in the regex),
// so append it to the replacement prefix if the replacement prefix doesn't already end in /
if strings.HasSuffix(path, "/") && !strings.HasSuffix(filterPrefix, "/") {
replacement = fmt.Sprintf("%s/$1", filterPrefix)
}
rewrites.MainRewrite = fmt.Sprintf("%s %s break", regex, replacement)
}
}
return rewrites
}
// routeMatch is an internal representation of an HTTPRouteMatch.
// This struct is stored as a key-value pair in /etc/nginx/conf.d/matches.json with a key for the route's path.
// The NJS httpmatches module will look up key specified in the nginx location on the request object
// and compare the request against the Method, Headers, and QueryParams contained in routeMatch.
// If the request satisfies the routeMatch, NGINX will redirect the request to the location RedirectPath.
type routeMatch struct {
// Method is the HTTPMethod of the HTTPRouteMatch.
Method string `json:"method,omitempty"`
// RedirectPath is the path to redirect the request to if the request satisfies the match conditions.
RedirectPath string `json:"redirectPath,omitempty"`
// Headers is a list of HTTPHeaders name value pairs with the format "{name}:{value}".
Headers []string `json:"headers,omitempty"`
// QueryParams is a list of HTTPQueryParams name value pairs with the format "{name}={value}".
QueryParams []string `json:"params,omitempty"`
// Any represents a match with no match conditions.
Any bool `json:"any,omitempty"`
}
func createRouteMatch(match dataplane.Match, redirectPath string) routeMatch {
hm := routeMatch{
RedirectPath: redirectPath,
}
if isPathOnlyMatch(match) {
hm.Any = true
return hm
}
if match.Method != nil {
hm.Method = *match.Method
}
if match.Headers != nil {
headers := make([]string, 0, len(match.Headers))
headerNames := make(map[string]struct{})
for _, h := range match.Headers {
// duplicate header names are not permitted by the spec
// only configure the first entry for every header name (case-insensitive)
lowerName := strings.ToLower(h.Name)
if _, ok := headerNames[lowerName]; !ok {
headers = append(headers, createHeaderKeyValString(h))
headerNames[lowerName] = struct{}{}
}
}
hm.Headers = headers
}
if match.QueryParams != nil {
params := make([]string, 0, len(match.QueryParams))
for _, p := range match.QueryParams {
params = append(params, createQueryParamKeyValString(p))
}
hm.QueryParams = params
}
return hm
}
// The name and values are delimited by "=". A name and value can always be recovered using strings.SplitN(arg,"=", 2).
// Query Parameters are case-sensitive so case is preserved.
func createQueryParamKeyValString(p dataplane.HTTPQueryParamMatch) string {
return p.Name + "=" + p.Value
}
// The name and values are delimited by ":". A name and value can always be recovered using strings.Split(arg, ":").
// Header names are case-insensitive and header values are case-sensitive.
// Ex. foo:bar == FOO:bar, but foo:bar != foo:BAR,
// We preserve the case of the name here because NGINX allows us to look up the header names in a case-insensitive
// manner.
func createHeaderKeyValString(h dataplane.HTTPHeaderMatch) string {
return h.Name + HeaderMatchSeparator + h.Value
}
func isPathOnlyMatch(match dataplane.Match) bool {
return match.Method == nil && len(match.Headers) == 0 && len(match.QueryParams) == 0
}
func createProxyPass(
backendGroup dataplane.BackendGroup,
filter *dataplane.HTTPURLRewriteFilter,
protocol string,
grpc bool,
) string {
var requestURI string
if !grpc {
if filter == nil || filter.Path == nil {
requestURI = "$request_uri"
}
}
backendName := backendGroupName(backendGroup)
if backendGroupNeedsSplit(backendGroup) {
return protocol + "://$" + convertStringToSafeVariableName(backendName) + requestURI
}
return protocol + "://" + backendName + requestURI
}
func createMatchLocation(path string, grpc bool) http.Location {
var rewrites []string
if grpc {
rewrites = []string{"^ $request_uri break"}
}
loc := http.Location{
Path: path,
Rewrites: rewrites,
Type: http.InternalLocationType,
}
return loc
}
func generateProxySetHeaders(filters *dataplane.HTTPFilters, grpc bool) []http.Header {
var headers []http.Header
if !grpc {
headers = make([]http.Header, len(httpBaseHeaders))
copy(headers, httpBaseHeaders)
} else {
headers = make([]http.Header, len(grpcBaseHeaders))
copy(headers, grpcBaseHeaders)
}
if filters != nil && filters.RequestURLRewrite != nil && filters.RequestURLRewrite.Hostname != nil {
for i, header := range headers {
if header.Name == "Host" {
headers[i].Value = *filters.RequestURLRewrite.Hostname
break
}
}
}
if filters == nil || filters.RequestHeaderModifiers == nil {
return headers
}
headerFilter := filters.RequestHeaderModifiers
headerLen := len(headerFilter.Add) + len(headerFilter.Set) + len(headerFilter.Remove) + len(headers)
proxySetHeaders := make([]http.Header, 0, headerLen)
if len(headerFilter.Add) > 0 {
addHeaders := createHeadersWithVarName(headerFilter.Add)
proxySetHeaders = append(proxySetHeaders, addHeaders...)
}
if len(headerFilter.Set) > 0 {
setHeaders := createHeaders(headerFilter.Set)
proxySetHeaders = append(proxySetHeaders, setHeaders...)
}
// If the value of a header field is an empty string then this field will not be passed to a proxied server
for _, h := range headerFilter.Remove {
proxySetHeaders = append(proxySetHeaders, http.Header{
Name: h,
Value: "",
})
}
return append(proxySetHeaders, headers...)
}
func generateResponseHeaders(filters *dataplane.HTTPFilters) http.ResponseHeaders {
if filters == nil || filters.ResponseHeaderModifiers == nil {
return http.ResponseHeaders{}
}
headerFilter := filters.ResponseHeaderModifiers
responseRemoveHeaders := make([]string, len(headerFilter.Remove))
// Make a deep copy to prevent the slice from being accidentally modified.
copy(responseRemoveHeaders, headerFilter.Remove)
return http.ResponseHeaders{
Add: createHeaders(headerFilter.Add),
Set: createHeaders(headerFilter.Set),
Remove: responseRemoveHeaders,
}
}
func createHeadersWithVarName(headers []dataplane.HTTPHeader) []http.Header {
locHeaders := make([]http.Header, 0, len(headers))
for _, h := range headers {
mapVarName := "${" + generateAddHeaderMapVariableName(h.Name) + "}"
locHeaders = append(locHeaders, http.Header{
Name: h.Name,
Value: mapVarName + h.Value,
})
}
return locHeaders
}
func createHeaders(headers []dataplane.HTTPHeader) []http.Header {
locHeaders := make([]http.Header, 0, len(headers))
for _, h := range headers {
locHeaders = append(locHeaders, http.Header{
Name: h.Name,
Value: h.Value,
})
}
return locHeaders
}
func exactPath(path string) string {
return fmt.Sprintf("= %s", path)
}
// createPath builds the location path depending on the path type.
func createPath(rule dataplane.PathRule) string {
switch rule.PathType {
case dataplane.PathTypeExact:
return exactPath(rule.Path)
default:
return rule.Path
}
}
func createDefaultRootLocation() http.Location {
return http.Location{
Path: "/",
Return: &http.Return{Code: http.StatusNotFound},
}
}
// isNonSlashedPrefixPath returns whether or not a path is of type Prefix and does not contain a trailing slash.
func isNonSlashedPrefixPath(pathType dataplane.PathType, path string) bool {
return pathType == dataplane.PathTypePrefix && !strings.HasSuffix(path, "/")
}