Skip to content

Commit c2fe0a6

Browse files
Dennisadiramudler
andauthored
fix(http): honor X-Forwarded-Prefix when proxy strips the prefix (#9614)
* fix(http): honor X-Forwarded-Prefix when proxy strips the prefix Closes #9145. Two related issues kept the React UI from loading when a reverse proxy rewrites a sub-path with prefix-stripping (e.g. Caddy `handle_path`): 1. `BaseURL` only computed a prefix from the path StripPathPrefix had removed, so when the proxy strips the prefix before forwarding, the request arrives without it and the base URL was returned without a prefix. Extract a `BasePathPrefix` helper and add an `X-Forwarded-Prefix` header fallback so the prefix is recovered. 2. `<base href>` only changes how relative URLs resolve; the build emits path-absolute references like `/assets/...` and `/favicon.svg`, which still resolve against the origin and bypass the proxy prefix. Rewrite those references in the served `index.html` so the browser requests them through the proxy. Adds unit coverage for `BaseURL` with a pre-stripped path and an end-to-end test for the proxy-stripped scenario. Assisted-by: Claude:claude-opus-4-7 * fix(http): gate X-Forwarded-Prefix through SafeForwardedPrefix in BasePathPrefix BasePathPrefix consumed X-Forwarded-Prefix directly, so a value the codebase elsewhere rejects (e.g. "//evil.com") slipped through and was interpolated into the SPA index.html — both into the path-absolute asset URL rewrite in serveIndex (turning "/assets/..." into "//evil.com/assets/...", a protocol-relative URL that loads JS from a foreign origin) and into <base href>. Route the header through the existing SafeForwardedPrefix validator that StripPathPrefix and prefixRedirect already use, and HTML-escape the prefix before injecting it into the asset rewrite as defense in depth against attribute breakout. Tests cover //evil.com, backslashes, control chars, CR/LF and a missing leading slash; the integration test asserts an unsafe prefix can't poison asset URLs. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: claude-code:claude-opus-4-7-1m [Read] [Edit] [Bash] --------- Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
1 parent ddbbdf4 commit c2fe0a6

4 files changed

Lines changed: 178 additions & 20 deletions

File tree

core/http/app.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,25 @@ func API(application *application.Application) (*echo.Echo, error) {
443443
baseTag := `<base href="` + httpMiddleware.SecureBaseHref(baseURL) + `" />`
444444
indexHTML = []byte(strings.Replace(string(indexHTML), "<head>", "<head>\n "+baseTag, 1))
445445
}
446+
// <base href> only changes how relative URLs resolve; path-absolute
447+
// URLs (those starting with `/`) still resolve against the origin
448+
// and would bypass the reverse-proxy prefix. Rewrite the internal
449+
// path-absolute references emitted by the build so the browser
450+
// requests them through the proxy under the prefix.
451+
//
452+
// HTML-escape the prefix before interpolating it into attributes:
453+
// BasePathPrefix already gates X-Forwarded-Prefix via
454+
// SafeForwardedPrefix, but the validator only blocks open-redirect
455+
// shapes (// prefix, backslashes, control chars), not attribute
456+
// breakout characters like `"`. Escaping makes this resilient
457+
// even if the validator ever loosens.
458+
if prefix := httpMiddleware.BasePathPrefix(c); prefix != "/" {
459+
safePrefix := httpMiddleware.SecureBaseHref(prefix)
460+
html := string(indexHTML)
461+
html = strings.ReplaceAll(html, `="/assets/`, `="`+safePrefix+`assets/`)
462+
html = strings.ReplaceAll(html, `="/favicon.svg"`, `="`+safePrefix+`favicon.svg"`)
463+
indexHTML = []byte(html)
464+
}
446465
return c.HTMLBlob(http.StatusOK, indexHTML)
447466
}
448467

core/http/app_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,42 @@ var _ = Describe("API test", func() {
446446
Expect(sc).To(Equal(200), "status code")
447447
Expect(string(body)).To(ContainSubstring(`<base href="https://example.org/myprefix/" />`), "body")
448448
})
449+
450+
// Caddy's `handle_path` (and similar directives) strip the matched
451+
// prefix before forwarding upstream, so LocalAI receives the
452+
// already-stripped path together with X-Forwarded-Prefix. The base
453+
// href and asset URLs must still include the prefix so the browser
454+
// requests them through the proxy.
455+
It("Should support reverse-proxy when prefix is stripped by the proxy", func() {
456+
457+
err, sc, body := getRequest("http://127.0.0.1:9090/app", http.Header{
458+
"X-Forwarded-Proto": {"https"},
459+
"X-Forwarded-Host": {"example.org"},
460+
"X-Forwarded-Prefix": {"/myprefix"},
461+
})
462+
Expect(err).To(BeNil(), "error")
463+
Expect(sc).To(Equal(200), "status code")
464+
Expect(string(body)).To(ContainSubstring(`<base href="https://example.org/myprefix/" />`), "body")
465+
Expect(string(body)).ToNot(ContainSubstring(`="/assets/`), "asset URLs must include the prefix")
466+
Expect(string(body)).ToNot(ContainSubstring(`="/favicon.svg"`), "favicon URL must include the prefix")
467+
})
468+
469+
// X-Forwarded-Prefix is attacker controllable on misconfigured
470+
// proxy chains. A value like "//evil.com" would otherwise turn the
471+
// asset URL rewrite into a protocol-relative URL that loads JS
472+
// from a foreign origin. BasePathPrefix must reject these via
473+
// SafeForwardedPrefix and fall back to "/".
474+
It("Should ignore an unsafe X-Forwarded-Prefix and not poison asset URLs", func() {
475+
err, sc, body := getRequest("http://127.0.0.1:9090/app", http.Header{
476+
"X-Forwarded-Proto": {"https"},
477+
"X-Forwarded-Host": {"example.org"},
478+
"X-Forwarded-Prefix": {"//evil.com"},
479+
})
480+
Expect(err).To(BeNil(), "error")
481+
Expect(sc).To(Equal(200), "status code")
482+
Expect(string(body)).ToNot(ContainSubstring("evil.com"), "unsafe prefix must not leak into the response")
483+
Expect(string(body)).ToNot(ContainSubstring(`="//`), "asset URLs must not become protocol-relative")
484+
})
449485
})
450486

451487
Context("Applying models", func() {

core/http/middleware/baseurl.go

Lines changed: 43 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,43 +6,66 @@ import (
66
"github.com/labstack/echo/v4"
77
)
88

9-
// BaseURL returns the base URL for the given HTTP request context.
10-
// It takes into account that the app may be exposed by a reverse-proxy under a different protocol, host and path.
11-
// The returned URL is guaranteed to end with `/`.
12-
// The method should be used in conjunction with the StripPathPrefix middleware.
13-
func BaseURL(c echo.Context) string {
9+
// BasePathPrefix returns the URL path prefix that the request was reached
10+
// under (e.g. "/myprefix/"). It always returns a value that starts and ends
11+
// with `/`, defaulting to "/" when the app is not behind a path prefix.
12+
//
13+
// It first looks at the path StripPathPrefix removed (when the proxy forwards
14+
// the prefix in the URL), then falls back to the X-Forwarded-Prefix header
15+
// (when the proxy strips the prefix before forwarding, e.g. Caddy's
16+
// handle_path).
17+
//
18+
// The header fallback is gated through SafeForwardedPrefix because the value
19+
// flows into the SPA HTML response (both <base href> and the path-absolute
20+
// asset URL rewrite in serveIndex). X-Forwarded-Prefix is attacker
21+
// controllable on misconfigured proxy chains; without that gate a value like
22+
// "//evil.com" turns the asset rewrite into a protocol-relative URL that
23+
// loads JS from a foreign origin.
24+
func BasePathPrefix(c echo.Context) string {
1425
path := c.Path()
1526
origPath := c.Request().URL.Path
1627

17-
// Check if StripPathPrefix middleware stored the original path
1828
if storedPath, ok := c.Get("_original_path").(string); ok && storedPath != "" {
1929
origPath = storedPath
2030
}
2131

22-
// Check X-Forwarded-Proto for scheme
32+
if path != origPath && strings.HasSuffix(origPath, path) && len(path) > 0 {
33+
prefixLen := len(origPath) - len(path)
34+
if prefixLen > 0 {
35+
pathPrefix := origPath[:prefixLen]
36+
if !strings.HasSuffix(pathPrefix, "/") {
37+
pathPrefix += "/"
38+
}
39+
return pathPrefix
40+
}
41+
}
42+
43+
if validated, ok := SafeForwardedPrefix(c.Request().Header.Get("X-Forwarded-Prefix")); ok {
44+
if !strings.HasSuffix(validated, "/") {
45+
validated += "/"
46+
}
47+
return validated
48+
}
49+
50+
return "/"
51+
}
52+
53+
// BaseURL returns the base URL for the given HTTP request context.
54+
// It takes into account that the app may be exposed by a reverse-proxy under a different protocol, host and path.
55+
// The returned URL is guaranteed to end with `/`.
56+
// The method should be used in conjunction with the StripPathPrefix middleware.
57+
func BaseURL(c echo.Context) string {
2358
scheme := "http"
2459
if c.Request().Header.Get("X-Forwarded-Proto") == "https" {
2560
scheme = "https"
2661
} else if c.Request().TLS != nil {
2762
scheme = "https"
2863
}
2964

30-
// Check X-Forwarded-Host for host
3165
host := c.Request().Host
3266
if forwardedHost := c.Request().Header.Get("X-Forwarded-Host"); forwardedHost != "" {
3367
host = forwardedHost
3468
}
3569

36-
if path != origPath && strings.HasSuffix(origPath, path) && len(path) > 0 {
37-
prefixLen := len(origPath) - len(path)
38-
if prefixLen > 0 && prefixLen <= len(origPath) {
39-
pathPrefix := origPath[:prefixLen]
40-
if !strings.HasSuffix(pathPrefix, "/") {
41-
pathPrefix += "/"
42-
}
43-
return scheme + "://" + host + pathPrefix
44-
}
45-
}
46-
47-
return scheme + "://" + host + "/"
70+
return scheme + "://" + host + BasePathPrefix(c)
4871
}

core/http/middleware/baseurl_test.go

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,84 @@ var _ = Describe("BaseURL", func() {
5555
Expect(actualURL).To(Equal("http://example.com/myprefix/"), "base URL")
5656
})
5757
})
58+
59+
// Caddy's handle_path (and similar reverse-proxy directives) strips the
60+
// matched prefix before forwarding upstream, so LocalAI receives the
61+
// already-stripped path together with X-Forwarded-Prefix. In that case
62+
// StripPathPrefix never stores _original_path, but BaseURL must still
63+
// honor the header so that <base href> and asset URLs include the prefix.
64+
Context("with X-Forwarded-Prefix header but pre-stripped path", func() {
65+
It("should return base URL with prefix from header", func() {
66+
app := echo.New()
67+
actualURL := ""
68+
69+
routePath := "/app"
70+
app.GET(routePath, func(c echo.Context) error {
71+
actualURL = BaseURL(c)
72+
return nil
73+
})
74+
75+
req := httptest.NewRequest("GET", "/app", nil)
76+
req.Header.Set("X-Forwarded-Prefix", "/localai")
77+
rec := httptest.NewRecorder()
78+
app.ServeHTTP(rec, req)
79+
80+
Expect(rec.Code).To(Equal(200), "response status code")
81+
Expect(actualURL).To(Equal("http://example.com/localai/"), "base URL")
82+
})
83+
84+
It("should normalize a prefix that already ends with a slash", func() {
85+
app := echo.New()
86+
actualURL := ""
87+
88+
routePath := "/app"
89+
app.GET(routePath, func(c echo.Context) error {
90+
actualURL = BaseURL(c)
91+
return nil
92+
})
93+
94+
req := httptest.NewRequest("GET", "/app", nil)
95+
req.Header.Set("X-Forwarded-Prefix", "/localai/")
96+
rec := httptest.NewRecorder()
97+
app.ServeHTTP(rec, req)
98+
99+
Expect(rec.Code).To(Equal(200), "response status code")
100+
Expect(actualURL).To(Equal("http://example.com/localai/"), "base URL")
101+
})
102+
})
103+
104+
// X-Forwarded-Prefix is attacker controllable on misconfigured proxy
105+
// chains, and the value flows into the SPA HTML response (<base href>
106+
// and asset URLs). BasePathPrefix must gate the header through
107+
// SafeForwardedPrefix so values that turn the prefix into an open
108+
// redirect or a protocol-relative URL are ignored and the base falls
109+
// back to "/".
110+
Context("with unsafe X-Forwarded-Prefix header", func() {
111+
DescribeTable("falls back to / when the header is unsafe",
112+
func(header string) {
113+
app := echo.New()
114+
actualURL := ""
115+
116+
app.GET("/app", func(c echo.Context) error {
117+
actualURL = BaseURL(c)
118+
return nil
119+
})
120+
121+
req := httptest.NewRequest("GET", "/app", nil)
122+
req.Header.Set("X-Forwarded-Prefix", header)
123+
rec := httptest.NewRecorder()
124+
app.ServeHTTP(rec, req)
125+
126+
Expect(rec.Code).To(Equal(200), "response status code")
127+
Expect(actualURL).To(Equal("http://example.com/"), "base URL")
128+
},
129+
Entry("protocol-relative URL", "//evil.com"),
130+
Entry("protocol-relative URL with path", "//evil.com/assets"),
131+
Entry("backslash path", `/foo\bar`),
132+
Entry("embedded NUL", "/foo\x00bar"),
133+
Entry("CR injection", "/foo\rbar"),
134+
Entry("LF injection", "/foo\nbar"),
135+
Entry("missing leading slash", "evil"),
136+
)
137+
})
58138
})

0 commit comments

Comments
 (0)