carlos / platform Public

feat: insert warnings into demo HTML responses

Add bounded-prefix HTML insertion, reserved warning assets and streaming representation handling for the resident demo pipeline. Preserve app readiness status and version, and apply the approved edge copy.

Cover transformations and the unchanged readiness probe with targeted tests. Exercise the pinned local Rastrillo fixture in Chromium through CDP; record Firefox and Safari evidence as outstanding. Production demo serving remains closed for Tasks 3 and 4.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 7e43747ca78350be5ce6ac36482b84ed37169ad8 parent 6f4bc28
11 files changed, +1,374 −5
  • internal/console/demo_publish_test.go +50 −0
  • internal/edge/demo_assets/banner.css +31 −0
  • internal/edge/demo_banner.go +286 −0
  • internal/edge/demo_banner_browser_test.go +330 −0
  • internal/edge/demo_banner_test.go +479 −0
  • internal/edge/demo_copy.go +4 −5
  • internal/edge/testdata/demo-protections/app.js +19 −0
  • internal/edge/testdata/demo-protections/go.mod +34 −0
  • internal/edge/testdata/demo-protections/go.sum +56 −0
  • internal/edge/testdata/demo-protections/main.go +83 −0
  • internal/edge/testdata/demo-protections/style.css +2 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>b7iy5abej</task-id> <tool-use-id>toolu_01Q2AeJC4MSikdsoqswXozBJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/b7iy5abej.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 1 fix run" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a36cead740f2f91fd</task-id> <tool-use-id>toolu_01Y6xm7s31CdvRboAtygAgxz</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6e566fe9-9aca-47cb-9753-64e881b0d285/tasks/a36cead740f2f91fd.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 1 fix (Opus)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>All four findings are fixed, and the fix diff (6f4bc286 over b89b07dd) adds no new P1 or P2. `go test ./internal/edge -run 'TestDemo' -count=1` passes on 6f4bc286. - **P2-1: ADDRESSED.** `demoAuthority` now splits the host from the port the same way the router does, before it lowercases and trims (`internal/edge/demo.go:21-24`). Bracketed names that fail that split are still stripped and classified (`demo.go:30-33`). Every bracketed demo name is treated as an invalid authority and gets 400 with the policy. The new test rows at `demo_response_test.go:108-111` cover each bracketed variant through all three handlers, for both GET and HEAD. - **P3-1: ADDRESSED.** `beginDemoResponse` now cleans the destination's headers at the start and keeps the original copy for the final check (`demo_response.go:176-180`). A handler that never writes now gets the policy on Go's implicit 200, and `TestDemoPolicyNoWrite` (`demo_response_test.go:222`) proves it over a real HTTP connection. - **P3-2: ADDRESSED.** The new `bracketed-marked-post-lookup` subtest (`demo_response_test.go:135`) publishes the marked route after the entry check has passed. The 400 it then gets can only come from the second check after route lookup (`edge.go:2005-2013`). - **P3-4: ADDRESSED.** A malformed Host now gets DEMO-GONE with 400, both at entry (`demo.go:96`) and in the post-lookup check (`edge.go:2007-2008`). The tests check the body text. **New P1/P2 in the fix diff:** none. Two observations, neither blocking: - A demo handler that never writes still answers 200 with an empty body, now with the policy. Task 3 may want that to be a 502. - P3-3 and P3-5 are still open, as the implementer's report says. The re-review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-2/.superpowers/sdd/2026-11-04-agent-start-demo-2-edge-protections/task-1-rereview.md`.</result> <usage><subagent_tokens>62208</subagent_tokens><tool_uses>7</tool_uses><duration_ms>82573</duration_ms></usage> </task-notification>

Attributed to this commit: 10.2 g CO₂e (1,134,422 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-2, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/demo_publish_test.go b/internal/console/demo_publish_test.go
index 02d3cc7fc..fce57737b 100644
--- a/internal/console/demo_publish_test.go
+++ b/internal/console/demo_publish_test.go
@@ -6,6 +6,7 @@ import (
"database/sql"
"encoding/hex"
"errors"
+ "io"
"net/http"
"net/http/httptest"
"os"
@@ -422,3 +423,52 @@ func TestDemoPublishResultStartsDeadline(t *testing.T) {
t.Fatalf("ready result has no bounded starting deadline: %v", remaining)
}
}
+
+func TestDemoProbeStillChecksApp(t *testing.T) {
+ s, d, _, _ := demoPublishFixture(t)
+ for _, tt := range []struct {
+ name, version, body string
+ status int
+ want bool
+ }{
+ {"app", "v1", "<body>shop</body>", 200, true},
+ {"empty", "v1", "", 200, true},
+ {"no-content", "v1", "", 204, true},
+ {"wrong-version", "v0", "<body>shop</body>", 200, false},
+ {"redirect", "v1", "<body>shop</body>", 302, false},
+ {"app-failure", "v1", "<body>shop</body>", 500, false},
+ {"reserved-stylesheet", "", "body{}", 200, false},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ calls := 0
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if r.Method != "GET" || r.URL.Path != "/" || r.Host != d.Host || r.Header.Get("Cache-Control") != "no-cache" {
+ t.Error("probe changed")
+ }
+ w.Header().Set("X-Carlos-Version", tt.version)
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ if tt.status == 302 {
+ w.Header().Set("Location", "/next")
+ }
+ w.WriteHeader(tt.status)
+ if tt.status != 204 {
+ _, _ = io.WriteString(w, tt.body)
+ }
+ }))
+ defer server.Close()
+ base := server.Client().Transport
+ s.demoTransport = demoReadyTransport(func(r *http.Request) (*http.Response, error) {
+ // Change only the test dial target. The production probe and HTTP Host
+ // still use the canonical demo identity and never follow a redirect.
+ q := r.Clone(r.Context())
+ q.URL.Host = strings.TrimPrefix(server.URL, "https://")
+ return base.RoundTrip(q)
+ })
+ ready, err := s.demoReady(t.Context(), d, "v1")
+ if err != nil || ready != tt.want || calls != 1 {
+ t.Fatalf("ready=%v err=%v requests=%d", ready, err, calls)
+ }
+ })
+ }
+}
diff --git a/internal/edge/demo_assets/banner.css b/internal/edge/demo_assets/banner.css
new file mode 100644
index 000000000..9567a8104
--- /dev/null
+++ b/internal/edge/demo_assets/banner.css
@@ -0,0 +1,31 @@
+#carlos-demo-warning {
+ all: initial;
+ box-sizing: border-box;
+ position: fixed;
+ inset: 0 0 auto 0;
+ z-index: 2147483647;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem 1rem;
+ align-items: center;
+ padding: 0.75rem 1rem;
+ color: #171717;
+ background: #fff4cc;
+ border-bottom: 2px solid #705400;
+ font: 400 16px/1.5 system-ui, sans-serif;
+ overflow-wrap: anywhere;
+ max-height: 100vh;
+ overflow-y: auto;
+}
+#carlos-demo-warning span { flex: 1 1 18rem; }
+#carlos-demo-warning a {
+ color: #172f70;
+ font: inherit;
+ font-weight: 700;
+ text-decoration: underline;
+ padding: 0.25rem 0;
+}
+#carlos-demo-warning a:focus-visible { outline: 3px solid #172f70; outline-offset: 2px; }
+body { padding-top: 7rem; }
+@media (max-width: 480px) { body { padding-top: 16rem; } }
+@media (max-width: 240px) { body { padding-top: 20rem; } }
diff --git a/internal/edge/demo_banner.go b/internal/edge/demo_banner.go
new file mode 100644
index 000000000..6687ef427
--- /dev/null
+++ b/internal/edge/demo_banner.go
@@ -0,0 +1,286 @@
+package edge
+
+import (
+ "bytes"
+ "compress/gzip"
+ _ "embed"
+ "errors"
+ stdhtml "html"
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+
+ "golang.org/x/net/html"
+)
+
+const demoBannerPrefixLimit = 64 << 10
+const demoAssetPrefix = "/.carlos/demo/"
+
+//go:embed demo_assets/banner.css
+var demoBannerCSS string
+
+// reportOrigin comes from edge configuration, never the request or app.
+func demoBannerMarkup(host, reportOrigin string) (string, error) {
+ origin, err := url.Parse(reportOrigin)
+ if err != nil || origin.Scheme != "https" || origin.Hostname() == "" || origin.User != nil || origin.Opaque != "" || origin.RawQuery != "" || origin.ForceQuery || origin.Fragment != "" || (origin.Path != "" && origin.Path != "/") || strings.ContainsAny(reportOrigin, "\\\r\n\t ") {
+ return "", errors.New("DEMO-RESPONSE")
+ }
+ origin.Path = "/demo/report"
+ origin.RawPath = ""
+ origin.RawQuery = url.Values{"host": {host}}.Encode()
+ return `<link rel="stylesheet" href="/.carlos/demo/banner.css"><aside id="carlos-demo-warning" role="note"><span>` + stdhtml.EscapeString(demoCopy["DEMO-BANNER"]) + `</span> <a href="` + stdhtml.EscapeString(origin.String()) + `" target="_blank" rel="noopener noreferrer">` + stdhtml.EscapeString(demoCopy["DEMO-REPORT-LINK"]) + `</a></aside>`, nil
+}
+
+// demoBannerReader buffers only the prefix. Tokenization finds real body tags
+// without reserializing app markup or mistaking script/comment text for tags.
+func demoBannerReader(src io.Reader, host, reportOrigin string) (io.Reader, error) {
+ markup, err := demoBannerMarkup(host, reportOrigin)
+ if err != nil {
+ return nil, err
+ }
+ var prefix bytes.Buffer
+ z := html.NewTokenizer(io.TeeReader(io.LimitReader(src, demoBannerPrefixLimit), &prefix))
+ offset, insert, doctype := 0, -1, 0
+ leading := true
+ for {
+ kind := z.Next()
+ raw := z.Raw()
+ offset += len(raw)
+ if kind == html.ErrorToken {
+ if err := z.Err(); err != io.EOF {
+ return nil, err
+ }
+ break
+ }
+ if kind == html.DoctypeToken && leading {
+ doctype = offset
+ }
+ if kind != html.CommentToken && (kind != html.TextToken || len(bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xef\xbb\xbf")))) != 0) {
+ leading = false
+ }
+ if kind == html.StartTagToken || kind == html.SelfClosingTagToken {
+ name, _ := z.TagName()
+ if bytes.EqualFold(name, []byte("body")) {
+ insert = offset
+ break
+ }
+ }
+ }
+ if insert < 0 {
+ insert = doctype
+ }
+ b := prefix.Bytes()
+ return io.MultiReader(bytes.NewReader(b[:insert]), strings.NewReader(markup), bytes.NewReader(b[insert:]), src), nil
+}
+
+func injectDemoBanner(dst io.Writer, src io.Reader, host, reportOrigin string) error {
+ r, err := demoBannerReader(src, host, reportOrigin)
+ if err != nil {
+ return err
+ }
+ _, err = io.Copy(dst, r)
+ return err
+}
+
+// serveDemoAsset is called only after demo identity and serving admission.
+// Task 3 places it before app dispatch on the resident box. These fixed bytes
+// are platform overhead and never advertise an app version.
+func (e *Edge) serveDemoAsset(w http.ResponseWriter, r *http.Request) bool {
+ if r.URL.Path != strings.TrimSuffix(demoAssetPrefix, "/") && !strings.HasPrefix(r.URL.Path, demoAssetPrefix) {
+ return false
+ }
+ w = e.beginDemoResponse(w, r)
+ clear(w.Header())
+ if r.URL.Path != demoAssetPrefix+"banner.css" {
+ serveDemoPlain(w, r, 404, "DEMO-GONE")
+ return true
+ }
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ serveDemoPlain(w, r, 405, "DEMO-RESPONSE")
+ return true
+ }
+ w.Header().Set("Content-Type", "text/css; charset=utf-8")
+ w.Header().Set("Content-Length", strconv.Itoa(len(demoBannerCSS)))
+ w.WriteHeader(http.StatusOK)
+ if r.Method != http.MethodHead {
+ _, _ = io.WriteString(w, demoBannerCSS)
+ }
+ return true
+}
+
+// Platform pages use the markup directly, outside the app transport. They
+// must not pass through the app injector a second time.
+func serveDemoHTML(w http.ResponseWriter, r *http.Request, status int, copyID, host, reportOrigin string) {
+ markup, err := demoBannerMarkup(host, reportOrigin)
+ message, ok := demoCopy[copyID]
+ if err != nil || !ok {
+ serveDemoPlain(w, r, 503, "DEMO-UNAVAILABLE")
+ return
+ }
+ w = new(Edge).beginDemoResponse(w, r)
+ clear(w.Header())
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.WriteHeader(status)
+ if r.Method != http.MethodHead && status != 204 && status != 205 && status != 304 {
+ _, _ = io.WriteString(w, `<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body>`+markup+`<main><p>`+stdhtml.EscapeString(message)+`</p></main></body></html>`)
+ }
+}
+
+// demoBannerTransport belongs on the resident app proxy, before response
+// policy, final compression and byte accounting. It produces identity HTML;
+// the final compressor negotiates the browser's encoding. It grants no
+// serving authority and is not installed until Tasks 3/4 supply admission.
+type demoBannerTransport struct {
+ base http.RoundTripper
+ host, reportOrigin string
+}
+
+func (t demoBannerTransport) RoundTrip(r *http.Request) (*http.Response, error) {
+ req := r.Clone(r.Context())
+ req.Header.Set("Accept-Encoding", "identity")
+ resp, err := t.base.RoundTrip(req)
+ if err != nil {
+ return nil, err
+ }
+ if r.Method == http.MethodHead || resp.StatusCode == 204 || resp.StatusCode == 205 {
+ return resp, nil
+ }
+ mt, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
+ // A 304 commonly omits Content-Type. Fetch its full representation so an
+ // earlier, unprotected HTML document cannot satisfy this navigation.
+ partial := (mt == "text/html" && (resp.StatusCode == 206 || resp.Header.Get("Content-Range") != "" || resp.StatusCode == 304)) || (mt == "" && (resp.StatusCode == 304 || resp.StatusCode == 206 || resp.Header.Get("Content-Range") != ""))
+ if partial {
+ if r.Method != http.MethodGet {
+ return demoBannerRefusal(resp), nil
+ }
+ _ = resp.Body.Close()
+ req = req.Clone(req.Context())
+ if r.Body != nil && r.Body != http.NoBody {
+ if r.GetBody == nil {
+ return demoBannerRefusal(resp), nil
+ }
+ req.Body, err = r.GetBody()
+ if err != nil {
+ return demoBannerRefusal(resp), nil
+ }
+ }
+ for key := range req.Header {
+ switch strings.ToLower(key) {
+ case "range", "if-range", "if-match", "if-none-match", "if-modified-since", "if-unmodified-since":
+ delete(req.Header, key)
+ }
+ }
+ resp, err = t.base.RoundTrip(req)
+ if err != nil {
+ return nil, err
+ }
+ if resp.StatusCode == 206 || resp.StatusCode == 304 || resp.Header.Get("Content-Range") != "" || strings.HasPrefix(strings.ToLower(resp.Header.Get("Content-Type")), "multipart/byteranges") {
+ return demoBannerRefusal(resp), nil
+ }
+ }
+ if err := transformDemoHTMLResponse(resp, t.host, t.reportOrigin); err != nil {
+ return demoBannerRefusal(resp), nil
+ }
+ return resp, nil
+}
+
+func demoBannerRefusal(resp *http.Response) *http.Response {
+ _ = resp.Body.Close()
+ resp.StatusCode = http.StatusBadGateway
+ resp.Status = "502 Bad Gateway"
+ resp.Header = make(http.Header)
+ demoPlainHeaders(resp.Header, "DEMO-RESPONSE")
+ host := ""
+ if resp.Request != nil {
+ host = resp.Request.Host
+ }
+ _ = sanitizeDemoHeaders(resp.Header, host)
+ resp.Trailer = nil
+ body := demoCopy["DEMO-RESPONSE"] + "\n"
+ resp.Body = io.NopCloser(strings.NewReader(body))
+ resp.ContentLength = int64(len(body))
+ resp.TransferEncoding = nil
+ return resp
+}
+
+func transformDemoHTMLResponse(resp *http.Response, host, reportOrigin string) error {
+ if resp.StatusCode == 204 || resp.StatusCode == 205 || resp.StatusCode == 304 {
+ return nil
+ }
+ types := resp.Header.Values("Content-Type")
+ if len(types) > 1 {
+ return errors.New("DEMO-RESPONSE")
+ }
+ ct := resp.Header.Get("Content-Type")
+ if ct == "" {
+ // With no media type browsers can sniff an HTML document. Pin the
+ // detected type and transform it by the same rules as declared HTML.
+ encoding := strings.TrimSpace(resp.Header.Get("Content-Encoding"))
+ if encoding != "" && !strings.EqualFold(encoding, "identity") {
+ return errors.New("DEMO-RESPONSE")
+ }
+ prefix, readErr := io.ReadAll(io.LimitReader(resp.Body, 512))
+ if readErr != nil {
+ return readErr
+ }
+ ct = http.DetectContentType(prefix)
+ resp.Header.Set("Content-Type", ct)
+ resp.Body = &demoHTMLBody{Reader: io.MultiReader(bytes.NewReader(prefix), resp.Body), Closer: resp.Body}
+ }
+
+ mt, params, err := mime.ParseMediaType(ct)
+ if err != nil && ct != "" {
+ return errors.New("DEMO-RESPONSE")
+ }
+ switch mt {
+ case "application/xhtml+xml", "application/xml", "text/xml", "image/svg+xml":
+ return errors.New("DEMO-RESPONSE")
+ }
+ if mt != "text/html" {
+ return nil
+ }
+ if charset := params["charset"]; charset != "" && !strings.EqualFold(charset, "utf-8") {
+ return errors.New("DEMO-RESPONSE")
+ }
+ var reader io.Reader = resp.Body
+ encoding := strings.ToLower(strings.TrimSpace(strings.Join(resp.Header.Values("Content-Encoding"), ",")))
+ switch encoding {
+ case "", "identity":
+ case "gzip":
+ decoded, err := gzip.NewReader(resp.Body)
+ if err != nil {
+ return err
+ }
+ reader = decoded
+ default:
+ return errors.New("DEMO-RESPONSE")
+ }
+ reader, err = demoBannerReader(reader, host, reportOrigin)
+ if err != nil {
+ return err
+ }
+ resp.Body = &demoHTMLBody{Reader: reader, Closer: resp.Body}
+ for key := range resp.Header {
+ switch strings.ToLower(key) {
+ case "content-encoding", "content-length", "etag", "last-modified", "digest", "content-md5", "content-digest", "repr-digest", "accept-ranges", "content-range", "trailer":
+ delete(resp.Header, key)
+ default:
+ if strings.HasPrefix(strings.ToLower(key), "trailer:") {
+ delete(resp.Header, key)
+ }
+ }
+ }
+ resp.Header.Set("Content-Type", "text/html; charset=utf-8")
+ resp.ContentLength = -1
+ resp.Trailer = nil
+ resp.TransferEncoding = nil
+ return nil
+}
+
+type demoHTMLBody struct {
+ io.Reader
+ io.Closer
+}
diff --git a/internal/edge/demo_banner_browser_test.go b/internal/edge/demo_banner_browser_test.go
new file mode 100644
index 000000000..9c6c0e244
--- /dev/null
+++ b/internal/edge/demo_banner_browser_test.go
@@ -0,0 +1,330 @@
+package edge
+
+import (
+ "context"
+ "crypto/sha256"
+ "crypto/x509"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "golang.org/x/net/websocket"
+)
+
+// This is test wiring, not a production serving bypass. Task 3 installs the
+// transport only after resident admission and puts accounting below gzip.
+func demoBannerTestProxy(t *testing.T, target *url.URL, transport http.RoundTripper, host string) http.Handler {
+ t.Helper()
+ proxy := httputil.NewSingleHostReverseProxy(target)
+ proxy.Transport = demoBannerTransport{base: transport, host: host, reportOrigin: "https://console.example.com"}
+ e := new(Edge)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if e.serveDemoAsset(w, r) {
+ return
+ }
+ if g := newGzipWriter(w, r); g != nil {
+ defer g.finish()
+ w = g
+ }
+ w = e.beginDemoResponse(w, r)
+ proxy.ServeHTTP(w, r)
+ })
+}
+
+func TestDemoBannerBrowser(t *testing.T) {
+ if os.Getenv("CARLOS_DEMO_BROWSER_TESTS") != "1" {
+ t.Skip("set CARLOS_DEMO_BROWSER_TESTS=1 to run installed Chromium via CDP")
+ }
+ if _, err := exec.LookPath("geckodriver"); err != nil {
+ t.Log("Firefox: NOT RUN, outstanding evidence; no Firefox driver is installed.")
+ } else {
+ t.Log("Firefox: NOT RUN, outstanding evidence; this witness drives Chromium CDP only.")
+ }
+ t.Log("Safari: NOT RUN, outstanding Task 6 check.")
+ if _, err := os.Stat("/usr/bin/chromium"); err != nil {
+ t.Fatalf("Chromium required: %v", err)
+ }
+ tmp := os.Getenv("TMPDIR")
+ if tmp == "" || filepath.Clean(tmp) == "/tmp" {
+ t.Fatal("set TMPDIR to disk scratch before browser tests")
+ }
+ scratch, err := os.MkdirTemp(tmp, "demo-banner-browser-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := os.RemoveAll(scratch); err != nil {
+ t.Error(err)
+ }
+ })
+ binary := filepath.Join(scratch, "shop")
+ build := exec.CommandContext(t.Context(), "go", "build", "-p", "1", "-o", binary, ".")
+ build.Dir = "testdata/demo-protections"
+ build.Env = append(os.Environ(), "GOPROXY=off", "GOFLAGS=-mod=readonly", "GOTOOLCHAIN=local")
+ if out, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("build fixture: %v\n%s", err, out)
+ }
+ socket := filepath.Join(scratch, "shop.sock")
+ fixture := exec.Command(binary, "--socket", socket, "--db", filepath.Join(scratch, "shop.db"))
+ fixture.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + scratch, "TMPDIR=" + scratch}
+ demoBrowserProcess(t, fixture, filepath.Join(scratch, "app.log"))
+ deadline := time.Now().Add(15 * time.Second)
+ for {
+ if _, err := os.Stat(socket); err == nil {
+ break
+ }
+ if time.Now().After(deadline) {
+ b, _ := os.ReadFile(filepath.Join(scratch, "app.log"))
+ t.Fatalf("fixture socket: %s", b)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ upstream := &http.Transport{Proxy: nil, DisableCompression: true, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", socket)
+ }}
+ defer upstream.CloseIdleConnections()
+ target, _ := url.Parse("http://shop.example.com")
+ var mu sync.Mutex
+ requests := map[string]int{}
+ foreignRequests := 0
+ foreign := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ foreignRequests++
+ mu.Unlock()
+ w.WriteHeader(204)
+ }))
+ defer foreign.Close()
+ handler := demoBannerTestProxy(t, target, upstream, "shop.example.com")
+ site := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ requests[r.URL.Path]++
+ mu.Unlock()
+ handler.ServeHTTP(w, r)
+ }))
+ defer site.Close()
+ // Trust only httptest's certificate key, for this isolated browser profile.
+ cert, err := x509.ParseCertificate(site.TLS.Certificates[0].Certificate[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ spki := sha256.Sum256(cert.RawSubjectPublicKeyInfo)
+ profile := filepath.Join(scratch, "chromium")
+ browser := exec.Command("/usr/bin/chromium", "--headless", "--no-sandbox", "--disable-gpu", "--no-first-run", "--no-default-browser-check", "--disable-background-networking", "--disable-component-update", "--disable-sync", "--disable-default-apps", "--no-proxy-server", "--remote-debugging-address=127.0.0.1", "--remote-debugging-port=0", "--remote-allow-origins=http://127.0.0.1", "--host-resolver-rules=MAP shop.example.com 127.0.0.1, MAP * ~NOTFOUND", "--ignore-certificate-errors-spki-list="+base64.StdEncoding.EncodeToString(spki[:]), "--user-data-dir="+profile, "about:blank")
+ browser.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + scratch, "TMPDIR=" + scratch}
+ demoBrowserProcess(t, browser, filepath.Join(scratch, "chromium.log"))
+ var port string
+ deadline = time.Now().Add(15 * time.Second)
+ for {
+ b, err := os.ReadFile(filepath.Join(profile, "DevToolsActivePort"))
+ if err == nil {
+ port = strings.Split(string(b), "\n")[0]
+ break
+ }
+ if time.Now().After(deadline) {
+ b, _ := os.ReadFile(filepath.Join(scratch, "chromium.log"))
+ t.Fatalf("Chromium startup: %s", b)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ client := &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{Proxy: nil}}
+ defer client.CloseIdleConnections()
+ response, err := client.Get("http://127.0.0.1:" + port + "/json/list")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var tabs []struct {
+ Type string `json:"type"`
+ URL string `json:"webSocketDebuggerUrl"`
+ }
+ err = json.NewDecoder(response.Body).Decode(&tabs)
+ response.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ wsURL := ""
+ for _, tab := range tabs {
+ if tab.Type == "page" {
+ wsURL = tab.URL
+ break
+ }
+ }
+ ws, err := websocket.Dial(wsURL, "", "http://127.0.0.1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ws.Close()
+ cdp := &demoCDP{t: t, ws: ws}
+ t.Logf("Browser version: %s", cdp.call("Browser.getVersion", nil))
+ cdp.call("Page.enable", nil)
+ cdp.call("Network.enable", nil)
+ parsed, _ := url.Parse(site.URL)
+ origin := "https://shop.example.com:" + parsed.Port()
+ navigate := func(path string) {
+ cdp.call("Page.navigate", map[string]any{"url": origin + path})
+ cdp.wait(`window.demoReady === true && location.pathname === ` + demoJSON(strings.Split(path, "?")[0]))
+ }
+ navigate("/?foreign=" + url.QueryEscape(foreign.URL))
+ cdp.check(`document.querySelectorAll('#carlos-demo-warning').length===1 && document.querySelectorAll('link[href="/.carlos/demo/banner.css"]').length===1`)
+ cdp.check(`document.querySelector('#carlos-demo-warning').textContent.includes(` + demoJSON(demoCopy["DEMO-BANNER"]) + `) && getComputedStyle(document.querySelector('#carlos-demo-warning')).position==='fixed'`)
+ cdp.check(`window.externalRan===true && window.inlineRan!==true && document.querySelector('#fetched').textContent==='shop' && document.cookie.includes('shop_script=1') && document.cookie.includes('shop_server=1')`)
+ cdp.check(`document.querySelector('#carlos-demo-warning a').href==='https://console.example.com/demo/report?host=shop.example.com' && document.querySelector('#carlos-demo-warning a').rel==='noopener noreferrer'`)
+ t.Log("Chromium DOM: one fixed warning and stylesheet; external same-origin script, self fetch, server cookie and script cookie work; inline script did not run; report URL contains only canonical host.")
+ cdp.eval(`document.querySelector('#self-form').submit(); true`)
+ cdp.wait(`location.pathname==='/shop' && window.demoReady===true && document.querySelector('#count').textContent==='1'`)
+ t.Log("Chromium form: same-origin POST succeeded; SQLite count is 1.")
+ cdp.eval(`document.querySelector('#deep').click(); true`)
+ cdp.wait(`location.pathname==='/shop/deep' && window.demoReady===true && !!document.querySelector('#carlos-demo-warning')`)
+ navigate("/shop/direct?foreign=" + url.QueryEscape(foreign.URL))
+ // At a 320px viewport, doubling CSS pixel sizes exercises 200% zoom's
+ // reflow rather than merely enlarging a screenshot with pinch zoom.
+ cdp.call("Emulation.setDeviceMetricsOverride", map[string]any{"width": 320, "height": 900, "deviceScaleFactor": 1, "mobile": true})
+ for _, zoom := range []int{1, 2} {
+ cdp.eval(fmt.Sprintf("document.documentElement.style.zoom=%d; true", zoom))
+ cdp.check(`(()=>{const b=document.querySelector('#carlos-demo-warning'),a=b.querySelector('a'),r=b.getBoundingClientRect(),q=a.getBoundingClientRect();return r.left>=0 && r.right<=innerWidth+1 && q.left>=r.left && q.right<=r.right+1 && q.bottom<=r.bottom+1 && document.querySelector('main').getBoundingClientRect().top>=r.bottom && r.height>0 && getComputedStyle(b).fontSize==='16px'})()`)
+ t.Logf("Chromium layout: 320px width, %d%% CSS zoom, banner and report link fit; geometry=%s", zoom*100, cdp.eval(`(()=>{const r=document.querySelector('#carlos-demo-warning').getBoundingClientRect();return {width:r.width,height:r.height,viewport:innerWidth,zoom:document.documentElement.style.zoom}})()`))
+ }
+ cdp.eval(`document.documentElement.style.zoom=1; true`)
+ // A plain HTTP client supplies no Fetch Metadata headers.
+ request, err := http.NewRequestWithContext(t.Context(), "GET", site.URL+"/shop/no-metadata", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Host = "shop.example.com"
+ noMetadata, err := site.Client().Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, err := io.ReadAll(noMetadata.Body)
+ noMetadata.Body.Close()
+ if err != nil || noMetadata.StatusCode != 200 || strings.Count(string(body), `id="carlos-demo-warning"`) != 1 {
+ t.Fatalf("absent Fetch Metadata: %d %v", noMetadata.StatusCode, err)
+ }
+ t.Log("Direct navigation, clicked deep link and GET without Fetch Metadata retained the app path and received one warning.")
+ cdp.eval(`window.hostile(` + demoJSON(foreign.URL) + `); true`)
+ cdp.wait(`window.foreignFetchBlocked===true && ['form-action','connect-src','img-src','script-src-elem'].every(d=>window.violations.includes(d))`)
+ cdp.check(`!document.querySelector('#carlos-demo-warning') && location.pathname==='/shop/direct'`)
+ mu.Lock()
+ hits := foreignRequests
+ observed := fmt.Sprint(requests)
+ mu.Unlock()
+ if hits != 0 {
+ t.Fatalf("foreign server received %d requests", hits)
+ }
+ t.Logf("Hostile same-origin JavaScript removed the notice. CSP still blocked foreign form, fetch, image and script; violations=%s; foreign server requests=%d", cdp.eval("window.violations"), hits)
+ t.Logf("Loopback app network observations: %s", observed)
+ for _, path := range []string{"/.carlos/demo/banner.css", "/static/tokens.css", "/static/theme.css", "/static/rastrillo.js", "/style.css", "/app.js", "/api/shop", "/shop", "/shop/deep"} {
+ mu.Lock()
+ n := requests[path]
+ mu.Unlock()
+ if n == 0 {
+ t.Errorf("missing network request %s", path)
+ }
+ }
+}
+
+func demoBrowserProcess(t *testing.T, cmd *exec.Cmd, logPath string) {
+ t.Helper()
+ log, err := os.Create(logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cmd.Stdout = log
+ cmd.Stderr = log
+ if err := cmd.Start(); err != nil {
+ log.Close()
+ t.Fatal(err)
+ }
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+ t.Cleanup(func() {
+ _ = cmd.Process.Signal(os.Interrupt)
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ _ = cmd.Process.Kill()
+ <-done
+ }
+ _ = log.Close()
+ })
+}
+
+type demoCDP struct {
+ t *testing.T
+ ws *websocket.Conn
+ id int
+}
+
+func (c *demoCDP) call(method string, params any) json.RawMessage {
+ c.t.Helper()
+ c.id++
+ _ = c.ws.SetDeadline(time.Now().Add(15 * time.Second))
+ if err := websocket.JSON.Send(c.ws, map[string]any{"id": c.id, "method": method, "params": params}); err != nil {
+ c.t.Fatal(err)
+ }
+ for {
+ var msg struct {
+ ID int `json:"id"`
+ Result json.RawMessage `json:"result"`
+ Error json.RawMessage `json:"error"`
+ }
+ if err := websocket.JSON.Receive(c.ws, &msg); err != nil {
+ c.t.Fatal(err)
+ }
+ if msg.ID == c.id {
+ if len(msg.Error) > 0 {
+ c.t.Fatalf("CDP %s: %s", method, msg.Error)
+ }
+ return msg.Result
+ }
+ }
+}
+func (c *demoCDP) eval(expression string) json.RawMessage {
+ c.t.Helper()
+ result := c.call("Runtime.evaluate", map[string]any{"expression": expression, "returnByValue": true, "awaitPromise": true})
+ var out struct {
+ Result struct {
+ Value json.RawMessage `json:"value"`
+ } `json:"result"`
+ Exception json.RawMessage `json:"exceptionDetails"`
+ }
+ if err := json.Unmarshal(result, &out); err != nil {
+ c.t.Fatal(err)
+ }
+ if len(out.Exception) > 0 {
+ c.t.Fatalf("JS %s: %s", expression, out.Exception)
+ }
+ return out.Result.Value
+}
+func (c *demoCDP) check(expression string) {
+ c.t.Helper()
+ if got := string(c.eval(expression)); got != "true" {
+ c.t.Fatalf("DOM assertion %s: %s", expression, got)
+ }
+}
+func (c *demoCDP) wait(expression string) {
+ c.t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ if string(c.eval(expression)) == "true" {
+ return
+ }
+ if time.Now().After(deadline) {
+ c.t.Fatalf("DOM wait: %s", expression)
+ }
+ time.Sleep(30 * time.Millisecond)
+ }
+}
+func demoJSON(v any) string { b, _ := json.Marshal(v); return string(b) }
diff --git a/internal/edge/demo_banner_test.go b/internal/edge/demo_banner_test.go
new file mode 100644
index 000000000..c60cf83ff
--- /dev/null
+++ b/internal/edge/demo_banner_test.go
@@ -0,0 +1,479 @@
+package edge
+
+import (
+ "bytes"
+ "compress/gzip"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestDemoBannerInsertion(t *testing.T) {
+ for _, tt := range []struct{ name, input, before string }{
+ {"body", "<body>shop</body>", "<body>"},
+ {"head", "<!DOCTYPE html><html><head><title>shop</title></head><body class='shop'>x</body>", "<!DOCTYPE html><html><head><title>shop</title></head><body class='shop'>"},
+ {"mixed", "<BoDy\n CLASS=x>shop", "<BoDy\n CLASS=x>"},
+ {"lookalikes", "<!-- <body> --><script>const x='<body>';</script><body>shop", "<!-- <body> --><script>const x='<body>';</script><body>"},
+ {"rawtext", "<style>body:before{content:'<body>'}</style><body>x", "<style>body:before{content:'<body>'}</style><body>"},
+ {"self-closing-body", "<body/>shop", "<body/>"},
+ {"bom-doctype", "\xef\xbb\xbf<!doctype html><p>shop", "\xef\xbb\xbf<!doctype html>"},
+ {"comment-doctype", "<!-- shop --><!doctype html><p>shop", "<!-- shop --><!doctype html>"},
+ {"empty", "", ""}, {"fragment", "<p>shop", ""}, {"malformed", "<body broken='", ""},
+ {"doctype", " \n<!doctype html><p>shop", " \n<!doctype html>"},
+ {"long", "<!doctype html><!--" + strings.Repeat("x", 70<<10) + "--><body>shop", "<!doctype html>"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ var out bytes.Buffer
+ if err := injectDemoBanner(&out, strings.NewReader(tt.input), "shop.example.com", "https://console.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ markup, err := demoBannerMarkup("shop.example.com", "https://console.example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := tt.before + markup + strings.TrimPrefix(tt.input, tt.before)
+ if out.String() != want {
+ t.Fatalf("insertion differs at prefix: %.250s", out.String())
+ }
+ if strings.Count(out.String(), `id="carlos-demo-warning"`) != 1 || strings.Count(out.String(), `href="/.carlos/demo/banner.css"`) != 1 {
+ t.Fatal("warning/style count")
+ }
+ })
+ }
+ t.Run("stream", func(t *testing.T) {
+ src := &demoRepeatingReader{left: 8 << 20}
+ dst := &demoStreamWitness{source: src}
+ if err := injectDemoBanner(dst, io.MultiReader(strings.NewReader("<body>"), src), "shop.example.com", "https://console.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ if !dst.beforeEOF || src.left != 0 || dst.n < 8<<20 {
+ t.Fatalf("not streamed: %+v", dst)
+ }
+ })
+ t.Run("reader-error", func(t *testing.T) {
+ if err := injectDemoBanner(io.Discard, demoBrokenReader{}, "shop.example.com", "https://console.example.com"); err == nil {
+ t.Fatal("read error lost")
+ }
+ })
+ t.Run("writer-error", func(t *testing.T) {
+ if err := injectDemoBanner(demoBrokenWriter{}, strings.NewReader("<body>x"), "shop.example.com", "https://console.example.com"); err == nil {
+ t.Fatal("write error lost")
+ }
+ })
+}
+
+type demoRepeatingReader struct{ left int }
+
+func (r *demoRepeatingReader) Read(p []byte) (int, error) {
+ if r.left == 0 {
+ return 0, io.EOF
+ }
+ n := min(len(p), r.left)
+ for i := range n {
+ p[i] = 'x'
+ }
+ r.left -= n
+ return n, nil
+}
+
+type demoStreamWitness struct {
+ source *demoRepeatingReader
+ n int
+ beforeEOF bool
+}
+
+func (w *demoStreamWitness) Write(p []byte) (int, error) {
+ w.beforeEOF = w.beforeEOF || w.source.left > 0
+ w.n += len(p)
+ return len(p), nil
+}
+
+type demoBrokenReader struct{}
+
+func (demoBrokenReader) Read([]byte) (int, error) { return 0, errors.New("read witness") }
+
+type demoBrokenWriter struct{}
+
+func (demoBrokenWriter) Write([]byte) (int, error) { return 0, errors.New("write witness") }
+
+type demoBannerRoundTrip func(*http.Request) (*http.Response, error)
+
+func (f demoBannerRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func TestDemoBannerRepresentations(t *testing.T) {
+ for _, tt := range []struct {
+ name, method, ct, encoding string
+ status int
+ retry, refuse, bodyless bool
+ }{
+ {name: "html", ct: "text/html", status: 200}, {name: "gzip", ct: "text/html; charset=UTF-8", encoding: "gzip", status: 200},
+ {name: "error", ct: "text/html", status: 500}, {name: "empty", ct: "text/html", status: 200},
+ {name: "partial", ct: "text/html", status: 206, retry: true}, {name: "conditional", ct: "text/html", status: 304, retry: true},
+ {name: "conditional-without-type", status: 304, retry: true},
+ {name: "partial-without-type", status: 206, retry: true},
+ {name: "still-partial", ct: "text/html", status: 206, retry: true, refuse: true},
+ {name: "post-partial", method: "POST", ct: "text/html", status: 206, refuse: true},
+ {name: "unsupported", ct: "text/html", encoding: "br", status: 200, refuse: true},
+ {name: "charset", ct: "text/html; charset=iso-8859-1", status: 200, refuse: true},
+ {name: "xhtml", ct: "application/xhtml+xml", status: 200, refuse: true},
+ {name: "svg", ct: "image/svg+xml", status: 200, refuse: true},
+ {name: "head", method: "HEAD", ct: "text/html", status: 200, bodyless: true},
+ {name: "204", ct: "text/html", status: 204, bodyless: true},
+ {name: "304-image", ct: "image/png", status: 304, bodyless: true},
+ {name: "range-image", ct: "image/png", status: 206},
+ {name: "range-multipart", ct: "multipart/byteranges; boundary=shop", status: 206}, {name: "json", ct: "application/json", status: 200},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ method := tt.method
+ if method == "" {
+ method = "GET"
+ }
+ req := httptest.NewRequest(method, "https://shop.example.com/deep", nil)
+ req.Header.Set("Range", "bytes=0-20")
+ req.Header.Set("If-None-Match", `"old"`)
+ req.Header.Set("Accept-Encoding", "br")
+ calls := 0
+ tr := demoBannerTransport{host: "shop.example.com", reportOrigin: "https://console.example.com", base: demoBannerRoundTrip(func(r *http.Request) (*http.Response, error) {
+ calls++
+ if r.Header.Get("Accept-Encoding") != "identity" {
+ t.Error("unsupported upstream negotiation")
+ }
+ status := tt.status
+ if calls == 2 {
+ if r.Header.Get("Range") != "" || r.Header.Get("If-None-Match") != "" {
+ t.Error("retry retains conditions")
+ }
+ if tt.name != "still-partial" {
+ status = 200
+ }
+ }
+ body := "<body>shop</body>"
+ if tt.name == "empty" || tt.bodyless || status == 304 {
+ body = ""
+ }
+ if tt.encoding == "gzip" {
+ var b bytes.Buffer
+ g := gzip.NewWriter(&b)
+ _, _ = io.WriteString(g, body)
+ _ = g.Close()
+ body = b.String()
+ }
+ h := http.Header{"Content-Type": {tt.ct}, "Content-Encoding": {tt.encoding}, "Etag": {`"old"`}, "Content-Length": {"17"}, "Digest": {"old"}, "Content-Digest": {"old"}, "Repr-Digest": {"old"}, "Last-Modified": {"old"}, "Accept-Ranges": {"bytes"}, "X-Carlos-Version": {"v1"}}
+ if status == 206 {
+ h.Set("Content-Range", "bytes 0-16/100")
+ }
+ return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(body)), Request: r, ContentLength: int64(len(body))}, nil
+ })}
+ resp, err := tr.RoundTrip(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if calls != 1+btoi(tt.retry) {
+ t.Fatalf("calls %d", calls)
+ }
+ if tt.refuse {
+ if resp.StatusCode != 502 || resp.Header.Get("X-Carlos-Version") != "" {
+ t.Fatalf("unsafe response: %+v", resp)
+ }
+ return
+ }
+ if tt.bodyless {
+ if len(b) != 0 {
+ t.Fatal("body on bodyless response")
+ }
+ return
+ }
+ transformed := strings.HasPrefix(tt.ct, "text/html") || tt.retry
+ if transformed {
+ if strings.Count(string(b), `id="carlos-demo-warning"`) != 1 {
+ t.Fatalf("no warning: %s", b)
+ }
+ for _, key := range []string{"Content-Encoding", "Content-Length", "ETag", "Last-Modified", "Digest", "Content-Digest", "Repr-Digest", "Accept-Ranges", "Content-Range"} {
+ if resp.Header.Get(key) != "" {
+ t.Errorf("stale %s", key)
+ }
+ }
+ if resp.ContentLength != -1 {
+ t.Fatal("stale structured length")
+ }
+ } else if string(b) != "<body>shop</body>" || resp.StatusCode != tt.status || resp.Header.Get("ETag") == "" {
+ t.Fatal("non-HTML changed")
+ }
+ if resp.Header.Get("X-Carlos-Version") != "v1" {
+ t.Fatal("app version changed")
+ }
+ if req.Header.Get("Accept-Encoding") != "br" || req.Header.Get("Range") == "" {
+ t.Fatal("caller request mutated")
+ }
+ })
+ }
+ t.Run("platform", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest("GET", "https://shop.example.com/", nil)
+ serveDemoHTML(w, r, 503, "DEMO-UNAVAILABLE", "shop.example.com", "https://console.example.com")
+ if w.Code != 503 || strings.Count(w.Body.String(), `id="carlos-demo-warning"`) != 1 || w.Header().Get("Content-Security-Policy") != demoCSP() {
+ t.Fatalf("platform response: %+v", w)
+ }
+ })
+}
+func btoi(b bool) int {
+ if b {
+ return 1
+ }
+ return 0
+}
+
+func TestDemoBannerAssets(t *testing.T) {
+ e := new(Edge)
+ for _, p := range []string{"/.carlos/demo/banner.css", "/.carlos/demo/unknown", "/.carlos/demo/", "/.carlos/demo"} {
+ w := httptest.NewRecorder()
+ w.Header().Set("X-Carlos-Version", "app-version")
+ if !e.serveDemoAsset(w, httptest.NewRequest("GET", "https://shop.example.com"+p, nil)) {
+ t.Fatalf("not reserved: %s", p)
+ }
+ if w.Header().Get("X-Carlos-Version") != "" || w.Header().Get("Content-Security-Policy") != demoCSP() {
+ t.Fatal("asset version/policy")
+ }
+ if p == "/.carlos/demo/banner.css" && (w.Code != 200 || w.Header().Get("Content-Type") != "text/css; charset=utf-8" || !strings.Contains(w.Body.String(), "position: fixed")) {
+ t.Fatal("stylesheet")
+ }
+ }
+ if e.serveDemoAsset(httptest.NewRecorder(), httptest.NewRequest("GET", "https://shop.example.com/shop", nil)) {
+ t.Fatal("ordinary path reserved")
+ }
+ for _, method := range []string{"HEAD", "POST"} {
+ w := httptest.NewRecorder()
+ e.serveDemoAsset(w, httptest.NewRequest(method, "https://shop.example.com/.carlos/demo/banner.css", nil))
+ if method == "HEAD" && w.Body.Len() != 0 || method == "POST" && w.Code != 405 {
+ t.Fatal("asset method")
+ }
+ }
+}
+
+func TestDemoBannerReportURL(t *testing.T) {
+ markup, err := demoBannerMarkup(`shop.example.com\"><script>`, "https://console.example.com")
+ if err != nil || strings.Contains(markup, "<script>") || !strings.Contains(markup, "/demo/report?host=") || !strings.Contains(markup, `target="_blank" rel="noopener noreferrer"`) {
+ t.Fatalf("escaping/link: %s %v", markup, err)
+ }
+ for _, origin := range []string{"", "http://console.example.com", "https://user@console.example.com", "https://console.example.com/path", "https://console.example.com?token=private"} {
+ if _, err := demoBannerMarkup("shop.example.com", origin); err == nil {
+ t.Fatalf("bad origin accepted %q", origin)
+ }
+ }
+}
+
+func TestDemoProbeStillChecksApp(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ status int
+ version, body string
+ ready bool
+ }{
+ {"app", 200, "v1", "<body>shop", true}, {"empty", 200, "v1", "", true},
+ {"wrong-version", 200, "v0", "<body>shop", false}, {"redirect", 302, "v1", "<body>shop", false},
+ {"failure", 500, "v1", "<body>shop", false},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ calls := 0
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("X-Carlos-Version", tt.version)
+ if tt.status == 302 {
+ w.Header().Set("Location", "/next")
+ }
+ w.WriteHeader(tt.status)
+ _, _ = io.WriteString(w, tt.body)
+ }))
+ defer app.Close()
+ target, err := url.Parse(app.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ edge := httptest.NewServer(demoBannerTestProxy(t, target, app.Client().Transport, "shop.example.com"))
+ defer edge.Close()
+ client := edge.Client()
+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ resp, err := client.Get(edge.URL + "/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ ready := resp.StatusCode >= 200 && resp.StatusCode < 300 && resp.Header.Get("X-Carlos-Version") == "v1"
+ if resp.StatusCode != tt.status || ready != tt.ready || calls != 1 || strings.Count(string(b), `id="carlos-demo-warning"`) != 1 {
+ t.Fatalf("status=%d ready=%v calls=%d body=%s", resp.StatusCode, ready, calls, b)
+ }
+ asset, err := client.Get(edge.URL + demoAssetPrefix + "banner.css")
+ if err != nil {
+ t.Fatal(err)
+ }
+ asset.Body.Close()
+ if asset.Header.Get("X-Carlos-Version") != "" || calls != 1 {
+ t.Fatal("asset reached app or impersonated app version")
+ }
+ })
+ }
+}
+
+func TestDemoBannerWireCompression(t *testing.T) {
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Content-Encoding", "gzip")
+ w.Header().Set("ETag", `"original"`)
+ w.Header().Set("Trailer", "Digest, Set-Cookie")
+ w.Header().Set("X-Carlos-Version", "v1")
+ w.WriteHeader(200)
+ g := gzip.NewWriter(w)
+ _, _ = io.WriteString(g, "<body>"+strings.Repeat("shop ", 20000))
+ _ = g.Close()
+ w.Header().Set("Digest", "stale")
+ w.Header().Set("Set-Cookie", "unsafe=1; Domain=example.com")
+ }))
+ defer app.Close()
+ target, _ := url.Parse(app.URL)
+ edge := httptest.NewServer(demoBannerTestProxy(t, target, app.Client().Transport, "shop.example.com"))
+ defer edge.Close()
+ for _, encoding := range []string{"gzip", "identity"} {
+ r, _ := http.NewRequest("GET", edge.URL, nil)
+ r.Header.Set("Accept-Encoding", encoding)
+ resp, err := edge.Client().Do(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var body io.Reader = resp.Body
+ if encoding == "gzip" {
+ if resp.Header.Get("Content-Encoding") != "gzip" {
+ t.Fatal("not re-encoded")
+ }
+ gz, err := gzip.NewReader(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer gz.Close()
+ body = gz
+ } else if resp.Header.Get("Content-Encoding") != "" {
+ t.Fatal("identity request got compressed bytes")
+ }
+ b, err := io.ReadAll(body)
+ resp.Body.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Count(string(b), `id="carlos-demo-warning"`) != 1 || strings.Count(string(b), "shop ") != 20000 {
+ t.Fatal("changed or duplicate document")
+ }
+ if len(resp.Trailer) != 0 || resp.Header.Get("ETag") != "" || resp.Header.Get("Content-Length") != "" || resp.Header.Get("Content-Security-Policy") != demoCSP() {
+ t.Fatalf("stale metadata/policy: %v %v", resp.Header, resp.Trailer)
+ }
+ }
+}
+
+func TestDemoBannerPrefixBound(t *testing.T) {
+ src := &demoBoundWitness{left: 2 << 20}
+ if err := injectDemoBanner(src, src, "shop.example.com", "https://console.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ if src.beforeWrite != demoBannerPrefixLimit || src.left != 0 {
+ t.Fatalf("prefix=%d remaining=%d", src.beforeWrite, src.left)
+ }
+}
+
+type demoBoundWitness struct {
+ left, beforeWrite int
+ wrote bool
+}
+
+func (r *demoBoundWitness) Read(p []byte) (int, error) {
+ if r.left == 0 {
+ return 0, io.EOF
+ }
+ if !r.wrote && r.beforeWrite+len(p) > demoBannerPrefixLimit {
+ return 0, errors.New("prefix read exceeds 64 KiB")
+ }
+ n := min(len(p), r.left)
+ for i := range n {
+ p[i] = 'x'
+ }
+ r.left -= n
+ if !r.wrote {
+ r.beforeWrite += n
+ }
+ return n, nil
+}
+func (r *demoBoundWitness) Write(p []byte) (int, error) { r.wrote = true; return len(p), nil }
+
+func TestDemoBannerBodyLifecycle(t *testing.T) {
+ t.Run("retry-close", func(t *testing.T) {
+ calls := 0
+ first := &demoCloseWitness{Reader: strings.NewReader("<body>partial")}
+ second := &demoCloseWitness{Reader: strings.NewReader("<body>full")}
+ tr := demoBannerTransport{host: "shop.example.com", reportOrigin: "https://console.example.com", base: demoBannerRoundTrip(func(r *http.Request) (*http.Response, error) {
+ calls++
+ status, body := 206, first
+ if calls == 2 {
+ if !first.closed {
+ t.Error("partial body not closed before retry")
+ }
+ status, body = 200, second
+ }
+ return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": {"text/html"}}, Body: body, Request: r}, nil
+ })}
+ resp, err := tr.RoundTrip(httptest.NewRequest("GET", "https://shop.example.com", nil))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := resp.Body.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if calls != 2 || !second.closed {
+ t.Fatal("transformed body did not close upstream")
+ }
+ })
+ t.Run("bad-gzip", func(t *testing.T) {
+ body := &demoCloseWitness{Reader: strings.NewReader("not gzip")}
+ tr := demoBannerTransport{host: "shop.example.com", reportOrigin: "https://console.example.com", base: demoBannerRoundTrip(func(r *http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/html"}, "Content-Encoding": {"gzip"}, "X-Carlos-Version": {"v1"}}, Body: body, Request: r}, nil
+ })}
+ resp, err := tr.RoundTrip(httptest.NewRequest("GET", "https://shop.example.com", nil))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != 502 || !body.closed || resp.Header.Get("X-Carlos-Version") != "" {
+ t.Fatal("bad gzip did not fail closed")
+ }
+ })
+ t.Run("late-read-error", func(t *testing.T) {
+ tr := demoBannerTransport{host: "shop.example.com", reportOrigin: "https://console.example.com", base: demoBannerRoundTrip(func(r *http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/html"}}, Body: io.NopCloser(io.MultiReader(strings.NewReader("<body>"+strings.Repeat("x", 100<<10)), demoBrokenReader{})), Request: r}, nil
+ })}
+ resp, err := tr.RoundTrip(httptest.NewRequest("GET", "https://shop.example.com", nil))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if _, err := io.Copy(io.Discard, resp.Body); err == nil {
+ t.Fatal("late upstream error hidden")
+ }
+ })
+}
+
+type demoCloseWitness struct {
+ io.Reader
+ closed bool
+}
+
+func (b *demoCloseWitness) Close() error { b.closed = true; return nil }
diff --git a/internal/edge/demo_copy.go b/internal/edge/demo_copy.go
index ff7f3bed0..0d2f3f04b 100644
--- a/internal/edge/demo_copy.go
+++ b/internal/edge/demo_copy.go
@@ -1,13 +1,12 @@
package edge
-// Draft plan-2 copy, keyed by the controller's copy-table IDs. Task 6 owns
-// the copy review before this branch ships.
+// Approved plan-2 copy, keyed by the controller's copy-table IDs.
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-LIMIT-PRECLAIM": "This demo has reached its limit. Claiming will be available in a future release.",
+ "DEMO-STOPPED": "Demo serving is temporarily off.",
"DEMO-GONE": "This demo is no longer available.",
- "DEMO-UNAVAILABLE": "This demo cannot be checked right now. Try again shortly.",
+ "DEMO-UNAVAILABLE": "This demo cannot be checked right now. Please try again shortly.",
"DEMO-RESPONSE": "This demo returned a response that cannot be shown.",
}
diff --git a/internal/edge/testdata/demo-protections/app.js b/internal/edge/testdata/demo-protections/app.js
new file mode 100644
index 000000000..ceaefb889
--- /dev/null
+++ b/internal/edge/testdata/demo-protections/app.js
@@ -0,0 +1,19 @@
+window.violations = [];
+document.addEventListener('securitypolicyviolation', e => window.violations.push(e.effectiveDirective));
+document.cookie = 'shop_script=1; Path=/; Secure; SameSite=Lax';
+window.externalRan = true;
+fetch('/api/shop').then(r => r.json()).then(data => {
+ document.querySelector('#fetched').textContent = data.shop ? 'shop' : '';
+ window.demoReady = true;
+});
+window.hostile = async function (foreign) {
+ document.querySelector('#carlos-demo-warning').remove();
+ const image = new Image();
+ image.src = foreign + '/image';
+ document.body.append(image);
+ const script = document.createElement('script');
+ script.src = foreign + '/script';
+ document.body.append(script);
+ document.querySelector('#foreign-form').submit();
+ try { await fetch(foreign + '/fetch'); } catch (_) { window.foreignFetchBlocked = true; }
+};
diff --git a/internal/edge/testdata/demo-protections/go.mod b/internal/edge/testdata/demo-protections/go.mod
new file mode 100644
index 000000000..36b00a9b4
--- /dev/null
+++ b/internal/edge/testdata/demo-protections/go.mod
@@ -0,0 +1,34 @@
+module demo.local/app
+
+go 1.26.10
+
+require (
+ amadan.net/rastrillo/rastrillo v0.30.2
+ amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
+ github.com/BurntSushi/toml v1.6.0 // indirect
+ github.com/chromedp/cdproto v0.158.6 // indirect
+ github.com/chromedp/chromedp v0.21.0 // indirect
+ github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/go-chi/chi/v5 v5.3.2 // indirect
+ github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/jinzhu/inflection v1.0.0 // indirect
+ github.com/jinzhu/now v1.1.5 // indirect
+ github.com/keymaildev/signin v0.1.1 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/ncruces/go-strftime v1.0.0 // indirect
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect
+ golang.org/x/crypto v0.53.0 // indirect
+ golang.org/x/mod v0.37.0 // indirect
+ golang.org/x/sync v0.21.0 // indirect
+ golang.org/x/sys v0.46.0 // indirect
+ golang.org/x/text v0.39.0 // indirect
+ golang.org/x/tools v0.47.0 // indirect
+ gorm.io/gorm v1.31.2 // indirect
+ gorm.io/plugin/dbresolver v1.6.2 // indirect
+ modernc.org/libc v1.74.1 // indirect
+ modernc.org/mathutil v1.7.1 // indirect
+ modernc.org/memory v1.11.0 // indirect
+ modernc.org/sqlite v1.55.0 // indirect
+)
diff --git a/internal/edge/testdata/demo-protections/go.sum b/internal/edge/testdata/demo-protections/go.sum
new file mode 100644
index 000000000..96f6e826f
--- /dev/null
+++ b/internal/edge/testdata/demo-protections/go.sum
@@ -0,0 +1,56 @@
+amadan.net/rastrillo/rastrillo v0.30.2 h1:xZ/cAfSvWFoWWL1xD5Lsq90xwxF+jigD1GsZmwgTcxs=
+amadan.net/rastrillo/rastrillo v0.30.2/go.mod h1:K7Clrt14+25ruVupgRjlIhH2GQp/OdL9VoD8xPmkt0w=
+amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
+amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U=
+github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
+github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
+github.com/chromedp/cdproto v0.158.6 h1:jaKiXWuhcxbvKbSe8U6Dp5U4Hcj2w6lETYgZqBD5n34=
+github.com/chromedp/cdproto v0.158.6/go.mod h1:h68JaIuFr9o3yiayxEYhBdvaxgYO3shDrPSYhNlyfu0=
+github.com/chromedp/chromedp v0.21.0 h1:nVHgS2LHyhZJ1l3BWRbG2eFIFYiJMnvkJbELbd8WBoQ=
+github.com/chromedp/chromedp v0.21.0/go.mod h1:6z1Y5FdKUxRzxx2qcC5h1xjaBJrSWrZp1mjgITfNZig=
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
+github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
+github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 h1:UADEEmDKgfXbtnGJZ97beY5XLo9ZechG1nlU4KnRrkE=
+github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/keymaildev/signin v0.1.1 h1:gO+1IAM99sqUkBtCezkgGxab+/DOrqwDxd5H32N1s9Q=
+github.com/keymaildev/signin v0.1.1/go.mod h1:Eb/sCmEel1jlcdkgPOrNeMn5jvxzoFvJrdjDUxOBHls=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
+golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
+golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
+golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
+golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
+golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
+golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
+golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
+golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
+gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
+gorm.io/plugin/dbresolver v1.6.2 h1:F4b85TenghUeITqe3+epPSUtHH7RIk3fXr5l83DF8Pc=
+gorm.io/plugin/dbresolver v1.6.2/go.mod h1:tctw63jdrOezFR9HmrKnPkmig3m5Edem9fdxk9bQSzM=
+modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
+modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
+modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
diff --git a/internal/edge/testdata/demo-protections/main.go b/internal/edge/testdata/demo-protections/main.go
new file mode 100644
index 000000000..8b9bb251b
--- /dev/null
+++ b/internal/edge/testdata/demo-protections/main.go
@@ -0,0 +1,83 @@
+package main
+
+import (
+ "database/sql"
+ _ "embed"
+ "flag"
+ "fmt"
+ "html"
+ "log"
+ "net/http"
+ "strings"
+
+ "amadan.net/rastrillo/rastrillo"
+ _ "amadan.net/rastrillo/rastrillo/locales/en"
+ "amadan.net/rastrillo/rastrillo/ui"
+)
+
+//go:embed app.js
+var appJS string
+
+//go:embed style.css
+var appCSS string
+
+func main() {
+ socket := flag.String("socket", "", "")
+ db := flag.String("db", "", "")
+ flag.Parse()
+ if *socket == "" || *db == "" {
+ log.Fatal("--socket and --db required")
+ }
+ err := rastrillo.Serve(rastrillo.Options{Socket: *socket, DBPath: *db,
+ Migrations: []string{`CREATE TABLE IF NOT EXISTS shop (id INTEGER PRIMARY KEY)`},
+ Router: func(db *sql.DB) (*http.ServeMux, error) {
+ mux := http.NewServeMux()
+ assets, ok := ui.VendoredAssets("day")
+ if !ok {
+ return nil, fmt.Errorf("missing day assets")
+ }
+ for name, body := range assets {
+ mux.HandleFunc("GET /static/"+name, func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(name, ".css") {
+ w.Header().Set("Content-Type", "text/css")
+ } else {
+ w.Header().Set("Content-Type", "application/javascript")
+ }
+ _, _ = w.Write(body)
+ })
+ }
+ mux.HandleFunc("GET /app.js", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/javascript")
+ _, _ = fmt.Fprint(w, appJS)
+ })
+ mux.HandleFunc("GET /style.css", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/css")
+ _, _ = fmt.Fprint(w, appCSS)
+ })
+ mux.HandleFunc("GET /api/shop", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = fmt.Fprint(w, `{"shop":true}`)
+ })
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == "POST" {
+ if _, err := db.ExecContext(r.Context(), `INSERT INTO shop DEFAULT VALUES`); err != nil {
+ http.Error(w, "shop", 500)
+ return
+ }
+ }
+ count := 0
+ if err := db.QueryRowContext(r.Context(), `SELECT count(*) FROM shop`).Scan(&count); err != nil {
+ http.Error(w, "shop", 500)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Add("Set-Cookie", "shop_server=1; Domain=example.com; Path=/; Secure; SameSite=Lax")
+ _, _ = fmt.Fprintf(w, `<!doctype html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1"><title>shop</title><link rel="stylesheet" href="/static/tokens.css"><link rel="stylesheet" href="/static/theme.css"><link rel="stylesheet" href="/style.css"><script src="/static/rastrillo.js" defer></script><script src="/app.js" defer></script><script>window.inlineRan=true</script></head><body><main class="rst-stack"><h1>shop</h1><p id="count">%d</p><a id="deep" href="/shop/deep">shop</a><form id="self-form" action="/shop" method="post"><input name="shop" value="shop"><button class="rst-btn rst-btn--primary" type="submit">shop</button></form><form id="foreign-form" action="%s/form" method="post"><input name="shop" value="shop"></form><p id="fetched"></p></main></body></html>`, count, html.EscapeString(r.URL.Query().Get("foreign")))
+ })
+ return mux, nil
+ },
+ })
+ if err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/internal/edge/testdata/demo-protections/style.css b/internal/edge/testdata/demo-protections/style.css
new file mode 100644
index 000000000..df89d62b6
--- /dev/null
+++ b/internal/edge/testdata/demo-protections/style.css
@@ -0,0 +1,2 @@
+main { max-width: 48rem; margin: 1rem auto; padding: 1rem; }
+input, button { font: inherit; max-width: 100%; }