diff --git a/src/main/java/run/halo/aipagebuilder/page/PagePreview.java b/src/main/java/run/halo/aipagebuilder/page/PagePreview.java index 6dd1886..aec330f 100644 --- a/src/main/java/run/halo/aipagebuilder/page/PagePreview.java +++ b/src/main/java/run/halo/aipagebuilder/page/PagePreview.java @@ -36,9 +36,10 @@ public Mono render( String description) { return renderer.render(request, name, slug, themeLayout, document, title, description) .flatMap(response -> RenderingResponse.from(response) - .header("Content-Security-Policy", policy(request).document()) + .header("Content-Security-Policy", "sandbox allow-scripts") .build()) - .cast(ServerResponse.class); + .map(response -> + new PagePreviewResponse(response, policy(request).document())); } public Mono token( @@ -56,9 +57,9 @@ public Mono token( var policy = policy(safeRequest); var uri = safeRequest.uri(); return RenderingResponse.from(response) - .header("Content-Security-Policy", policy.host(uri)) + .header("Content-Security-Policy", "sandbox allow-scripts") .build() - .map(host -> new PagePreviewResponse(host, uri, policy.child(uri))); + .map(host -> new PagePreviewResponse(host, uri, policy.host(uri), policy.child(uri))); }); }); } @@ -107,11 +108,11 @@ private List allowedPrefixes() { private record Policy(String common) { String document() { - return "sandbox allow-scripts; " + content("'none'", "'none'"); + return content("'none'", "'none'"); } String host(URI uri) { - return "sandbox allow-scripts; " + content(uri.toASCIIString(), "data:"); + return content(uri.toASCIIString(), "data:"); } String child(URI uri) { diff --git a/src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java b/src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java index e035521..d6dc74b 100644 --- a/src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java +++ b/src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java @@ -7,7 +7,9 @@ import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.DataNode; +import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; +import org.jsoup.parser.Parser; import org.reactivestreams.Publisher; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; @@ -17,17 +19,32 @@ import org.springframework.http.server.reactive.ServerHttpResponseDecorator; import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.HandlerMapping; +import org.springframework.web.reactive.function.server.RenderingResponse; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerRequest; -import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.ServerWebExchangeDecorator; import org.springframework.web.util.UriComponentsBuilder; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -/** Keep the bearer URL in a script-free host, outside the untrusted preview document. */ -record PagePreviewResponse(ServerResponse delegate, URI documentUri, String childPolicy) implements ServerResponse { +/** Keeps variable-size CSP in HTML and bearer URLs outside the untrusted preview document. */ +record PagePreviewResponse(RenderingResponse delegate, URI documentUri, String policy, String childPolicy) + implements RenderingResponse { + PagePreviewResponse(RenderingResponse delegate, String policy) { + this(delegate, null, policy, null); + } + + @Override + public String name() { + return delegate.name(); + } + + @Override + public Map model() { + return delegate.model(); + } + static ServerRequest withoutCredential(ServerRequest request) { var uri = UriComponentsBuilder.fromUri(request.uri()) .replacePath(request.requestPath().contextPath().value() + "/") @@ -83,7 +100,7 @@ public Mono writeWith(Publisher body) { } finally { DataBufferUtils.release(buffer); } - var bytes = host(html, documentUri, childPolicy).getBytes(StandardCharsets.UTF_8); + var bytes = render(html).getBytes(StandardCharsets.UTF_8); getHeaders().setContentLength(bytes.length); return super.writeWith(Mono.just(bufferFactory().wrap(bytes))); }); @@ -95,23 +112,41 @@ public Mono writeAndFlushWith(Publisher. + var document = Jsoup.parse(html, Parser.htmlParser().setTrackPosition(true)); + var head = document.head().sourceRange(); + // An implicit head has a zero-width range before its first content token. + var index = head.isTracked() ? head.endPos() : 0; + return html.substring(0, index) + policyElement(policy).outerHtml() + html.substring(index); + } + + private static void prependPolicy(Document document, String policy) { + document.head().prependChild(policyElement(policy)); + } + + private static Element policyElement(String policy) { + // Apply before every theme resource/script. Sandbox remains in the HTTP header: + // meta CSP cannot enforce it, while API allowlists can exceed proxy header buffers. + return new Element("meta").attr("http-equiv", "Content-Security-Policy").attr("content", policy); } - private static String host(String html, URI base, String policy) { + private static Document host(String html, URI base, String policy) { var child = Jsoup.parse(html); child.select("base").remove(); var baseElement = child.head().prependElement("base"); baseElement.attr("href", base.toASCIIString()); - child.head() - .prependElement("meta") - .attr("http-equiv", "Content-Security-Policy") - .attr("content", policy); + prependPolicy(child, policy); // Run before any theme script so startup storage access succeeds in the opaque origin. var shim = new Element("script").attr("data-ai-page-builder", "preview-storage"); shim.appendChild(new DataNode(PreviewStorageShim.BODY)); @@ -129,6 +164,6 @@ private static String host(String html, URI base, String policy) { .attr("referrerpolicy", "no-referrer") .attr("style", "position:fixed;inset:0;width:100%;height:100%;border:0") .attr("src", "data:text/html;base64," + source); - return host.outerHtml(); + return host; } } diff --git a/src/test/java/run/halo/aipagebuilder/page/PageEndpointTest.java b/src/test/java/run/halo/aipagebuilder/page/PageEndpointTest.java index 379dec1..12a402b 100644 --- a/src/test/java/run/halo/aipagebuilder/page/PageEndpointTest.java +++ b/src/test/java/run/halo/aipagebuilder/page/PageEndpointTest.java @@ -309,12 +309,11 @@ void candidatePreviewUsesSameThemeAndCssAsGetWithoutSaving() { assertThat(response.headers().getCacheControl()).isEqualTo("no-store"); assertThat(response.name()).isEqualTo("theme:custom-ai-page-builder"); assertThat(response.model()).isEqualTo(getResponse.model()); - assertThat(response.headers().getFirst("Content-Security-Policy")) - .contains( - "sandbox allow-scripts", - "connect-src http://localhost/rss.xml http://localhost/feed.xml " - + "http://localhost/sitemap.xml http://localhost/feed/") + assertThat(((PagePreviewResponse) response).policy()) + .contains("connect-src http://localhost/rss.xml http://localhost/feed.xml " + + "http://localhost/sitemap.xml http://localhost/feed/") .doesNotContain("allow-same-origin"); + assertThat(response.headers().getFirst("Content-Security-Policy")).isEqualTo("sandbox allow-scripts"); assertThat(getResponse.headers().getFirst("Content-Security-Policy")) .isEqualTo(response.headers().getFirst("Content-Security-Policy")); var view = (PageRenderer.PageView) response.model().get("aiPageBuilder"); diff --git a/src/test/java/run/halo/aipagebuilder/page/PagePreviewIsolationTest.java b/src/test/java/run/halo/aipagebuilder/page/PagePreviewIsolationTest.java index f78dd56..4c49f17 100644 --- a/src/test/java/run/halo/aipagebuilder/page/PagePreviewIsolationTest.java +++ b/src/test/java/run/halo/aipagebuilder/page/PagePreviewIsolationTest.java @@ -11,6 +11,7 @@ import java.util.Base64; import java.util.List; import java.util.Map; +import java.util.stream.IntStream; import org.jsoup.Jsoup; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -44,6 +45,102 @@ class PagePreviewIsolationTest { private final PageDocument document = new PageDocument(2, "code", null, null, "

中文页面

", "p {color: red}", "window.executed = true"); + @ParameterizedTest + @ValueSource( + strings = { + "%s", + "x%s", + "%s", + "%s", + "%s", + "%s" + }) + void ordinaryPreviewPreservesWhitespaceAndMarkupWhenInsertingPolicy(String template) { + var exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://example.test/pages/one/preview")); + var request = ServerRequest.create(exchange, strategies.messageReaders()); + when(templates.resolveTemplateNameOrDefault(any(), any())).thenReturn(Mono.just("test")); + var content = new PageDocument( + 2, "code", null, null, "
A B\n C
\n\n中文
", ""); + var response = previews.render(request, "one", "about", true, content, "About", "") + .block(); + var page = + (PageRenderer.PageView) ((PagePreviewResponse) response).model().get("aiPageBuilder"); + var original = template.formatted(page.html()); + response.writeTo(exchange, context(new View() { + @Override + public Mono render(Map model, MediaType type, ServerWebExchange incoming) { + return incoming.getResponse() + .writeWith(Mono.just(incoming.getResponse() + .bufferFactory() + .wrap(original.getBytes(StandardCharsets.UTF_8)))); + } + })) + .block(); + + var html = exchange.getResponse().getBodyAsString().block(); + var parsed = Jsoup.parse(html); + var meta = parsed.head().child(0); + assertThat(meta.attr("http-equiv")).isEqualTo("Content-Security-Policy"); + assertThat(html.replace(meta.outerHtml(), "")).isEqualTo(original); + assertThat(parsed.selectFirst("div").wholeText()).isEqualTo("A B\n C"); + assertThat(parsed.selectFirst("pre").wholeText()).isEqualTo("\n中文"); + if (html.contains("" + + "中文页面"; + var buffer = incoming.getResponse().bufferFactory().wrap(html.getBytes(StandardCharsets.UTF_8)); + return incoming.getResponse().writeAndFlushWith(Mono.just(Mono.just(buffer))); + } + })) + .block(); + + var headers = exchange.getResponse().getHeaders(); + assertThat(headers.toString().getBytes(StandardCharsets.UTF_8).length).isLessThan(1024); + assertThat(headers.getFirst("Content-Security-Policy")).isEqualTo("sandbox allow-scripts"); + var html = exchange.getResponse().getBodyAsString().block(); + assertThat(headers.getContentLength()).isEqualTo(html.getBytes(StandardCharsets.UTF_8).length); + var parsed = Jsoup.parse(html); + assertThat(parsed.head().child(0).attr("http-equiv")).isEqualTo("Content-Security-Policy"); + var policy = parsed.head().child(0).attr("content"); + assertThat(policy.length()).isGreaterThan(16 * 1024); + for (var path : paths) { + assertThat(policy).contains("https://example.test" + path); + } + assertThat(policy).doesNotContain("sandbox", "connect-src *", "allow-same-origin"); + if (token) { + var source = parsed.selectFirst("iframe").attr("src").split(",", 2)[1]; + parsed = Jsoup.parse(new String(Base64.getDecoder().decode(source), StandardCharsets.UTF_8)); + assertThat(parsed.head().child(0).attr("http-equiv")).isEqualTo("Content-Security-Policy"); + for (var path : paths) { + assertThat(parsed.head().child(0).attr("content")).contains("https://example.test" + path); + } + } + assertThat(parsed.selectFirst("script")).isNotNull(); + assertThat(parsed.body().text()).contains("中文页面"); + } + @ParameterizedTest @ValueSource(strings = {"", "/site"}) void tokenPreviewIsolatesRealRenderingAndIncrementalWrites(String prefix) { @@ -114,7 +211,13 @@ public Mono render(Map model, MediaType type, ServerWebExchange .doesNotContain("sandbox", "frame-src data:", "allow-same-origin"); assertThat(exchange.getResponse().getHeaders().getFirst("Content-Security-Policy")) .isEqualTo(expectedPolicy) - .contains("sandbox allow-scripts", "base-uri " + safeUri, "frame-src data:"); + .isEqualTo("sandbox allow-scripts"); + assertThat(host.head().child(0).attr("http-equiv")).isEqualTo("Content-Security-Policy"); + assertThat(host.head().child(0).attr("content")) + .contains( + "base-uri " + safeUri, + "frame-src data:", + "connect-src https://example.test" + prefix + "/apis/api.content.halo.run/"); assertThat(exchange.getResponse().getHeaders().getCacheControl()).isEqualTo("no-store"); assertThat(exchange.getResponse().getHeaders().getContentLength()) .isEqualTo(hostHtml.getBytes(StandardCharsets.UTF_8).length); @@ -135,7 +238,8 @@ void ordinaryPreviewWritesItsPolicyWithoutChangingTheRenderingRequest(boolean la response.writeTo(exchange, context(new View() { @Override public Mono render(Map model, MediaType type, ServerWebExchange incoming) { - assertThat(incoming).isSameAs(exchange); + assertThat(incoming.getRequest()).isSameAs(exchange.getRequest()); + assertThat(incoming.getAttributes()).isSameAs(exchange.getAttributes()); var page = (PageRenderer.PageView) model.get("aiPageBuilder"); return incoming.getResponse() .writeWith(Mono.just(incoming.getResponse() @@ -149,8 +253,11 @@ public Mono render(Map model, MediaType type, ServerWebExchange .doesNotContain(" assertThat(value) - .contains("sandbox allow-scripts", "frame-src data:", "connect-src 'none'")) + .value("Content-Security-Policy", value -> assertThat(value).isEqualTo("sandbox allow-scripts")) .expectBody(String.class) - .value(body -> - assertThat(body).contains(" assertThat(body) + .contains( + "