Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Preserve omitted PDF metadata and support URL conversion in background jobs (#8779)

Anthony Stirlingc718a37074b3
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index d800f668bf..85295534af 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -1495,7 +1495,7 @@ public class ApplicationProperties {
@Data
public static class Sharing {
- private boolean enabled = false;
+ private boolean enabled = true;
private boolean linkEnabled = true;
private boolean emailEnabled = false;
private int linkExpirationDays = 3;
diff --git a/app/common/src/main/java/stirling/software/common/service/FileStorage.java b/app/common/src/main/java/stirling/software/common/service/FileStorage.java
index 700a6e5a65..ec14490e32 100644
--- a/app/common/src/main/java/stirling/software/common/service/FileStorage.java
+++ b/app/common/src/main/java/stirling/software/common/service/FileStorage.java
@@ -92,7 +92,13 @@ public class FileStorage {
public StoredFile storeInputStream(InputStream inputStream, String originalName)
throws IOException {
- FileStore.Stored stored = fileStore.store(inputStream, originalName, resolveOwner());
+ return storeInputStream(inputStream, originalName, resolveOwner());
+ }
+
+ /** Stores on behalf of an authenticated owner supplied by a credential outside the session. */
+ public StoredFile storeInputStream(InputStream inputStream, String originalName, String owner)
+ throws IOException {
+ FileStore.Stored stored = fileStore.store(inputStream, originalName, owner);
log.debug("Stored input stream with ID: {}", stored.fileId());
return new StoredFile(stored.fileId(), stored.size());
}
diff --git a/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java b/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java
index 58211b1f70..5ea32dbe5b 100644
--- a/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java
+++ b/app/common/src/main/java/stirling/software/common/service/JobExecutorService.java
@@ -1,6 +1,7 @@
package stirling.software.common.service;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
@@ -264,6 +265,19 @@ public class JobExecutorService {
ResponseEntity<?> response = (ResponseEntity<?>) result;
Object body = response.getBody();
+ if (!response.getStatusCode().is2xxSuccessful()) {
+ String error =
+ "Job rejected with HTTP status " + response.getStatusCode().value();
+ String reason = rejectionReason(response);
+ if (reason != null) {
+ error += ": " + reason;
+ } else if (response.getHeaders().getLocation() != null) {
+ error += " at " + response.getHeaders().getLocation();
+ }
+ taskManager.setError(jobId, error);
+ return;
+ }
+
if (body instanceof byte[]) {
String filename = extractResponseFilename(response);
String contentType = extractResponseContentType(response);
@@ -418,6 +432,54 @@ public class JobExecutorService {
}
}
+ private static final int MAX_REJECTION_REASON_CHARS = 300;
+
+ /** The short message a rejecting endpoint gave, or null when it sent none worth showing. */
+ static String rejectionReason(ResponseEntity<?> response) {
+ Object body = response.getBody();
+ String reason = null;
+ if (body instanceof String text) {
+ reason = text;
+ } else if (body instanceof Map<?, ?> map) {
+ Object value = map.containsKey("error") ? map.get("error") : map.get("message");
+ reason = value instanceof String text ? text : null;
+ } else if (isPlainText(response.getHeaders().getContentType())) {
+ reason = smallText(body);
+ }
+ if (reason == null || reason.isBlank()) {
+ return null;
+ }
+ String flat = reason.strip().replaceAll("\\s+", " ");
+ return flat.length() > MAX_REJECTION_REASON_CHARS
+ ? flat.substring(0, MAX_REJECTION_REASON_CHARS) + "..."
+ : flat;
+ }
+
+ private static boolean isPlainText(MediaType contentType) {
+ return contentType != null && MediaType.TEXT_PLAIN.isCompatibleWith(contentType);
+ }
+
+ private static String smallText(Object body) {
+ try {
+ byte[] bytes;
+ if (body instanceof byte[] raw) {
+ bytes = raw;
+ } else if (body instanceof Resource resource && resource.isReadable()) {
+ if (resource.contentLength() > 4096) {
+ return null;
+ }
+ try (var in = resource.getInputStream()) {
+ bytes = in.readNBytes(4096);
+ }
+ } else {
+ return null;
+ }
+ return bytes.length > 4096 ? null : new String(bytes, StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ return null;
+ }
+ }
+
private static String extractResponseFilename(ResponseEntity<?> response) {
if (response.getHeaders().getContentDisposition() != null) {
String filename = response.getHeaders().getContentDisposition().getFilename();
diff --git a/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java b/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java
index 154a494ce8..3747dbc031 100644
--- a/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java
@@ -11,10 +11,10 @@ public class RequestUriUtils {
private static final Pattern SHARE_LINK_PATTERN =
Pattern.compile(
"^/share/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/?$");
- // Share-link download (not /metadata or /accessed); token format as above
+ // Share-link download and its /metadata (not /accessed); token format as above
private static final Pattern SHARE_LINK_API_PATTERN =
Pattern.compile(
- "^/api/v1/storage/share-links/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$");
+ "^/api/v1/storage/share-links/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(/metadata)?$");
// The phone's two mobile-scanner calls, matched exactly so only a bare session id passes
private static final Pattern MOBILE_SCANNER_PHONE_PATTERN =
Pattern.compile("^/api/v1/mobile-scanner/(validate-session|upload)/[A-Za-z0-9-]+$");
@@ -221,12 +221,22 @@ public class RequestUriUtils {
|| trimmedUri.startsWith("/api/v1/workflow/participant/")
// Share-link SPA bootstrap; data APIs remain protected
|| SHARE_LINK_PATTERN.matcher(trimmedUri).matches()
- // Share-link download; the service still demands login unless the link is public
+ // Share-link download and metadata; the controller still demands login unless the
+ // link is public
|| SHARE_LINK_API_PATTERN.matcher(trimmedUri).matches()
// Invite-accept SPA bootstrap; data APIs remain protected
|| INVITE_LINK_PATTERN.matcher(trimmedUri).matches();
}
+ /**
+ * Share-link download or metadata, which serve public links anonymously and private ones signed
+ * in.
+ */
+ public static boolean isShareLinkRead(String requestURI, String contextPath) {
+ String normalizedUri = normalizeUriOrNull(contextPath, requestURI);
+ return normalizedUri != null && SHARE_LINK_API_PATTERN.matcher(normalizedUri).matches();
+ }
+
public static String normalizeUri(String contextPath, String requestURI) {
String decodedUri = UriUtils.decode(requestURI, StandardCharsets.UTF_8);
if (contextPath != null && !contextPath.isBlank()) {
diff --git a/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java b/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java
index 3e9eea0dbf..d76e2ec714 100644
--- a/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java
+++ b/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java
@@ -32,13 +32,13 @@ class ApplicationPropertiesLogicTest {
}
@Test
- void storageDefaultsEnableLocalStorageAndSigningWithoutSharingOrEncryption() {
+ void storageDefaultsEnableLocalStorageSigningAndSharingWithoutEncryption() {
ApplicationProperties.Storage storage = new ApplicationProperties().getStorage();
assertTrue(storage.isEnabled());
assertTrue(storage.getSigning().isEnabled());
assertEquals("local", storage.getProvider());
- assertFalse(storage.getSharing().isEnabled());
+ assertTrue(storage.getSharing().isEnabled());
assertFalse(storage.getEncryption().isEnabled());
}
diff --git a/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java b/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java
index d5a8ba3584..e0b7366df3 100644
--- a/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java
+++ b/app/common/src/test/java/stirling/software/common/service/JobExecutorServiceTest.java
@@ -3,6 +3,7 @@ package stirling.software.common.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -10,10 +11,12 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@@ -126,6 +129,106 @@ class JobExecutorServiceTest {
verify(taskManager).createTask(jobIdCaptor.capture());
}
+ @Test
+ void shouldReturnSynchronousRedirectUnchanged() {
+ ResponseEntity<?> rejection =
+ ResponseEntity.status(HttpStatus.SEE_OTHER)
+ .location(URI.create("/url-to-pdf?error=error.endpointDisabled"))
+ .build();
+
+ assertSame(rejection, jobExecutorService.runJobGeneric(false, () -> rejection));
+ }
+
+ @ParameterizedTest
+ @EnumSource(
+ value = HttpStatus.class,
+ names = {"SEE_OTHER", "BAD_REQUEST", "SERVICE_UNAVAILABLE"})
+ void shouldRecordBodylessHttpRejectionsAsJobErrors(HttpStatus status) {
+ URI location = URI.create("/url-to-pdf?error=error.endpointDisabled");
+ ResponseEntity<?> rejection = ResponseEntity.status(status).location(location).build();
+ when(resourceMonitor.shouldQueueJob(80)).thenReturn(true);
+ when(jobQueue.queueJob(anyString(), eq(80), any(), anyLong()))
+ .thenAnswer(
+ invocation -> {
+ Supplier<?> queuedWork = invocation.getArgument(2);
+ queuedWork.get();
+ return CompletableFuture.completedFuture(ResponseEntity.ok().build());
+ });
+
+ jobExecutorService.runJobGeneric(true, () -> rejection, 5000, true, 80);
+
+ verify(taskManager)
+ .setError(
+ anyString(),
+ eq("Job rejected with HTTP status " + status.value() + " at " + location));
+ verify(taskManager, never()).setResult(anyString(), any());
+ verify(taskManager, never()).setComplete(anyString());
+ }
+
+ @Test
+ void shouldRecordHttpRejectionsWithABodyAsJobErrors() {
+ ResponseEntity<?> rejection =
+ ResponseEntity.status(HttpStatus.BAD_REQUEST).body(Map.of("error", "bad input"));
+ when(resourceMonitor.shouldQueueJob(80)).thenReturn(true);
+ when(jobQueue.queueJob(anyString(), eq(80), any(), anyLong()))
+ .thenAnswer(
+ invocation -> {
+ Supplier<?> queuedWork = invocation.getArgument(2);
+ queuedWork.get();
+ return CompletableFuture.completedFuture(ResponseEntity.ok().build());
+ });
+
+ jobExecutorService.runJobGeneric(true, () -> rejection, 5000, true, 80);
+
+ verify(taskManager)
+ .setError(anyString(), eq("Job rejected with HTTP status 400: bad input"));
+ verify(taskManager, never()).setResult(anyString(), any());
+ verify(taskManager, never()).setComplete(anyString());
+ }
+
+ @Test
+ void shouldKeepAPlainTextRejectionMessage() {
+ byte[] message = "No files provided".getBytes(StandardCharsets.UTF_8);
+ ResponseEntity<?> rejection =
+ ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .contentType(MediaType.TEXT_PLAIN)
+ .body(new ByteArrayResource(message));
+ when(resourceMonitor.shouldQueueJob(80)).thenReturn(true);
+ when(jobQueue.queueJob(anyString(), eq(80), any(), anyLong()))
+ .thenAnswer(
+ invocation -> {
+ Supplier<?> queuedWork = invocation.getArgument(2);
+ queuedWork.get();
+ return CompletableFuture.completedFuture(ResponseEntity.ok().build());
+ });
+
+ jobExecutorService.runJobGeneric(true, () -> rejection, 5000, true, 80);
+
+ verify(taskManager)
+ .setError(anyString(), eq("Job rejected with HTTP status 400: No files provided"));
+ }
+
+ @Test
+ void shouldIgnoreANonTextRejectionBody() {
+ ResponseEntity<?> rejection =
+ ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .contentType(MediaType.APPLICATION_PDF)
+ .body(new ByteArrayResource(new byte[] {0x25, 0x50, 0x44, 0x46}));
+
+ assertNull(JobExecutorService.rejectionReason(rejection));
+ }
+
+ @Test
+ void shouldKeepBodylessSuccessfulJobsSuccessful() {
+ ResponseEntity<?> success = ResponseEntity.noContent().build();
+
+ jobExecutorService.runJobGeneric(true, () -> success);
+
+ verify(taskManager, timeout(5000)).setComplete(anyString());
+ verify(taskManager).setResult(anyString(), org.mockito.ArgumentMatchers.isNull());
+ verify(taskManager, never()).setError(anyString(), anyString());
+ }
+
@Test
void shouldHandleSyncJobError() {
// Given
diff --git a/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java
index 3f9b707ba8..84f4b231fe 100644
--- a/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java
@@ -264,13 +264,26 @@ class RequestUriUtilsTest {
}
@Test
- void testIsPublicAuthEndpoint_shareLinkOtherApisStayProtected() {
- assertFalse(
+ void testIsPublicAuthEndpoint_shareLinkMetadataApi() {
+ assertTrue(
RequestUriUtils.isPublicAuthEndpoint(
"/api/v1/storage/share-links/00dcac3a-fc7a-4989-9c4f-97745484d62f/metadata",
""));
+ }
+
+ @Test
+ void testIsPublicAuthEndpoint_shareLinkOtherApisStayProtected() {
+ String link = "/api/v1/storage/share-links/00dcac3a-fc7a-4989-9c4f-97745484d62f";
assertFalse(
RequestUriUtils.isPublicAuthEndpoint("/api/v1/storage/share-links/accessed", ""));
+ assertFalse(RequestUriUtils.isPublicAuthEndpoint(link + "/metadata/extra", ""));
+ assertFalse(RequestUriUtils.isPublicAuthEndpoint(link + "/accesses", ""));
+ assertFalse(RequestUriUtils.isPublicAuthEndpoint(link + "/", ""));
+ assertFalse(
+ RequestUriUtils.isPublicAuthEndpoint(
+ "/api/v1/storage/files/1/shares/links/"
+ + "00dcac3a-fc7a-4989-9c4f-97745484d62f/accesses",
+ ""));
}
// --- share-link SPA bootstrap ---
@@ -318,6 +331,19 @@ class RequestUriUtilsTest {
assertFalse(RequestUriUtils.isPublicAuthEndpoint("/share/abc/admin", ""));
}
+ @Test
+ void testIsShareLinkRead_onlyTheTokenDownloadAndMetadataPaths() {
+ String link = "/api/v1/storage/share-links/00dcac3a-fc7a-4989-9c4f-97745484d62f";
+ assertTrue(RequestUriUtils.isShareLinkRead(link, ""));
+ assertTrue(RequestUriUtils.isShareLinkRead("/app" + link, "/app"));
+ assertTrue(RequestUriUtils.isShareLinkRead(link + "/metadata", ""));
+ assertTrue(RequestUriUtils.isShareLinkRead("/app" + link + "/metadata", "/app"));
+ assertFalse(RequestUriUtils.isShareLinkRead(link + "/accesses", ""));
+ assertFalse(RequestUriUtils.isShareLinkRead("/api/v1/storage/share-links/accessed", ""));
+ assertFalse(
+ RequestUriUtils.isShareLinkRead("/share/00dcac3a-fc7a-4989-9c4f-97745484d62f", ""));
+ }
+
@Test
void testIsPublicAuthEndpoint_shareApiStillProtected() {
// Share-link data APIs must NOT be public - they enforce auth + access checks
diff --git a/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java b/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java
index 13f30d43ad..65a5882ac9 100644
--- a/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java
+++ b/app/core/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java
@@ -56,6 +56,8 @@ public class CleanUrlInterceptor implements HandlerInterceptor {
// The frontend needs state to bind the SaaS response to the initiating browser.
boolean accountLinkCallback =
requestURI.equals(request.getContextPath() + "/account-link/callback");
+ // Share links carry ?action=download|open for the share page to run once.
+ boolean shareLink = requestURI.startsWith(request.getContextPath() + "/share/");
// Keep only the allowed parameters
String[] queryParameters = queryString.split("&");
@@ -65,7 +67,9 @@ public class CleanUrlInterceptor implements HandlerInterceptor {
continue;
}
String key = keyValuePair[0];
- if (ALLOWED_PARAMS.contains(key) || (accountLinkCallback && "state".equals(key))) {
+ if (ALLOWED_PARAMS.contains(key)
+ || (accountLinkCallback && "state".equals(key))
+ || (shareLink && "action".equals(key))) {
allowedParameters.put(key, keyValuePair.length == 2 ? keyValuePair[1] : null);
}
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java
index 659fdc8dd8..035f4ca12e 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java
@@ -20,6 +20,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponentsBuilder;
@@ -72,8 +73,12 @@ public class ConvertWebsiteToPDF {
public ResponseEntity<?> urlToPdf(@ModelAttribute UrlToPdfRequest request)
throws IOException, InterruptedException {
String URL = request.getUrlInput();
+ // Async jobs (MCP, pipelines) run off the request thread, where there is no request URL.
UriComponentsBuilder uriComponentsBuilder =
- ServletUriComponentsBuilder.fromCurrentContextPath().path("/url-to-pdf");
+ (RequestContextHolder.getRequestAttributes() != null
+ ? ServletUriComponentsBuilder.fromCurrentContextPath()
+ : UriComponentsBuilder.newInstance())
+ .path("/url-to-pdf");
URI location = null;
HttpStatus status = HttpStatus.SEE_OTHER;
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java
index 74e45d09da..71e9167120 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java
@@ -1,9 +1,10 @@
package stirling.software.SPDF.controller.api.misc;
import java.io.IOException;
-import java.util.Calendar;
+import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Set;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
@@ -59,6 +60,23 @@ public class MetadataController {
binder.registerCustomEditor(Map.class, "allRequestParams", new StringToMapPropertyEditor());
}
+ private static final Set<String> STANDARD_METADATA_KEYS =
+ Set.of(
+ "author",
+ "creationdate",
+ "creator",
+ "keywords",
+ "moddate",
+ "modificationdate",
+ "producer",
+ "subject",
+ "title",
+ "trapped");
+
+ private static boolean isStandardMetadataKey(String key) {
+ return key != null && STANDARD_METADATA_KEYS.contains(key.toLowerCase(Locale.ROOT));
+ }
+
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/update-metadata",
@@ -68,9 +86,10 @@ public class MetadataController {
@Operation(
summary = "Update a PDF's metadata",
description =
- "Standard fields left out are cleared, so send the current values of"
- + " the others too (see get-info-on-pdf). Dates use yyyy/MM/dd HH:mm:ss."
- + " deleteAll=true removes all metadata.")
+ "Standard fields left out are cleared unless keepOmitted=true, so"
+ + " otherwise send the current values of the others too (see"
+ + " get-info-on-pdf). Dates use yyyy/MM/dd HH:mm:ss. deleteAll=true"
+ + " removes all metadata.")
public ResponseEntity<Resource> metadata(@ModelAttribute MetadataRequest request)
throws IOException {
@@ -79,6 +98,7 @@ public class MetadataController {
// Extract metadata information
boolean deleteAll = Boolean.TRUE.equals(request.getDeleteAll());
+ boolean keepOmitted = !deleteAll && Boolean.TRUE.equals(request.getKeepOmitted());
String author = request.getAuthor();
String creationDate = request.getCreationDate();
String creator = request.getCreator();
@@ -110,6 +130,14 @@ public class MetadataController {
subject = checkUndefined(subject);
title = checkUndefined(title);
trapped = checkUndefined(trapped);
+ if (keepOmitted) {
+ author = author != null ? author : info.getAuthor();
+ creator = creator != null ? creator : info.getCreator();
+ keywords = keywords != null ? keywords : info.getKeywords();
+ producer = producer != null ? producer : info.getProducer();
+ subject = subject != null ? subject : info.getSubject();
+ title = title != null ? title : info.getTitle();
+ }
// If the "deleteAll" flag is set, remove all metadata from the document
// information
@@ -138,15 +166,7 @@ public class MetadataController {
for (Entry<String, String> entry : allRequestParams.entrySet()) {
String key = entry.getKey();
// Check if the key is a standard metadata key
- if (!"Author".equalsIgnoreCase(key)
- && !"CreationDate".equalsIgnoreCase(key)
- && !"Creator".equalsIgnoreCase(key)
- && !"Keywords".equalsIgnoreCase(key)
- && !"modificationDate".equalsIgnoreCase(key)
- && !"Producer".equalsIgnoreCase(key)
- && !"Subject".equalsIgnoreCase(key)
- && !"Title".equalsIgnoreCase(key)
- && !"Trapped".equalsIgnoreCase(key)
+ if (!isStandardMetadataKey(key)
&& !key.contains("customKey")
&& !key.contains("customValue")) {
info.setCustomMetadataValue(key, entry.getValue());
@@ -159,6 +179,10 @@ public class MetadataController {
.matcher(key)
.replaceAll(""));
String customKey = entry.getValue();
+ if (isStandardMetadataKey(customKey)) {
+ log.warn("Skipping custom key '{}': reserved name", customKey);
+ continue;
+ }
String customValue = allRequestParams.get("customValue" + number);
info.setCustomMetadataValue(customKey, customValue);
} catch (NumberFormatException e) {
@@ -169,20 +193,21 @@ public class MetadataController {
}
}
}
- // Set creation date using utility method
- Calendar creationDateCal = PdfMetadataService.parseToCalendar(creationDate);
- info.setCreationDate(creationDateCal);
-
- // Set modification date using utility method
- Calendar modificationDateCal = PdfMetadataService.parseToCalendar(modificationDate);
- info.setModificationDate(modificationDateCal);
+ if (!keepOmitted || creationDate != null) {
+ info.setCreationDate(PdfMetadataService.parseToCalendar(creationDate));
+ }
+ if (!keepOmitted || modificationDate != null) {
+ info.setModificationDate(PdfMetadataService.parseToCalendar(modificationDate));
+ }
info.setCreator(creator);
info.setKeywords(keywords);
info.setAuthor(author);
info.setProducer(producer);
info.setSubject(subject);
info.setTitle(title);
- info.setTrapped(trapped);
+ if (!keepOmitted || trapped != null) {
+ info.setTrapped(trapped);
+ }
document.setDocumentInformation(info);
return WebResponseUtils.pdfDocToWebResponse(
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/MetadataRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/MetadataRequest.java
index 3a150bc1cc..9db5612db2 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/MetadataRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/MetadataRequest.java
@@ -20,7 +20,15 @@ public class MetadataRequest extends PDFFile {
private Boolean deleteAll = false;
@Schema(
- description = "The author of the document. Omit to remove it.",
+ description =
+ "True keeps the current value of every standard field left out, instead of"
+ + " removing it",
+ defaultValue = "false",
+ requiredMode = Schema.RequiredMode.NOT_REQUIRED)
+ private Boolean keepOmitted = false;
+
+ @Schema(
+ description = "The author of the document. Omit to remove it unless keepOmitted=true.",
example = "author",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String author;
@@ -28,20 +36,21 @@ public class MetadataRequest extends PDFFile {
@Schema(
description =
"The creation date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to"
- + " remove it.",
+ + " remove it unless keepOmitted=true.",
pattern = "yyyy/MM/dd HH:mm:ss",
example = "2023/10/01 12:00:00",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String creationDate;
@Schema(
- description = "The creator of the document. Omit to remove it.",
+ description = "The creator of the document. Omit to remove it unless keepOmitted=true.",
example = "creator",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String creator;
@Schema(
- description = "The keywords for the document. Omit to remove it.",
+ description =
+ "The keywords for the document. Omit to remove it unless keepOmitted=true.",
example = "keywords",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String keywords;
@@ -49,34 +58,35 @@ public class MetadataRequest extends PDFFile {
@Schema(
description =
"The modification date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to"
- + " remove it.",
+ + " remove it unless keepOmitted=true.",
pattern = "yyyy/MM/dd HH:mm:ss",
example = "2023/10/01 12:00:00",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String modificationDate;
@Schema(
- description = "The producer of the document. Omit to remove it.",
+ description =
+ "The producer of the document. Omit to remove it unless keepOmitted=true.",
example = "producer",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String producer;
@Schema(
- description = "The subject of the document. Omit to remove it.",
+ description = "The subject of the document. Omit to remove it unless keepOmitted=true.",
example = "subject",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String subject;
@Schema(
- description = "The title of the document. Omit to remove it.",
+ description = "The title of the document. Omit to remove it unless keepOmitted=true.",
example = "title",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String title;
@Schema(
description =
- "The trapped status of the document. Omit to remove it, which readers treat"
- + " as Unknown.",
+ "The trapped status of the document. Omit to remove it unless keepOmitted=true;"
+ + " readers treat a missing value as Unknown.",
allowableValues = {"True", "False", "Unknown"},
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private String trapped;
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index 9dd3825ddd..e160bb98e2 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -308,7 +308,7 @@ storage:
maxStorageMbTotal: -1 # Max storage across all users in MB; -1 disables total cap
maxFileMb: -1 # Max size per stored file (including history/audit) in MB; -1 disables limit
sharing:
- enabled: false # set to 'true' to enable file sharing features [ALPHA]
+ enabled: true # set to 'false' to disable file sharing features
linkEnabled: true # set to 'false' to disable share links (requires system.frontendUrl)
emailEnabled: false # set to 'true' to allow sharing by email (requires mail.enabled)
linkExpirationDays: 3 # Number of days before share links expire
diff --git a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java
index d3181d4e77..7df7592ff8 100644
--- a/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/config/CleanUrlInterceptorTest.java
@@ -52,6 +52,17 @@ class CleanUrlInterceptorTest {
assertTrue(interceptor.preHandle(request, response, new Object()));
}
+ @Test
+ void shareLinksKeepTheirActionOnly() throws Exception {
+ when(request.getContextPath()).thenReturn("");
+ when(request.getRequestURI()).thenReturn("/share/00dcac3a-fc7a-4989-9c4f-97745484d62f");
+ when(request.getQueryString()).thenReturn("action=download");
+ assertTrue(interceptor.preHandle(request, response, new Object()));
+
+ when(request.getRequestURI()).thenReturn("/some-page");
+ assertFalse(interceptor.preHandle(request, response, new Object()));
+ }
+
@Test
void preHandleRedirectsWhenDisallowedParamsPresent() throws Exception {
when(request.getRequestURI()).thenReturn("/some-page");
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
index 9ec80f4d45..e0be3e3722 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
@@ -110,7 +110,7 @@ class ConfigControllerMoreTest {
assertThat(body).containsEntry("storageEnabled", expectedStorage);
assertThat(body).containsEntry("storageGroupSigningEnabled", expectedSigning);
- assertThat(body).containsEntry("storageSharingEnabled", false);
+ assertThat(body).containsEntry("storageSharingEnabled", expectedStorage);
}
@Test
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/MetadataControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/MetadataControllerTest.java
index b21c65e8b4..4f9aa79e44 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/MetadataControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/MetadataControllerTest.java
@@ -5,26 +5,37 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
+import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
+import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
+import org.apache.pdfbox.pdmodel.PDPage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
+import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import stirling.software.SPDF.model.api.misc.MetadataRequest;
+import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.TempFileRegistry;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@@ -33,6 +44,8 @@ class MetadataControllerTest {
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@InjectMocks private MetadataController metadataController;
+ @TempDir private Path responseDirectory;
+
private PDDocument mockDocument;
private PDDocumentInformation mockInfo;
private PDDocumentCatalog mockCatalog;
@@ -126,6 +139,132 @@ class MetadataControllerTest {
verify(mockInfo).setTrapped("True");
}
+ @Test
+ void keepOmittedKeepsTheFieldsARequestLeavesOut() throws Exception {
+ PDDocument source = new PDDocument();
+ source.addPage(new PDPage());
+ PDDocumentInformation info = source.getDocumentInformation();
+ info.setAuthor("Original Author");
+ info.setSubject("Original Subject");
+ info.getCOSObject().setString(COSName.CREATION_DATE, "D:20250102030405Z");
+
+ MetadataRequest request = new MetadataRequest();
+ request.setFileInput(mockFile);
+ request.setKeepOmitted(true);
+ request.setTitle("New Title");
+
+ try (PDDocument result = writeMetadata(source, request)) {
+ PDDocumentInformation updated = result.getDocumentInformation();
+ assertEquals("New Title", updated.getTitle());
+ assertEquals("Original Author", updated.getAuthor());
+ assertEquals("Original Subject", updated.getSubject());
+ assertEquals(
+ "D:20250102030405Z", updated.getCOSObject().getString(COSName.CREATION_DATE));
+ }
+ }
+
+ @Test
+ void keepOmittedPreservesPartialAndUnparseableDateEntriesVerbatim() throws Exception {
+ PDDocument source = new PDDocument();
+ source.addPage(new PDPage());
+ source.getDocumentInformation().getCOSObject().setString(COSName.CREATION_DATE, "D:202501");
+ source.getDocumentInformation().getCOSObject().setString(COSName.MOD_DATE, "unparseable");
+ MetadataRequest request = new MetadataRequest();
+ request.setFileInput(mockFile);
+ request.setKeepOmitted(true);
+ request.setTitle("New Title");
+
+ try (PDDocument result = writeMetadata(source, request)) {
+ COSDictionary info = result.getDocumentInformation().getCOSObject();
+ assertEquals("D:202501", info.getString(COSName.CREATION_DATE));
+ assertEquals("unparseable", info.getString(COSName.MOD_DATE));
+ }
+ }
+
+ @Test
+ void keepOmittedPreservesAnUnrecognizedTrappedEntry() throws Exception {
+ PDDocument source = new PDDocument();
+ source.addPage(new PDPage());
+ source.getDocumentInformation().getCOSObject().setName(COSName.TRAPPED, "Maybe");
+ MetadataRequest request = new MetadataRequest();
+ request.setFileInput(mockFile);
+ request.setKeepOmitted(true);
+ request.setTitle("New Title");
+
+ try (PDDocument result = writeMetadata(source, request)) {
+ assertEquals("New Title", result.getDocumentInformation().getTitle());
+ assertEquals(
+ "Maybe",
+ result.getDocumentInformation()
+ .getCOSObject()
+ .getNameAsString(COSName.TRAPPED));
+ }
+ }
+
+ @Test
+ void keepOmittedCanReplaceATrappedEntry() throws Exception {
+ PDDocument source = new PDDocument();
+ source.addPage(new PDPage());
+ source.getDocumentInformation().getCOSObject().setName(COSName.TRAPPED, "Maybe");
+ MetadataRequest request = new MetadataRequest();
+ request.setFileInput(mockFile);
+ request.setKeepOmitted(true);
+ request.setTrapped("True");
+
+ try (PDDocument result = writeMetadata(source, request)) {
+ assertEquals("True", result.getDocumentInformation().getTrapped());
+ }
+ }
+
+ @Test
+ void keepOmittedIgnoresCustomPairsNamedAfterStandardFields() throws Exception {
+ PDDocument source = new PDDocument();
+ source.addPage(new PDPage());
+ source.getDocumentInformation().getCOSObject().setName(COSName.TRAPPED, "Maybe");
+ source.getDocumentInformation().getCOSObject().setString(COSName.CREATION_DATE, "D:202501");
+ Map<String, String> params = new HashMap<>();
+ params.put("customKey1", "Trapped");
+ params.put("customValue1", "True");
+ params.put("customKey2", "creationdate");
+ params.put("customValue2", "not a date");
+ params.put("customKey3", "Department");
+ params.put("customValue3", "Legal");
+ MetadataRequest request = new MetadataRequest();
+ request.setFileInput(mockFile);
+ request.setKeepOmitted(true);
+ request.setAllRequestParams(params);
+
+ try (PDDocument result = writeMetadata(source, request)) {
+ COSDictionary info = result.getDocumentInformation().getCOSObject();
+ assertEquals("Maybe", info.getNameAsString(COSName.TRAPPED));
+ assertEquals("D:202501", info.getString(COSName.CREATION_DATE));
+ assertEquals(
+ "Legal", result.getDocumentInformation().getCustomMetadataValue("Department"));
+ }
+ }
+
+ @Test
+ void deleteAllClearsDatesEvenWhenKeepOmittedIsEnabled() throws Exception {
+ PDDocument source = new PDDocument();
+ source.addPage(new PDPage());
+ source.getDocumentInformation().setAuthor("Original Author");
+ source.getDocumentInformation().getCOSObject().setString(COSName.CREATION_DATE, "D:202501");
+ source.getDocumentInformation().getCOSObject().setString(COSName.MOD_DATE, "unparseable");
+ source.getDocumentInformation().getCOSObject().setName(COSName.TRAPPED, "Maybe");
+ MetadataRequest request = new MetadataRequest();
+ request.setFileInput(mockFile);
+ request.setKeepOmitted(true);
+ request.setDeleteAll(true);
+
+ try (PDDocument result = writeMetadata(source, request)) {
+ PDDocumentInformation info = result.getDocumentInformation();
+ assertNull(info.getAuthor());
+ assertNull(info.getCOSObject().getItem(COSName.CREATION_DATE));
+ assertNull(info.getCOSObject().getItem(COSName.MOD_DATE));
+ assertNull(info.getCOSObject().getItem(COSName.TRAPPED));
+ }
+ }
+
@Test
void testMetadata_undefinedFieldsSetToNull() throws Exception {
when(pdfDocumentFactory.load(any(MultipartFile.class), eq(true))).thenReturn(mockDocument);
@@ -299,4 +438,24 @@ class MetadataControllerTest {
verify(mockInfo).setCreationDate(any());
}
+
+ private PDDocument writeMetadata(PDDocument source, MetadataRequest request)
+ throws IOException {
+ when(pdfDocumentFactory.load(mockFile, true)).thenReturn(source);
+ TempFileRegistry registry = mock(TempFileRegistry.class);
+ when(registry.register(any(File.class)))
+ .thenAnswer(invocation -> invocation.getArgument(0));
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getSystem().getTempFileManagement().setBaseTmpDir(responseDirectory.toString());
+ MetadataController controller =
+ new MetadataController(
+ pdfDocumentFactory, new TempFileManager(registry, properties));
+ var response = controller.metadata(request);
+ assertEquals(200, response.getStatusCode().value());
+ assertEquals(MediaType.APPLICATION_PDF, response.getHeaders().getContentType());
+ assertNotNull(response.getBody());
+ try (InputStream content = response.getBody().getInputStream()) {
+ return Loader.loadPDF(content.readAllBytes());
+ }
+ }
}
diff --git a/app/core/src/test/java/stirling/software/common/configuration/ConfigInitializerRestartTest.java b/app/core/src/test/java/stirling/software/common/configuration/ConfigInitializerRestartTest.java
index 9093dbaa90..c1ade45ae2 100644
--- a/app/core/src/test/java/stirling/software/common/configuration/ConfigInitializerRestartTest.java
+++ b/app/core/src/test/java/stirling/software/common/configuration/ConfigInitializerRestartTest.java
@@ -45,7 +45,7 @@ class ConfigInitializerRestartTest {
assertEquals("true", read(settings, "storage", "enabled"));
assertEquals("true", read(settings, "storage", "signing", "enabled"));
assertEquals("local", read(settings, "storage", "provider"));
- assertEquals("false", read(settings, "storage", "sharing", "enabled"));
+ assertEquals("true", read(settings, "storage", "sharing", "enabled"));
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java
index 22b8b8bc4d..feb2b09cd9 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/filter/JwtAuthenticationFilter.java
@@ -2,6 +2,7 @@ package stirling.software.proprietary.security.filter;
import static stirling.software.common.util.RequestUriUtils.isApiRequest;
import static stirling.software.common.util.RequestUriUtils.isPublicAuthEndpoint;
+import static stirling.software.common.util.RequestUriUtils.isShareLinkRead;
import static stirling.software.common.util.RequestUriUtils.isStaticResource;
import static stirling.software.proprietary.security.model.AuthenticationType.OAUTH2;
import static stirling.software.proprietary.security.model.AuthenticationType.SAML2;
@@ -79,7 +80,10 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
// Check if this is a public endpoint BEFORE validating JWT
// This allows public endpoints to work even with expired tokens in the request
if (isPublicAuthEndpoint(requestURI, contextPath)) {
- // For public auth endpoints, skip JWT validation and continue
+ // Private share links still need the signed-in user; a bad token stays anonymous.
+ if (jwtToken != null && isShareLinkRead(requestURI, contextPath)) {
+ tryAuthenticate(request, jwtToken);
+ }
filterChain.doFilter(request, response);
return;
}
@@ -184,6 +188,16 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
return true;
}
+ private void tryAuthenticate(HttpServletRequest request, String jwtToken) {
+ try {
+ jwtService.validateToken(jwtToken);
+ authenticate(request, jwtService.extractClaims(jwtToken));
+ } catch (AuthenticationException | SQLException | UnsupportedProviderException e) {
+ log.debug("Optional JWT on a public endpoint ignored: {}", e.getMessage());
+ SecurityContextHolder.clearContext();
+ }
+ }
+
private void authenticate(HttpServletRequest request, Map<String, Object> claims)
throws SQLException, UnsupportedProviderException {
String username = claims.get("sub").toString();
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/controller/FileStorageController.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/controller/FileStorageController.java
index 3e5589b31d..129c3ed6b8 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/controller/FileStorageController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/controller/FileStorageController.java
@@ -227,23 +227,24 @@ public class FileStorageController {
throw new ResponseStatusException(status, message);
}
StoredFile file = share.getFile();
- User currentUser = fileStorageService.requireAuthenticatedUser();
- boolean ownedByCurrentUser =
- currentUser != null
- && file.getOwner() != null
- && currentUser.getId().equals(file.getOwner().getId());
- return ShareLinkMetadataResponse.builder()
- .shareToken(share.getShareToken())
- .fileId(file.getId())
- .fileName(file.getOriginalFilename())
- .owner(file.getOwner() != null ? file.getOwner().getUsername() : null)
+ ShareLinkMetadataResponse.ShareLinkMetadataResponseBuilder response =
+ ShareLinkMetadataResponse.builder()
+ .shareToken(share.getShareToken())
+ .fileName(file.getOriginalFilename())
+ .accessRole(
+ share.getAccessRole() != null
+ ? share.getAccessRole().name().toLowerCase(Locale.ROOT)
+ : null)
+ .createdAt(share.getCreatedAt())
+ .expiresAt(share.getExpiresAt());
+ if (!isAuthenticated(authentication)) {
+ return response.build();
+ }
+ User owner = file.getOwner();
+ boolean ownedByCurrentUser = fileStorageService.isOwnedByCaller(file, authentication);
+ return response.fileId(file.getId())
+ .owner(owner != null ? owner.getUsername() : null)
.ownedByCurrentUser(ownedByCurrentUser)
- .accessRole(
- share.getAccessRole() != null
- ? share.getAccessRole().name().toLowerCase(Locale.ROOT)
- : null)
- .createdAt(share.getCreatedAt())
- .expiresAt(share.getExpiresAt())
.build();
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/provider/LocalStorageProvider.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/provider/LocalStorageProvider.java
index 91e8ef2945..62fb6d4cc3 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/provider/LocalStorageProvider.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/provider/LocalStorageProvider.java
@@ -8,6 +8,7 @@ import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Optional;
import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import org.springframework.core.io.FileSystemResource;
@@ -15,14 +16,17 @@ import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.security.model.User;
+@Slf4j
@RequiredArgsConstructor
public class LocalStorageProvider implements StorageProvider {
private static final Pattern CONTROL_CHARACTER_PATTERN = Pattern.compile("\\p{Cntrl}");
private final Path basePath;
+ private final AtomicBoolean missingWarned = new AtomicBoolean();
@Override
public StoredObject store(User owner, MultipartFile file) throws IOException {
@@ -63,6 +67,7 @@ public class LocalStorageProvider implements StorageProvider {
}
if (!Files.exists(targetPath)) {
+ warnMissingOnce(storageKey);
throw new IOException("File not found");
}
@@ -78,6 +83,19 @@ public class LocalStorageProvider implements StorageProvider {
Files.deleteIfExists(targetPath);
}
+ // The database knows the file but this disk does not: usually several nodes on local storage.
+ private void warnMissingOnce(String storageKey) {
+ if (missingWarned.compareAndSet(false, true)) {
+ log.warn(
+ "Stored file '{}' is in the database but not under {}. If several Stirling"
+ + " nodes share this database, enable cluster mode with shared storage"
+ + " (storage.provider=s3 or database), or each node only sees its own"
+ + " files.",
+ storageKey,
+ basePath);
+ }
+ }
+
private String sanitizeFilename(String filename) {
if (filename == null || filename.isBlank()) {
return "file";
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java
index 3a62787c37..8d7e17bf41 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/FileStorageService.java
@@ -18,6 +18,7 @@ import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@@ -116,6 +117,14 @@ public class FileStorageService {
.toList();
}
+ /** Accessible files plus temporary ones that have not expired yet (e.g. MCP results). */
+ public List<StoredFile> listLiveAccessibleFiles(User user) {
+ ensureStorageEnabled();
+ return storedFileRepository.findAccessibleFiles(user).stream()
+ .filter(file -> !isExpired(file))
+ .toList();
+ }
+
public StoredFile storeFile(User owner, MultipartFile file) {
return storeFile(owner, file, null, null);
}
@@ -690,6 +699,18 @@ public class FileStorageService {
return fileShareRepository.save(share);
}
+ /** A link only {@code recipient} (and the owner) can open, e.g. an MCP result's own link. */
+ public FileShare createShareLink(
+ User owner,
+ StoredFile file,
+ ShareAccessRole role,
+ LocalDateTime expiresAt,
+ User recipient) {
+ FileShare share = createShareLink(owner, file, role, false, expiresAt);
+ share.setSharedWithUser(recipient);
+ return fileShareRepository.save(share);
+ }
+
/** True when share links can be created, so callers can degrade instead of failing. */
public boolean canCreateShareLinks() {
return applicationProperties.getStorage().isEnabled()
@@ -925,7 +946,37 @@ public class FileStorageService {
if (principal instanceof User user) {
return user;
}
- return null;
+ // Token sign-ins (Supabase on SaaS) carry a Jwt; only its subject identifies the account,
+ // since the name is an email another local account may share.
+ if (principal instanceof Jwt jwt) {
+ return findBySupabaseId(jwt.getSubject()).orElse(null);
+ }
+ String name = authentication.getName();
+ if (name == null || name.isBlank() || "anonymousUser".equals(name)) {
+ return null;
+ }
+ Optional<User> byName = userRepository.findByUsernameIgnoreCase(name);
+ if (byName.isPresent()) {
+ return byName.get();
+ }
+ return findBySupabaseId(name).orElse(null);
+ }
+
+ /** Whether the caller owns the file, resolved the same way share-link access is. */
+ public boolean isOwnedByCaller(StoredFile file, Authentication authentication) {
+ User caller = extractAuthenticatedUser(authentication);
+ return caller != null && file.getOwner() != null && isOwner(file, caller);
+ }
+
+ private Optional<User> findBySupabaseId(String id) {
+ if (id == null) {
+ return Optional.empty();
+ }
+ try {
+ return userRepository.findBySupabaseId(UUID.fromString(id));
+ } catch (IllegalArgumentException e) {
+ return Optional.empty();
+ }
}
private static final Set<String> BLOCKED_CONTENT_TYPES =
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/StorageExpiryPurger.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/StorageExpiryPurger.java
index e6d2943491..483e85277a 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/StorageExpiryPurger.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/service/StorageExpiryPurger.java
@@ -1,7 +1,9 @@
package stirling.software.proprietary.storage.service;
+import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
+import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.springframework.data.domain.PageRequest;
@@ -12,6 +14,8 @@ import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.common.cluster.DistributedLock;
+import stirling.software.common.cluster.DistributedLock.LockHandle;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.storage.model.StoredFile;
import stirling.software.proprietary.storage.repository.StoredFileRepository;
@@ -23,21 +27,46 @@ import stirling.software.proprietary.storage.repository.StoredFileRepository;
public class StorageExpiryPurger {
private static final Pageable BATCH = PageRequest.of(0, 100);
+ private static final String PURGE_LOCK = "storage-expiry-purge";
+ private static final Duration LOCK_LEASE = Duration.ofMinutes(5);
private final StoredFileRepository storedFileRepository;
private final FileStorageService fileStorageService;
private final ApplicationProperties applicationProperties;
+ private final DistributedLock distributedLock;
@Scheduled(fixedDelay = 10, timeUnit = TimeUnit.MINUTES)
public void purgeExpiredFiles() {
if (!applicationProperties.getStorage().isEnabled()) {
return;
}
+ // One node per cycle; the others would race it to delete the same rows.
+ Optional<LockHandle> lock;
+ try {
+ lock = distributedLock.tryAcquire(PURGE_LOCK, LOCK_LEASE);
+ } catch (RuntimeException e) {
+ log.warn("Could not acquire the storage purge lock ({}); skipping", e.getMessage());
+ return;
+ }
+ if (lock.isEmpty()) {
+ log.debug("Another node is purging expired stored files; skipping this cycle");
+ return;
+ }
+ try (LockHandle held = lock.get()) {
+ purge(held);
+ }
+ }
+
+ private void purge(LockHandle held) {
LocalDateTime now = LocalDateTime.now();
// Id cursor so files that keep failing cannot pin every batch.
long afterId = 0;
List<StoredFile> batch;
do {
+ if (afterId > 0 && !held.renew(LOCK_LEASE)) {
+ log.warn("Lost the storage purge lock; stopping until the next cycle");
+ return;
+ }
batch = storedFileRepository.findExpiredAfterId(now, afterId, BATCH);
for (StoredFile file : batch) {
afterId = file.getId();
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/controller/FileStorageControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/controller/FileStorageControllerMoreTest.java
index f423ecba22..96a575693e 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/storage/controller/FileStorageControllerMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/controller/FileStorageControllerMoreTest.java
@@ -7,6 +7,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -25,8 +26,10 @@ import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
+import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
@@ -365,15 +368,63 @@ class FileStorageControllerMoreTest {
Authentication authentication = auth(owner);
when(fileStorageService.getShareByToken("tok")).thenReturn(share);
when(fileStorageService.canAccessShareLink(share, authentication)).thenReturn(true);
- when(fileStorageService.requireAuthenticatedUser()).thenReturn(owner);
+ when(fileStorageService.isOwnedByCaller(f, authentication)).thenReturn(true);
ShareLinkMetadataResponse response = controller.getShareLinkMetadata("tok", authentication);
assertThat(response.getShareToken()).isEqualTo("tok");
assertThat(response.getFileId()).isEqualTo(77L);
+ assertThat(response.getOwner()).isEqualTo("alice");
assertThat(response.isOwnedByCurrentUser()).isTrue();
}
+ @Test
+ @DisplayName("getShareLinkMetadata names the owner to a signed-in recipient")
+ void getShareLinkMetadata_signedInRecipient_seesOwner() {
+ User recipient = new User();
+ recipient.setId(12L);
+ recipient.setUsername("bob");
+ FileShare share = new FileShare();
+ share.setFile(storedFile());
+ share.setShareToken("tok");
+ Authentication authentication = auth(recipient);
+ when(fileStorageService.getShareByToken("tok")).thenReturn(share);
+ when(fileStorageService.canAccessShareLink(share, authentication)).thenReturn(true);
+
+ ShareLinkMetadataResponse response = controller.getShareLinkMetadata("tok", authentication);
+
+ assertThat(response.getOwner()).isEqualTo("alice");
+ assertThat(response.getFileId()).isEqualTo(77L);
+ assertThat(response.isOwnedByCurrentUser()).isFalse();
+ }
+
+ @Test
+ @DisplayName("getShareLinkMetadata answers a public link anonymously without owner details")
+ void getShareLinkMetadata_anonymousPublicLink_omitsOwnerDetails() {
+ FileShare share = new FileShare();
+ share.setFile(storedFile());
+ share.setShareToken("tok");
+ share.setPublicAccess(true);
+ share.setAccessRole(ShareAccessRole.EDITOR);
+ Authentication anonymous =
+ new AnonymousAuthenticationToken(
+ "key",
+ "anonymousUser",
+ AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
+ when(fileStorageService.getShareByToken("tok")).thenReturn(share);
+ when(fileStorageService.canAccessShareLink(share, anonymous)).thenReturn(true);
+
+ ShareLinkMetadataResponse response = controller.getShareLinkMetadata("tok", anonymous);
+
+ assertThat(response.getShareToken()).isEqualTo("tok");
+ assertThat(response.getFileName()).isEqualTo("doc.pdf");
+ assertThat(response.getAccessRole()).isEqualTo("editor");
+ assertThat(response.getOwner()).isNull();
+ assertThat(response.getFileId()).isNull();
+ assertThat(response.isOwnedByCurrentUser()).isFalse();
+ verify(fileStorageService, never()).requireAuthenticatedUser();
+ }
+
@Test
@DisplayName("getShareLinkMetadata denied for anonymous throws 401")
void getShareLinkMetadata_anonymousDenied_throwsUnauthorized() {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceMoreTest.java
index b7b486b7d9..5a3ae65fd2 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/FileStorageServiceMoreTest.java
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -13,6 +14,7 @@ import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
+import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
@@ -28,6 +30,8 @@ import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.oauth2.jwt.Jwt;
+import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.server.ResponseStatusException;
import stirling.software.common.model.ApplicationProperties;
@@ -385,6 +389,74 @@ class FileStorageServiceMoreTest {
assertThat(service.canAccessShareLink(share, authFor(owner))).isTrue();
}
+
+ @Test
+ void ownerOnlyShare_supabaseJwt_resolvesOwnerBySubjectNotEmail() {
+ User owner = user(1L);
+ UUID supabaseId = UUID.randomUUID();
+ FileShare share = shareFor(ownedFile(owner), owner, ShareAccessRole.VIEWER);
+ when(userRepository.findBySupabaseId(supabaseId)).thenReturn(Optional.of(owner));
+ Jwt jwt =
+ Jwt.withTokenValue("t")
+ .header("alg", "RS256")
+ .subject(supabaseId.toString())
+ .claim("email", "[email protected]")
+ .build();
+ // SaaS names the token by its email claim, which may no longer match the username.
+ Authentication auth = new JwtAuthenticationToken(jwt, List.of(), "[email protected]");
+
+ assertThat(service.canAccessShareLink(share, auth)).isTrue();
+ }
+
+ @Test
+ void recipientShare_jwtWithUnknownSubject_doesNotFallBackToEmail() {
+ User owner = user(1L);
+ User localRecipient = user(2L);
+ localRecipient.setUsername("[email protected]");
+ FileShare share = shareFor(ownedFile(owner), localRecipient, ShareAccessRole.VIEWER);
+ lenient()
+ .when(userRepository.findByUsernameIgnoreCase("[email protected]"))
+ .thenReturn(Optional.of(localRecipient));
+ Jwt jwt =
+ Jwt.withTokenValue("t")
+ .header("alg", "RS256")
+ .subject(UUID.randomUUID().toString())
+ .claim("email", "[email protected]")
+ .build();
+ Authentication auth = new JwtAuthenticationToken(jwt, List.of(), "[email protected]");
+
+ assertThat(service.canAccessShareLink(share, auth)).isFalse();
+ }
+
+ @Test
+ void isOwnedByCaller_resolvesJwtOwnerBySubject() {
+ User owner = user(1L);
+ UUID supabaseId = UUID.randomUUID();
+ StoredFile file = ownedFile(owner);
+ when(userRepository.findBySupabaseId(supabaseId)).thenReturn(Optional.of(owner));
+ Jwt jwt =
+ Jwt.withTokenValue("t")
+ .header("alg", "RS256")
+ .subject(supabaseId.toString())
+ .claim("email", "[email protected]")
+ .build();
+
+ assertThat(
+ service.isOwnedByCaller(
+ file,
+ new JwtAuthenticationToken(
+ jwt, List.of(), "[email protected]")))
+ .isTrue();
+ assertThat(service.isOwnedByCaller(file, authFor(user(9L)))).isFalse();
+ }
+
+ @Test
+ void ownerOnlyShare_otherSignedInUser_returnsFalse() {
+ User owner = user(1L);
+ FileShare share = shareFor(ownedFile(owner), owner, ShareAccessRole.VIEWER);
+
+ assertThat(service.canAccessShareLink(share, authFor(user(9L)))).isFalse();
+ }
}
// -------------------------------------------------------------------------
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/StorageExpiryPurgerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/StorageExpiryPurgerTest.java
index ad95554019..949a5e0e87 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/StorageExpiryPurgerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/service/StorageExpiryPurgerTest.java
@@ -10,9 +10,12 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
+import java.util.Optional;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import stirling.software.common.cluster.DistributedLock;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.storage.model.StoredFile;
@@ -23,7 +26,15 @@ class StorageExpiryPurgerTest {
private final StoredFileRepository repo = mock(StoredFileRepository.class);
private final FileStorageService service = mock(FileStorageService.class);
private final ApplicationProperties props = new ApplicationProperties();
- private final StorageExpiryPurger purger = new StorageExpiryPurger(repo, service, props);
+ private final DistributedLock lock = mock(DistributedLock.class);
+ private final DistributedLock.LockHandle handle = mock(DistributedLock.LockHandle.class);
+ private final StorageExpiryPurger purger = new StorageExpiryPurger(repo, service, props, lock);
+
+ @BeforeEach
+ void setUp() {
+ when(lock.tryAcquire(any(), any())).thenReturn(Optional.of(handle));
+ when(handle.renew(any())).thenReturn(true);
+ }
private static StoredFile file(long id, User owner) {
StoredFile f = new StoredFile();
@@ -48,6 +59,39 @@ class StorageExpiryPurgerTest {
verify(service).deleteFile(owner, next);
}
+ @Test
+ void anotherNodeHoldsTheLock_skipsTheCycle() {
+ props.getStorage().setEnabled(true);
+ when(lock.tryAcquire(any(), any())).thenReturn(Optional.empty());
+
+ purger.purgeExpiredFiles();
+
+ verify(repo, never()).findExpiredAfterId(any(), anyLong(), any());
+ }
+
+ @Test
+ void lockBackendError_skipsTheCycle() {
+ props.getStorage().setEnabled(true);
+ when(lock.tryAcquire(any(), any())).thenThrow(new IllegalStateException("valkey down"));
+
+ purger.purgeExpiredFiles();
+
+ verify(repo, never()).findExpiredAfterId(any(), anyLong(), any());
+ }
+
+ @Test
+ void lostLease_stopsBeforeTheNextBatchAndReleases() {
+ props.getStorage().setEnabled(true);
+ User owner = new User();
+ when(repo.findExpiredAfterId(any(), eq(0L), any())).thenReturn(List.of(file(1, owner)));
+ when(handle.renew(any())).thenReturn(false);
+
+ purger.purgeExpiredFiles();
+
+ verify(repo, never()).findExpiredAfterId(any(), eq(1L), any());
+ verify(handle).close();
+ }
+
@Test
void storageDisabled_doesNothing() {
props.getStorage().setEnabled(false);
diff --git a/app/saas/src/main/java/stirling/software/saas/security/SupabaseAuthenticationFilter.java b/app/saas/src/main/java/stirling/software/saas/security/SupabaseAuthenticationFilter.java
index 729e08e917..4b12e1ded2 100644
--- a/app/saas/src/main/java/stirling/software/saas/security/SupabaseAuthenticationFilter.java
+++ b/app/saas/src/main/java/stirling/software/saas/security/SupabaseAuthenticationFilter.java
@@ -5,6 +5,7 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static stirling.software.common.model.enumeration.Role.LIMITED_API_USER;
import static stirling.software.common.model.enumeration.Role.USER;
import static stirling.software.common.util.RequestUriUtils.isPublicAuthEndpoint;
+import static stirling.software.common.util.RequestUriUtils.isShareLinkRead;
import static stirling.software.common.util.RequestUriUtils.isStaticResource;
import static stirling.software.proprietary.security.model.AuthenticationType.ANONYMOUS;
import static stirling.software.proprietary.security.model.AuthenticationType.OAUTH2;
@@ -101,7 +102,12 @@ public class SupabaseAuthenticationFilter extends OncePerRequestFilter {
}
if (isPublicAuthEndpoint(request.getRequestURI(), request.getContextPath())) {
- filterChain.doFilter(request, response);
+ HttpServletRequest forwarded = request;
+ if (isShareLinkRead(request.getRequestURI(), request.getContextPath())
+ && !tryJwtAuthentication(request)) {
+ forwarded = new WithoutAuthorizationHeader(request);
+ }
+ filterChain.doFilter(forwarded, response);
return;
}
@@ -138,7 +144,22 @@ public class SupabaseAuthenticationFilter extends OncePerRequestFilter {
return true;
}
}
- return isPublicAuthEndpoint(uri, contextPath);
+ return isPublicAuthEndpoint(uri, contextPath) && !isShareLinkRead(uri, contextPath);
+ }
+
+ /**
+ * Signs in from an optional bearer token. False when the token was rejected: the caller must
+ * then hide it, or the resource-server filter later in the chain accepts it on its own.
+ */
+ private boolean tryJwtAuthentication(HttpServletRequest request) {
+ try {
+ processJwtAuthentication(request);
+ return true;
+ } catch (AuthenticationException e) {
+ log.debug("Optional JWT on a share link ignored: {}", e.getMessage());
+ SecurityContextHolder.clearContext();
+ return false;
+ }
}
private void processJwtAuthentication(HttpServletRequest request)
diff --git a/app/saas/src/main/java/stirling/software/saas/security/WithoutAuthorizationHeader.java b/app/saas/src/main/java/stirling/software/saas/security/WithoutAuthorizationHeader.java
new file mode 100644
index 0000000000..02c5a2c6bc
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/security/WithoutAuthorizationHeader.java
@@ -0,0 +1,39 @@
+package stirling.software.saas.security;
+
+import java.util.Collections;
+import java.util.Enumeration;
+
+import org.springframework.http.HttpHeaders;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletRequestWrapper;
+
+/** The request as later filters should see it once its bearer token has been rejected. */
+class WithoutAuthorizationHeader extends HttpServletRequestWrapper {
+
+ WithoutAuthorizationHeader(HttpServletRequest request) {
+ super(request);
+ }
+
+ @Override
+ public String getHeader(String name) {
+ return isAuthorization(name) ? null : super.getHeader(name);
+ }
+
+ @Override
+ public Enumeration<String> getHeaders(String name) {
+ return isAuthorization(name) ? Collections.emptyEnumeration() : super.getHeaders(name);
+ }
+
+ @Override
+ public Enumeration<String> getHeaderNames() {
+ return Collections.enumeration(
+ Collections.list(super.getHeaderNames()).stream()
+ .filter(name -> !isAuthorization(name))
+ .toList());
+ }
+
+ private static boolean isAuthorization(String name) {
+ return HttpHeaders.AUTHORIZATION.equalsIgnoreCase(name);
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/security/SupabaseAuthenticationFilterMoreTest.java b/app/saas/src/test/java/stirling/software/saas/security/SupabaseAuthenticationFilterMoreTest.java
index a51093167c..1e8e428b81 100644
--- a/app/saas/src/test/java/stirling/software/saas/security/SupabaseAuthenticationFilterMoreTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/security/SupabaseAuthenticationFilterMoreTest.java
@@ -10,6 +10,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.Instant;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -31,9 +32,12 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.oauth2.jwt.BadJwtException;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
+import jakarta.servlet.http.HttpServletRequest;
+
import stirling.software.proprietary.model.Team;
import stirling.software.proprietary.security.model.AuthenticationType;
import stirling.software.proprietary.security.model.User;
@@ -62,6 +66,9 @@ class SupabaseAuthenticationFilterMoreTest {
private stirling.software.proprietary.security.service.ApiKeyAuthenticationService
apiKeyAuthenticationService;
+ private static final String SHARE_LINK =
+ "/api/v1/storage/share-links/00dcac3a-fc7a-4989-9c4f-97745484d62f";
+
private SupabaseAuthenticationFilter filter;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@@ -156,6 +163,45 @@ class SupabaseAuthenticationFilterMoreTest {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
+ @Test
+ @DisplayName("share-link metadata signs in a valid bearer and still passes through")
+ void shareLinkReadAuthenticatesValidBearer() throws Exception {
+ UUID supabaseId = UUID.randomUUID();
+ when(jwtDecoder.decode("token"))
+ .thenReturn(fullJwt(supabaseId, "[email protected]", false, "email"));
+ User existing = newUser("[email protected]");
+ existing.setSupabaseId(supabaseId);
+ existing.setAuthenticationType(AuthenticationType.WEB);
+ when(supabaseUserService.findLinkedUser(supabaseId)).thenReturn(Optional.of(existing));
+ request.setRequestURI(SHARE_LINK + "/metadata");
+ request.setMethod("GET");
+ request.addHeader("Authorization", "Bearer token");
+
+ filter.doFilter(request, response, chain);
+
+ assertThat(chain.getRequest()).isSameAs(request);
+ assertThat(SecurityContextHolder.getContext().getAuthentication())
+ .isInstanceOf(EnhancedJwtAuthenticationToken.class);
+ }
+
+ @Test
+ @DisplayName("share-link read with a bad bearer stays anonymous and hides the token")
+ void shareLinkReadIgnoresInvalidBearer() throws Exception {
+ when(jwtDecoder.decode("bad")).thenThrow(new BadJwtException("bad"));
+ request.setRequestURI(SHARE_LINK);
+ request.setMethod("GET");
+ request.addHeader("Authorization", "Bearer bad");
+
+ filter.doFilter(request, response, chain);
+
+ HttpServletRequest forwarded = (HttpServletRequest) chain.getRequest();
+ assertThat(forwarded.getHeader("Authorization")).isNull();
+ assertThat(Collections.list(forwarded.getHeaderNames()))
+ .noneMatch(name -> name.equalsIgnoreCase("Authorization"));
+ assertThat(response.getStatus()).isEqualTo(200);
+ assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
+ }
+
@Test
@DisplayName("already-authenticated context passes through without decoding")
void alreadyAuthenticatedPassesThrough() throws Exception {
@@ -226,6 +272,16 @@ class SupabaseAuthenticationFilterMoreTest {
assertThat(filter.shouldNotFilter(request)).isTrue();
}
+ @Test
+ @DisplayName("share-link download and metadata are filtered so a bearer can sign in")
+ void shareLinkReadsFiltered() {
+ request.setMethod("GET");
+ request.setRequestURI(SHARE_LINK + "/metadata");
+ assertThat(filter.shouldNotFilter(request)).isFalse();
+ request.setRequestURI(SHARE_LINK);
+ assertThat(filter.shouldNotFilter(request)).isFalse();
+ }
+
@Test
@DisplayName("POST to a protected api endpoint is filtered")
void postProtectedEndpointFiltered() {
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index e517d666fe..79fa22eb6f 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -1749,7 +1749,7 @@ class UnlockPdfFormsParams(ApiModel):
class Trapped(StrEnum):
"""
- The trapped status of the document. Omit to remove it, which readers treat as Unknown.
+ The trapped status of the document. Omit to remove it unless keepOmitted=true; readers treat a missing value as Unknown.
"""
true = "True"
@@ -1759,44 +1759,60 @@ class Trapped(StrEnum):
class UpdateMetadataParams(ApiModel):
"""
- Standard fields left out are cleared, so send the current values of the others too (see get-info-on-pdf). Dates use yyyy/MM/dd HH:mm:ss. deleteAll=true removes all metadata. Input:PDF Output:PDF Type:SISO
+ Standard fields left out are cleared unless keepOmitted=true, so otherwise send the current values of the others too (see get-info-on-pdf). Dates use yyyy/MM/dd HH:mm:ss. deleteAll=true removes all metadata. Input:PDF Output:PDF Type:SISO
"""
all_request_params: dict[str, str] | None = Field(
None,
description='Custom metadata to add or update, e.g. {"Department":"Finance"}. Existing custom keys are kept. customKeyN/customValueN pairs also work.',
)
- author: str | None = Field(None, description="The author of the document. Omit to remove it.", examples=["author"])
+ author: str | None = Field(
+ None, description="The author of the document. Omit to remove it unless keepOmitted=true.", examples=["author"]
+ )
creation_date: str | None = Field(
None,
- description="The creation date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it.",
+ description="The creation date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it unless keepOmitted=true.",
examples=["2023/10/01 12:00:00"],
pattern="yyyy/MM/dd HH:mm:ss",
)
creator: str | None = Field(
- None, description="The creator of the document. Omit to remove it.", examples=["creator"]
+ None,
+ description="The creator of the document. Omit to remove it unless keepOmitted=true.",
+ examples=["creator"],
)
delete_all: bool = Field(
False, description="True removes all metadata, including XMP, and ignores the other fields"
)
+ keep_omitted: bool = Field(
+ False, description="True keeps the current value of every standard field left out, instead of removing it"
+ )
keywords: str | None = Field(
- None, description="The keywords for the document. Omit to remove it.", examples=["keywords"]
+ None,
+ description="The keywords for the document. Omit to remove it unless keepOmitted=true.",
+ examples=["keywords"],
)
modification_date: str | None = Field(
None,
- description="The modification date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it.",
+ description="The modification date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it unless keepOmitted=true.",
examples=["2023/10/01 12:00:00"],
pattern="yyyy/MM/dd HH:mm:ss",
)
producer: str | None = Field(
- None, description="The producer of the document. Omit to remove it.", examples=["producer"]
+ None,
+ description="The producer of the document. Omit to remove it unless keepOmitted=true.",
+ examples=["producer"],
)
subject: str | None = Field(
- None, description="The subject of the document. Omit to remove it.", examples=["subject"]
+ None,
+ description="The subject of the document. Omit to remove it unless keepOmitted=true.",
+ examples=["subject"],
+ )
+ title: str | None = Field(
+ None, description="The title of the document. Omit to remove it unless keepOmitted=true.", examples=["title"]
)
- title: str | None = Field(None, description="The title of the document. Omit to remove it.", examples=["title"])
trapped: Trapped | None = Field(
- None, description="The trapped status of the document. Omit to remove it, which readers treat as Unknown."
+ None,
+ description="The trapped status of the document. Omit to remove it unless keepOmitted=true; readers treat a missing value as Unknown.",
)
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index 2982d741ff..8bf165e238 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -14002,7 +14002,6 @@ noLinks = "No active share links yet."
noSharedUsers = "No users have access yet."
openInApp = "Open in Stirling PDF"
ownerLabel = "Owner"
-ownerUnknown = "Unknown"
removeLink = "Remove link"
removeUser = "Remove"
requiresLogin = "This shared file requires login."
diff --git a/frontend/src/editor/core/tests/stubbed/share-link-auto-action.spec.ts b/frontend/src/editor/core/tests/stubbed/share-link-auto-action.spec.ts
new file mode 100644
index 0000000000..9333847f59
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/share-link-auto-action.spec.ts
@@ -0,0 +1,119 @@
+import fs from "node:fs";
+import path from "node:path";
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+
+const admin = {
+ id: 1,
+ username: "admin",
+ role: "ROLE_ADMIN",
+ portalAccess: true,
+};
+const TOKEN = "share-token";
+const FILE_NAME = "Shared Report.pdf";
+const PDF = fs.readFileSync(
+ path.resolve("src/editor/core/tests/test-fixtures/user-sample.pdf"),
+);
+
+test.use({
+ autoGoto: false,
+ seedJwt: true,
+ stubOptions: { enableLogin: true, isAdmin: true, user: admin },
+});
+
+let downloadRequests = 0;
+
+test.beforeEach(async ({ page, context }) => {
+ downloadRequests = 0;
+ await context.route("**/api/v1/**", (route) => route.fulfill({ json: {} }));
+ await page.route("**/api/v1/auth/me", (route) =>
+ route.fulfill({ json: { user: admin } }),
+ );
+ await page.route("**/api/v1/proprietary/ui-data/login", (route) =>
+ route.fulfill({ json: { enableLogin: true, loginMethod: "normal" } }),
+ );
+ await page.route("**/api/v1/proprietary/ui-data/account", (route) =>
+ route.fulfill({
+ json: { ...admin, settings: "{}", changeCredsFlag: false },
+ }),
+ );
+ await page.route(
+ /\/api\/v1\/storage\/share-links\/[^/]+\/metadata/,
+ (route) =>
+ route.fulfill({
+ json: {
+ fileName: FILE_NAME,
+ owner: "[email protected]",
+ accessRole: "editor",
+ createdAt: "2026-11-02T09:15:00Z",
+ },
+ }),
+ );
+ await page.route(
+ /\/api\/v1\/storage\/share-links\/[^/?]+(\?.*)?$/,
+ (route) => {
+ downloadRequests += 1;
+ return route.fulfill({
+ status: 200,
+ body: PDF,
+ headers: {
+ "content-type": "application/pdf",
+ "content-disposition": `attachment; filename="${FILE_NAME}"`,
+ },
+ });
+ },
+ );
+});
+
+test("?action=download runs once and is removed from the URL", async ({
+ page,
+}) => {
+ const downloads: string[] = [];
+ page.on("download", (download) =>
+ downloads.push(download.suggestedFilename()),
+ );
+
+ await page.goto(`/share/${TOKEN}?action=download&ref=chat#card`, {
+ waitUntil: "domcontentloaded",
+ });
+ await expect.poll(() => downloads).toEqual([FILE_NAME]);
+ await expect(page).toHaveURL(
+ (url) =>
+ url.pathname === `/share/${TOKEN}` &&
+ url.search === "?ref=chat" &&
+ url.hash === "#card",
+ );
+
+ await page.reload({ waitUntil: "domcontentloaded" });
+ await expect(page.getByText(FILE_NAME, { exact: true })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Download" })).toBeEnabled();
+ await page.getByRole("button", { name: "Download" }).click();
+ await expect.poll(() => downloads).toEqual([FILE_NAME, FILE_NAME]);
+ expect(downloadRequests).toBe(2);
+});
+
+test("?action=open is removed from the URL when opening fails", async ({
+ page,
+}) => {
+ await page.route(
+ /\/api\/v1\/storage\/share-links\/[^/?]+(\?.*)?$/,
+ (route) => {
+ downloadRequests += 1;
+ return route.fulfill({ status: 500, json: {} });
+ },
+ );
+
+ await page.goto(`/share/${TOKEN}?action=open&ref=chat`, {
+ waitUntil: "domcontentloaded",
+ });
+ await expect(page.getByText("Unable to open shared file.")).toBeVisible();
+ await expect(page).toHaveURL(
+ (url) => url.pathname === `/share/${TOKEN}` && url.search === "?ref=chat",
+ );
+
+ await page.reload({ waitUntil: "domcontentloaded" });
+ await expect(page.getByText(FILE_NAME, { exact: true })).toBeVisible();
+ await expect(
+ page.getByRole("button", { name: "Open in Stirling PDF" }),
+ ).toBeEnabled();
+ expect(downloadRequests).toBe(1);
+});
diff --git a/frontend/src/editor/core/tests/stubbed/share-link-signed-out.spec.ts b/frontend/src/editor/core/tests/stubbed/share-link-signed-out.spec.ts
new file mode 100644
index 0000000000..1e6f0382fc
--- /dev/null
+++ b/frontend/src/editor/core/tests/stubbed/share-link-signed-out.spec.ts
@@ -0,0 +1,101 @@
+import fs from "node:fs";
+import path from "node:path";
+import type { Page, Route } from "@playwright/test";
+import { test, expect } from "@editor/tests/helpers/stub-test-base";
+
+const admin = {
+ id: 1,
+ username: "admin",
+ role: "ROLE_ADMIN",
+ portalAccess: true,
+};
+const TOKEN = "00dcac3a-fc7a-4989-9c4f-97745484d62f";
+const FILE_NAME = "Shared Report.pdf";
+const PDF = fs.readFileSync(
+ path.resolve("src/editor/core/tests/test-fixtures/user-sample.pdf"),
+);
+
+test.use({
+ autoGoto: false,
+ stubOptions: { enableLogin: true, isAdmin: true, user: admin },
+});
+
+const hasAuth = (route: Route) =>
+ Boolean(route.request().headers()["authorization"]);
+
+async function stubShareLink(page: Page, publicLink: boolean): Promise<void> {
+ await page.route("**/api/v1/auth/me", (route) =>
+ route.fulfill({ status: 401, json: {} }),
+ );
+ await page.route("**/api/v1/proprietary/ui-data/login", (route) =>
+ route.fulfill({ json: { enableLogin: true, loginMethod: "normal" } }),
+ );
+ await page.route(
+ /\/api\/v1\/storage\/share-links\/[^/]+\/metadata/,
+ (route) => {
+ if (!publicLink && !hasAuth(route)) {
+ return route.fulfill({ status: 401, json: {} });
+ }
+ return route.fulfill({
+ json: {
+ shareToken: TOKEN,
+ fileName: FILE_NAME,
+ accessRole: "editor",
+ createdAt: "2026-11-02T09:15:00Z",
+ },
+ });
+ },
+ );
+ await page.route(
+ /\/api\/v1\/storage\/share-links\/[^/?]+(\?.*)?$/,
+ (route) => {
+ if (!publicLink && !hasAuth(route)) {
+ return route.fulfill({ status: 401, json: {} });
+ }
+ return route.fulfill({
+ status: 200,
+ body: PDF,
+ headers: {
+ "content-type": "application/pdf",
+ "content-disposition": `attachment; filename="${FILE_NAME}"`,
+ },
+ });
+ },
+ );
+}
+
+test.beforeEach(async ({ context }) => {
+ await context.route("**/api/v1/**", (route) => route.fulfill({ json: {} }));
+});
+
+test("a public link opens signed out and downloads without signing in", async ({
+ page,
+}) => {
+ await stubShareLink(page, true);
+ const downloads: string[] = [];
+ page.on("download", (download) =>
+ downloads.push(download.suggestedFilename()),
+ );
+
+ await page.goto(`/share/${TOKEN}`, { waitUntil: "domcontentloaded" });
+
+ await expect(page.getByText(FILE_NAME, { exact: true })).toBeVisible();
+ await expect(page).toHaveURL((url) => url.pathname === `/share/${TOKEN}`);
+ await expect(page.getByText(/^Owner:/)).toHaveCount(0);
+ await page.getByRole("button", { name: "Download" }).click();
+ await expect.poll(() => downloads).toEqual([FILE_NAME]);
+ await expect(page).toHaveURL((url) => url.pathname === `/share/${TOKEN}`);
+});
+
+test("a private link signed out still goes to sign-in", async ({ page }) => {
+ await stubShareLink(page, false);
+
+ await page.goto(`/share/${TOKEN}`, { waitUntil: "domcontentloaded" });
+
+ await expect(page).toHaveURL(
+ (url) =>
+ url.pathname === "/login" &&
+ url.searchParams.get("from") === `/share/${TOKEN}`,
+ );
+ await expect(page.getByText(FILE_NAME, { exact: true })).toHaveCount(0);
+});
diff --git a/frontend/src/editor/core/types/toolApiTypes.ts b/frontend/src/editor/core/types/toolApiTypes.ts
index 8f7c8f1de3..a06bed04e3 100644
--- a/frontend/src/editor/core/types/toolApiTypes.ts
+++ b/frontend/src/editor/core/types/toolApiTypes.ts
@@ -777,15 +777,15 @@ export interface MetadataRequest {
[k: string]: string | undefined;
};
/**
- * The author of the document. Omit to remove it.
+ * The author of the document. Omit to remove it unless keepOmitted=true.
*/
author?: string;
/**
- * The creation date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it.
+ * The creation date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it unless keepOmitted=true.
*/
creationDate?: string;
/**
- * The creator of the document. Omit to remove it.
+ * The creator of the document. Omit to remove it unless keepOmitted=true.
*/
creator?: string;
/**
@@ -793,27 +793,31 @@ export interface MetadataRequest {
*/
deleteAll?: boolean;
/**
- * The keywords for the document. Omit to remove it.
+ * True keeps the current value of every standard field left out, instead of removing it
+ */
+ keepOmitted?: boolean;
+ /**
+ * The keywords for the document. Omit to remove it unless keepOmitted=true.
*/
keywords?: string;
/**
- * The modification date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it.
+ * The modification date of the document (format: yyyy/MM/dd HH:mm:ss). Omit to remove it unless keepOmitted=true.
*/
modificationDate?: string;
/**
- * The producer of the document. Omit to remove it.
+ * The producer of the document. Omit to remove it unless keepOmitted=true.
*/
producer?: string;
/**
- * The subject of the document. Omit to remove it.
+ * The subject of the document. Omit to remove it unless keepOmitted=true.
*/
subject?: string;
/**
- * The title of the document. Omit to remove it.
+ * The title of the document. Omit to remove it unless keepOmitted=true.
*/
title?: string;
/**
- * The trapped status of the document. Omit to remove it, which readers treat as Unknown.
+ * The trapped status of the document. Omit to remove it unless keepOmitted=true; readers treat a missing value as Unknown.
*/
trapped?: "True" | "False" | "Unknown";
}
diff --git a/frontend/src/editor/proprietary/routes/ShareLinkPage.tsx b/frontend/src/editor/proprietary/routes/ShareLinkPage.tsx
index 155e98218f..92a0305829 100644
--- a/frontend/src/editor/proprietary/routes/ShareLinkPage.tsx
+++ b/frontend/src/editor/proprietary/routes/ShareLinkPage.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { isAxiosError } from "axios";
-import { useNavigate, useParams } from "react-router-dom";
+import { useLocation, useNavigate, useParams } from "react-router-dom";
import {
Alert,
Badge,
@@ -35,15 +35,41 @@ type ShareLinkStatus =
| "notfound"
| "error";
+const LOGIN_REDIRECT_MARKER = "shareLinkLoginRedirect:";
+
+function readSessionFlag(key: string): boolean {
+ try {
+ return sessionStorage.getItem(key) !== null;
+ } catch {
+ return false;
+ }
+}
+
+function writeSessionFlag(key: string, on: boolean): void {
+ try {
+ if (on) sessionStorage.setItem(key, "1");
+ else sessionStorage.removeItem(key);
+ } catch {
+ return;
+ }
+}
+
export default function ShareLinkPage() {
const { token } = useParams<{ token: string }>();
const { actions } = useFileActions();
const { actions: navActions } = useNavigationActions();
const navigate = useNavigate();
+ const location = useLocation();
const { t } = useTranslation();
const [status, setStatus] = useState<ShareLinkStatus>("loading");
const [metadata, setMetadata] = useState<ShareLinkMetadata | null>(null);
const [isWorking, setIsWorking] = useState(false);
+ // ?action=download|open (e.g. from a chat app's result card) runs that button once.
+ const [autoActionDone, setAutoActionDone] = useState(false);
+ const autoAction = useMemo(
+ () => new URLSearchParams(location.search).get("action"),
+ [location.search],
+ );
const normalizedToken = useMemo(() => (token || "").trim(), [token]);
const shareRole = (metadata?.accessRole ?? "viewer").toLowerCase();
@@ -85,11 +111,39 @@ export default function ShareLinkPage() {
}, [loadMetadata]);
const handleLogin = useCallback(() => {
- navigate("/login", {
+ // In the query as well as state: the SaaS login page only reads ?from=.
+ const back = `/share/${normalizedToken}${location.search}`;
+ navigate(`/login?from=${encodeURIComponent(back)}`, {
replace: true,
- state: { from: { pathname: `/share/${normalizedToken}` } },
+ state: {
+ from: {
+ pathname: `/share/${normalizedToken}`,
+ search: location.search,
+ },
+ },
});
- }, [navigate, normalizedToken]);
+ }, [location.search, navigate, normalizedToken]);
+
+ const clearActionParam = useCallback(() => {
+ const params = new URLSearchParams(location.search);
+ if (!params.has("action")) return;
+ params.delete("action");
+ const search = params.toString();
+ navigate(
+ {
+ pathname: location.pathname,
+ search: search ? `?${search}` : "",
+ hash: location.hash,
+ },
+ { replace: true, state: location.state },
+ );
+ }, [
+ location.hash,
+ location.pathname,
+ location.search,
+ location.state,
+ navigate,
+ ]);
const handleDownload = useCallback(async () => {
if (!normalizedToken || !canDownload) return;
@@ -104,10 +158,12 @@ export default function ShareLinkPage() {
link.click();
link.remove();
URL.revokeObjectURL(url);
+ clearActionParam();
} catch (error: unknown) {
const statusCode = isAxiosError(error)
? error.response?.status
: undefined;
+ if (statusCode !== 401) clearActionParam();
if (statusCode === 401) {
setStatus("login");
} else if (statusCode === 403) {
@@ -128,7 +184,7 @@ export default function ShareLinkPage() {
} finally {
setIsWorking(false);
}
- }, [canDownload, normalizedToken, t]);
+ }, [canDownload, clearActionParam, normalizedToken, t]);
const handleOpen = useCallback(async () => {
if (!normalizedToken || !canOpen) return;
@@ -148,6 +204,7 @@ export default function ShareLinkPage() {
const statusCode = isAxiosError(error)
? error.response?.status
: undefined;
+ if (statusCode !== 401) clearActionParam();
if (statusCode === 401) {
setStatus("login");
} else if (statusCode === 403) {
@@ -165,12 +222,51 @@ export default function ShareLinkPage() {
} finally {
setIsWorking(false);
}
- }, [actions, canOpen, metadata, navActions, navigate, normalizedToken, t]);
+ }, [
+ actions,
+ canOpen,
+ clearActionParam,
+ metadata,
+ navActions,
+ navigate,
+ normalizedToken,
+ t,
+ ]);
+
+ // Signed out: go straight to the normal sign-in page; it returns here afterwards. Only once
+ // per link and tab: a session the backend keeps rejecting would otherwise loop through /login.
+ useEffect(() => {
+ if (!normalizedToken) return;
+ const marker = `${LOGIN_REDIRECT_MARKER}${normalizedToken}`;
+ if (status === "ready") {
+ writeSessionFlag(marker, false);
+ } else if (status === "login" && !readSessionFlag(marker)) {
+ writeSessionFlag(marker, true);
+ handleLogin();
+ }
+ }, [handleLogin, normalizedToken, status]);
+
+ useEffect(() => {
+ if (status !== "ready" || autoActionDone) return;
+ if (autoAction === "download" && canDownload) {
+ setAutoActionDone(true);
+ void handleDownload();
+ } else if (autoAction === "open" && canOpen) {
+ setAutoActionDone(true);
+ void handleOpen();
+ }
+ }, [
+ autoAction,
+ autoActionDone,
+ canDownload,
+ canOpen,
+ handleDownload,
+ handleOpen,
+ status,
+ ]);
const title =
metadata?.fileName || t("storageShare.titleDefault", "Shared file");
- const ownerLabel =
- metadata?.owner || t("storageShare.ownerUnknown", "Unknown");
return (
<div style={{ minHeight: "100%", padding: "2.5rem 1.5rem" }}>
@@ -213,10 +309,12 @@ export default function ShareLinkPage() {
<Text size="lg" fw={600} className={privateContentClassName}>
{title}
</Text>
- <Text size="sm" c="dimmed">
- {t("storageShare.ownerLabel", "Owner")}:{" "}
- <PrivateContent>{ownerLabel}</PrivateContent>
- </Text>
+ {metadata?.owner && (
+ <Text size="sm" c="dimmed">
+ {t("storageShare.ownerLabel", "Owner")}:{" "}
+ <PrivateContent>{metadata.owner}</PrivateContent>
+ </Text>
+ )}
{metadata?.createdAt && (
<Text size="sm" c="dimmed">
{t("storageShare.createdAt", "Created")}{" "}
diff --git a/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx b/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx
index 403bacbc7f..73f9ee82f4 100644
--- a/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx
+++ b/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx
@@ -124,6 +124,22 @@ describe("RunLocationGate", () => {
},
);
+ it.each([
+ "/share/00dcac3a-fc7a-4989-9c4f-97745484d62f",
+ "/login?next=%2Fshare%2F00dcac3a-fc7a-4989-9c4f-97745484d62f",
+ "/login?from=%2Fshare%2F00dcac3a-fc7a-4989-9c4f-97745484d62f%3Faction%3Ddownload",
+ "/signup?next=%2Fshare%2F00dcac3a-fc7a-4989-9c4f-97745484d62f",
+ ])("lets %s through to the shared file without asking", (path) => {
+ renderAt(path);
+ expect(screen.getByText("The app")).toBeInTheDocument();
+ expect(window.localStorage.getItem(SEEN_KEY)).toBeNull();
+ });
+
+ it("still asks on sign-in headed to a share-like path that is not a share link", () => {
+ renderAt("/login?next=%2Fshared");
+ expect(screen.queryByText("The app")).not.toBeInTheDocument();
+ });
+
it("still asks on sign-in headed anywhere else", () => {
renderAt("/login");
expect(screen.queryByText("The app")).not.toBeInTheDocument();
diff --git a/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx b/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx
index b95269ae2a..bf0cb3ea8c 100644
--- a/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx
+++ b/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx
@@ -28,24 +28,32 @@ const FLOW_PATHS = [
...LANDING_PATHS,
];
-// Signing in from a landing link detours through these, naming it as `next`.
+// Signing in from a landing link or a shared file detours through these, naming
+// it as `next` (or `from`).
const AUTH_PATHS = ["/login", "/signup"];
+function authDestination(pathname: string, search: string): string | undefined {
+ if (!AUTH_PATHS.includes(normalizePath(pathname))) return undefined;
+ const params = new URLSearchParams(search);
+ return nextPathOf(params.get("next") ?? params.get("from"));
+}
+
+function isShareLink(path: string): boolean {
+ return path.startsWith("/share/");
+}
+
/** On a landing link, or signing in on the way to one. */
function isLanding(pathname: string, search: string): boolean {
- const path = normalizePath(pathname);
- if (LANDING_PATHS.includes(path)) return true;
- const nextPath = nextPathOf(new URLSearchParams(search).get("next"));
- return (
- AUTH_PATHS.includes(path) &&
- nextPath !== undefined &&
- LANDING_PATHS.includes(nextPath)
- );
+ if (LANDING_PATHS.includes(normalizePath(pathname))) return true;
+ const destination = authDestination(pathname, search);
+ return destination !== undefined && LANDING_PATHS.includes(destination);
}
export function bypassesRunLocation(pathname: string, search = ""): boolean {
const path = normalizePath(pathname);
- if (FLOW_PATHS.includes(path) || path.startsWith("/share/")) return true;
+ if (FLOW_PATHS.includes(path) || isShareLink(path)) return true;
+ const destination = authDestination(pathname, search);
+ if (destination !== undefined && isShareLink(destination)) return true;
return isLanding(pathname, search);
}
diff --git a/frontend/src/editor/saas/routes/Login.test.tsx b/frontend/src/editor/saas/routes/Login.test.tsx
new file mode 100644
index 0000000000..9564a6998e
--- /dev/null
+++ b/frontend/src/editor/saas/routes/Login.test.tsx
@@ -0,0 +1,164 @@
+import type { ButtonHTMLAttributes, ReactNode } from "react";
+import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
+import { act, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+const state = vi.hoisted(() => ({
+ session: null as { user: { id: string } } | null,
+ isAnonymous: false,
+ navigate: vi.fn(),
+ refresh: vi.fn(),
+ anonymousSignIn: vi.fn(),
+ landing: vi.fn(),
+ takeDestination: vi.fn(),
+}));
+
+vi.mock("@editor/auth/UseSession", () => ({
+ useAuth: () => ({
+ session: state.session,
+ isAnonymous: state.isAnonymous,
+ loading: false,
+ refreshSession: state.refresh,
+ }),
+}));
+vi.mock("@editor/auth/supabase", () => ({
+ supabase: { auth: {} },
+ signInAnonymously: state.anonymousSignIn,
+}));
+vi.mock("@editor/utils/loginLanding", () => ({
+ resolveLandingPath: state.landing,
+}));
+vi.mock("@editor/services/pendingDestination", () => ({
+ rememberPendingDestination: vi.fn(),
+ takePendingDestination: state.takeDestination,
+}));
+vi.mock("react-router-dom", async () => ({
+ ...(await vi.importActual<typeof import("react-router-dom")>(
+ "react-router-dom",
+ )),
+ useNavigate: () => state.navigate,
+}));
+vi.mock("@editor/hooks/useTranslation", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: unknown) =>
+ typeof fallback === "string" ? fallback : key,
+ }),
+}));
+vi.mock("@editor/hooks/useDocumentMeta", () => ({ useDocumentMeta: () => {} }));
+vi.mock("@editor/routes/authShared/AuthLayout", () => ({
+ default: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+}));
+vi.mock("@editor/ui/Button", () => ({
+ Button: ({
+ children,
+ onClick,
+ disabled,
+ }: ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button onClick={onClick} disabled={disabled}>
+ {children}
+ </button>
+ ),
+}));
+vi.mock("@editor/ui/Icon", () => ({ Icon: () => null }));
+vi.mock("@editor/components/shared/PrivateContent", () => ({
+ PrivateContent: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+vi.mock("@editor/routes/login/OAuthButtons", () => ({ default: () => null }));
+vi.mock("@editor/routes/login/EmailPasswordForm", () => ({
+ default: () => <div data-testid="credential-form">Sign in</div>,
+}));
+vi.mock("@editor/routes/login/LoggedInState", () => ({
+ default: () => <div>Signed in</div>,
+}));
+vi.mock("@editor/auth/ui/ErrorMessage", () => ({
+ default: ({ error }: { error: string | null }) =>
+ error ? <div role="alert">{error}</div> : null,
+}));
+
+const Login = (await import("@editor/routes/Login")).default;
+const originalUrl = window.location.href;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.session = null;
+ state.isAnonymous = false;
+ state.refresh.mockResolvedValue(undefined);
+ state.anonymousSignIn.mockResolvedValue({ data: { user: { id: "guest" } } });
+ state.landing.mockResolvedValue("/editor");
+ state.takeDestination.mockReturnValue(null);
+ window.history.replaceState({}, "", "/login");
+});
+
+afterEach(() => {
+ window.history.replaceState({}, "", originalUrl);
+});
+
+describe("SaaS guest sign-in", () => {
+ it("navigates to the normal landing page after creating a guest session", async () => {
+ render(<Login />);
+ await userEvent.click(screen.getByRole("button", { name: /^Skip/ }));
+ await waitFor(() =>
+ expect(state.navigate).toHaveBeenCalledWith("/editor", { replace: true }),
+ );
+ expect(state.refresh).toHaveBeenCalledOnce();
+ });
+
+ it("uses an explicit safe return path and consumes a remembered destination", async () => {
+ window.history.replaceState(
+ {},
+ "",
+ "/login?from=%2Feditor%3Ftool%3Dcompress",
+ );
+ state.takeDestination.mockReturnValue("/workspace");
+ render(<Login />);
+ await userEvent.click(screen.getByRole("button", { name: /^Skip/ }));
+ await waitFor(() =>
+ expect(state.navigate).toHaveBeenCalledWith("/editor?tool=compress", {
+ replace: true,
+ }),
+ );
+ expect(state.takeDestination).toHaveBeenCalledOnce();
+ expect(state.landing).not.toHaveBeenCalled();
+ });
+
+ it("uses a remembered destination when there is no explicit return path", async () => {
+ state.takeDestination.mockReturnValue("/workspace");
+ render(<Login />);
+ await userEvent.click(screen.getByRole("button", { name: /^Skip/ }));
+ await waitFor(() =>
+ expect(state.navigate).toHaveBeenCalledWith("/workspace", {
+ replace: true,
+ }),
+ );
+ expect(state.landing).not.toHaveBeenCalled();
+ });
+
+ it("keeps an existing guest on a requested account sign-in form", () => {
+ state.session = { user: { id: "guest" } };
+ state.isAnonymous = true;
+ window.history.replaceState({}, "", "/login?from=%2Foauth%2Fconsent");
+ render(<Login />);
+ expect(screen.getByTestId("credential-form")).toBeInTheDocument();
+ expect(state.navigate).not.toHaveBeenCalled();
+ });
+
+ it("waits for session refresh before navigating", async () => {
+ let finishRefresh: () => void = () => {};
+ state.refresh.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finishRefresh = resolve;
+ }),
+ );
+ render(<Login />);
+ await userEvent.click(screen.getByRole("button", { name: /^Skip/ }));
+ expect(state.refresh).toHaveBeenCalledOnce();
+ expect(state.navigate).not.toHaveBeenCalled();
+ await act(async () => {
+ finishRefresh();
+ });
+ await waitFor(() =>
+ expect(state.navigate).toHaveBeenCalledWith("/editor", { replace: true }),
+ );
+ });
+});
diff --git a/frontend/src/editor/saas/routes/Login.tsx b/frontend/src/editor/saas/routes/Login.tsx
index fa415a8c7b..4c8aa09cf6 100644
--- a/frontend/src/editor/saas/routes/Login.tsx
+++ b/frontend/src/editor/saas/routes/Login.tsx
@@ -270,11 +270,13 @@ export default function Login() {
"[Login] Anonymous sign in successful, refreshing session...",
);
- // Refresh session to ensure backend endpoints are properly synchronized
await refreshSession();
// A guest session does not count as signed in here, so nothing else moves them on.
- continueToNext();
+ const remembered = takePendingDestination();
+ navigate(nextPath ?? remembered ?? (await resolveLandingPath()), {
+ replace: true,
+ });
}
} catch (err) {
console.error("[Login] Unexpected error:", err);