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.rest.server.view.mustache;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020import static org.apache.juneau.commons.utils.StringUtils.*;
021
022import java.io.*;
023import java.util.*;
024
025import org.apache.juneau.commons.utils.*;
026import org.apache.juneau.http.response.*;
027import org.apache.juneau.rest.server.*;
028import org.apache.juneau.rest.server.view.*;
029
030import com.github.mustachejava.*;
031import com.github.mustachejava.resolver.*;
032
033/**
034 * Flavor-neutral worker bean carrying the Mustache raw-template-dispatch logic shared by the
035 * {@link MustacheMixin} mixin, the {@link MustacheServlet} servlet, and the {@link MustacheResource}
036 * child flavors.
037 *
038 * <p>
039 * This is the <i>flavor-neutral worker</i> for the Mustache capability: it is <b>not</b> one
040 * of the three {@code @Rest} flavor classes &mdash; it is a plain bean that implements
041 * {@link RawTemplateDispatcher} and holds the capability state ({@code basePath} /
042 * {@code templateSuffix} / lazy default factory) plus the raw-serve and factory-resolution logic.
043 * Each flavor independently holds an instance of this worker and delegates to it, so no flavor is
044 * another flavor's worker.
045 *
046 * <h2 class='section'>See Also:</h2><ul>
047 *    <li class='jc'>{@link MustacheMixin}
048 *    <li class='jc'>{@link MustacheServlet}
049 *    <li class='jc'>{@link MustacheResource}
050 *    <li class='jic'>{@link RawTemplateDispatcher}
051 * </ul>
052 *
053 * @since 10.0.0
054 */
055@SuppressWarnings({
056   "resource" // Closeables here are framework-managed and not owned/closed by this class; not a real leak.
057})
058public class MustacheDispatcher implements RawTemplateDispatcher {
059
060   /** Default base path applied when no {@link Builder#basePath(String)} call has been made. */
061   @SuppressWarnings({
062      "java:S1075" // Default for the configurable basePath setting, not a hardcoded location.
063   })
064   public static final String DEFAULT_BASE_PATH = "/templates/";
065
066   /** Default template suffix &mdash; empty (literal template names, no implicit suffix). */
067   public static final String DEFAULT_TEMPLATE_SUFFIX = "";
068
069   /** Default cache-templates setting &mdash; {@code true} (cache forever; production-safe). */
070   public static final boolean DEFAULT_CACHE_TEMPLATES = true;
071
072   private final String basePath;
073   private final String templateSuffix;
074   private final boolean cacheTemplates;
075
076   // Lazy bridge-default factory. Built on first call to resolveMustacheFactory(...) when no
077   // MustacheFactory bean is registered in the request's BeanStore. Volatile so the
078   // double-checked-locking idiom is safe under concurrent first-request load.
079   @SuppressWarnings({
080      "java:S3077" // Publish-once cache: assigned once under double-checked locking in resolveMustacheFactory(); the MustacheFactory is fully built before assignment, so volatile safe-publication is sufficient.
081   })
082   private volatile MustacheFactory defaultFactory;
083
084   /**
085    * Creates a new builder.
086    *
087    * @return A new builder.
088    */
089   public static Builder create() {
090      return new Builder();
091   }
092
093   /**
094    * Builder constructor.
095    *
096    * @param builder The builder. Must not be {@code null}.
097    */
098   protected MustacheDispatcher(Builder builder) {
099      basePath = builder.basePath;
100      templateSuffix = builder.templateSuffix;
101      cacheTemplates = builder.cacheTemplates;
102   }
103
104   /**
105    * Returns the base path under which template resources are resolved.
106    *
107    * @return The base path. Never {@code null}.
108    */
109   public String getBasePath() {
110      return basePath;
111   }
112
113   /**
114    * Returns the configured template-name suffix.
115    *
116    * @return The template suffix. Never {@code null}.
117    */
118   public String getTemplateSuffix() {
119      return templateSuffix;
120   }
121
122   /**
123    * Returns whether the bridge-default {@link MustacheFactory} caches compiled templates.
124    *
125    * @return The cache flag. Defaults to {@link #DEFAULT_CACHE_TEMPLATES}.
126    */
127   public boolean isCacheTemplates() {
128      return cacheTemplates;
129   }
130
131   /**
132    * The extension of the templates this bridge serves: the configured {@link #getTemplateSuffix() templateSuffix}, or
133    * {@code ".mustache"} when no suffix is configured.
134    */
135   private String servedExtension() {
136      return isEmpty(templateSuffix) ? ".mustache" : templateSuffix;
137   }
138
139   /**
140    * Appends {@link #getTemplateSuffix()} to {@code name} if not already present (idempotent).
141    *
142    * @param name The template name. Must not be {@code null}.
143    * @return The template name with the configured suffix appended (if applicable).
144    */
145   public String applyTemplateSuffix(String name) {
146      if (isEmpty(templateSuffix))
147         return name;
148      if (name.endsWith(templateSuffix))
149         return name;
150      return name + templateSuffix;
151   }
152
153   /**
154    * Resolves the active {@link MustacheFactory}.
155    *
156    * <p>
157    * Lookup order:
158    * <ol class='spaced-list'>
159    *    <li>{@code req.getContext().getBeanStore().getBean(MustacheFactory.class)} &mdash; any
160    *       user-supplied bean (Spring {@code @Bean}, microservice {@code BasicBeanStore.put},
161    *       etc.). Never cached or rebuilt by this bridge &mdash; {@link #isCacheTemplates()} does
162    *       not apply to user-supplied factories.
163    *    <li>Bridge default &mdash; a {@link DefaultMustacheFactory} anchored on a resource root
164    *       derived from {@link #getBasePath() basePath} (leading + trailing slashes trimmed).
165    *       When {@link #isCacheTemplates()} is {@code true} (the default), a single instance is
166    *       lazily built once and reused (mustache.java's own {@code DefaultMustacheFactory}
167    *       compiles-and-caches templates internally, so reuse means "compile once"). When
168    *       {@code false}, a fresh factory with an empty compile-cache is built on every call, so
169    *       every render recompiles the template from its current classpath contents (hot-reload).
170    * </ol>
171    *
172    * @param req The current REST request.
173    * @return The active Mustache factory. Never {@code null}.
174    */
175   public MustacheFactory resolveMustacheFactory(RestRequest req) {
176      var bean = req.getContext().getBeanStore().getBean(MustacheFactory.class);
177      if (bean.isPresent())
178         return bean.get();
179      if (! cacheTemplates)
180         return buildDefaultFactory();
181      var local = defaultFactory;
182      if (local == null) {
183         synchronized (this) {
184            local = defaultFactory;
185            if (local == null) {
186               local = buildDefaultFactory();
187               defaultFactory = local;
188            }
189         }
190      }
191      return local;
192   }
193
194   /**
195    * Constructs the bridge-default {@link MustacheFactory}.
196    *
197    * <p>
198    * {@link DefaultMustacheFactory} anchored on a classpath resource root derived from
199    * {@link #getBasePath() basePath} (leading + trailing slashes trimmed). A {@code "/"} base
200    * yields a no-prefix factory. Subclasses may override to plug in custom resolvers / object
201    * handlers without registering a separate {@code @Bean MustacheFactory}.
202    *
203    * @return A new {@link MustacheFactory} instance.
204    */
205   protected MustacheFactory buildDefaultFactory() {
206      var root = toResourceRoot(basePath);
207      // Classpath-only resolver: no URI or file-system resolution of template or partial names.
208      return new DefaultMustacheFactory(root.isEmpty() ? new ClasspathResolver() : new ClasspathResolver(root));
209   }
210
211   /**
212    * Translates a virtual base path (e.g. {@code "/templates/"}) into a mustache.java resource
213    * root (e.g. {@code "templates"}).
214    *
215    * <p>
216    * mustache.java's {@link DefaultMustacheFactory#DefaultMustacheFactory(String)} expects a
217    * classpath-relative root without a leading slash and treats a trailing slash as part of the
218    * resolved path, so we trim both ends. A {@code null} / blank / {@code "/"} base yields an
219    * empty string &mdash; meaning "no prefix" (factory resolves names directly).
220    *
221    * @param base The virtual base path.
222    * @return The mustache.java resource root (never {@code null}).
223    */
224   static String toResourceRoot(String base) {
225      if (isBlank(base))
226         return "";
227      var s = base;
228      while (s.startsWith("/"))
229         s = s.substring(1);
230      while (s.endsWith("/"))
231         s = s.substring(0, s.length() - 1);
232      return s;
233   }
234
235   /**
236    * Renders a raw template through the Mustache engine onto the response.
237    *
238    * @param path The trailing path segment after the mount prefix (the template name relative to
239    *    the configured {@link #getBasePath() base path}; configured suffix appended if missing).
240    * @param req The current REST request.
241    * @param res The current REST response.
242    * @throws IOException If the underlying response writer fails.
243    * @throws BasicHttpException On boundary violation (403), missing engine (500), or render
244    *    failure (500).
245    */
246   @Override /* RawTemplateDispatcher */
247   public void render(String path, RestRequest req, RestResponse res)
248         throws IOException, BasicHttpException {
249
250      var template = (path == null) ? "" : path;
251
252      // resolveVirtualPathSafely validates that the resolved virtual path stays inside the
253      // configured basePath. The traversal check operates on basePath + template so a template
254      // name like "../../etc/passwd" or "a/b/../../../secret" is rejected before reaching the
255      // engine. We re-derive the factory-relative template name from the safe result by
256      // stripping the (already-normalized) basePath prefix.
257      String safeTemplate;
258      try {
259         var resolved = FileUtils.resolveVirtualPathSafely(basePath, template);
260         safeTemplate = stripBasePath(basePath, resolved);
261      } catch (IllegalArgumentException ex) {
262         throw new Forbidden("Path escapes configured base path.");
263      }
264
265      // Apply suffix idempotently so /mustache/about resolves to about.mustache (when
266      // templateSuffix is configured), while /mustache/about.mustache stays as-is.
267      safeTemplate = applyTemplateSuffix(safeTemplate);
268
269      // Only template-extension names are served, and names carrying a scheme or backslash never are.
270      if (! ViewTemplateNames.isPlainName(safeTemplate) || ! ViewTemplateNames.hasAllowedExtension(safeTemplate, servedExtension()))
271         throw new NotFound("Template not found.");
272
273      try {
274         var factory = resolveMustacheFactory(req);
275         if (! res.containsHeader("Content-Type"))
276            res.setHeader("Content-Type", MustacheViewRenderer.DEFAULT_CONTENT_TYPE);
277         var mustache = factory.compile(safeTemplate);
278         mustache.execute(res.getWriter(), Map.of()).flush();
279      } catch (LinkageError ex) {
280         throw new InternalServerError(ex, MustacheViewRenderer.NO_ENGINE_DIAGNOSTIC);
281      } catch (IOException | BasicHttpException ex) {
282         throw ex;
283      } catch (Exception ex) {
284         throw new InternalServerError(ex, "Mustache render failed for '%s'", safeTemplate);
285      }
286   }
287
288   /**
289    * Strips the normalized {@code basePath} prefix from a {@code resolveVirtualPathSafely}
290    * result so the leftover string is factory-relative (the bridge's default factory re-adds
291    * the configured resource-root prefix).
292    *
293    * <p>
294    * Normalization mirrors {@code FileUtils.resolveVirtualPathSafely}: a {@code null} / empty
295    * base normalizes to {@code "/"}; otherwise the base is guaranteed to start with {@code "/"}
296    * and end with {@code "/"} once the helper has normalized it.
297    *
298    * @param base The configured base path (typically {@code "/templates/"}).
299    * @param resolved The output of {@code resolveVirtualPathSafely} (always starts with the
300    *    normalized base).
301    * @return The factory-relative template name (e.g. {@code "hello.mustache"} for base
302    *    {@code "/templates/"} and resolved {@code "/templates/hello.mustache"}).
303    */
304   static String stripBasePath(String base, String resolved) {
305      var bp = isEmpty(base) ? "/" : base;
306      if (! bp.endsWith("/"))
307         bp = bp + "/";
308      if (! bp.startsWith("/"))
309         bp = "/" + bp;
310      if (resolved.startsWith(bp))
311         return resolved.substring(bp.length());
312      throw iaex("Resolved path '%s' does not start with base '%s'", resolved, bp);
313   }
314
315   /**
316    * Builder for {@link MustacheDispatcher}.
317    */
318   public static class Builder {
319
320      String basePath = DEFAULT_BASE_PATH;
321      String templateSuffix = DEFAULT_TEMPLATE_SUFFIX;
322      boolean cacheTemplates = DEFAULT_CACHE_TEMPLATES;
323
324      /** Constructor &mdash; package access for {@link MustacheDispatcher#create()}. */
325      protected Builder() {}
326
327      /**
328       * Sets the classpath base path under which template resources are resolved.
329       *
330       * @param value The base path. {@code null} or blank values reset to the default
331       *    {@link MustacheDispatcher#DEFAULT_BASE_PATH}.
332       * @return This object.
333       */
334      public Builder basePath(String value) {
335         basePath = isBlank(value) ? DEFAULT_BASE_PATH : value;
336         return this;
337      }
338
339      /**
340       * Sets the suffix to append to template names that don't already end with it (idempotent).
341       *
342       * @param value The new suffix. {@code null} resets to
343       *    {@link MustacheDispatcher#DEFAULT_TEMPLATE_SUFFIX}.
344       * @return This object.
345       */
346      public Builder templateSuffix(String value) {
347         templateSuffix = (value == null) ? DEFAULT_TEMPLATE_SUFFIX : value;
348         return this;
349      }
350
351      /**
352       * Sets whether the bridge-default {@link MustacheFactory} caches compiled templates.
353       *
354       * <p>
355       * Defaults to {@link MustacheDispatcher#DEFAULT_CACHE_TEMPLATES true} (cache
356       * forever &mdash; production-safe). Set {@code false} to enable dev hot-reload (every
357       * render rebuilds the factory from a fresh, empty compile-cache).
358       *
359       * <p>
360       * This flag only affects the bridge-default factory; a user-supplied
361       * {@code @Bean MustacheFactory} is not modified.
362       *
363       * @param value The cache flag.
364       * @return This object.
365       */
366      public Builder cacheTemplates(boolean value) {
367         cacheTemplates = value;
368         return this;
369      }
370
371      /**
372       * Reads the current base path setting (test/inspection helper).
373       *
374       * @return The base path. Never {@code null}.
375       */
376      public String getBasePath() {
377         return basePath;
378      }
379
380      /**
381       * Reads the current template-suffix setting (test/inspection helper).
382       *
383       * @return The template suffix. Never {@code null}.
384       */
385      public String getTemplateSuffix() {
386         return templateSuffix;
387      }
388
389      /**
390       * Reads the current cache-templates setting (test/inspection helper).
391       *
392       * @return The cache flag.
393       */
394      public boolean isCacheTemplates() {
395         return cacheTemplates;
396      }
397
398      /**
399       * Builds the {@link MustacheDispatcher}.
400       *
401       * @return A new {@link MustacheDispatcher} instance.
402       */
403      public MustacheDispatcher build() {
404         if (basePath == null)
405            throw iaex("basePath must not be null");
406         return new MustacheDispatcher(this);
407      }
408   }
409}