This repository has been archived by the owner on Nov 22, 2022. It is now read-only.
forked from cllunsford/aws-signing-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
195 lines (170 loc) · 6.09 KB
/
main.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
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/kelseyhightower/envconfig"
)
type EnvConfig struct {
Target string
Port int `default:"8080"`
Service string `default:"es"`
}
type AppConfig struct {
Service string
FlushInterval time.Duration
IdleConnTimeout time.Duration
DialTimeout time.Duration
}
// NewSigningProxy proxies requests to AWS services which require URL signing using the provided credentials
func NewSigningProxy(target *url.URL, creds *credentials.Credentials, region string, appConfig AppConfig) *httputil.ReverseProxy {
director := func(req *http.Request) {
// Rewrite request to desired server host
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.Host = target.Host
// To perform the signing, we leverage aws-sdk-go
// aws.request performs more functions than we need here
// we only populate enough of the fields to successfully
// sign the request
config := aws.NewConfig().WithCredentials(creds).WithRegion(region)
clientInfo := metadata.ClientInfo{
ServiceName: appConfig.Service,
}
operation := &request.Operation{
Name: "",
HTTPMethod: req.Method,
HTTPPath: req.URL.Path,
}
handlers := request.Handlers{}
handlers.Sign.PushBack(v4.SignSDKRequest)
// Do we need to use request.New ? Or can we create a raw Request struct and
// jus swap out the HTTPRequest with our own existing one?
awsReq := request.New(*config, clientInfo, handlers, nil, operation, nil, nil)
// Referenced during the execution of awsReq.Sign():
// req.Config.Credentials
// req.Config.LogLevel.Value()
// req.Config.Logger
// req.ClientInfo.SigningRegion (will default to Config.Region)
// req.ClientInfo.SigningName (will default to ServiceName)
// req.ClientInfo.ServiceName
// req.HTTPRequest
// req.Time
// req.ExpireTime
// req.Body
// Set the body in the awsReq for calculation of body Digest
// iotuil.ReadAll reads the Body from the stream so it can be copied into awsReq
// This drains the body from the original (proxied) request.
// To fix, we replace req.Body with a copy (NopCloser provides io.ReadCloser interface)
if req.Body != nil {
buf, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("error reading request body: %v\n", err)
}
req.Body = ioutil.NopCloser(bytes.NewBuffer(buf))
awsReq.SetBufferBody(buf)
}
// Use the updated req.URL for creating the signed request
// We pass the full URL object to include Host, Scheme, and any params
awsReq.HTTPRequest.URL = req.URL
if awsReq.HTTPRequest.URL.Path == "/" || awsReq.HTTPRequest.URL.Path == "" {
awsReq.HTTPRequest.URL.Path = "/index.html"
}
// These are now set above via req, but it's imperative that this remains
// correctly set before calling .Sign()
//awsReq.HTTPRequest.URL.Scheme = target.Scheme
//awsReq.HTTPRequest.URL.Host = target.Host
// Perform the signing, updating awsReq in place
if err := awsReq.Sign(); err != nil {
log.Printf("error signing: %v\n", err)
}
// Write the Signed Headers into the Original Request
for k, v := range awsReq.HTTPRequest.Header {
req.Header[k] = v
}
}
// transport is http.DefaultTransport but with the ability to override some
// timeouts
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: appConfig.DialTimeout,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: appConfig.IdleConnTimeout,
TLSHandshakeTimeout: 10 * time.Second,
}
return &httputil.ReverseProxy{
Director: director,
FlushInterval: appConfig.FlushInterval,
Transport: transport,
}
}
func main() {
// Adding envconfig to allow setting key vars via ENV
var e EnvConfig
if err := envconfig.Process("ASP", &e); err != nil {
log.Fatal(err.Error())
}
if val, ok := os.LookupEnv("AWS_ES_TARGET"); ok {
e.Target = val
}
var targetFlag = flag.String("target", e.Target, "target url to proxy to")
var portFlag = flag.Int("port", e.Port, "listening port for proxy")
var serviceFlag = flag.String("service", e.Service, "AWS Service.")
var regionFlag = flag.String("region", os.Getenv("AWS_REGION"), "AWS region for credentials")
var flushInterval = flag.Duration("flush-interval", 0, "Flush interval to flush to the client while copying the response body.")
var idleConnTimeout = flag.Duration("idle-conn-timeout", 90*time.Second, "the maximum amount of time an idle (keep-alive) connection will remain idle before closing itself. Zero means no limit.")
var dialTimeout = flag.Duration("dial-timeout", 30*time.Second, "The maximum amount of time a dial will wait for a connect to complete.")
flag.Parse()
appC := AppConfig{
Service: *serviceFlag,
FlushInterval: *flushInterval,
IdleConnTimeout: *idleConnTimeout,
DialTimeout: *dialTimeout,
}
// Validate target URL
if len(*targetFlag) == 0 {
log.Fatal("Requires target URL to proxy to. Please use the -target flag")
}
targetURL, err := url.Parse(*targetFlag)
if err != nil {
log.Fatal(err.Error())
}
// Get credentials:
// Environment variables > local aws config file > remote role provider
// https://github.com/aws/aws-sdk-go/blob/master/aws/defaults/defaults.go#L88
creds := defaults.CredChain(defaults.Config(), defaults.Handlers())
if _, err = creds.Get(); err != nil {
// We couldn't get any credentials
fmt.Println(err)
return
}
// Region order of precident:
// regionFlag > os.Getenv("AWS_REGION") > "us-west-2"
region := *regionFlag
if len(region) == 0 {
region = "us-west-2"
}
// Start the proxy server
proxy := NewSigningProxy(targetURL, creds, region, appC)
listenString := fmt.Sprintf(":%v", *portFlag)
fmt.Printf("Listening on %v\n", listenString)
http.ListenAndServe(listenString, proxy)
}