#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Serve only bundled fonts from the public fonts route (#8806)
Anthony Stirlingb412467b8d98
diff --git a/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java b/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.javaindex 91e513fed6..9a2db76389 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java@@ -1,5 +1,6 @@package stirling.software.SPDF.config;+import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.ArrayList;import java.util.List;@@ -10,6 +11,7 @@ import java.util.stream.Stream;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Configuration;+import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;import org.springframework.http.CacheControl;import org.springframework.http.HttpHeaders;@@ -21,6 +23,7 @@ import org.springframework.web.servlet.resource.EncodedResourceResolver;import org.springframework.web.servlet.resource.HttpResource;import org.springframework.web.servlet.resource.ResourceResolver;import org.springframework.web.servlet.resource.ResourceResolverChain;+import org.springframework.web.util.UriUtils;import jakarta.servlet.http.HttpServletRequest;@@ -48,6 +51,21 @@ public class WebMvcConfig implements WebMvcConfigurer {CacheControl.maxAge(Duration.ofDays(1)).cachePublic().staleWhileRevalidate(Duration.ofDays(7));+ private static final List<String> BRANDING_FOLDERS =+ List.of(+ "icons",+ "modern-logo",+ "pdfjs",+ "pdfium",+ "locales",+ "css",+ "js",+ "vendor",+ "samples",+ "og_images",+ "Login");+ private static final String PRIVATE_FONTS_FOLDER = "fonts";+ private static final int MAX_DECODE_PASSES = 4;@Overridepublic void addInterceptors(InterceptorRegistry registry) {@@ -84,12 +102,13 @@ public class WebMvcConfig implements WebMvcConfigurer {// so a one-year immutable policy would strand a browser on one release's// bytes. A day of freshness plus SWR keeps repeat opens cheap without// pinning an update.- registry.addResourceHandler("/images/**", "/fonts/**")- .addResourceLocations(- staticPath + "images/",- "classpath:/static/images/",- staticPath + "fonts/",- "classpath:/static/fonts/")+ registry.addResourceHandler("/images/**")+ .addResourceLocations(staticPath + "images/", "classpath:/static/images/")+ .setCacheControl(STABLE_ONE_DAY)+ .resourceChain(true)+ .addResolver(new PreferredEncodingResourceResolver());+ registry.addResourceHandler("/fonts/**")+ .addResourceLocations("classpath:/static/fonts/").setCacheControl(STABLE_ONE_DAY).resourceChain(true).addResolver(new PreferredEncodingResourceResolver());@@ -102,46 +121,19 @@ public class WebMvcConfig implements WebMvcConfigurer {"/android-chrome-*.png","/mstile-*.png","/safari-pinned-tab.svg",- "/icons/**",- "/modern-logo/**",- "/3rdPartyLicenses.json",- "/pdfjs/**",- "/pdfium/**",- "/locales/**",- "/css/**",- "/js/**",- "/vendor/**",- "/samples/**",- "/og_images/**",- "/Login/**")- .addResourceLocations(- staticPath,- "classpath:/static/",- staticPath + "pdfjs/",- "classpath:/static/pdfjs/",- staticPath + "pdfium/",- "classpath:/static/pdfium/",- staticPath + "locales/",- "classpath:/static/locales/",- staticPath + "css/",- "classpath:/static/css/",- staticPath + "js/",- "classpath:/static/js/",- staticPath + "vendor/",- "classpath:/static/vendor/",- staticPath + "samples/",- "classpath:/static/samples/",- staticPath + "og_images/",- "classpath:/static/og_images/",- staticPath + "Login/",- "classpath:/static/Login/",- staticPath + "icons/",- "classpath:/static/icons/",- staticPath + "modern-logo/",- "classpath:/static/modern-logo/")+ "/3rdPartyLicenses.json")+ .addResourceLocations(staticPath, "classpath:/static/").setCacheControl(STABLE_ONE_DAY).resourceChain(true).addResolver(new PreferredEncodingResourceResolver());+ for (String folder : BRANDING_FOLDERS) {+ registry.addResourceHandler("/" + folder + "/**")+ .addResourceLocations(+ staticPath + folder + "/", "classpath:/static/" + folder + "/")+ .setCacheControl(STABLE_ONE_DAY)+ .resourceChain(true)+ .addResolver(new PreferredEncodingResourceResolver());+ }// 5. Catch-all (SPA fallback)// Must check with server to ensure index.html is always fresh.@@ -149,6 +141,7 @@ public class WebMvcConfig implements WebMvcConfigurer {.addResourceLocations(staticPath, "classpath:/static/").setCacheControl(NO_CACHE).resourceChain(true)+ .addResolver(new BundledOnlyFolderResolver(PRIVATE_FONTS_FOLDER)).addResolver(new PreferredEncodingResourceResolver());}@@ -257,6 +250,98 @@ public class WebMvcConfig implements WebMvcConfigurer {}}+ /**+ * Restricts one top-level folder on the catch-all handler to classpath locations, so files an+ * operator drops into the custom static directory under that name are never served publicly.+ *+ * <p>The folder is matched however the filesystem might resolve it: case-insensitively, after+ * up to {@link #MAX_DECODE_PASSES} rounds of percent-decoding, with either separator, and with+ * Windows stream suffixes and trailing dots or spaces stripped. A path that cannot be fully+ * decoded is treated as targeting the folder.+ *+ * <p>Hazard: this is the only guard for spellings the {@code /fonts/**} handler does not match,+ * so the two must name the same folder.+ */+ static final class BundledOnlyFolderResolver implements ResourceResolver {++ private final String folder;++ BundledOnlyFolderResolver(String folder) {+ this.folder = folder.toLowerCase(Locale.ROOT);+ }++ @Override+ public Resource resolveResource(+ HttpServletRequest request,+ String requestPath,+ List<? extends Resource> locations,+ ResourceResolverChain chain) {+ return chain.resolveResource(+ request, requestPath, allowedLocations(requestPath, locations));+ }++ @Override+ public String resolveUrlPath(+ String resourcePath,+ List<? extends Resource> locations,+ ResourceResolverChain chain) {+ return chain.resolveUrlPath(resourcePath, allowedLocations(resourcePath, locations));+ }++ List<? extends Resource> allowedLocations(String path, List<? extends Resource> locations) {+ if (!targetsFolder(path)) {+ return locations;+ }+ return locations.stream()+ .filter(location -> location instanceof ClassPathResource)+ .toList();+ }++ boolean targetsFolder(String path) {+ if (path == null) {+ return false;+ }+ String decoded = fullyDecoded(path);+ if (decoded == null) {+ return true;+ }+ for (String segment : decoded.split("[/\\\\]")) {+ String name = windowsName(segment);+ if (!name.isEmpty()) {+ return name.toLowerCase(Locale.ROOT).equals(folder);+ }+ }+ return false;+ }++ private static String fullyDecoded(String path) {+ String current = path;+ for (int pass = 0; pass < MAX_DECODE_PASSES; pass++) {+ String next;+ try {+ next = UriUtils.decode(current, StandardCharsets.UTF_8);+ } catch (IllegalArgumentException e) {+ return null;+ }+ if (next.equals(current)) {+ return current;+ }+ current = next;+ }+ return null;+ }++ private static String windowsName(String segment) {+ int stream = segment.indexOf(':');+ String name = stream >= 0 ? segment.substring(0, stream) : segment;+ int end = name.length();+ while (end > 0 && (name.charAt(end - 1) == '.' || name.charAt(end - 1) == ' ')) {+ end--;+ }+ return name.substring(0, end);+ }+ }+@Overridepublic void addCorsMappings(CorsRegistry registry) {// Check if running in Tauri modediff --git a/app/core/src/test/java/stirling/software/SPDF/config/WebMvcConfigTest.java b/app/core/src/test/java/stirling/software/SPDF/config/WebMvcConfigTest.javaindex 9201141d51..59a270915c 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/WebMvcConfigTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/WebMvcConfigTest.java@@ -7,11 +7,17 @@ import static org.mockito.Mockito.RETURNS_DEEP_STUBS;import static org.mockito.Mockito.atLeastOnce;import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.mockStatic;import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;+import java.io.File;import java.io.IOException;+import java.net.URI;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;@@ -25,16 +31,25 @@ import org.junit.jupiter.api.extension.ExtendWith;import org.junit.jupiter.api.io.TempDir;import org.mockito.ArgumentCaptor;import org.mockito.Mock;+import org.mockito.MockedStatic;import org.mockito.junit.jupiter.MockitoExtension;import org.mockito.junit.jupiter.MockitoSettings;import org.mockito.quality.Strictness;+import org.springframework.context.annotation.AnnotationConfigUtils;+import org.springframework.context.annotation.Configuration;+import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.Resource;import org.springframework.http.CacheControl;import org.springframework.http.HttpHeaders;import org.springframework.mock.web.MockHttpServletRequest;+import org.springframework.mock.web.MockServletContext;+import org.springframework.test.web.servlet.MockMvc;+import org.springframework.test.web.servlet.setup.MockMvcBuilders;+import org.springframework.web.context.support.GenericWebApplicationContext;import org.springframework.web.servlet.config.annotation.CorsRegistration;import org.springframework.web.servlet.config.annotation.CorsRegistry;+import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.InterceptorRegistration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;@@ -44,6 +59,7 @@ import org.springframework.web.servlet.resource.ResourceResolverChain;import jakarta.servlet.http.HttpServletRequest;+import stirling.software.common.configuration.InstallationPathConfig;import stirling.software.common.model.ApplicationProperties;@ExtendWith(MockitoExtension.class)@@ -101,8 +117,8 @@ class WebMvcConfigTest {class AddResourceHandlers {@Test- @DisplayName("registers all five resource handler groups")- void registersFiveHandlerGroups() {+ @DisplayName("registers every resource handler group")+ void registersEveryHandlerGroup() {ResourceHandlerRegistry registry = mock(ResourceHandlerRegistry.class);ResourceHandlerRegistration registration =mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);@@ -110,8 +126,9 @@ class WebMvcConfigTest {config.addResourceHandlers(registry);- // SW/PWA, assets, media+fonts, branding, catch-all = 5 handler registrations.- verify(registry, times(5)).addResourceHandler(any(String[].class));+ // SW/PWA, assets, images, fonts, branding root files, 11 branding folders,+ // catch-all = 17 handler registrations.+ verify(registry, times(17)).addResourceHandler(any(String[].class));}@Test@@ -139,6 +156,8 @@ class WebMvcConfigTest {mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);ResourceHandlerRegistration assets =mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);+ ResourceHandlerRegistration images =+ mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);ResourceHandlerRegistration media =mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);ResourceHandlerRegistration branding =@@ -146,31 +165,157 @@ class WebMvcConfigTest {ResourceHandlerRegistration catchAll =mock(ResourceHandlerRegistration.class, RETURNS_DEEP_STUBS);when(registry.addResourceHandler(any(String[].class)))- .thenReturn(sw, assets, media, branding, catchAll);+ .thenReturn(sw, assets, images, media, branding, catchAll);// addResourceLocations is the chain link before setCacheControl.when(sw.addResourceLocations(any(String[].class))).thenReturn(sw);when(assets.addResourceLocations(any(String[].class))).thenReturn(assets);+ when(images.addResourceLocations(any(String[].class))).thenReturn(images);when(media.addResourceLocations(any(String[].class))).thenReturn(media);when(branding.addResourceLocations(any(String[].class))).thenReturn(branding);when(catchAll.addResourceLocations(any(String[].class))).thenReturn(catchAll);config.addResourceHandlers(registry);- // Third registration is the media/fonts group. The names never change+ // Fourth registration is the fonts group. The names never change// across releases, so the tier has to allow revalidation; repeating a// 17 MB CJK face is still cheap because an unchanged file answers the// conditional request with 304.ArgumentCaptor<String[]> patterns = ArgumentCaptor.forClass(String[].class);- verify(registry, times(5)).addResourceHandler(patterns.capture());- assertThat(patterns.getAllValues().get(2)).contains("/fonts/**");+ verify(registry, times(17)).addResourceHandler(patterns.capture());+ assertThat(patterns.getAllValues().get(3)).containsExactly("/fonts/**");ArgumentCaptor<CacheControl> caches = ArgumentCaptor.forClass(CacheControl.class);verify(media).setCacheControl(caches.capture());String header = caches.getValue().getHeaderValue();assertThat(header).contains("max-age=86400").doesNotContain("immutable");}++ @Test+ @DisplayName("keeps custom fonts off every public prefix while bundled assets resolve")+ void customFontsStayPrivate(@TempDir Path root, @TempDir Path outside) throws Exception {+ Path fonts = Files.createDirectories(root.resolve("fonts"));+ Files.writeString(fonts.resolve("Custom.ttf"), "custom");+ Files.createSymbolicLink(+ fonts.resolve("leak.ttf"),+ Files.writeString(outside.resolve("target.ttf"), "outside"));+ Files.writeString(root.resolve("favicon.ico"), "custom-icon");+ Files.writeString(+ Files.createDirectories(root.resolve("js")).resolve("custom.js"), "js");++ MockMvc mvc = resourceMvc(root);++ for (String prefix : PUBLIC_PREFIXES) {+ for (String file : List.of("Custom.ttf", "leak.ttf")) {+ mvc.perform(get(prefix + "/fonts/" + file)).andExpect(status().isNotFound());+ }+ }+ mvc.perform(get("/css/fonts/bootstrap-icons.woff2")).andExpect(status().isOk());+ mvc.perform(get("/fonts/DejaVuSans.ttf")).andExpect(status().isOk());+ mvc.perform(get("/favicon.ico")).andExpect(content().string("custom-icon"));+ mvc.perform(get("/js/custom.js")).andExpect(content().string("js"));+ }++ @Test+ @DisplayName("keeps custom fonts private when the folder is named in another case")+ void customFontsStayPrivateUnderAnyCase(@TempDir Path root) throws Exception {+ Path fonts = Files.createDirectories(root.resolve("fonts"));+ Files.writeString(fonts.resolve("Custom.ttf"), "custom");+ for (String alias : FOLDER_ALIASES) {+ if (!Files.exists(root.resolve(alias))) {+ Files.createSymbolicLink(root.resolve(alias), fonts);+ }+ }++ MockMvc mvc = resourceMvc(root);++ for (String alias : FOLDER_ALIASES) {+ mvc.perform(get(URI.create("/" + alias + "/Custom.ttf")))+ .andExpect(status().isNotFound());+ }+ mvc.perform(get(URI.create("/%46onts/Custom.ttf"))).andExpect(status().isNotFound());+ int bundledStatus =+ new ClassPathResource("static/Fonts/DejaVuSans.ttf").exists() ? 200 : 404;+ mvc.perform(get(URI.create("/Fonts/DejaVuSans.ttf")))+ .andExpect(status().is(bundledStatus));+ }++ @Test+ @DisplayName("limits every spelling of the fonts folder to bundled locations")+ void bundledOnlyResolverMatchesEverySpelling(@TempDir Path root) {+ WebMvcConfig.BundledOnlyFolderResolver resolver =+ new WebMvcConfig.BundledOnlyFolderResolver("fonts");+ Resource custom = new FileSystemResource(root);+ Resource bundled = new ClassPathResource("static/");+ List<Resource> locations = List.of(custom, bundled);++ for (String path :+ List.of(+ "fonts/Custom.ttf",+ "Fonts/Custom.ttf",+ "FONTS/Custom.ttf",+ "/fOnTs/Custom.ttf",+ "%46onts/Custom.ttf",+ "%2546onts/Custom.ttf",+ "%46ONTS%2fCustom.ttf",+ "Fonts\\Custom.ttf",+ "./Fonts/Custom.ttf",+ "fonts./Custom.ttf",+ "Fonts . /Custom.ttf",+ "fonts::$INDEX_ALLOCATION/Custom.ttf",+ "%zzonts/Custom.ttf")) {+ assertThat(List.<Resource>copyOf(resolver.allowedLocations(path, locations)))+ .as(path)+ .containsExactly(bundled);+ }+ for (String path :+ List.of("index.html", "js/fonts/a.ttf", "fontsx/a.ttf", "myfonts/a.ttf")) {+ assertThat(List.<Resource>copyOf(resolver.allowedLocations(path, locations)))+ .as(path)+ .containsExactly(custom, bundled);+ }+ }++ private static final List<String> FOLDER_ALIASES =+ List.of("Fonts", "FONTS", "fOnTs", "fonts.");++ private static final List<String> PUBLIC_PREFIXES =+ List.of(+ "",+ "/images",+ "/icons",+ "/modern-logo",+ "/pdfjs",+ "/pdfium",+ "/locales",+ "/css",+ "/js",+ "/vendor",+ "/samples",+ "/og_images",+ "/Login");++ private MockMvc resourceMvc(Path staticRoot) throws Exception {+ when(endpointInterceptor.preHandle(any(), any(), any())).thenReturn(true);+ when(pdfMetricsInterceptor.preHandle(any(), any(), any())).thenReturn(true);+ GenericWebApplicationContext context =+ new GenericWebApplicationContext(new MockServletContext());+ AnnotationConfigUtils.registerAnnotationConfigProcessors(context);+ context.registerBean(ResourceMvc.class);+ context.getBeanFactory().registerSingleton("webMvcConfig", config);+ try (MockedStatic<InstallationPathConfig> paths =+ mockStatic(InstallationPathConfig.class)) {+ paths.when(InstallationPathConfig::getStaticPath)+ .thenReturn(staticRoot + File.separator);+ context.refresh();+ }+ return MockMvcBuilders.webAppContextSetup(context).build();+ }}+ @Configuration(proxyBeanMethods = false)+ @EnableWebMvc+ static class ResourceMvc {}+@Nested@DisplayName("addCorsMappings")class AddCorsMappings {