rewrite.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. package appproxy
  2. import (
  3. "bytes"
  4. "io"
  5. "net/url"
  6. "regexp"
  7. "strings"
  8. "golang.org/x/net/html"
  9. )
  10. /*
  11. rewrite.go
  12. Keeps an app that assumes it owns "/" working under /app/<slug>/.
  13. - rewriteURL root-absolute and same-host absolute URLs -> prefixed
  14. - rewriteHTML URL attributes, <base>, <style>, style="", meta refresh,
  15. plus the rewrite script injected first in <head>
  16. - rewriteCSS url(...) and @import
  17. - rewriteSetCookie scope a container cookie to the prefix and keep it
  18. away from the ArozOS cookie names
  19. - stripFrameAncestors / fixReferrerPolicy for response headers
  20. Everything here is a pure function so it can be unit tested.
  21. */
  22. // renamedCookiePrefix marks a container cookie renamed to avoid an ArozOS name
  23. const renamedCookiePrefix = "aoc_"
  24. // hasPrefixPath reports whether p already lives under prefix
  25. func hasPrefixPath(p string, prefix string) bool {
  26. if !strings.HasPrefix(p, prefix) {
  27. return false
  28. }
  29. rest := p[len(prefix):]
  30. return rest == "" || rest[0] == '/' || rest[0] == '?' || rest[0] == '#'
  31. }
  32. // rewriteURL maps a URL an app emitted into the prefixed namespace. knownHosts
  33. // are hosts that mean "this app" (the public host and the upstream address)
  34. func rewriteURL(raw string, prefix string, knownHosts []string) string {
  35. trimmed := strings.TrimSpace(raw)
  36. if trimmed == "" {
  37. return raw
  38. }
  39. if strings.HasPrefix(trimmed, "//") {
  40. u, err := url.Parse("http:" + trimmed)
  41. if err != nil || !hostKnown(u.Host, knownHosts) {
  42. return raw
  43. }
  44. return prefixPath(u, prefix)
  45. }
  46. if strings.HasPrefix(trimmed, "/") {
  47. if hasPrefixPath(trimmed, prefix) {
  48. return raw
  49. }
  50. return prefix + trimmed
  51. }
  52. lower := strings.ToLower(trimmed)
  53. if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {
  54. u, err := url.Parse(trimmed)
  55. if err != nil || !hostKnown(u.Host, knownHosts) {
  56. return raw
  57. }
  58. return prefixPath(u, prefix)
  59. }
  60. return raw
  61. }
  62. // prefixPath renders a parsed URL as a prefixed, origin-relative URL
  63. func prefixPath(u *url.URL, prefix string) string {
  64. p := u.EscapedPath()
  65. if p == "" {
  66. p = "/"
  67. }
  68. if !hasPrefixPath(p, prefix) {
  69. p = prefix + p
  70. }
  71. if u.RawQuery != "" || u.ForceQuery {
  72. p += "?" + u.RawQuery
  73. }
  74. if u.Fragment != "" {
  75. p += "#" + u.EscapedFragment()
  76. }
  77. return p
  78. }
  79. func hostKnown(host string, knownHosts []string) bool {
  80. host = strings.ToLower(host)
  81. for _, h := range knownHosts {
  82. if h != "" && strings.ToLower(h) == host {
  83. return true
  84. }
  85. }
  86. return false
  87. }
  88. var (
  89. cssURLRegex = regexp.MustCompile(`(?i)url\(\s*(['"]?)([^'")]+?)(['"]?)\s*\)`)
  90. cssImportRegex = regexp.MustCompile(`(?i)@import\s+(['"])([^'"]+)(['"])`)
  91. )
  92. // rewriteCSS prefixes root paths in url(...) and @import
  93. func rewriteCSS(css string, prefix string, knownHosts []string) string {
  94. css = cssURLRegex.ReplaceAllStringFunc(css, func(m string) string {
  95. parts := cssURLRegex.FindStringSubmatch(m)
  96. if parts[1] != parts[3] || strings.HasPrefix(strings.ToLower(parts[2]), "data:") {
  97. return m
  98. }
  99. return "url(" + parts[1] + rewriteURL(parts[2], prefix, knownHosts) + parts[3] + ")"
  100. })
  101. return cssImportRegex.ReplaceAllStringFunc(css, func(m string) string {
  102. parts := cssImportRegex.FindStringSubmatch(m)
  103. if parts[1] != parts[3] {
  104. return m
  105. }
  106. return "@import " + parts[1] + rewriteURL(parts[2], prefix, knownHosts) + parts[3]
  107. })
  108. }
  109. // rewriteSrcset prefixes each candidate URL of a srcset attribute
  110. func rewriteSrcset(v string, prefix string, knownHosts []string) string {
  111. candidates := strings.Split(v, ",")
  112. for i, c := range candidates {
  113. fields := strings.Fields(c)
  114. if len(fields) == 0 {
  115. continue
  116. }
  117. fields[0] = rewriteURL(fields[0], prefix, knownHosts)
  118. candidates[i] = strings.Join(fields, " ")
  119. }
  120. return strings.Join(candidates, ", ")
  121. }
  122. // rewriteMetaRefresh prefixes the url= part of a meta refresh value
  123. func rewriteMetaRefresh(v string, prefix string, knownHosts []string) string {
  124. lower := strings.ToLower(v)
  125. idx := strings.Index(lower, "url=")
  126. if idx < 0 {
  127. return v
  128. }
  129. target := v[idx+4:]
  130. quote := ""
  131. if len(target) > 0 && (target[0] == '\'' || target[0] == '"') {
  132. quote = target[:1]
  133. target = strings.TrimSuffix(target[1:], quote)
  134. }
  135. return v[:idx+4] + quote + rewriteURL(target, prefix, knownHosts) + quote
  136. }
  137. // URL carrying attributes rewritten on any element
  138. var urlAttributes = map[string]bool{
  139. "href": true, "src": true, "action": true, "formaction": true,
  140. "poster": true, "data": true, "background": true, "manifest": true,
  141. "xlink:href": true,
  142. }
  143. // referrer policies that still send the full URL to the same origin
  144. var fullSameOriginReferrer = map[string]bool{
  145. "no-referrer-when-downgrade": true,
  146. "same-origin": true,
  147. "origin-when-cross-origin": true,
  148. "strict-origin-when-cross-origin": true,
  149. "unsafe-url": true,
  150. }
  151. // rewriteTag rewrites the attributes of one start tag, reporting whether anything changed
  152. func rewriteTag(t *html.Token, prefix string, knownHosts []string) bool {
  153. changed := false
  154. isMetaRefresh := false
  155. isMetaReferrer := false
  156. if t.Data == "meta" {
  157. for _, a := range t.Attr {
  158. if strings.EqualFold(a.Key, "http-equiv") && strings.EqualFold(strings.TrimSpace(a.Val), "refresh") {
  159. isMetaRefresh = true
  160. }
  161. if strings.EqualFold(a.Key, "name") && strings.EqualFold(strings.TrimSpace(a.Val), "referrer") {
  162. isMetaReferrer = true
  163. }
  164. }
  165. }
  166. for i := range t.Attr {
  167. a := &t.Attr[i]
  168. key := strings.ToLower(a.Key)
  169. if a.Namespace != "" {
  170. key = strings.ToLower(a.Namespace) + ":" + key
  171. }
  172. newVal := a.Val
  173. switch {
  174. case urlAttributes[key]:
  175. newVal = rewriteURL(a.Val, prefix, knownHosts)
  176. case key == "srcset" || key == "imagesrcset":
  177. newVal = rewriteSrcset(a.Val, prefix, knownHosts)
  178. case key == "style":
  179. newVal = rewriteCSS(a.Val, prefix, knownHosts)
  180. case key == "content" && isMetaRefresh:
  181. newVal = rewriteMetaRefresh(a.Val, prefix, knownHosts)
  182. case key == "content" && isMetaReferrer:
  183. if !fullSameOriginReferrer[strings.ToLower(strings.TrimSpace(a.Val))] {
  184. newVal = "strict-origin-when-cross-origin"
  185. }
  186. }
  187. if newVal != a.Val {
  188. a.Val = newVal
  189. changed = true
  190. }
  191. }
  192. return changed
  193. }
  194. // rewriteHTML rewrites an HTML document for the prefix. When shimSrc is not
  195. // empty a blocking <script src> is placed first in <head> so it runs before
  196. // any script of the app
  197. func rewriteHTML(r io.Reader, dst io.Writer, prefix string, knownHosts []string, shimSrc string) error {
  198. z := html.NewTokenizer(r)
  199. w := &errWriter{w: dst}
  200. injected := shimSrc == ""
  201. inStyle := false
  202. shimTag := []byte(`<script src="` + html.EscapeString(shimSrc) + `"></script>`)
  203. for {
  204. if w.err != nil {
  205. //The reader went away, stop early
  206. return w.err
  207. }
  208. tt := z.Next()
  209. if tt == html.ErrorToken {
  210. if z.Err() == io.EOF {
  211. return nil
  212. }
  213. return z.Err()
  214. }
  215. raw := z.Raw()
  216. switch tt {
  217. case html.StartTagToken, html.SelfClosingTagToken:
  218. t := z.Token()
  219. if !injected && t.Data != "html" && t.Data != "head" {
  220. //No <head> before content: inject before the first real tag
  221. w.Write(shimTag)
  222. injected = true
  223. }
  224. if rewriteTag(&t, prefix, knownHosts) {
  225. io.WriteString(w, t.String())
  226. } else {
  227. w.Write(raw)
  228. }
  229. if t.Data == "head" && !injected {
  230. w.Write(shimTag)
  231. injected = true
  232. }
  233. inStyle = tt == html.StartTagToken && t.Data == "style"
  234. case html.TextToken:
  235. if inStyle {
  236. io.WriteString(w, rewriteCSS(string(raw), prefix, knownHosts))
  237. } else {
  238. w.Write(raw)
  239. }
  240. case html.EndTagToken:
  241. inStyle = false
  242. w.Write(raw)
  243. default:
  244. w.Write(raw)
  245. }
  246. }
  247. }
  248. // errWriter remembers the first write error so a long rewrite can stop early
  249. type errWriter struct {
  250. w io.Writer
  251. err error
  252. }
  253. func (e *errWriter) Write(p []byte) (int, error) {
  254. if e.err != nil {
  255. return 0, e.err
  256. }
  257. n, err := e.w.Write(p)
  258. e.err = err
  259. return n, err
  260. }
  261. // rewriteHTMLString is a convenience wrapper used by tests
  262. func rewriteHTMLString(doc string, prefix string, knownHosts []string, shimSrc string) string {
  263. var buf bytes.Buffer
  264. rewriteHTML(strings.NewReader(doc), &buf, prefix, knownHosts, shimSrc)
  265. return buf.String()
  266. }
  267. // rewriteSetCookie scopes one Set-Cookie header value. In path mode the cookie
  268. // path is moved under prefix; in both modes Domain is dropped (the browser
  269. // only ever sees the public host) and names that clash with ArozOS cookies
  270. // are renamed
  271. func rewriteSetCookie(v string, prefix string, reserved map[string]bool) string {
  272. parts := strings.Split(v, ";")
  273. if len(parts) == 0 {
  274. return v
  275. }
  276. name, value, ok := strings.Cut(parts[0], "=")
  277. if !ok {
  278. return v
  279. }
  280. name = strings.TrimSpace(name)
  281. if cookieNameReserved(name, reserved) {
  282. name = renamedCookiePrefix + name
  283. }
  284. out := []string{name + "=" + value}
  285. for _, attr := range parts[1:] {
  286. key, val, _ := strings.Cut(strings.TrimSpace(attr), "=")
  287. switch strings.ToLower(strings.TrimSpace(key)) {
  288. case "domain":
  289. continue
  290. case "path":
  291. if prefix != "" {
  292. p := strings.TrimSpace(val)
  293. if p == "" || !strings.HasPrefix(p, "/") {
  294. p = "/"
  295. }
  296. if !hasPrefixPath(p, prefix) {
  297. p = prefix + p
  298. }
  299. out = append(out, "Path="+p)
  300. continue
  301. }
  302. }
  303. out = append(out, strings.TrimSpace(attr))
  304. }
  305. return strings.Join(out, "; ")
  306. }
  307. // cookieNameReserved reports whether a container may not use a cookie name as is
  308. func cookieNameReserved(name string, reserved map[string]bool) bool {
  309. return reserved[name] || strings.HasPrefix(name, "ao_") || strings.HasPrefix(name, renamedCookiePrefix)
  310. }
  311. // filterRequestCookies removes ArozOS cookies from a Cookie header and gives
  312. // renamed container cookies their original name back
  313. func filterRequestCookies(header string, reserved map[string]bool) string {
  314. kept := []string{}
  315. for _, c := range strings.Split(header, ";") {
  316. c = strings.TrimSpace(c)
  317. if c == "" {
  318. continue
  319. }
  320. name, value, _ := strings.Cut(c, "=")
  321. if strings.HasPrefix(name, renamedCookiePrefix) {
  322. kept = append(kept, strings.TrimPrefix(name, renamedCookiePrefix)+"="+value)
  323. continue
  324. }
  325. if cookieNameReserved(name, reserved) {
  326. continue
  327. }
  328. kept = append(kept, c)
  329. }
  330. return strings.Join(kept, "; ")
  331. }
  332. // stripFrameAncestors removes the frame-ancestors directive from a CSP value
  333. func stripFrameAncestors(policy string) string {
  334. kept := []string{}
  335. for _, d := range strings.Split(policy, ";") {
  336. d = strings.TrimSpace(d)
  337. if d == "" || strings.HasPrefix(strings.ToLower(d), "frame-ancestors") {
  338. continue
  339. }
  340. kept = append(kept, d)
  341. }
  342. return strings.Join(kept, "; ")
  343. }
  344. // fixReferrerPolicy makes sure same-origin requests keep carrying the full
  345. // Referer, which the root redirect depends on. Empty means leave the header
  346. func fixReferrerPolicy(values []string) string {
  347. effective := ""
  348. for _, v := range values {
  349. for _, p := range strings.Split(v, ",") {
  350. p = strings.ToLower(strings.TrimSpace(p))
  351. if p != "" {
  352. effective = p
  353. }
  354. }
  355. }
  356. if effective == "" || fullSameOriginReferrer[effective] {
  357. return ""
  358. }
  359. return "strict-origin-when-cross-origin"
  360. }