/
server.go
167 lines (141 loc) · 4.39 KB
/
server.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
// Copyright The OpenTelemetry Authors
//
// 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 proxy provides an http server to act as a signing proxy for SDKs calling AWS X-Ray APIs
package proxy
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"net/url"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/endpoints"
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
"go.uber.org/zap"
)
const (
service = "xray"
connHeader = "Connection"
)
// Server represents HTTP server.
type Server interface {
ListenAndServe() error
Close() error
}
// NewServer returns a local TCP server that proxies requests to AWS
// backend using the given credentials.
func NewServer(cfg *Config, logger *zap.Logger) (Server, error) {
_, err := net.ResolveTCPAddr("tcp", cfg.Endpoint)
if err != nil {
return nil, err
}
if cfg.ProxyAddress != "" {
logger.Debug("Using remote proxy", zap.String("address", cfg.ProxyAddress))
}
awsCfg, sess, err := getAWSConfigSession(cfg, logger)
if err != nil {
return nil, err
}
awsEndPoint, err := getServiceEndpoint(awsCfg)
if err != nil {
return nil, err
}
// Parse url from endpoint
awsURL, err := url.Parse(awsEndPoint)
if err != nil {
return nil, fmt.Errorf("unable to parse AWS service endpoint: %w", err)
}
signer := &v4.Signer{
Credentials: sess.Config.Credentials,
}
transport, err := proxyServerTransport(cfg)
if err != nil {
return nil, err
}
// Reverse proxy handler
handler := &httputil.ReverseProxy{
Transport: transport,
// Handler for modifying and forwarding requests
Director: func(req *http.Request) {
if req != nil && req.URL != nil {
logger.Debug("Received request on X-Ray receiver TCP proxy server", zap.String("URL", req.URL.String()))
}
// Remove connection header before signing request, otherwise the
// reverse-proxy will remove the header before forwarding to X-Ray
// resulting in a signed header being missing from the request.
req.Header.Del(connHeader)
// Set req url to xray endpoint
req.URL.Scheme = awsURL.Scheme
req.URL.Host = awsURL.Host
req.Host = awsURL.Host
// Consume body and convert to io.ReadSeeker for signer to consume
body, err := consume(req.Body)
if err != nil {
logger.Error("Unable to consume request body", zap.Error(err))
// Forward unsigned request
return
}
// Sign request. signer.Sign() also repopulates the request body.
_, err = signer.Sign(req, body, service, *awsCfg.Region, time.Now())
if err != nil {
logger.Error("Unable to sign request", zap.Error(err))
}
},
}
return &http.Server{
Addr: cfg.Endpoint,
Handler: handler,
}, nil
}
// getServiceEndpoint returns X-Ray service endpoint.
// It is guaranteed that awsCfg config instance is non-nil and the region value is non nil or non empty in awsCfg object.
// Currently the caller takes care of it.
func getServiceEndpoint(awsCfg *aws.Config) (string, error) {
if isEmpty(awsCfg.Endpoint) {
if isEmpty(awsCfg.Region) {
return "", errors.New("unable to generate endpoint from region with nil value")
}
resolved, err := endpoints.DefaultResolver().EndpointFor(service, *awsCfg.Region, setResolverConfig())
return resolved.URL, err
}
return *awsCfg.Endpoint, nil
}
func isEmpty(val *string) bool {
return val == nil || *val == ""
}
// consume readsAll() the body and creates a new io.ReadSeeker from the content. v4.Signer
// requires an io.ReadSeeker to be able to sign requests. May return a nil io.ReadSeeker.
func consume(body io.ReadCloser) (io.ReadSeeker, error) {
var buf []byte
// Return nil ReadSeeker if body is nil
if body == nil {
return nil, nil
}
// Consume body
buf, err := ioutil.ReadAll(body)
if err != nil {
return nil, err
}
return bytes.NewReader(buf), nil
}
func setResolverConfig() func(*endpoints.Options) {
return func(p *endpoints.Options) {
p.ResolveUnknownService = true
}
}