-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtransparent.go
More file actions
180 lines (160 loc) · 4.36 KB
/
transparent.go
File metadata and controls
180 lines (160 loc) · 4.36 KB
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
package backend
import (
"bytes"
"context"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/netip"
"net/url"
"sync"
"go.uber.org/zap"
)
type TransparentBackend struct {
logger *zap.Logger
url *url.URL
trusted []netip.Prefix
ctx context.Context
ctxLock sync.Mutex
}
func NewTransparentBackend(logger *zap.Logger, u *url.URL, trusted []string) (Backend, error) {
trn := make([]netip.Prefix, 0, len(trusted))
for _, c := range trusted {
p, err := netip.ParsePrefix(c)
if err != nil {
return nil, err
}
trn = append(trn, p)
}
return &TransparentBackend{
logger: logger,
url: u,
trusted: trn,
}, nil
}
const maxBackendRedirects = 10
// redirectFollowingTransport wraps an http.RoundTripper to transparently
// follow 307/308 redirects from backend servers. This is needed because
// httputil.ReverseProxy uses Transport.RoundTrip() directly, which does
// not follow redirects. Many MCP backends (Starlette/FastAPI) redirect
// /mcp → /mcp/ via 307, which POST-based MCP clients won't follow.
type redirectFollowingTransport struct {
base http.RoundTripper
targetHost string // only follow redirects to this host
}
func (t *redirectFollowingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// Buffer body upfront so we can replay it on redirect.
// MCP JSON-RPC payloads are small, so this is fine.
var bodyBytes []byte
if req.Body != nil {
var err error
bodyBytes, err = io.ReadAll(req.Body)
if err != nil {
return nil, fmt.Errorf("failed to read request body: %w", err)
}
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
}
for i := 0; i <= maxBackendRedirects; i++ {
resp, err := t.base.RoundTrip(req)
if err != nil {
return nil, err
}
// Only follow 307 (Temporary) and 308 (Permanent) redirects.
// These preserve the original method and body per HTTP spec.
if resp.StatusCode != http.StatusTemporaryRedirect &&
resp.StatusCode != http.StatusPermanentRedirect {
return resp, nil
}
location := resp.Header.Get("Location")
if location == "" {
return resp, nil
}
// Resolve relative Location against the request URL
newURL, err := req.URL.Parse(location)
if err != nil {
return resp, nil
}
// Security: only follow redirects to the same backend host.
// Don't leak Authorization headers or body to arbitrary hosts.
if newURL.Host != "" && newURL.Host != t.targetHost {
return resp, nil
}
// Drain and close the redirect response body
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
// Clone the request for the next hop, replaying the body
newReq := req.Clone(req.Context())
newReq.URL = newURL
newReq.Host = newURL.Host
if bodyBytes != nil {
newReq.Body = io.NopCloser(bytes.NewReader(bodyBytes))
newReq.ContentLength = int64(len(bodyBytes))
}
req = newReq
}
return nil, fmt.Errorf("backend exceeded maximum redirects (%d)", maxBackendRedirects)
}
func (p *TransparentBackend) Run(ctx context.Context) (http.Handler, error) {
p.ctxLock.Lock()
defer p.ctxLock.Unlock()
if p.ctx != nil {
return nil, fmt.Errorf("transparent backend is already running")
}
p.ctx = ctx
rp := httputil.ReverseProxy{
Transport: &redirectFollowingTransport{
base: http.DefaultTransport,
targetHost: p.url.Host,
},
FlushInterval: -1,
Rewrite: func(pr *httputil.ProxyRequest) {
pr.SetURL(p.url)
if p.isTrusted(pr.In.RemoteAddr) {
pr.Out.Header["X-Forwarded-For"] = pr.In.Header["X-Forwarded-For"]
}
pr.SetXForwarded()
if p.isTrusted(pr.In.RemoteAddr) {
if v := pr.In.Header.Get("X-Forwarded-Host"); v != "" {
pr.Out.Header.Set("X-Forwarded-Host", v)
}
if v := pr.In.Header.Get("X-Forwarded-Proto"); v != "" {
pr.Out.Header.Set("X-Forwarded-Proto", v)
}
if v := pr.In.Header.Get("X-Forwarded-Port"); v != "" {
pr.Out.Header.Set("X-Forwarded-Port", v)
}
}
},
}
return &rp, nil
}
func (p *TransparentBackend) isTrusted(hostport string) bool {
if host, _, err := net.SplitHostPort(hostport); err == nil {
hostport = host
}
ip, err := netip.ParseAddr(hostport)
if err != nil {
return false
}
if ip.Is4In6() {
ip = ip.Unmap()
}
for _, p := range p.trusted {
if p.Contains(ip) {
return true
}
}
return false
}
func (p *TransparentBackend) Wait() error {
if p.ctx == nil {
return nil
}
<-p.ctx.Done()
return nil
}
func (p *TransparentBackend) Close() error {
return nil
}