#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Tighten processing folder input handling (#8031)
Reece Browne1066f35e3e3a
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.javaindex 8424422ec2..d74d3b40c3 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/ProcessingFolderController.java@@ -359,7 +359,7 @@ public class ProcessingFolderController {Policy policy = requireOwn(id, user);Path directory = watchedDirectory(policy);if (directory == null) {- return storageFiles(policy);+ return storageFiles(policy, user);}// Re-check on read: the permitted roots may have narrowed since the folder was created.Path permitted = folderAccessGuard.requirePermitted(directory);@@ -431,18 +431,8 @@ public class ProcessingFolderController {* A storage-backed folder's files, joined to the ledger by the identity the storage source* claims by.*/- private List<MountedFileView> storageFiles(Policy policy) {- UUID folderId = storageFolderId(policy);- if (folderId == null) {- return List.of();- }- List<StoredFile> files =- storedFileRepository.findAllByFolderId(folderId).stream()- .filter(- file ->- file.getPurpose() == null- || file.getPurpose() == FilePurpose.GENERIC)- .toList();+ private List<MountedFileView> storageFiles(Policy policy, User user) {+ List<StoredFile> files = ownedStorageFiles(policy, user);Map<String, ClaimState> states =processedLedger.statesFor(policy.id(), files.stream().map(StorageFileIdentities::identity).toList());@@ -459,6 +449,20 @@ public class ProcessingFolderController {.toList();}+ private List<StoredFile> ownedStorageFiles(Policy policy, User user) {+ UUID folderId = storageFolderId(policy);+ if (folderId == null) {+ return List.of();+ }+ requireOwnedFolder(folderId.toString(), user);+ return storedFileRepository.findAllByFolderIdAndOwner(folderId, user).stream()+ .filter(+ file ->+ file.getPurpose() == null+ || file.getPurpose() == FilePurpose.GENERIC)+ .toList();+ }+private static long lastModifiedMillis(StoredFile file) {LocalDateTime updatedAt = file.getUpdatedAt();return updatedAt == null@@ -545,7 +549,7 @@ public class ProcessingFolderController {throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "a file name is required");}String name = request.name().trim();- String identity = identityForName(policy, name);+ String identity = identityForName(policy, name, user);if (identity == null || !processedLedger.forgetFailure(policy.id(), identity)) {throw new ResponseStatusException(HttpStatus.CONFLICT, "'" + name + "' has no failure to retry");@@ -710,14 +714,10 @@ public class ProcessingFolderController {}/** The ledger identity of a named file in this folder; null when no such file is listed. */- private String identityForName(Policy policy, String name) {+ private String identityForName(Policy policy, String name, User user) {Path directory = watchedDirectory(policy);if (directory == null) {- UUID folderId = storageFolderId(policy);- if (folderId == null) {- return null;- }- return storedFileRepository.findAllByFolderId(folderId).stream()+ return ownedStorageFiles(policy, user).stream().filter(file -> name.equals(file.getOriginalFilename())).map(StorageFileIdentities::identity).findFirst()diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.javaindex c7cbbd7d5c..56df2b5981 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyRunner.java@@ -243,7 +243,7 @@ public class PolicyRunner {}List<ResolvedInput> work;try {- work = source.resolve(spec, context);+ work = source.resolve(storedSource, context, policy.owner());} catch (IOException | RuntimeException e) {log.warn("Failed to resolve source '{}' for policy {}: {}",diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.javaindex 59836624ad..323e3d31a4 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/FolderInputSource.java@@ -29,6 +29,7 @@ import stirling.software.proprietary.policy.config.FolderAccessGuard;import stirling.software.proprietary.policy.ledger.FolderIdentities;import stirling.software.proprietary.policy.model.InputSpec;import stirling.software.proprietary.policy.model.PolicyInputs;+import stirling.software.proprietary.policy.source.Source;/*** Reads input files from a directory; each ready file is its own unit of work, claimed through the@@ -75,6 +76,13 @@ public class FolderInputSource implements InputSource {return List.of(FolderConfig.from(spec.options()).directory());}+ /** Filesystem permissions follow the installation's {@link FolderAccessGuard}. */+ @Override+ public List<ResolvedInput> resolve(Source source, ResolveContext ctx, String policyOwner)+ throws IOException {+ return resolve(source.toInputSpec(), ctx);+ }+@Overridepublic List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {FolderConfig config = FolderConfig.from(spec.options());diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/InputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/InputSource.javaindex 15fb0d84f2..25dd8e11b8 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/InputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/InputSource.java@@ -6,6 +6,7 @@ import java.util.List;import java.util.Map;import stirling.software.proprietary.policy.model.InputSpec;+import stirling.software.proprietary.policy.source.Source;/*** Resolves a policy {@link InputSpec} into the files to run on. Implementations are beans selected@@ -36,6 +37,15 @@ public interface InputSource {*/List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException;+ /**+ * Resolve a persisted source on behalf of its policy owner, including on background threads+ * without request authentication. Both identities must come from server-owned records, never+ * input options. Sources backed by private user storage must scope their reads to that owner;+ * sources over a connection shared by a policy's whole team say why they need not.+ */+ List<ResolvedInput> resolve(Source source, ResolveContext ctx, String policyOwner)+ throws IOException;+/*** Whether {@link #resolve} observes everything in the source (a complete listing) rather than* e.g. only what events surfaced. Presence cleanup of the ledger is skipped for the wholediff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.javaindex b5256fce42..6977849d8b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/S3InputSource.java@@ -19,6 +19,7 @@ import stirling.software.proprietary.policy.s3.S3Config;import stirling.software.proprietary.policy.s3.S3ConnectionPool;import stirling.software.proprietary.policy.s3.S3ConnectionResolver;import stirling.software.proprietary.policy.s3.S3Identities;+import stirling.software.proprietary.policy.source.Source;import software.amazon.awssdk.core.exception.SdkException;import software.amazon.awssdk.services.s3.S3Client;@@ -86,6 +87,13 @@ public class S3InputSource implements InputSource {}}+ /** Remote object access uses the source's configured S3 connection, shared by its policies. */+ @Override+ public List<ResolvedInput> resolve(Source source, ResolveContext ctx, String policyOwner)+ throws IOException {+ return resolve(source.toInputSpec(), ctx);+ }+@Overridepublic List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {S3Config config = connectionResolver.resolve(spec.options());diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.javaindex 53bf031b9a..86918aa5b6 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/StorageFolderInputSource.java@@ -16,6 +16,9 @@ import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.policy.ledger.StorageFileIdentities;import stirling.software.proprietary.policy.model.InputSpec;import stirling.software.proprietary.policy.model.PolicyInputs;+import stirling.software.proprietary.policy.source.Source;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.UserService;import stirling.software.proprietary.storage.model.FilePurpose;import stirling.software.proprietary.storage.model.StoredFile;import stirling.software.proprietary.storage.provider.StorageProvider;@@ -42,6 +45,7 @@ public class StorageFolderInputSource implements InputSource {private final FolderRepository folderRepository;private final StorageProvider storageProvider;private final ApplicationProperties applicationProperties;+ private final UserService userService;@Overridepublic String type() {@@ -53,24 +57,42 @@ public class StorageFolderInputSource implements InputSource {return spec != null && TYPE.equals(spec.type());}- /** Fails fast at save time: storage must be on and the folder must exist. */+ /** Private folders must belong to the authenticated caller configuring the source. */@Overridepublic void validate(InputSpec spec) {+ requireStorageEnabled();+ requireOwnedFolder(folderId(spec), requireOwner(userService.getCurrentUsername()));+ }++ private void requireStorageEnabled() {if (!applicationProperties.getSecurity().isEnableLogin()|| !applicationProperties.getStorage().isEnabled()) {throw new IllegalArgumentException("file storage is not enabled on this server");}- if (!folderRepository.existsById(folderId(spec))) {- throw new IllegalArgumentException(- "unknown storage folder: " + spec.options().get("folderId"));- }}@Overridepublic List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {+ return resolveForOwner(spec, ctx, userService.getCurrentUsername());+ }++ @Override+ public List<ResolvedInput> resolve(Source source, ResolveContext ctx, String policyOwner)+ throws IOException {+ if (policyOwner == null || !policyOwner.equals(source.owner())) {+ throw new IllegalArgumentException("Storage folder sources are private to their owner");+ }+ return resolveForOwner(source.toInputSpec(), ctx, policyOwner);+ }++ private List<ResolvedInput> resolveForOwner(InputSpec spec, ResolveContext ctx, String username)+ throws IOException {+ requireStorageEnabled();+ User owner = requireOwner(username);UUID folderId = folderId(spec);+ requireOwnedFolder(folderId, owner);List<StoredFile> files =- storedFileRepository.findAllByFolderId(folderId).stream()+ storedFileRepository.findAllByFolderIdAndOwner(folderId, owner).stream().filter(StorageFolderInputSource::ingestible).toList();@@ -82,19 +104,18 @@ public class StorageFolderInputSource implements InputSource {String gate = gate(file);// The hash tier turns metadata-only gate bumps (a folder move, a rename) into a gate// refresh instead of a reprocess; only genuinely new content runs again.- if (!ctx.claim(- identity,- gate,- () -> StorageFileIdentities.contentHash(storageProvider, file))) {+ if (!ctx.claim(identity, gate, () -> ownedContentHash(file, folderId, owner))) {continue;}Long fileId = file.getId();work.add(new ResolvedInput(- PolicyInputs.of(List.of(new StoredFileResource(storageProvider, file))),+ PolicyInputs.of(List.of(new StoredFileResource(file, folderId, owner))),identity,success ->- settleAtCurrentVersion(ctx, fileId, identity, gate, success)));+ settleAtCurrentVersion(+ ctx, fileId, identity, gate, success, folderId,+ owner)));}return work;}@@ -105,8 +126,18 @@ public class StorageFolderInputSource implements InputSource {* the claimed gate; presence cleanup prunes its row.*/private void settleAtCurrentVersion(- ResolveContext ctx, Long fileId, String identity, String claimedGate, boolean success) {- StoredFile current = storedFileRepository.findById(fileId).orElse(null);+ ResolveContext ctx,+ Long fileId,+ String identity,+ String claimedGate,+ boolean success,+ UUID folderId,+ User owner) {+ StoredFile current =+ storedFileRepository+ .findByIdAndOwner(fileId, owner)+ .filter(StorageFolderInputSource::ingestible)+ .orElse(null);if (current == null) {ctx.settle(identity, claimedGate, null, success);return;@@ -115,13 +146,48 @@ public class StorageFolderInputSource implements InputSource {// gate instead of reprocessing. Hash failures fall back to gate-only semantics.String finalContentHash = null;try {- finalContentHash = StorageFileIdentities.contentHash(storageProvider, current);+ finalContentHash = ownedContentHash(current, folderId, owner);} catch (RuntimeException e) {log.debug("Could not hash {} at settle: {}", identity, e.getMessage());}ctx.settle(identity, gate(current), finalContentHash, success);}+ private User requireOwner(String username) {+ if (username == null || username.isBlank()) {+ throw new IllegalArgumentException(+ "Storage folder input requires an authenticated owner");+ }+ return userService+ .findByUsername(username)+ .filter(user -> user.getId() != null)+ .orElseThrow(+ () -> new IllegalArgumentException("Storage folder owner is unavailable"));+ }++ private void requireOwnedFolder(UUID folderId, User owner) {+ if (folderRepository.findByIdAndOwner(folderId, owner).isEmpty()) {+ throw new IllegalArgumentException("Unknown or inaccessible storage folder");+ }+ }++ private void requireOwnedFile(Long fileId, UUID folderId, User owner) {+ // Reads and completion hashing can outlive discovery. These queries deliberately recheck+ // both owners each time so a cached permission cannot survive an ownership change.+ requireOwnedFolder(folderId, owner);+ if (storedFileRepository+ .findByIdAndOwner(fileId, owner)+ .filter(StorageFolderInputSource::ingestible)+ .isEmpty()) {+ throw new IllegalArgumentException("Unknown or inaccessible stored file");+ }+ }++ private String ownedContentHash(StoredFile file, UUID folderId, User owner) {+ requireOwnedFile(file.getId(), folderId, owner);+ return StorageFileIdentities.contentHash(storageProvider, file);+ }+/** Only generic user files are processed — purpose-bound artifacts belong to their feature. */private static boolean ingestible(StoredFile file) {return file.getPurpose() == null || file.getPurpose() == FilePurpose.GENERIC;@@ -148,17 +214,18 @@ public class StorageFolderInputSource implements InputSource {* Streams the stored blob on demand, presenting the user-visible filename. Content is not* version-pinned: a concurrent replace is reconciled by the gate on the next sweep.*/- private static final class StoredFileResource extends AbstractResource- implements StoredFileBacked {+ private final class StoredFileResource extends AbstractResource implements StoredFileBacked {- private final StorageProvider storageProvider;+ private final UUID folderId;+ private final User owner;private final Long fileId;private final String storageKey;private final String filename;private final long sizeBytes;- private StoredFileResource(StorageProvider storageProvider, StoredFile file) {- this.storageProvider = storageProvider;+ private StoredFileResource(StoredFile file, UUID folderId, User owner) {+ this.folderId = folderId;+ this.owner = owner;this.fileId = file.getId();this.storageKey = file.getStorageKey();this.filename = file.getOriginalFilename();@@ -172,6 +239,7 @@ public class StorageFolderInputSource implements InputSource {@Overridepublic InputStream getInputStream() throws IOException {+ requireOwnedFile(fileId, folderId, owner);return storageProvider.load(storageKey).getInputStream();}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/WebhookInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/WebhookInputSource.javaindex ff79b5be20..a4c241e58f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/WebhookInputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/input/WebhookInputSource.java@@ -21,6 +21,7 @@ import stirling.software.common.util.FileReadinessChecker;import stirling.software.proprietary.policy.ledger.FolderIdentities;import stirling.software.proprietary.policy.model.InputSpec;import stirling.software.proprietary.policy.model.PolicyInputs;+import stirling.software.proprietary.policy.source.Source;import stirling.software.proprietary.policy.webhook.WebhookConfig;import stirling.software.proprietary.policy.webhook.WebhookIds;import stirling.software.proprietary.policy.webhook.WebhookSpool;@@ -65,6 +66,13 @@ public class WebhookInputSource implements InputSource {return prepared;}+ /** A webhook's ingress spool is shared by every policy bound to that source. */+ @Override+ public List<ResolvedInput> resolve(Source source, ResolveContext ctx, String policyOwner)+ throws IOException {+ return resolve(source.toInputSpec(), ctx);+ }+@Overridepublic List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {WebhookConfig config = WebhookConfig.from(spec.options());diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.javaindex 6d29790e42..5cc83dcbf9 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/network/NetworkInputSource.java@@ -15,6 +15,7 @@ import stirling.software.proprietary.policy.input.ResolveContext;import stirling.software.proprietary.policy.input.ResolvedInput;import stirling.software.proprietary.policy.model.InputSpec;import stirling.software.proprietary.policy.model.PolicyInputs;+import stirling.software.proprietary.policy.source.Source;/*** Reads input files from a network file server (SFTP, FTP/FTPS, or SMB), one bean serving all three@@ -68,6 +69,13 @@ public class NetworkInputSource implements InputSource {}}+ /** Remote file access uses the source's configured network account, shared by its policies. */+ @Override+ public List<ResolvedInput> resolve(Source source, ResolveContext ctx, String policyOwner)+ throws IOException {+ return resolve(source.toInputSpec(), ctx);+ }+@Overridepublic List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {NetworkConfig config = connectionResolver.resolve(spec.options());diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/storage/repository/StoredFileRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/storage/repository/StoredFileRepository.javaindex 4b52c56e42..496bc06522 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/storage/repository/StoredFileRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/storage/repository/StoredFileRepository.java@@ -61,7 +61,7 @@ public interface StoredFileRepository extends JpaRepository<StoredFile, Long> {List<StoredFile> findAllByOwner(User owner);- List<StoredFile> findAllByFolderId(UUID folderId);+ List<StoredFile> findAllByFolderIdAndOwner(UUID folderId, User owner);/*** A file's folder placement as a plain id. Reads the FK directly so callers outside adiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.javaindex dfb54d277a..0c38e4fa23 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/ProcessingFolderControllerTest.java@@ -9,6 +9,7 @@ import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.timeout;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;import java.nio.file.Files;@@ -25,12 +26,14 @@ 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.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.http.HttpStatus;import org.springframework.web.server.ResponseStatusException;import stirling.software.common.model.ApplicationProperties;-import stirling.software.common.service.UserServiceInterface;import stirling.software.proprietary.document.conditions.Condition;import stirling.software.proprietary.document.conditions.ConditionInput;import stirling.software.proprietary.policy.config.FolderAccessGuard;@@ -84,7 +87,7 @@ class ProcessingFolderControllerTest {@Mock private FileStorageService fileStorageService;@Mock private StoredFileRepository storedFileRepository;@Mock private StorageProvider storageProvider;- @Mock private UserServiceInterface userService;+ @Mock private UserService userService;@Mock private PolicyManagementAuthority policyManagementAuthority;@Mock private FolderAccessGuard folderAccessGuard;@Mock private PolicyTrigger folderWatchTrigger;@@ -136,6 +139,13 @@ class ProcessingFolderControllerTest {.when(folderRepository.existsById(any(UUID.class))).thenAnswer(invocation -> folders.containsKey(invocation.getArgument(0)));lenient().when(userService.getCurrentUsername()).thenReturn("reece");+ lenient().when(userService.findByUsername("reece")).thenReturn(Optional.of(user));+ lenient()+ .when(folderRepository.findByIdAndOwner(any(UUID.class), eq(user)))+ .thenAnswer(+ invocation ->+ Optional.ofNullable(folders.get(invocation.getArgument(0)))+ .filter(candidate -> candidate.getOwner() == user));lenient().when(policyManagementAuthority.currentUserTeamId()).thenReturn(3L);lenient().when(policyRunner.run(any(), any()))@@ -160,7 +170,8 @@ class ProcessingFolderControllerTest {storedFileRepository,folderRepository,storageProvider,- properties),+ properties,+ userService),diskFolderSource),List.of(new StorageOutputSink(@@ -525,12 +536,60 @@ class ProcessingFolderControllerTest {assertThat(controller.list()).hasSize(1);}+ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void rejectsForeignFolderReferencesFromPersistedSources(boolean retry) {+ var view = controller.save(request(null, "new_version")).getBody();+ User other = new User();+ other.setId(99L);+ Folder foreign = new Folder();+ foreign.setId(UUID.randomUUID());+ foreign.setOwner(other);+ when(folderRepository.findById(foreign.getId())).thenReturn(Optional.of(foreign));+ Source source =+ sourceStore+ .get(+ policyStore+ .get(view.id())+ .orElseThrow()+ .inputs()+ .getFirst()+ .sourceId())+ .orElseThrow();+ sourceStore.save(+ new Source(+ source.id(),+ source.name(),+ source.type(),+ Map.of("folderId", foreign.getId().toString()),+ source.enabled(),+ source.owner(),+ source.teamId()));++ assertThatThrownBy(+ () -> {+ if (retry) {+ controller.retryFile(+ view.id(),+ new ProcessingFolderController.RetryFileRequest(+ "private.pdf"));+ } else {+ controller.files(view.id());+ }+ })+ .isInstanceOfSatisfying(+ ResponseStatusException.class,+ error -> assertThat(error.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));+ verifyNoInteractions(storedFileRepository);+ }+@Testvoid aStorageFolderListsItsFilesWithTheirLedgerState() {var view = controller.save(request(null, "new_version")).getBody();StoredFile done = storedFile(11L, "done.pdf");StoredFile waiting = storedFile(12L, "waiting.pdf");- when(storedFileRepository.findAllByFolderId(FOLDER_ID)).thenReturn(List.of(done, waiting));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER_ID, user))+ .thenReturn(List.of(done, waiting));when(processedLedger.statesFor(eq(view.id()), any())).thenReturn(Map.of("storage:11", new ClaimState(ProcessedFileStatus.DONE, "g", null)));@@ -547,7 +606,8 @@ class ProcessingFolderControllerTest {void retryRunsOnlyTheNamedFile() {var view = controller.save(request(null, "new_version")).getBody();StoredFile doc = storedFile(11L, "doc.pdf");- when(storedFileRepository.findAllByFolderId(FOLDER_ID)).thenReturn(List.of(doc));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER_ID, user))+ .thenReturn(List.of(doc));when(processedLedger.forgetFailure(view.id(), "storage:11")).thenReturn(true);controller.retryFile(view.id(), new ProcessingFolderController.RetryFileRequest("doc.pdf"));@@ -562,7 +622,8 @@ class ProcessingFolderControllerTest {void retryRefusesAFileWithNoParkedFailure() {var view = controller.save(request(null, "new_version")).getBody();StoredFile doc = storedFile(11L, "doc.pdf");- when(storedFileRepository.findAllByFolderId(FOLDER_ID)).thenReturn(List.of(doc));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER_ID, user))+ .thenReturn(List.of(doc));when(processedLedger.forgetFailure(view.id(), "storage:11")).thenReturn(false);assertThatThrownBy(diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.javaindex c46fdc2b2e..18d2d1857c 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunnerTest.java@@ -34,7 +34,7 @@ import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.UserServiceInterface;import stirling.software.proprietary.policy.config.PolicyAccessGuard;import stirling.software.proprietary.policy.config.PolicyManagementAuthority;-import stirling.software.proprietary.policy.input.InputSource;+import stirling.software.proprietary.policy.input.FolderInputSource;import stirling.software.proprietary.policy.input.ResolveContext;import stirling.software.proprietary.policy.input.ResolvedInput;import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;@@ -62,7 +62,7 @@ import stirling.software.proprietary.policy.source.SourceStore;class PolicyRunnerTest {@Mock private PolicyEngine policyEngine;- @Mock private InputSource folderSource;+ @Mock private FolderInputSource folderSource;@Mock private ProcessedLedger processedLedger;private final SourceStore sourceStore = new InProcessSourceStore();@@ -70,7 +70,8 @@ class PolicyRunnerTest {private PolicyRunner runner;@BeforeEach- void setUp() {+ void setUp() throws IOException {+ lenient().when(folderSource.resolve(any(Source.class), any(), any())).thenCallRealMethod();runner =new PolicyRunner(policyEngine,diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.javanew file mode 100644index 0000000000..4cace860e5--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderAuthorizationTest.java@@ -0,0 +1,384 @@+package stirling.software.proprietary.policy.input;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.time.LocalDateTime;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.UUID;+import java.util.concurrent.CompletableFuture;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.core.io.ByteArrayResource;+import org.springframework.http.HttpStatus;+import org.springframework.web.server.ResponseStatusException;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.policy.config.PolicyAccessGuard;+import stirling.software.proprietary.policy.config.PolicyManagementAuthority;+import stirling.software.proprietary.policy.engine.PolicyEngine;+import stirling.software.proprietary.policy.engine.PolicyRunHandle;+import stirling.software.proprietary.policy.engine.PolicyRunner;+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.PipelineInput;+import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.model.PolicyInputs;+import stirling.software.proprietary.policy.source.InProcessSourceDocCounter;+import stirling.software.proprietary.policy.source.InProcessSourceStore;+import stirling.software.proprietary.policy.source.Source;+import stirling.software.proprietary.policy.source.SourceAccessGuard;+import stirling.software.proprietary.policy.source.SourceController;+import stirling.software.proprietary.policy.source.SourceOverviewService;+import stirling.software.proprietary.policy.store.InProcessPolicyStore;+import stirling.software.proprietary.policy.trigger.PolicyTriggerManager;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.UserService;+import stirling.software.proprietary.storage.model.FilePurpose;+import stirling.software.proprietary.storage.model.Folder;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.provider.StorageProvider;+import stirling.software.proprietary.storage.repository.FolderRepository;+import stirling.software.proprietary.storage.repository.StoredFileRepository;++@ExtendWith(MockitoExtension.class)+class StorageFolderAuthorizationTest {++ @Mock private FolderRepository folderRepository;+ @Mock private StoredFileRepository fileRepository;+ @Mock private StorageProvider blobs;+ @Mock private UserService users;+ @Mock private PolicyManagementAuthority authority;+ @Mock private PolicyEngine engine;++ private final ApplicationProperties properties = new ApplicationProperties();+ private final InProcessSourceStore sources = new InProcessSourceStore();+ private final Map<UUID, Folder> folders = new HashMap<>();+ private final Map<Long, StoredFile> files = new HashMap<>();+ private User alice;+ private User bob;+ private Folder aliceFolder;+ private Folder bobFolder;+ private StorageFolderInputSource input;+ private SourceController controller;+ private PolicyRunner runner;++ @BeforeEach+ void setUp() throws IOException {+ properties.getSecurity().setEnableLogin(true);+ properties.getStorage().setEnabled(true);+ alice = user(1L, "alice");+ bob = user(2L, "bob");+ aliceFolder = folder(alice);+ bobFolder = folder(bob);+ file(1L, aliceFolder);+ file(2L, bobFolder);+ lenient().when(users.getCurrentUsername()).thenReturn("alice");+ lenient().when(users.findByUsername("alice")).thenReturn(Optional.of(alice));+ lenient().when(users.findByUsername("bob")).thenReturn(Optional.of(bob));+ lenient().when(users.usernameExists(anyString())).thenReturn(true);+ lenient().when(authority.canEditPolicies()).thenReturn(true);+ lenient().when(authority.currentUserTeamId()).thenReturn(1L);+ lenient()+ .when(folderRepository.findByIdAndOwner(any(), any()))+ .thenAnswer(+ call ->+ Optional.ofNullable(folders.get(call.getArgument(0)))+ .filter(+ folder ->+ folder.getOwner() == call.getArgument(1)));+ lenient()+ .when(fileRepository.findAllByFolderIdAndOwner(any(), any()))+ .thenAnswer(+ call ->+ files.values().stream()+ .filter(+ file ->+ file.getFolder()+ .getId()+ .equals(call.getArgument(0)))+ .filter(file -> file.getOwner() == call.getArgument(1))+ .toList());+ lenient()+ .when(fileRepository.findByIdAndOwner(any(), any()))+ .thenAnswer(+ call ->+ Optional.ofNullable(files.get(call.getArgument(0)))+ .filter(file -> file.getOwner() == call.getArgument(1)));+ lenient()+ .when(blobs.load(anyString()))+ .thenAnswer(+ call ->+ new ByteArrayResource(+ ((String) call.getArgument(0))+ .getBytes(StandardCharsets.UTF_8)));+ input =+ new StorageFolderInputSource(+ fileRepository, folderRepository, blobs, properties, users);+ PolicyAccessGuard policies = new PolicyAccessGuard(users, properties, authority);+ controller =+ new SourceController(+ sources,+ new SourceAccessGuard(users, properties, authority),+ mock(SourceOverviewService.class),+ new InProcessPolicyStore(),+ policies,+ authority,+ mock(PolicyTriggerManager.class),+ properties,+ List.of(input));+ runner =+ new PolicyRunner(+ engine,+ List.of(input),+ sources,+ new InProcessSourceDocCounter(),+ new InProcessProcessedLedger(),+ properties,+ policies);+ }++ @Test+ void sourceCreationRejectsAnotherCustomersFolderEvenWithForgedOwnership() {+ Source request =+ new Source(+ null,+ "Input",+ "storage-folder",+ Map.of("folderId", bobFolder.getId().toString(), "owner", "bob"),+ true,+ "bob",+ 2L);++ ResponseStatusException error =+ assertThrows(ResponseStatusException.class, () -> controller.save(request));++ assertThat(error.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);+ assertThat(sources.all()).isEmpty();+ verifyNoInteractions(fileRepository, blobs, engine);+ }++ @Test+ void aRejectedEditPreservesTheOriginalFolderBinding() {+ Source saved = controller.save(source(null, aliceFolder, null)).getBody();++ assertThrows(+ ResponseStatusException.class,+ () -> controller.save(source(saved.id(), bobFolder, null)));++ assertThat(sources.get(saved.id())).contains(saved);+ verifyNoInteractions(fileRepository, blobs, engine);+ }++ @Test+ void foreignAndMissingFoldersHaveTheSamePublicError() {+ ResponseStatusException foreign =+ assertThrows(+ ResponseStatusException.class,+ () -> controller.save(source(null, bobFolder, null)));+ folders.remove(bobFolder.getId());+ ResponseStatusException missing =+ assertThrows(+ ResponseStatusException.class,+ () -> controller.save(source(null, bobFolder, null)));++ assertThat(foreign.getStatusCode()).isEqualTo(missing.getStatusCode());+ assertThat(foreign.getReason()).isEqualTo(missing.getReason());+ }++ @Test+ void directResolutionWithoutAnAuthenticatedOwnerFailsClosed() {+ when(users.getCurrentUsername()).thenReturn(null);++ assertThatThrownBy(+ () ->+ input.resolve(+ source(null, aliceFolder, "alice").toInputSpec(),+ mock(ResolveContext.class)))+ .isInstanceOf(IllegalArgumentException.class);++ verifyNoInteractions(fileRepository, blobs);+ }++ @Test+ void backgroundSweepRejectsAnAlreadyStoredForeignFolderBeforeProcessing() {+ Source stored = sources.save(source(null, bobFolder, "alice"));+ lenient().when(users.getCurrentUsername()).thenReturn(null);++ assertThat(runner.run(policy(stored, "alice")).runIds()).isEmpty();++ verifyNoInteractions(fileRepository, blobs, engine);+ verify(users, never()).getCurrentUsername();+ }++ @Test+ void aPolicyCannotBorrowAnotherOwnersPrivateSourceEvenInTheSameTeam() {+ Source stored = sources.save(source(null, bobFolder, "bob"));++ assertThat(runner.run(policy(stored, "alice")).runIds()).isEmpty();++ verifyNoInteractions(fileRepository, blobs, engine);+ }++ @Test+ void backgroundProcessingUsesStoredAuthorityInsteadOfTheRequestUser() throws IOException {+ Source stored = controller.save(source(null, aliceFolder, null)).getBody();+ lenient().when(users.getCurrentUsername()).thenReturn("bob");+ clearInvocations(users);+ when(engine.runPolicy(any(), any(), any(), any(), any(), any()))+ .thenReturn(new PolicyRunHandle("run", new CompletableFuture<>()));++ assertThat(runner.run(policy(stored, "alice")).runIds()).containsExactly("run");+ verify(users, never()).getCurrentUsername();++ ArgumentCaptor<PolicyInputs> captured = ArgumentCaptor.forClass(PolicyInputs.class);+ verify(engine).runPolicy(any(), captured.capture(), any(), any(), any(), any());+ assertThat(captured.getValue().primary()).hasSize(1);+ try (var stream = captured.getValue().primary().getFirst().getInputStream()) {+ assertThat(new String(stream.readAllBytes(), StandardCharsets.UTF_8))+ .isEqualTo("alice/1");+ }+ }++ @Test+ void filesOwnedBySomeoneElseAreExcludedEvenInsideAnOwnedFolder() throws IOException {+ files.get(2L).setFolder(aliceFolder);++ List<ResolvedInput> work = resolveOwned();++ assertThat(work).extracting(ResolvedInput::fileIdentity).containsExactly("storage:1");+ }++ @Test+ void changingFileOwnershipAfterDiscoveryPreventsOpeningItsContents() throws IOException {+ List<ResolvedInput> work = resolveOwned();+ files.get(1L).setOwner(bob);+ clearInvocations(blobs);++ assertThatThrownBy(() -> work.getFirst().inputs().primary().getFirst().getInputStream())+ .isInstanceOf(IllegalArgumentException.class);++ verifyNoInteractions(blobs);+ }++ @Test+ void changingFolderOwnershipAfterDiscoveryPreventsOpeningItsContents() throws IOException {+ List<ResolvedInput> work = resolveOwned();+ aliceFolder.setOwner(bob);+ clearInvocations(blobs);++ assertThatThrownBy(() -> work.getFirst().inputs().primary().getFirst().getInputStream())+ .isInstanceOf(IllegalArgumentException.class);++ verifyNoInteractions(blobs);+ }++ @Test+ void aFileReclassifiedAsAPrivateArtifactCannotBeOpened() throws IOException {+ List<ResolvedInput> work = resolveOwned();+ files.get(1L).setPurpose(FilePurpose.SIGNING_ORIGINAL);+ clearInvocations(blobs);++ assertThatThrownBy(() -> work.getFirst().inputs().primary().getFirst().getInputStream())+ .isInstanceOf(IllegalArgumentException.class);++ verifyNoInteractions(blobs);+ }++ @Test+ void completionDoesNotHashAFileThatNowBelongsToSomeoneElse() throws IOException {+ List<ResolvedInput> work = resolveOwned();+ files.get(1L).setOwner(bob);+ clearInvocations(blobs);++ work.getFirst().onComplete().accept(true);++ verifyNoInteractions(blobs);+ }++ @Test+ void disabledStorageAlsoRejectsExistingSourcesAtExecution() {+ Source stored = sources.save(source(null, aliceFolder, "alice"));+ properties.getStorage().setEnabled(false);++ assertThat(runner.run(policy(stored, "alice")).runIds()).isEmpty();++ verifyNoInteractions(fileRepository, blobs, engine);+ }++ private List<ResolvedInput> resolveOwned() throws IOException {+ ResolveContext context = mock(ResolveContext.class);+ when(context.claim(any(), any(), any())).thenReturn(true);+ return input.resolve(source(null, aliceFolder, "alice"), context, "alice");+ }++ private static Source source(String id, Folder folder, String owner) {+ return new Source(+ id,+ "Input",+ "storage-folder",+ Map.of("folderId", folder.getId().toString()),+ true,+ owner,+ 1L);+ }++ private static Policy policy(Source source, String owner) {+ return new Policy(+ "policy",+ "Process",+ owner,+ true,+ List.of(new PipelineInput(source.id(), null)),+ List.of(),+ OutputSpec.inline(),+ 1L);+ }++ private static User user(Long id, String name) {+ User user = new User();+ user.setId(id);+ user.setUsername(name);+ return user;+ }++ private Folder folder(User owner) {+ Folder folder = new Folder();+ folder.setId(UUID.randomUUID());+ folder.setOwner(owner);+ folders.put(folder.getId(), folder);+ return folder;+ }++ private void file(Long id, Folder folder) {+ StoredFile file = new StoredFile();+ file.setId(id);+ file.setFolder(folder);+ file.setOwner(folder.getOwner());+ file.setOriginalFilename("document.pdf");+ file.setStorageKey(folder.getOwner().getUsername() + "/" + id);+ file.setSizeBytes(7L);+ file.setUpdatedAt(LocalDateTime.of(2026, 9, 15, 12, 0));+ files.put(id, file);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderInputSourceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderInputSourceTest.javaindex 0bad1d732e..96767d0e0b 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderInputSourceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/input/StorageFolderInputSourceTest.java@@ -27,7 +27,10 @@ import org.springframework.core.io.ByteArrayResource;import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;import stirling.software.proprietary.policy.model.InputSpec;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.UserService;import stirling.software.proprietary.storage.model.FilePurpose;+import stirling.software.proprietary.storage.model.Folder;import stirling.software.proprietary.storage.model.StoredFile;import stirling.software.proprietary.storage.provider.StorageProvider;import stirling.software.proprietary.storage.repository.FolderRepository;@@ -49,6 +52,9 @@ class StorageFolderInputSourceTest {@Mock private StoredFileRepository storedFileRepository;@Mock private FolderRepository folderRepository;@Mock private StorageProvider storageProvider;+ @Mock private UserService userService;++ private User owner;private StorageFolderInputSource source;private InProcessProcessedLedger ledger;@@ -58,6 +64,17 @@ class StorageFolderInputSourceTest {@BeforeEachvoid setUp() throws IOException {+ owner = new User();+ owner.setId(7L);+ owner.setUsername("alice");+ Folder folder = new Folder();+ folder.setId(FOLDER);+ folder.setOwner(owner);+ lenient().when(userService.getCurrentUsername()).thenReturn("alice");+ lenient().when(userService.findByUsername("alice")).thenReturn(Optional.of(owner));+ lenient()+ .when(folderRepository.findByIdAndOwner(FOLDER, owner))+ .thenReturn(Optional.of(folder));lenient().when(storageProvider.load(anyString())).thenAnswer(invocation -> new ByteArrayResource(blobContent));@@ -66,7 +83,8 @@ class StorageFolderInputSourceTest {storedFileRepository,folderRepository,storageProvider,- storageEnabledProperties());+ storageEnabledProperties(),+ userService);ledger = new InProcessProcessedLedger();ctx = new RecordingContext();}@@ -74,8 +92,9 @@ class StorageFolderInputSourceTest {@Testvoid claimsEachFileOncePerContentVersion() throws IOException {StoredFile file = storedFile(1L, "doc.pdf", T1);- when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));- when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER, owner))+ .thenReturn(List.of(file));+ when(storedFileRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(file));List<ResolvedInput> work = source.resolve(spec(), ctx);@@ -92,13 +111,14 @@ class StorageFolderInputSourceTest {@Testvoid anInPlaceOutputDoesNotRetriggerTheFolder() throws IOException {StoredFile file = storedFile(1L, "doc.pdf", T1);- when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER, owner))+ .thenReturn(List.of(file));List<ResolvedInput> work = source.resolve(spec(), ctx);// The run replaces the file's content in place before completion fires.file.setUpdatedAt(T2);- when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));+ when(storedFileRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(file));work.get(0).onComplete().accept(true);// The next sweep sees the bumped version already settled — no self-feeding loop.@@ -108,8 +128,9 @@ class StorageFolderInputSourceTest {@Testvoid aGenuineEditIsPickedUpAgain() throws IOException {StoredFile file = storedFile(1L, "doc.pdf", T1);- when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));- when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER, owner))+ .thenReturn(List.of(file));+ when(storedFileRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(file));source.resolve(spec(), ctx).get(0).onComplete().accept(true);@@ -122,8 +143,9 @@ class StorageFolderInputSourceTest {@Testvoid aMetadataOnlyBumpDoesNotReprocess() throws IOException {StoredFile file = storedFile(1L, "doc.pdf", T1);- when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));- when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER, owner))+ .thenReturn(List.of(file));+ when(storedFileRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(file));source.resolve(spec(), ctx).get(0).onComplete().accept(true);@@ -137,7 +159,8 @@ class StorageFolderInputSourceTest {void purposeBoundFilesAreNeverIngested() throws IOException {StoredFile signing = storedFile(2L, "contract.pdf", T1);signing.setPurpose(FilePurpose.SIGNING_ORIGINAL);- when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(signing));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER, owner))+ .thenReturn(List.of(signing));assertTrue(source.resolve(spec(), ctx).isEmpty());assertTrue(ctx.present.isEmpty());@@ -146,8 +169,9 @@ class StorageFolderInputSourceTest {@Testvoid aFailedRunLeavesTheFileForItsNextVersion() throws IOException {StoredFile file = storedFile(1L, "doc.pdf", T1);- when(storedFileRepository.findAllByFolderId(FOLDER)).thenReturn(List.of(file));- when(storedFileRepository.findById(1L)).thenReturn(Optional.of(file));+ when(storedFileRepository.findAllByFolderIdAndOwner(FOLDER, owner))+ .thenReturn(List.of(file));+ when(storedFileRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(file));source.resolve(spec(), ctx).get(0).onComplete().accept(false);@@ -160,7 +184,7 @@ class StorageFolderInputSourceTest {@Testvoid validateRejectsAnUnknownFolder() {- when(folderRepository.existsById(FOLDER)).thenReturn(false);+ when(folderRepository.findByIdAndOwner(FOLDER, owner)).thenReturn(Optional.empty());assertThrows(IllegalArgumentException.class, () -> source.validate(spec()));}@@ -179,7 +203,8 @@ class StorageFolderInputSourceTest {storedFileRepository,folderRepository,storageProvider,- new ApplicationProperties());+ new ApplicationProperties(),+ userService);assertThrows(IllegalArgumentException.class, () -> disabled.validate(spec()));}@@ -188,13 +213,17 @@ class StorageFolderInputSourceTest {return new InputSpec("storage-folder", Map.of("folderId", FOLDER.toString()));}- private static StoredFile storedFile(Long id, String name, LocalDateTime updatedAt) {+ private StoredFile storedFile(Long id, String name, LocalDateTime updatedAt) {StoredFile file = new StoredFile();file.setId(id);file.setOriginalFilename(name);file.setStorageKey("key-" + id);file.setSizeBytes(100);file.setUpdatedAt(updatedAt);+ file.setOwner(owner);+ lenient()+ .when(storedFileRepository.findByIdAndOwner(id, owner))+ .thenReturn(Optional.of(file));return file;}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/storage/repository/StorageFolderOwnershipDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/storage/repository/StorageFolderOwnershipDbTest.javanew file mode 100644index 0000000000..63197dfa56--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/storage/repository/StorageFolderOwnershipDbTest.java@@ -0,0 +1,85 @@+package stirling.software.proprietary.storage.repository;++import static org.assertj.core.api.Assertions.assertThat;++import java.util.UUID;++import org.junit.jupiter.api.Test;+import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.boot.SpringBootConfiguration;+import org.springframework.boot.autoconfigure.AutoConfigurationPackage;+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;+import org.springframework.test.annotation.DirtiesContext;++import jakarta.persistence.EntityManager;++import stirling.software.proprietary.model.Team;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.model.Folder;+import stirling.software.proprietary.storage.model.StoredFile;++@DataJpaTest+@DirtiesContext+class StorageFolderOwnershipDbTest {++ @Autowired private FolderRepository folders;+ @Autowired private StoredFileRepository files;+ @Autowired private EntityManager entityManager;++ @Test+ void folderAndFileQueriesEnforceOwnershipIndependently() {+ User alice = user("alice");+ User bob = user("bob");+ Folder aliceFolder = folder(alice);+ Folder bobFolder = folder(bob);+ StoredFile own = file(alice, aliceFolder);+ StoredFile foreign = file(bob, aliceFolder);+ file(alice, bobFolder);+ entityManager.flush();+ entityManager.clear();++ assertThat(folders.findByIdAndOwner(aliceFolder.getId(), alice)).isPresent();+ assertThat(folders.findByIdAndOwner(bobFolder.getId(), alice)).isEmpty();+ assertThat(files.findAllByFolderIdAndOwner(aliceFolder.getId(), alice))+ .extracting(StoredFile::getId)+ .containsExactly(own.getId());+ assertThat(files.findByIdAndOwner(foreign.getId(), alice)).isEmpty();+ }++ private User user(String name) {+ Team team = new Team();+ team.setName(name);+ entityManager.persist(team);+ User user = new User();+ user.setUsername(name);+ user.setPassword("test-password");+ user.setTeam(team);+ entityManager.persist(user);+ return user;+ }++ private Folder folder(User owner) {+ Folder folder = new Folder();+ folder.setId(UUID.randomUUID());+ folder.setOwner(owner);+ folder.setName("Documents");+ entityManager.persist(folder);+ return folder;+ }++ private StoredFile file(User owner, Folder folder) {+ StoredFile file = new StoredFile();+ file.setOwner(owner);+ file.setFolder(folder);+ file.setOriginalFilename("document.pdf");+ file.setContentType("application/pdf");+ file.setStorageKey(UUID.randomUUID().toString());+ file.setSizeBytes(10L);+ entityManager.persist(file);+ return file;+ }++ @SpringBootConfiguration+ @AutoConfigurationPackage(basePackages = "stirling.software.proprietary")+ static class TestApp {}+}