proxy_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package appproxy
  2. import (
  3. "compress/gzip"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/url"
  8. "strings"
  9. "testing"
  10. )
  11. // newUpstream starts a fake container web app that records what it received
  12. func newUpstream(t *testing.T) (*httptest.Server, *http.Request) {
  13. t.Helper()
  14. last := &http.Request{}
  15. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  16. *last = *r.Clone(r.Context())
  17. switch r.URL.Path {
  18. case "/":
  19. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  20. w.Header().Set("X-Frame-Options", "DENY")
  21. w.Header().Set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'")
  22. http.SetCookie(w, &http.Cookie{Name: "sid", Value: "1", Path: "/"})
  23. io.WriteString(w, `<html><head><link href="/style.css" rel="stylesheet"></head><body><img src="/logo.png"></body></html>`)
  24. case "/gz":
  25. w.Header().Set("Content-Type", "text/html")
  26. w.Header().Set("Content-Encoding", "gzip")
  27. gz := gzip.NewWriter(w)
  28. io.WriteString(gz, `<head></head><img src="/zipped.png">`)
  29. gz.Close()
  30. case "/style.css":
  31. w.Header().Set("Content-Type", "text/css")
  32. io.WriteString(w, `body{background:url(/bg.png)}`)
  33. case "/login":
  34. http.Redirect(w, r, "/dashboard", http.StatusFound)
  35. case "/absolute":
  36. w.Header().Set("Location", "http://"+r.Host+"/elsewhere")
  37. w.WriteHeader(http.StatusFound)
  38. default:
  39. io.WriteString(w, "path="+r.URL.Path)
  40. }
  41. }))
  42. t.Cleanup(srv.Close)
  43. return srv, last
  44. }
  45. func upstreamTarget(srv *httptest.Server) string {
  46. u, _ := url.Parse(srv.URL)
  47. return u.Host
  48. }
  49. func doRequest(m *Manager, method string, target string, headers map[string]string) *httptest.ResponseRecorder {
  50. req := httptest.NewRequest(method, target, nil)
  51. for k, v := range headers {
  52. req.Header.Set(k, v)
  53. }
  54. rec := httptest.NewRecorder()
  55. if !m.HandleRequest(rec, req) {
  56. rec.Code = -1
  57. }
  58. return rec
  59. }
  60. func TestPathModeProxy(t *testing.T) {
  61. up, last := newUpstream(t)
  62. m := newTestManager(t, nil)
  63. ep := pathEndpoint("demo", upstreamTarget(up))
  64. ep.RewriteRoot = true
  65. ep.AllowFraming = true
  66. if _, err := m.Save(ep, true, "admin", "nas.local"); err != nil {
  67. t.Fatal(err)
  68. }
  69. t.Run("prefix stripped and cookies filtered", func(t *testing.T) {
  70. rec := doRequest(m, "GET", "http://nas.local/app/demo/api/x?q=1", map[string]string{
  71. "X-Test-User": "alice",
  72. "Cookie": "ao_auth=secret; sid=1; aoc_ao_acc=mine",
  73. "Referer": "http://nas.local/app/demo/page",
  74. })
  75. if rec.Code != 200 || rec.Body.String() != "path=/api/x" {
  76. t.Fatalf("got %d %q", rec.Code, rec.Body.String())
  77. }
  78. if got := last.Header.Get("Cookie"); got != "sid=1; ao_acc=mine" {
  79. t.Errorf("upstream cookies = %q", got)
  80. }
  81. if last.Host != "nas.local" {
  82. t.Errorf("upstream Host = %q, want the public host", last.Host)
  83. }
  84. if last.Header.Get("X-Forwarded-Prefix") != "/app/demo" {
  85. t.Errorf("missing X-Forwarded-Prefix")
  86. }
  87. if last.Header.Get("Referer") != "http://nas.local/page" {
  88. t.Errorf("upstream Referer = %q", last.Header.Get("Referer"))
  89. }
  90. if last.URL.RawQuery != "q=1" {
  91. t.Errorf("query = %q", last.URL.RawQuery)
  92. }
  93. })
  94. t.Run("html rewritten and headers fixed", func(t *testing.T) {
  95. rec := doRequest(m, "GET", "http://nas.local/app/demo/", map[string]string{"X-Test-User": "alice"})
  96. body := rec.Body.String()
  97. for _, want := range []string{`href="/app/demo/style.css"`, `src="/app/demo/logo.png"`, `/app/demo/__appproxy/shim.js`} {
  98. if !strings.Contains(body, want) {
  99. t.Errorf("body missing %q: %s", want, body)
  100. }
  101. }
  102. if rec.Header().Get("X-Frame-Options") != "" {
  103. t.Errorf("X-Frame-Options should be stripped")
  104. }
  105. if csp := rec.Header().Get("Content-Security-Policy"); strings.Contains(csp, "frame-ancestors") {
  106. t.Errorf("CSP still has frame-ancestors: %q", csp)
  107. }
  108. if c := rec.Header().Get("Set-Cookie"); !strings.Contains(c, "Path=/app/demo/") {
  109. t.Errorf("Set-Cookie not scoped: %q", c)
  110. }
  111. })
  112. t.Run("gzip html rewritten", func(t *testing.T) {
  113. rec := doRequest(m, "GET", "http://nas.local/app/demo/gz", map[string]string{"X-Test-User": "alice", "Accept-Encoding": "gzip"})
  114. if rec.Header().Get("Content-Encoding") != "" {
  115. t.Errorf("rewritten body should be sent decoded")
  116. }
  117. if !strings.Contains(rec.Body.String(), `src="/app/demo/zipped.png"`) {
  118. t.Errorf("gzip body not rewritten: %q", rec.Body.String())
  119. }
  120. })
  121. t.Run("css rewritten", func(t *testing.T) {
  122. rec := doRequest(m, "GET", "http://nas.local/app/demo/style.css", map[string]string{"X-Test-User": "alice"})
  123. if rec.Body.String() != `body{background:url(/app/demo/bg.png)}` {
  124. t.Errorf("css = %q", rec.Body.String())
  125. }
  126. })
  127. t.Run("redirects stay under the prefix", func(t *testing.T) {
  128. rec := doRequest(m, "GET", "http://nas.local/app/demo/login", map[string]string{"X-Test-User": "alice"})
  129. if loc := rec.Header().Get("Location"); loc != "/app/demo/dashboard" {
  130. t.Errorf("Location = %q", loc)
  131. }
  132. rec = doRequest(m, "GET", "http://nas.local/app/demo/absolute", map[string]string{"X-Test-User": "alice"})
  133. if loc := rec.Header().Get("Location"); loc != "/app/demo/elsewhere" {
  134. t.Errorf("absolute Location = %q", loc)
  135. }
  136. })
  137. t.Run("shim served", func(t *testing.T) {
  138. rec := doRequest(m, "GET", "http://nas.local/app/demo/__appproxy/shim.js", map[string]string{"X-Test-User": "alice"})
  139. if !strings.Contains(rec.Body.String(), `"/app/demo"`) {
  140. t.Errorf("shim not served")
  141. }
  142. })
  143. }
  144. func TestPathModeAccess(t *testing.T) {
  145. up, _ := newUpstream(t)
  146. m := newTestManager(t, nil)
  147. ep := pathEndpoint("demo", upstreamTarget(up))
  148. ep.AllowedGroups = []string{"users"}
  149. if _, err := m.Save(ep, true, "admin", "nas.local"); err != nil {
  150. t.Fatal(err)
  151. }
  152. tests := []struct {
  153. name string
  154. target string
  155. headers map[string]string
  156. wantCode int
  157. wantLoc string
  158. }{
  159. {"anonymous page load goes to login", "/app/demo/x", map[string]string{"Sec-Fetch-Mode": "navigate"}, http.StatusFound, "/login.html?redirect=/app/demo/x"},
  160. {"anonymous xhr is refused", "/app/demo/x", map[string]string{"Sec-Fetch-Mode": "cors"}, http.StatusUnauthorized, ""},
  161. {"wrong group", "/app/demo/x", map[string]string{"X-Test-User": "bob"}, http.StatusForbidden, ""},
  162. {"right group", "/app/demo/x", map[string]string{"X-Test-User": "alice"}, http.StatusOK, ""},
  163. {"admin", "/app/demo/x", map[string]string{"X-Test-User": "admin"}, http.StatusOK, ""},
  164. {"no trailing slash", "/app/demo", map[string]string{"X-Test-User": "alice"}, http.StatusFound, "/app/demo/"},
  165. {"unknown app", "/app/nope/", map[string]string{"X-Test-User": "alice"}, http.StatusNotFound, ""},
  166. {"bare /app/", "/app/", map[string]string{"X-Test-User": "alice"}, http.StatusNotFound, ""},
  167. }
  168. for _, tt := range tests {
  169. t.Run(tt.name, func(t *testing.T) {
  170. rec := doRequest(m, "GET", "http://nas.local"+tt.target, tt.headers)
  171. if rec.Code != tt.wantCode {
  172. t.Errorf("code = %d, want %d", rec.Code, tt.wantCode)
  173. }
  174. if tt.wantLoc != "" && rec.Header().Get("Location") != tt.wantLoc {
  175. t.Errorf("Location = %q, want %q", rec.Header().Get("Location"), tt.wantLoc)
  176. }
  177. })
  178. }
  179. }
  180. func TestLeakRedirect(t *testing.T) {
  181. up, _ := newUpstream(t)
  182. m := newTestManager(t, nil)
  183. if _, err := m.Save(pathEndpoint("demo", upstreamTarget(up)), true, "admin", "nas.local"); err != nil {
  184. t.Fatal(err)
  185. }
  186. noRedirect := pathEndpoint("plain", upstreamTarget(up))
  187. noRedirect.RootRedirect = false
  188. if _, err := m.Save(noRedirect, true, "admin", "nas.local"); err != nil {
  189. t.Fatal(err)
  190. }
  191. tests := []struct {
  192. name string
  193. method string
  194. target string
  195. referer string
  196. extra map[string]string
  197. handled bool
  198. wantLoc string
  199. }{
  200. {"asset from app page", "GET", "/script/jquery.min.js", "http://nas.local/app/demo/", nil, true, "/app/demo/script/jquery.min.js"},
  201. {"post keeps query", "POST", "/api/save?x=1", "http://nas.local/app/demo/edit", nil, true, "/app/demo/api/save?x=1"},
  202. {"favicon of the app", "GET", "/favicon.ico", "http://nas.local/app/demo/", nil, true, "/app/demo/favicon.ico"},
  203. {"arozos page untouched", "GET", "/script/jquery.min.js", "http://nas.local/desktop.html", nil, false, ""},
  204. {"no referer", "GET", "/desktop.html", "", nil, false, ""},
  205. {"login is exempt", "GET", "/login.html?redirect=/app/demo/", "http://nas.local/app/demo/", nil, false, ""},
  206. {"other host referer", "GET", "/x", "http://evil.example/app/demo/", nil, false, ""},
  207. {"cross-site fetch", "GET", "/x", "http://nas.local/app/demo/", map[string]string{"Sec-Fetch-Site": "cross-site"}, false, ""},
  208. {"redirect disabled for app", "GET", "/x", "http://nas.local/app/plain/", nil, false, ""},
  209. {"unknown app", "GET", "/x", "http://nas.local/app/gone/", nil, false, ""},
  210. }
  211. for _, tt := range tests {
  212. t.Run(tt.name, func(t *testing.T) {
  213. headers := map[string]string{"X-Test-User": "alice"}
  214. if tt.referer != "" {
  215. headers["Referer"] = tt.referer
  216. }
  217. for k, v := range tt.extra {
  218. headers[k] = v
  219. }
  220. rec := doRequest(m, tt.method, "http://nas.local"+tt.target, headers)
  221. if handled := rec.Code != -1; handled != tt.handled {
  222. t.Fatalf("handled = %v, want %v", handled, tt.handled)
  223. }
  224. if tt.handled {
  225. if rec.Code != http.StatusTemporaryRedirect {
  226. t.Errorf("code = %d, want 307", rec.Code)
  227. }
  228. if rec.Header().Get("Location") != tt.wantLoc {
  229. t.Errorf("Location = %q, want %q", rec.Header().Get("Location"), tt.wantLoc)
  230. }
  231. }
  232. })
  233. }
  234. if s := m.Stats("demo"); s.Leaks != 3 || s.LastLeaks[0] != "/favicon.ico" {
  235. t.Errorf("leak stats = %+v", s)
  236. }
  237. }
  238. func TestSubdomainMode(t *testing.T) {
  239. up, last := newUpstream(t)
  240. m := newTestManager(t, nil)
  241. ep := Endpoint{
  242. Slug: "media", Target: upstreamTarget(up), Mode: ModeSubdomain,
  243. Hostname: "media.example.com", PortalOrigin: "https://nas.example.com", RequireLogin: true,
  244. }
  245. if _, err := m.Save(ep, true, "admin", "nas.example.com"); err != nil {
  246. t.Fatal(err)
  247. }
  248. //1. The shortcut opens /app/media/ on the portal, which hands the login over
  249. rec := doRequest(m, "GET", "https://nas.example.com/app/media/library?x=1", map[string]string{"X-Test-User": "alice"})
  250. loc, _ := url.Parse(rec.Header().Get("Location"))
  251. if rec.Code != http.StatusFound || loc.Host != "media.example.com" || loc.Path != claimPath {
  252. t.Fatalf("hand-off redirect = %d %q", rec.Code, rec.Header().Get("Location"))
  253. }
  254. ticketValue := loc.Query().Get("t")
  255. //2. Without a session the app host sends a page load back to the portal
  256. rec = doRequest(m, "GET", "https://media.example.com/library", map[string]string{"Sec-Fetch-Mode": "navigate"})
  257. if rec.Code != http.StatusFound || rec.Header().Get("Location") != "https://nas.example.com/app/media/library" {
  258. t.Errorf("anonymous app host = %d %q", rec.Code, rec.Header().Get("Location"))
  259. }
  260. //3. Claiming the ticket sets the app session and continues to the page
  261. rec = doRequest(m, "GET", "https://media.example.com"+claimPath+"?t="+ticketValue, map[string]string{"X-Forwarded-Proto": "https"})
  262. if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/library?x=1" {
  263. t.Fatalf("claim = %d %q", rec.Code, rec.Header().Get("Location"))
  264. }
  265. setCookie := rec.Header().Get("Set-Cookie")
  266. if !strings.Contains(setCookie, SessionCookie+"=") || !strings.Contains(setCookie, "HttpOnly") || !strings.Contains(setCookie, "Secure") {
  267. t.Errorf("session cookie = %q", setCookie)
  268. }
  269. session := strings.TrimPrefix(strings.Split(setCookie, ";")[0], SessionCookie+"=")
  270. //4. A ticket works once
  271. rec = doRequest(m, "GET", "https://media.example.com"+claimPath+"?t="+ticketValue, nil)
  272. if rec.Code != http.StatusForbidden {
  273. t.Errorf("reused ticket = %d, want 403", rec.Code)
  274. }
  275. //5. With the session the app is proxied, without the session cookie
  276. rec = doRequest(m, "GET", "https://media.example.com/library", map[string]string{"Cookie": SessionCookie + "=" + session + "; theme=dark"})
  277. if rec.Body.String() != "path=/library" {
  278. t.Fatalf("proxied body = %q", rec.Body.String())
  279. }
  280. if got := last.Header.Get("Cookie"); got != "theme=dark" {
  281. t.Errorf("upstream cookies = %q", got)
  282. }
  283. //6. Root paths need no rewriting on its own host
  284. rec = doRequest(m, "GET", "https://media.example.com/", map[string]string{"Cookie": SessionCookie + "=" + session})
  285. if !strings.Contains(rec.Body.String(), `href="/style.css"`) || strings.Contains(rec.Body.String(), "shim.js") {
  286. t.Errorf("subdomain page should be untouched: %s", rec.Body.String())
  287. }
  288. //7. Editing the app ends its sessions
  289. if _, err := m.Save(ep, false, "admin", "nas.example.com"); err != nil {
  290. t.Fatal(err)
  291. }
  292. rec = doRequest(m, "GET", "https://media.example.com/library", map[string]string{"Cookie": SessionCookie + "=" + session})
  293. if rec.Code != http.StatusUnauthorized {
  294. t.Errorf("session after edit = %d, want 401", rec.Code)
  295. }
  296. }
  297. func TestSubdomainPublicApp(t *testing.T) {
  298. up, _ := newUpstream(t)
  299. m := newTestManager(t, nil)
  300. ep := Endpoint{
  301. Slug: "status", Target: upstreamTarget(up), Mode: ModeSubdomain,
  302. Hostname: "status.example.com", PortalOrigin: "https://nas.example.com",
  303. }
  304. if _, err := m.Save(ep, true, "admin", "nas.example.com"); err != nil {
  305. t.Fatal(err)
  306. }
  307. rec := doRequest(m, "GET", "https://nas.example.com/app/status/", nil)
  308. if rec.Header().Get("Location") != "https://status.example.com/" {
  309. t.Errorf("public hand-off = %q", rec.Header().Get("Location"))
  310. }
  311. rec = doRequest(m, "GET", "https://status.example.com/ping", nil)
  312. if rec.Body.String() != "path=/ping" {
  313. t.Errorf("public app = %d %q", rec.Code, rec.Body.String())
  314. }
  315. }
  316. func TestUpstreamDown(t *testing.T) {
  317. up, _ := newUpstream(t)
  318. target := upstreamTarget(up)
  319. up.Close()
  320. m := newTestManager(t, nil)
  321. if _, err := m.Save(pathEndpoint("down", target), true, "admin", "nas.local"); err != nil {
  322. t.Fatal(err)
  323. }
  324. rec := doRequest(m, "GET", "http://nas.local/app/down/", map[string]string{"X-Test-User": "alice"})
  325. if rec.Code != http.StatusBadGateway || !strings.Contains(rec.Body.String(), "App unavailable") {
  326. t.Errorf("down upstream = %d %q", rec.Code, rec.Body.String())
  327. }
  328. }
  329. func TestUnrelatedRequestsPassThrough(t *testing.T) {
  330. m := newTestManager(t, nil)
  331. for _, p := range []string{"/", "/desktop.html", "/application/x", "/apps"} {
  332. if rec := doRequest(m, "GET", "http://nas.local"+p, nil); rec.Code != -1 {
  333. t.Errorf("%s should not be handled", p)
  334. }
  335. }
  336. }