Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions src/main/java/run/halo/aipagebuilder/page/PagePreview.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ public Mono<ServerResponse> 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<ServerResponse> token(
Expand All @@ -56,9 +57,9 @@ public Mono<ServerResponse> 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)));
});
});
}
Expand Down Expand Up @@ -107,11 +108,11 @@ private List<String> 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) {
Expand Down
67 changes: 51 additions & 16 deletions src/main/java/run/halo/aipagebuilder/page/PagePreviewResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<String, Object> model() {
return delegate.model();
}

static ServerRequest withoutCredential(ServerRequest request) {
var uri = UriComponentsBuilder.fromUri(request.uri())
.replacePath(request.requestPath().contextPath().value() + "/")
Expand Down Expand Up @@ -83,7 +100,7 @@ public Mono<Void> writeWith(Publisher<? extends DataBuffer> 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)));
});
Expand All @@ -95,23 +112,41 @@ public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends Data
}
};
// View rendering happens in writeTo, so sanitizing only ServerRequest is insufficient.
return delegate.writeTo(
withoutCredential(exchange, documentUri)
.mutate()
.response(response)
.build(),
context);
var renderingExchange = documentUri == null ? exchange : withoutCredential(exchange, documentUri);
return delegate.writeTo(renderingExchange.mutate().response(response).build(), context);
}

private String render(String html) {
if (documentUri != null) {
var document = host(html, documentUri, childPolicy);
prependPolicy(document, policy);
return document.outerHtml();
}
// Locate the real head without reserializing theme markup: another DOM roundtrip
// collapses CSS-preserved whitespace and consumes a leading newline in <pre>.
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));
Expand All @@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -44,6 +45,102 @@ class PagePreviewIsolationTest {
private final PageDocument document =
new PageDocument(2, "code", null, null, "<p>中文页面</p>", "p {color: red}", "window.executed = true");

@ParameterizedTest
@ValueSource(
strings = {
"<!doctype html><html><head><script>theme()</script></head><body>%s</body></html>",
"<!-- example <head> --><html><HEAD data-label='a > b'><title>x</title></HEAD><body>%s</body></html>",
"<html data-example='<head>'><head></head><body>%s</body></html>",
"<!doctype html><html><body>%s</body></html>",
"<script>var example = '<head>'</script>%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, "<div style='white-space:pre-wrap'>A B\n C</div><pre>\n\n中文</pre>", "");
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<Void> render(Map<String, ?> 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("<script>")) {
assertThat(html.indexOf(meta.outerHtml())).isLessThan(html.indexOf("<script>"));
}
assertThat(exchange.getResponse().getHeaders().getContentLength())
.isEqualTo(html.getBytes(StandardCharsets.UTF_8).length);
}

@ParameterizedTest
@ValueSource(booleans = {true, false})
void largeApiCatalogKeepsHeadersSmallAndEnforcesEveryPathInTheDocument(boolean token) {
var exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://example.test/pages/one/preview"));
var request = ServerRequest.create(exchange, strategies.messageReaders());
var paths = IntStream.range(0, 300)
.mapToObj(index -> "/apis/api.plugin-" + index + ".halo.run/v1alpha1/items/")
.toList();
when(catalog.publicPathPrefixes()).thenReturn(paths);
when(templates.resolveTemplateNameOrDefault(any(), any())).thenReturn(Mono.just("test"));
var response = (token
? previews.token(request, "one", "about", true, document, "About", "")
: previews.render(request, "one", "about", true, document, "About", ""))
.block();
response.writeTo(exchange, context(new View() {
@Override
public Mono<Void> render(Map<String, ?> model, MediaType type, ServerWebExchange incoming) {
var html = "<!doctype html><html><head><script>window.theme = true</script>"
+ "<link rel='stylesheet' href='/theme.css'></head><body>中文页面</body></html>";
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) {
Expand Down Expand Up @@ -114,7 +211,13 @@ public Mono<Void> render(Map<String, ?> 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);
Expand All @@ -135,7 +238,8 @@ void ordinaryPreviewWritesItsPolicyWithoutChangingTheRenderingRequest(boolean la
response.writeTo(exchange, context(new View() {
@Override
public Mono<Void> render(Map<String, ?> 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()
Expand All @@ -149,8 +253,11 @@ public Mono<Void> render(Map<String, ?> model, MediaType type, ServerWebExchange
.doesNotContain("<iframe");
assertThat(exchange.getResponse().getHeaders().getFirst("Content-Security-Policy"))
.isEqualTo(response.headers().getFirst("Content-Security-Policy"))
.isEqualTo("sandbox allow-scripts");
var html = Jsoup.parse(exchange.getResponse().getBodyAsString().block());
assertThat(html.head().child(0).attr("http-equiv")).isEqualTo("Content-Security-Policy");
assertThat(html.head().child(0).attr("content"))
.contains(
"sandbox allow-scripts",
"connect-src https://example.test/rss.xml https://example.test/feed.xml "
+ "https://example.test/sitemap.xml https://example.test/feed/",
"base-uri 'none'",
Expand Down
Loading
Loading