carlos / platform Public

feat: enforce demo response policy and host-only cookies

Keep demo serving closed until durable counters and serving authorization are wired.

Enforce the fixed response policy, host-only cookies and safe redirects through a private response writer. Refuse reserved and invalid marked identities before fallback, cache or proxy exits, with regression coverage for ordinary hosts.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 849f5b8708c60a8a3edeb83cd62cfce6bdee5bec parent 14dd4de
5 files changed, +793 −3
  • internal/edge/demo.go +84 −0
  • internal/edge/demo_copy.go +13 −0
  • internal/edge/demo_response.go +253 −0
  • internal/edge/demo_response_test.go +418 −0
  • internal/edge/edge.go +25 −3

Intent

Human

<task-notification> <task-id>bjd0avhfe</task-id> <tool-use-id>toolu_01Lktpm3hpcpkh8yKXwVWdVf</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/bjd0avhfe.output</output-file> <status>completed</status> <summary>Background command "Wait for Luna copy pass to finish" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/edge/demo.go b/internal/edge/demo.go
index 0a502e726..c5ba078c4 100644
--- a/internal/edge/demo.go
+++ b/internal/edge/demo.go
@@ -1,7 +1,9 @@
package edge
import (
+ "net/http"
"os"
+ "strconv"
"strings"
"time"
@@ -10,6 +12,88 @@ import (
"github.com/carlosframework/platform/internal/registry"
)
+// demoAuthority returns a classification name even for malformed authorities.
+// Only a valid authority can select a route. Ordinary requests keep their
+// existing host handling; this normalization is solely for demo refusal.
+func demoAuthority(authority string) (host string, valid bool) {
+ name := strings.ToLower(strings.TrimSpace(authority))
+ if i := strings.LastIndexByte(name, '@'); i >= 0 {
+ name = name[i+1:]
+ }
+ if i := strings.IndexAny(name, ":/\\?#"); i >= 0 {
+ name = name[:i]
+ }
+ host = strings.TrimRight(name, ".")
+ if !demo.ValidDomain(host) {
+ return host, false
+ }
+ raw := strings.ToLower(authority)
+ if raw == host {
+ return host, true
+ }
+ if port, ok := strings.CutPrefix(raw, host+":"); ok && port != "" {
+ for i := range len(port) {
+ if port[i] < '0' || port[i] > '9' {
+ return host, false
+ }
+ }
+ n, err := strconv.Atoi(port)
+ return host, err == nil && n > 0 && n <= 65535
+ }
+ return host, false
+}
+
+// demoRefusalNames retains marked identities even when reload drops their
+// routes. Otherwise a malformed descriptor outside the reserved domain could
+// reach an ordinary fallback, or an alias could reach a parent's catch-all.
+func demoRefusalNames(m map[string]upstream, routes []registry.Route, aliases []registry.RouteAlias) map[string]bool {
+ names := make(map[string]bool)
+ for _, route := range routes {
+ if route.IsDemo() {
+ host, _ := demoAuthority(route.Host)
+ names[host] = true
+ }
+ }
+ for host, up := range m {
+ if up.route.IsDemo() {
+ name, _ := demoAuthority(host)
+ names[name] = true
+ }
+ }
+ for _, alias := range aliases {
+ source, _ := demoAuthority(alias.Host)
+ if up, exists := m[alias.Alias]; names[source] && (!exists || up.route.IsDemo()) {
+ name, _ := demoAuthority(alias.Alias)
+ names[name] = true
+ }
+ }
+ return names
+}
+
+// refuseDemoRequest runs before any response exit, including HTTP fallback.
+// Task 3 adds durable traffic admission and Task 4 the serving gate. Until
+// both are wired, even a valid live demo must stop here without dispatch.
+func (e *Edge) refuseDemoRequest(w http.ResponseWriter, r *http.Request) bool {
+ host, valid := demoAuthority(r.Host)
+ marked := false
+ if names := e.demoNames.Load(); names != nil {
+ marked = (*names)[host]
+ }
+ up, ok := e.lookupUpstreamPath(host, r.URL.Path)
+ if !e.demoReserved(host) && !marked && !(ok && up.route.IsDemo()) {
+ return false
+ }
+ w = e.beginDemoResponse(w, r)
+ if !valid {
+ serveDemoPlain(w, r, http.StatusBadRequest, "DEMO-RESPONSE")
+ } else if !ok || !up.route.IsDemo() || !e.demoRouteOK(host, up.route) || up.alias || up.platformAlias {
+ serveDemoPlain(w, r, http.StatusNotFound, "DEMO-GONE")
+ } else {
+ serveDemoPlain(w, r, http.StatusServiceUnavailable, "DEMO-UNAVAILABLE")
+ }
+ return true
+}
+
func demoEdgeConfig() demo.Config {
return demo.Config{Account: os.Getenv("CARLOS_DEMO_ACCOUNT"), Fleet: os.Getenv("CARLOS_DEMO_FLEET"), Domain: os.Getenv("CARLOS_DEMO_DOMAIN")}
}
diff --git a/internal/edge/demo_copy.go b/internal/edge/demo_copy.go
new file mode 100644
index 000000000..ff7f3bed0
--- /dev/null
+++ b/internal/edge/demo_copy.go
@@ -0,0 +1,13 @@
+package edge
+
+// Draft plan-2 copy, keyed by the controller's copy-table IDs. Task 6 owns
+// the copy review before this branch ships.
+var demoCopy = map[string]string{
+ "DEMO-BANNER": "This app was built by an AI. It is temporary. Do not enter real passwords or sensitive information.",
+ "DEMO-REPORT-LINK": "Report abuse",
+ "DEMO-LIMIT-PRECLAIM": "This demo has hit its limit. Claiming will let you keep it running when it becomes available.",
+ "DEMO-STOPPED": "Demos are temporarily unavailable.",
+ "DEMO-GONE": "This demo is no longer available.",
+ "DEMO-UNAVAILABLE": "This demo cannot be checked right now. Try again shortly.",
+ "DEMO-RESPONSE": "This demo returned a response that cannot be shown.",
+}
diff --git a/internal/edge/demo_response.go b/internal/edge/demo_response.go
new file mode 100644
index 000000000..8dd9e5d6d
--- /dev/null
+++ b/internal/edge/demo_response.go
@@ -0,0 +1,253 @@
+package edge
+
+import (
+ "errors"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+
+ "golang.org/x/net/http/httpguts"
+)
+
+func demoCSP() string {
+ return "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'"
+}
+
+// rewriteDemoCookies keeps each field separate, including Expires commas.
+// Validate before forwarding raw attributes: net/http's parser alone accepts
+// malformed attributes in Unparsed and permits comma-coalesced cookie values.
+func rewriteDemoCookies(h http.Header) error {
+ var cookies []string
+ for key, values := range h {
+ if strings.EqualFold(key, "Set-Cookie") {
+ cookies = append(cookies, values...)
+ delete(h, key)
+ }
+ }
+ for _, raw := range cookies {
+ if !demoCookieASCII(raw) {
+ continue
+ }
+ parts := strings.Split(raw, ";")
+ kept := parts[:1]
+ valid := true
+ for _, part := range parts[1:] {
+ name, _, _ := strings.Cut(strings.TrimSpace(part), "=")
+ name = strings.TrimSpace(name)
+ if strings.EqualFold(name, "Domain") {
+ continue
+ }
+ if strings.TrimSpace(part) != "" && !httpguts.ValidHeaderFieldName(name) {
+ valid = false
+ break
+ }
+ kept = append(kept, part)
+ }
+ if !valid {
+ continue
+ }
+ line := strings.Join(kept, ";")
+ cookie, err := http.ParseSetCookie(line)
+ if err != nil || cookie.Valid() != nil || strings.ContainsAny(cookie.Value, ", ") {
+ continue
+ }
+ for _, attr := range cookie.Unparsed {
+ name, _, _ := strings.Cut(attr, "=")
+ switch strings.ToLower(strings.TrimSpace(name)) {
+ case "expires", "max-age", "path", "secure", "httponly", "samesite", "partitioned":
+ valid = false
+ }
+ }
+ if valid {
+ h.Add("Set-Cookie", line)
+ }
+ }
+ return nil
+}
+
+func demoCookieASCII(s string) bool {
+ for i := range len(s) {
+ if s[i] < 0x20 || s[i] >= 0x7f {
+ return false
+ }
+ }
+ return true
+}
+
+// sanitizeDemoHeaders also handles noncanonical map keys. Neither a policy
+// override nor a second Location can hide behind a different spelling.
+func sanitizeDemoHeaders(h http.Header, host string) error {
+ var locations []string
+ for key, values := range h {
+ lower := strings.ToLower(key)
+ if lower == "location" {
+ locations = append(locations, values...)
+ delete(h, key)
+ continue
+ }
+ if strings.HasPrefix(lower, "access-control-") || strings.HasPrefix(lower, "trailer:") {
+ delete(h, key)
+ continue
+ }
+ switch lower {
+ case "content-security-policy", "content-security-policy-report-only",
+ "x-frame-options", "x-content-type-options", "referrer-policy", "cache-control",
+ "x-dns-prefetch-control", "permissions-policy", "refresh", "link",
+ "reporting-endpoints", "report-to", "nel", "clear-site-data", "service-worker-allowed",
+ "trailer", "connection", "upgrade", "proxy-connection", "keep-alive", "transfer-encoding", "te",
+ "set-cookie2":
+ delete(h, key)
+ }
+ }
+ h.Set("Content-Security-Policy", demoCSP())
+ h.Set("X-Frame-Options", "DENY")
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Referrer-Policy", "no-referrer")
+ h.Set("Cache-Control", "no-store")
+ h.Set("X-DNS-Prefetch-Control", "off")
+ h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), fullscreen=(), document-domain=()")
+ if err := rewriteDemoCookies(h); err != nil {
+ return err
+ }
+ if len(locations) != 0 {
+ if len(locations) != 1 || !demoLocationOK(locations[0], host) {
+ return errors.New("DEMO-RESPONSE")
+ }
+ h.Set("Location", locations[0])
+ }
+ return nil
+}
+
+func demoLocationOK(location, host string) bool {
+ // Browsers treat backslashes as slashes in special URLs, unlike net/url.
+ // Reject whitespace, controls and encoded controls too, before resolving.
+ if location == "" || strings.HasPrefix(location, "///") || strings.Contains(location, "\\") {
+ return false
+ }
+ for i := range len(location) {
+ if location[i] <= 0x20 || location[i] == 0x7f {
+ return false
+ }
+ }
+ decoded, err := url.PathUnescape(location)
+ if err != nil {
+ return false
+ }
+ for i := range len(decoded) {
+ if decoded[i] < 0x20 || decoded[i] == 0x7f || decoded[i] == '\\' {
+ return false
+ }
+ }
+ ref, err := url.Parse(location)
+ if err != nil || ref.Opaque != "" || ref.User != nil || ((ref.Scheme != "" || strings.HasPrefix(location, "//")) && ref.Host == "") {
+ return false
+ }
+ base := &url.URL{Scheme: "https", Host: host, Path: "/"}
+ target := base.ResolveReference(ref)
+ if target.Scheme != "https" || target.User != nil {
+ return false
+ }
+ // HTTPS's default port is the only spelling difference allowed besides
+ // DNS case. A trailing dot is a different browser origin.
+ origin := func(authority string) string {
+ return strings.TrimSuffix(strings.ToLower(authority), ":443")
+ }
+ return origin(target.Host) == origin(host)
+}
+
+// demoResponseWriter never embeds or unwraps its destination. Headers are
+// copied once, at the final status; later app mutations cannot become trailers.
+// Flush is supported for streams, but neither Hijack nor full-duplex access is.
+type demoResponseWriter struct {
+ dst http.ResponseWriter
+ header http.Header
+ request *http.Request
+ status int
+ refused bool
+}
+
+func (e *Edge) beginDemoResponse(w http.ResponseWriter, r *http.Request) http.ResponseWriter {
+ if _, ok := w.(*demoResponseWriter); ok {
+ return w
+ }
+ return &demoResponseWriter{dst: w, header: w.Header().Clone(), request: r}
+}
+
+func (w *demoResponseWriter) Header() http.Header { return w.header }
+
+func (w *demoResponseWriter) WriteHeader(status int) {
+ if w.status != 0 || status >= 100 && status < 200 && status != http.StatusSwitchingProtocols {
+ return
+ }
+ h := w.header.Clone()
+ err := sanitizeDemoHeaders(h, w.request.Host)
+ missingLocation := (status == 301 || status == 302 || status == 303 || status == 307 || status == 308) && h.Get("Location") == ""
+ worker := false
+ for _, value := range w.request.Header.Values("Sec-Fetch-Dest") {
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case "worker", "serviceworker", "sharedworker":
+ worker = true
+ }
+ }
+ worker = worker && status < 400
+ if status == http.StatusSwitchingProtocols || err != nil || missingLocation || worker {
+ w.refused = true
+ status = http.StatusBadGateway
+ if worker {
+ status = http.StatusBadRequest
+ }
+ h = make(http.Header)
+ demoPlainHeaders(h, "DEMO-RESPONSE")
+ _ = sanitizeDemoHeaders(h, w.request.Host)
+ }
+ w.status = status
+ dst := w.dst.Header()
+ clear(dst)
+ for key, values := range h {
+ dst[key] = append([]string(nil), values...)
+ }
+ w.dst.WriteHeader(status)
+ if w.refused && w.request.Method != http.MethodHead {
+ _, _ = io.WriteString(w.dst, demoCopy["DEMO-RESPONSE"]+"\n")
+ }
+}
+
+func (w *demoResponseWriter) Write(p []byte) (int, error) {
+ if w.status == 0 {
+ w.WriteHeader(http.StatusOK)
+ }
+ if w.refused || w.request.Method == http.MethodHead || w.status == http.StatusNoContent || w.status == http.StatusNotModified {
+ return len(p), nil
+ }
+ return w.dst.Write(p)
+}
+
+func (w *demoResponseWriter) FlushError() error {
+ if w.status == 0 {
+ w.WriteHeader(http.StatusOK)
+ }
+ return http.NewResponseController(w.dst).Flush()
+}
+
+func (w *demoResponseWriter) Flush() { _ = w.FlushError() }
+
+func demoPlainHeaders(h http.Header, copyID string) {
+ clear(h)
+ h.Set("Content-Type", "text/plain; charset=utf-8")
+ h.Set("Content-Length", strconv.Itoa(len(demoCopy[copyID])+1))
+}
+
+func serveDemoPlain(w http.ResponseWriter, r *http.Request, status int, copyID string) {
+ if _, ok := demoCopy[copyID]; !ok {
+ copyID = "DEMO-UNAVAILABLE"
+ status = http.StatusServiceUnavailable
+ }
+ w = new(Edge).beginDemoResponse(w, r)
+ demoPlainHeaders(w.Header(), copyID)
+ w.WriteHeader(status)
+ if r.Method != http.MethodHead {
+ _, _ = io.WriteString(w, demoCopy[copyID]+"\n")
+ }
+}
diff --git a/internal/edge/demo_response_test.go b/internal/edge/demo_response_test.go
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())
+ }
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index e8e17c6a0..6ebc4c915 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -121,9 +121,10 @@ type Edge struct {
replicaMu sync.Mutex
replicaProbes *replicaProber
- demo demo.Config
- devbox bool // installs front-door proxy hooks on every reload
- reg *registry.Registry
+ demo demo.Config
+ demoNames atomic.Pointer[map[string]bool] // includes marked routes refused by reload
+ devbox bool // installs front-door proxy hooks on every reload
+ reg *registry.Registry
// hold is this Edge's local-upstream hold settings (localhold.go), set
// before the startup Reload and read by it.
hold localHold
@@ -1347,6 +1348,7 @@ func (e *Edge) Reload() error {
}
}
e.foldRegional(m, routes, regionalRows)
+ demoNames := demoRefusalNames(m, routes, aliases)
e.filterDemoRoutes(m, routes)
// Refusals hold through every fold above: last, so nothing re-adds them.
refusedHosts(m, verdict.Refused)
@@ -1389,6 +1391,7 @@ func (e *Edge) Reload() error {
// The one publication of the map (guarded by TestReloadIsTheOnlyPublisher),
// then at once the sweep: every open upgrade is judged against the map
// just published, under reloadMu, so no older map can replace it first.
+ e.demoNames.Store(&demoNames)
e.upstreams.Store(&m)
if h := e.hooks; h != nil && h.afterPublish != nil {
_ = h.afterPublish(id)
@@ -1888,6 +1891,9 @@ func firstSegmentClean(p string) string {
}
func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ if e.refuseDemoRequest(w, r) {
+ return
+ }
host := r.Host
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
@@ -1994,6 +2000,16 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
replicaProbe := replicaProbeAuthenticated(r) && !isDoor && !hopPresent
r.Header.Del(tunnelclient.ReplicaProbeHeader)
up, ok := e.lookupUpstreamPath(host, r.URL.Path)
+ // Recheck the selected row: reload may have published since entry, and
+ // no marked route may enter ordinary dispatch even outside the demo zone.
+ if ok && up.route.IsDemo() {
+ status, copyID := http.StatusNotFound, "DEMO-GONE"
+ if e.demoRouteOK(host, up.route) && !up.alias && !up.platformAlias {
+ status, copyID = http.StatusServiceUnavailable, "DEMO-UNAVAILABLE"
+ }
+ serveDemoPlain(w, r, status, copyID)
+ return
+ }
if ok && e.admissionRefuses(w, r, up.route) {
return
}
@@ -3220,6 +3236,9 @@ func (r *recordingResponseWriter) Flush() {
// that this edge has not heard about yet, and a dead end for it strands the
// visitor where a retry would have worked.
func (e *Edge) unknownHost(w http.ResponseWriter, r *http.Request) {
+ if e.refuseDemoRequest(w, r) {
+ return
+ }
host := r.Host
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
@@ -3258,6 +3277,9 @@ func (e *Edge) unknownHost(w http.ResponseWriter, r *http.Request) {
// handler, so a challenge request never reaches lookupUpstream at all.
func (e *Edge) httpFallbackHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if e.refuseDemoRequest(w, r) {
+ return
+ }
host := r.Host
if h, _, err := net.SplitHostPort(host); err == nil {
host = h