001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.console.freemarker; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020 021import java.io.*; 022import java.util.*; 023import java.util.logging.*; 024import java.util.regex.*; 025 026import org.apache.juneau.rest.server.*; 027import org.apache.juneau.console.*; 028import org.apache.juneau.console.views.*; 029import org.apache.juneau.rest.server.filter.*; 030import org.apache.juneau.rest.server.view.freemarker.*; 031 032import freemarker.core.*; 033import freemarker.template.*; 034 035/** 036 * The {@code <@console>} document-shell FreeMarker directive. 037 * 038 * <p> 039 * Renders its body into the per-render {@link PageCapture} (theme, navigation, header/footer slots, the banner region 040 * before {@code <@main/>}), then writes the document: the server-rendered {@code <head>}, the {@code <body>} tag, the 041 * {@code #juneau-page} contract island, one {@code <template>} per markup body, the {@code juneau-console.js} shell, 042 * and the server-emitted scripts. The shell renders the header, nav, cards and footer from the contract. 043 * 044 * <h2 class='section'>Example:</h2> 045 * <p class='bcode'> 046 * <@console brand="Release Manager" icon="/app/logo.svg" title="Releases"> 047 * <@navigation> 048 * <@node id="home" label="Home" href="/home"/> 049 * </@navigation> 050 * <@main/> 051 * <@footer text="ACME"/> 052 * </@console> 053 * </p> 054 * 055 * @since 10.0.0 056 */ 057@SuppressWarnings({ 058 "java:S1192" // Duplicated literals read more clearly inline than as constants 059}) 060public final class ConsoleDirectiveModel implements TemplateDirectiveModel { 061 062 /** The shared-variable name this directive registers under. */ 063 public static final String NAME = "console"; 064 065 private static final Logger LOG = Logger.getLogger(ConsoleDirectiveModel.class.getName()); 066 067 static final Set<String> ATTRS = Set.of("theme", "icon", "favicon", "brand", "title", "chrome", "facts", "scheme", "schemeToggle", "themeSelector"); 068 069 private final boolean devMode; 070 private final CardTypeRegistry cardTypes; 071 private final ToolkitPackRegistry packs; 072 073 ConsoleDirectiveModel(boolean devMode, CardTypeRegistry cardTypes, ToolkitPackRegistry packs) { 074 this.devMode = devMode; 075 this.cardTypes = cardTypes; 076 this.packs = packs; 077 } 078 079 @Override 080 @SuppressWarnings({ 081 "java:S3776", // Attribute validation and document emission read best as one straight-line method. 082 "resource", // FreeMarker owns env.getOut(); closing it would close the HTTP response. 083 "unchecked" // FreeMarker's raw params Map is String-keyed by contract. 084 }) 085 public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, 086 TemplateDirectiveBody body) throws TemplateException, IOException { 087 Map<String, TemplateModel> p = params; 088 if (p.containsKey("format")) 089 throw FtlAttrLists.reject("<@console> has no format= attribute."); 090 FtlAttrLists.rejectUnknown(p, NAME, ATTRS); 091 092 var req = FreemarkerRenderScope.request(); 093 if (n(req)) 094 throw FtlAttrLists.reject("<@console> needs FreemarkerRenderScope.request() (renderer wrap)."); 095 096 var cap = PageCapture.of(env); 097 if (cap.consoleOpen || cap.consoleDone) 098 throw FtlAttrLists.reject("<@console> cannot be nested inside another <@console>."); 099 100 // Fail-closed validate an explicit theme= attribute up front; a nested <@theme> (or, absent both, a theme seeded 101 // by a page spec) decides the final name below. 102 var themeAttr = FtlAttrLists.scalar(p, "theme"); 103 if (! themeAttr.isEmpty() && ! ConsoleChromeMixin.BUILTIN_THEME_NAMES.contains(themeAttr)) 104 throw FtlAttrLists.reject("<@console> unknown theme name '" + themeAttr + "'. Built-in themes: " 105 + String.join(", ", ConsoleChromeMixin.BUILTIN_THEME_NAMES) + "."); 106 107 // Colour scheme: an explicit attribute wins over a page-spec value, which wins over the default. 108 var schemeAttr = FtlAttrLists.scalar(p, "scheme"); 109 if (! schemeAttr.isEmpty() && ! ConsoleChromeMixin.SCHEMES.contains(schemeAttr)) 110 throw FtlAttrLists.reject("<@console> unknown scheme '" + schemeAttr + "'. Schemes: " 111 + String.join(", ", ConsoleChromeMixin.SCHEMES) + "."); 112 var capScheme = nn(cap.scheme()) ? cap.scheme() : ConsoleChromeMixin.SCHEMES.get(0); 113 var scheme = schemeAttr.isEmpty() ? capScheme : schemeAttr; 114 var schemeToggle = FtlAttrLists.strictBoolean(p, NAME, "schemeToggle", cap.schemeToggle()); 115 var themeSelector = FtlAttrLists.strictBoolean(p, NAME, "themeSelector", cap.themeSelector()); 116 117 var icon = FtlAttrLists.scalar(p, "icon"); 118 var favicon = FtlAttrLists.scalar(p, "favicon"); 119 var iconSymbol = symbolName("icon", icon); 120 var faviconSymbol = symbolName("favicon", favicon); 121 if (nn(faviconSymbol)) 122 favicon = req.getUriResolver().resolve("servlet:" + ViewsMixin.SYMBOL_SVG_PATH.replace("{file}", faviconSymbol + ".svg")); 123 var faviconHref = favicon; 124 var brand = FtlAttrLists.scalar(p, "brand"); 125 var titleAttr = FtlAttrLists.scalar(p, "title"); 126 var chrome = FtlAttrLists.strictBoolean(p, NAME, "chrome", false); 127 var factsAttr = FtlAttrLists.map(p, NAME, "facts"); 128 129 // Document <title>: a title seeded by a page spec wins; else the title= attribute, else brand=; omitted when none. 130 var docTitle = titleAttr.isEmpty() ? brand : titleAttr; 131 cap.titleDefault(docTitle); 132 cap.header(h -> { 133 if (! brand.isEmpty()) 134 h.title(brand); 135 if (nn(iconSymbol)) 136 h.logoSymbol(iconSymbol, req.getUriResolver().resolve("context:/"), brand.isEmpty() ? null : brand); 137 else if (! icon.isEmpty()) 138 h.logo(icon, req.getUriResolver().resolve("context:/"), brand.isEmpty() ? null : brand); 139 h.chrome(chrome); 140 }); 141 142 // Chrome-side facts: last-wins against <@facts>; the one strict check against PageSpec.facts runs at </@console>. 143 if (! factsAttr.isEmpty()) 144 cap.mergeChromeFacts(factsAttr); 145 146 cap.consoleTheme = themeAttr.isEmpty() ? null : themeAttr; 147 cap.consoleOpen = true; 148 try { 149 if (nn(body)) 150 body.render(cap.consoleBuffer()); 151 } finally { 152 cap.consoleOpen = false; 153 } 154 cap.checkConsoleClose(); 155 try { 156 cap.checkWiring(cardTypes); 157 } catch (IllegalArgumentException e) { 158 throw FtlAttrLists.reject(e.getMessage()); 159 } 160 cap.resolveActiveNav(); 161 162 // A page that never reached <@page> (a PageSpec rendered straight through the chrome) has not had its seeded 163 // toolkits and card-required packs resolved yet; <@page> does it itself, so never twice. 164 // The guard is a pure optimisation: toolkitAssets overwrites, and nothing after <@page> can change its inputs 165 // (<@card> is only legal inside <@page>), so a second resolve would be identical and no test can observe it. 166 if (! cap.assetsResolved()) 167 PageDirectiveModel.resolveAssets(env, cap, packs); 168 169 if (n(cap.themeCssUrl)) { 170 // No <@theme> ran: an explicit theme= wins, else a theme seeded by a page spec is inherited, else the default. 171 var themeName = themeAttr.isEmpty() ? cap.themeOrNull() : themeAttr; 172 if (themeName == null) 173 themeName = ConsoleChromeMixin.BUILTIN_THEME_NAMES.get(0); 174 cap.themeCssUrl = ConsoleChromeMixin.themeAssetUrl(req, themeName); 175 cap.theme(themeName); 176 } 177 178 // Each embed asks for its own value, so a masking boundary never repeats the same masked token in one page. 179 var metaToken = csrfToken(req); 180 var bodyToken = csrfToken(req); 181 var csrfHeader = req.getAttribute(RequestBoundaryFilter.HEADER_ATTRIBUTE).asString().orElse(null); 182 var hasCsrf = inb(metaToken) && inb(bodyToken); 183 184 // A page that carries a token must not be cached, and the header has to be set before any of the body is 185 // written. A response that is already committed can no longer be marked, so it never carries the token: both 186 // automatic embeds and any spec- or <@body>-authored csrf attributes are dropped, and the page's own writes then 187 // fail visibly instead of leaking the secret. 188 var bodyAttrs = cap.bodyAttrs; 189 if (req.getResponse().getHttpServletResponse().isCommitted()) { 190 var omitted = hasCsrf; 191 hasCsrf = false; 192 bodyAttrs = cap.bodyAttrsWithout("data-juneau-csrf", "data-juneau-csrf-header"); 193 if (bodyAttrs != null && ! bodyAttrs.equals(cap.bodyAttrs.strip())) 194 omitted = true; 195 if (omitted) 196 LOG.fine("Response already committed; the CSRF token is not embedded in the page."); 197 } else if (hasCsrf || cap.hasBodyAttr("data-juneau-csrf")) { 198 RequestBoundaryFilter.markTokenBearing(req.getResponse().getHttpServletResponse()); 199 } 200 201 if (devMode) { 202 var findings = PageContractSchema.get().validate(cap.toContractJson(), cap.templates().keySet()); 203 if (! findings.isEmpty()) 204 throw FtlAttrLists.reject(f("Page contract failed schema validation: '%s'.", String.join("; ", findings))); 205 } 206 207 if (cap.allowInlineHandlers()) 208 checkInlineCsp(req); 209 addFrameAncestors(req); 210 211 var out = env.getOut(); 212 var nonce = req.getAttribute(RestRequest.CSP_NONCE_ATTR).as(String.class).orElse(null); 213 var htmlAttrs = ConsoleChromeMixin.schemeHtmlAttributes(scheme, schemeToggle); 214 if (themeSelector) 215 htmlAttrs += (htmlAttrs.isEmpty() ? "" : " ") + ConsoleChromeMixin.themeSelectorHtmlAttributes(); 216 out.write("<!DOCTYPE html>\n<html lang=\"en\"" + (htmlAttrs.isEmpty() ? "" : " " + htmlAttrs) + ">\n<head>\n"); 217 // The pre-paint scheme script runs before any stylesheet so the first paint already has the right scheme. 218 out.write(ConsoleChromeMixin.schemeScriptElement(nonce) + "\n"); 219 out.write("<meta charset=\"utf-8\">\n"); 220 out.write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"); 221 if (! cap.title().isEmpty()) 222 out.write("<title>" + attrEscape(cap.title()) + "</title>\n"); 223 if (! cap.tab().isEmpty()) 224 out.write("<meta name=\"page-tab\" content=\"" + attrEscape(cap.tab()) + "\">\n"); 225 if (hasCsrf) 226 out.write("<meta name=\"csrf-token\" content=\"" + attrEscape(metaToken) + "\">\n"); 227 if (! faviconHref.isEmpty()) 228 out.write("<link rel=\"icon\" href=\"" + attrEscape(faviconHref) + "\">\n"); 229 out.write("<link rel=\"stylesheet\" href=\"" + attrEscape(ConsoleChromeMixin.chromeCssUrl(req)) + "\">\n"); 230 out.write("<link rel=\"stylesheet\" href=\"" + attrEscape(ConsoleChromeMixin.themeAssetUrl(req, "dark")) + "\">\n"); 231 out.write("<link rel=\"stylesheet\" href=\"" + attrEscape(cap.themeCssUrl) + "\"" + (themeSelector ? " data-jc-theme-link" : "") + ">\n"); 232 if (nn(cap.themeOverrideBlock)) 233 out.write("<style" + ConsoleChromeMixin.nonceAttr(nonce) + ">" + cap.themeOverrideBlock + "</style>\n"); 234 // App CSS that must lose to page-local css=: emitted BEFORE the page css so a page rule still wins. 235 if (nn(cap.headBeforePageCss)) 236 out.write(cap.headBeforePageCss); 237 for (var href : cap.vendorCss()) 238 out.write("<link rel=\"stylesheet\" href=\"" + attrEscape(href) + "\" data-toolkit-css>\n"); 239 for (var href : cap.cssHrefs()) 240 out.write("<link rel=\"stylesheet\" href=\"" + attrEscape(resolveAsset(req, href)) + "\">\n"); 241 for (var href : cap.runtimeCss()) 242 out.write("<link rel=\"stylesheet\" href=\"" + attrEscape(href) + "\" data-toolkit-css>\n"); 243 if (nn(cap.head)) 244 out.write(cap.head); 245 out.write("\n</head>\n"); 246 247 out.write("<body"); 248 // A spec- or <@body>-authored csrf attribute (merged by checkConsoleClose above) wins over the auto-detection. 249 // Either name suppresses both auto attributes, so a token and its header never come from different sources. 250 if (hasCsrf && ! cap.hasBodyAttr("data-juneau-csrf") && ! cap.hasBodyAttr("data-juneau-csrf-header")) { 251 out.write(" data-juneau-csrf=\"" + attrEscape(bodyToken) + "\""); 252 if (inb(csrfHeader)) 253 out.write(" data-juneau-csrf-header=\"" + attrEscape(csrfHeader) + "\""); 254 } 255 if (inb(bodyAttrs)) 256 out.write(" " + bodyAttrs.trim()); 257 out.write(">\n"); 258 259 cap.shellUrl(ConsoleChromeMixin.consoleJsUrl(req)); 260 cap.writeBody(out); 261 out.write("\n"); 262 263 for (var src : cap.vendorJs()) 264 out.write("<script src=\"" + attrEscape(src) + "\" data-toolkit-js></script>\n"); 265 for (var src : cap.runtimeJs()) 266 out.write("<script src=\"" + attrEscape(src) + "\" data-toolkit-js></script>\n"); 267 // The inline-handler compiler is the one script that compiles strings; it is not in any pack and is emitted 268 // only for a page that opted in, after the runtime pack (which holds the model it plugs into). 269 if (cap.allowInlineHandlers()) 270 out.write("<script" + ConsoleChromeMixin.nonceAttr(nonce) + " src=\"" + attrEscape(ViewsMixin.viewAssetUrl(req, ViewsMixin.MODEL_INLINE_JS_PATH)) + "\" data-toolkit-js></script>\n"); 271 // The badge runtime mounts header.badges from the contract on load. Not a toolkit pack: a chrome-template 272 // <@badge> is only known here, after the page's packs were resolved. 273 if (cap.hasBadges()) 274 out.write("<script src=\"" + attrEscape(ConsoleChromeMixin.badgesJsUrl(req)) + "\" data-toolkit-js></script>\n"); 275 // App scripts that must run after the toolkit pack but before the page-local init= scripts. 276 if (nn(cap.scriptsAfterToolkit)) 277 out.write(cap.scriptsAfterToolkit); 278 for (var src : cap.initScripts()) 279 out.write("<script src=\"" + attrEscape(resolveAsset(req, src)) + "\"></script>\n"); 280 if (nn(cap.scripts)) 281 out.write(cap.scripts); 282 out.write("\n</body>\n</html>\n"); 283 cap.consoleDone = true; 284 } 285 286 /** 287 * One CSRF token value for one embed, or <jk>null</jk> when the request carries none. 288 * 289 * <p> 290 * Prefers the filter's token supplier, read straight from the servlet request: converting it through the REST 291 * attribute view would stringify the supplier itself. Only the filter's own {@link RequestBoundaryFilter.TokenSupplier} 292 * is trusted; a value of any other type under that name was set by request code, so no token is embedded. Falls 293 * back to the single string value for a filter that publishes only that. 294 */ 295 private static final Pattern SYMBOL_NAME = Pattern.compile("[a-z0-9_]{1,64}"); 296 297 // Returns the symbol name when value is "symbol:<name>", null when it is not a symbol reference; rejects a bad name. 298 private static String symbolName(String attr, String value) throws TemplateModelException { 299 if (! value.startsWith("symbol:")) 300 return null; 301 var name = value.substring("symbol:".length()); 302 if (! SYMBOL_NAME.matcher(name).matches()) 303 throw FtlAttrLists.reject(f("<@console> %s='%s' needs a symbol name matching [a-z0-9_]{1,64}.", attr, value)); 304 return name; 305 } 306 307 // A context: / servlet: page asset resolves against the request; an absolute path passes through. 308 private static String resolveAsset(RestRequest req, String url) { 309 return url.startsWith("context:") || url.startsWith("servlet:") ? req.getUriResolver().resolve(url) : url; 310 } 311 312 private static String csrfToken(RestRequest req) { 313 var supplier = req.getHttpServletRequest().getAttribute(RequestBoundaryFilter.TOKEN_SUPPLIER_ATTRIBUTE); 314 if (supplier instanceof RequestBoundaryFilter.TokenSupplier s) 315 return s.get(); 316 if (supplier != null) 317 return null; 318 return req.getAttribute(RequestBoundaryFilter.TOKEN_ATTRIBUTE).asString().orElse(null); 319 } 320 321 /** Minimal HTML-attribute escape for an author-/request-supplied value placed in a double-quoted attribute. */ 322 private static String attrEscape(String s) { 323 return s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); 324 } 325 326 /** 327 * Fails fast when a page opts in to inline handlers under a CSP that would block them. Every 328 * {@code Content-Security-Policy} value already on the response is checked: its effective script directive 329 * ({@code script-src}, else {@code default-src}) must list {@code 'unsafe-eval'}. A header added after this point 330 * is not seen here; the client reports it as a loud failure instead. 331 */ 332 private static void checkInlineCsp(RestRequest req) { 333 var values = req.getResponse().getHttpServletResponse().getHeaders("Content-Security-Policy"); 334 if (values == null || values.isEmpty()) 335 return; 336 for (var v : values) 337 if (! allowsEval(v)) 338 throw new IllegalStateException("allowInlineHandlers(true) needs 'unsafe-eval' in script-src; the response CSP is: " + String.join(", ", values)); 339 } 340 341 /** 342 * Restricts framing of the page to its own origin unless the application already set a framing policy. 343 * 344 * <p> 345 * Adds {@code Content-Security-Policy: frame-ancestors 'self'} when the response carries neither an 346 * {@code X-Frame-Options} header nor a {@code Content-Security-Policy} value with a {@code frame-ancestors} 347 * directive, so an application keeps full control by setting its own. 348 */ 349 private static void addFrameAncestors(RestRequest req) { 350 var res = req.getResponse().getHttpServletResponse(); 351 if (res.isCommitted() || res.containsHeader("X-Frame-Options")) 352 return; 353 var values = res.getHeaders("Content-Security-Policy"); 354 if (values != null) 355 for (var v : values) 356 if (v.toLowerCase(Locale.ROOT).contains("frame-ancestors")) 357 return; 358 res.addHeader("Content-Security-Policy", "frame-ancestors 'self'"); 359 } 360 361 private static boolean allowsEval(String policy) { 362 String script = null; 363 String dflt = null; 364 for (var d : policy.split(";")) { 365 var t = d.trim(); 366 var lower = t.toLowerCase(java.util.Locale.ROOT); 367 if (lower.equals("script-src") || lower.startsWith("script-src ")) 368 script = t; 369 else if (lower.equals("default-src") || lower.startsWith("default-src ")) 370 dflt = t; 371 } 372 var effective = script != null ? script : dflt; 373 return effective == null || effective.toLowerCase(java.util.Locale.ROOT).contains(org.apache.juneau.http.header.ContentSecurityPolicy.Builder.UNSAFE_EVAL); 374 } 375}