#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
Resolve issues with file ownership in pipelines (#8021)
James Brunton274c857c5d6c
diff --git a/app/common/src/main/java/stirling/software/common/service/JobOwnershipService.java b/app/common/src/main/java/stirling/software/common/service/JobOwnershipService.javaindex 7f08dfded3..98057ab9b1 100644--- a/app/common/src/main/java/stirling/software/common/service/JobOwnershipService.java+++ b/app/common/src/main/java/stirling/software/common/service/JobOwnershipService.java@@ -23,6 +23,11 @@ public interface JobOwnershipService {*/String createScopedJobKey(String jobId);+ /**+ * Scope a job to an owner resolved by trusted server code, independently of the current caller.+ */+ String createScopedJobKey(String jobId, String owner);+/*** Validate that the current user has access to the given job.*diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.javaindex 8fb6814f38..e47c18ff48 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImpl.java@@ -64,6 +64,14 @@ public class JobOwnershipServiceImplreturn jobId;}+ @Override+ public String createScopedJobKey(String jobId, String owner) {+ if (owner == null || owner.isBlank() || "anonymousUser".equals(owner)) {+ throw new IllegalArgumentException("An authenticated job must have an owner");+ }+ return owner + ":" + jobId;+ }+/*** Validate that the current user has access to the given job.*diff --git a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipService.java b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipService.javaindex d6a7d52b77..24eb149e16 100644--- a/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipService.java+++ b/app/core/src/main/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipService.java@@ -29,6 +29,11 @@ public class NoOpJobOwnershipServicereturn jobId;}+ @Override+ public String createScopedJobKey(String jobId, String owner) {+ return jobId;+ }+@Overridepublic boolean validateJobAccess(String scopedJobKey) {// All jobs are accessible when security is disableddiff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.javaindex c2b1191473..9db6412cdc 100644--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/JobOwnershipServiceImplTest.java@@ -25,6 +25,29 @@ class JobOwnershipServiceImplTest {field.set(service, userService);}+ @Test+ void explicitOwnerScopesABackgroundJobWithoutAnAuthenticatedCaller() {+ assertEquals("alice:job", service.createScopedJobKey("job", "alice"));+ verifyNoInteractions(userService);+ }++ @Test+ void explicitOwnerDoesNotUseTheTriggeringUser() {+ when(userService.getCurrentUsername()).thenReturn("bob");+ String key = service.createScopedJobKey("job", "alice");+ assertThrows(SecurityException.class, () -> service.validateJobAccess(key));+ when(userService.getCurrentUsername()).thenReturn("alice");+ assertTrue(service.validateJobAccess(key));+ }++ @Test+ void explicitOwnershipRejectsMissingAndAnonymousOwners() {+ for (String owner : new String[] {null, "", " ", "anonymousUser"}) {+ assertThrows(+ IllegalArgumentException.class, () -> service.createScopedJobKey("job", owner));+ }+ }+// --- getCurrentUserId tests ---@Testdiff --git a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipServiceTest.javaindex c5a5a2d36d..8d17b8665c 100644--- a/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipServiceTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/service/pdfjson/NoOpJobOwnershipServiceTest.java@@ -16,6 +16,13 @@ class NoOpJobOwnershipServiceTest {service = new NoOpJobOwnershipService();}+ @Test+ void explicitOwnersDoNotScopeJobsWhenLoginIsDisabled() {+ NoOpJobOwnershipService ownership = new NoOpJobOwnershipService();+ assertEquals("job", ownership.createScopedJobKey("job", "alice"));+ assertEquals("job", ownership.createScopedJobKey("job", null));+ }+@Testvoid getCurrentUserId_alwaysReturnsEmpty() {assertEquals(Optional.empty(), service.getCurrentUserId());diff --git a/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.java b/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.javanew file mode 100644index 0000000000..ecdaa01a16--- /dev/null+++ b/app/core/src/test/java/stirling/software/common/controller/JobControllerUserAccessTest.java@@ -0,0 +1,128 @@+package stirling.software.common.controller;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.io.ByteArrayInputStream;+import java.nio.file.Path;+import java.util.List;+import java.util.Optional;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.http.HttpStatus;+import org.springframework.test.util.ReflectionTestUtils;++import jakarta.servlet.http.HttpServletRequest;++import stirling.software.SPDF.service.pdfjson.JobOwnershipServiceImpl;+import stirling.software.SPDF.service.pdfjson.NoOpJobOwnershipService;+import stirling.software.common.cluster.inprocess.InProcessClusterBackplane;+import stirling.software.common.cluster.inprocess.InProcessJobStore;+import stirling.software.common.cluster.inprocess.LocalDiskFileStore;+import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.model.job.ResultFile;+import stirling.software.common.service.FileOrUploadService;+import stirling.software.common.service.FileStorage;+import stirling.software.common.service.JobOwnershipService;+import stirling.software.common.service.JobQueue;+import stirling.software.common.service.TaskManager;+import stirling.software.common.service.UserServiceInterface;+import stirling.software.common.util.JobContext;++class JobControllerUserAccessTest {+ private static final byte[] OUTPUT =+ "%PDF-processed-document".getBytes(java.nio.charset.StandardCharsets.UTF_8);+ @TempDir Path directory;+ private final UserServiceInterface users = mock(UserServiceInterface.class);+ private TaskManager tasks;+ private JobController controller;+ private String fileId;+ private String runId;++ private void storeOutput(boolean loginEnabled) throws Exception {+ JobOwnershipService ownership;+ if (loginEnabled) {+ ownership = new JobOwnershipServiceImpl();+ ReflectionTestUtils.setField(ownership, "userService", users);+ } else {+ ownership = new NoOpJobOwnershipService();+ }+ LocalDiskFileStore disk = new LocalDiskFileStore(directory.toString());+ FileStorage storage =+ new FileStorage(mock(FileOrUploadService.class), disk, Optional.of(ownership));+ tasks =+ new TaskManager(+ storage,+ new InProcessJobStore(),+ new InProcessClusterBackplane(new ApplicationProperties()));+ controller =+ new JobController(+ tasks,+ storage,+ mock(JobQueue.class),+ mock(HttpServletRequest.class),+ null,+ null);+ ReflectionTestUtils.setField(controller, "jobOwnershipService", ownership);+ runId = ownership.createScopedJobKey("run", "source-owner");+ tasks.createTask(runId);+ JobContext.setOwner("source-owner");+ try {+ fileId =+ storage.storeInputStream(new ByteArrayInputStream(OUTPUT), "result.pdf")+ .fileId();+ } finally {+ JobContext.setOwner(null);+ }+ tasks.setMultipleFileResults(+ runId,+ List.of(+ ResultFile.builder()+ .fileId(fileId)+ .fileName("result.pdf")+ .contentType("application/pdf")+ .fileSize((long) OUTPUT.length)+ .build()));+ tasks.setComplete(runId);+ assertEquals("source-owner", disk.getOwner(fileId));+ }++ @AfterEach+ void tearDown() {+ if (tasks != null) {+ tasks.shutdown();+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"pipeline-creator", "trigger-user", "teammate"})+ void onlyTheDocumentOwnerCanReadResults(String otherUser) throws Exception {+ storeOutput(true);+ when(users.getCurrentUsername()).thenReturn(otherUser);+ assertEquals(HttpStatus.FORBIDDEN, controller.downloadFile(fileId).getStatusCode());+ assertEquals(HttpStatus.FORBIDDEN, controller.getFileMetadata(fileId).getStatusCode());+ assertEquals(HttpStatus.FORBIDDEN, controller.getJobStatus(runId).getStatusCode());++ when(users.getCurrentUsername()).thenReturn("source-owner");+ var response = controller.downloadFile(fileId);+ assertEquals(HttpStatus.OK, response.getStatusCode());+ assertArrayEquals(OUTPUT, (byte[]) response.getBody());+ assertEquals(HttpStatus.OK, controller.getFileMetadata(fileId).getStatusCode());+ assertEquals(HttpStatus.OK, controller.getJobStatus(runId).getStatusCode());+ }++ @Test+ void loginDisabledKeepsOutputsAccessible() throws Exception {+ storeOutput(false);+ assertEquals("run", runId);+ var response = controller.downloadFile(fileId);+ assertEquals(HttpStatus.OK, response.getStatusCode());+ assertArrayEquals(OUTPUT, (byte[]) response.getBody());+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/PolicyAccessGuard.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/PolicyAccessGuard.javaindex 067dc4f0b7..ea855d939e 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/PolicyAccessGuard.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/config/PolicyAccessGuard.java@@ -12,6 +12,7 @@ import stirling.software.common.service.UserServiceInterface;import stirling.software.proprietary.policy.asset.PolicyAsset;import stirling.software.proprietary.policy.asset.PolicyAssetStore;import stirling.software.proprietary.policy.model.Policy;+import stirling.software.proprietary.policy.source.Source;import stirling.software.proprietary.policy.store.PolicyStore;/**@@ -83,6 +84,14 @@ public class PolicyAccessGuard {return policy.owner() == null || !userService.usernameExists(policy.owner());}+ /** A source without a reachable owner must not produce inaccessible documents under login. */+ public boolean isOrphaned(Source source) {+ return enforced()+ && (source.owner() == null+ || source.owner().isBlank()+ || !userService.usernameExists(source.owner()));+ }+/*** The policies visible to the caller: their whole team's, loaded scoped rather than fetched* globally and filtered, so on SaaS it never pulls another team's policies into memory. Logindiff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.javaindex 083327af4a..a5dd6e8e08 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java@@ -192,18 +192,19 @@ public class PolicyController {summary = "Get pipeline run status",description = "Returns the current status, step cursor, and output files of a run.")public ResponseEntity<PolicyRunView> status(@PathVariable String runId) {+ if (!ownedByCurrentUser(runId)) {+ return ResponseEntity.notFound().build();+ }PolicyRun run = runRegistry.get(runId);if (run != null) {return ResponseEntity.ok(PolicyRunView.of(run));}// Not local: read the run's shared projection so any node can serve its status.- if (ownedByCurrentUser(runId)) {- Optional<JobStoreEntry> entry = jobStore.get(runId);- if (entry.isPresent()- && entry.get().resultMeta() != null- && entry.get().resultMeta().containsKey("policyId")) {- return ResponseEntity.ok(PolicyRunView.ofEntry(entry.get()));- }+ Optional<JobStoreEntry> entry = jobStore.get(runId);+ if (entry.isPresent()+ && entry.get().resultMeta() != null+ && entry.get().resultMeta().containsKey("policyId")) {+ return ResponseEntity.ok(PolicyRunView.ofEntry(entry.get()));}return ResponseEntity.notFound().build();}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.javaindex bb5a2646fd..ce42dd6cf3 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java@@ -52,6 +52,7 @@ import stirling.software.proprietary.policy.output.OutputDelivery;import stirling.software.proprietary.policy.output.PolicyOutputResolver;import stirling.software.proprietary.policy.output.PolicyOutputSink;import stirling.software.proprietary.policy.progress.PolicyProgressListener;+import stirling.software.proprietary.policy.source.Source;import stirling.software.proprietary.service.DownstreamEntitlementError;import tools.jackson.databind.JsonNode;@@ -162,17 +163,17 @@ public class PolicyEngine {/*** As {@link #runPolicy(Policy, PolicyInputs, PolicyProgressListener)}, recording which source* fed the run and its opaque reference to the document. The first says where an unattended- * failure came from; the second says which document, and is what lets the same document failing- * again fold into one incident. With no source {@code fileIdentity} is the client's own- * reference, with one it is that source's hash; this engine only carries it either way.+ * failure came from; the second identifies repeat failures of the same document. Source-fed+ * outputs belong to the source owner even when a different user triggers the run. Uploaded+ * documents belong to the caller; a generator with no input belongs to the pipeline creator.*/public PolicyRunHandle runPolicy(Policy policy,PolicyInputs inputs,PolicyProgressListener listener,- String sourceId,+ Source source,String fileIdentity) {- return runPolicy(policy, inputs, listener, sourceId, fileIdentity, null);+ return runPolicy(policy, inputs, listener, source, fileIdentity, null);}/**@@ -183,25 +184,16 @@ public class PolicyEngine {Policy policy,PolicyInputs inputs,PolicyProgressListener listener,- String sourceId,+ Source source,String fileIdentity,Semaphore admission) {- // Bill the policy owner: trigger-fired runs have no security context, and the async worker- // doesn't inherit the caller's, so the owner (stamped at policy creation) is the reliable- // billing identity — and for org-wide policies the org/owner is meant to pay. But own the- // OUTPUT files as the user who triggered the run (captured here on the request thread) so- // they can download their enforced file; otherwise an org-wide policy's output is owned by- // the admin and the triggering user is denied it. Trigger-fired runs have no such user, so- // the owner owns those outputs.- //- // The triggering user is also carried on the run, as the actor of any failure it records:- // null for a trigger-fired run, which is what makes an unattended incident ownerless rather- // than the owner's problem. Three identities, deliberately not interchangeable.String triggeringUser = currentActingPrincipal();- String fileOwner = triggeringUser != null ? triggeringUser : policy.owner();- // Unowned policies (the seeded Classification policy) have no owner to bill; fall back to- // the triggering user, or the run goes out principal-less and its tool sub-steps bill the- // team-less INTERNAL_API_USER, which PAYG refuses with a usage-limit 402.+ String sourceId = source == null ? null : source.id();+ String fileOwner = source == null ? triggeringUser : source.owner();+ if (source == null && inputs.primary().isEmpty()) {+ fileOwner = policy.owner() != null ? policy.owner() : triggeringUser;+ }+ // The pipeline's payer is independent of the document owner and the incident's actor.String billingPrincipal = policy.owner() != null ? policy.owner() : triggeringUser;PolicyInputs resolved;PipelineDefinition definition;@@ -226,7 +218,8 @@ public class PolicyEngine {new PipelineDefinition(policy.name(), policy.steps(), List.of()),sourceId,fileIdentity,- triggeringUser);+ triggeringUser,+ fileOwner);String message = "Policy run could not start: " + e.getMessage();run.fail(message);taskManager.setError(run.getRunId(), message);@@ -239,8 +232,6 @@ public class PolicyEngine {triggeringUser,policy.id(),definition,- // main's asset-resolved inputs, not the raw ones: stored certificates and watermark- // images bind here, before the async hop, because worker threads have no principal.resolved,listener,sourceId,@@ -259,7 +250,9 @@ public class PolicyEngine {String sourceId,String fileIdentity,Semaphore admission) {- PolicyRun run = registerRun(policyId, definition, sourceId, fileIdentity, triggeringUser);+ PolicyRun run =+ registerRun(+ policyId, definition, sourceId, fileIdentity, triggeringUser, fileOwner);String runId = run.getRunId();CompletableFuture<PolicyRun> completion = new CompletableFuture<>();PolicyProgressListener tracking = trackingListener(runId, run, listener);@@ -320,10 +313,10 @@ public class PolicyEngine {PipelineDefinition definition,String sourceId,String fileIdentity,- String triggeringUser) {- // Scope the run id to the current user (this request thread) so the file-download- // ownership check passes. No-op when security is off.- String runId = jobOwnershipService.createScopedJobKey(UUID.randomUUID().toString());+ String triggeringUser,+ String fileOwner) {+ String runId =+ jobOwnershipService.createScopedJobKey(UUID.randomUUID().toString(), fileOwner);taskManager.createTask(runId);// Tag the shared job entry with the policy id so peers can list it as a policy run.if (policyId != null) {@@ -575,7 +568,8 @@ public class PolicyEngine {private List<ResultFile> deliver(PolicyRun run, String runId, PolicyInputs inputs, List<Resource> files)throws IOException {- OutputDelivery delivery = new OutputDelivery(runId, run.getPolicyId(), inputs);+ OutputDelivery delivery =+ new OutputDelivery(runId, run.getPolicyId(), inputs, JobContext.getOwner());List<OutputSpec> fallback = run.getDefinition().outputs();if (fallback.isEmpty()) {// No destinations means inline delivery (results returned to the caller), preserving@@ -675,15 +669,7 @@ public class PolicyEngine {*/private static void runAsPrincipal(String billingPrincipal, String fileOwner, String policyName, Runnable body) {- // Billing identity (MDC auditPrincipal) and output-file ownership (JobContext owner) are- // set- // independently: usage is charged to billingPrincipal, but stored output files are owned by- // fileOwner — the user who triggered an org-wide policy — so they can fetch their results.- // Either may be null (e.g. login disabled, or a trigger-fired run); each is applied only- // when present and restored afterward (defensive — worker threads aren't pooled). The- // policy- // name rides MDC too so each tool step's loopback dispatch (InternalApiClient) can forward- // it as a header, letting the audit tie the step back to its policy.+ // Tool dispatch reads the billing principal; output storage reads the document owner.String previousPrincipal = MDC.get(AUDIT_PRINCIPAL_MDC_KEY);String previousPolicyName = MDC.get(InternalApiClient.POLICY_NAME_MDC_KEY);String previousOwner = JobContext.getOwner();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 5a3d05a199..c7cbbd7d5c 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@@ -144,7 +144,12 @@ public class PolicyRunner {context.vetoCleanup();continue;}- runIds.addAll(pullAndRun(policy, sourceId, source.toInputSpec(), context, admission));+ if (policyAccessGuard.isOrphaned(source)) {+ log.warn("Source {} has no reachable owner; not sweeping it", sourceId);+ context.vetoCleanup();+ continue;+ }+ runIds.addAll(pullAndRun(policy, source, context, admission));}boolean fullPolicy = inputs.size() == policy.inputs().size();if (fullPolicy && context.cleanupAllowed()) {@@ -222,11 +227,8 @@ public class PolicyRunner {* this sweep's ledger cleanup.*/private List<String> pullAndRun(- Policy policy,- String sourceId,- InputSpec spec,- PolicySweep context,- Semaphore admission) {+ Policy policy, Source storedSource, PolicySweep context, Semaphore admission) {+ InputSpec spec = storedSource.toInputSpec();InputSource source = sourceFor(spec);if (source == null) {log.warn(@@ -257,20 +259,20 @@ public class PolicyRunner {runIds.add(startRun(policy,- sourceId,+ storedSource,unit.fileIdentity(),unit.inputs(),unit.onComplete(),admission));docsFed += unit.inputs().primary().size();}- docCounter.record(sourceId, docsFed);+ docCounter.record(storedSource.id(), docsFed);return runIds;}private String startRun(Policy policy,- String sourceId,+ Source source,String fileIdentity,PolicyInputs inputs,Consumer<Boolean> onComplete,@@ -281,7 +283,7 @@ public class PolicyRunner {policy,inputs,PolicyProgressListener.NOOP,- sourceId,+ source,fileIdentity,admission);handle.completion()diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.javaindex fcce40648b..8e745e0b57 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java@@ -8,15 +8,21 @@ import stirling.software.proprietary.policy.model.PolicyInputs;* Context for one run's output delivery. {@code policyId} is null for ad-hoc pipelines; when* present, sinks record outputs in the processed-file ledger so the producing policy does not* re-ingest them. {@code inputs} carries the run's inputs so a sink that writes back to where the- * input lives (e.g. a new version of a stored file) can correlate output to origin.+ * input lives (e.g. a new version of a stored file) can correlate output to origin. {@code+ * fileOwner} is resolved from the input source or uploader by the engine; storage outputs require+ * it and must not substitute the destination's owner.*/-public record OutputDelivery(String runId, String policyId, PolicyInputs inputs) {+public record OutputDelivery(String runId, String policyId, PolicyInputs inputs, String fileOwner) {public OutputDelivery {inputs = inputs == null ? PolicyInputs.of(List.of()) : inputs;}+ public OutputDelivery(String runId, String policyId, PolicyInputs inputs) {+ this(runId, policyId, inputs, null);+ }+public OutputDelivery(String runId, String policyId) {- this(runId, policyId, null);+ this(runId, policyId, null, null);}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/StorageOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/StorageOutputSink.javaindex 9c1a3b935d..97f57c15f0 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/StorageOutputSink.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/StorageOutputSink.java@@ -22,6 +22,7 @@ import stirling.software.proprietary.policy.ledger.ProcessedLedger;import stirling.software.proprietary.policy.ledger.StorageFileIdentities;import stirling.software.proprietary.policy.model.OutputSpec;import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.UserService;import stirling.software.proprietary.storage.model.Folder;import stirling.software.proprietary.storage.model.StoredFile;import stirling.software.proprietary.storage.provider.StorageProvider;@@ -34,9 +35,8 @@ import stirling.software.proprietary.storage.service.FileStorageService;* mode} picks: {@code new_version} (default) replaces the input file's content in place under its* own name, settling the ledger at the bumped version; {@code new_file} stores each output as a new* file in {@code folderId} (default: the input's folder), recorded in the ledger before it becomes- * visible so a sweep never claims the policy's own output. Ownership follows the input; a run fed- * from disk has no anchor, so it is stored as the owner of the {@code folderId} it writes into, and- * must name one.+ * visible so a sweep never claims the policy's own output. The engine supplies the document owner;+ * existing files and destination folders must belong to that user before anything is written.*/@Slf4j@Service@@ -55,6 +55,7 @@ public class StorageOutputSink implements PolicyOutputSink {private final ProcessedLedger processedLedger;private final StorageProvider storageProvider;private final ApplicationProperties applicationProperties;+ private final UserService userService;@Overridepublic String type() {@@ -87,7 +88,7 @@ public class StorageOutputSink implements PolicyOutputSink {OutputDelivery delivery, List<Resource> outputs, OutputSpec spec) throws IOException {StoredFile origin = originOf(delivery);UUID folderId = folderIdOf(spec);- User owner = ownerFor(origin, folderId);+ User owner = ownerFor(delivery, origin, folderId);List<ResultFile> results = new ArrayList<>();// Replacing in place needs a stored row to replace, which a run fed from disk has not got.@@ -169,23 +170,44 @@ public class StorageOutputSink implements PolicyOutputSink {.orElse(null);}- /**- * Who the outputs are stored as, and whose quota they count against: the input's owner, or for- * a disk-fed run the owner of the folder being written into.- */- private User ownerFor(StoredFile origin, UUID folderId) {- if (origin != null) {- return origin.getOwner();+ private User ownerFor(OutputDelivery delivery, StoredFile origin, UUID folderId) {+ String username = delivery.fileOwner();+ if (username == null || username.isBlank()) {+ throw new IllegalStateException("Storage output requires a document owner");+ }+ User owner =+ userService+ .findByUsername(username)+ .orElseThrow(+ () ->+ new IllegalStateException(+ "The document owner is unavailable"));+ if (origin != null && !ownedBy(origin.getOwner(), owner)) {+ throw new IllegalStateException("The input file does not belong to the document owner");}- if (folderId == null) {+ if (folderId != null) {+ Folder folder =+ folderRepository+ .findById(folderId)+ .orElseThrow(+ () ->+ new IllegalStateException(+ "Unknown storage folder: " + folderId));+ if (!ownedBy(folder.getOwner(), owner)) {+ throw new IllegalStateException(+ "The output folder does not belong to the document owner");+ }+ } else if (origin == null) {throw new IllegalStateException(- "storage output from a non-storage input needs a folderId to anchor ownership");+ "Storage output without a stored input requires a folder");}- return folderRepository- .findById(folderId)- .map(Folder::getOwner)- .orElseThrow(- () -> new IllegalStateException("unknown storage folder: " + folderId));+ return owner;+ }++ private static boolean ownedBy(User actual, User expected) {+ return actual != null+ && expected.getId() != null+ && expected.getId().equals(actual.getId());}private static String modeOf(OutputSpec spec) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/FolderWatchTrigger.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/FolderWatchTrigger.javaindex dc5a194cc0..5b859a4786 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/FolderWatchTrigger.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/trigger/FolderWatchTrigger.java@@ -20,7 +20,6 @@ import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;-import org.slf4j.MDC;import org.springframework.stereotype.Service;import lombok.RequiredArgsConstructor;@@ -28,7 +27,6 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.policy.config.FolderAccessGuard;-import stirling.software.proprietary.policy.engine.PolicyEngine;import stirling.software.proprietary.policy.engine.PolicyRunner;import stirling.software.proprietary.policy.engine.SweepKind;import stirling.software.proprietary.policy.input.InputSource;@@ -212,28 +210,7 @@ public class FolderWatchTrigger implements PolicyTrigger {binding.policy().id(),binding.input().sourceId());// Light: the periodic reconcile does the full sweep.- runAsOwner(binding, SweepKind.LIGHT);- }- }- }-- /**- * Run one binding as its policy's owner: watch threads have no security context, so run ids- * would mint unscoped and stay invisible to the owner's runs feed on a login install.- */- private void runAsOwner(PolicyBinding binding, SweepKind sweep) {- String owner = binding.policy().owner();- String previous = MDC.get(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY);- if (owner != null) {- MDC.put(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY, owner);- }- try {- policyRunner.runInput(binding.policy(), binding.input(), sweep);- } finally {- if (previous != null) {- MDC.put(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY, previous);- } else if (owner != null) {- MDC.remove(PolicyEngine.AUDIT_PRINCIPAL_MDC_KEY);+ policyRunner.runInput(binding.policy(), binding.input(), SweepKind.LIGHT);}}}@@ -251,7 +228,7 @@ public class FolderWatchTrigger implements PolicyTrigger {void runAll() {for (PolicyBinding binding : policyStore.findBindingsByTriggerType(TYPE)) {try {- runAsOwner(binding, SweepKind.FULL);+ policyRunner.runInput(binding.policy(), binding.input(), SweepKind.FULL);} catch (RuntimeException e) {log.warn("Folder-watch reconcile run failed for input {}/{}: {}",diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.javaindex 17e9d310a8..4825fb96ee 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java@@ -153,8 +153,39 @@ class PolicyAutomationBillingDbTest {assertThat(stepCount("run:0")).isEqualTo(2);}+ @Test+ void sharedSupportingFileKeepsDocumentsSeparateAndContributesUnits() throws IOException {+ execute(+ 2,+ 20,+ List.of(+ new PipelineStep(ROTATE, Map.of(), Map.of("stampImage", "logo")),+ new PipelineStep(ROTATE, Map.of())),+ Map.of("logo", List.of(file("logo.bin", new byte[2050]))));++ assertThat(totalUnits()).isEqualTo(8);+ assertThat(signatures.count()).isEqualTo(2);+ assertThat(stepCount("run:0")).isEqualTo(2);+ assertThat(stepCount("run:1")).isEqualTo(2);+ }+private PolicyExecutionResult execute(int inputCount, int stepLimit, String... operations)throws IOException {+ return execute(+ inputCount,+ stepLimit,+ Arrays.stream(operations)+ .map(operation -> new PipelineStep(operation, Map.of()))+ .toList(),+ Map.of());+ }++ private PolicyExecutionResult execute(+ int inputCount,+ int stepLimit,+ List<PipelineStep> steps,+ Map<String, List<Resource>> supportingFiles)+ throws IOException {when(entitlementCache.current()).thenReturn(Optional.of(@@ -174,18 +205,14 @@ class PolicyAutomationBillingDbTest {.mapToObj(index -> file("input-" + index + ".bin", new byte[] {(byte) index})).toList();- PipelineDefinition definition =- new PipelineDefinition(- "test",- Arrays.stream(operations)- .map(operation -> new PipelineStep(operation, Map.of()))- .toList(),- OutputSpec.inline());+ PipelineDefinition definition = new PipelineDefinition("test", steps, OutputSpec.inline());PolicyExecutionResult result;try (AutomationRunContext.Scope run = AutomationRunContext.open("run")) {result =executor.execute(- definition, PolicyInputs.of(inputs), PolicyProgressListener.NOOP);+ definition,+ new PolicyInputs(inputs, supportingFiles),+ PolicyProgressListener.NOOP);assertThat(AutomationRunContext.currentDocument()).isNull();}return result;@@ -201,15 +228,18 @@ class PolicyAutomationBillingDbTest {if (documentId != null) {request.addHeader(AutomationRunContext.DOCUMENT_ID_HEADER, documentId);}- for (Object input : body.get("fileInput")) {- Resource resource = (Resource) input;- try (var stream = resource.getInputStream()) {- request.addFile(- new MockMultipartFile(- "fileInput",- resource.getFilename(),- "application/octet-stream",- stream));+ for (var field : body.entrySet()) {+ for (Object input : field.getValue()) {+ if (input instanceof Resource resource) {+ try (var stream = resource.getInputStream()) {+ request.addFile(+ new MockMultipartFile(+ field.getKey(),+ resource.getFilename(),+ "application/octet-stream",+ stream));+ }+ }}}MockHttpServletResponse response = new MockHttpServletResponse();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.javaindex 3d1026524f..3519344fd0 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureAttributionTest.java@@ -50,6 +50,7 @@ import stirling.software.proprietary.policy.output.InlineOutputSink;import stirling.software.proprietary.policy.output.PolicyOutputResolver;import stirling.software.proprietary.policy.progress.PolicyProgressListener;import stirling.software.proprietary.policy.source.InProcessSourceStore;+import stirling.software.proprietary.policy.source.Source;import stirling.software.proprietary.policy.store.PolicyStore;import tools.jackson.databind.json.JsonMapper;@@ -130,7 +131,7 @@ class PolicyFailureAttributionTest {new PolicyAssetResolver(new InProcessPolicyAssetStore()));lenient()- .when(jobOwnershipService.createScopedJobKey(anyString()))+ .when(jobOwnershipService.createScopedJobKey(anyString(), any())).thenAnswer(invocation -> invocation.getArgument(0));lenient().when(resourceMonitor.shouldQueueJob(anyInt())).thenReturn(false);lenient().when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);@@ -166,7 +167,11 @@ class PolicyFailureAttributionTest {sharedPolicy(),PolicyInputs.of(List.of(pdf())),PolicyProgressListener.NOOP,- sourceId,+ sourceId == null+ ? null+ : new Source(+ sourceId, "Input", "folder", Map.of(), true, "carol",+ TEAM),fileIdentity).completion().get(10, TimeUnit.SECONDS);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.javaindex 0932b65a32..2f17a04b84 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/failure/PolicyFailureOwnershipTest.java@@ -50,6 +50,7 @@ import stirling.software.proprietary.policy.output.InlineOutputSink;import stirling.software.proprietary.policy.output.PolicyOutputResolver;import stirling.software.proprietary.policy.progress.PolicyProgressListener;import stirling.software.proprietary.policy.source.InProcessSourceStore;+import stirling.software.proprietary.policy.source.Source;import stirling.software.proprietary.policy.store.PolicyStore;import tools.jackson.databind.json.JsonMapper;@@ -122,7 +123,7 @@ class PolicyFailureOwnershipTest {new PolicyAssetResolver(new InProcessPolicyAssetStore()));lenient()- .when(jobOwnershipService.createScopedJobKey(anyString()))+ .when(jobOwnershipService.createScopedJobKey(anyString(), any())).thenAnswer(invocation -> invocation.getArgument(0));lenient().when(resourceMonitor.shouldQueueJob(anyInt())).thenReturn(false);lenient().when(toolMetadataService.isMultiInput(anyString())).thenReturn(false);@@ -156,7 +157,11 @@ class PolicyFailureOwnershipTest {sharedPolicy(),PolicyInputs.of(List.of(pdf())),PolicyProgressListener.NOOP,- sourceId,+ sourceId == null+ ? null+ : new Source(+ sourceId, "Input", "folder", Map.of(), true, "carol",+ TEAM),fileIdentity).completion().get(10, TimeUnit.SECONDS);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.javaindex e4b52e5a6c..872839c640 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java@@ -12,8 +12,11 @@ import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.doThrow;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.time.Duration;+import java.time.Instant;import java.util.List;import java.util.Map;import java.util.Optional;@@ -34,6 +37,7 @@ import org.springframework.web.server.ResponseStatusException;import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;import stirling.software.common.cluster.JobStore;+import stirling.software.common.cluster.JobStoreEntry;import stirling.software.common.cluster.inprocess.InProcessJobStore;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.model.job.JobResponse;@@ -381,6 +385,8 @@ class PolicyControllerTest {void found() {PolicyRun run = new PolicyRun("run-3", null, definitionWithStep(), null, null, null);when(runRegistry.get("run-3")).thenReturn(run);+ when(jobOwnershipService.extractJobId("run-3")).thenReturn("run-3");+ when(jobOwnershipService.createScopedJobKey("run-3")).thenReturn("run-3");ResponseEntity<PolicyRunView> response = controller.status("run-3");@@ -388,6 +394,36 @@ class PolicyControllerTest {assertThat(response.getBody().runId()).isEqualTo("run-3");}+ @Test+ void rejectsAnotherUsersRunBeforeReadingLocalOrSharedState() {+ when(jobOwnershipService.extractJobId("alice:run")).thenReturn("run");+ when(jobOwnershipService.createScopedJobKey("run")).thenReturn("bob:run");++ assertThat(controller.status("alice:run").getStatusCode())+ .isEqualTo(HttpStatus.NOT_FOUND);+ verifyNoInteractions(runRegistry);+ }++ @Test+ void returnsTheOwnersSharedRunWhenItIsNotLocal() {+ when(jobOwnershipService.extractJobId("alice:run")).thenReturn("run");+ when(jobOwnershipService.createScopedJobKey("run")).thenReturn("alice:run");+ jobStore.put(+ new JobStoreEntry(+ "alice:run",+ JobStoreEntry.JobState.COMPLETE,+ "peer",+ Instant.now(),+ Instant.now(),+ null,+ List.of("output"),+ Map.of("policyId", "pipeline")),+ Duration.ofMinutes(5));++ assertThat(controller.status("alice:run").getStatusCode()).isEqualTo(HttpStatus.OK);+ assertThat(controller.status("alice:run").getBody().outputs()).hasSize(1);+ }+@Test@DisplayName("returns 404 when run is unknown")void notFound() {diff --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 31958469e1..fcfb925062 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@@ -52,6 +52,7 @@ import stirling.software.proprietary.policy.store.InProcessPolicyStore;import stirling.software.proprietary.policy.trigger.PolicyTrigger;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.Folder;import stirling.software.proprietary.storage.model.StoredFile;import stirling.software.proprietary.storage.provider.StorageProvider;@@ -163,7 +164,8 @@ class ProcessingFolderControllerTest {fileStorageService,processedLedger,storageProvider,- properties),+ properties,+ mock(UserService.class)),diskFolderSink),List.of(),sourceStore,diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.javaindex 6a89e37c01..5e60383914 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineRoutingTest.java@@ -1,6 +1,7 @@package stirling.software.proprietary.policy.engine;import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.Mockito.when;@@ -100,7 +101,7 @@ class PolicyEngineRoutingTest {resourceMonitor,jobQueue,new PolicyAssetResolver(new InProcessPolicyAssetStore()));- when(jobOwnershipService.createScopedJobKey(anyString()))+ when(jobOwnershipService.createScopedJobKey(anyString(), any())).thenAnswer(inv -> inv.getArgument(0));}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.javaindex 2100d4c150..7bb6f04770 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyEngineTest.java@@ -16,6 +16,7 @@ import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;@@ -60,6 +61,7 @@ import stirling.software.common.service.ResourceMonitor;import stirling.software.common.service.TaskManager;import stirling.software.common.service.ToolMetadataService;import stirling.software.common.util.FileReadinessChecker;+import stirling.software.common.util.JobContext;import stirling.software.common.util.TempFileManager;import stirling.software.common.util.TempFileRegistry;import stirling.software.proprietary.failure.PolicyFailureRecorder;@@ -148,12 +150,79 @@ class PolicyEngineTest {// Identity scoping: the run id is the generated UUID unchanged. Lenient because the// resume/cancel tests do not submit a run.lenient()- .when(jobOwnershipService.createScopedJobKey(anyString()))+ .when(jobOwnershipService.createScopedJobKey(anyString(), any())).thenAnswer(inv -> inv.getArgument(0));// Default to running immediately; the queueing test overrides this.lenient().when(resourceMonitor.shouldQueueJob(anyInt())).thenReturn(false);}+ @ParameterizedTest+ @CsvSource({+ "editor,bob,bob",+ "source,bob,carol",+ "source,,carol",+ "generator,bob,alice",+ "generator,,alice"+ })+ void separatesDocumentOwnershipFromBillingAndTheTriggeringUser(+ String inputKind, String actor, String expectedOwner) throws Exception {+ Source source =+ "source".equals(inputKind)+ ? new Source("input", "Input", "folder", Map.of(), true, "carol", null)+ : null;+ PolicyInputs inputs =+ PolicyInputs.of(+ "generator".equals(inputKind)+ ? List.of()+ : List.of(pdf("original", "input.pdf")));+ String[] storedOwner = {null};+ String[] billedUser = {null};+ when(jobOwnershipService.createScopedJobKey(anyString(), any()))+ .thenAnswer(+ invocation -> invocation.getArgument(1) + ":" + invocation.getArgument(0));+ when(internalApiClient.post(eq(ROTATE), any()))+ .thenAnswer(+ invocation -> {+ billedUser[0] = MDC.get("auditPrincipal");+ return ResponseEntity.ok(pdf("processed", "output.pdf"));+ });+ when(fileStorage.storeInputStream(any(), anyString()))+ .thenAnswer(+ invocation -> {+ storedOwner[0] = JobContext.getOwner();+ InputStream input = invocation.getArgument(0);+ assertEquals(+ "processed",+ new String(+ input.readAllBytes(),+ java.nio.charset.StandardCharsets.UTF_8));+ return new StoredFile("output", 9);+ });+ if (actor != null) {+ MDC.put("auditPrincipal", actor);+ }+ PolicyRun run;+ try {+ run =+ engine.runPolicy(+ policyOwnedBy("alice"),+ inputs,+ PolicyProgressListener.NOOP,+ source,+ "document")+ .completion()+ .get(10, TimeUnit.SECONDS);+ } finally {+ MDC.remove("auditPrincipal");+ }+ assertEquals(PolicyRunStatus.COMPLETED, run.getStatus());+ assertTrue(run.getRunId().startsWith(expectedOwner + ":"));+ assertEquals(expectedOwner, storedOwner[0]);+ assertEquals("alice", billedUser[0]);+ assertEquals(actor, run.getTriggeringUser());+ verify(taskManager).setMultipleFileResults(eq(run.getRunId()), eq(run.getOutputs()));+ }+@ParameterizedTest@CsvSource({"track,false", "track,true", "consume,false", "consume,true"})void unavailableOutputFailsEveryClaimWithoutConsumingFiles(String mode, boolean disabled)@@ -169,7 +238,7 @@ class PolicyEngineTest {"folder",Map.of("directory", input.toString(), "mode", mode),true,- "owner",+ "source-owner",null));String outputId =disabled@@ -237,6 +306,7 @@ class PolicyEngineTest {anyString(),any(Throwable.class));}+ verify(jobOwnershipService, times(2)).createScopedJobKey(anyString(), eq("source-owner"));assertFalse(ledger.anyInFlight(policy.id()));assertTrue(runner.quiesced(policy.id()));assertEquals("first original", Files.readString(input.resolve("first.pdf")));@@ -360,7 +430,14 @@ class PolicyEngineTest {policyOwnedBy("owner"),PolicyInputs.of(List.of(pdf("input", "input.pdf"))),PolicyProgressListener.NOOP,- "src-s3-invoices",+ new Source(+ "src-s3-invoices",+ "Input",+ "folder",+ Map.of(),+ true,+ "carol",+ null),"file-hash-1");handle.completion().get(10, TimeUnit.SECONDS);@@ -427,7 +504,14 @@ class PolicyEngineTest {policyOwnedBy("alice"),PolicyInputs.of(List.of(pdf("input", "input.pdf"))),PolicyProgressListener.NOOP,- "src-watched-folder",+ new Source(+ "src-watched-folder",+ "Input",+ "folder",+ Map.of(),+ true,+ "carol",+ null),"file-hash-1").completion().get(10, TimeUnit.SECONDS);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 98c3b6f73f..c46fdc2b2e 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@@ -345,7 +345,13 @@ class PolicyRunnerTest {runner.run(policy);verify(policyEngine)- .runPolicy(eq(policy), any(), any(), eq(sourceId), eq("/in/doc.pdf"), any());+ .runPolicy(+ eq(policy),+ any(),+ any(),+ eq(sourceStore.get(sourceId).orElseThrow()),+ eq("/in/doc.pdf"),+ any());}@Test@@ -375,6 +381,36 @@ class PolicyRunnerTest {assertEquals(2, docCounter.statsFor(List.of(key)).get(key).total());}+ @Test+ void sourcesWithoutReachableOwnersAreNotClaimedOrPruned() {+ ApplicationProperties loginOn = new ApplicationProperties();+ loginOn.getSecurity().setEnableLogin(true);+ PolicyRunner enforced =+ new PolicyRunner(+ policyEngine,+ List.of(folderSource),+ sourceStore,+ docCounter,+ processedLedger,+ loginOn,+ guardOver(loginOn, noUsers()));+ for (String owner : new String[] {null, "", "deleted-user"}) {+ Source source =+ sourceStore.save(+ new Source(+ null,+ "Input",+ "folder",+ Map.of("directory", "/in"),+ true,+ owner,+ null));+ SweepOutcome outcome = enforced.run(policyReferencing(List.of(source.id())));+ assertTrue(outcome.runIds().isEmpty());+ }+ verifyNoInteractions(folderSource, policyEngine, processedLedger);+ }+@Testvoid anOwnerlessProcessingFolderIsNotSweptUnderLogin() {// Created while login was disabled, so stamped with no owner; enabling login strands itdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/StorageOutputSinkTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/StorageOutputSinkTest.javanew file mode 100644index 0000000000..ea61978231--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/StorageOutputSinkTest.java@@ -0,0 +1,188 @@+package stirling.software.proprietary.policy.output;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.UUID;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.core.io.ByteArrayResource;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.policy.input.StoredFileBacked;+import stirling.software.proprietary.policy.ledger.ProcessedLedger;+import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.PolicyInputs;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.UserService;+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;+import stirling.software.proprietary.storage.service.FileStorageService;++@ExtendWith(MockitoExtension.class)+class StorageOutputSinkTest {+ @Mock private StoredFileRepository files;+ @Mock private FolderRepository folders;+ @Mock private FileStorageService storage;+ @Mock private UserService users;+ private StorageOutputSink sink;+ private final UUID folderId = UUID.randomUUID();+ private final User owner = user(1L, "source-owner");+ private final ByteArrayResource output = new ByteArrayResource(new byte[] {1, 2, 3});++ @BeforeEach+ void setUp() {+ sink =+ new StorageOutputSink(+ files,+ folders,+ storage,+ mock(ProcessedLedger.class),+ mock(StorageProvider.class),+ new ApplicationProperties(),+ users);+ }++ @Test+ void storesDiskOutputsAsTheResolvedSourceOwner() throws Exception {+ when(users.findByUsername("source-owner")).thenReturn(Optional.of(owner));+ Folder folder = folder(owner);+ when(folders.findById(folderId)).thenReturn(Optional.of(folder));+ when(folders.getReferenceById(folderId)).thenReturn(folder);+ StoredFile stored = stored(owner);+ when(storage.storeFile(eq(owner), any())).thenReturn(stored);+ when(files.save(stored)).thenReturn(stored);++ var results = sink.deliver(delivery("source-owner", false), List.of(output), destination());++ assertThat(results).hasSize(1);+ verify(storage).storeFile(eq(owner), any());+ assertThat(stored.getFolder()).isSameAs(folder);+ }++ @Test+ void refusesToWriteIntoAnotherUsersFolder() {+ when(users.findByUsername("source-owner")).thenReturn(Optional.of(owner));+ when(folders.findById(folderId))+ .thenReturn(Optional.of(folder(user(2L, "pipeline-owner"))));++ assertThatThrownBy(+ () ->+ sink.deliver(+ delivery("source-owner", false),+ List.of(output),+ destination()))+ .isInstanceOf(IllegalStateException.class)+ .hasMessageContaining("output folder");+ verifyNoInteractions(storage);+ }++ @Test+ void refusesToReplaceAnotherUsersInput() {+ when(users.findByUsername("source-owner")).thenReturn(Optional.of(owner));+ when(files.findById(10L)).thenReturn(Optional.of(stored(user(2L, "other-user"))));++ assertThatThrownBy(+ () ->+ sink.deliver(+ delivery("source-owner", true),+ List.of(output),+ new OutputSpec("storage", Map.of())))+ .isInstanceOf(IllegalStateException.class)+ .hasMessageContaining("input file");+ verifyNoInteractions(storage);+ }++ @Test+ void versionsTheOwnersStoredInputWithoutChangingOwnership() throws Exception {+ when(users.findByUsername("source-owner")).thenReturn(Optional.of(owner));+ StoredFile origin = stored(owner);+ when(files.findById(10L)).thenReturn(Optional.of(origin));+ when(storage.replaceFile(eq(owner), eq(origin), any())).thenReturn(origin);++ sink.deliver(+ delivery("source-owner", true),+ List.of(output),+ new OutputSpec("storage", Map.of()));++ verify(storage).replaceFile(eq(owner), eq(origin), any());+ assertThat(origin.getOwner()).isSameAs(owner);+ }++ @Test+ void doesNotSubstituteTheDestinationOwnerWhenTheRunOwnerIsMissing() {+ for (String username : new String[] {null, "", "deleted-user"}) {+ assertThatThrownBy(+ () ->+ sink.deliver(+ delivery(username, false),+ List.of(output),+ destination()))+ .isInstanceOf(IllegalStateException.class);+ }+ verifyNoInteractions(storage, folders);+ }++ private OutputDelivery delivery(String username, boolean storedInput) {+ return new OutputDelivery(+ "run",+ null,+ PolicyInputs.of(storedInput ? List.of(new StoredInput()) : List.of(output)),+ username);+ }++ private OutputSpec destination() {+ return new OutputSpec(+ "storage", Map.of("folderId", folderId.toString(), "mode", "new_file"));+ }++ private Folder folder(User owner) {+ Folder folder = new Folder();+ folder.setId(folderId);+ folder.setOwner(owner);+ return folder;+ }++ private static StoredFile stored(User owner) {+ StoredFile file = new StoredFile();+ file.setId(10L);+ file.setOwner(owner);+ file.setOriginalFilename("document.pdf");+ file.setSizeBytes(3L);+ return file;+ }++ private static User user(long id, String username) {+ User user = new User();+ user.setId(id);+ user.setUsername(username);+ return user;+ }++ private static class StoredInput extends ByteArrayResource implements StoredFileBacked {+ private StoredInput() {+ super(new byte[] {1});+ }++ @Override+ public Long storedFileId() {+ return 10L;+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/FolderWatchTriggerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/FolderWatchTriggerTest.javaindex c955e9ed8d..99a0c6aca2 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/FolderWatchTriggerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/FolderWatchTriggerTest.java@@ -1,6 +1,7 @@package stirling.software.proprietary.policy.trigger;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;@@ -25,10 +26,12 @@ import org.junit.jupiter.api.extension.ExtendWith;import org.junit.jupiter.api.io.TempDir;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import org.slf4j.MDC;import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.policy.engine.PolicyRunner;import stirling.software.proprietary.policy.engine.SweepKind;+import stirling.software.proprietary.policy.engine.SweepOutcome;import stirling.software.proprietary.policy.input.InputSource;import stirling.software.proprietary.policy.model.InputSpec;import stirling.software.proprietary.policy.model.OutputSpec;@@ -144,6 +147,22 @@ class FolderWatchTriggerTest {verify(policyRunner).runInput(b, b.inputs().get(0), SweepKind.FULL);}+ @Test+ void backgroundDispatchDoesNotImpersonateThePipelineCreator() {+ Policy policy = folderWatch("pipeline", List.of(InputSpec.folder("/in")));+ when(policyStore.findBindingsByTriggerType("folder-watch")).thenReturn(bindings(policy));+ when(policyRunner.runInput(eq(policy), any(), eq(SweepKind.FULL)))+ .thenAnswer(+ invocation -> {+ assertNull(MDC.get("auditPrincipal"));+ return new SweepOutcome(List.of(), 0, 0, 0, 0, 0);+ });++ trigger.runAll();++ verify(policyRunner).runInput(eq(policy), any(), eq(SweepKind.FULL));+ }+@Testvoid syncRegistrationsWatchesExistingDirsAndCancelsRemovedOnes() throws Exception {Path dirA = Files.createDirectories(tempDir.resolve("a"));diff --git a/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java b/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.javaindex 5250847269..3438e60ca6 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java@@ -125,8 +125,7 @@ public class JobChargeService {stepLimit,ctx.runId());- List<Path> paths = inputs.stream().map(JobInput::path).toList();- JoinOrOpenResult result = jobService.joinOrOpen(jobCtx, paths);+ JoinOrOpenResult result = jobService.joinOrOpen(jobCtx, lineagePaths(ctx, inputs));if (result.disposition() == JoinOrOpenResult.Disposition.JOINED) {return new ChargeOutcome(result.job().getId(), 0, ChargeOutcome.Disposition.JOINED);@@ -340,6 +339,21 @@ public class JobChargeService {ledgerRepository.save(entry);}+ private static List<Path> lineagePaths(ChargeContext ctx, List<JobInput> inputs) {+ if (ctx.runId() != null) {+ // PolicyExecutor sends primary documents as fileInput, with assets in named fields.+ List<Path> primaryPaths =+ inputs.stream()+ .filter(input -> "fileInput".equals(input.multipart().getName()))+ .map(JobInput::path)+ .toList();+ if (!primaryPaths.isEmpty()) {+ return primaryPaths;+ }+ }+ return inputs.stream().map(JobInput::path).toList();+ }+private int computeUnits(List<JobInput> inputs, PricingPolicy policy) {List<MultipartFile> multiparts = inputs.stream().map(JobInput::multipart).toList();// Reuse the temp file the caller already wrote (in PaygChargeInterceptor.preHandle fordiff --git a/app/saas/src/test/java/stirling/software/saas/payg/charge/SupportingFileBillingTest.java b/app/saas/src/test/java/stirling/software/saas/payg/charge/SupportingFileBillingTest.javanew file mode 100644index 0000000000..dc2e0f6f2f--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/payg/charge/SupportingFileBillingTest.java@@ -0,0 +1,222 @@+package stirling.software.saas.payg.charge;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.time.Duration;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.UUID;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.springframework.mock.web.MockMultipartFile;++import stirling.software.common.util.TempFileManager;+import stirling.software.saas.payg.billing.TeamBillingService;+import stirling.software.saas.payg.bundle.PrepaidBundleService;+import stirling.software.saas.payg.docs.DefaultDocumentClassifier;+import stirling.software.saas.payg.job.JobService;+import stirling.software.saas.payg.job.ProcessingJob;+import stirling.software.saas.payg.lineage.ByteHashSignatureExtractor;+import stirling.software.saas.payg.lineage.DefaultHashLineageDetector;+import stirling.software.saas.payg.lineage.InMemoryJobLineageStore;+import stirling.software.saas.payg.meter.PaygMeterReportingService;+import stirling.software.saas.payg.model.BillingCategory;+import stirling.software.saas.payg.model.JobSource;+import stirling.software.saas.payg.model.ProcessType;+import stirling.software.saas.payg.policy.PricingPolicy;+import stirling.software.saas.payg.policy.PricingPolicyService;+import stirling.software.saas.payg.repository.PaygShadowChargeRepository;+import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;+import stirling.software.saas.payg.repository.ProcessingJobRepository;+import stirling.software.saas.payg.repository.ProcessingJobStepRepository;+import stirling.software.saas.payg.repository.WalletLedgerRepository;+import stirling.software.saas.payg.wallet.WalletLedgerEntry;++/** Uses real hashing, job grouping and unit calculation; persistence stays in memory. */+class SupportingFileBillingTest {++ private static final ChargeContext CONTEXT =+ new ChargeContext(+ 42L,+ 100L,+ JobSource.PIPELINE,+ ProcessType.SINGLE_TOOL,+ BillingCategory.AUTOMATION,+ "run");++ @TempDir Path tempDir;++ private final Map<UUID, ProcessingJob> jobs = new HashMap<>();+ private final List<WalletLedgerEntry> debits = new ArrayList<>();+ private JobService jobService;+ private JobChargeService chargeService;+ private PricingPolicy policy;++ @BeforeEach+ void setUp() {+ InMemoryJobLineageStore store = new InMemoryJobLineageStore();+ ProcessingJobRepository jobRepository = mock(ProcessingJobRepository.class);+ when(jobRepository.save(any()))+ .thenAnswer(+ invocation -> {+ ProcessingJob job = invocation.getArgument(0);+ jobs.put(job.getId(), job);+ store.registerJob(+ job.getId(),+ job.getOwnerUserId(),+ job.getStatus(),+ job.getLastStepAt());+ return job;+ });+ when(jobRepository.findById(any()))+ .thenAnswer(invocation -> Optional.ofNullable(jobs.get(invocation.getArgument(0))));+ Duration window = Duration.ofMinutes(5);+ jobService =+ new JobService(+ new DefaultHashLineageDetector(+ List.of(new ByteHashSignatureExtractor()), store, window),+ jobRepository,+ mock(ProcessingJobStepRepository.class),+ window);+ policy = new PricingPolicy();+ policy.setId(7L);+ policy.setDocPagesPerUnit(25);+ policy.setDocBytesPerUnit(1024L);+ policy.setFileUnitCap(1000);+ policy.setMinChargeUnits(1);+ policy.setStepLimits(Map.of(JobSource.PIPELINE, 10));+ PricingPolicyService policies = mock(PricingPolicyService.class);+ when(policies.getEffectivePolicy(100L)).thenReturn(policy);+ WalletLedgerRepository ledger = mock(WalletLedgerRepository.class);+ when(ledger.save(any()))+ .thenAnswer(+ invocation -> {+ WalletLedgerEntry debit = invocation.getArgument(0);+ debits.add(debit);+ return debit;+ });+ chargeService =+ new JobChargeService(+ jobService,+ policies,+ new DefaultDocumentClassifier(mock(TempFileManager.class)),+ mock(PaygShadowChargeRepository.class),+ jobRepository,+ mock(PaygTeamExtensionsRepository.class),+ mock(PaygMeterReportingService.class),+ ledger,+ mock(PrepaidBundleService.class),+ mock(TeamBillingService.class));+ }++ @Test+ void sharedAssetKeepsDocumentsSeparateAndStillContributesUnits() throws IOException {+ JobInput asset = input("stampImage", "logo", new byte[2050]);+ JobInput first = input("fileInput", "first", new byte[] {1});+ JobInput second = input("fileInput", "second", new byte[] {2});++ ChargeOutcome firstCharge = charge(first, asset);+ ChargeOutcome secondCharge = charge(second, asset);++ assertThat(firstCharge.units()).isEqualTo(4);+ assertThat(secondCharge.units()).isEqualTo(4);+ assertThat(secondCharge.processId()).isNotEqualTo(firstCharge.processId());+ assertThat(debits).extracting(WalletLedgerEntry::getAmountUnits).containsExactly(-4, -4);+ assertThat(debits).extracting(WalletLedgerEntry::getDocCount).containsExactly(1, 1);++ JobInput firstOutput = input("fileInput", "first-output", new byte[] {3});+ JobInput secondOutput = input("fileInput", "second-output", new byte[] {4});+ jobService.recordOutput(firstCharge.processId(), firstOutput.path());+ jobService.recordOutput(secondCharge.processId(), secondOutput.path());++ assertJoined(charge(firstOutput, asset), firstCharge);+ assertJoined(charge(secondOutput, asset), secondCharge);+ assertJoined(charge(firstOutput), firstCharge);+ assertThat(debits).hasSize(2);+ }++ @Test+ void supportingAssetsDoNotBecomeDocumentLineage() throws IOException {+ JobInput asset = input("overlayFiles", "overlay", new byte[] {1});+ ChargeOutcome first = charge(input("fileInput", "primary", new byte[] {2}), asset);++ ChargeOutcome reusedAsPrimary =+ charge(input("fileInput", "overlay-as-primary", new byte[] {1}));++ assertThat(reusedAsPrimary.disposition()).isEqualTo(ChargeOutcome.Disposition.OPENED);+ assertThat(reusedAsPrimary.processId()).isNotEqualTo(first.processId());+ assertThat(debits).extracting(WalletLedgerEntry::getAmountUnits).containsExactly(-2, -1);+ }++ @Test+ void eachDocumentKeepsItsOwnAllowanceWhenAnAssetIsShared() throws IOException {+ policy.setStepLimits(Map.of(JobSource.PIPELINE, 2));+ JobInput asset = input("stampImage", "logo", new byte[] {3});+ JobInput first = input("fileInput", "first", new byte[] {1});+ JobInput second = input("fileInput", "second", new byte[] {2});+ ChargeOutcome firstCharge = charge(first, asset);+ ChargeOutcome secondCharge = charge(second, asset);++ assertJoined(charge(first, asset), firstCharge);+ assertJoined(charge(second, asset), secondCharge);+ ChargeOutcome overflow = charge(first, asset);++ assertThat(overflow.disposition()).isEqualTo(ChargeOutcome.Disposition.OPENED);+ assertThat(overflow.units()).isEqualTo(2);+ assertThat(jobs.get(secondCharge.processId()).getStepCount()).isEqualTo(2);+ assertThat(debits)+ .extracting(WalletLedgerEntry::getAmountUnits)+ .containsExactly(-2, -2, -2);+ }++ @Test+ void allPrimaryFilesStillParticipateInMergeMatching() throws IOException {+ JobInput first = input("fileInput", "first", new byte[] {1});+ JobInput second = input("fileInput", "second", new byte[] {2});+ JobInput asset = input("stampImage", "logo", new byte[] {3});+ ChargeOutcome firstCharge = charge(first, asset);++ assertJoined(charge(second, first, asset), firstCharge);+ assertThat(debits).hasSize(1);+ }++ @Test+ void toolsWithoutFileInputKeepTheirExistingInputGrouping() throws IOException {+ JobInput first = input("fileInput1", "first", new byte[] {1});+ JobInput second = input("fileInput2", "second", new byte[] {2});+ ChargeOutcome original = charge(first, second);++ assertThat(original.units()).isEqualTo(2);+ assertJoined(charge(first, second), original);+ assertThat(debits).extracting(WalletLedgerEntry::getDocCount).containsExactly(2);+ }++ private ChargeOutcome charge(JobInput... inputs) throws IOException {+ return chargeService.openProcess(CONTEXT, List.of(inputs));+ }++ private JobInput input(String field, String name, byte[] contents) throws IOException {+ Path path = tempDir.resolve(name + ".bin");+ Files.write(path, contents);+ return new JobInput(+ new MockMultipartFile(field, name + ".bin", "application/octet-stream", contents),+ path);+ }++ private static void assertJoined(ChargeOutcome outcome, ChargeOutcome original) {+ assertThat(outcome.processId()).isEqualTo(original.processId());+ assertThat(outcome.disposition()).isEqualTo(ChargeOutcome.Disposition.JOINED);+ assertThat(outcome.units()).isZero();+ }+}