File
Blob: gateway/proxy_handler.go
| 1 | package gateway |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "log" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "net/http/httputil" |
| 12 | "net/url" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | "time" |
| 16 | |
| 17 | "go.miragespace.co/specter/spec/protocol" |
| 18 | "go.miragespace.co/specter/spec/rpc" |
| 19 | "go.miragespace.co/specter/spec/tun" |
| 20 | "go.miragespace.co/specter/util" |
| 21 | |
| 22 | "github.com/alecthomas/units" |
| 23 | "github.com/go-chi/chi/v5" |
| 24 | "github.com/go-chi/chi/v5/middleware" |
| 25 | "go.uber.org/zap" |
| 26 | ) |
| 27 | |
| 28 | var delHeaders = []string{ |
| 29 | "True-Client-IP", |
| 30 | "X-Real-IP", |
| 31 | "X-Forwarded-For", |
| 32 | } |
| 33 | |
| 34 | const ( |
| 35 | proxyHeaderTimeout = time.Second * 300 // global limit of how long the gateway will wait for response |
| 36 | ) |
| 37 | |
| 38 | // inspiration from https://blog.cloudflare.com/eliminating-cold-starts-with-cloudflare-workers/ |
| 39 | // warm the route cache when tls handshake begins |
| 40 | func (g *Gateway) HandshakeEarlyHint(sni string) { |
| 41 | if g.HandshakeHintFunc == nil { |
| 42 | return |
| 43 | } |
| 44 | hostname, err := g.extractHostname(sni) |
| 45 | if err != nil { |
| 46 | return |
| 47 | } |
| 48 | if slices.Contains(g.RootDomains, hostname) { |
| 49 | return |
| 50 | } |
| 51 | g.Logger.Debug("Handshake early hint", zap.String("hostname", hostname)) |
| 52 | // TODO: implement a limiter |
| 53 | go g.HandshakeHintFunc(hostname) |
| 54 | } |
| 55 | |
| 56 | func (g *Gateway) httpConnect(w http.ResponseWriter, r *http.Request) { |
| 57 | remote, err := g.connectDialer(r.Context(), r) |
| 58 | if err != nil { |
| 59 | http.Error(w, err.Error(), http.StatusNotFound) |
| 60 | return |
| 61 | } |
| 62 | status := protocol.TunnelStatus{} |
| 63 | err = rpc.BoundedReceive(remote, &status, 1024) |
| 64 | if err != nil { |
| 65 | http.Error(w, err.Error(), http.StatusBadGateway) |
| 66 | remote.Close() |
| 67 | return |
| 68 | } |
| 69 | if status.Status != protocol.TunnelStatusCode_STATUS_OK { |
| 70 | http.Error(w, status.GetError(), http.StatusServiceUnavailable) |
| 71 | remote.Close() |
| 72 | return |
| 73 | } |
| 74 | |
| 75 | rc := http.NewResponseController(w) |
| 76 | local, rw, err := rc.Hijack() |
| 77 | if err != nil { |
| 78 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 79 | remote.Close() |
| 80 | return |
| 81 | } |
| 82 | |
| 83 | connectResp := http.Response{ |
| 84 | StatusCode: http.StatusOK, |
| 85 | Proto: r.Proto, |
| 86 | ProtoMajor: r.ProtoMajor, |
| 87 | ProtoMinor: r.ProtoMinor, |
| 88 | } |
| 89 | connectResp.Write(rw) |
| 90 | rw.Flush() |
| 91 | |
| 92 | tun.Pipe(local, remote) |
| 93 | } |
| 94 | |
| 95 | func (g *Gateway) extractHostname(host string) (hostname string, err error) { |
| 96 | if net.ParseIP(host) != nil { |
| 97 | err = fmt.Errorf("gateway: hostname cannot be IP") |
| 98 | return |
| 99 | } |
| 100 | if strings.Count(host, ".") < 2 { |
| 101 | err = fmt.Errorf("gateway: too few labels in hostname") |
| 102 | return |
| 103 | } |
| 104 | parts := strings.SplitN(host, ".", 2) |
| 105 | if len(parts) != 2 { |
| 106 | err = fmt.Errorf("gateway: invalid hostname for forwarding") |
| 107 | return |
| 108 | } |
| 109 | if slices.Contains(g.RootDomains, parts[1]) { |
| 110 | hostname = parts[0] |
| 111 | } else { |
| 112 | hostname = host |
| 113 | } |
| 114 | hostname = strings.ToLower(hostname) |
| 115 | return |
| 116 | } |
| 117 | |
| 118 | func (g *Gateway) parseAddr(addr string) (host, hostname string, err error) { |
| 119 | host, _, err = net.SplitHostPort(addr) |
| 120 | if err != nil { |
| 121 | return |
| 122 | } |
| 123 | hostname, err = g.extractHostname(host) |
| 124 | return |
| 125 | } |
| 126 | |
| 127 | func (g *Gateway) connectDialer(ctx context.Context, r *http.Request) (conn net.Conn, err error) { |
| 128 | defer func() { |
| 129 | if pr := recover(); pr != nil { |
| 130 | err = fmt.Errorf("connectDialer panic: %v", pr) |
| 131 | } |
| 132 | }() |
| 133 | |
| 134 | host, hostname, err := g.parseAddr(r.Host) |
| 135 | if err != nil { |
| 136 | return nil, err |
| 137 | } |
| 138 | connectHostname.Add(hostname, 1) |
| 139 | g.Logger.Debug("Dialing to client via overlay (HTTP Connect)", zap.String("hostname", hostname), zap.String("req.URL.Host", host)) |
| 140 | return g.TunnelServer.DialClient(ctx, &protocol.Link{ |
| 141 | Alpn: protocol.Link_TCP, |
| 142 | Hostname: hostname, |
| 143 | Remote: r.RemoteAddr, |
| 144 | }) |
| 145 | } |
| 146 | |
| 147 | func (g *Gateway) overlayDialer(ctx context.Context, addr string) (conn net.Conn, err error) { |
| 148 | defer func() { |
| 149 | if pr := recover(); pr != nil { |
| 150 | err = fmt.Errorf("overlayDialer panic: %v", pr) |
| 151 | } |
| 152 | }() |
| 153 | |
| 154 | host, hostname, err := g.parseAddr(addr) |
| 155 | if err != nil { |
| 156 | return nil, err |
| 157 | } |
| 158 | g.Logger.Debug("Dialing to client via overlay (HTTP)", zap.String("hostname", hostname), zap.String("req.URL.Host", host)) |
| 159 | return g.TunnelServer.DialClient(ctx, &protocol.Link{ |
| 160 | Alpn: protocol.Link_HTTP, |
| 161 | Hostname: hostname, |
| 162 | Remote: g.TunnelServer.Identity().GetAddress(), // include gateway address as placeholder |
| 163 | }) |
| 164 | } |
| 165 | |
| 166 | func (g *Gateway) forwardTCP(ctx context.Context, host string, remote string, conn DeadlineReadWriteCloser) error { |
| 167 | var ( |
| 168 | hostname string |
| 169 | c net.Conn |
| 170 | err error |
| 171 | ) |
| 172 | defer func() { |
| 173 | if err != nil { |
| 174 | tun.SendStatusProto(conn, err) |
| 175 | conn.Close() |
| 176 | return |
| 177 | } |
| 178 | tun.Pipe(conn, c) |
| 179 | }() |
| 180 | |
| 181 | // because of quic's early connection, the client need to "poke" us before |
| 182 | // we can actually accept a stream, despite .OpenStreamSync |
| 183 | conn.SetReadDeadline(time.Now().Add(time.Second * 3)) |
| 184 | err = tun.DrainStatusProto(conn) |
| 185 | if err != nil { |
| 186 | return err |
| 187 | } |
| 188 | conn.SetReadDeadline(time.Time{}) |
| 189 | |
| 190 | hostname, err = g.extractHostname(host) |
| 191 | if err != nil { |
| 192 | return err |
| 193 | } |
| 194 | |
| 195 | g.Logger.Debug("Dialing to client via overlay (TCP)", zap.String("hostname", host)) |
| 196 | c, err = g.TunnelServer.DialClient(ctx, &protocol.Link{ |
| 197 | Alpn: protocol.Link_TCP, |
| 198 | Hostname: hostname, |
| 199 | Remote: remote, |
| 200 | }) |
| 201 | if err != nil { |
| 202 | return err |
| 203 | } |
| 204 | |
| 205 | return nil |
| 206 | } |
| 207 | |
| 208 | func effectiveRequestHost(in *http.Request) string { |
| 209 | host := in.Host |
| 210 | // Most browsers' connection coalescing behavior for http3 is the same as http2, |
| 211 | // as they could be reusing the same tcp/quic connection for different hosts. |
| 212 | // https://daniel.haxx.se/blog/2016/08/18/http2-connection-coalescing/ |
| 213 | // https://mailarchive.ietf.org/arch/msg/quic/ffjARd8-IobIE2T9_r5u9hBDbuk/ |
| 214 | if !in.ProtoAtLeast(2, 0) && in.TLS != nil { |
| 215 | host = in.TLS.ServerName |
| 216 | } |
| 217 | return (&url.URL{Host: host}).Hostname() |
| 218 | } |
| 219 | |
| 220 | func (g *Gateway) proxyRewrite(preq *httputil.ProxyRequest) { |
| 221 | in := preq.In |
| 222 | out := preq.Out |
| 223 | |
| 224 | out.URL.Scheme = "https" |
| 225 | out.URL.Host = effectiveRequestHost(in) |
| 226 | out.Host = out.URL.Host |
| 227 | |
| 228 | for _, header := range delHeaders { |
| 229 | out.Header.Del(header) |
| 230 | } |
| 231 | |
| 232 | // This is the public trust boundary. Rewrite has already removed Forwarded |
| 233 | // and the three X-Forwarded fields set below; never restore visitor-supplied |
| 234 | // values. The tunnel carries one visitor IP, without appending tunnel peers. |
| 235 | preq.SetXForwarded() |
| 236 | if g.GatewayPort == 443 { |
| 237 | out.Header.Set("X-Forwarded-Host", out.URL.Host) |
| 238 | } else { |
| 239 | out.Header.Set("X-Forwarded-Host", fmt.Sprintf("%s:%d", out.URL.Host, g.GatewayPort)) |
| 240 | } |
| 241 | out.Header.Set("X-Forwarded-Proto", "https") |
| 242 | out.Header.Set(middleware.RequestIDHeader, middleware.GetReqID(in.Context())) |
| 243 | } |
| 244 | |
| 245 | func (g *Gateway) proxyHandler(proxyLogger *log.Logger) http.Handler { |
| 246 | respHandler := func(r *http.Response) error { |
| 247 | r.Header.Del("alt-svc") |
| 248 | r.Header.Set(middleware.RequestIDHeader, middleware.GetReqID(r.Request.Context())) |
| 249 | g.appendHeaders(r.Request.ProtoAtLeast(3, 0))(r.Header) |
| 250 | return nil |
| 251 | } |
| 252 | |
| 253 | g.Logger.Info("Using buffer sizes for proxy", |
| 254 | zap.String("transport", units.Base2Bytes(g.Options.TransportBufferSize).String()), |
| 255 | zap.String("proxy", units.Base2Bytes(g.Options.ProxyBufferSize).String()), |
| 256 | ) |
| 257 | |
| 258 | proxyTransport := &http.Transport{ |
| 259 | MaxConnsPerHost: 30, |
| 260 | MaxIdleConnsPerHost: 5, |
| 261 | DisableCompression: true, |
| 262 | IdleConnTimeout: time.Second * 30, |
| 263 | ResponseHeaderTimeout: proxyHeaderTimeout, |
| 264 | ExpectContinueTimeout: time.Second * 5, |
| 265 | WriteBufferSize: g.Options.TransportBufferSize, |
| 266 | ReadBufferSize: g.Options.TransportBufferSize, |
| 267 | } |
| 268 | proxyTransport.DialTLSContext = func(ctx context.Context, _, addr string) (net.Conn, error) { |
| 269 | return g.overlayDialer(ctx, addr) |
| 270 | } |
| 271 | |
| 272 | bufPool := util.NewBufferPool(g.Options.ProxyBufferSize) |
| 273 | proxy := &httputil.ReverseProxy{ |
| 274 | Rewrite: g.proxyRewrite, |
| 275 | Transport: proxyTransport, |
| 276 | BufferPool: bufPool, |
| 277 | ErrorHandler: g.errorHandler, |
| 278 | ModifyResponse: respHandler, |
| 279 | ErrorLog: proxyLogger, |
| 280 | FlushInterval: -1, |
| 281 | } |
| 282 | |
| 283 | router := chi.NewRouter() |
| 284 | |
| 285 | g.mountCgiHandler(router) |
| 286 | router.Handle("/*", g.applicationHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 287 | // Proxy response hooks set the final ID after any informational response |
| 288 | // clears these headers, without appending a duplicate backend value. |
| 289 | w.Header().Del(middleware.RequestIDHeader) |
| 290 | proxy.ServeHTTP(w, r) |
| 291 | }))) |
| 292 | |
| 293 | return router |
| 294 | } |
| 295 | |
| 296 | func (g *Gateway) applicationHandler(next http.Handler) http.Handler { |
| 297 | application := next |
| 298 | if g.ApplicationMiddleware != nil { |
| 299 | application = g.ApplicationMiddleware(application, func(r *http.Request) (string, error) { |
| 300 | return g.extractHostname(effectiveRequestHost(r)) |
| 301 | }) |
| 302 | } |
| 303 | |
| 304 | identified := middleware.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 305 | w.Header().Set(middleware.RequestIDHeader, middleware.GetReqID(r.Context())) |
| 306 | |
| 307 | // Route and inspect the same authority that Rewrite forwards to the client. |
| 308 | host := effectiveRequestHost(r) |
| 309 | if r.Host != host { |
| 310 | copy := *r |
| 311 | copy.Host = host |
| 312 | r = © |
| 313 | } |
| 314 | if g.RouteCheckFunc != nil { |
| 315 | hostname, err := g.extractHostname(host) |
| 316 | // Only established absence skips inspection. Uncertain lookups keep |
| 317 | // the normal inspection and proxy recovery path. |
| 318 | if err == nil && errors.Is(g.RouteCheckFunc(r.Context(), hostname), tun.ErrDestinationNotFound) { |
| 319 | g.errorHandler(w, r, tun.ErrDestinationNotFound) |
| 320 | return |
| 321 | } |
| 322 | } |
| 323 | application.ServeHTTP(w, r) |
| 324 | })) |
| 325 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 326 | // The public gateway owns request identity; visitors cannot select it. |
| 327 | r.Header.Del(middleware.RequestIDHeader) |
| 328 | identified.ServeHTTP(w, r) |
| 329 | }) |
| 330 | } |
| 331 | |
| 332 | func (g *Gateway) errorHandler(w http.ResponseWriter, r *http.Request, e error) { |
| 333 | g.appendHeaders(r.ProtoAtLeast(3, 0))(w.Header()) |
| 334 | requestID := middleware.GetReqID(r.Context()) |
| 335 | w.Header().Set(middleware.RequestIDHeader, requestID) |
| 336 | hostname := effectiveRequestHost(r) |
| 337 | |
| 338 | if errors.Is(e, tun.ErrDestinationNotFound) { |
| 339 | w.WriteHeader(http.StatusNotFound) |
| 340 | fmt.Fprintf(w, "Destination %s not found on the specter network.", hostname) |
| 341 | return |
| 342 | } |
| 343 | |
| 344 | if errors.Is(e, tun.ErrTunnelClientNotConnected) { |
| 345 | w.WriteHeader(http.StatusServiceUnavailable) |
| 346 | fmt.Fprintf(w, "Destination %s is not connected to specter network.", hostname) |
| 347 | return |
| 348 | } |
| 349 | |
| 350 | if errors.Is(e, context.Canceled) { |
| 351 | // this is expected |
| 352 | return |
| 353 | } |
| 354 | |
| 355 | logger := g.Logger.With(zap.String("hostname", hostname), zap.String("request_id", requestID)) |
| 356 | |
| 357 | logger.Debug("error forwarding http request", zap.Error(e)) |
| 358 | |
| 359 | if tun.IsTimeout(e) { |
| 360 | w.WriteHeader(http.StatusGatewayTimeout) |
| 361 | fmt.Fprintf(w, "Destination %s is taking too long to respond.", hostname) |
| 362 | return |
| 363 | } |
| 364 | |
| 365 | if !errors.Is(e, io.EOF) { |
| 366 | logger.Error("error forwarding to client", zap.Error(e)) |
| 367 | } |
| 368 | w.WriteHeader(http.StatusBadGateway) |
| 369 | fmt.Fprint(w, "An unexpected error has occurred while attempting to forward to destination.") |
| 370 | } |