|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "net" |
| 7 | + "net/http" |
| 8 | + "net/http/httputil" |
| 9 | + "net/url" |
| 10 | + "sort" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/rs/zerolog/log" |
| 14 | + |
| 15 | + "github.com/gosuda/portal/v2/utils" |
| 16 | +) |
| 17 | + |
| 18 | +type httpRoute struct { |
| 19 | + prefix string |
| 20 | + upstream *url.URL |
| 21 | + proxy *httputil.ReverseProxy |
| 22 | +} |
| 23 | + |
| 24 | +func newHTTPRouteHandler(rawRoutes []string) (http.Handler, error) { |
| 25 | + if len(rawRoutes) == 0 { |
| 26 | + return nil, errors.New("at least one --http-route is required") |
| 27 | + } |
| 28 | + |
| 29 | + routes := make([]*httpRoute, 0, len(rawRoutes)) |
| 30 | + seen := make(map[string]struct{}, len(rawRoutes)) |
| 31 | + for _, raw := range rawRoutes { |
| 32 | + route, err := parseHTTPRoute(raw) |
| 33 | + if err != nil { |
| 34 | + return nil, err |
| 35 | + } |
| 36 | + if _, ok := seen[route.prefix]; ok { |
| 37 | + return nil, fmt.Errorf("duplicate --http-route prefix %q", route.prefix) |
| 38 | + } |
| 39 | + seen[route.prefix] = struct{}{} |
| 40 | + route.proxy = route.newReverseProxy() |
| 41 | + routes = append(routes, route) |
| 42 | + } |
| 43 | + |
| 44 | + // longest-prefix-first |
| 45 | + sort.Slice(routes, func(i, j int) bool { |
| 46 | + if len(routes[i].prefix) == len(routes[j].prefix) { |
| 47 | + return routes[i].prefix < routes[j].prefix |
| 48 | + } |
| 49 | + return len(routes[i].prefix) > len(routes[j].prefix) |
| 50 | + }) |
| 51 | + |
| 52 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 53 | + p := r.URL.Path |
| 54 | + if p == "" { |
| 55 | + p = "/" |
| 56 | + } |
| 57 | + for _, route := range routes { |
| 58 | + if route.prefix == "/" || p == route.prefix || strings.HasPrefix(p, route.prefix+"/") { |
| 59 | + route.proxy.ServeHTTP(w, r) |
| 60 | + return |
| 61 | + } |
| 62 | + } |
| 63 | + http.NotFound(w, r) |
| 64 | + }), nil |
| 65 | +} |
| 66 | + |
| 67 | +func parseHTTPRoute(raw string) (*httpRoute, error) { |
| 68 | + raw = strings.TrimSpace(raw) |
| 69 | + if raw == "" { |
| 70 | + return nil, errors.New("--http-route: expected PATH=UPSTREAM") |
| 71 | + } |
| 72 | + |
| 73 | + prefixRaw, upstreamRaw, ok := strings.Cut(raw, "=") |
| 74 | + if !ok { |
| 75 | + return nil, fmt.Errorf("--http-route %q: expected PATH=UPSTREAM", raw) |
| 76 | + } |
| 77 | + |
| 78 | + prefix := strings.TrimSpace(prefixRaw) |
| 79 | + if prefix == "" { |
| 80 | + return nil, fmt.Errorf("--http-route %q: prefix is required", raw) |
| 81 | + } |
| 82 | + if !strings.HasPrefix(prefix, "/") { |
| 83 | + return nil, fmt.Errorf("--http-route %q: prefix must start with /", raw) |
| 84 | + } |
| 85 | + prefix = utils.NormalizeURLPath(prefix) |
| 86 | + |
| 87 | + upstreamInput := strings.TrimSpace(upstreamRaw) |
| 88 | + if upstreamInput == "" { |
| 89 | + return nil, fmt.Errorf("--http-route %q: upstream is required", raw) |
| 90 | + } |
| 91 | + if !strings.Contains(upstreamInput, "://") { |
| 92 | + target, err := utils.NormalizeLoopbackTarget(upstreamInput) |
| 93 | + if err != nil { |
| 94 | + return nil, fmt.Errorf("--http-route %q: %w", raw, err) |
| 95 | + } |
| 96 | + upstreamInput = "http://" + target |
| 97 | + } |
| 98 | + |
| 99 | + upstream, err := url.Parse(upstreamInput) |
| 100 | + if err != nil { |
| 101 | + return nil, fmt.Errorf("--http-route %q: %w", raw, err) |
| 102 | + } |
| 103 | + if upstream.Host == "" { |
| 104 | + return nil, fmt.Errorf("--http-route %q: upstream host is required", raw) |
| 105 | + } |
| 106 | + if upstream.Scheme != "http" && upstream.Scheme != "https" { |
| 107 | + return nil, fmt.Errorf("--http-route %q: scheme must be http or https", raw) |
| 108 | + } |
| 109 | + upstream.Fragment = "" |
| 110 | + upstream.Path = utils.NormalizeURLPath(upstream.Path) |
| 111 | + |
| 112 | + return &httpRoute{prefix: prefix, upstream: upstream}, nil |
| 113 | +} |
| 114 | + |
| 115 | +func (r *httpRoute) newReverseProxy() *httputil.ReverseProxy { |
| 116 | + return &httputil.ReverseProxy{ |
| 117 | + Rewrite: r.rewriteRequest, |
| 118 | + ModifyResponse: func(resp *http.Response) error { |
| 119 | + if resp == nil || resp.Request == nil { |
| 120 | + return nil |
| 121 | + } |
| 122 | + publicHost := resp.Request.Header.Get("X-Forwarded-Host") |
| 123 | + publicScheme := resp.Request.Header.Get("X-Forwarded-Proto") |
| 124 | + r.rewriteLocation(resp.Header, publicHost, publicScheme) |
| 125 | + r.rewriteSetCookies(resp.Header, publicHost) |
| 126 | + return nil |
| 127 | + }, |
| 128 | + ErrorHandler: func(w http.ResponseWriter, req *http.Request, err error) { |
| 129 | + log.Error().Err(err). |
| 130 | + Str("route_prefix", r.prefix). |
| 131 | + Str("upstream", r.upstream.String()). |
| 132 | + Msg("http route proxy failed") |
| 133 | + http.Error(w, "bad gateway", http.StatusBadGateway) |
| 134 | + }, |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +func (r *httpRoute) rewriteRequest(pr *httputil.ProxyRequest) { |
| 139 | + // strip route prefix from the path before forwarding |
| 140 | + reqPath := utils.NormalizeURLPath(pr.In.URL.Path) |
| 141 | + rawPath := pr.In.URL.RawPath |
| 142 | + if r.prefix != "/" { |
| 143 | + if reqPath == r.prefix { |
| 144 | + reqPath = "/" |
| 145 | + rawPath = "" |
| 146 | + } else { |
| 147 | + reqPath = strings.TrimPrefix(reqPath, r.prefix) |
| 148 | + if reqPath == "" { |
| 149 | + reqPath = "/" |
| 150 | + } |
| 151 | + if rawPath == r.prefix { |
| 152 | + rawPath = "/" |
| 153 | + } else if strings.HasPrefix(rawPath, r.prefix+"/") { |
| 154 | + rawPath = strings.TrimPrefix(rawPath, r.prefix) |
| 155 | + } |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + pr.Out.URL.Path = reqPath |
| 160 | + pr.Out.URL.RawPath = rawPath |
| 161 | + pr.Out.URL.RawQuery = pr.In.URL.RawQuery |
| 162 | + pr.SetURL(r.upstream) |
| 163 | + pr.SetXForwarded() |
| 164 | + |
| 165 | + // SetXForwarded checks pr.In.TLS, but behind a TLS-terminating proxy |
| 166 | + // the inbound X-Forwarded-Proto carries the real client scheme. |
| 167 | + if pr.In.TLS == nil { |
| 168 | + proto, _, _ := strings.Cut(pr.In.Header.Get("X-Forwarded-Proto"), ",") |
| 169 | + if proto = strings.ToLower(strings.TrimSpace(proto)); proto != "" { |
| 170 | + pr.Out.Header.Set("X-Forwarded-Proto", proto) |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + if r.prefix != "/" { |
| 175 | + pr.Out.Header.Set("X-Forwarded-Prefix", r.prefix) |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 179 | +func (r *httpRoute) rewriteLocation(header http.Header, publicHost, publicScheme string) { |
| 180 | + location := header.Get("Location") |
| 181 | + if location == "" { |
| 182 | + return |
| 183 | + } |
| 184 | + parsed, err := url.Parse(location) |
| 185 | + if err != nil { |
| 186 | + return |
| 187 | + } |
| 188 | + |
| 189 | + switch { |
| 190 | + case parsed.IsAbs(): |
| 191 | + if !strings.EqualFold(parsed.Scheme, r.upstream.Scheme) || !strings.EqualFold(parsed.Host, r.upstream.Host) { |
| 192 | + return |
| 193 | + } |
| 194 | + parsed.Scheme = publicScheme |
| 195 | + parsed.Host = publicHost |
| 196 | + case strings.HasPrefix(location, "/") && parsed.Host == "" && (len(location) == 1 || (location[1] != '\\' && location[1] != '/')): |
| 197 | + // server-relative redirect |
| 198 | + default: |
| 199 | + return |
| 200 | + } |
| 201 | + |
| 202 | + mapped := r.mapUpstreamPathToPublic(parsed.Path) |
| 203 | + if !strings.HasPrefix(mapped, "/") || (len(mapped) > 1 && (mapped[1] == '/' || mapped[1] == '\\')) { |
| 204 | + return |
| 205 | + } |
| 206 | + parsed.Path = mapped |
| 207 | + parsed.RawPath = "" |
| 208 | + header.Set("Location", parsed.String()) |
| 209 | +} |
| 210 | + |
| 211 | +func (r *httpRoute) rewriteSetCookies(header http.Header, publicHost string) { |
| 212 | + values := header.Values("Set-Cookie") |
| 213 | + if len(values) == 0 { |
| 214 | + return |
| 215 | + } |
| 216 | + |
| 217 | + publicDomain := publicHost |
| 218 | + if host, port, err := net.SplitHostPort(publicDomain); err == nil && port != "" { |
| 219 | + publicDomain = host |
| 220 | + } |
| 221 | + publicDomain = strings.ToLower(strings.Trim(publicDomain, "[]")) |
| 222 | + upstreamDomain := strings.ToLower(r.upstream.Hostname()) |
| 223 | + |
| 224 | + header.Del("Set-Cookie") |
| 225 | + for _, value := range values { |
| 226 | + cookie, err := http.ParseSetCookie(value) |
| 227 | + if err != nil { |
| 228 | + header.Add("Set-Cookie", value) |
| 229 | + continue |
| 230 | + } |
| 231 | + |
| 232 | + changed := false |
| 233 | + if cookie.Path != "" { |
| 234 | + if rewritten := r.mapUpstreamPathToPublic(cookie.Path); rewritten != cookie.Path { |
| 235 | + cookie.Path = rewritten |
| 236 | + changed = true |
| 237 | + } |
| 238 | + } |
| 239 | + |
| 240 | + domain := strings.ToLower(strings.TrimPrefix(cookie.Domain, ".")) |
| 241 | + if domain != "" && domain != publicDomain && |
| 242 | + (domain == upstreamDomain || utils.IsLocalRelayHost(domain)) { |
| 243 | + cookie.Domain = "" |
| 244 | + changed = true |
| 245 | + } |
| 246 | + |
| 247 | + if changed { |
| 248 | + header.Add("Set-Cookie", cookie.String()) |
| 249 | + } else { |
| 250 | + header.Add("Set-Cookie", value) |
| 251 | + } |
| 252 | + } |
| 253 | +} |
| 254 | + |
| 255 | +func (r *httpRoute) mapUpstreamPathToPublic(raw string) string { |
| 256 | + raw = utils.NormalizeURLPath(raw) |
| 257 | + if r.prefix != "/" && (raw == r.prefix || strings.HasPrefix(raw, r.prefix+"/")) { |
| 258 | + return raw |
| 259 | + } |
| 260 | + |
| 261 | + base := utils.NormalizeURLPath(r.upstream.Path) |
| 262 | + rest := raw |
| 263 | + if base != "/" { |
| 264 | + if raw == base { |
| 265 | + rest = "/" |
| 266 | + } else if strings.HasPrefix(raw, base+"/") { |
| 267 | + rest = strings.TrimPrefix(raw, base) |
| 268 | + } |
| 269 | + } |
| 270 | + |
| 271 | + if r.prefix == "/" { |
| 272 | + return rest |
| 273 | + } |
| 274 | + if rest == "/" { |
| 275 | + return r.prefix |
| 276 | + } |
| 277 | + return r.prefix + rest |
| 278 | +} |
0 commit comments