├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.yml ├── teeproxy.go └── xff_header_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | teeproxy 25 | 26 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine AS builder 2 | WORKDIR /go/src/teeproxy 3 | COPY teeproxy.go ./ 4 | RUN go mod init teeproxy && go build -o teeproxy 5 | 6 | FROM alpine:3.5 AS runner 7 | COPY --from=builder /go/src/teeproxy/teeproxy /usr/local/bin 8 | ENTRYPOINT ["/usr/local/bin/teeproxy"] 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | teeproxy 2 | ========= 3 | 4 | [![Docker Pulls](https://img.shields.io/docker/pulls/chrislusf/teeproxy.svg?maxAge=604800)](https://hub.docker.com/r/chrislusf/teeproxy/) 5 | 6 | A reverse HTTP proxy that duplicates requests. 7 | 8 | Why you may need this? 9 | ---------------------- 10 | 11 | You may have production servers running, but you need to upgrade to a new system. You want to run A/B test on both old and new systems to confirm the new system can handle the production load, and want to see whether the new system can run in shadow mode continuously without any issue. 12 | 13 | How it works? 14 | ------------- 15 | 16 | teeproxy is a reverse HTTP proxy. For each incoming request, it clones the request into 2 requests, forwards them to 2 servers. The results from server A are returned as usual, but the results from server B are ignored. 17 | 18 | teeproxy handles GET, POST, and all other http methods. 19 | 20 | Build 21 | ------------- 22 | 23 | ``` 24 | go build 25 | ``` 26 | 27 | Usage 28 | ------------- 29 | 30 | ``` 31 | ./teeproxy -l :8888 -a [http(s)://]localhost:9000 -b [http(s)://]localhost:9001 [-b [http(s)://]localhost:9002] 32 | ``` 33 | 34 | `-l` specifies the listening port. `-a` and `-b` are meant for system A and systems B. The B systems can be taken down or started up without causing any issue to the teeproxy. 35 | 36 | #### Configuring timeouts #### 37 | 38 | It's also possible to configure the timeout to both systems 39 | 40 | * `-a.timeout int`: timeout in milliseconds for production traffic (default `2500`) 41 | * `-b.timeout int`: timeout in milliseconds for alternate site traffic (default `1000`) 42 | 43 | #### Configuring host header rewrite #### 44 | 45 | Optionally rewrite host value in the http request header. 46 | 47 | * `-a.rewrite bool`: rewrite for production traffic (default `false`) 48 | * `-b.rewrite bool`: rewrite for alternate site traffic (default `false`) 49 | 50 | #### Configuring a percentage of requests to alternate site #### 51 | 52 | * `-p float64`: only send a percentage of requests. The value is float64 for more precise control. (default `100.0`) 53 | 54 | #### Configuring HTTPS #### 55 | 56 | * `-key.file string`: a TLS private key file. (default `""`) 57 | * `-cert.file string`: a TLS certificate file. (default `""`) 58 | 59 | #### Configuring client IP forwarding #### 60 | 61 | It's possible to write `X-Forwarded-For` and `Forwarded` header (RFC 7239) so 62 | that the production and alternate backends know about the clients: 63 | 64 | * `-forward-client-ip` (default is false) 65 | 66 | #### Configuring connection handling #### 67 | 68 | By default, teeproxy tries to reuse connections. This can be turned off, if the 69 | endpoints do not support this. 70 | 71 | * `-close-connections` (default is false) 72 | 73 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | teeproxy: 2 | image: ankitguptag18/teeproxy:distroless-static 3 | ports: 4 | - "8000:8000" 5 | command: /teeproxy -l=:8000 -a="hostname1:8888" -b="hostname2:9908" -debug=false 6 | 7 | 8 | -------------------------------------------------------------------------------- /teeproxy.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/tls" 6 | "flag" 7 | "io" 8 | "io/ioutil" 9 | "log" 10 | "math/rand" 11 | "net" 12 | "net/http" 13 | "net/url" 14 | "regexp" 15 | "runtime" 16 | "strings" 17 | "time" 18 | ) 19 | 20 | // Console flags 21 | var ( 22 | listen = flag.String("l", ":8888", "port to accept requests") 23 | targetProduction = flag.String("a", "localhost:8080", "where production traffic goes. http://localhost:8080/production") 24 | debug = flag.Bool("debug", false, "more logging, showing ignored output") 25 | productionTimeout = flag.Int("a.timeout", 2500, "timeout in milliseconds for production traffic") 26 | alternateTimeout = flag.Int("b.timeout", 1000, "timeout in milliseconds for alternate site traffic") 27 | productionHostRewrite = flag.Bool("a.rewrite", false, "rewrite the host header when proxying production traffic") 28 | alternateHostRewrite = flag.Bool("b.rewrite", false, "rewrite the host header when proxying alternate site traffic") 29 | alternateMethods = flag.String("b.methods", "", "forward only the given HTTP methods matched by regex") 30 | percent = flag.Float64("p", 100.0, "float64 percentage of traffic to send to testing") 31 | tlsPrivateKey = flag.String("key.file", "", "path to the TLS private key file") 32 | tlsCertificate = flag.String("cert.file", "", "path to the TLS certificate file") 33 | forwardClientIP = flag.Bool("forward-client-ip", false, "enable forwarding of the client IP to the backend using the 'X-Forwarded-For' and 'Forwarded' headers") 34 | closeConnections = flag.Bool("close-connections", false, "close connections to the clients and backends") 35 | 36 | alternateMethodsRegex *regexp.Regexp 37 | ) 38 | 39 | // Sets the request URL. 40 | // 41 | // This turns a inbound request (a request without URL) into an outbound request. 42 | func setRequestTarget(request *http.Request, target string, scheme string) { 43 | URL, err := url.Parse(scheme + "://" + target + request.URL.String()) 44 | if err != nil { 45 | log.Println(err) 46 | } 47 | request.URL = URL 48 | } 49 | 50 | func getTransport(scheme string, timeout time.Duration) (transport *http.Transport) { 51 | if scheme == "https" { 52 | transport = &http.Transport{ 53 | Dial: (&net.Dialer{ // go1.8 deprecated: Use DialContext instead 54 | Timeout: timeout, 55 | KeepAlive: 10 * timeout, 56 | }).Dial, 57 | DisableKeepAlives: *closeConnections, 58 | TLSHandshakeTimeout: timeout, 59 | ResponseHeaderTimeout: timeout, 60 | TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, 61 | } 62 | } else { 63 | transport = &http.Transport{ 64 | Dial: (&net.Dialer{ // go1.8 deprecated: Use DialContext instead 65 | Timeout: timeout, 66 | KeepAlive: 10 * timeout, 67 | }).Dial, 68 | DisableKeepAlives: *closeConnections, 69 | TLSHandshakeTimeout: timeout, 70 | ResponseHeaderTimeout: timeout, 71 | } 72 | } 73 | return 74 | } 75 | 76 | // handleAlternativeRequest duplicate request and sent it to alternative backend 77 | func handleAlternativeRequest(request *http.Request, timeout time.Duration, scheme string) { 78 | defer func() { 79 | if r := recover(); r != nil && *debug { 80 | log.Println("Recovered in ServeHTTP(alternate request) from:", r) 81 | } 82 | }() 83 | response := handleRequest(request, timeout, scheme) 84 | if response != nil { 85 | log.Printf("| B | \"%s %s %v\" %s", request.Method, request.URL.RequestURI(), request.Proto, response.Status) 86 | response.Body.Close() 87 | } 88 | } 89 | 90 | // Sends a request and returns the response. 91 | func handleRequest(request *http.Request, timeout time.Duration, scheme string) *http.Response { 92 | transport := getTransport(scheme, timeout) 93 | response, err := transport.RoundTrip(request) 94 | if err != nil { 95 | log.Println("Request failed:", err) 96 | } 97 | return response 98 | } 99 | 100 | // SchemeAndHost parse URL into scheme and rest of endpoint 101 | func SchemeAndHost(url string) (scheme, hostname string) { 102 | if strings.HasPrefix(url, "https") { 103 | hostname = strings.TrimPrefix(url, "https://") 104 | scheme = "https" 105 | } else { 106 | hostname = strings.TrimPrefix(url, "http://") 107 | scheme = "http" 108 | } 109 | return 110 | } 111 | 112 | // handler contains the address of the main Target and the one for the Alternative target 113 | type handler struct { 114 | Target string 115 | TargetScheme string 116 | Alternatives []backend 117 | Randomizer rand.Rand 118 | } 119 | 120 | type backend struct { 121 | Alternative string 122 | AlternativeScheme string 123 | } 124 | 125 | type arrayAlternatives []backend 126 | 127 | func (i *arrayAlternatives) String() string { 128 | return "my string representation" 129 | } 130 | 131 | func (i *arrayAlternatives) Set(value string) error { 132 | scheme, endpoint := SchemeAndHost(value) 133 | altServer := backend{AlternativeScheme: scheme, Alternative: endpoint} 134 | *i = append(*i, altServer) 135 | return nil 136 | } 137 | 138 | func (h *handler) SetSchemes() { 139 | h.TargetScheme, h.Target = SchemeAndHost(h.Target) 140 | } 141 | 142 | // ServeHTTP duplicates the incoming request (req) and does the request to the 143 | // Target and the Alternate target discading the Alternate response 144 | func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { 145 | var alternativeRequest *http.Request 146 | var productionRequest *http.Request 147 | 148 | if *forwardClientIP { 149 | updateForwardedHeaders(req) 150 | } 151 | if *percent == 100.0 || h.Randomizer.Float64()*100 < *percent { 152 | if matchedByHttpMethod(req.Method) { 153 | for _, alt := range h.Alternatives { 154 | alternativeRequest = DuplicateRequest(req) 155 | 156 | timeout := time.Duration(*alternateTimeout) * time.Millisecond 157 | 158 | setRequestTarget(alternativeRequest, alt.Alternative, alt.AlternativeScheme) 159 | 160 | if *alternateHostRewrite { 161 | alternativeRequest.Host = alt.Alternative 162 | } 163 | 164 | go handleAlternativeRequest(alternativeRequest, timeout, alt.AlternativeScheme) 165 | } 166 | } 167 | } 168 | 169 | productionRequest = req 170 | defer func() { 171 | if r := recover(); r != nil && *debug { 172 | log.Println("Recovered in ServeHTTP(production request) from:", r) 173 | } 174 | }() 175 | 176 | setRequestTarget(productionRequest, h.Target, h.TargetScheme) 177 | 178 | if *productionHostRewrite { 179 | productionRequest.Host = h.Target 180 | } 181 | 182 | timeout := time.Duration(*productionTimeout) * time.Millisecond 183 | resp := handleRequest(productionRequest, timeout, h.TargetScheme) 184 | 185 | if resp != nil { 186 | defer resp.Body.Close() 187 | 188 | log.Printf("| A | \"%s %s %v\" %s", productionRequest.Method, productionRequest.URL.RequestURI(), productionRequest.Proto, resp.Status) 189 | 190 | // Forward response headers. 191 | for k, v := range resp.Header { 192 | w.Header()[k] = v 193 | } 194 | w.WriteHeader(resp.StatusCode) 195 | 196 | // Forward response body. 197 | io.Copy(w, resp.Body) 198 | } 199 | } 200 | 201 | func matchedByHttpMethod(requestMethod string) bool { 202 | if alternateMethodsRegex == nil { 203 | return true 204 | } 205 | return alternateMethodsRegex.MatchString(requestMethod) 206 | } 207 | 208 | func main() { 209 | var altServers arrayAlternatives 210 | flag.Var(&altServers, "b", "where testing traffic goes. response are skipped. http://localhost:8081/test, allowed multiple times for multiple testing backends") 211 | flag.Parse() 212 | 213 | if *alternateMethods != "" { 214 | alternateMethodsRegex = regexp.MustCompile(*alternateMethods) 215 | } 216 | 217 | log.Printf("Starting teeproxy at %s sending to A: %s and B: %s", 218 | *listen, *targetProduction, altServers) 219 | 220 | runtime.GOMAXPROCS(runtime.NumCPU()) 221 | 222 | var err error 223 | 224 | var listener net.Listener 225 | 226 | if len(*tlsPrivateKey) > 0 { 227 | cer, err := tls.LoadX509KeyPair(*tlsCertificate, *tlsPrivateKey) 228 | if err != nil { 229 | log.Fatalf("Failed to load certficate: %s and private key: %s", *tlsCertificate, *tlsPrivateKey) 230 | } 231 | 232 | config := &tls.Config{Certificates: []tls.Certificate{cer}} 233 | listener, err = tls.Listen("tcp", *listen, config) 234 | if err != nil { 235 | log.Fatalf("Failed to listen to %s: %s", *listen, err) 236 | } 237 | } else { 238 | listener, err = net.Listen("tcp", *listen) 239 | if err != nil { 240 | log.Fatalf("Failed to listen to %s: %s", *listen, err) 241 | } 242 | } 243 | 244 | h := handler{ 245 | Target: *targetProduction, 246 | Alternatives: arrayAlternatives(altServers), 247 | Randomizer: *rand.New(rand.NewSource(time.Now().UnixNano())), 248 | } 249 | 250 | h.SetSchemes() 251 | 252 | server := &http.Server{ 253 | Handler: h, 254 | } 255 | if *closeConnections { 256 | // Close connections to clients by setting the "Connection": "close" header in the response. 257 | server.SetKeepAlivesEnabled(false) 258 | } 259 | server.Serve(listener) 260 | } 261 | 262 | type nopCloser struct { 263 | io.Reader 264 | } 265 | 266 | func (nopCloser) Close() error { return nil } 267 | 268 | // DuplicateRequest duplicate http request 269 | func DuplicateRequest(request *http.Request) (dup *http.Request) { 270 | var bodyBytes []byte 271 | if request.Body != nil { 272 | bodyBytes, _ = ioutil.ReadAll(request.Body) 273 | } 274 | request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) 275 | dup = &http.Request{ 276 | Method: request.Method, 277 | URL: request.URL, 278 | Proto: request.Proto, 279 | ProtoMajor: request.ProtoMajor, 280 | ProtoMinor: request.ProtoMinor, 281 | Header: request.Header, 282 | Body: ioutil.NopCloser(bytes.NewBuffer(bodyBytes)), 283 | Host: request.Host, 284 | ContentLength: request.ContentLength, 285 | Close: true, 286 | } 287 | return 288 | } 289 | 290 | func updateForwardedHeaders(request *http.Request) { 291 | positionOfColon := strings.LastIndex(request.RemoteAddr, ":") 292 | var remoteIP string 293 | if positionOfColon != -1 { 294 | remoteIP = request.RemoteAddr[:positionOfColon] 295 | } else { 296 | log.Printf("The default format of request.RemoteAddr should be IP:Port but was %s\n", remoteIP) 297 | remoteIP = request.RemoteAddr 298 | } 299 | insertOrExtendForwardedHeader(request, remoteIP) 300 | insertOrExtendXFFHeader(request, remoteIP) 301 | } 302 | 303 | const XFF_HEADER = "X-Forwarded-For" 304 | 305 | func insertOrExtendXFFHeader(request *http.Request, remoteIP string) { 306 | header := request.Header.Get(XFF_HEADER) 307 | if header != "" { 308 | // extend 309 | request.Header.Set(XFF_HEADER, header+", "+remoteIP) 310 | } else { 311 | // insert 312 | request.Header.Set(XFF_HEADER, remoteIP) 313 | } 314 | } 315 | 316 | const FORWARDED_HEADER = "Forwarded" 317 | 318 | // Implementation according to rfc7239 319 | func insertOrExtendForwardedHeader(request *http.Request, remoteIP string) { 320 | extension := "for=" + remoteIP 321 | header := request.Header.Get(FORWARDED_HEADER) 322 | if header != "" { 323 | // extend 324 | request.Header.Set(FORWARDED_HEADER, header+", "+extension) 325 | } else { 326 | // insert 327 | request.Header.Set(FORWARDED_HEADER, extension) 328 | } 329 | } 330 | -------------------------------------------------------------------------------- /xff_header_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | "testing" 6 | ) 7 | 8 | func TestNoHeaderProvided(t *testing.T) { 9 | adserverRequest, _ := http.NewRequest("GET", "ad1/test", nil) 10 | adserverRequest.RemoteAddr = "192.168.0.1:80" 11 | updateForwardedHeaders(adserverRequest) 12 | var xffHeader = adserverRequest.Header.Get("X-FORWARDED-FOR") 13 | var forwardedHeader = adserverRequest.Header.Get("FORWARDED") 14 | if expectation := "192.168.0.1"; xffHeader != expectation { 15 | t.Errorf("Expected ''%s'', but received ''%s''", expectation, xffHeader) 16 | } 17 | if expectation := "for=192.168.0.1"; forwardedHeader != expectation { 18 | t.Errorf("Expected '%s', but received '%s'", expectation, forwardedHeader) 19 | } 20 | } 21 | 22 | func TestOnlyXFFProvided(t *testing.T) { 23 | adserverRequest, _ := http.NewRequest("GET", "ad1/test", nil) 24 | adserverRequest.RemoteAddr = "192.168.0.1:80" 25 | adserverRequest.Header.Add("X-FORWARDED-FOR", "172.20.2.5") 26 | updateForwardedHeaders(adserverRequest) 27 | var xffHeader = adserverRequest.Header.Get("X-FORWARDED-FOR") 28 | var forwardedHeader = adserverRequest.Header.Get("FORWARDED") 29 | if expectation := "172.20.2.5, 192.168.0.1"; xffHeader != expectation { 30 | t.Errorf("Expected '%s', but received '%s'", expectation, xffHeader) 31 | } 32 | if expectation := "for=192.168.0.1"; forwardedHeader != expectation { 33 | t.Errorf("Expected '%s', but received '%s'", expectation, forwardedHeader) 34 | } 35 | } 36 | 37 | func TestOnlyForwardedProvided(t *testing.T) { 38 | adserverRequest, _ := http.NewRequest("GET", "ad1/test", nil) 39 | adserverRequest.RemoteAddr = "192.168.0.1:80" 40 | adserverRequest.Header.Add("FORWARDED", "for=172.20.2.5") 41 | updateForwardedHeaders(adserverRequest) 42 | var xffHeader = adserverRequest.Header.Get("X-FORWARDED-FOR") 43 | var forwardedHeader = adserverRequest.Header.Get("FORWARDED") 44 | if expectation := "192.168.0.1"; xffHeader != expectation { 45 | t.Errorf("Expected '%s', but received '%s'", expectation, xffHeader) 46 | } 47 | if expectation := "for=172.20.2.5, for=192.168.0.1"; forwardedHeader != expectation { 48 | t.Errorf("Expected '%s', but received '%s'", expectation, forwardedHeader) 49 | } 50 | } 51 | 52 | func TestBothProvided(t *testing.T) { 53 | adserverRequest, _ := http.NewRequest("GET", "ad1/test", nil) 54 | adserverRequest.RemoteAddr = "192.168.0.1:80" 55 | adserverRequest.Header.Add("FORWARDED", "for=172.20.2.5") 56 | adserverRequest.Header.Add("X-FORWARDED-FOR", "172.20.2.5") 57 | updateForwardedHeaders(adserverRequest) 58 | var xffHeader = adserverRequest.Header.Get("X-FORWARDED-FOR") 59 | var forwardedHeader = adserverRequest.Header.Get("FORWARDED") 60 | if expectation := "172.20.2.5, 192.168.0.1"; xffHeader != expectation { 61 | t.Errorf("Expected '%s', but received '%s'", expectation, xffHeader) 62 | } 63 | if expectation := "for=172.20.2.5, for=192.168.0.1"; forwardedHeader != expectation { 64 | t.Errorf("Expected '%s', but received '%s'", expectation, forwardedHeader) 65 | } 66 | } 67 | 68 | func TestBothProvidedWithMoreProxies(t *testing.T) { 69 | adserverRequest, _ := http.NewRequest("GET", "ad1/test", nil) 70 | adserverRequest.RemoteAddr = "192.168.0.15:80" 71 | adserverRequest.Header.Add("FORWARDED", "for=172.20.2.5, for=172.20.2.36") 72 | adserverRequest.Header.Add("X-FORWARDED-FOR", "172.20.2.5, 172.20.2.36") 73 | updateForwardedHeaders(adserverRequest) 74 | var xffHeader = adserverRequest.Header.Get("X-FORWARDED-FOR") 75 | var forwardedHeader = adserverRequest.Header.Get("FORWARDED") 76 | if expectation := "172.20.2.5, 172.20.2.36, 192.168.0.15"; xffHeader != expectation { 77 | t.Errorf("Expected '%s', but received '%s'", expectation, xffHeader) 78 | } 79 | if expectation := "for=172.20.2.5, for=172.20.2.36, for=192.168.0.15"; forwardedHeader != expectation { 80 | t.Errorf("Expected '%s', but received '%s'", expectation, forwardedHeader) 81 | } 82 | } 83 | --------------------------------------------------------------------------------