proxy.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. package appproxy
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "context"
  6. "errors"
  7. "html"
  8. "io"
  9. "net/http"
  10. "net/http/httputil"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. /*
  17. proxy.go
  18. Request routing and the reverse proxy itself.
  19. HandleRequest is called first thing by the core router and claims:
  20. 1. every request whose Host is a subdomain mode app hostname
  21. 2. /app/<slug>/... on the ArozOS host
  22. 3. "leaked" root requests: a request outside /app/ whose Referer is a
  23. path mode app page, e.g. an app at /app/grafana/ asking for
  24. /public/app.css. They are redirected (307) to /app/grafana/public/app.css,
  25. so they never fall through to the ArozOS web root, and the redirected
  26. document's own Referer keeps the chain inside the app.
  27. */
  28. const (
  29. // SessionCookie is the login cookie of a subdomain mode app host
  30. SessionCookie = "ao_appsess"
  31. claimPath = "/__appproxy/claim"
  32. maxCSSBytes = 8 << 20
  33. )
  34. // ArozOS paths a root request from an app is never redirected away from
  35. var leakExemptPrefixes = []string{
  36. "/login.html",
  37. "/reset.html",
  38. "/system/auth/",
  39. }
  40. type ctxKey struct{}
  41. // requestInfo travels with the proxied request to ModifyResponse
  42. type requestInfo struct {
  43. rt *endpointRuntime
  44. pathMode bool
  45. prefix string //Path mode prefix, "" in subdomain mode
  46. publicHost string
  47. scheme string
  48. }
  49. func infoFrom(ctx context.Context) *requestInfo {
  50. info, _ := ctx.Value(ctxKey{}).(*requestInfo)
  51. return info
  52. }
  53. // requestScheme is the scheme the browser used, honouring a fronting proxy
  54. func requestScheme(r *http.Request) string {
  55. if p := strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0])); p == "http" || p == "https" {
  56. return p
  57. }
  58. if r.TLS != nil {
  59. return "https"
  60. }
  61. return "http"
  62. }
  63. // isNavigation reports whether the browser expects a page (so a redirect to a
  64. // login page makes sense) rather than data
  65. func isNavigation(r *http.Request) bool {
  66. if r.Method != http.MethodGet && r.Method != http.MethodHead {
  67. return false
  68. }
  69. if mode := r.Header.Get("Sec-Fetch-Mode"); mode != "" {
  70. return mode == "navigate"
  71. }
  72. return strings.Contains(r.Header.Get("Accept"), "text/html")
  73. }
  74. func isWebSocket(r *http.Request) bool {
  75. return strings.EqualFold(r.Header.Get("Upgrade"), "websocket")
  76. }
  77. // safeReturnPath keeps a post-login return target on the same host
  78. func safeReturnPath(p string) string {
  79. if !strings.HasPrefix(p, "/") || strings.HasPrefix(p, "//") || strings.ContainsAny(p, "\\\r\n") {
  80. return "/"
  81. }
  82. return p
  83. }
  84. // HandleRequest serves the request if it belongs to a container app and
  85. // reports whether it did
  86. func (m *Manager) HandleRequest(w http.ResponseWriter, r *http.Request) bool {
  87. if rt := m.runtimeByHost(r.Host); rt != nil {
  88. m.serveSubdomain(w, r, rt)
  89. return true
  90. }
  91. if r.URL.Path == "/app" || strings.HasPrefix(r.URL.Path, "/app/") {
  92. m.servePath(w, r)
  93. return true
  94. }
  95. return m.redirectLeak(w, r)
  96. }
  97. // servePath handles /app/<slug>/... on the ArozOS host
  98. func (m *Manager) servePath(w http.ResponseWriter, r *http.Request) {
  99. slug, rest, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/app/"), "/")
  100. rt := m.runtimeBySlug(slug)
  101. if slug == "" || rt == nil {
  102. errorPage(w, http.StatusNotFound, "App not found", "This container app does not exist or has been removed.")
  103. return
  104. }
  105. ep := rt.ep
  106. prefix := ep.PathPrefix()
  107. if r.URL.Path == prefix {
  108. target := prefix + "/"
  109. if r.URL.RawQuery != "" {
  110. target += "?" + r.URL.RawQuery
  111. }
  112. http.Redirect(w, r, target, http.StatusFound)
  113. return
  114. }
  115. rest = "/" + rest
  116. var id *Identity
  117. if ep.RequireLogin {
  118. id = m.opts.ResolveUser(w, r)
  119. if id == nil {
  120. m.denyAnonymous(w, r, m.opts.LoginURL(r.URL.RequestURI()))
  121. return
  122. }
  123. }
  124. if !ep.CanAccess(id) {
  125. errorPage(w, http.StatusForbidden, "Access denied", "You do not have permission to open this app.")
  126. return
  127. }
  128. if ep.Mode == ModeSubdomain {
  129. m.handOff(w, r, ep, id, rest)
  130. return
  131. }
  132. if ep.RewriteRoot && rest == shimPath {
  133. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  134. w.Header().Set("Cache-Control", "no-cache")
  135. w.Write(renderShim(prefix))
  136. return
  137. }
  138. out := r.Clone(context.WithValue(r.Context(), ctxKey{}, &requestInfo{
  139. rt: rt,
  140. pathMode: true,
  141. prefix: prefix,
  142. publicHost: r.Host,
  143. scheme: requestScheme(r),
  144. }))
  145. out.URL.Path = rest
  146. out.URL.RawPath = ""
  147. if raw := r.URL.RawPath; raw != "" && strings.HasPrefix(raw, prefix+"/") {
  148. out.URL.RawPath = strings.TrimPrefix(raw, prefix)
  149. }
  150. out.RequestURI = ""
  151. rt.requests.Add(1)
  152. rt.proxy.ServeHTTP(w, out)
  153. }
  154. // handOff sends a user from /app/<slug>/ on the ArozOS host to the app hostname
  155. func (m *Manager) handOff(w http.ResponseWriter, r *http.Request, ep *Endpoint, id *Identity, rest string) {
  156. returnTo := rest
  157. if r.URL.RawQuery != "" {
  158. returnTo += "?" + r.URL.RawQuery
  159. }
  160. origin := ep.AppOrigin()
  161. if !ep.RequireLogin || id == nil {
  162. http.Redirect(w, r, origin+safeReturnPath(returnTo), http.StatusFound)
  163. return
  164. }
  165. t := m.sessions.issueTicket(id.Username, ep.Slug, safeReturnPath(returnTo))
  166. w.Header().Set("Cache-Control", "no-store")
  167. http.Redirect(w, r, origin+claimPath+"?t="+url.QueryEscape(t), http.StatusFound)
  168. }
  169. // AppOrigin is the origin a subdomain mode app is served on, following the
  170. // scheme and port of the ArozOS portal
  171. func (e *Endpoint) AppOrigin() string {
  172. portal, err := url.Parse(e.PortalOrigin)
  173. if err != nil || portal.Scheme == "" {
  174. return "https://" + e.Hostname
  175. }
  176. origin := portal.Scheme + "://" + e.Hostname
  177. if port := portal.Port(); port != "" {
  178. origin += ":" + port
  179. }
  180. return origin
  181. }
  182. // serveSubdomain handles every request on a subdomain mode app host
  183. func (m *Manager) serveSubdomain(w http.ResponseWriter, r *http.Request, rt *endpointRuntime) {
  184. ep := rt.ep
  185. scheme := requestScheme(r)
  186. if r.URL.Path == claimPath {
  187. token, returnTo, ok := m.sessions.claimTicket(r.URL.Query().Get("t"), ep.Slug)
  188. if !ok {
  189. errorPageWithLink(w, http.StatusForbidden, "Sign in expired",
  190. "The sign in link has expired or was already used.",
  191. ep.PortalOrigin+ep.PathPrefix()+"/", "Try again")
  192. return
  193. }
  194. http.SetCookie(w, &http.Cookie{
  195. Name: SessionCookie,
  196. Value: token,
  197. Path: "/",
  198. MaxAge: int(sessionTTL / time.Second),
  199. HttpOnly: true,
  200. Secure: scheme == "https",
  201. SameSite: http.SameSiteLaxMode,
  202. })
  203. w.Header().Set("Cache-Control", "no-store")
  204. http.Redirect(w, r, safeReturnPath(returnTo), http.StatusFound)
  205. return
  206. }
  207. if ep.RequireLogin {
  208. token := ""
  209. if c, err := r.Cookie(SessionCookie); err == nil {
  210. token = c.Value
  211. }
  212. id := m.sessions.resolve(token, ep.Slug, m.opts.LookupUser)
  213. if id == nil {
  214. //Go back through the portal, which hands the login over again
  215. m.denyAnonymous(w, r, ep.PortalOrigin+ep.PathPrefix()+safeReturnPath(r.URL.RequestURI()))
  216. return
  217. }
  218. if !ep.CanAccess(id) {
  219. m.sessions.revoke(token)
  220. errorPage(w, http.StatusForbidden, "Access denied", "You do not have permission to open this app.")
  221. return
  222. }
  223. }
  224. out := r.WithContext(context.WithValue(r.Context(), ctxKey{}, &requestInfo{
  225. rt: rt,
  226. publicHost: r.Host,
  227. scheme: scheme,
  228. }))
  229. rt.requests.Add(1)
  230. rt.proxy.ServeHTTP(w, out)
  231. }
  232. // denyAnonymous redirects a page load to sign in, and refuses anything else
  233. func (m *Manager) denyAnonymous(w http.ResponseWriter, r *http.Request, loginURL string) {
  234. w.Header().Set("Cache-Control", "no-store")
  235. if isNavigation(r) {
  236. http.Redirect(w, r, loginURL, http.StatusFound)
  237. return
  238. }
  239. http.Error(w, "401 - Unauthorized", http.StatusUnauthorized)
  240. }
  241. // leakSource returns the path mode app whose page issued a root request, or nil
  242. func (m *Manager) leakSource(r *http.Request) *endpointRuntime {
  243. ref := r.Header.Get("Referer")
  244. if ref == "" || !strings.Contains(ref, "/app/") || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
  245. return nil
  246. }
  247. for _, p := range leakExemptPrefixes {
  248. if strings.HasPrefix(r.URL.Path, p) {
  249. return nil
  250. }
  251. }
  252. refURL, err := url.Parse(ref)
  253. if err != nil || !strings.EqualFold(refURL.Host, r.Host) || !strings.HasPrefix(refURL.Path, "/app/") {
  254. return nil
  255. }
  256. slug, _, _ := strings.Cut(strings.TrimPrefix(refURL.Path, "/app/"), "/")
  257. rt := m.runtimeBySlug(slug)
  258. if rt == nil || rt.ep.Mode != ModePath || !rt.ep.RootRedirect {
  259. return nil
  260. }
  261. return rt
  262. }
  263. // redirectLeak sends a root request made by a path mode app back under its prefix
  264. func (m *Manager) redirectLeak(w http.ResponseWriter, r *http.Request) bool {
  265. rt := m.leakSource(r)
  266. if rt == nil {
  267. return false
  268. }
  269. rt.recordLeak(r.URL.Path)
  270. if isWebSocket(r) {
  271. //A websocket handshake cannot follow a redirect: route it directly
  272. prefixed := r.Clone(r.Context())
  273. prefixed.URL.Path = rt.ep.PathPrefix() + r.URL.Path
  274. prefixed.URL.RawPath = ""
  275. m.servePath(w, prefixed)
  276. return true
  277. }
  278. target := rt.ep.PathPrefix() + r.URL.EscapedPath()
  279. if r.URL.RawQuery != "" {
  280. target += "?" + r.URL.RawQuery
  281. }
  282. w.Header().Set("Cache-Control", "no-store")
  283. http.Redirect(w, r, target, http.StatusTemporaryRedirect)
  284. return true
  285. }
  286. // reservedCookies are the cookie names never forwarded to a container
  287. func (m *Manager) reservedCookies() map[string]bool {
  288. reserved := map[string]bool{SessionCookie: true}
  289. for _, c := range m.opts.StripCookies {
  290. reserved[c] = true
  291. }
  292. return reserved
  293. }
  294. // newReverseProxy builds the proxy of one endpoint
  295. func (m *Manager) newReverseProxy(rt *endpointRuntime) *httputil.ReverseProxy {
  296. ep := rt.ep
  297. upstream := ep.UpstreamURL()
  298. transport := m.transport
  299. if ep.TargetTLS && ep.SkipTLSVerify {
  300. transport = m.insecureTransport
  301. }
  302. reserved := m.reservedCookies()
  303. return &httputil.ReverseProxy{
  304. Transport: transport,
  305. FlushInterval: 100 * time.Millisecond,
  306. Rewrite: func(pr *httputil.ProxyRequest) {
  307. info := infoFrom(pr.In.Context())
  308. pr.SetURL(upstream)
  309. pr.SetXForwarded()
  310. //Keep the host name the browser used, like most reverse proxies
  311. pr.Out.Host = pr.In.Host
  312. if info != nil {
  313. pr.Out.Header.Set("X-Forwarded-Proto", info.scheme)
  314. if info.pathMode {
  315. pr.Out.Header.Set("X-Forwarded-Prefix", info.prefix)
  316. //Present the Referer as the app would see it without the prefix
  317. if ref, err := url.Parse(pr.In.Header.Get("Referer")); err == nil && strings.EqualFold(ref.Host, pr.In.Host) && hasPrefixPath(ref.Path, info.prefix) {
  318. ref.Path = strings.TrimPrefix(ref.Path, info.prefix)
  319. if ref.Path == "" {
  320. ref.Path = "/"
  321. }
  322. ref.RawPath = ""
  323. pr.Out.Header.Set("Referer", ref.String())
  324. }
  325. if ep.RewriteRoot {
  326. //Only gzip can be decoded for rewriting
  327. if strings.Contains(pr.In.Header.Get("Accept-Encoding"), "gzip") {
  328. pr.Out.Header.Set("Accept-Encoding", "gzip")
  329. } else {
  330. pr.Out.Header.Set("Accept-Encoding", "identity")
  331. }
  332. }
  333. }
  334. }
  335. if cookies := pr.Out.Header.Values("Cookie"); len(cookies) > 0 {
  336. filtered := filterRequestCookies(strings.Join(cookies, "; "), reserved)
  337. pr.Out.Header.Del("Cookie")
  338. if filtered != "" {
  339. pr.Out.Header.Set("Cookie", filtered)
  340. }
  341. }
  342. },
  343. ModifyResponse: func(resp *http.Response) error {
  344. return m.modifyResponse(resp, reserved)
  345. },
  346. ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
  347. if errors.Is(err, context.Canceled) {
  348. return
  349. }
  350. m.opts.Log("Container app "+ep.Name+" ("+ep.Target+") is not responding", err)
  351. errorPage(w, http.StatusBadGateway, "App unavailable", "The container behind this app is not responding. It may be stopped or still starting.")
  352. },
  353. }
  354. }
  355. // modifyResponse rewrites the upstream response headers and, when enabled, body
  356. func (m *Manager) modifyResponse(resp *http.Response, reserved map[string]bool) error {
  357. info := infoFrom(resp.Request.Context())
  358. if info == nil {
  359. return nil
  360. }
  361. ep := info.rt.ep
  362. knownHosts := []string{info.publicHost, ep.Target}
  363. if loc := resp.Header.Get("Location"); loc != "" {
  364. resp.Header.Set("Location", rewriteLocation(loc, info, ep))
  365. }
  366. if cookies := resp.Header.Values("Set-Cookie"); len(cookies) > 0 {
  367. resp.Header.Del("Set-Cookie")
  368. for _, c := range cookies {
  369. resp.Header.Add("Set-Cookie", rewriteSetCookie(c, info.prefix, reserved))
  370. }
  371. }
  372. if ep.AllowFraming {
  373. resp.Header.Del("X-Frame-Options")
  374. for _, h := range []string{"Content-Security-Policy", "Content-Security-Policy-Report-Only"} {
  375. values := resp.Header.Values(h)
  376. if len(values) == 0 {
  377. continue
  378. }
  379. resp.Header.Del(h)
  380. for _, v := range values {
  381. if stripped := stripFrameAncestors(v); stripped != "" {
  382. resp.Header.Add(h, stripped)
  383. }
  384. }
  385. }
  386. }
  387. if !info.pathMode {
  388. return nil
  389. }
  390. if ep.RootRedirect {
  391. if fixed := fixReferrerPolicy(resp.Header.Values("Referrer-Policy")); fixed != "" {
  392. resp.Header.Set("Referrer-Policy", fixed)
  393. }
  394. }
  395. if refresh := resp.Header.Get("Refresh"); refresh != "" {
  396. resp.Header.Set("Refresh", rewriteMetaRefresh(refresh, info.prefix, knownHosts))
  397. }
  398. if !ep.RewriteRoot || resp.Request.Method == http.MethodHead || resp.StatusCode == http.StatusNoContent || resp.StatusCode == http.StatusNotModified {
  399. return nil
  400. }
  401. mediaType := strings.ToLower(strings.TrimSpace(strings.Split(resp.Header.Get("Content-Type"), ";")[0]))
  402. isHTML := mediaType == "text/html" || mediaType == "application/xhtml+xml"
  403. isCSS := mediaType == "text/css"
  404. if !isHTML && !isCSS {
  405. return nil
  406. }
  407. encoding := strings.ToLower(strings.TrimSpace(resp.Header.Get("Content-Encoding")))
  408. if encoding != "" && encoding != "identity" && encoding != "gzip" {
  409. //Cannot decode it, pass through untouched
  410. return nil
  411. }
  412. body := resp.Body
  413. if encoding == "gzip" {
  414. gz, err := gzip.NewReader(resp.Body)
  415. if err != nil {
  416. //Not really gzip, leave it alone
  417. return nil
  418. }
  419. body = struct {
  420. io.Reader
  421. io.Closer
  422. }{gz, resp.Body}
  423. resp.Header.Del("Content-Encoding")
  424. }
  425. resp.Header.Del("Content-Length")
  426. resp.Header.Del("Content-MD5")
  427. resp.Header.Del("ETag")
  428. resp.ContentLength = -1
  429. if isCSS {
  430. data, err := io.ReadAll(io.LimitReader(body, maxCSSBytes+1))
  431. if err != nil || len(data) > maxCSSBytes {
  432. //Too large (or broken) to rewrite: stream it unchanged
  433. resp.Body = struct {
  434. io.Reader
  435. io.Closer
  436. }{io.MultiReader(bytes.NewReader(data), body), body}
  437. return nil
  438. }
  439. body.Close()
  440. rewritten := rewriteCSS(string(data), info.prefix, knownHosts)
  441. resp.Body = io.NopCloser(strings.NewReader(rewritten))
  442. resp.ContentLength = int64(len(rewritten))
  443. resp.Header.Set("Content-Length", strconv.Itoa(len(rewritten)))
  444. return nil
  445. }
  446. //HTML is rewritten as a stream
  447. pr, pw := io.Pipe()
  448. go func() {
  449. err := rewriteHTML(body, pw, info.prefix, knownHosts, info.prefix+shimPath)
  450. body.Close()
  451. pw.CloseWithError(err)
  452. }()
  453. resp.Body = pr
  454. return nil
  455. }
  456. // rewriteLocation maps a redirect of the app onto its public address
  457. func rewriteLocation(loc string, info *requestInfo, ep *Endpoint) string {
  458. if info.pathMode {
  459. return rewriteURL(loc, info.prefix, []string{info.publicHost, ep.Target})
  460. }
  461. u, err := url.Parse(loc)
  462. if err != nil || !strings.EqualFold(u.Host, ep.Target) {
  463. return loc
  464. }
  465. u.Scheme = info.scheme
  466. u.Host = info.publicHost
  467. return u.String()
  468. }
  469. // errorPage renders a small self-contained error page
  470. func errorPage(w http.ResponseWriter, status int, title string, message string) {
  471. errorPageWithLink(w, status, title, message, "", "")
  472. }
  473. func errorPageWithLink(w http.ResponseWriter, status int, title string, message string, link string, linkText string) {
  474. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  475. w.Header().Set("Cache-Control", "no-store")
  476. w.WriteHeader(status)
  477. action := ""
  478. if link != "" {
  479. action = `<p><a href="` + html.EscapeString(link) + `">` + html.EscapeString(linkText) + `</a></p>`
  480. }
  481. io.WriteString(w, `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>`+
  482. html.EscapeString(title)+`</title><style>
  483. body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;background:#f5f5f7;color:#1d1d1f;display:flex;align-items:center;justify-content:center;min-height:100vh}
  484. @media (prefers-color-scheme:dark){body{background:#1c1c1e;color:#f5f5f7}.card{background:#2c2c2e!important}}
  485. .card{background:#fff;border-radius:12px;padding:28px 32px;max-width:420px;box-shadow:0 6px 20px rgba(0,0,0,.08)}
  486. h1{font-size:18px;margin:0 0 8px}p{font-size:14px;line-height:1.5;margin:0 0 8px;opacity:.8}a{color:#0a84ff}
  487. .code{font-size:12px;opacity:.5;margin-bottom:6px}</style></head><body><div class="card"><div class="code">`+
  488. strconv.Itoa(status)+`</div><h1>`+html.EscapeString(title)+`</h1><p>`+html.EscapeString(message)+`</p>`+action+`</div></body></html>`)
  489. }