Skip to content

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

Neaten handling of sensitive fields in policies (#8685)

James Brunton91782e82fb04
diff --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.java
index 547c34f80a..4bc60f1e0c 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
@@ -122,6 +122,7 @@ public class PolicyController {
private final JobOwnershipService jobOwnershipService;
// Shared job store: lets the run endpoints see runs that executed on other nodes.
private final JobStore jobStore;
+ private final StepSecrets stepSecrets;
@PostMapping(value = "/run", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(
@@ -137,7 +138,7 @@ public class PolicyController {
@RequestParam(value = "policyId", required = false) String policyId,
@Valid @ModelAttribute PolicyRunFiles files)
throws IOException {
- PipelineDefinition definition = request.toDefinition();
+ PipelineDefinition definition = withStoredStepSecrets(policyId, request.toDefinition());
stampPolicyAudit(definition);
requireRunnable(definition);
validateAdHocRun(definition);
@@ -166,7 +167,7 @@ public class PolicyController {
@RequestParam(value = "policyId", required = false) String policyId,
@Valid @ModelAttribute PolicyRunFiles files)
throws IOException {
- PipelineDefinition definition = request.toDefinition();
+ PipelineDefinition definition = withStoredStepSecrets(policyId, request.toDefinition());
stampPolicyAudit(definition);
requireRunnable(definition);
validateAdHocRun(definition);
@@ -306,7 +307,8 @@ public class PolicyController {
requirePolicyEditingAllowed();
Policy owned =
ClassificationStepPlanner.ensureClassificationFirst(
- withStoredOutputSecrets(resolveOwnership(policy)));
+ withStoredSecrets(resolveOwnership(policy)));
+ stepSecrets.requireUnmasked(owned.steps());
// Snapshot the previous version before saving so supporting files this edit dropped can
// be cleaned up once nothing references them.
Policy previous =
@@ -325,7 +327,7 @@ public class PolicyController {
// Re-sync trigger registrations now so a new/changed folder-watch policy starts being
// watched immediately instead of after the next reconcile sweep.
policyTriggerManager.notifyPoliciesChanged();
- return ResponseEntity.ok(withMaskedOutputSecrets(saved));
+ return ResponseEntity.ok(withMaskedSecrets(saved));
}
@PutMapping("/order")
@@ -462,20 +464,25 @@ public class PolicyController {
policy.routingRules());
}
- /** Output secrets never leave the server: reads return the redaction sentinel instead. */
- private static Policy withMaskedOutputSecrets(Policy policy) {
+ /**
+ * Output and step secrets never leave the server, even to a policy editor: reads return the
+ * redaction sentinel instead.
+ */
+ private Policy withMaskedSecrets(Policy policy) {
return withOutput(
- policy,
- new OutputSpec(
- policy.output().type(), SecretMasker.mask(policy.output().options())));
+ policy,
+ new OutputSpec(
+ policy.output().type(),
+ SecretMasker.mask(policy.output().options())))
+ .withSteps(stepSecrets.mask(policy.steps()));
}
/**
- * An edit that round-trips a masked read sends output secrets back as the sentinel; restore
- * them from the stored policy so saving without re-typing keeps them (validation then runs
- * against the real values).
+ * An edit that round-trips a masked read sends secrets back as the sentinel; restore them from
+ * the stored policy so saving without re-typing keeps them (validation then runs against the
+ * real values).
*/
- private Policy withStoredOutputSecrets(Policy incoming) {
+ private Policy withStoredSecrets(Policy incoming) {
if (incoming.id() == null || incoming.id().isBlank()) {
return incoming;
}
@@ -484,12 +491,15 @@ public class PolicyController {
.map(
existing ->
withOutput(
- incoming,
- new OutputSpec(
- incoming.output().type(),
- SecretMasker.restoreRedacted(
- incoming.output().options(),
- existing.output().options()))))
+ incoming,
+ new OutputSpec(
+ incoming.output().type(),
+ SecretMasker.restoreRedacted(
+ incoming.output().options(),
+ existing.output().options())))
+ .withSteps(
+ stepSecrets.restore(
+ incoming.steps(), existing.steps())))
.orElse(incoming);
}
@@ -543,11 +553,11 @@ public class PolicyController {
summary = "List policies",
description =
"Lists the policies belonging to the caller's team. Secret-bearing output"
- + " options are returned as a redaction sentinel, never their stored"
- + " values.")
+ + " options and step passwords are returned as a redaction sentinel,"
+ + " never their stored values.")
public List<Policy> listPolicies() {
return policyAccessGuard.visibleFrom(policyStore).stream()
- .map(PolicyController::withMaskedOutputSecrets)
+ .map(this::withMaskedSecrets)
.toList();
}
@@ -591,14 +601,14 @@ public class PolicyController {
@Operation(
summary = "Get a policy by id",
description =
- "Secret-bearing output options are returned as a redaction sentinel, never"
- + " their stored values; an edit that sends the sentinel back keeps"
- + " them.")
+ "Secret-bearing output options and step passwords are returned as a"
+ + " redaction sentinel, never their stored values; an edit that sends"
+ + " the sentinel back keeps them.")
public ResponseEntity<Policy> getPolicy(@PathVariable String policyId) {
return policyStore
.get(policyId)
.filter(this::accessiblePolicySurface)
- .map(PolicyController::withMaskedOutputSecrets)
+ .map(this::withMaskedSecrets)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@@ -784,16 +794,39 @@ public class PolicyController {
* inaccessible policy leaves the run-supplied inputs untouched.
*/
private PolicyInputs resolveStoredAssets(String policyId, PolicyInputs inputs) {
- if (policyId == null || policyId.isBlank() || !policyEditingAllowed()) {
- return inputs;
- }
- return policyStore
- .get(policyId)
- .filter(this::accessiblePolicySurface)
+ return testedPolicy(policyId)
.map(policy -> assetResolver.resolve(policy, inputs))
.orElse(inputs);
}
+ /**
+ * A test run sends the saved policy's steps as read, so their passwords arrive as the sentinel.
+ * Restore them under the same rule as its stored assets; a sentinel left over is rejected
+ * rather than run as the password.
+ */
+ private PipelineDefinition withStoredStepSecrets(
+ String policyId, PipelineDefinition requested) {
+ PipelineDefinition definition =
+ testedPolicy(policyId)
+ .map(
+ policy ->
+ new PipelineDefinition(
+ requested.name(),
+ stepSecrets.restore(
+ requested.steps(), policy.steps()),
+ requested.outputs()))
+ .orElse(requested);
+ stepSecrets.requireUnmasked(definition.steps());
+ return definition;
+ }
+
+ private Optional<Policy> testedPolicy(String policyId) {
+ if (policyId == null || policyId.isBlank() || !policyEditingAllowed()) {
+ return Optional.empty();
+ }
+ return policyStore.get(policyId).filter(this::accessiblePolicySurface);
+ }
+
/**
* Turn the typed run files into engine {@link PolicyInputs}: the primary documents plus the
* named supporting-file store, where each asset's {@code key} is the name a step references
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.java
index 48908c992f..a789cd114a 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
@@ -117,6 +117,7 @@ public class ProcessingFolderController {
private final FolderAccessGuard folderAccessGuard;
private final SourceAccessGuard sourceAccessGuard;
private final ApplicationProperties applicationProperties;
+ private final StepSecrets stepSecrets;
public record ProcessingFolderView(
String id,
@@ -245,6 +246,9 @@ public class ProcessingFolderController {
throw new ResponseStatusException(
HttpStatus.BAD_REQUEST, "Pipeline steps must not be null");
}
+ // Folder views return their steps as stored, so a sentinel here was copied from a masked
+ // policy read and has no stored value behind it.
+ stepSecrets.requireUnmasked(steps);
Stream.concat(outputIds.stream(), routingRules.stream().map(RoutingRule::outputId))
.distinct()
.forEach(outputId -> requireAccessibleDestination(outputId, steps));
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/StepSecrets.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/StepSecrets.java
new file mode 100644
index 0000000000..91ba820490
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/StepSecrets.java
@@ -0,0 +1,172 @@
+package stirling.software.proprietary.policy.controller;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.event.ContextRefreshedEvent;
+import org.springframework.context.event.EventListener;
+import org.springframework.core.MethodParameter;
+import org.springframework.http.HttpStatus;
+import org.springframework.stereotype.Component;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.server.ResponseStatusException;
+import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
+import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+import stirling.software.proprietary.policy.model.PipelineStep;
+import stirling.software.proprietary.util.SecretMasker;
+
+/**
+ * Keeps the passwords pipeline steps carry on the server. A step parameter is secret when the
+ * tool's request model marks its field {@code @Schema(format = "password")}. Reads return {@link
+ * SecretMasker#REDACTED} in its place; a write that sends the sentinel back has it restored from
+ * the stored step, and one with nothing to restore from is rejected, since running it would apply
+ * the sentinel as the password.
+ */
+@Component
+class StepSecrets {
+
+ private final ApplicationContext applicationContext;
+
+ private volatile Map<String, Set<String>> secretsByOperation = Map.of();
+
+ StepSecrets(ApplicationContext applicationContext) {
+ this.applicationContext = applicationContext;
+ }
+
+ static StepSecrets forSecrets(Map<String, Set<String>> secretsByOperation) {
+ StepSecrets stepSecrets = new StepSecrets(null);
+ stepSecrets.secretsByOperation = Map.copyOf(secretsByOperation);
+ return stepSecrets;
+ }
+
+ @EventListener(ContextRefreshedEvent.class)
+ public void discoverSecretParameters() {
+ Map<String, Set<String>> discovered = new HashMap<>();
+ for (RequestMappingHandlerMapping mapping :
+ applicationContext.getBeansOfType(RequestMappingHandlerMapping.class).values()) {
+ mapping.getHandlerMethods()
+ .forEach((info, handler) -> register(discovered, info, handler));
+ }
+ secretsByOperation = Map.copyOf(discovered);
+ }
+
+ private static void register(
+ Map<String, Set<String>> target, RequestMappingInfo info, HandlerMethod handler) {
+ Set<String> secrets = secretFields(handler);
+ if (secrets.isEmpty()) {
+ return;
+ }
+ for (String path : info.getDirectPaths()) {
+ target.computeIfAbsent(path, key -> new HashSet<>()).addAll(secrets);
+ }
+ }
+
+ static Set<String> secretFields(HandlerMethod handler) {
+ Set<String> names = new HashSet<>();
+ for (MethodParameter parameter : handler.getMethodParameters()) {
+ for (Class<?> type = parameter.getParameterType();
+ type != null && type != Object.class;
+ type = type.getSuperclass()) {
+ for (Field field : type.getDeclaredFields()) {
+ Schema schema = field.getAnnotation(Schema.class);
+ if (schema != null && "password".equals(schema.format())) {
+ names.add(field.getName());
+ }
+ }
+ }
+ }
+ return names;
+ }
+
+ List<PipelineStep> mask(List<PipelineStep> steps) {
+ return steps.stream().map(this::mask).toList();
+ }
+
+ private PipelineStep mask(PipelineStep step) {
+ Set<String> secrets = secretsOf(step);
+ if (secrets.isEmpty()) {
+ return step;
+ }
+ Map<String, Object> parameters = new LinkedHashMap<>(step.parameters());
+ parameters.replaceAll(
+ (key, value) ->
+ secrets.contains(key) && isSet(value) ? SecretMasker.REDACTED : value);
+ return new PipelineStep(step.operation(), parameters, step.fileParameters());
+ }
+
+ /**
+ * Steps carry no id, so a step's stored counterpart is the stored step running the same tool at
+ * the same occurrence (the second add-password matches the second add-password). That survives
+ * steps added or removed around it, but not two steps of one tool swapping places.
+ */
+ List<PipelineStep> restore(List<PipelineStep> incoming, List<PipelineStep> stored) {
+ Map<String, List<PipelineStep>> storedByOperation = new HashMap<>();
+ for (PipelineStep step : stored) {
+ if (!secretsOf(step).isEmpty()) {
+ storedByOperation
+ .computeIfAbsent(step.operation(), key -> new ArrayList<>())
+ .add(step);
+ }
+ }
+ Map<String, Integer> occurrences = new HashMap<>();
+ List<PipelineStep> restored = new ArrayList<>(incoming.size());
+ for (PipelineStep step : incoming) {
+ if (secretsOf(step).isEmpty()) {
+ restored.add(step);
+ continue;
+ }
+ int occurrence = occurrences.merge(step.operation(), 1, Integer::sum) - 1;
+ List<PipelineStep> counterparts =
+ storedByOperation.getOrDefault(step.operation(), List.of());
+ restored.add(
+ occurrence < counterparts.size()
+ ? restore(step, counterparts.get(occurrence))
+ : step);
+ }
+ return restored;
+ }
+
+ private PipelineStep restore(PipelineStep step, PipelineStep stored) {
+ Map<String, Object> storedSecrets = new HashMap<>(stored.parameters());
+ storedSecrets.keySet().retainAll(secretsOf(step));
+ return new PipelineStep(
+ step.operation(),
+ SecretMasker.restoreRedacted(step.parameters(), storedSecrets),
+ step.fileParameters());
+ }
+
+ /** Rejects steps still carrying the sentinel for a password, which nothing could restore. */
+ void requireUnmasked(List<PipelineStep> steps) {
+ for (int i = 0; i < steps.size(); i++) {
+ PipelineStep step = steps.get(i);
+ for (String secret : secretsOf(step)) {
+ if (SecretMasker.REDACTED.equals(step.parameters().get(secret))) {
+ throw new ResponseStatusException(
+ HttpStatus.BAD_REQUEST,
+ "Step " + (i + 1) + ": enter the " + secret + " again");
+ }
+ }
+ }
+ }
+
+ private Set<String> secretsOf(PipelineStep step) {
+ if (step == null || step.operation() == null) {
+ return Set.of();
+ }
+ return secretsByOperation.getOrDefault(step.operation(), Set.of());
+ }
+
+ private static boolean isSet(Object value) {
+ return value != null && !value.toString().isBlank();
+ }
+}
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.java
index 1dcc947553..887f247bfe 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
@@ -21,6 +21,7 @@ import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.BeforeEach;
@@ -80,6 +81,10 @@ import tools.jackson.databind.json.JsonMapper;
@DisplayName("PolicyController")
class PolicyControllerTest {
+ private static final String ADD_PASSWORD = "/api/v1/security/add-password";
+ private static final StepSecrets STEP_SECRETS =
+ StepSecrets.forSecrets(Map.of(ADD_PASSWORD, Set.of("password", "ownerPassword")));
+
@Mock private PolicyRunner policyRunner;
@Mock private PolicyRunRegistry runRegistry;
@Mock private stirling.software.proprietary.policy.store.PolicyStore policyStore;
@@ -140,7 +145,8 @@ class PolicyControllerTest {
applicationProperties,
tempFileManager,
jobOwnershipService,
- jobStore);
+ jobStore,
+ STEP_SECRETS);
}
@Test
@@ -216,6 +222,15 @@ class PolicyControllerTest {
};
}
+ private static PipelineStep addPasswordStep(String password) {
+ return new PipelineStep(ADD_PASSWORD, Map.of("password", password, "keyLength", 256));
+ }
+
+ private static Policy passwordPolicy(String id, String password) {
+ return new Policy(
+ id, "name", "owner", true, List.of(), List.of(addPasswordStep(password)), null, 1L);
+ }
+
private static PipelineDefinition definitionWithStep() {
return requestWithStep().toDefinition();
}
@@ -427,6 +442,47 @@ class PolicyControllerTest {
verify(assetResolver).resolve(eq(p), any());
}
+
+ @Test
+ @DisplayName("restores a test run's step passwords from the saved policy for an editor")
+ void restoresStepPasswordsForEditor() throws Exception {
+ applicationProperties.getSecurity().setEnableLogin(false); // editing allowed
+ Policy saved = passwordPolicy("pol-1", "Open-Sesame");
+ when(policyStore.get("pol-1")).thenReturn(Optional.of(saved));
+ when(policyAccessGuard.canAccess(saved)).thenReturn(true);
+ when(assetResolver.resolve(eq(saved), any())).thenAnswer(inv -> inv.getArgument(1));
+ when(policyRunner.runAdHoc(any(), any(), eq(PolicyProgressListener.NOOP)))
+ .thenReturn(handle("run-1"));
+
+ controller.run(
+ new AdHocRunRequest(
+ "pipe", List.of(addPasswordStep(SecretMasker.REDACTED)), List.of()),
+ "pol-1",
+ new PolicyRunFiles());
+
+ ArgumentCaptor<PipelineDefinition> submitted =
+ ArgumentCaptor.forClass(PipelineDefinition.class);
+ verify(policyRunner).runAdHoc(submitted.capture(), any(), any());
+ assertThat(submitted.getValue().steps().getFirst().parameters())
+ .containsEntry("password", "Open-Sesame");
+ }
+
+ @Test
+ @DisplayName("refuses a masked step password rather than run it as the password")
+ void rejectsMaskedStepPasswordForMember() {
+ applicationProperties.getSecurity().setEnableLogin(true);
+ when(policyManagementAuthority.canEditPolicies()).thenReturn(false);
+ AdHocRunRequest copied =
+ new AdHocRunRequest(
+ "pipe", List.of(addPasswordStep(SecretMasker.REDACTED)), List.of());
+
+ assertThatThrownBy(() -> controller.run(copied, "pol-1", new PolicyRunFiles()))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
+ verify(policyStore, never()).get(any());
+ verify(policyRunner, never()).runAdHoc(any(), any(), any());
+ }
}
@Nested
@@ -607,6 +663,41 @@ class PolicyControllerTest {
.isEqualTo(SecretMasker.REDACTED);
}
+ @Test
+ @DisplayName("saving the sentinel back keeps the stored step password")
+ void saveRestoresStepPasswords() {
+ applicationProperties.getSecurity().setEnableLogin(false);
+ Policy existing = passwordPolicy("p1", "Open-Sesame");
+ when(policyStore.get("p1")).thenReturn(Optional.of(existing));
+ when(policyAccessGuard.canAccess(existing)).thenReturn(true);
+ when(policyStore.save(any())).thenAnswer(i -> i.getArgument(0));
+
+ ResponseEntity<Policy> response =
+ controller.savePolicy(passwordPolicy("p1", SecretMasker.REDACTED));
+
+ ArgumentCaptor<Policy> stored = ArgumentCaptor.forClass(Policy.class);
+ verify(policyStore).save(stored.capture());
+ assertThat(stored.getValue().steps().getFirst().parameters())
+ .containsEntry("password", "Open-Sesame");
+ assertThat(response.getBody().steps().getFirst().parameters())
+ .containsEntry("password", SecretMasker.REDACTED);
+ }
+
+ @Test
+ @DisplayName("refuses a step password sentinel with no stored password behind it")
+ void rejectsUnrestorableStepPassword() {
+ applicationProperties.getSecurity().setEnableLogin(false);
+
+ assertThatThrownBy(
+ () ->
+ controller.savePolicy(
+ passwordPolicy(null, SecretMasker.REDACTED)))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
+ verify(policyStore, never()).save(any());
+ }
+
@Test
@DisplayName("forbidden when a non-manager saves any pipeline or policy")
void forbidsSaveForNonManager() {
@@ -784,6 +875,25 @@ class PolicyControllerTest {
assertThat(read.output().options().get("bucket")).isEqualTo("outbox");
}
+ @Test
+ @DisplayName("step passwords are returned as the sentinel, even to a policy editor")
+ void readsMaskStepPasswords() {
+ applicationProperties.getSecurity().setEnableLogin(false); // editing allowed
+ Policy p = passwordPolicy("a", "Open-Sesame");
+ when(policyStore.get("a")).thenReturn(Optional.of(p));
+ when(policyAccessGuard.canAccess(p)).thenReturn(true);
+ when(policyAccessGuard.visibleFrom(policyStore)).thenReturn(List.of(p));
+
+ Policy read = controller.getPolicy("a").getBody();
+ Policy listed = controller.listPolicies().getFirst();
+
+ for (Policy policy : List.of(read, listed)) {
+ assertThat(policy.steps().getFirst().parameters())
+ .containsEntry("password", SecretMasker.REDACTED)
+ .containsEntry("keyLength", 256);
+ }
+ }
+
@Test
@DisplayName("getPolicy returns 404 when not accessible")
void getNotAccessible() {
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.java
index f281ef5852..baaa3a4ce0 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
@@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
@@ -74,6 +75,7 @@ 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;
+import stirling.software.proprietary.util.SecretMasker;
/**
* Tests for {@link ProcessingFolderController}: the source + policy pair composes and tears down
@@ -212,7 +214,9 @@ class ProcessingFolderControllerTest {
accessGuard,
folderAccessGuard,
new SourceAccessGuard(userService, properties, policyManagementAuthority),
- properties);
+ properties,
+ StepSecrets.forSecrets(
+ Map.of("/api/v1/security/add-password", Set.of("password"))));
}
@Test
@@ -1143,6 +1147,27 @@ class ProcessingFolderControllerTest {
return file;
}
+ @Test
+ void refusesAStepPasswordCopiedFromAMaskedPolicyRead() {
+ var copied =
+ new ProcessingFolderController.SaveProcessingFolderRequest(
+ null,
+ FOLDER_ID.toString(),
+ null,
+ true,
+ List.of(
+ new PipelineStep(
+ "/api/v1/security/add-password",
+ Map.of("password", SecretMasker.REDACTED),
+ Map.of())),
+ Map.of("mode", "new_version"));
+
+ assertThatThrownBy(() -> controller.save(copied))
+ .isInstanceOf(ResponseStatusException.class)
+ .hasMessageContaining("enter the password again");
+ assertThat(policyStore.all()).isEmpty();
+ }
+
private static ProcessingFolderController.SaveProcessingFolderRequest request(
String id, String mode) {
return new ProcessingFolderController.SaveProcessingFolderRequest(
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/StepSecretsTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/StepSecretsTest.java
new file mode 100644
index 0000000000..9ac831e544
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/StepSecretsTest.java
@@ -0,0 +1,150 @@
+package stirling.software.proprietary.policy.controller;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.server.ResponseStatusException;
+
+import io.swagger.v3.oas.annotations.media.Schema;
+
+import stirling.software.proprietary.policy.model.PipelineStep;
+import stirling.software.proprietary.util.SecretMasker;
+
+class StepSecretsTest {
+
+ private static final String ADD_PASSWORD = "/api/v1/security/add-password";
+ private static final String COMPRESS = "/api/v1/misc/compress-pdf";
+
+ private final StepSecrets stepSecrets =
+ StepSecrets.forSecrets(Map.of(ADD_PASSWORD, Set.of("password", "ownerPassword")));
+
+ @Test
+ void masksSetPasswordsAndLeavesEverythingElse() {
+ PipelineStep step =
+ new PipelineStep(
+ ADD_PASSWORD,
+ parameters(
+ "password", "Open-Sesame", "ownerPassword", "", "keyLength", 256));
+ PipelineStep compress = new PipelineStep(COMPRESS, parameters("password", "not-a-secret"));
+
+ List<PipelineStep> masked = stepSecrets.mask(List.of(step, compress));
+
+ // A blank password stays blank, so a read still tells "none set" from "set".
+ assertThat(masked.get(0).parameters())
+ .containsEntry("password", SecretMasker.REDACTED)
+ .containsEntry("ownerPassword", "")
+ .containsEntry("keyLength", 256);
+ assertThat(masked.get(1)).isEqualTo(compress);
+ }
+
+ @Test
+ void restoresEachStepFromTheStoredStepOfTheSameToolAndOccurrence() {
+ List<PipelineStep> stored =
+ List.of(
+ new PipelineStep(ADD_PASSWORD, parameters("password", "first")),
+ new PipelineStep(COMPRESS, parameters()),
+ new PipelineStep(ADD_PASSWORD, parameters("password", "second")));
+ List<PipelineStep> incoming =
+ List.of(
+ new PipelineStep(COMPRESS, parameters()),
+ new PipelineStep(
+ ADD_PASSWORD, parameters("password", SecretMasker.REDACTED)),
+ new PipelineStep(
+ ADD_PASSWORD, parameters("password", SecretMasker.REDACTED)));
+
+ List<PipelineStep> restored = stepSecrets.restore(incoming, stored);
+
+ assertThat(restored.get(1).parameters()).containsEntry("password", "first");
+ assertThat(restored.get(2).parameters()).containsEntry("password", "second");
+ }
+
+ @Test
+ void restoresOnlySentinelsAndOnlyInSecretFields() {
+ List<PipelineStep> stored =
+ List.of(
+ new PipelineStep(
+ ADD_PASSWORD,
+ parameters(
+ "password", "old", "ownerPassword", "owner", "note", "x")));
+ List<PipelineStep> incoming =
+ List.of(
+ new PipelineStep(
+ ADD_PASSWORD,
+ parameters(
+ "password",
+ "retyped",
+ "ownerPassword",
+ SecretMasker.REDACTED,
+ "note",
+ SecretMasker.REDACTED)));
+
+ PipelineStep restored = stepSecrets.restore(incoming, stored).getFirst();
+
+ assertThat(restored.parameters())
+ .containsEntry("password", "retyped")
+ .containsEntry("ownerPassword", "owner")
+ .containsEntry("note", SecretMasker.REDACTED);
+ }
+
+ @Test
+ void rejectsASentinelLeftInAPasswordField() {
+ List<PipelineStep> steps =
+ List.of(
+ new PipelineStep(COMPRESS, parameters()),
+ new PipelineStep(
+ ADD_PASSWORD, parameters("password", SecretMasker.REDACTED)));
+
+ assertThatThrownBy(() -> stepSecrets.requireUnmasked(steps))
+ .isInstanceOfSatisfying(
+ ResponseStatusException.class,
+ e -> {
+ assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
+ assertThat(e.getReason()).isEqualTo("Step 2: enter the password again");
+ });
+ }
+
+ @Test
+ void readsPasswordFieldsFromTheRequestModelAndItsSuperclasses() throws Exception {
+ HandlerMethod handler =
+ new HandlerMethod(
+ new PasswordTool(),
+ PasswordTool.class.getMethod(
+ "protect", ProtectRequest.class, String.class));
+
+ assertThat(StepSecrets.secretFields(handler))
+ .containsExactlyInAnyOrder("password", "ownerPassword");
+ }
+
+ private static Map<String, Object> parameters(Object... keysAndValues) {
+ Map<String, Object> parameters = new LinkedHashMap<>();
+ for (int i = 0; i < keysAndValues.length; i += 2) {
+ parameters.put((String) keysAndValues[i], keysAndValues[i + 1]);
+ }
+ return parameters;
+ }
+
+ static class PasswordRequest {
+ @Schema(format = "password")
+ private String password;
+ }
+
+ static class ProtectRequest extends PasswordRequest {
+ @Schema(format = "password")
+ private String ownerPassword;
+
+ @Schema(description = "Not a secret")
+ private String note;
+ }
+
+ static class PasswordTool {
+ public void protect(ProtectRequest request, String label) {}
+ }
+}