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
20 changes: 18 additions & 2 deletions src/main/java/run/halo/aipagebuilder/page/PagePreview.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.net.URI;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RenderingResponse;
import org.springframework.web.reactive.function.server.ServerRequest;
Expand Down Expand Up @@ -52,8 +53,12 @@ private Policy policy(ServerRequest request) {
// Resources resolve against the origin actually serving the preview, which can
// differ from the configured external URL used for public links.
var base = origins.servingOrigin(request);
var sources = base == null ? List.<String>of()
: allowedPrefixes().stream().map(prefix -> base + prefix).distinct().toList();
// Public paths live below the context path, so every source must name it too.
var origin = scopedOrigin(base, request.requestPath().contextPath().value());
var paths = Stream.concat(allowedPrefixes().stream(), PreviewPublicPaths.ALL.stream())
.toList();
var sources = origin == null ? List.<String>of()
: paths.stream().map(prefix -> origin + prefix).distinct().toList();
// A trailing slash also allows resources below a configured deployment sub-path.
var resourceSources = base == null ? "'unsafe-inline'" : base + "/ 'unsafe-inline'";
var connectSources = sources.isEmpty() ? "'none'" : String.join(" ", sources);
Expand All @@ -64,6 +69,17 @@ private Policy policy(ServerRequest request) {
+ "; connect-src " + connectSources);
}

/** Adds the deployment path the preview document is served under. */
private static String scopedOrigin(String base, String contextPath) {
if (base == null || contextPath.isEmpty()) {
return base;
}
// The external URL fallback may already carry the configured path. Compare the
// suffix as plain text so a malformed authority or path cannot throw here.
var path = base.indexOf('/', base.indexOf("://") + 3);
return contextPath.equals(path < 0 ? "" : base.substring(path)) ? base : base + contextPath;
}

private List<String> allowedPrefixes() {
try {
return publicApiCatalog.publicPathPrefixes();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import java.util.HashMap;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Element;
import org.reactivestreams.Publisher;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
Expand Down Expand Up @@ -100,9 +102,14 @@ public Mono<Void> writeAndFlushWith(
private static String host(String html, URI base, String policy) {
var child = Jsoup.parse(html);
child.select("base").remove();
child.head().prependElement("base").attr("href", base.toASCIIString());
var baseElement = child.head().prependElement("base");
baseElement.attr("href", base.toASCIIString());
child.head().prependElement("meta").attr("http-equiv", "Content-Security-Policy")
.attr("content", 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));
baseElement.after(shim);
var source = Base64.getEncoder().encodeToString(
child.outerHtml().getBytes(StandardCharsets.UTF_8));
var host = Jsoup.parse("<!doctype html><html><head><meta charset='utf-8'>"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@

/**
* Sandboxed previews run in an opaque origin, so the theme CSS, module scripts and fonts they
* reference are cross-origin CORS requests. Those assets are public, so allow every origin
* without granting the preview page same-origin access to the site. The response must not
* depend on the request Origin: shared caches ignore {@code Vary: Origin}, and a cached
* no-CORS copy would keep breaking the preview.
* reference, as well as the feeds their widgets fetch, are cross-origin requests. Those
* resources are public, so allow every origin without granting the preview page same-origin
* access to the site. The response must not depend on the request Origin: shared caches ignore
* {@code Vary: Origin}, and a cached no-CORS copy would keep breaking the preview.
*/
@Component
public class PreviewAssetCorsFilter implements AdditionalWebFilter {
Expand All @@ -22,7 +22,8 @@ public class PreviewAssetCorsFilter implements AdditionalWebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
var path = exchange.getRequest().getPath().pathWithinApplication().value();
if (ASSET_PREFIXES.stream().anyMatch(path::startsWith)) {
if (ASSET_PREFIXES.stream().anyMatch(path::startsWith)
|| PreviewPublicPaths.matches(path)) {
exchange.getResponse().getHeaders()
.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
}
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/run/halo/aipagebuilder/page/PreviewPublicPaths.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package run.halo.aipagebuilder.page;

import java.util.List;

/** Public site documents that sandboxed theme widgets may fetch. */
final class PreviewPublicPaths {
static final List<String> ALL = List.of("/rss.xml", "/feed.xml", "/sitemap.xml", "/feed/");

private PreviewPublicPaths() {
}

static boolean matches(String path) {
return ALL.stream().anyMatch(publicPath -> publicPath.endsWith("/")
? path.startsWith(publicPath) : path.equals(publicPath));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package run.halo.aipagebuilder.page;

import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import org.reactivestreams.Publisher;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import run.halo.app.security.AdditionalWebFilter;

/**
* Injects the preview storage shim into rendered preview documents. The document body is
* produced by the theme view, so it is rewritten here rather than in the renderer. Only HTML
* responses for the two preview routes are touched; errors and other routes pass through.
*/
@Component
public class PreviewStorageFilter implements AdditionalWebFilter {
private static final Pattern PATH = Pattern.compile(
"/apis/console\\.api\\.aipagebuilder\\.halo\\.run/v1alpha1/pages/[^/]+/"
+ "(?:revisions/[^/]+/)?preview");

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
var request = exchange.getRequest();
var path = request.getPath().pathWithinApplication().value();
if (!HttpMethod.GET.equals(request.getMethod()) || !PATH.matcher(path).matches()) {
return chain.filter(exchange);
}
return chain.filter(exchange.mutate()
.response(new InjectingResponse(exchange.getResponse())).build());
}

private static final class InjectingResponse extends ServerHttpResponseDecorator {
InjectingResponse(ServerHttpResponse delegate) {
super(delegate);
}

@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
return DataBufferUtils.join(body).flatMap(buffer -> {
var type = getHeaders().getContentType();
if (buffer.readableByteCount() == 0 || type == null
|| !MediaType.TEXT_HTML.isCompatibleWith(type)) {
return super.writeWith(Mono.just(buffer));
}
final String html;
try {
html = buffer.toString(StandardCharsets.UTF_8);
} finally {
DataBufferUtils.release(buffer);
}
var bytes = PreviewStorageShim.inject(html).getBytes(StandardCharsets.UTF_8);
getHeaders().setContentLength(bytes.length);
return super.writeWith(Mono.just(bufferFactory().wrap(bytes)));
});
}

@Override
public Mono<Void> writeAndFlushWith(
Publisher<? extends Publisher<? extends DataBuffer>> body) {
return writeWith(Flux.from(body).concatMap(Flux::from));
}
}
}
162 changes: 162 additions & 0 deletions src/main/java/run/halo/aipagebuilder/page/PreviewStorageShim.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package run.halo.aipagebuilder.page;

import java.util.regex.Pattern;

/**
* Replaces storage APIs that a sandboxed preview cannot reach. A sandboxed document has an
* opaque origin, so reading {@code localStorage}, {@code sessionStorage} or
* {@code document.cookie} throws a SecurityError. Themes read them while starting, and an
* unguarded access aborts the rest of their scripts. The shim keeps the synchronous API
* backed by memory, so values live only for the current preview document.
*/
final class PreviewStorageShim {
// Comments are matched so a literal "<head>" inside one cannot capture the shim, and
// quoted attribute values may contain ">" without ending the tag early. Possessive
// quantifiers keep long attributes from recursing the matcher into a StackOverflowError.
private static final Pattern HEAD = Pattern.compile(
"<!--.*?-->|<head(?:\\s(?:[^>\"']++|\"[^\"]*+\"|'[^']*+')*+)?>",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private static final Pattern DOCTYPE =
Pattern.compile("<!doctype[^>]*>", Pattern.CASE_INSENSITIVE);

static final String BODY = """
(function () {
function memory() {
var data = new Map();
var api = {
getItem: function (key) {
key = String(key);
return data.has(key) ? data.get(key) : null;
},
setItem: function (key, value) {
data.set(String(key), String(value));
},
removeItem: function (key) {
data.delete(String(key));
},
clear: function () {
data.clear();
},
key: function (index) {
// Web Storage converts the argument to an unsigned long before indexing.
index = +index >>> 0;
var keys = Array.from(data.keys());
return index < keys.length ? keys[index] : null;
}
};
Object.defineProperty(api, 'length', {
get: function () { return data.size; },
configurable: true
});
return new Proxy(api, {
get: function (target, prop) {
if (typeof prop === 'symbol') return target[prop];
if (prop in target) return target[prop];
// A missing item reads as undefined, like native storage; getItem keeps null.
return data.has(String(prop)) ? data.get(String(prop)) : undefined;
},
set: function (target, prop, value) {
api.setItem(prop, value);
return true;
},
has: function (target, prop) {
if (typeof prop === 'symbol') return prop in target;
return prop in target || data.has(String(prop));
},
deleteProperty: function (target, prop) {
if (typeof prop !== 'symbol') api.removeItem(prop);
return true;
},
ownKeys: function () { return Array.from(data.keys()); },
getOwnPropertyDescriptor: function (target, prop) {
if (typeof prop === 'symbol') return undefined;
if (prop in target) return Object.getOwnPropertyDescriptor(target, prop);
if (!data.has(String(prop))) return undefined;
return {
value: api.getItem(prop),
writable: true,
enumerable: true,
configurable: true
};
}
});
}
['localStorage', 'sessionStorage'].forEach(function (name) {
try {
if (window[name]) return;
} catch (error) {
// The sandbox rejects access; install the in-memory replacement below.
}
try {
Object.defineProperty(window, name, { value: memory(), configurable: true });
} catch (error) {
// Leave the native error in place when the property cannot be replaced.
}
});
try {
void document.cookie;
} catch (error) {
Comment thread
ruibaby marked this conversation as resolved.
Resolved
var jar = Object.create(null);
Object.defineProperty(document, 'cookie', {
configurable: true,
get: function () {
return Object.keys(jar).map(function (key) {
return key + '=' + jar[key];
}).join('; ');
},
set: function (value) {
var parts = String(value).split(';');
var pair = parts.shift();
var index = pair.indexOf('=');
if (index <= 0) return;
var name = pair.slice(0, index).trim();
// A past expiry deletes the cookie, as it would in a real jar. Max-Age wins
// over Expires, and an attribute that does not parse is ignored.
var maxAge = null;
var expires = null;
parts.forEach(function (attribute) {
var at = attribute.indexOf('=');
var key = (at < 0 ? attribute : attribute.slice(0, at)).trim().toLowerCase();
var raw = at < 0 ? '' : attribute.slice(at + 1).trim();
if (key === 'max-age' && /^-?\\d+$/.test(raw)) maxAge = Number(raw);
if (key === 'expires') {
var parsed = Date.parse(raw);
// Keep an earlier valid date when a repeated attribute does not parse.
if (!isNaN(parsed)) expires = parsed;
}
});
var expired = maxAge !== null ? maxAge <= 0
: expires !== null && expires < Date.now();
if (expired) delete jar[name];
else jar[name] = pair.slice(index + 1).trim();
}
});
}
})();
""";

private PreviewStorageShim() {
}

static String script() {
return "<script data-ai-page-builder=\"preview-storage\">" + BODY + "</script>";
}

/** Inserts the shim as early as possible without reserializing the rest of the page. */
static String inject(String html) {
var head = HEAD.matcher(html);
while (head.find()) {
if (head.group().startsWith("<!--")) {
continue;
}
return insertAt(html, head.end());
}
// Keep the doctype first so a document without <head> stays in standards mode.
var doctype = DOCTYPE.matcher(html);
return insertAt(html, doctype.find() ? doctype.end() : 0);
}

private static String insertAt(String html, int index) {
return html.substring(0, index) + script() + html.substring(index);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,10 @@ void candidatePreviewUsesSameThemeAndCssAsGetWithoutSaving() {
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 'none'").doesNotContain("allow-same-origin");
.contains("sandbox allow-scripts",
"connect-src http://localhost/rss.xml http://localhost/feed.xml "
+ "http://localhost/sitemap.xml http://localhost/feed/")
.doesNotContain("allow-same-origin");
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 @@ -102,10 +102,13 @@ public Mono<Void> render(Map<String, ?> model, MediaType type,
.doesNotContain(token, "wrong.test");
var child = Jsoup.parse(childHtml);
assertThat(child.select("base")).hasSize(1);
// The storage shim must precede every theme script in the opaque-origin document.
assertThat(child.selectFirst("script").attr("data-ai-page-builder"))
.isEqualTo("preview-storage");
var childPolicy = child.selectFirst("meta[http-equiv=Content-Security-Policy]")
.attr("content");
assertThat(childPolicy).contains("base-uri " + safeUri, "frame-src 'none'",
"connect-src https://example.test/apis/api.content.halo.run/")
"connect-src https://example.test" + prefix + "/apis/api.content.halo.run/")
.doesNotContain("sandbox", "frame-src data:", "allow-same-origin");
assertThat(exchange.getResponse().getHeaders().getFirst("Content-Security-Policy"))
.isEqualTo(expectedPolicy)
Expand Down Expand Up @@ -142,8 +145,11 @@ public Mono<Void> render(Map<String, ?> model, MediaType type,
.doesNotContain("<iframe");
assertThat(exchange.getResponse().getHeaders().getFirst("Content-Security-Policy"))
.isEqualTo(response.headers().getFirst("Content-Security-Policy"))
.contains("sandbox allow-scripts", "connect-src 'none'", "base-uri 'none'",
"frame-src 'none'").doesNotContain("allow-same-origin");
.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'", "frame-src 'none'")
.doesNotContain("allow-same-origin", "/apis/");
}

private static void assertClean(ServerWebExchange exchange, URI uri) {
Expand Down
Loading
Loading