| new file mode 100644 |
| index 000000000..0e01d4cc5 |
| --- /dev/null |
| +++ b/internal/edge/demo_response_test.go |
| @@ -0,0 +1,418 @@ |
| +package edge |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/http/httptrace" |
| + "net/textproto" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +const testDemoCSP = "default-src 'none'; form-action 'self'; connect-src 'self'; img-src 'self'; script-src 'self'; script-src-attr 'none'; style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'self'; object-src 'none'; base-uri 'none'; worker-src 'none'; manifest-src 'none'; frame-ancestors 'none'" |
| + |
| +func assertDemoPolicy(t *testing.T, h http.Header) { |
| + t.Helper() |
| + for key, want := range map[string]string{ |
| + "Content-Security-Policy": testDemoCSP, |
| + "X-Frame-Options": "DENY", |
| + "X-Content-Type-Options": "nosniff", |
| + "Referrer-Policy": "no-referrer", |
| + "Cache-Control": "no-store", |
| + "X-DNS-Prefetch-Control": "off", |
| + "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=(), fullscreen=(), document-domain=()", |
| + } { |
| + if got := h.Values(key); !reflect.DeepEqual(got, []string{want}) { |
| + t.Errorf("%s = %q, want single %q", key, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoPolicyEveryExit(t *testing.T) { |
| + for _, method := range []string{http.MethodGet, http.MethodHead} { |
| + for _, status := range []int{200, 204, 303, 304, 400, 404, 429, 502, 503} { |
| + t.Run(fmt.Sprintf("%s/%d", method, status), func(t *testing.T) { |
| + r := httptest.NewRequest(method, "https://shop.demos.example.com/path", nil) |
| + rec := httptest.NewRecorder() |
| + w := new(Edge).beginDemoResponse(rec, r) |
| + w.Header().Set("Content-Security-Policy", "default-src *") |
| + w.Header().Set("Content-Security-Policy-Report-Only", "default-src *") |
| + if status == 303 { |
| + w.Header().Set("Location", "../next?q=1") |
| + } |
| + w.WriteHeader(status) |
| + _, _ = io.WriteString(w, "body") |
| + if rec.Code != status { |
| + t.Fatalf("status = %d", rec.Code) |
| + } |
| + assertDemoPolicy(t, rec.Result().Header) |
| + if rec.Header().Get("Content-Security-Policy-Report-Only") != "" { |
| + t.Error("report-only policy survived") |
| + } |
| + if (method == http.MethodHead || status == 204 || status == 304) && rec.Body.Len() != 0 { |
| + t.Error("body on an empty response") |
| + } |
| + }) |
| + } |
| + } |
| + |
| + t.Setenv("CARLOS_DEMO_DOMAIN", "demos.example.com") |
| + t.Setenv("CARLOS_DEMO_ACCOUNT", "bah") |
| + t.Setenv("CARLOS_DEMO_FLEET", "home") |
| + reg := openReg(t) |
| + t.Cleanup(func() { _ = reg.Close() }) |
| + identity, err := demo.NewIdentity(strings.NewReader(strings.Repeat("\x00", 64))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + host := identity.Name + ".demos.example.com" |
| + route := provision.RouteFor(provision.Record{Host: host, App: identity.App, Account: "bah", Region: "fleet/home", Channel: "edge", FleetBox: "box-1", FleetBoxAt: time.Now().UTC().Format(time.RFC3339Nano), Demo: &demo.Descriptor{ID: identity.ID, Host: host, Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()}}, t.TempDir(), "", true, nil) |
| + if err := reg.Upsert(route); err != nil { |
| + t.Fatal(err) |
| + } |
| + bad := registry.Route{Host: "marked.example.com", App: "shop", Kind: "instance", Addr: "127.0.0.1:1", Status: "ready", DemoID: "partial"} |
| + if err := reg.Upsert(bad); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.UpsertAlias(registry.RouteAlias{Host: bad.Host, Alias: "alias.example.com"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + e.fallbackURL = "https://example.com/fallback" |
| + e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)) |
| + seed(t, e.cache, host, "/path", "", "cached demo") |
| + seed(t, e.cache, host, "/", "", "cached demo") |
| + for _, tc := range []struct { |
| + host string |
| + status int |
| + }{ |
| + {host, 503}, {strings.ToUpper(host) + ":443", 503}, |
| + {"unknown.demos.example.com", 404}, {"demos.example.com", 404}, {"deep.shop.demos.example.com", 404}, |
| + {"shop.demos.example.com.", 400}, {"shop.demos.example.com:bad", 400}, |
| + {"shop.demos.example.com:443:80", 400}, |
| + {bad.Host, 404}, {"MARKED.EXAMPLE.COM:443", 404}, {"alias.example.com", 404}, |
| + } { |
| + for _, method := range []string{http.MethodGet, http.MethodHead} { |
| + for _, handler := range []http.Handler{e, e.httpFallbackHandler(), http.HandlerFunc(e.unknownHost)} { |
| + r := httptest.NewRequest(method, "https://example.com/path", nil) |
| + r.Host = tc.host |
| + rec := httptest.NewRecorder() |
| + handler.ServeHTTP(rec, r) |
| + if rec.Code != tc.status { |
| + t.Errorf("%s %s: status = %d, want %d", method, tc.host, rec.Code, tc.status) |
| + } |
| + assertDemoPolicy(t, rec.Result().Header) |
| + if rec.Header().Get("Location") != "" { |
| + t.Errorf("%s: fallback redirect", tc.host) |
| + } |
| + if method == http.MethodHead && rec.Body.Len() != 0 { |
| + t.Error("HEAD body") |
| + } |
| + } |
| + } |
| + } |
| + // Even a stale map entry that escaped reload filtering cannot dispatch. |
| + m := e.current() |
| + m[bad.Host] = upstream{route: bad, proxy: http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("invalid demo dispatched") })} |
| + for _, dest := range []string{"", "worker", "serviceworker", "sharedworker"} { |
| + r := httptest.NewRequest(http.MethodGet, "https://"+host+"/", nil) |
| + r.Header.Set("Sec-Fetch-Dest", dest) |
| + r.Header.Set("Connection", "upgrade") |
| + r.Header.Set("Upgrade", "websocket") |
| + rec := httptest.NewRecorder() |
| + e.ServeHTTP(rec, r) |
| + if rec.Code != 503 { |
| + t.Errorf("%s: demo served while disabled: %d", dest, rec.Code) |
| + } |
| + assertDemoPolicy(t, rec.Header()) |
| + } |
| + r := httptest.NewRequest(http.MethodGet, "https://"+bad.Host+"/", nil) |
| + rec := httptest.NewRecorder() |
| + e.ServeHTTP(rec, r) |
| + if rec.Code != 404 { |
| + t.Errorf("invalid marked route: %d", rec.Code) |
| + } |
| + assertDemoPolicy(t, rec.Header()) |
| + // An unavailable fleet tunnel must not replace the closed serving gate. |
| + m[host] = upstream{route: route, viaTunnel: true, proxy: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Error("demo reached tunnel"); w.WriteHeader(502) })} |
| + rec = get(e, "GET", "https://"+host+"/") |
| + if rec.Code != 503 { |
| + t.Errorf("tunnel: %d", rec.Code) |
| + } |
| + assertDemoPolicy(t, rec.Header()) |
| + route.DemoExpiresAt = time.Now().Add(-time.Minute).Unix() |
| + m[host] = upstream{route: route, proxy: http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("expired demo dispatched") })} |
| + rec = get(e, "GET", "https://"+host+"/") |
| + unknown := get(e, "GET", "https://unknown.demos.example.com/") |
| + if rec.Code != 404 || rec.Body.String() != unknown.Body.String() { |
| + t.Errorf("expired demo differs from unknown: %d %q", rec.Code, rec.Body.String()) |
| + } |
| + assertDemoPolicy(t, rec.Header()) |
| + e.demo = demo.Config{} |
| + rec = get(e, "GET", "https://"+bad.Host+"/") |
| + if rec.Code != 404 { |
| + t.Errorf("marked route with no demo configuration: %d", rec.Code) |
| + } |
| + assertDemoPolicy(t, rec.Header()) |
| +} |
| + |
| +func TestDemoCookieRewrite(t *testing.T) { |
| + h := http.Header{"Set-Cookie": { |
| + "sid=one; Domain=example.com; Path=/; dOmAiN=.demos.example.com; Secure; HttpOnly; SameSite=Lax", |
| + "other=two; Expires=Wed, 09 Jun 2027 10:18:14 GMT; DOMAIN=example.com; Max-Age=60; Partitioned; Secure", |
| + "bad name=value; Domain=example.com", "broken", "bad=value\r\nSet-Cookie: evil=yes", "bad=one,two", "bad=\"unclosed", |
| + }} |
| + if err := rewriteDemoCookies(h); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []string{"sid=one; Path=/; Secure; HttpOnly; SameSite=Lax", "other=two; Expires=Wed, 09 Jun 2027 10:18:14 GMT; Max-Age=60; Partitioned; Secure"} |
| + if !reflect.DeepEqual(h.Values("Set-Cookie"), want) { |
| + t.Fatalf("cookies = %#v", h.Values("Set-Cookie")) |
| + } |
| + for _, trailer := range []string{"Trailer", "trailer", "Trailer:Set-Cookie", "Trailer:Content-Security-Policy", "trailer:Access-Control-Allow-Origin"} { |
| + h.Set(trailer, "Set-Cookie, Content-Security-Policy") |
| + } |
| + if err := sanitizeDemoHeaders(h, "shop.demos.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + for key := range h { |
| + if strings.HasPrefix(strings.ToLower(key), "trailer") { |
| + t.Errorf("trailer survived: %s", key) |
| + } |
| + } |
| + if !reflect.DeepEqual(h.Values("Set-Cookie"), want) { |
| + t.Error("sanitizing changed cookie fields") |
| + } |
| +} |
| + |
| +func TestDemoHeaderIsolation(t *testing.T) { |
| + r := httptest.NewRequest("GET", "https://shop.demos.example.com/", nil) |
| + rec := httptest.NewRecorder() |
| + rec.Header().Set("X-Cached", "original") |
| + w := new(Edge).beginDemoResponse(rec, r) |
| + h := w.Header() |
| + h.Set("X-Cached", "upstream") |
| + if rec.Header().Get("X-Cached") != "original" { |
| + t.Fatal("shared header map") |
| + } |
| + h.Set("Content-Security-Policy", "default-src *") |
| + h.Set("Trailer", "Set-Cookie, Content-Security-Policy") |
| + w.WriteHeader(103) |
| + if rec.Flushed || rec.Body.Len() != 0 { |
| + t.Error("informational response escaped") |
| + } |
| + w.WriteHeader(200) |
| + h.Set("Content-Security-Policy", "default-src https://example.com") |
| + h.Set("Set-Cookie", "late=1; Domain=example.com") |
| + h.Set("Trailer:Set-Cookie", "late=2; Domain=example.com") |
| + h.Set("Trailer:Content-Security-Policy", "default-src *") |
| + _, _ = io.WriteString(w, "body") |
| + assertDemoPolicy(t, rec.Result().Header) |
| + assertDemoPolicy(t, rec.Header()) |
| + if rec.Header().Get("Set-Cookie") != "" || len(rec.Result().Trailer) != 0 { |
| + t.Error("late cookie or trailer escaped") |
| + } |
| + if _, ok := w.(http.Hijacker); ok { |
| + t.Error("Hijacker exposed") |
| + } |
| + if _, ok := w.(interface{ Unwrap() http.ResponseWriter }); ok { |
| + t.Error("Unwrap exposed") |
| + } |
| + if _, _, err := http.NewResponseController(w).Hijack(); !errors.Is(err, http.ErrNotSupported) { |
| + t.Errorf("controller hijack: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoRedirectPolicy(t *testing.T) { |
| + for _, tc := range []struct { |
| + location []string |
| + ok bool |
| + }{ |
| + {[]string{"/next"}, true}, {[]string{"../next?q=1#part"}, true}, {[]string{"?next=shop"}, true}, {[]string{"/next%20page"}, true}, |
| + {[]string{"https://SHOP.DEMOS.EXAMPLE.COM:443/next"}, true}, {[]string{"//shop.demos.example.com/next"}, true}, |
| + {[]string{"https://example.com/"}, false}, {[]string{"http://shop.demos.example.com/"}, false}, |
| + {[]string{"https://shop.demos.example.com:444/"}, false}, {[]string{"https://user@shop.demos.example.com/"}, false}, |
| + {[]string{"//example.com/"}, false}, {[]string{"/\\example.com/"}, false}, {[]string{"///example.com/"}, false}, |
| + {[]string{" /next"}, false}, {[]string{"/next\r\nLink: x"}, false}, {[]string{"/%0d%0aLocation:evil"}, false}, |
| + {[]string{"https://shop.demos.example.com./"}, false}, {[]string{"/a", "/b"}, false}, {[]string{""}, false}, {nil, false}, {[]string{"//"}, false}, |
| + } { |
| + t.Run(fmt.Sprintf("%q", tc.location), func(t *testing.T) { |
| + r := httptest.NewRequest("GET", "https://shop.demos.example.com/path", nil) |
| + rec := httptest.NewRecorder() |
| + w := new(Edge).beginDemoResponse(rec, r) |
| + w.Header()["Location"] = tc.location |
| + w.Header().Set("Content-Encoding", "gzip") |
| + w.Header().Set("Content-Length", "999") |
| + w.WriteHeader(303) |
| + _, _ = io.WriteString(w, "upstream") |
| + if tc.ok { |
| + if rec.Code != 303 || rec.Header().Get("Location") != tc.location[0] { |
| + t.Errorf("valid redirect changed: %d %v", rec.Code, rec.Header()) |
| + } |
| + } else { |
| + if rec.Code != 502 || rec.Body.String() != demoCopy["DEMO-RESPONSE"]+"\n" { |
| + t.Errorf("unsafe redirect not replaced: %d %q", rec.Code, rec.Body.String()) |
| + } |
| + if rec.Header().Get("Location") != "" || rec.Header().Get("Content-Encoding") != "" { |
| + t.Error("unsafe response headers survived") |
| + } |
| + } |
| + assertDemoPolicy(t, rec.Header()) |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoPolicyForbiddenHeaders(t *testing.T) { |
| + h := make(http.Header) |
| + for _, name := range []string{ |
| + "Content-Security-Policy", "Content-Security-Policy-Report-Only", "Refresh", "Link", |
| + "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Access-Control-Expose-Headers", |
| + "Reporting-Endpoints", "Report-To", "NEL", "Clear-Site-Data", "Service-Worker-Allowed", |
| + "Trailer", "Trailer:Set-Cookie", "Trailer:Content-Security-Policy", "Trailer:Cache-Control", |
| + "Set-Cookie2", "Connection", "Upgrade", |
| + } { |
| + h[name] = []string{"unsafe"} |
| + h[strings.ToLower(name)] = []string{"unsafe"} |
| + } |
| + h["location"] = []string{"/one"} |
| + h["Location"] = []string{"/two"} |
| + if err := sanitizeDemoHeaders(h, "shop.demos.example.com"); err == nil { |
| + t.Error("duplicate case variants of Location accepted") |
| + } |
| + assertDemoPolicy(t, h) |
| + for key, values := range h { |
| + for _, value := range values { |
| + if value == "unsafe" { |
| + t.Errorf("unsafe header survived: %s", key) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestDemoPolicyWireTrailers(t *testing.T) { |
| + server := httptest.NewServer(http.HandlerFunc(func(dst http.ResponseWriter, r *http.Request) { |
| + w := new(Edge).beginDemoResponse(dst, r) |
| + w.Header().Set("Link", "</unsafe>; rel=preload") |
| + w.WriteHeader(103) |
| + w.Header().Set("Trailer", "Set-Cookie, Content-Security-Policy, X-Trailer") |
| + w.Header().Add("Set-Cookie", "sid=one; Domain=example.com; HttpOnly") |
| + _, _ = io.WriteString(w, "shop") |
| + w.(http.Flusher).Flush() |
| + w.Header().Set("Set-Cookie", "late=1; Domain=example.com") |
| + w.Header().Set("Content-Security-Policy", "default-src *") |
| + w.Header().Set("Trailer:Set-Cookie", "late=2; Domain=example.com") |
| + w.Header().Set("Trailer:Content-Security-Policy", "default-src *") |
| + w.Header().Set("X-Trailer", "late") |
| + })) |
| + t.Cleanup(server.Close) |
| + r, err := http.NewRequest("GET", server.URL, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var hints int |
| + r = r.WithContext(httptrace.WithClientTrace(r.Context(), &httptrace.ClientTrace{Got1xxResponse: func(int, textproto.MIMEHeader) error { hints++; return nil }})) |
| + resp, err := server.Client().Do(r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + body, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if hints != 0 || resp.StatusCode != 200 || string(body) != "shop" { |
| + t.Errorf("response: hints=%d status=%d body=%q", hints, resp.StatusCode, body) |
| + } |
| + assertDemoPolicy(t, resp.Header) |
| + if got := resp.Header.Values("Set-Cookie"); !reflect.DeepEqual(got, []string{"sid=one; HttpOnly"}) { |
| + t.Errorf("cookies: %v", got) |
| + } |
| + if len(resp.Trailer) != 0 { |
| + t.Errorf("trailers: %v", resp.Trailer) |
| + } |
| +} |
| + |
| +func TestDemoPolicyWorkerAndUpgrade(t *testing.T) { |
| + for _, dest := range []string{"worker", "serviceworker", "sharedworker"} { |
| + r := httptest.NewRequest("GET", "https://shop.demos.example.com/", nil) |
| + r.Header.Set("Sec-Fetch-Dest", dest) |
| + rec := httptest.NewRecorder() |
| + w := new(Edge).beginDemoResponse(rec, r) |
| + _, _ = io.WriteString(w, "upstream") |
| + if rec.Code != 400 || rec.Body.String() != demoCopy["DEMO-RESPONSE"]+"\n" { |
| + t.Errorf("%s: %d %q", dest, rec.Code, rec.Body.String()) |
| + } |
| + assertDemoPolicy(t, rec.Header()) |
| + } |
| + r := httptest.NewRequest("GET", "https://shop.demos.example.com/", nil) |
| + rec := httptest.NewRecorder() |
| + w := new(Edge).beginDemoResponse(rec, r) |
| + w.WriteHeader(101) |
| + _, _ = io.WriteString(w, "upgraded") |
| + if rec.Code != 502 || rec.Body.String() != demoCopy["DEMO-RESPONSE"]+"\n" { |
| + t.Errorf("upgrade: %d %q", rec.Code, rec.Body.String()) |
| + } |
| + assertDemoPolicy(t, rec.Header()) |
| +} |
| + |
| +func TestDemoPolicyOrdinaryUnchanged(t *testing.T) { |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "text/plain") |
| + w.Header().Set("Content-Security-Policy", "default-src 'self'") |
| + w.Header().Set("Cache-Control", "public, max-age=60") |
| + w.Header().Set("Access-Control-Allow-Origin", "https://example.com") |
| + w.Header().Set("Link", "</shop.css>; rel=stylesheet") |
| + w.Header().Add("Set-Cookie", "sid=one; Domain=example.com") |
| + w.Header().Add("Set-Cookie", "other=two; Secure") |
| + _, _ = io.WriteString(w, "shop") |
| + })) |
| + t.Cleanup(backend.Close) |
| + reg := openReg(t) |
| + t.Cleanup(func() { _ = reg.Close() }) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example.com", App: "shop", Account: "bah", Kind: "instance", Status: "ready", Addr: strings.TrimPrefix(backend.URL, "http://")}); err != nil { |
| + t.Fatal(err) |
| + } |
| + var baseline http.Header |
| + for _, domain := range []string{"", "demos.example.com"} { |
| + t.Setenv("CARLOS_DEMO_DOMAIN", domain) |
| + t.Setenv("CARLOS_DEMO_ACCOUNT", "") |
| + t.Setenv("CARLOS_DEMO_FLEET", "") |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + rec := get(e, "GET", "https://shop.example.com/") |
| + if rec.Code != 200 || rec.Body.String() != "shop" { |
| + t.Fatalf("ordinary response: %d %q", rec.Code, rec.Body.String()) |
| + } |
| + h := rec.Result().Header.Clone() |
| + h.Del("Date") |
| + if baseline == nil { |
| + baseline = h |
| + } else if !reflect.DeepEqual(baseline, h) { |
| + t.Errorf("ordinary headers changed: before=%v after=%v", baseline, h) |
| + } |
| + if got := h.Values("Set-Cookie"); !reflect.DeepEqual(got, []string{"sid=one; Domain=example.com", "other=two; Secure"}) { |
| + t.Errorf("ordinary cookies changed: %v", got) |
| + } |
| + e.fallbackURL = "https://example.com/fallback" |
| + rec = get(e, "GET", "https://unknown.example.com/") |
| + if rec.Code != 302 || rec.Header().Get("Location") != e.fallbackURL || rec.Header().Get("Content-Security-Policy") != "" { |
| + t.Errorf("ordinary fallback changed: %d %v", rec.Code, rec.Header()) |
| + } |
| + } |
| +} |