#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
Add external-API integrations plus pipeline steps (#7098)
Anthony Stirling1e2895a79f92
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex 2aa8413cf6..b20dc298f7 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -250,6 +250,27 @@ public class ApplicationProperties {*/private boolean allowPrivateS3Endpoints = false;+ /**+ * Whether an API/Purview/ConsignO integration's base URL may resolve to a loopback,+ * link-local, or private address. Off by default: unlike S3 connections, any user may+ * create one of these, so without this gate a user could point a connection at the cloud+ * metadata address and have the server fetch it for them. Enable only when integrations+ * genuinely live inside the network (e.g. an on-prem ConsignO or an internal API gateway).+ */+ private boolean allowPrivateApiEndpoints = false;++ /**+ * Whether administrators may define their own API integrations - a free-form base URL,+ * path, body and headers - as opposed to only using the built-in vendor presets (Purview,+ * ConsignO, S3). On by default, and admin-only regardless: a custom integration can point+ * the server at any host, so it is authoring power, not self-serve.+ *+ * <p>Turning this off stops new custom integrations being created or edited. Ones that+ * already exist keep running, because a policy that silently stopped calling out would be a+ * worse surprise than one that keeps working; disable the connection itself to stop it.+ */+ private boolean allowCustomApiIntegrations = true;+private long webhookMaxBytes = 104857600L;}diff --git a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.javaindex 63d577ca85..dd49ab3f51 100644--- a/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java+++ b/app/common/src/main/java/stirling/software/common/service/InternalApiClient.java@@ -46,9 +46,14 @@ public class InternalApiClient {// The second alternation carves out `/api/v1/ai/tools/*` specifically — AI tools are// dispatchable, but the broader `/api/v1/ai/` surface (orchestrate, health, etc.) is// intentionally NOT permitted to avoid plan steps re-entering the orchestrator.+ //+ // `/api/v1/integration/*` holds third-party steps (external API call, Purview labelling,+ // ConsignO). They reach outside the JVM, so the namespace is deliberately kept to tools that+ // dereference an admin-owned connection rather than a caller-supplied host — see+ // ApiConnectionResolver.private static final Pattern ALLOWED_ENDPOINT_PATH =Pattern.compile(- "^/api/v1/(general|misc|security|convert|filter)(/[A-Za-z0-9_-]+)+$"+ "^/api/v1/(general|misc|security|convert|filter|integration)(/[A-Za-z0-9_-]+)+$"+ "|^/api/v1/ai/tools(/[A-Za-z0-9_-]+)+$");/**diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/SecretMasker.java b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/SecretMasker.javaindex f160b92759..4be76e174e 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/access/service/SecretMasker.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/access/service/SecretMasker.java@@ -39,6 +39,11 @@ public class SecretMasker {"bearer","signature");+ // Keys whose nested map holds secrets under arbitrary, caller-named keys - a free-form HTTP+ // headers map is the case in point: the secret can sit under any header name (X-API-Key,+ // Ocp-Apim-Subscription-Key), so the name is no signal. Mask every value in these outright.+ private static final Set<String> SENSITIVE_VALUE_CONTAINERS = Set.of("headers");+/** Replace sensitive values with the mask (recursively) for safe display. */public Map<String, Object> mask(Map<String, Object> config) {return mask(config, 0);@@ -73,6 +78,12 @@ public class SecretMasker {if (isSensitive(e.getKey()) && isRedacted(e.getValue(), depth)) {continue;}+ if (isSensitiveContainer(e.getKey())+ && e.getValue() instanceof Map<?, ?> m+ && depth < MAX_DEPTH) {+ out.put(e.getKey(), sanitizeAllValues(castMap(m), depth + 1));+ continue;+ }out.put(e.getKey(),e.getValue() instanceof Map<?, ?> m && depth < MAX_DEPTH@@ -100,6 +111,14 @@ public class SecretMasker {}continue;}+ if (isSensitiveContainer(key)+ && depth < MAX_DEPTH+ && stored.get(key) instanceof Map<?, ?> s+ && value instanceof Map<?, ?> i) {+ // Every value here is a secret, so restore a redacted one from stored per-entry.+ out.put(key, mergeAllValues(castMap(s), castMap(i), depth + 1));+ continue;+ }if (depth < MAX_DEPTH&& stored.get(key) instanceof Map<?, ?> s&& value instanceof Map<?, ?> i) {@@ -119,6 +138,9 @@ public class SecretMasker {}return MASK;}+ if (isSensitiveContainer(key) && value instanceof Map<?, ?> m && depth < MAX_DEPTH) {+ return maskAllValues(castMap(m), depth + 1);+ }if (depth >= MAX_DEPTH) {// Too deep to descend; mask containers rather than risk leaking an unmasked secret.return value instanceof Map<?, ?> || value instanceof List<?> ? MASK : value;@@ -141,6 +163,53 @@ public class SecretMasker {return SENSITIVE_HINTS.stream().anyMatch(lower::contains);}+ private boolean isSensitiveContainer(String key) {+ return SENSITIVE_VALUE_CONTAINERS.contains(key.toLowerCase(Locale.ROOT));+ }++ /** Mask every value in a container map, whatever its keys are named. */+ private Map<String, Object> maskAllValues(Map<String, Object> map, int depth) {+ Map<String, Object> out = new LinkedHashMap<>();+ for (Map.Entry<String, Object> e : map.entrySet()) {+ Object v = e.getValue();+ if (v == null || (v instanceof String s && s.isBlank())) {+ out.put(e.getKey(), v);+ } else if (v instanceof Map<?, ?> m && depth < MAX_DEPTH) {+ out.put(e.getKey(), maskAllValues(castMap(m), depth + 1));+ } else {+ out.put(e.getKey(), MASK);+ }+ }+ return out;+ }++ /** Merge a container map treating every entry as a secret, restoring redacted from stored. */+ private Map<String, Object> mergeAllValues(+ Map<String, Object> stored, Map<String, Object> incoming, int depth) {+ Map<String, Object> out = new LinkedHashMap<>();+ for (Map.Entry<String, Object> e : incoming.entrySet()) {+ if (isRedacted(e.getValue(), depth)) {+ if (stored.containsKey(e.getKey())) {+ out.put(e.getKey(), stored.get(e.getKey()));+ }+ } else {+ out.put(e.getKey(), e.getValue());+ }+ }+ return out;+ }++ /** Drop redacted entries from a container map on create, whatever their keys are named. */+ private Map<String, Object> sanitizeAllValues(Map<String, Object> map, int depth) {+ Map<String, Object> out = new LinkedHashMap<>();+ for (Map.Entry<String, Object> e : map.entrySet()) {+ if (!isRedacted(e.getValue(), depth)) {+ out.put(e.getKey(), e.getValue());+ }+ }+ return out;+ }+/** Blank, the mask placeholder, or any structure that still contains the mask. */private boolean isRedacted(Object value, int depth) {if (value == null) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiAuthType.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiAuthType.javanew file mode 100644index 0000000000..0eef442523--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiAuthType.java@@ -0,0 +1,25 @@+package stirling.software.proprietary.integration.api;++/**+ * How an {@link stirling.software.proprietary.integration.model.IntegrationType#API} connection+ * authenticates.+ */+public enum ApiAuthType {+ /** No credentials; the endpoint is open or authorises by network position. */+ NONE,+ /** {@code Authorization: Bearer <token>}. */+ BEARER,+ /** {@code Authorization: Basic base64(username:password)}. */+ BASIC,+ /** The token in a caller-named header, e.g. {@code X-API-Key: <token>}. */+ HEADER,+ /**+ * The connection logs in first and reuses the short-lived token it gets back.+ *+ * <p>For the large class of enterprise APIs - ConsignO Cloud, OAuth2 client-credentials, and+ * others - where credentials buy a token rather than authenticating a call directly. Without+ * this a step could not reach them at all: each call needs a token, and a stateless step has+ * nowhere to obtain or keep one. See {@link ApiTokenLogin}.+ */+ TOKEN_LOGIN+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiConnectionResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiConnectionResolver.javanew file mode 100644index 0000000000..e29435ff14--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiConnectionResolver.java@@ -0,0 +1,130 @@+package stirling.software.proprietary.integration.api;++import java.util.LinkedHashMap;+import java.util.Map;++import org.springframework.security.core.Authentication;+import org.springframework.security.core.context.SecurityContextHolder;+import org.springframework.security.core.userdetails.UserDetails;+import org.springframework.stereotype.Service;+import org.springframework.transaction.annotation.Transactional;++import lombok.RequiredArgsConstructor;++import stirling.software.proprietary.access.model.ResourceType;+import stirling.software.proprietary.access.service.OwnershipService;+import stirling.software.proprietary.integration.model.IntegrationConfig;+import stirling.software.proprietary.integration.model.IntegrationType;+import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.service.UserService;++import tools.jackson.core.type.TypeReference;+import tools.jackson.databind.ObjectMapper;++/**+ * Dereferences a step's {@code connectionId} to a stored integration config.+ *+ * <p>Mirrors {@code S3ConnectionResolver}. When an authenticated caller is present the connection+ * must be usable by them; a background worker thread carries no {@code SecurityContext} and skips+ * that check, relying on the step having been access-checked when the policy was saved or when an+ * ad-hoc run was dispatched - see {@link IntegrationStepValidator}, which is what makes that+ * assumption true rather than merely hoped for.+ */+@Service+@RequiredArgsConstructor+@Transactional(readOnly = true)+public class ApiConnectionResolver {++ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();++ private final IntegrationConfigRepository connections;+ private final OwnershipService ownership;+ private final UserService userService;++ /** The raw config map for a connection of the given type. */+ public Map<String, Object> resolveConfig(Long connectionId, IntegrationType type) {+ IntegrationConfig connection =+ connections+ .findById(connectionId)+ .filter(cfg -> cfg.getIntegrationType() == type)+ .filter(this::usableByCurrentUser)+ // Existence and access collapse into one error so a caller cannot tell+ // "no such connection" from "someone else's connection" and enumerate ids.+ .orElseThrow(+ () ->+ new IllegalArgumentException(+ "unknown or inaccessible "+ + type.name().toLowerCase()+ + " connection"));+ if (!connection.isEnabled()) {+ throw new IllegalArgumentException(+ type.name().toLowerCase() + " connection is disabled");+ }+ return configOf(connection);+ }++ /** The settings for a generic {@code API} connection. */+ public ApiConnectionSettings resolve(Long connectionId) {+ return ApiConnectionSettings.from(resolveConfig(connectionId, IntegrationType.API));+ }++ /** Parse a {@code connectionId} step parameter; null when absent. */+ public static Long connectionId(Object reference) {+ if (reference == null || (reference instanceof String s && s.isBlank())) {+ return null;+ }+ if (reference instanceof Number number) {+ return number.longValue();+ }+ try {+ return Long.valueOf(reference.toString().trim());+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException(+ "'connectionId' is not a valid connection reference: " + reference);+ }+ }++ /**+ * Whether the current caller may use this connection. A missing principal means a worker+ * thread, where access was established earlier; it must never be the only thing standing+ * between a caller and a connection, or the check becomes a confused deputy.+ */+ private boolean usableByCurrentUser(IntegrationConfig connection) {+ User user = currentUser();+ return user == null || ownership.canUse(ResourceType.INTEGRATION_CONFIG, connection, user);+ }++ // Mirrors ResourceAccessSecurity's principal resolution; null when unauthenticated.+ private User currentUser() {+ Authentication auth = SecurityContextHolder.getContext().getAuthentication();+ if (auth == null || !auth.isAuthenticated()) {+ return null;+ }+ Object principal = auth.getPrincipal();+ if (principal instanceof User user) {+ return user;+ }+ if (principal instanceof UserDetails userDetails) {+ return userService.findByUsername(userDetails.getUsername()).orElse(null);+ }+ if (principal instanceof String username && !"anonymousUser".equals(username)) {+ return userService.findByUsername(username).orElse(null);+ }+ return null;+ }++ private static Map<String, Object> configOf(IntegrationConfig connection) {+ String json = connection.getConfig();+ if (json == null || json.isBlank()) {+ return Map.of();+ }+ try {+ return OBJECT_MAPPER.readValue(+ json, new TypeReference<LinkedHashMap<String, Object>>() {});+ } catch (Exception e) {+ throw new IllegalArgumentException(+ "connection '" + connection.getName() + "' has unreadable config", e);+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiConnectionSettings.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiConnectionSettings.javanew file mode 100644index 0000000000..a1bb29cf84--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiConnectionSettings.java@@ -0,0 +1,282 @@+package stirling.software.proprietary.integration.api;++import java.net.URI;+import java.net.URISyntaxException;+import java.util.LinkedHashMap;+import java.util.Locale;+import java.util.Map;+import java.util.Objects;+import java.util.Set;++/**+ * A resolved {@code API} connection: where to call, and how to authenticate.+ *+ * <p>{@code baseUrl} is the security anchor of the whole feature. It is set by whoever can manage+ * the connection (an admin or team owner) and is the only thing that decides which host is+ * contacted. A pipeline step supplies a <em>relative path</em> only, resolved under this base by+ * {@link ExternalApiPaths}, so a step author can never pivot the call to a host of their choosing.+ * Widening that - letting a step pass a full URL - would turn every policy into an SSRF primitive.+ *+ * <p>Whether the base URL may resolve to a private address is deliberately <em>not</em> a field+ * here. Any user may create an API connection (unlike S3, which {@code IntegrationConfigService}+ * restricts to admins), so a per-connection opt-in would let a user grant themselves a fetch of the+ * cloud metadata service. It is an operator property instead - {@code+ * policies.allowPrivateApiEndpoints} - checked by {@link ApiIntegrationValidator}.+ */+public record ApiConnectionSettings(+ String baseUrl,+ ApiAuthType authType,+ String headerName,+ String headerPrefix,+ String token,+ String username,+ String password,+ Map<String, String> headers,+ ApiTokenLogin tokenLogin,+ Set<String> resultUrlHosts,+ int timeoutSeconds) {++ static final String BASE_URL_OPTION = "baseUrl";+ static final String AUTH_TYPE_OPTION = "authType";+ static final String HEADER_NAME_OPTION = "headerName";+ static final String HEADER_PREFIX_OPTION = "headerPrefix";+ // "token"/"password" contain SecretMasker hints, so they mask on read and merge on update.+ static final String TOKEN_OPTION = "token";+ static final String USERNAME_OPTION = "username";+ static final String PASSWORD_OPTION = "password";+ static final String HEADERS_OPTION = "headers";+ static final String RESULT_URL_HOSTS_OPTION = "resultUrlHosts";+ static final String TIMEOUT_SECONDS_OPTION = "timeoutSeconds";++ static final int DEFAULT_TIMEOUT_SECONDS = 60;+ private static final int MAX_TIMEOUT_SECONDS = 600;++ public ApiConnectionSettings {+ headers = headers == null ? Map.of() : Map.copyOf(headers);+ resultUrlHosts = resultUrlHosts == null ? Set.of() : Set.copyOf(resultUrlHosts);+ }++ /**+ * @throws IllegalArgumentException if the config is unusable; the message is surfaced to the+ * operator editing the connection, so it names the offending option.+ */+ public static ApiConnectionSettings from(Map<String, Object> options) {+ String baseUrl = trimmed(options.get(BASE_URL_OPTION));+ if (baseUrl == null) {+ throw new IllegalArgumentException("api config requires a 'baseUrl' option");+ }+ URI uri = parseHttpUrl(baseUrl);+ if (uri.getQuery() != null || uri.getFragment() != null) {+ throw new IllegalArgumentException(+ "api config 'baseUrl' must not carry a query string or fragment");+ }++ ApiAuthType authType = parseAuthType(trimmed(options.get(AUTH_TYPE_OPTION)));+ String headerName = trimmed(options.get(HEADER_NAME_OPTION));+ // Many APIs want a scheme before the token ("Authorization: Token abc",+ // "Authorization: DeepL-Auth-Key abc"). Without this a preset would have to make the+ // operator paste the scheme into the secret itself, which reads as a typo waiting to+ // happen.+ String headerPrefix = trimmed(options.get(HEADER_PREFIX_OPTION));+ String token = trimmed(options.get(TOKEN_OPTION));+ String username = trimmed(options.get(USERNAME_OPTION));+ String password = trimmed(options.get(PASSWORD_OPTION));++ switch (authType) {+ case BEARER -> require(token, "api config authType 'BEARER' requires a 'token'");+ case HEADER -> {+ require(token, "api config authType 'HEADER' requires a 'token'");+ require(headerName, "api config authType 'HEADER' requires a 'headerName'");+ if (!ExternalApiHeaders.isValidName(headerName)) {+ throw new IllegalArgumentException(+ "api config 'headerName' is not a valid HTTP header name: "+ + headerName);+ }+ }+ case BASIC -> {+ require(username, "api config authType 'BASIC' requires a 'username'");+ require(password, "api config authType 'BASIC' requires a 'password'");+ }+ case TOKEN_LOGIN -> {+ /* validated by ApiTokenLogin.from below */+ }+ case NONE -> {+ /* nothing to check */+ }+ }++ return new ApiConnectionSettings(+ stripTrailingSlash(baseUrl),+ authType,+ headerName,+ headerPrefix,+ token,+ username,+ password,+ parseHeaders(options.get(HEADERS_OPTION)),+ authType == ApiAuthType.TOKEN_LOGIN ? ApiTokenLogin.from(options) : null,+ parseResultUrlHosts(options.get(RESULT_URL_HOSTS_OPTION)),+ parseTimeout(options.get(TIMEOUT_SECONDS_OPTION)));+ }++ /** The configured base as a URI; callers resolve step paths under it. */+ public URI baseUri() {+ return URI.create(baseUrl);+ }++ /**+ * Identity of this connection's login for token-cache purposes. Includes the credentials, so+ * editing a password evicts the token cached under the old one rather than reusing it until it+ * expires.+ */+ String tokenCacheKey() {+ return baseUrl + "|" + Objects.hash(tokenLogin);+ }++ private static URI parseHttpUrl(String value) {+ URI uri;+ try {+ uri = new URI(value);+ } catch (URISyntaxException e) {+ throw new IllegalArgumentException("api config 'baseUrl' is not a valid URL", e);+ }+ String scheme = uri.getScheme() == null ? null : uri.getScheme().toLowerCase(Locale.ROOT);+ if (!"http".equals(scheme) && !"https".equals(scheme)) {+ throw new IllegalArgumentException(+ "api config 'baseUrl' must be an http(s) URL, e.g. https://api.example.com");+ }+ if (uri.getHost() == null || uri.getHost().isBlank()) {+ throw new IllegalArgumentException("api config 'baseUrl' must include a host");+ }+ return uri;+ }++ private static ApiAuthType parseAuthType(String value) {+ if (value == null) {+ return ApiAuthType.NONE;+ }+ try {+ return ApiAuthType.valueOf(value.toUpperCase(Locale.ROOT));+ } catch (IllegalArgumentException e) {+ throw new IllegalArgumentException(+ "api config 'authType' must be one of NONE, BEARER, BASIC, HEADER; got "+ + value);+ }+ }++ /** Static headers sent on every call. Rejects anything auth-bearing to keep one auth path. */+ private static Map<String, String> parseHeaders(Object value) {+ if (value == null) {+ return Map.of();+ }+ if (!(value instanceof Map<?, ?> raw)) {+ throw new IllegalArgumentException("api config 'headers' must be an object");+ }+ Map<String, String> headers = new LinkedHashMap<>();+ for (Map.Entry<?, ?> entry : raw.entrySet()) {+ String name = trimmed(entry.getKey());+ String headerValue = entry.getValue() == null ? null : entry.getValue().toString();+ if (name == null) {+ continue;+ }+ if (!ExternalApiHeaders.isValidName(name)) {+ throw new IllegalArgumentException(+ "api config 'headers' has an invalid header name: " + name);+ }+ if (ExternalApiHeaders.isReserved(name)) {+ throw new IllegalArgumentException(+ "api config 'headers' must not set '"+ + name+ + "'; use 'authType' and 'token' instead");+ }+ if (headerValue == null || !ExternalApiHeaders.isValidValue(headerValue)) {+ throw new IllegalArgumentException(+ "api config 'headers' has an invalid value for '" + name + "'");+ }+ headers.put(name, headerValue);+ }+ return headers;+ }++ /**+ * Hosts a result may be fetched from, beyond the connection's own. Declared by the operator+ * because the alternative - trusting the host named in the API's response - is an SSRF.+ */+ private static Set<String> parseResultUrlHosts(Object value) {+ if (value == null) {+ return Set.of();+ }+ if (!(value instanceof java.util.List<?> list)) {+ throw new IllegalArgumentException(+ "api config 'resultUrlHosts' must be a list of hostnames");+ }+ Set<String> out = new java.util.LinkedHashSet<>();+ for (Object entry : list) {+ String host = trimmed(entry);+ if (host == null) {+ continue;+ }+ if (host.contains("/") || host.contains(":") || host.contains("*")) {+ // A URL, port or wildcard here would read as broader than it is; subdomains are+ // already covered by the "endsWith('.' + host)" rule at match time.+ throw new IllegalArgumentException(+ "api config 'resultUrlHosts' takes bare hostnames, e.g."+ + " cdn.vendor.com; got "+ + host);+ }+ out.add(host.toLowerCase(Locale.ROOT));+ }+ return out;+ }++ private static int parseTimeout(Object value) {+ if (value == null) {+ return DEFAULT_TIMEOUT_SECONDS;+ }+ int seconds;+ try {+ seconds = Integer.parseInt(value.toString().trim());+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException("api config 'timeoutSeconds' must be a number");+ }+ if (seconds < 1 || seconds > MAX_TIMEOUT_SECONDS) {+ throw new IllegalArgumentException(+ "api config 'timeoutSeconds' must be between 1 and " + MAX_TIMEOUT_SECONDS);+ }+ return seconds;+ }++ private static void require(String value, String message) {+ if (value == null) {+ throw new IllegalArgumentException(message);+ }+ }++ private static String stripTrailingSlash(String value) {+ String out = value;+ while (out.endsWith("/")) {+ out = out.substring(0, out.length() - 1);+ }+ return out;+ }++ private static String trimmed(Object value) {+ if (value == null) {+ return null;+ }+ String text = value.toString().trim();+ return text.isEmpty() ? null : text;+ }++ /** Never prints the credentials, so an accidental log line cannot leak them. */+ @Override+ public String toString() {+ return "ApiConnectionSettings[baseUrl="+ + baseUrl+ + ", authType="+ + authType+ + ", timeoutSeconds="+ + timeoutSeconds+ + "]";+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiIntegrationValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiIntegrationValidator.javanew file mode 100644index 0000000000..014bacb4a5--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiIntegrationValidator.java@@ -0,0 +1,109 @@+package stirling.software.proprietary.integration.api;++import java.util.Map;++import org.springframework.stereotype.Component;++import lombok.RequiredArgsConstructor;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.cluster.s3.S3Clients;+import stirling.software.proprietary.integration.model.IntegrationType;+import stirling.software.proprietary.integration.service.IntegrationConfigValidator;++/**+ * The {@code API} connection schema, enforced when the config is saved: an http(s) base URL, a+ * coherent auth block, and a host that must not reach private addresses without the operator+ * opt-in.+ *+ * <p>The host check runs here so a bad connection fails in the form rather than mid-run. It is not+ * the only check - {@link ExternalApiCaller} re-checks before dispatch, because DNS can be+ * re-pointed at a private address long after save time (a check-then-use gap this validator alone+ * cannot close).+ */+@Component+@RequiredArgsConstructor+public class ApiIntegrationValidator implements IntegrationConfigValidator {++ private final ApplicationProperties applicationProperties;++ @Override+ public IntegrationType type() {+ return IntegrationType.API;+ }++ @Override+ public void validate(Map<String, Object> config) {+ ApiConnectionSettings settings = ApiConnectionSettings.from(config);+ requirePublicHost(settings, applicationProperties, "API connection base URL");+ }++ /**+ * Shared by every integration type that dials an operator-supplied host, so they cannot drift+ * apart on what counts as reachable.+ */+ static void requirePublicHost(+ ApiConnectionSettings settings,+ ApplicationProperties applicationProperties,+ String settingName) {+ // Block the cloud metadata service unconditionally - before the opt-in check. The private-+ // endpoint opt-in exists for on-prem services (RFC1918, an internal gateway), but the+ // metadata endpoint is never a real integration and reaching it is the highest-value SSRF:+ // it hands out the instance's own IAM credentials. So it stays blocked even when the+ // operator has allowed private endpoints.+ denyCloudMetadata(settings.baseUri(), settingName);+ try {+ S3Clients.validateEndpointHost(+ settings.baseUri(),+ applicationProperties.getPolicies().isAllowPrivateApiEndpoints(),+ settingName,+ "set policies.allowPrivateApiEndpoints=true to opt in (e.g. for an on-prem"+ + " integration).");+ } catch (IllegalStateException e) {+ throw new IllegalArgumentException(e.getMessage(), e);+ }+ }++ /** AWS/GCP/Azure, Oracle and IBM metadata addresses; mirrors {@code SsrfProtectionService}. */+ private static final java.util.Set<String> CLOUD_METADATA_IPS =+ java.util.Set.of(+ "169.254.169.254", "169.254.169.253", "169.254.169.250", "fd00:ec2::254");++ private static void denyCloudMetadata(java.net.URI uri, String settingName) {+ String host = uri.getHost();+ if (host == null || host.isBlank()) {+ return; // a missing host is S3Clients' error to report, with its own message+ }+ java.net.InetAddress[] addresses;+ try {+ addresses = java.net.InetAddress.getAllByName(host);+ } catch (java.net.UnknownHostException e) {+ return; // an unresolvable host is likewise left to S3Clients to reject+ }+ for (java.net.InetAddress address : addresses) {+ String ip = normalise(address.getHostAddress());+ if (CLOUD_METADATA_IPS.stream().anyMatch(ip::startsWith)) {+ throw new IllegalArgumentException(+ settingName+ + " host '"+ + host+ + "' resolves to the cloud metadata service ("+ + ip+ + "), which is never a valid integration target.");+ }+ }+ }++ /** Strip an IPv4-mapped-IPv6 prefix and any zone id so the compare sees a bare address. */+ private static String normalise(String ip) {+ String out = ip;+ int zone = out.indexOf('%');+ if (zone >= 0) {+ out = out.substring(0, zone);+ }+ if (out.startsWith("::ffff:")) {+ out = out.substring(7);+ }+ return out;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiTokenCache.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiTokenCache.javanew file mode 100644index 0000000000..3610f77ab0--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiTokenCache.java@@ -0,0 +1,149 @@+package stirling.software.proprietary.integration.api;++import java.io.IOException;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.time.Duration;+import java.util.Map;+import java.util.concurrent.TimeUnit;++import org.springframework.http.MediaType;++import com.github.benmanes.caffeine.cache.Cache;+import com.github.benmanes.caffeine.cache.Caffeine;++import lombok.extern.slf4j.Slf4j;++import tools.jackson.databind.ObjectMapper;++/**+ * Obtains and caches the short-lived tokens of {@link ApiAuthType#TOKEN_LOGIN} connections.+ *+ * <p>The step that uses a token is stateless and runs once per document, so without a cache a+ * hundred-document policy would perform a hundred logins - which many vendors rate-limit, and some+ * treat as suspicious. The cache is keyed on the connection's login identity (credentials included)+ * so that editing a password does not keep reusing the token bought with the old one.+ *+ * <p>Entries expire well inside the vendor's stated lifetime, and a 401 additionally evicts and+ * retries once ({@link ExternalApiCaller}), so a token that expires early - or is revoked - costs+ * one retry rather than a failed run.+ */+@Slf4j+public class ApiTokenCache {++ /** Bounded so a deployment with many connections cannot grow this without limit. */+ private static final int MAX_ENTRIES = 500;++ private final Cache<String, String> tokens;+ private final HttpClient httpClient;+ private final ObjectMapper objectMapper;++ ApiTokenCache(HttpClient httpClient, ObjectMapper objectMapper) {+ this.httpClient = httpClient;+ this.objectMapper = objectMapper;+ this.tokens =+ Caffeine.newBuilder()+ .maximumSize(MAX_ENTRIES)+ // Per-entry, because each connection states its own lifetime.+ .expireAfter(+ new com.github.benmanes.caffeine.cache.Expiry<String, String>() {+ @Override+ public long expireAfterCreate(+ String key, String value, long currentTime) {+ return ttlNanos(key);+ }++ @Override+ public long expireAfterUpdate(+ String key,+ String value,+ long currentTime,+ long currentDuration) {+ return ttlNanos(key);+ }++ @Override+ public long expireAfterRead(+ String key,+ String value,+ long currentTime,+ long currentDuration) {+ // Reading must not extend a token's life: the vendor's+ // clock is running regardless of how often we use it.+ return currentDuration;+ }+ })+ .build();+ }++ // The TTL travels in the key so the Expiry callbacks can see it without a second lookup.+ private static long ttlNanos(String key) {+ int seconds = Integer.parseInt(key.substring(key.lastIndexOf('#') + 1));+ return TimeUnit.SECONDS.toNanos(seconds);+ }++ /**+ * The connection's current token, logging in if there is not a live one.+ *+ * @throws IOException if the login call fails or returns no token+ */+ String token(ApiConnectionSettings settings) throws IOException {+ String key = cacheKey(settings);+ String cached = tokens.getIfPresent(key);+ if (cached != null) {+ return cached;+ }+ String token = login(settings);+ tokens.put(key, token);+ return token;+ }++ /** Drop the cached token, e.g. after a 401 says it is no longer accepted. */+ void invalidate(ApiConnectionSettings settings) {+ tokens.invalidate(cacheKey(settings));+ }++ private static String cacheKey(ApiConnectionSettings settings) {+ return settings.tokenCacheKey() + "#" + settings.tokenLogin().tokenTtlSeconds();+ }++ private String login(ApiConnectionSettings settings) throws IOException {+ ApiTokenLogin login = settings.tokenLogin();+ URI target = ExternalApiPaths.resolve(settings.baseUri(), login.loginPath());++ HttpRequest.Builder request =+ HttpRequest.newBuilder(target)+ .timeout(Duration.ofSeconds(settings.timeoutSeconds()))+ .header("Content-Type", MediaType.APPLICATION_JSON_VALUE)+ .POST(+ HttpRequest.BodyPublishers.ofByteArray(+ objectMapper.writeValueAsBytes(login.loginBody())));+ login.loginHeaders().forEach(request::header);++ ExternalApiCaller.Response response =+ ExternalApiCaller.send(httpClient, request.build(), target);+ if (!response.isSuccess()) {+ // Deliberately does not echo the body: a login failure response can repeat the+ // credentials back, and this message reaches the run log.+ throw new IOException(+ "Login to "+ + target.getHost()+ + login.loginPath()+ + " returned HTTP "+ + response.status());+ }+ try {+ String token = login.extractToken(response, objectMapper);+ log.debug("[external-api] obtained a token from {}", target.getHost());+ return token;+ } catch (IllegalStateException e) {+ throw new IOException(e.getMessage(), e);+ }+ }++ /** The auth header for an authenticated call. */+ Map.Entry<String, String> authHeader(ApiConnectionSettings settings) throws IOException {+ return settings.tokenLogin().authHeader(token(settings));+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiTokenLogin.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiTokenLogin.javanew file mode 100644index 0000000000..a7c02d786f--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ApiTokenLogin.java@@ -0,0 +1,209 @@+package stirling.software.proprietary.integration.api;++import java.util.LinkedHashMap;+import java.util.Map;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;++/**+ * How a connection turns credentials into a short-lived token.+ *+ * <p>Modelled on what real APIs actually do rather than on one vendor. The two axes that vary are+ * where the token comes back ({@code tokenResponseHeader} or {@code tokenResponseJsonPath}) and how+ * it is then presented ({@code tokenHeaderName} + {@code tokenPrefix}). That covers both ends of+ * the spectrum:+ *+ * <ul>+ * <li>ConsignO Cloud - {@code POST /auth/login} with {@code X-Client-Id}/{@code X-Client-Secret}+ * headers and a {@code {username, password, tenantId}} body, returning the token in the+ * {@code X-Auth-Token} <em>response header</em>, which is then sent back as {@code+ * X-Auth-Token}.+ * <li>OAuth2 client-credentials - a form or JSON post returning {@code {"access_token": ...}} in+ * the body, sent back as {@code Authorization: Bearer ...}.+ * </ul>+ *+ * <p>{@code loginBody} and {@code loginHeaders} are stored as nested maps rather than a+ * pre-rendered JSON string so {@code SecretMasker} can recurse and mask the {@code password} /+ * {@code X-Client-Secret} entries inside them. A flat string would sail past it and hand the+ * password back in plaintext on every read of the connection.+ */+record ApiTokenLogin(+ String loginPath,+ Map<String, Object> loginBody,+ Map<String, String> loginHeaders,+ String tokenResponseHeader,+ String tokenResponseJsonPath,+ String tokenHeaderName,+ String tokenPrefix,+ int tokenTtlSeconds) {++ static final String LOGIN_PATH_OPTION = "loginPath";+ static final String LOGIN_BODY_OPTION = "loginBody";+ static final String LOGIN_HEADERS_OPTION = "loginHeaders";+ static final String TOKEN_RESPONSE_HEADER_OPTION = "tokenResponseHeader";+ static final String TOKEN_RESPONSE_JSON_PATH_OPTION = "tokenResponseJsonPath";+ static final String TOKEN_HEADER_NAME_OPTION = "tokenHeaderName";+ static final String TOKEN_PREFIX_OPTION = "tokenPrefix";+ static final String TOKEN_TTL_SECONDS_OPTION = "tokenTtlSeconds";++ /**+ * Conservative default. ConsignO's token lasts 30 minutes; caching for 25 leaves room for a+ * slow call to finish on a token that was still valid when it started. A cache that expired+ * exactly on the vendor's boundary would fail intermittently and look like a network fault.+ */+ static final int DEFAULT_TOKEN_TTL_SECONDS = 1500;++ private static final int MAX_TOKEN_TTL_SECONDS = 86400;++ ApiTokenLogin {+ loginBody = loginBody == null ? Map.of() : Map.copyOf(loginBody);+ loginHeaders = loginHeaders == null ? Map.of() : Map.copyOf(loginHeaders);+ }++ static ApiTokenLogin from(Map<String, Object> options) {+ String loginPath = trimmed(options.get(LOGIN_PATH_OPTION));+ if (loginPath == null) {+ throw new IllegalArgumentException(+ "api config authType 'TOKEN_LOGIN' requires a 'loginPath', e.g. /auth/login");+ }+ String responseHeader = trimmed(options.get(TOKEN_RESPONSE_HEADER_OPTION));+ String responseJsonPath = trimmed(options.get(TOKEN_RESPONSE_JSON_PATH_OPTION));+ if ((responseHeader == null) == (responseJsonPath == null)) {+ throw new IllegalArgumentException(+ "api config authType 'TOKEN_LOGIN' needs exactly one of"+ + " 'tokenResponseHeader' (e.g. X-Auth-Token) or"+ + " 'tokenResponseJsonPath' (e.g. access_token) to say where the token"+ + " comes back");+ }+ String tokenHeaderName = trimmed(options.get(TOKEN_HEADER_NAME_OPTION));+ if (tokenHeaderName == null) {+ throw new IllegalArgumentException(+ "api config authType 'TOKEN_LOGIN' requires a 'tokenHeaderName' saying which"+ + " header carries the token back, e.g. X-Auth-Token or Authorization");+ }+ if (!ExternalApiHeaders.isValidName(tokenHeaderName)) {+ throw new IllegalArgumentException(+ "api config 'tokenHeaderName' is not a valid HTTP header name: "+ + tokenHeaderName);+ }+ if (responseHeader != null && !ExternalApiHeaders.isValidName(responseHeader)) {+ throw new IllegalArgumentException(+ "api config 'tokenResponseHeader' is not a valid HTTP header name: "+ + responseHeader);+ }++ return new ApiTokenLogin(+ loginPath,+ nestedObject(options.get(LOGIN_BODY_OPTION), LOGIN_BODY_OPTION),+ loginHeaders(options.get(LOGIN_HEADERS_OPTION)),+ responseHeader,+ responseJsonPath,+ tokenHeaderName,+ trimmed(options.get(TOKEN_PREFIX_OPTION)) == null+ ? ""+ : trimmed(options.get(TOKEN_PREFIX_OPTION)) + " ",+ ttl(options.get(TOKEN_TTL_SECONDS_OPTION)));+ }++ /** Pull the token out of a login response. */+ String extractToken(ExternalApiCaller.Response response, ObjectMapper objectMapper) {+ if (tokenResponseHeader != null) {+ String value = response.header(tokenResponseHeader);+ if (value == null || value.isBlank()) {+ throw new IllegalStateException(+ "Login succeeded but returned no '"+ + tokenResponseHeader+ + "' response header");+ }+ return value;+ }+ JsonNode node = response.bodyAsJson(objectMapper);+ for (String segment : tokenResponseJsonPath.split("\\.")) {+ if (node == null) {+ break;+ }+ node = node.get(segment);+ }+ if (node == null || !node.isValueNode() || node.asString().isBlank()) {+ throw new IllegalStateException(+ "Login succeeded but its body had no token at '" + tokenResponseJsonPath + "'");+ }+ return node.asString();+ }++ /** The header to send on an authenticated call. */+ Map.Entry<String, String> authHeader(String token) {+ return Map.entry(tokenHeaderName, tokenPrefix + token);+ }++ private static Map<String, Object> nestedObject(Object value, String option) {+ if (value == null) {+ return Map.of();+ }+ if (!(value instanceof Map<?, ?> raw)) {+ throw new IllegalArgumentException("api config '" + option + "' must be an object");+ }+ Map<String, Object> out = new LinkedHashMap<>();+ raw.forEach((key, entry) -> out.put(String.valueOf(key), entry));+ return out;+ }++ private static Map<String, String> loginHeaders(Object value) {+ Map<String, String> out = new LinkedHashMap<>();+ nestedObject(value, LOGIN_HEADERS_OPTION)+ .forEach(+ (name, entry) -> {+ String headerValue = entry == null ? null : entry.toString();+ if (!ExternalApiHeaders.isValidName(name)) {+ throw new IllegalArgumentException(+ "api config 'loginHeaders' has an invalid header name: "+ + name);+ }+ if (headerValue == null+ || !ExternalApiHeaders.isValidValue(headerValue)) {+ throw new IllegalArgumentException(+ "api config 'loginHeaders' has an invalid value for '"+ + name+ + "'");+ }+ out.put(name, headerValue);+ });+ return out;+ }++ private static int ttl(Object value) {+ if (value == null) {+ return DEFAULT_TOKEN_TTL_SECONDS;+ }+ int seconds;+ try {+ seconds = Integer.parseInt(value.toString().trim());+ } catch (NumberFormatException e) {+ throw new IllegalArgumentException("api config 'tokenTtlSeconds' must be a number");+ }+ if (seconds < 1 || seconds > MAX_TOKEN_TTL_SECONDS) {+ throw new IllegalArgumentException(+ "api config 'tokenTtlSeconds' must be between 1 and " + MAX_TOKEN_TTL_SECONDS);+ }+ return seconds;+ }++ private static String trimmed(Object value) {+ if (value == null) {+ return null;+ }+ String text = value.toString().trim();+ return text.isEmpty() ? null : text;+ }++ /** Never prints the login body or headers: both carry the credentials. */+ @Override+ public String toString() {+ return "ApiTokenLogin[loginPath="+ + loginPath+ + ", tokenTtlSeconds="+ + tokenTtlSeconds+ + "]";+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/DocumentContext.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/DocumentContext.javanew file mode 100644index 0000000000..044d24c0c5--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/DocumentContext.java@@ -0,0 +1,180 @@+package stirling.software.proprietary.integration.api;++import java.io.IOException;+import java.security.MessageDigest;+import java.security.NoSuchAlgorithmException;+import java.time.Instant;+import java.util.Base64;+import java.util.Calendar;+import java.util.HexFormat;+import java.util.List;+import java.util.Locale;++import org.apache.pdfbox.Loader;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDDocumentInformation;+import org.springframework.web.multipart.MultipartFile;++import lombok.extern.slf4j.Slf4j;++import stirling.software.common.service.PdfMetadataService;+import stirling.software.proprietary.integration.purview.PdfSensitivityLabels;+import stirling.software.proprietary.integration.purview.SensitivityLabel;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ObjectNode;++/**+ * Everything Stirling already knows about the document and the run, as one JSON object.+ *+ * <p>An external API almost always wants more than the bytes: what the file is, what it was called,+ * whether it is already classified or labelled, and which policy sent it. All of that is in hand at+ * the moment of the call, so it is offered rather than left for the operator to re-derive - most+ * usefully the Purview label and the classifier's verdict, which turn a call-out into something the+ * receiving system can make a decision with.+ *+ * <p>The shape is also the namespace for placeholders (see {@link Placeholders}), so {@code+ * {{document.sha256}}} or {@code {{sensitivityLabel.name}}} in a field, path, or header resolves+ * against exactly what is documented here:+ *+ * <pre>+ * document.filename | .extension | .contentType | .sizeBytes | .sha256 | .base64+ * .pageCount | .encrypted | .title | .author | .subject | .keywords+ * .creator | .producer | .created | .modified+ * classification.* the classifier policy's verdict, when it has run+ * sensitivityLabel.labelId | .name | .siteId | .method | .protected+ * run.policyName | .runId | .timestamp+ * </pre>+ *+ * <p>Every field is best-effort: a non-PDF, an unparseable PDF, or an ad-hoc run with no policy+ * simply omits what it cannot know. Building the context must never be the reason a step fails.+ */+@Slf4j+final class DocumentContext {++ private DocumentContext() {}++ static ObjectNode build(+ MultipartFile file,+ byte[] content,+ String policyName,+ String runId,+ ObjectMapper objectMapper) {+ ObjectNode root = objectMapper.createObjectNode();+ ObjectNode document = root.putObject("document");++ String filename = file.getOriginalFilename();+ document.put("filename", filename);+ document.put("extension", extensionOf(filename));+ document.put("contentType", file.getContentType());+ document.put("sizeBytes", content.length);+ document.put("sha256", sha256(content));+ // The bytes themselves, for steps that carry the document inside a JSON body+ // (an attachment field, a signing payload) rather than as multipart.+ document.put("base64", Base64.getEncoder().encodeToString(content));++ if (looksLikePdf(content)) {+ addPdfFacts(document, root, content, objectMapper);+ }++ ObjectNode run = root.putObject("run");+ run.put("policyName", policyName);+ run.put("runId", runId);+ run.put("timestamp", Instant.now().toString());+ return root;+ }++ /** PDF-only facts. A document we cannot parse still gets the basics above. */+ private static void addPdfFacts(+ ObjectNode document, ObjectNode root, byte[] content, ObjectMapper objectMapper) {+ try (PDDocument pdf = Loader.loadPDF(content)) {+ document.put("pageCount", pdf.getNumberOfPages());+ document.put("encrypted", pdf.isEncrypted());++ PDDocumentInformation info = pdf.getDocumentInformation();+ document.put("title", info.getTitle());+ document.put("author", info.getAuthor());+ document.put("subject", info.getSubject());+ document.put("keywords", info.getKeywords());+ document.put("creator", info.getCreator());+ document.put("producer", info.getProducer());+ document.put("created", toIso(info.getCreationDate()));+ document.put("modified", toIso(info.getModificationDate()));++ addClassification(root, info, objectMapper);+ addSensitivityLabel(root, pdf);+ } catch (IOException | RuntimeException e) {+ // An encrypted or malformed PDF is a normal thing to send to an external API; the+ // extra facts are a convenience, not a precondition.+ log.debug("Could not read PDF facts for the step context: {}", e.getMessage());+ }+ }++ /** The classifier policy's verdict, so a call-out can act on it without re-classifying. */+ private static void addClassification(+ ObjectNode root, PDDocumentInformation info, ObjectMapper objectMapper) {+ String raw = info.getCustomMetadataValue(PdfMetadataService.CLASSIFICATION_KEY);+ if (raw == null || raw.isBlank()) {+ return;+ }+ try {+ JsonNode parsed = objectMapper.readTree(raw);+ root.set("classification", parsed);+ } catch (RuntimeException e) {+ // Written by another tool; if it is not JSON, pass it through as text rather than drop+ // it - the receiving system may still recognise it.+ root.put("classification", raw);+ }+ }++ /** The Purview label already on the document, if any. */+ private static void addSensitivityLabel(ObjectNode root, PDDocument pdf) {+ List<SensitivityLabel> labels = PdfSensitivityLabels.readAll(pdf);+ if (labels.isEmpty()) {+ return;+ }+ SensitivityLabel label = labels.get(0);+ ObjectNode node = root.putObject("sensitivityLabel");+ node.put("labelId", label.labelId());+ node.put("name", label.name());+ node.put("siteId", label.siteId());+ node.put("method", label.method() == null ? null : label.method().name());+ node.put("protected", label.isProtected());+ }++ /** Cheap check so a non-PDF never pays for a parse attempt. */+ private static boolean looksLikePdf(byte[] content) {+ return content.length > 4+ && content[0] == '%'+ && content[1] == 'P'+ && content[2] == 'D'+ && content[3] == 'F';+ }++ /**+ * A content hash is the field external systems most often key on - dedupe, chain-of-custody,+ * "have I already scanned this" - and they cannot compute it without the bytes we are sending.+ */+ private static String sha256(byte[] content) {+ try {+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(content));+ } catch (NoSuchAlgorithmException e) {+ throw new IllegalStateException("SHA-256 is required by the Java platform", e);+ }+ }++ private static String toIso(Calendar calendar) {+ return calendar == null ? null : calendar.toInstant().toString();+ }++ private static String extensionOf(String filename) {+ if (filename == null) {+ return null;+ }+ int dot = filename.lastIndexOf('.');+ return dot < 0 || dot == filename.length() - 1+ ? null+ : filename.substring(dot + 1).toLowerCase(Locale.ROOT);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiCallController.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiCallController.javanew file mode 100644index 0000000000..499ab90fdb--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiCallController.java@@ -0,0 +1,552 @@+package stirling.software.proprietary.integration.api;++import java.io.IOException;+import java.util.Base64;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Locale;+import java.util.Map;++import org.springframework.core.io.ByteArrayResource;+import org.springframework.core.io.Resource;+import org.springframework.http.HttpHeaders;+import org.springframework.http.MediaType;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.PostMapping;+import org.springframework.web.bind.annotation.RequestHeader;+import org.springframework.web.bind.annotation.RequestMapping;+import org.springframework.web.bind.annotation.RequestParam;+import org.springframework.web.bind.annotation.RestController;+import org.springframework.web.multipart.MultipartFile;++import io.github.pixee.security.Filenames;+import io.swagger.v3.oas.annotations.Operation;+import io.swagger.v3.oas.annotations.tags.Tag;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.AutomationRunContext;+import stirling.software.common.service.InternalApiClient;+import stirling.software.common.util.TempFileManager;+import stirling.software.proprietary.service.AiToolResponseHeaders;++import tools.jackson.core.type.TypeReference;+import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ObjectNode;++/**+ * Posts the document flowing through a policy to a third-party HTTP API and folds the answer back+ * into the run.+ *+ * <p>This is the generic integration step: rather than a bespoke connector per vendor, an operator+ * defines an {@code API} connection (base URL + credentials) once and any policy can call a path+ * under it. The connection owns the host and the credentials; the step owns only the path and the+ * form fields, so a policy author can never aim the call somewhere else or read the secret.+ *+ * <p>Response handling is explicit rather than inferred, because the two useful behaviours destroy+ * different things when guessed wrong:+ *+ * <ul>+ * <li>{@code report} (default) - the document continues untouched and the API's answer rides+ * along in {@link AiToolResponseHeaders#TOOL_REPORT}. For call-outs that inspect or notify. A+ * {@code requireTrue} field turns the answer into a gate: the named JSON verdict must be true+ * or the step fails, so a scanner's "not clean" actually stops the run.+ * <li>{@code replace} - the response body <em>becomes</em> the document. For call-outs that+ * transform. Fails loudly if the API returns JSON or an empty body, instead of silently+ * dropping the document from the pipeline.+ * </ul>+ */+@Slf4j+@RestController+@RequestMapping("/api/v1/integration")+@RequiredArgsConstructor+@Tag(name = "Integrations", description = "Third-party integration steps.")+public class ExternalApiCallController {++ static final String MODE_REPORT = "report";+ static final String MODE_REPLACE = "replace";++ /**+ * The report travels as an HTTP header, and Jetty caps a response header at 8KB by default. A+ * body larger than this is summarised rather than risking a header the container refuses to+ * write - which would fail the whole step over a merely verbose API.+ */+ static final int MAX_REPORT_BODY_CHARS = 4096;++ static final String BODY_MULTIPART = "multipart";+ static final String BODY_JSON = "json";+ static final String BODY_BINARY = "binary";++ /** Field (multipart) and property (json) the auto-populated context is offered under. */+ static final String CONTEXT_FIELD = "stirlingContext";++ private final ApiConnectionResolver connectionResolver;+ private final ExternalApiCaller caller;+ private final ObjectMapper objectMapper;+ private final TempFileManager tempFileManager;+ private final ApplicationProperties applicationProperties;++ @PostMapping(value = "/external-api-call", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)+ @Operation(+ summary = "Send the document to an external API",+ description =+ "Sends the document to a path under a stored API connection's base URL and"+ + " either records the response as a step report or replaces the"+ + " document with it. Fields, path and headers may reference"+ + " {{document.*}}, {{classification.*}}, {{sensitivityLabel.*}} and"+ + " {{run.*}}. Type:SISO")+ public ResponseEntity<Resource> call(+ @RequestParam("fileInput") MultipartFile fileInput,+ @RequestParam("connectionId") String connectionId,+ @RequestParam(value = "path", required = false) String path,+ @RequestParam(value = "method", defaultValue = "POST") String method,+ @RequestParam(value = "bodyMode", defaultValue = BODY_MULTIPART) String bodyMode,+ @RequestParam(value = "fileFieldName", defaultValue = "file") String fileFieldName,+ @RequestParam(value = "responseMode", defaultValue = MODE_REPORT) String responseMode,+ @RequestParam(value = "resultUrlPath", required = false) String resultUrlPath,+ @RequestParam(value = "resultUrlHeader", required = false) String resultUrlHeader,+ @RequestParam(value = "responseSelect", required = false) String responseSelect,+ @RequestParam(value = "requireTrue", required = false) String requireTrue,+ @RequestParam(value = "fields", required = false) String fields,+ @RequestParam(value = "bodyTemplate", required = false) String bodyTemplate,+ @RequestParam(value = "headers", required = false) String headers,+ @RequestParam(value = "includeContext", defaultValue = "false") boolean includeContext,+ @RequestParam(value = "includeFile", defaultValue = "true") boolean includeFile,+ @RequestHeader(value = InternalApiClient.POLICY_NAME_HEADER, required = false)+ String policyName,+ @RequestHeader(value = AutomationRunContext.RUN_ID_HEADER, required = false)+ String runId)+ throws IOException {++ String mode = normalise(responseMode, MODE_REPORT, MODE_REPORT, MODE_REPLACE);+ String body = normalise(bodyMode, BODY_MULTIPART, BODY_MULTIPART, BODY_JSON, BODY_BINARY);+ String verb = parseMethod(method);++ Long id = ApiConnectionResolver.connectionId(connectionId);+ if (id == null) {+ throw new IllegalArgumentException("'connectionId' is required");+ }+ ApiConnectionSettings settings = connectionResolver.resolve(id);++ String filename = safeFileName(fileInput.getOriginalFilename());+ String contentType =+ fileInput.getContentType() == null+ ? MediaType.APPLICATION_OCTET_STREAM_VALUE+ : fileInput.getContentType();+ byte[] content = fileInput.getBytes();++ ObjectNode context =+ DocumentContext.build(fileInput, content, policyName, runId, objectMapper);++ ExternalApiCaller.Response response =+ caller.dispatch(+ settings,+ verb,+ Placeholders.resolve(path, context, Placeholders.Escaping.URL_PATH),+ buildBody(+ body,+ bodyTemplate,+ includeFile,+ includeContext,+ context,+ fileFieldName,+ filename,+ contentType,+ content,+ resolveAll(parseJsonObject(fields, "fields"), context)),+ validatedHeaders(resolveAll(parseJsonObject(headers, "headers"), context)));++ if (!response.isSuccess()) {+ // Fail the step: a policy that silently continued past a rejected call-out would+ // deliver documents the external system believes it never approved.+ throw new IOException(+ "External API returned HTTP " + response.status() + summarise(response));+ }++ enforceVerdict(response, requireTrue);++ return MODE_REPLACE.equals(mode)+ ? replaceDocument(+ settings,+ response,+ filename,+ resultUrlPath,+ resultUrlHeader,+ responseSelect)+ : reportOnly(fileInput, filename, contentType, response);+ }++ /**+ * Assemble the outbound body.+ *+ * <ul>+ * <li>{@code multipart} - the file plus form fields, what most upload APIs expect.+ * <li>{@code json} - a JSON object of the fields, with the context merged in and the file+ * base64'd under {@code content}. For APIs that take a document as JSON, and for+ * notify-style call-outs (with {@code includeFile=false}) that want the facts only.+ * <li>{@code binary} - the raw bytes as the body. For APIs that want the file and nothing+ * else; fields would have nowhere to go, so they are refused rather than dropped.+ * </ul>+ */+ private ExternalApiCaller.Body buildBody(+ String bodyMode,+ String bodyTemplate,+ boolean includeFile,+ boolean includeContext,+ ObjectNode context,+ String fileFieldName,+ String filename,+ String contentType,+ byte[] content,+ Map<String, String> fields)+ throws IOException {++ if (bodyTemplate != null && !bodyTemplate.isBlank()) {+ return templatedBody(bodyTemplate, context, filename, contentType, content);+ }+ switch (bodyMode) {+ case BODY_BINARY -> {+ if (!fields.isEmpty()) {+ throw new IllegalArgumentException(+ "bodyMode 'binary' sends only the document, so 'fields' cannot be"+ + " sent; use 'headers' instead, or bodyMode 'multipart'.");+ }+ if (!includeFile) {+ throw new IllegalArgumentException(+ "bodyMode 'binary' with includeFile=false would send an empty body");+ }+ return ExternalApiCaller.raw(contentType, content);+ }+ case BODY_JSON -> {+ ObjectNode json = objectMapper.createObjectNode();+ fields.forEach(json::put);+ if (includeContext) {+ json.setAll(context);+ }+ if (includeFile) {+ json.put("filename", filename);+ json.put("contentType", contentType);+ json.put("content", Base64.getEncoder().encodeToString(content));+ }+ return ExternalApiCaller.raw(+ MediaType.APPLICATION_JSON_VALUE, objectMapper.writeValueAsBytes(json));+ }+ default -> {+ Map<String, String> all = new LinkedHashMap<>(fields);+ if (includeContext) {+ all.put(CONTEXT_FIELD, objectMapper.writeValueAsString(context));+ }+ if (!includeFile) {+ // Fields-only multipart: a notify-style call-out that wants the facts, not+ // the document.+ MultipartBody body = new MultipartBody();+ body.addFields(all);+ return new ExternalApiCaller.Body(body.contentType(), body.build());+ }+ return ExternalApiCaller.multipart(+ fileFieldName, filename, contentType, content, all);+ }+ }+ }++ /**+ * A caller-shaped JSON body: the template is resolved against the context, so an arbitrary+ * vendor payload can be expressed as config. {@code {{document.base64}}} carries the file+ * itself, which is how APIs that take a document nested inside a JSON document are reached.+ *+ * <p>The base64 is added to a copy of the context rather than the context proper: it is the+ * size of the file, and {@code stirlingContext} must not silently grow by a whole document.+ */+ private ExternalApiCaller.Body templatedBody(+ String bodyTemplate,+ ObjectNode context,+ String filename,+ String contentType,+ byte[] content)+ throws IOException {+ JsonNode template;+ try {+ template = objectMapper.readTree(bodyTemplate);+ } catch (Exception e) {+ throw new IllegalArgumentException("api step 'bodyTemplate' must be valid JSON", e);+ }+ ObjectNode withFile = context.deepCopy();+ ObjectNode document = (ObjectNode) withFile.get("document");+ if (document != null) {+ document.put("base64", Base64.getEncoder().encodeToString(content));+ document.put("safeFilename", filename);+ document.put("resolvedContentType", contentType);+ }+ JsonNode resolved = Placeholders.resolveTree(template, withFile);+ return ExternalApiCaller.raw(+ MediaType.APPLICATION_JSON_VALUE, objectMapper.writeValueAsBytes(resolved));+ }++ /** Resolve every value's placeholders against the context. */+ private Map<String, String> resolveAll(Map<String, String> values, ObjectNode context) {+ Map<String, String> out = new LinkedHashMap<>();+ values.forEach(+ (key, value) ->+ out.put(+ key,+ Placeholders.resolve(value, context, Placeholders.Escaping.NONE)));+ return out;+ }++ /** Per-step headers, held to the same rules as a connection's static headers. */+ private Map<String, String> validatedHeaders(Map<String, String> headers) {+ headers.forEach(+ (name, value) -> {+ if (!ExternalApiHeaders.isValidName(name)) {+ throw new IllegalArgumentException(+ "api step 'headers' has an invalid header name: " + name);+ }+ if (ExternalApiHeaders.isReserved(name)) {+ throw new IllegalArgumentException(+ "api step 'headers' must not set '"+ + name+ + "'; it is set by the connection or the client");+ }+ if (!ExternalApiHeaders.isValidValue(value)) {+ // A resolved placeholder could carry a newline out of document metadata.+ throw new IllegalArgumentException(+ "api step 'headers' has an invalid value for '" + name + "'");+ }+ });+ return headers;+ }++ private static String parseMethod(String method) {+ String verb = method == null ? "POST" : method.trim().toUpperCase(Locale.ROOT);+ // Only the verbs that carry a body; GET/DELETE would silently drop the document.+ if (!List.of("POST", "PUT", "PATCH").contains(verb)) {+ throw new IllegalArgumentException(+ "'method' must be POST, PUT or PATCH; got " + method);+ }+ return verb;+ }++ private static String normalise(String value, String fallback, String... allowed) {+ String out =+ value == null || value.isBlank() ? fallback : value.trim().toLowerCase(Locale.ROOT);+ if (!List.of(allowed).contains(out)) {+ throw new IllegalArgumentException(+ "must be one of " + String.join(", ", allowed) + "; got " + value);+ }+ return out;+ }++ /**+ * Turn the response into the document that continues down the pipeline.+ *+ * <p>Three shapes of answer are accepted, because real APIs use all three: the document inline,+ * a URL to fetch it from, or an archive to pick it out of. Anything else fails the step rather+ * than putting a non-document into the pipeline for a later step to trip over.+ */+ private ResponseEntity<Resource> replaceDocument(+ ApiConnectionSettings settings,+ ExternalApiCaller.Response response,+ String requestFilename,+ String resultUrlPath,+ String resultUrlHeader,+ String responseSelect)+ throws IOException {++ ExternalApiCaller.Response payload = response;+ boolean followed = false;+ String url = resultUrl(response, resultUrlPath, resultUrlHeader);+ if (url != null) {+ // The URL came out of the response, so ResultUrls decides whether it may be fetched.+ payload =+ caller.getResult(+ settings, ResultUrls.validate(settings, url, applicationProperties));+ followed = true;+ if (!payload.isSuccess()) {+ throw new IOException(+ "Fetching the API's result URL returned HTTP " + payload.status());+ }+ }++ if (payload.body().length == 0) {+ throw new IOException(+ "External API returned an empty body, so there is no document to replace with;"+ + " use responseMode=report to keep the original.");+ }+ if (payload.isJson() && !followed) {+ throw new IOException(+ "External API returned JSON, which cannot replace the document. Use"+ + " responseMode=report to keep the original and record the answer, or"+ + " set resultUrlPath if the JSON points at the document.");+ }++ String filename = ResultFiles.nameFor(payload, requestFilename);+ Resource result = ResultFiles.asResource(payload.body(), filename);++ if (ResultFiles.isArchive(result)) {+ if (responseSelect == null || responseSelect.isBlank()) {+ // Handing a .zip to a step that expects a PDF fails later and more obscurely.+ throw new IOException(+ "External API returned an archive; set 'responseSelect' (e.g. *.pdf, or an"+ + " index) to say which entry becomes the document.");+ }+ result = ResultFiles.selectFromArchive(result, responseSelect, tempFileManager);+ filename = result.getFilename();+ } else if (responseSelect != null && !responseSelect.isBlank()) {+ throw new IOException(+ "'responseSelect' was set but the API returned a single file, not an archive");+ }++ MediaType type =+ payload.contentType() == null || ResultFiles.isArchiveName(filename)+ ? MediaType.APPLICATION_OCTET_STREAM+ : MediaType.parseMediaType(payload.contentType().split(";")[0].trim());+ return ResponseEntity.ok()+ .contentType(type)+ .header(+ HttpHeaders.CONTENT_DISPOSITION,+ "attachment; filename=\"" + filename + "\"")+ .body(result);+ }++ /** The result URL the API pointed at, from the body or a header; null when neither is set. */+ private String resultUrl(+ ExternalApiCaller.Response response, String resultUrlPath, String resultUrlHeader) {+ if (resultUrlHeader != null && !resultUrlHeader.isBlank()) {+ String value = response.header(resultUrlHeader.trim());+ if (value == null || value.isBlank()) {+ throw new IllegalArgumentException(+ "'resultUrlHeader' names '"+ + resultUrlHeader+ + "' but the response had no such header");+ }+ return value;+ }+ if (resultUrlPath == null || resultUrlPath.isBlank()) {+ return null;+ }+ JsonNode node = response.bodyAsJson(objectMapper);+ for (String segment : resultUrlPath.trim().split("\\.")) {+ if (node == null) {+ break;+ }+ node = node.get(segment);+ }+ if (node == null || !node.isValueNode() || node.asString().isBlank()) {+ throw new IllegalArgumentException(+ "'resultUrlPath' found no URL at '" + resultUrlPath + "' in the response");+ }+ return node.asString();+ }++ /**+ * Gate the run on a boolean verdict in the API's JSON answer (e.g. Cloudmersive's {@code+ * CleanResult}). When {@code requireTrue} names a field - dotted for a nested one - that field+ * must be JSON {@code true}, or the step fails so the document is parked rather than delivered.+ * Fail-closed: a missing field, a non-boolean, a false, or a non-JSON body all stop the run.+ * This is what makes a scanner's "not clean" actually stop the pipeline.+ */+ private void enforceVerdict(ExternalApiCaller.Response response, String requireTrue)+ throws IOException {+ if (requireTrue == null || requireTrue.isBlank()) {+ return;+ }+ JsonNode node = response.isJson() ? response.bodyAsJson(objectMapper) : null;+ for (String segment : requireTrue.trim().split("\\.")) {+ if (node == null) {+ break;+ }+ node = node.get(segment);+ }+ if (node == null || !node.asBoolean(false)) {+ throw new IOException(+ "External API verdict '"+ + requireTrue.trim()+ + "' was not true"+ + summarise(response)+ + "; the document was not approved, so the run was stopped.");+ }+ }++ /** The document passes through; the API's answer rides in the report header. */+ private ResponseEntity<Resource> reportOnly(+ MultipartFile fileInput,+ String filename,+ String contentType,+ ExternalApiCaller.Response response)+ throws IOException {+ return ResponseEntity.ok()+ .contentType(MediaType.parseMediaType(contentType))+ .header(+ HttpHeaders.CONTENT_DISPOSITION,+ "attachment; filename=\"" + filename + "\"")+ .header(AiToolResponseHeaders.TOOL_REPORT, buildReport(response))+ .body(new ByteArrayResource(fileInput.getBytes()));+ }++ /** A JSON object describing the call, small enough to survive as a header. */+ private String buildReport(ExternalApiCaller.Response response) {+ ObjectNode report = objectMapper.createObjectNode();+ report.put("status", response.status());+ report.put("contentType", response.contentType());+ if (response.isJson()) {+ try {+ JsonNode parsed = objectMapper.readTree(response.bodyAsText());+ String rendered = objectMapper.writeValueAsString(parsed);+ if (rendered.length() <= MAX_REPORT_BODY_CHARS) {+ report.set("body", parsed);+ } else {+ report.put("bodyTruncated", true);+ report.put("body", rendered.substring(0, MAX_REPORT_BODY_CHARS));+ }+ } catch (Exception e) {+ // Content-Type said JSON but the body is not; keep the step alive and say so.+ report.put("bodyParseError", e.getMessage());+ report.put("body", truncate(response.bodyAsText()));+ }+ } else {+ report.put("bodyBytes", response.body().length);+ }+ return objectMapper.writeValueAsString(report);+ }++ /** A JSON object of string values, e.g. {@code {"policy":"strict"}}. */+ private Map<String, String> parseJsonObject(String json, String what) {+ if (json == null || json.isBlank()) {+ return Map.of();+ }+ Map<String, Object> raw;+ try {+ raw =+ objectMapper.readValue(+ json, new TypeReference<LinkedHashMap<String, Object>>() {});+ } catch (Exception e) {+ throw new IllegalArgumentException("api step '" + what + "' must be a JSON object", e);+ }+ Map<String, String> out = new LinkedHashMap<>();+ raw.forEach((key, value) -> out.put(key, value == null ? "" : value.toString()));+ return out;+ }++ private String summarise(ExternalApiCaller.Response response) {+ String text = truncate(response.bodyAsText());+ return text.isBlank() ? "" : ": " + text;+ }++ private static String truncate(String text) {+ if (text == null) {+ return "";+ }+ String oneLine = text.replaceAll("\\s+", " ").trim();+ return oneLine.length() <= MAX_REPORT_BODY_CHARS+ ? oneLine+ : oneLine.substring(0, MAX_REPORT_BODY_CHARS) + "…";+ }++ private static String safeFileName(String originalFilename) {+ String name = Filenames.toSimpleFileName(originalFilename);+ return (name == null || name.isBlank()) ? "document" : name;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiCaller.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiCaller.javanew file mode 100644index 0000000000..67171bb5f5--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiCaller.java@@ -0,0 +1,299 @@+package stirling.software.proprietary.integration.api;++import java.io.IOException;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.nio.charset.StandardCharsets;+import java.time.Duration;+import java.util.Base64;+import java.util.LinkedHashMap;+import java.util.Map;++import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.stereotype.Service;++import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;++/**+ * Performs the outbound call for an {@code API} connection.+ *+ * <p>Follows the established self-hosted outbound pattern (JDK {@link HttpClient}; see {@code+ * AccountLinkClient}): the client is injectable so tests can drive a real local server without+ * reaching the network.+ */+@Slf4j+@Service+public class ExternalApiCaller {++ /**+ * Cap on a response we will read into memory. An external API returning something enormous is a+ * misconfiguration, and without a cap it would be a trivial way to OOM the server.+ */+ static final int MAX_RESPONSE_BYTES = 64 * 1024 * 1024;++ private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);++ private final HttpClient httpClient;+ private final ApplicationProperties applicationProperties;+ private final ApiTokenCache tokenCache;++ @Autowired+ public ExternalApiCaller(+ ApplicationProperties applicationProperties, ObjectMapper objectMapper) {+ this(+ HttpClient.newBuilder()+ .connectTimeout(CONNECT_TIMEOUT)+ // Following a redirect would re-target the request at a host the base URL+ // never authorised, undoing ExternalApiPaths. Let the caller see the 3xx.+ .followRedirects(HttpClient.Redirect.NEVER)+ .build(),+ applicationProperties,+ objectMapper);+ }++ ExternalApiCaller(+ HttpClient httpClient,+ ApplicationProperties applicationProperties,+ ObjectMapper objectMapper) {+ this.httpClient = httpClient;+ this.applicationProperties = applicationProperties;+ this.tokenCache = new ApiTokenCache(httpClient, objectMapper);+ }++ /** What the external API sent back, before the step decides what to do with it. */+ public record Response(+ int status, String contentType, byte[] body, Map<String, String> headers) {++ public Response {+ headers = headers == null ? Map.of() : Map.copyOf(headers);+ }++ /** A response header by name, case-insensitively; null when absent. */+ public String header(String name) {+ for (Map.Entry<String, String> entry : headers.entrySet()) {+ if (entry.getKey().equalsIgnoreCase(name)) {+ return entry.getValue();+ }+ }+ return null;+ }++ JsonNode bodyAsJson(ObjectMapper objectMapper) {+ try {+ return objectMapper.readTree(bodyAsText());+ } catch (RuntimeException e) {+ return null;+ }+ }++ public boolean isSuccess() {+ return status >= 200 && status < 300;+ }++ public boolean isJson() {+ return contentType != null && contentType.toLowerCase().contains("json");+ }++ public String bodyAsText() {+ return new String(body, StandardCharsets.UTF_8);+ }+ }++ /**+ * POST a document to {@code path} under the connection's base URL as multipart/form-data.+ *+ * @throws IOException on transport failure or an oversized response+ */+ public Response postFile(+ ApiConnectionSettings settings,+ String path,+ String fileFieldName,+ String filename,+ String fileContentType,+ byte[] content,+ Map<String, String> fields)+ throws IOException {+ return dispatch(+ settings,+ "POST",+ path,+ multipart(fileFieldName, filename, fileContentType, content, fields),+ Map.of());+ }++ /** A request body plus the Content-Type that describes it. */+ record Body(String contentType, HttpRequest.BodyPublisher publisher) {}++ static Body multipart(+ String fileFieldName,+ String filename,+ String fileContentType,+ byte[] content,+ Map<String, String> fields)+ throws IOException {+ MultipartBody body = new MultipartBody();+ body.addFields(fields);+ body.addFile(fileFieldName, filename, fileContentType, content);+ return new Body(body.contentType(), body.build());+ }++ /** A body of caller-built bytes, e.g. a JSON document or the raw file. */+ static Body raw(String contentType, byte[] content) {+ return new Body(contentType, HttpRequest.BodyPublishers.ofByteArray(content));+ }++ /**+ * Send {@code body} to {@code path} under the connection's base URL.+ *+ * @param method POST, PUT or PATCH - the verbs that carry a body+ * @param extraHeaders per-step headers, already validated by the caller+ */+ public Response dispatch(+ ApiConnectionSettings settings,+ String method,+ String path,+ Body body,+ Map<String, String> extraHeaders)+ throws IOException {++ URI target = ExternalApiPaths.resolve(settings.baseUri(), path);+ // Re-check at dispatch: save-time validation cannot see a DNS record re-pointed at a+ // private address afterwards.+ ApiIntegrationValidator.requirePublicHost(+ settings, applicationProperties, "API connection base URL");++ Response response = attempt(settings, method, target, body, extraHeaders);+ if (response.status() == 401 && settings.authType() == ApiAuthType.TOKEN_LOGIN) {+ // The cached token was rejected - expired early, or revoked. One fresh login and+ // one retry; if that also 401s the credentials are wrong and the step says so.+ log.debug("[external-api] token rejected by {}; re-authenticating", target.getHost());+ tokenCache.invalidate(settings);+ response = attempt(settings, method, target, body, extraHeaders);+ }+ return response;+ }++ private Response attempt(+ ApiConnectionSettings settings,+ String method,+ URI target,+ Body body,+ Map<String, String> extraHeaders)+ throws IOException {+ HttpRequest.Builder request =+ HttpRequest.newBuilder(target)+ .timeout(Duration.ofSeconds(settings.timeoutSeconds()))+ .header("Content-Type", body.contentType())+ .method(method, body.publisher());+ applyHeaders(request, settings);+ // Step headers last so a step can override a connection default, but never the auth+ // header: ExternalApiHeaders rejects reserved names before we get here.+ extraHeaders.forEach(request::header);+ return send(httpClient, request.build(), target);+ }++ /**+ * GET an absolute result URL the API pointed us at.+ *+ * <p>Takes a {@link URI} rather than a string so it cannot be called with something unchecked:+ * the only way to obtain one is {@link ResultUrls#validate}, which is where the host allowlist+ * lives. Credentials are deliberately not sent - the URL is usually a presigned link on another+ * host, and forwarding the connection's token there would leak it to a third party.+ */+ public Response getResult(ApiConnectionSettings settings, URI target) throws IOException {+ HttpRequest request =+ HttpRequest.newBuilder(target)+ .timeout(Duration.ofSeconds(settings.timeoutSeconds()))+ .GET()+ .build();+ return send(httpClient, request, target);+ }++ /** GET {@code path} under the connection's base URL. */+ public Response get(ApiConnectionSettings settings, String path) throws IOException {+ URI target = ExternalApiPaths.resolve(settings.baseUri(), path);+ ApiIntegrationValidator.requirePublicHost(+ settings, applicationProperties, "API connection base URL");++ HttpRequest.Builder request =+ HttpRequest.newBuilder(target)+ .timeout(Duration.ofSeconds(settings.timeoutSeconds()))+ .GET();+ applyHeaders(request, settings);+ return send(httpClient, request.build(), target);+ }++ static Response send(HttpClient httpClient, HttpRequest request, URI target)+ throws IOException {+ HttpResponse<byte[]> response;+ try {+ response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new IOException("Interrupted calling " + safeTarget(target), e);+ } catch (IOException e) {+ // The message can carry the host but never the credentials, which live in headers.+ throw new IOException(+ "Failed to call " + safeTarget(target) + ": " + e.getMessage(), e);+ }+ byte[] body = response.body() == null ? new byte[0] : response.body();+ if (body.length > MAX_RESPONSE_BYTES) {+ throw new IOException(+ "Response from "+ + safeTarget(target)+ + " exceeds the "+ + MAX_RESPONSE_BYTES+ + " byte limit");+ }+ String contentType = response.headers().firstValue("content-type").orElse(null);+ Map<String, String> headers = new LinkedHashMap<>();+ response.headers()+ .map()+ .forEach((name, values) -> headers.put(name, String.join(", ", values)));+ log.debug("[external-api] {} -> HTTP {}", safeTarget(target), response.statusCode());+ return new Response(response.statusCode(), contentType, body, headers);+ }++ private void applyHeaders(HttpRequest.Builder request, ApiConnectionSettings settings)+ throws IOException {+ settings.headers().forEach(request::header);+ switch (settings.authType()) {+ case BEARER -> request.header("Authorization", "Bearer " + settings.token());+ case HEADER ->+ request.header(+ settings.headerName(),+ settings.headerPrefix() == null+ ? settings.token()+ : settings.headerPrefix() + " " + settings.token());+ case BASIC ->+ request.header(+ "Authorization",+ "Basic "+ + Base64.getEncoder()+ .encodeToString(+ (settings.username()+ + ":"+ + settings.password())+ .getBytes(StandardCharsets.UTF_8)));+ case TOKEN_LOGIN -> {+ Map.Entry<String, String> auth = tokenCache.authHeader(settings);+ request.header(auth.getKey(), auth.getValue());+ }+ case NONE -> {+ /* no credentials */+ }+ }+ }++ /** Scheme, host and path only: a query string could carry a token an operator put there. */+ private static String safeTarget(URI target) {+ return target.getScheme() + "://" + target.getAuthority() + target.getPath();+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiHeaders.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiHeaders.javanew file mode 100644index 0000000000..055101e381--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiHeaders.java@@ -0,0 +1,72 @@+package stirling.software.proprietary.integration.api;++import java.util.Locale;+import java.util.Set;++/**+ * Validation for operator-supplied HTTP header names and values.+ *+ * <p>Header values reach the wire verbatim, so a value carrying CR/LF could splice extra headers -+ * or a whole second request - into the stream. Names and values are therefore checked against the+ * RFC 7230 grammar rather than trusted.+ */+public final class ExternalApiHeaders {++ /**+ * Headers a connection may not set as a static header. Authentication has exactly one path+ * ({@code authType} + {@code token}) so credentials cannot be smuggled in as a "static" header+ * that bypasses the auth validation; the rest are framing headers owned by the HTTP client,+ * where a caller-set value would contradict the body actually sent.+ */+ private static final Set<String> RESERVED =+ Set.of(+ "authorization",+ "proxy-authorization",+ "host",+ "content-length",+ "transfer-encoding",+ "connection",+ "upgrade",+ "expect");++ private ExternalApiHeaders() {}++ /** RFC 7230 {@code token}: the only characters legal in a header name. */+ public static boolean isValidName(String name) {+ if (name == null || name.isEmpty()) {+ return false;+ }+ for (int i = 0; i < name.length(); i++) {+ if (!isTokenChar(name.charAt(i))) {+ return false;+ }+ }+ return true;+ }++ /** Visible ASCII, space and horizontal tab. Excludes CR/LF and NUL, which would inject. */+ public static boolean isValidValue(String value) {+ if (value == null) {+ return false;+ }+ for (int i = 0; i < value.length(); i++) {+ char c = value.charAt(i);+ boolean printable = c >= 0x20 && c <= 0x7E;+ if (!printable && c != '\t') {+ return false;+ }+ }+ return true;+ }++ public static boolean isReserved(String name) {+ return name != null && RESERVED.contains(name.toLowerCase(Locale.ROOT));+ }++ private static boolean isTokenChar(char c) {+ return (c >= 'a' && c <= 'z')+ || (c >= 'A' && c <= 'Z')+ || (c >= '0' && c <= '9')+ || "!#$%&'*+-.^_`|~".indexOf(c) >= 0;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiPaths.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiPaths.javanew file mode 100644index 0000000000..36ca00816c--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ExternalApiPaths.java@@ -0,0 +1,120 @@+package stirling.software.proprietary.integration.api;++import java.net.URI;+import java.net.URISyntaxException;+import java.util.Locale;++/**+ * Resolves a step-supplied relative path under a connection's operator-set base URL.+ *+ * <p>This is the control that keeps the external-API step from being an SSRF primitive. The base+ * URL comes from an {@code IntegrationConfig} only someone with manage rights can edit; the path+ * comes from a pipeline step, which is a far weaker trust boundary. Everything here exists to+ * guarantee that a path can address a resource <em>under</em> the base and nothing else.+ *+ * <p>{@link URI#resolve} is deliberately not used: resolving the protocol-relative {@code+ * //evil.example} against {@code https://api.example.com/v1} yields {@code https://evil.example},+ * silently changing host. Instead the path is screened, appended textually, normalised, and then+ * the result is re-checked against the base - so a miss in the screen is still caught by the check.+ */+public final class ExternalApiPaths {++ private ExternalApiPaths() {}++ /**+ * @param base the connection's base URL, already validated as http(s) with a host+ * @param path a relative path, optionally with a query string; blank means the base itself+ * @throws IllegalArgumentException if the path is absolute, escapes the base, or carries+ * characters that could split the request line+ */+ public static URI resolve(URI base, String path) {+ if (path == null || path.isBlank()) {+ return base;+ }+ String candidate = path.trim();+ screen(candidate);++ if (!candidate.startsWith("/")) {+ candidate = "/" + candidate;+ }++ URI resolved;+ try {+ resolved = new URI(base + candidate).normalize();+ } catch (URISyntaxException e) {+ throw new IllegalArgumentException(+ "api step 'path' is not a valid URL path: " + path, e);+ }+ requireSameOrigin(base, resolved, path);+ requireUnderBasePath(base, resolved, path);+ return resolved;+ }++ /** Reject the shapes that could retarget the request before it is even assembled. */+ private static void screen(String path) {+ if (path.contains("://") || path.startsWith("//")) {+ throw new IllegalArgumentException(+ "api step 'path' must be relative to the connection's base URL, not an"+ + " absolute or protocol-relative URL: "+ + path);+ }+ for (int i = 0; i < path.length(); i++) {+ char c = path.charAt(i);+ // Control characters and spaces can split the request line; a backslash is normalised+ // to '/' by some servers and would sidestep the traversal check below.+ if (c <= 0x20 || c == 0x7F || c == '\\') {+ throw new IllegalArgumentException(+ "api step 'path' contains an illegal character: " + path);+ }+ }+ if (path.indexOf('#') >= 0) {+ throw new IllegalArgumentException(+ "api step 'path' must not contain a fragment: " + path);+ }+ // Percent-encoded dots would survive the normalise() below and be decoded by the target, so+ // a traversal must not be smuggled past us in encoded form.+ //+ // Only dots are rejected. An encoded slash or backslash is legitimate: Placeholders encodes+ // substituted values, so a filename containing '/' arrives here as %2F, where it is data+ // inside one segment rather than structure. Rejecting those would refuse ordinary filenames+ // while doing nothing for traversal, which needs the dots.+ String lower = path.toLowerCase(Locale.ROOT);+ if (lower.contains("%2e")) {+ throw new IllegalArgumentException(+ "api step 'path' must not percent-encode dots: " + path);+ }+ }++ private static void requireSameOrigin(URI base, URI resolved, String original) {+ boolean sameOrigin =+ equalsIgnoreCase(base.getScheme(), resolved.getScheme())+ && equalsIgnoreCase(base.getHost(), resolved.getHost())+ && base.getPort() == resolved.getPort()+ && resolved.getUserInfo() == null;+ if (!sameOrigin) {+ throw new IllegalArgumentException(+ "api step 'path' would change the target host; it must stay under the"+ + " connection's base URL: "+ + original);+ }+ }++ private static void requireUnderBasePath(URI base, URI resolved, String original) {+ String basePath = base.getPath() == null ? "" : base.getPath();+ String resolvedPath = resolved.getPath() == null ? "" : resolved.getPath();+ // The base URL has its trailing slash stripped at parse time, so a base path of "/v1"+ // must match "/v1" exactly or be followed by a separator - never "/v1betray".+ boolean under =+ basePath.isEmpty()+ || resolvedPath.equals(basePath)+ || resolvedPath.startsWith(basePath + "/");+ if (!under) {+ throw new IllegalArgumentException(+ "api step 'path' escapes the connection's base path: " + original);+ }+ }++ private static boolean equalsIgnoreCase(String a, String b) {+ return a == null ? b == null : a.equalsIgnoreCase(b);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/IntegrationStepValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/IntegrationStepValidator.javanew file mode 100644index 0000000000..6118f3b642--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/IntegrationStepValidator.java@@ -0,0 +1,68 @@+package stirling.software.proprietary.integration.api;++import java.util.Map;++import org.springframework.stereotype.Component;++import lombok.RequiredArgsConstructor;++import stirling.software.proprietary.integration.model.IntegrationType;+import stirling.software.proprietary.policy.engine.PipelineStepValidator;+import stirling.software.proprietary.policy.model.PipelineStep;++/**+ * Authorization-checks the {@code connectionId} of any integration step, on the request thread.+ *+ * <p>This is what stops an integration step being a confused deputy. A step names a connection by+ * id, and the worker thread that runs it has no principal - so {@link ApiConnectionResolver} lets+ * the lookup through unchecked there, exactly as the S3 resolver does. Without this validator a+ * caller could put any id in a step and have the server dial that tenant's endpoint with that+ * tenant's stored credentials. Resolving here, while the caller is still on the thread, forces the+ * ownership check to run.+ *+ * <p>Registered as a {@link PipelineStepValidator} so both entry points cover it: save-time+ * validation of a stored policy, and {@code PolicyController}'s ad-hoc gate.+ */+@Component+@RequiredArgsConstructor+public class IntegrationStepValidator implements PipelineStepValidator {++ static final String CONNECTION_ID_PARAM = "connectionId";+ private static final String INTEGRATION_PREFIX = "/api/v1/integration/";++ /**+ * Which connection type each integration step dereferences. A step under {@link+ * #INTEGRATION_PREFIX} that is absent here is rejected rather than waved through, so a new+ * endpoint cannot quietly skip this check by forgetting to register.+ */+ private static final Map<String, IntegrationType> STEP_CONNECTION_TYPES =+ Map.of(+ "/api/v1/integration/external-api-call", IntegrationType.API,+ "/api/v1/integration/purview-apply-label", IntegrationType.PURVIEW,+ "/api/v1/integration/purview-read-label", IntegrationType.PURVIEW,+ "/api/v1/integration/consigno-submit", IntegrationType.CONSIGNO,+ "/api/v1/integration/consigno-fetch-signed", IntegrationType.CONSIGNO);++ private final ApiConnectionResolver connectionResolver;++ @Override+ public void validate(PipelineStep step) {+ String operation = step.operation();+ if (operation == null || !operation.startsWith(INTEGRATION_PREFIX)) {+ return;+ }+ IntegrationType type = STEP_CONNECTION_TYPES.get(operation);+ if (type == null) {+ throw new IllegalArgumentException("unknown integration step: " + operation);+ }+ Long connectionId =+ ApiConnectionResolver.connectionId(step.parameters().get(CONNECTION_ID_PARAM));+ if (connectionId == null) {+ throw new IllegalArgumentException(+ operation + " requires a '" + CONNECTION_ID_PARAM + "' parameter");+ }+ // Throws if the connection is missing, the wrong type, disabled, or not usable by the+ // caller. The parsed settings are discarded: this call is the check.+ connectionResolver.resolveConfig(connectionId, type);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/MultipartBody.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/MultipartBody.javanew file mode 100644index 0000000000..a848f8599c--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/MultipartBody.java@@ -0,0 +1,101 @@+package stirling.software.proprietary.integration.api;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.net.http.HttpRequest;+import java.nio.charset.StandardCharsets;+import java.security.SecureRandom;+import java.util.Base64;+import java.util.Map;++/**+ * Builds a {@code multipart/form-data} body for the JDK HTTP client, which has no multipart+ * publisher of its own.+ *+ * <p>The body is assembled in memory. Callers bound the document size before getting here; the+ * external-API step is for API-shaped payloads, not bulk transfer.+ */+final class MultipartBody {++ private final String boundary;+ private final ByteArrayOutputStream out = new ByteArrayOutputStream();++ MultipartBody() {+ byte[] random = new byte[16];+ new SecureRandom().nextBytes(random);+ this.boundary =+ "StirlingBoundary" + Base64.getUrlEncoder().withoutPadding().encodeToString(random);+ }++ String contentType() {+ return "multipart/form-data; boundary=" + boundary;+ }++ /**+ * @throws IllegalArgumentException if the <em>name</em> could break out of its part header;+ * names come from step parameters, so they are checked rather than trusted+ */+ MultipartBody addField(String name, String value) throws IOException {+ requireSafe(name, "field name");+ writeAscii("--" + boundary + "\r\n");+ writeAscii("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");+ // The value is body, not header: quotes, newlines and backslashes are ordinary data here+ // and must survive untouched. Checking it like a header rejected every JSON value - which+ // is most of them, the auto-populated context included.+ out.write(value.getBytes(StandardCharsets.UTF_8));+ writeAscii("\r\n");+ return this;+ }++ MultipartBody addFile(String name, String filename, String contentType, byte[] content)+ throws IOException {+ requireSafe(name, "file field name");+ requireSafe(filename, "filename");+ writeAscii("--" + boundary + "\r\n");+ writeAscii(+ "Content-Disposition: form-data; name=\""+ + name+ + "\"; filename=\""+ + filename+ + "\"\r\n");+ writeAscii("Content-Type: " + contentType + "\r\n\r\n");+ out.write(content);+ writeAscii("\r\n");+ return this;+ }++ HttpRequest.BodyPublisher build() throws IOException {+ writeAscii("--" + boundary + "--\r\n");+ return HttpRequest.BodyPublishers.ofByteArray(out.toByteArray());+ }++ MultipartBody addFields(Map<String, String> fields) throws IOException {+ for (Map.Entry<String, String> entry : fields.entrySet()) {+ addField(entry.getKey(), entry.getValue());+ }+ return this;+ }++ /**+ * A quote, CR, LF or backslash in a <em>part header</em> - a field name or filename - would let+ * it close the quoted string and forge headers of its own. Values are not checked: they are+ * body, and the boundary that delimits them is 16 random bytes minted per request, so a value+ * cannot end its own part.+ */+ private static void requireSafe(String value, String what) {+ if (value == null) {+ throw new IllegalArgumentException("api step " + what + " must not be null");+ }+ if (value.indexOf('"') >= 0+ || value.indexOf('\r') >= 0+ || value.indexOf('\n') >= 0+ || value.indexOf('\\') >= 0) {+ throw new IllegalArgumentException(+ "api step " + what + " contains an illegal character: " + value);+ }+ }++ private void writeAscii(String text) throws IOException {+ out.write(text.getBytes(StandardCharsets.UTF_8));+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/Placeholders.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/Placeholders.javanew file mode 100644index 0000000000..7a8a3fade3--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/Placeholders.java@@ -0,0 +1,153 @@+package stirling.software.proprietary.integration.api;++import java.util.regex.Matcher;+import java.util.regex.Pattern;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.node.ArrayNode;+import tools.jackson.databind.node.ObjectNode;+import tools.jackson.databind.node.StringNode;++/**+ * Substitutes {@code {{dotted.path}}} references against the {@link DocumentContext}.+ *+ * <p>This is what lets one step satisfy APIs that disagree about payload shape. Rather than a+ * connector per vendor, an operator writes the field names the vendor expects and fills them from+ * context - {@code {"sha256": "{{document.sha256}}", "class": "{{sensitivityLabel.name}}"}}.+ *+ * <p>Deliberately not a template language: dotted lookup and nothing else. No expressions, no+ * control flow, no method calls - a step definition is lower-trust than server config, and the+ * whole point of a template engine (evaluating what it is given) is the thing to avoid here.+ */+final class Placeholders {++ private static final Pattern PLACEHOLDER = Pattern.compile("\\{\\{\\s*([\\w.]+)\\s*}}");++ /** How a resolved value is escaped for the position it lands in. */+ enum Escaping {+ /** Verbatim: form fields and header values, which are validated separately. */+ NONE,+ /** Percent-encoded: a path segment, where a stray slash would change the target. */+ URL_PATH+ }++ private Placeholders() {}++ /**+ * @param template text that may contain {@code {{...}}} references; null passes through+ * @param context the object to resolve against+ * @throws IllegalArgumentException if a reference names something the context does not hold, so+ * a typo surfaces as an error instead of silently sending an empty value+ */+ static String resolve(String template, JsonNode context, Escaping escaping) {+ if (template == null || template.isEmpty()) {+ return template;+ }+ Matcher matcher = PLACEHOLDER.matcher(template);+ StringBuilder out = new StringBuilder();+ while (matcher.find()) {+ String path = matcher.group(1);+ JsonNode value = lookup(context, path);+ if (value == null || value.isMissingNode()) {+ throw new IllegalArgumentException(+ "unknown placeholder '{{"+ + path+ + "}}'; available: document.*, classification.*,"+ + " sensitivityLabel.*, run.*");+ }+ matcher.appendReplacement(out, Matcher.quoteReplacement(render(value, escaping)));+ }+ matcher.appendTail(out);+ return out.toString();+ }++ /**+ * Resolve every string in a JSON tree, in place, leaving structure and non-strings alone.+ *+ * <p>This is what lets one step post an arbitrary vendor-shaped body - a nested {@code+ * documents[0].data} as readily as a flat field - without a connector per vendor.+ */+ static JsonNode resolveTree(JsonNode node, JsonNode context) {+ if (node instanceof ObjectNode object) {+ for (String name : new java.util.ArrayList<>(object.propertyNames())) {+ object.set(name, resolveTree(object.get(name), context));+ }+ return object;+ }+ if (node instanceof ArrayNode array) {+ for (int i = 0; i < array.size(); i++) {+ array.set(i, resolveTree(array.get(i), context));+ }+ return array;+ }+ if (node != null && node.isString()) {+ return StringNode.valueOf(resolve(node.asString(), context, Escaping.NONE));+ }+ return node;+ }++ /** Whether the text references anything at all, so callers can skip resolving. */+ static boolean hasPlaceholder(String text) {+ return text != null && PLACEHOLDER.matcher(text).find();+ }++ private static JsonNode lookup(JsonNode context, String path) {+ JsonNode node = context;+ for (String segment : path.split("\\.")) {+ if (node == null || !node.isObject()) {+ return null;+ }+ node = node.get(segment);+ }+ return node;+ }++ /**+ * A null in context renders empty rather than the literal "null": absent metadata is a normal+ * state, and "null" in a vendor's field would be a value, not an absence.+ */+ private static String render(JsonNode value, Escaping escaping) {+ String text;+ if (value.isNull()) {+ text = "";+ } else if (value.isValueNode()) {+ text = value.asString();+ } else {+ // An object or array (e.g. {{classification}}) renders as its JSON.+ text = value.toString();+ }+ return escaping == Escaping.URL_PATH ? urlEncodePathSegment(text) : text;+ }++ /**+ * Encode for a path segment: a filename is the likeliest value to land in a path and may carry+ * a slash, which would otherwise read as structure rather than data.+ *+ * <p>Dots are left alone even though a traversal is made of them. Encoding them would be worse:+ * {@code %2E%2E} survives {@link java.net.URI#normalize()} and gets decoded by the target, so+ * the traversal would arrive intact and unexamined. Left raw, {@code ..} normalises here and is+ * caught by {@code ExternalApiPaths}' under-the-base check - the one place that can actually+ * see it.+ */+ private static String urlEncodePathSegment(String text) {+ StringBuilder out = new StringBuilder(text.length());+ for (byte b : text.getBytes(java.nio.charset.StandardCharsets.UTF_8)) {+ char c = (char) (b & 0xFF);+ // RFC 3986 unreserved.+ boolean unreserved =+ (c >= 'a' && c <= 'z')+ || (c >= 'A' && c <= 'Z')+ || (c >= '0' && c <= '9')+ || c == '-'+ || c == '.'+ || c == '_'+ || c == '~';+ if (unreserved) {+ out.append(c);+ } else {+ out.append('%').append(String.format("%02X", b & 0xFF));+ }+ }+ return out.toString();+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultFiles.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultFiles.javanew file mode 100644index 0000000000..f2ceb7988f--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultFiles.java@@ -0,0 +1,215 @@+package stirling.software.proprietary.integration.api;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;+import java.util.Locale;+import java.util.Map;++import org.springframework.core.io.ByteArrayResource;+import org.springframework.core.io.Resource;++import stirling.software.common.util.TempFileManager;+import stirling.software.common.util.ZipExtractionUtils;++/**+ * Works out which bytes, and under which name, a response should contribute to the pipeline.+ *+ * <p>Three things go wrong if this is left implicit:+ *+ * <ul>+ * <li><b>The name.</b> A step that replaces the document must name it for what came back, not for+ * what went out. Keeping the inbound name means a PDF-to-DOCX call-out yields a DOCX called+ * {@code .pdf}, and the next step's type check either waves it through or rejects it for the+ * wrong reason. The response's own {@code Content-Disposition} or {@code Content-Type} is the+ * only honest source.+ * <li><b>Archives.</b> Plenty of APIs answer with a ZIP even when one file was sent - ConsignO+ * returns "PDF (single) or ZIP (multiple)". Handing a {@code .zip} to a step expecting a PDF+ * is a confusing failure, so a step can select what it wanted out of the archive.+ * <li><b>Nothing useful at all.</b> An empty body or an error page is not a document, and saying+ * so beats letting it flow onward as one.+ * </ul>+ */+final class ResultFiles {++ /** Extensions we can name from a content type; anything else keeps the server's filename. */+ private static final Map<String, String> EXTENSION_BY_TYPE =+ Map.ofEntries(+ Map.entry("application/pdf", "pdf"),+ Map.entry("application/zip", "zip"),+ Map.entry("application/json", "json"),+ Map.entry("text/plain", "txt"),+ Map.entry("text/html", "html"),+ Map.entry("image/png", "png"),+ Map.entry("image/jpeg", "jpg"),+ Map.entry("image/tiff", "tiff"),+ Map.entry("application/msword", "doc"),+ Map.entry(+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "docx"),+ Map.entry("application/vnd.ms-excel", "xls"),+ Map.entry(+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ "xlsx"));++ private ResultFiles() {}++ /**+ * The filename to give the returned bytes.+ *+ * <p>Prefers what the server said ({@code Content-Disposition}), then the base name of the+ * request with an extension derived from {@code Content-Type}, and only then the original name+ * unchanged.+ */+ static String nameFor(ExternalApiCaller.Response response, String requestFilename) {+ String disposition = response.header("content-disposition");+ String fromServer = filenameFromDisposition(disposition);+ if (fromServer != null) {+ return fromServer;+ }+ String extension = extensionFor(response.contentType());+ if (extension == null) {+ return requestFilename;+ }+ return baseName(requestFilename) + "." + extension;+ }++ /**+ * Pick the file a step asked for out of an archive.+ *+ * @param select a glob such as {@code *.pdf}, or a 0-based index such as {@code 1}+ * @throws IOException if nothing in the archive matches, naming what was there - a silent pick+ * of the wrong file would be worse than a failed step+ */+ static Resource selectFromArchive(+ Resource archive, String select, TempFileManager tempFileManager) throws IOException {+ List<Resource> entries = ZipExtractionUtils.extractZip(archive, tempFileManager);+ if (entries.isEmpty()) {+ throw new IOException("The API returned an empty archive");+ }+ Integer index = asIndex(select);+ if (index != null) {+ if (index < 0 || index >= entries.size()) {+ throw new IOException(+ "'responseSelect' asked for entry "+ + index+ + " but the archive has "+ + entries.size()+ + ": "+ + names(entries));+ }+ return entries.get(index);+ }+ List<Resource> matches = new ArrayList<>();+ for (Resource entry : entries) {+ if (matchesGlob(entry.getFilename(), select)) {+ matches.add(entry);+ }+ }+ if (matches.isEmpty()) {+ throw new IOException(+ "'responseSelect' matched nothing in the archive; it holds " + names(entries));+ }+ if (matches.size() > 1) {+ // Taking the first would be a coin toss the operator did not ask for.+ throw new IOException(+ "'responseSelect' matched "+ + matches.size()+ + " entries ("+ + names(matches)+ + "); narrow it, or use an index");+ }+ return matches.get(0);+ }++ /** Whether the chosen name is itself an archive, so its content type is not the entry's. */+ static boolean isArchiveName(String filename) {+ return filename != null && filename.toLowerCase(Locale.ROOT).endsWith(".zip");+ }++ static boolean isArchive(Resource resource) throws IOException {+ return ZipExtractionUtils.isZip(resource);+ }++ static Resource asResource(byte[] content, String filename) {+ return new ByteArrayResource(content) {+ @Override+ public String getFilename() {+ return filename;+ }+ };+ }++ /** Only {@code *} is supported, and only against the entry's own name. */+ private static boolean matchesGlob(String filename, String glob) {+ if (filename == null) {+ return false;+ }+ String name = filename.toLowerCase(Locale.ROOT);+ String pattern = glob.trim().toLowerCase(Locale.ROOT);+ String regex =+ java.util.Arrays.stream(pattern.split("\\*", -1))+ .map(java.util.regex.Pattern::quote)+ .reduce((a, b) -> a + ".*" + b)+ .orElse("");+ return name.matches(regex);+ }++ private static Integer asIndex(String select) {+ try {+ return Integer.valueOf(select.trim());+ } catch (NumberFormatException e) {+ return null;+ }+ }++ private static String names(List<Resource> entries) {+ return entries.stream().map(Resource::getFilename).toList().toString();+ }++ /** {@code attachment; filename="signed.pdf"} or its RFC 5987 {@code filename*} form. */+ private static String filenameFromDisposition(String disposition) {+ if (disposition == null) {+ return null;+ }+ for (String part : disposition.split(";")) {+ String token = part.trim();+ String value = null;+ if (token.regionMatches(true, 0, "filename=", 0, 9)) {+ value = token.substring(9).trim();+ } else if (token.regionMatches(true, 0, "filename*=", 0, 10)) {+ value = token.substring(10).trim();+ int tick = value.lastIndexOf('\'');+ if (tick >= 0) {+ value = value.substring(tick + 1);+ }+ }+ if (value == null) {+ continue;+ }+ if (value.length() >= 2 && value.startsWith("\"") && value.endsWith("\"")) {+ value = value.substring(1, value.length() - 1);+ }+ // The name comes from the remote server, so it is treated as data: strip any path it+ // tries to bring with it rather than letting it steer where anything is written.+ String simple = io.github.pixee.security.Filenames.toSimpleFileName(value);+ if (simple != null && !simple.isBlank()) {+ return simple;+ }+ }+ return null;+ }++ private static String extensionFor(String contentType) {+ if (contentType == null) {+ return null;+ }+ String type = contentType.split(";")[0].trim().toLowerCase(Locale.ROOT);+ return EXTENSION_BY_TYPE.get(type);+ }++ private static String baseName(String filename) {+ int dot = filename.lastIndexOf('.');+ return dot <= 0 ? filename : filename.substring(0, dot);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultUrls.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultUrls.javanew file mode 100644index 0000000000..53d382f3ef--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/api/ResultUrls.java@@ -0,0 +1,108 @@+package stirling.software.proprietary.integration.api;++import java.net.URI;+import java.net.URISyntaxException;+import java.util.Locale;+import java.util.Set;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.cluster.s3.S3Clients;++/**+ * Validates a result URL an external API asked us to fetch.+ *+ * <p>This is the most dangerous input in the whole feature and deserves saying plainly: unlike a+ * step's {@code path}, which an operator wrote, this URL is <em>chosen by the remote service at run+ * time</em>. Fetching whatever it names would hand any integration - or anything that has+ * compromised, spoofed, or MITM'd one - a server-side GET of its choosing, i.e. the cloud metadata+ * service. {@link ExternalApiPaths} cannot help here: the whole point of a result URL is that it+ * usually lives on a different host (a CDN or presigned object store), so "must be under the base+ * URL" would reject the normal case.+ *+ * <p>The rule is therefore an <em>operator-declared</em> allowlist: a result may come from the+ * connection's own host, or from a host named in the connection's {@code resultUrlHosts}. The+ * decision of which hosts are legitimate stays with whoever configured the connection, and never+ * with the response.+ */+final class ResultUrls {++ private ResultUrls() {}++ /**+ * @param url exactly as the API returned it+ * @return the URL to fetch+ * @throws IllegalArgumentException if the response named a host the operator did not authorise+ */+ static URI validate(+ ApiConnectionSettings settings,+ String url,+ ApplicationProperties applicationProperties) {+ URI uri;+ try {+ uri = new URI(url.trim());+ } catch (URISyntaxException e) {+ throw new IllegalArgumentException(+ "The API returned a result URL that is not a valid URL: " + url, e);+ }+ String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);+ if (!"http".equals(scheme) && !"https".equals(scheme)) {+ // file:, gopher:, jar: and friends are how a URL fetch becomes a local file read.+ throw new IllegalArgumentException(+ "The API returned a result URL that is not http(s): " + url);+ }+ String host = uri.getHost();+ if (host == null || host.isBlank()) {+ throw new IllegalArgumentException(+ "The API returned a result URL with no host: " + url);+ }+ if (uri.getUserInfo() != null) {+ // Credentials in a URL are also the classic way to make a host look like another one.+ throw new IllegalArgumentException(+ "The API returned a result URL carrying credentials, which is not accepted");+ }++ if (!isAllowedHost(settings, host)) {+ throw new IllegalArgumentException(+ "The API returned a result URL on '"+ + host+ + "', which this connection does not allow. Add it to the connection's"+ + " 'resultUrlHosts' if results are meant to come from there.");+ }+ // Even an allowlisted name must not resolve somewhere internal: a hostile or compromised+ // DNS record for cdn.vendor.example pointing at 169.254.169.254 would otherwise be obeyed.+ try {+ S3Clients.validateEndpointHost(+ uri,+ applicationProperties.getPolicies().isAllowPrivateApiEndpoints(),+ "API result URL",+ "set policies.allowPrivateApiEndpoints=true to opt in (e.g. for an on-prem"+ + " integration).");+ } catch (IllegalStateException e) {+ throw new IllegalArgumentException(e.getMessage(), e);+ }+ return uri;+ }++ /**+ * The connection's own host is implicitly allowed; anything else must be declared.+ *+ * <p>Package-private so the matching rule can be tested without a DNS lookup: {@link #validate}+ * additionally resolves the host, which fails closed and so cannot run against example hosts.+ */+ static boolean isAllowedHost(ApiConnectionSettings settings, String host) {+ String candidate = host.toLowerCase(Locale.ROOT);+ if (candidate.equalsIgnoreCase(settings.baseUri().getHost())) {+ return true;+ }+ Set<String> allowed = settings.resultUrlHosts();+ for (String entry : allowed) {+ String allowedHost = entry.toLowerCase(Locale.ROOT);+ // An exact host, or a subdomain of it. Not a bare suffix match: "evilvendor.com"+ // must not be admitted by an entry of "vendor.com".+ if (candidate.equals(allowedHost) || candidate.endsWith("." + allowedHost)) {+ return true;+ }+ }+ return false;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/controller/IntegrationConfigController.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/controller/IntegrationConfigController.javaindex 4e79fc5e7a..2c92883aee 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/controller/IntegrationConfigController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/controller/IntegrationConfigController.java@@ -52,6 +52,25 @@ public class IntegrationConfigController {return ResponseEntity.ok(service.toResponse(service.create(request, user), user));}+ /**+ * What this caller may set up, so the UI offers the vendor presets and the free-form "custom+ * API" option only to those who can actually use them. The answer is computed here rather than+ * inferred client-side: hiding a button is presentation, and the service still refuses the call+ * regardless of what the client believed.+ */+ @GetMapping("/capabilities")+ public ResponseEntity<IntegrationCapabilitiesResponse> capabilities(+ @AuthenticationPrincipal User user) {+ requireUser(user);+ return ResponseEntity.ok(+ new IntegrationCapabilitiesResponse(service.canAuthorCustomApi(user)));+ }++ /**+ * @param customApi whether the caller may author a free-form API integration+ */+ public record IntegrationCapabilitiesResponse(boolean customApi) {}+@GetMapping("/{id}")public ResponseEntity<IntegrationConfigResponse> get(@PathVariable Long id, @AuthenticationPrincipal User user) {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/model/IntegrationType.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/model/IntegrationType.javaindex 1e5bc0c7d4..375b7f4604 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/model/IntegrationType.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/model/IntegrationType.java@@ -4,5 +4,10 @@ package stirling.software.proprietary.integration.model;public enum IntegrationType {S3,MCP,- API+ /** A generic outbound HTTP endpoint a pipeline step can post a document to. */+ API,+ /** Microsoft Purview Information Protection: sensitivity-label taxonomy via Graph. */+ PURVIEW,+ /** ConsignO Cloud (Notarius) e-signature and notarization. */+ CONSIGNO}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PdfSensitivityLabels.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PdfSensitivityLabels.javanew file mode 100644index 0000000000..28ed8de8f3--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PdfSensitivityLabels.java@@ -0,0 +1,323 @@+package stirling.software.proprietary.integration.purview;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.function.Predicate;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDDocumentCatalog;+import org.apache.pdfbox.pdmodel.PDDocumentInformation;+import org.apache.pdfbox.pdmodel.common.PDMetadata;++import lombok.extern.slf4j.Slf4j;++/**+ * Reads and writes Microsoft Purview sensitivity labels on a PDF.+ *+ * <p>Microsoft documents <em>what</em> a label is - the {@code MSIP_Label_<GUID>_<Attribute>}+ * key/value set - but not <em>where</em> it lives inside a PDF; that detail sits inside the MIP+ * SDK, which is C++/.NET only and has no Java binding. This class therefore treats the two places a+ * PDF can hold such pairs as equally valid:+ *+ * <ul>+ * <li>the Document Information dictionary, whose custom entries are literally a key/value map;+ * <li>the XMP packet, where the same keys appear as properties.+ * </ul>+ *+ * <p>Reading is deliberately tolerant - it scans both and takes whichever yields a label - so a+ * document labelled by Acrobat, the MIP client, or another vendor is still understood. Writing+ * populates both, because a downstream reader may only look at one.+ *+ * <p>Scope: this applies the label <em>metadata</em>. It does not encrypt, and cannot: protection+ * is enforced by the Azure Rights Management service through the MIP SDK. A label whose policy+ * demands encryption will be marked here but not protected, which {@link #apply} refuses to do+ * silently.+ */+@Slf4j+public final class PdfSensitivityLabels {++ /** Captures the GUID and the attribute name out of {@code MSIP_Label_<guid>_<attr>}. */+ private static final Pattern LABEL_KEY =+ Pattern.compile("^MSIP_Label_([0-9a-fA-F-]{36})_(\\w+)$");++ /** Finds the same keys inside a raw XMP packet, whatever schema wraps them. */+ private static final Pattern XMP_LABEL_ENTRY =+ Pattern.compile(+ "<([\\w-]+:)?(MSIP_Label_[0-9a-fA-F-]{36}_\\w+)>([^<]*)</\\1?\\2>",+ Pattern.CASE_INSENSITIVE);++ /**+ * Adobe's extension schema for carrying arbitrary Document Info entries in XMP. Using it keeps+ * the XMP copy standards-shaped instead of inventing a namespace.+ */+ private static final String PDFX_NAMESPACE = "http://ns.adobe.com/pdfx/1.3/";++ private static final int MAX_XMP_BYTES = 8 * 1024 * 1024;++ private PdfSensitivityLabels() {}++ /**+ * The label on this document, if any.+ *+ * <p>A document carries at most one label per organisation, but may carry labels from several.+ * When more than one is present the first found is returned - callers that care about a+ * specific tenant should compare {@link SensitivityLabel#siteId()}.+ */+ public static Optional<SensitivityLabel> read(PDDocument document) {+ List<SensitivityLabel> all = readAll(document);+ return all.isEmpty() ? Optional.empty() : Optional.of(all.get(0));+ }++ /** Every label on the document, across both metadata surfaces, de-duplicated by GUID. */+ public static List<SensitivityLabel> readAll(PDDocument document) {+ Map<String, Map<String, String>> byLabelId = new LinkedHashMap<>();+ collect(infoPairs(document), byLabelId);+ collect(xmpPairs(document), byLabelId);++ List<SensitivityLabel> labels = new ArrayList<>();+ byLabelId.forEach(+ (labelId, attributes) -> {+ SensitivityLabel label = SensitivityLabel.fromAttributes(labelId, attributes);+ if (label != null) {+ labels.add(label);+ }+ });+ return labels;+ }++ /**+ * Apply a label, replacing any the same tenant already set.+ *+ * @throws IllegalArgumentException if the label claims encryption, which this cannot honour+ */+ public static void apply(PDDocument document, SensitivityLabel label) throws IOException {+ if (label.isProtected()) {+ // Writing ContentBits=ENCRYPT onto an unencrypted file would tell every downstream+ // reader the content is protected when it is plaintext. Refuse rather than lie.+ throw new IllegalArgumentException(+ "This label requires encryption, which needs the Microsoft Purview client or"+ + " MIP SDK; Stirling can apply the label metadata but cannot protect"+ + " the content.");+ }+ // "An object can only have one label from the same organization." Replace this tenant's+ // labels on both surfaces, but leave other tenants' labels untouched on both.+ Set<String> replaced = labelIdsOfTenant(document, label.siteId());+ replaced.add(label.labelId());+ Map<String, String> pairs = label.toMetadata();+ removeInfoLabels(document, replaced::contains);+ writeInfo(document, pairs);+ writeXmp(document, pairs, replaced::contains);+ }++ /** Strip every label, e.g. before re-labelling or when downgrading a document. */+ public static void clear(PDDocument document) throws IOException {+ removeInfoLabels(document, labelId -> true);+ writeXmp(document, Map.of(), labelId -> true);+ }++ /** The GUIDs of labels this tenant already set, so both surfaces can drop exactly those. */+ private static Set<String> labelIdsOfTenant(PDDocument document, String siteId) {+ Set<String> ids = new LinkedHashSet<>();+ for (SensitivityLabel existing : readAll(document)) {+ if (siteId.equalsIgnoreCase(existing.siteId())) {+ ids.add(existing.labelId());+ }+ }+ return ids;+ }++ /** Drop info-dictionary label entries whose GUID the predicate selects. */+ private static void removeInfoLabels(PDDocument document, Predicate<String> removeLabelId) {+ PDDocumentInformation info = document.getDocumentInformation();+ for (String key : new ArrayList<>(info.getMetadataKeys())) {+ Matcher matcher = LABEL_KEY.matcher(key);+ if (matcher.matches() && removeLabelId.test(matcher.group(1))) {+ info.setCustomMetadataValue(key, null);+ }+ }+ }++ private static void writeInfo(PDDocument document, Map<String, String> pairs) {+ PDDocumentInformation info = document.getDocumentInformation();+ pairs.forEach(info::setCustomMetadataValue);+ }++ /**+ * Rewrite the XMP packet's label properties, leaving the rest of the packet untouched.+ *+ * <p>The packet is edited textually rather than re-serialised through xmpbox: a document's XMP+ * may carry schemas xmpbox does not model, and a round-trip through it would silently drop+ * them.+ */+ private static void writeXmp(+ PDDocument document, Map<String, String> pairs, Predicate<String> removeLabelId)+ throws IOException {+ PDDocumentCatalog catalog = document.getDocumentCatalog();+ String existing = readXmpString(catalog);+ if (existing == null) {+ if (pairs.isEmpty()) {+ return;+ }+ existing = emptyPacket();+ }+ String stripped = stripLabels(existing, removeLabelId);+ String updated = insertLabelProperties(stripped, pairs);+ if (updated == null) {+ log.debug("XMP packet has no rdf:Description to hold the label; info dictionary only");+ return;+ }+ PDMetadata metadata = new PDMetadata(document);+ metadata.importXMPMetadata(updated.getBytes(StandardCharsets.UTF_8));+ catalog.setMetadata(metadata);+ }++ /** Remove only the XMP label entries whose GUID the predicate selects, keeping the rest. */+ private static String stripLabels(String packet, Predicate<String> removeLabelId) {+ Matcher matcher = XMP_LABEL_ENTRY.matcher(packet);+ StringBuilder out = new StringBuilder();+ while (matcher.find()) {+ Matcher key = LABEL_KEY.matcher(matcher.group(2));+ boolean remove = key.matches() && removeLabelId.test(key.group(1));+ matcher.appendReplacement(out, Matcher.quoteReplacement(remove ? "" : matcher.group()));+ }+ matcher.appendTail(out);+ return out.toString();+ }++ /** Splice the properties into the first {@code rdf:Description}; null when there is none. */+ private static String insertLabelProperties(String packet, Map<String, String> pairs) {+ if (pairs.isEmpty()) {+ return packet;+ }+ Matcher description = Pattern.compile("<rdf:Description\\b[^>]*>").matcher(packet);+ if (!description.find()) {+ return null;+ }+ StringBuilder properties = new StringBuilder();+ pairs.forEach(+ (key, value) ->+ properties+ .append("\n <pdfx:")+ .append(key)+ .append('>')+ .append(escapeXml(value))+ .append("</pdfx:")+ .append(key)+ .append('>'));+ String opening = description.group();+ String withNamespace =+ opening.contains("xmlns:pdfx=")+ ? opening+ : opening.substring(0, opening.length() - 1)+ + " xmlns:pdfx=\""+ + PDFX_NAMESPACE+ + "\">";+ return packet.substring(0, description.start())+ + withNamespace+ + properties+ + packet.substring(description.end());+ }++ private static Map<String, String> infoPairs(PDDocument document) {+ Map<String, String> pairs = new LinkedHashMap<>();+ PDDocumentInformation info = document.getDocumentInformation();+ for (String key : info.getMetadataKeys()) {+ String value = info.getCustomMetadataValue(key);+ if (value != null) {+ pairs.put(key, value);+ }+ }+ return pairs;+ }++ private static Map<String, String> xmpPairs(PDDocument document) {+ Map<String, String> pairs = new LinkedHashMap<>();+ String packet;+ try {+ packet = readXmpString(document.getDocumentCatalog());+ } catch (IOException e) {+ log.debug(+ "Unreadable XMP packet; falling back to the info dictionary: {}",+ e.getMessage());+ return pairs;+ }+ if (packet == null) {+ return pairs;+ }+ Matcher matcher = XMP_LABEL_ENTRY.matcher(packet);+ while (matcher.find()) {+ pairs.put(matcher.group(2), unescapeXml(matcher.group(3).trim()));+ }+ return pairs;+ }++ /** Group raw pairs by label GUID, keeping the attribute name as the key. */+ private static void collect(Map<String, String> pairs, Map<String, Map<String, String>> into) {+ pairs.forEach(+ (key, value) -> {+ Matcher matcher = LABEL_KEY.matcher(key);+ if (!matcher.matches()) {+ return;+ }+ into.computeIfAbsent(matcher.group(1), id -> new LinkedHashMap<>())+ // Info-dictionary pairs are collected first and win: a stale XMP copy+ // must not override the value the labelling client wrote.+ .putIfAbsent(matcher.group(2), value);+ });+ }++ private static String readXmpString(PDDocumentCatalog catalog) throws IOException {+ PDMetadata metadata = catalog.getMetadata();+ if (metadata == null) {+ return null;+ }+ try (InputStream is = metadata.exportXMPMetadata()) {+ ByteArrayOutputStream buffer = new ByteArrayOutputStream();+ byte[] chunk = new byte[8192];+ int read;+ int total = 0;+ while ((read = is.read(chunk)) != -1) {+ total += read;+ if (total > MAX_XMP_BYTES) {+ // A hostile document could otherwise hand us an unbounded packet to hold.+ throw new IOException("XMP packet exceeds " + MAX_XMP_BYTES + " bytes");+ }+ buffer.write(chunk, 0, read);+ }+ return buffer.toString(StandardCharsets.UTF_8);+ }+ }++ private static String emptyPacket() {+ return "<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>"+ + "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">"+ + "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">"+ + "<rdf:Description rdf:about=\"\"></rdf:Description>"+ + "</rdf:RDF></x:xmpmeta><?xpacket end=\"w\"?>";+ }++ private static String escapeXml(String value) {+ return value.replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+ .replace("\"", """);+ }++ private static String unescapeXml(String value) {+ return value.replace("<", "<")+ .replace(">", ">")+ .replace(""", "\"")+ .replace("&", "&");+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewConnectionSettings.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewConnectionSettings.javanew file mode 100644index 0000000000..cc40872293--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewConnectionSettings.java@@ -0,0 +1,94 @@+package stirling.software.proprietary.integration.purview;++import java.util.Locale;+import java.util.Map;+import java.util.regex.Pattern;++/**+ * A Microsoft Purview tenant connection.+ *+ * <p>Only {@code tenantId} is required, because labelling a document needs nothing else: a label is+ * a set of key/value pairs and the tenant id is the {@code SiteId} among them. No call to Microsoft+ * is involved, so the step works with no network and no app registration.+ *+ * <p>The app-registration fields are optional and buy exactly one thing: reading the tenant's label+ * taxonomy from Graph, so the UI can offer a list of labels instead of asking someone to paste a+ * GUID. They are not needed to apply or read a label. Graph cannot apply labels for an application+ * anyway - "application permissions are not supported when updating assignedLabels" - which is why+ * labelling here goes through the published metadata contract instead.+ */+public record PurviewConnectionSettings(+ String tenantId,+ String clientId,+ String clientSecret,+ String graphBaseUrl,+ String loginBaseUrl) {++ static final String TENANT_ID_OPTION = "tenantId";+ static final String CLIENT_ID_OPTION = "clientId";+ // Contains a SecretMasker hint, so it masks on read and merges on update.+ static final String CLIENT_SECRET_OPTION = "clientSecret";+ static final String GRAPH_BASE_URL_OPTION = "graphBaseUrl";+ static final String LOGIN_BASE_URL_OPTION = "loginBaseUrl";++ public static final String DEFAULT_GRAPH_BASE_URL = "https://graph.microsoft.com";+ public static final String DEFAULT_LOGIN_BASE_URL = "https://login.microsoftonline.com";++ /** Entra tenant ids are GUIDs; the value ends up in document metadata, so it is checked. */+ private static final Pattern GUID =+ Pattern.compile("^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$");++ public static PurviewConnectionSettings from(Map<String, Object> options) {+ String tenantId = trimmed(options.get(TENANT_ID_OPTION));+ if (tenantId == null) {+ throw new IllegalArgumentException("purview config requires a 'tenantId'");+ }+ if (!GUID.matcher(tenantId).matches()) {+ throw new IllegalArgumentException(+ "purview config 'tenantId' must be a GUID, e.g."+ + " cb46c030-1825-4e81-a295-151c039dbf02");+ }+ String clientId = trimmed(options.get(CLIENT_ID_OPTION));+ String clientSecret = trimmed(options.get(CLIENT_SECRET_OPTION));+ // Half an app registration would fail only when someone opened the label picker, which is+ // a confusing place to discover it.+ if ((clientId == null) != (clientSecret == null)) {+ throw new IllegalArgumentException(+ "purview config needs both 'clientId' and 'clientSecret' to read the label"+ + " list, or neither");+ }+ return new PurviewConnectionSettings(+ tenantId.toLowerCase(Locale.ROOT),+ clientId,+ clientSecret,+ orDefault(trimmed(options.get(GRAPH_BASE_URL_OPTION)), DEFAULT_GRAPH_BASE_URL),+ orDefault(trimmed(options.get(LOGIN_BASE_URL_OPTION)), DEFAULT_LOGIN_BASE_URL));+ }++ /** Whether this connection can read the tenant's label taxonomy from Graph. */+ public boolean canListLabels() {+ return clientId != null && clientSecret != null;+ }++ private static String orDefault(String value, String fallback) {+ return value == null ? fallback : value;+ }++ private static String trimmed(Object value) {+ if (value == null) {+ return null;+ }+ String text = value.toString().trim();+ return text.isEmpty() ? null : text;+ }++ /** Never prints the client secret, so an accidental log line cannot leak it. */+ @Override+ public String toString() {+ return "PurviewConnectionSettings[tenantId="+ + tenantId+ + ", canListLabels="+ + canListLabels()+ + "]";+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewIntegrationValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewIntegrationValidator.javanew file mode 100644index 0000000000..485345e5cd--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewIntegrationValidator.java@@ -0,0 +1,23 @@+package stirling.software.proprietary.integration.purview;++import java.util.Map;++import org.springframework.stereotype.Component;++import stirling.software.proprietary.integration.model.IntegrationType;+import stirling.software.proprietary.integration.service.IntegrationConfigValidator;++/** The Purview connection schema, enforced when the config is saved. */+@Component+public class PurviewIntegrationValidator implements IntegrationConfigValidator {++ @Override+ public IntegrationType type() {+ return IntegrationType.PURVIEW;+ }++ @Override+ public void validate(Map<String, Object> config) {+ PurviewConnectionSettings.from(config);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewLabelController.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewLabelController.javanew file mode 100644index 0000000000..65555077c3--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/PurviewLabelController.java@@ -0,0 +1,184 @@+package stirling.software.proprietary.integration.purview;++import java.io.IOException;+import java.time.Instant;+import java.util.List;+import java.util.Optional;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.springframework.core.io.ByteArrayResource;+import org.springframework.core.io.Resource;+import org.springframework.http.HttpHeaders;+import org.springframework.http.MediaType;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.PostMapping;+import org.springframework.web.bind.annotation.RequestMapping;+import org.springframework.web.bind.annotation.RequestParam;+import org.springframework.web.bind.annotation.RestController;+import org.springframework.web.multipart.MultipartFile;++import io.github.pixee.security.Filenames;+import io.swagger.v3.oas.annotations.Operation;+import io.swagger.v3.oas.annotations.tags.Tag;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.common.util.TempFileManager;+import stirling.software.common.util.WebResponseUtils;+import stirling.software.proprietary.integration.api.ApiConnectionResolver;+import stirling.software.proprietary.integration.model.IntegrationType;+import stirling.software.proprietary.integration.purview.SensitivityLabel.AssignmentMethod;+import stirling.software.proprietary.service.AiToolResponseHeaders;++import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ArrayNode;+import tools.jackson.databind.node.ObjectNode;++/**+ * Purview sensitivity labelling as policy steps.+ *+ * <p>Both steps are local: a label is metadata, so applying and reading one involves no call to+ * Microsoft. The connection supplies the tenant id that becomes the label's {@code SiteId}.+ *+ * <p>{@code purview-read-label} exists to make labels <em>actionable</em>: it reports what a+ * document already carries, so a policy can branch on it - the case Purview itself does not cover,+ * since it labels documents but does not process them.+ */+@Slf4j+@RestController+@RequestMapping("/api/v1/integration")+@RequiredArgsConstructor+@Tag(name = "Integrations", description = "Third-party integration steps.")+public class PurviewLabelController {++ private final ApiConnectionResolver connectionResolver;+ private final CustomPDFDocumentFactory pdfDocumentFactory;+ private final TempFileManager tempFileManager;+ private final ObjectMapper objectMapper;++ @PostMapping(value = "/purview-apply-label", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)+ @Operation(+ summary = "Apply a Microsoft Purview sensitivity label",+ description =+ "Writes the Purview label metadata (MSIP_Label_<GUID>_*) onto the PDF, so"+ + " Purview-aware tools recognise the label. Applies the label only;"+ + " it cannot encrypt, which requires the Microsoft client."+ + " Input:PDF Output:PDF Type:SISO")+ public ResponseEntity<Resource> applyLabel(+ @RequestParam("fileInput") MultipartFile fileInput,+ @RequestParam("connectionId") String connectionId,+ @RequestParam("labelId") String labelId,+ @RequestParam(value = "labelName", required = false) String labelName,+ @RequestParam(value = "method", defaultValue = "STANDARD") String method,+ @RequestParam(value = "contentBits", required = false) Integer contentBits)+ throws IOException {++ PurviewConnectionSettings settings = settings(connectionId);+ AssignmentMethod assignment = parseMethod(method);++ try (PDDocument document = pdfDocumentFactory.load(fileInput, true)) {+ String fileName = safeFileName(fileInput.getOriginalFilename());+ SensitivityLabel label =+ new SensitivityLabel(+ labelId.trim(),+ labelName,+ settings.tenantId(),+ assignment,+ Instant.now(),+ contentBits);+ PdfSensitivityLabels.apply(document, label);+ log.debug("[purview-apply-label] labelled {} as {}", fileName, labelId);+ return WebResponseUtils.pdfDocToWebResponse(document, fileName, tempFileManager);+ }+ }++ @PostMapping(value = "/purview-read-label", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)+ @Operation(+ summary = "Read the Microsoft Purview sensitivity label on a PDF",+ description =+ "Reports the Purview labels a PDF already carries so a policy can act on"+ + " them. The document passes through unchanged."+ + " Input:PDF Output:PDF Type:SISO")+ public ResponseEntity<Resource> readLabel(+ @RequestParam("fileInput") MultipartFile fileInput,+ @RequestParam("connectionId") String connectionId)+ throws IOException {++ PurviewConnectionSettings settings = settings(connectionId);++ List<SensitivityLabel> labels;+ try (PDDocument document = pdfDocumentFactory.load(fileInput, true)) {+ labels = PdfSensitivityLabels.readAll(document);+ }+ // The document is returned byte-for-byte rather than re-saved: a read must not perturb the+ // file it inspected, and a PDFBox round-trip would rewrite its structure.+ byte[] bytes = fileInput.getBytes();+ HttpHeaders headers = new HttpHeaders();+ headers.setContentType(MediaType.APPLICATION_PDF);+ headers.setContentDispositionFormData(+ "attachment", safeFileName(fileInput.getOriginalFilename()));+ headers.setContentLength(bytes.length);+ headers.set(AiToolResponseHeaders.TOOL_REPORT, buildReport(labels, settings));+ return ResponseEntity.ok().headers(headers).body(new ByteArrayResource(bytes));+ }++ /**+ * The labels found, and which of them is this tenant's - a document can carry labels from+ * several organisations, and only the matching one reflects this tenant's policy.+ */+ private String buildReport(List<SensitivityLabel> labels, PurviewConnectionSettings settings) {+ Optional<SensitivityLabel> own =+ labels.stream()+ .filter(label -> settings.tenantId().equalsIgnoreCase(label.siteId()))+ .findFirst();+ ObjectNode report = objectMapper.createObjectNode();+ report.put("labelled", own.isPresent());+ own.ifPresent(+ label -> {+ report.put("labelId", label.labelId());+ report.put("labelName", label.name());+ report.put("method", label.method() == null ? null : label.method().name());+ report.put(+ "setDate", label.setDate() == null ? null : label.setDate().toString());+ report.put("contentBits", label.contentBits());+ report.put("protected", label.isProtected());+ });+ ArrayNode others = report.putArray("otherTenantLabels");+ labels.stream()+ .filter(label -> !settings.tenantId().equalsIgnoreCase(label.siteId()))+ .forEach(+ label -> {+ ObjectNode node = others.addObject();+ node.put("labelId", label.labelId());+ node.put("siteId", label.siteId());+ });+ return objectMapper.writeValueAsString(report);+ }++ private PurviewConnectionSettings settings(String connectionId) {+ Long id = ApiConnectionResolver.connectionId(connectionId);+ if (id == null) {+ throw new IllegalArgumentException("'connectionId' is required");+ }+ return PurviewConnectionSettings.from(+ connectionResolver.resolveConfig(id, IntegrationType.PURVIEW));+ }++ private static AssignmentMethod parseMethod(String method) {+ AssignmentMethod parsed = AssignmentMethod.parse(method);+ if (parsed == null) {+ throw new IllegalArgumentException(+ "'method' must be STANDARD (applied automatically) or PRIVILEGED (chosen by a"+ + " person); got "+ + method);+ }+ return parsed;+ }++ private static String safeFileName(String originalFilename) {+ String name = Filenames.toSimpleFileName(originalFilename);+ return (name == null || name.isBlank()) ? "labelled.pdf" : name;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/SensitivityLabel.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/SensitivityLabel.javanew file mode 100644index 0000000000..5f6e97452e--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/purview/SensitivityLabel.java@@ -0,0 +1,186 @@+package stirling.software.proprietary.integration.purview;++import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.util.LinkedHashMap;+import java.util.Locale;+import java.util.Map;+import java.util.regex.Pattern;++/**+ * One Microsoft Purview Information Protection label as it is written to a document.+ *+ * <p>Microsoft persists a label as a flat set of key/value pairs named {@code+ * MSIP_Label_<GUID>_<Attribute>}, and documents that contract publicly so third-party software can+ * read a label and act on it. That published contract - not the MIP SDK, which has no Java binding+ * - is what this type implements. See <a+ * href="https://learn.microsoft.com/en-us/information-protection/develop/concept-mip-metadata">Label+ * metadata in the MIP SDK</a>.+ *+ * <p>Only {@code Enabled} and {@code SiteId} are mandatory in that contract; the rest are optional+ * and may be absent on a label written by an older client, so readers here tolerate their absence.+ */+public record SensitivityLabel(+ String labelId,+ String name,+ String siteId,+ AssignmentMethod method,+ Instant setDate,+ Integer contentBits) {++ /** How the label came to be applied. */+ public enum AssignmentMethod {+ /** Applied by default or automatically - e.g. by a policy like this one. */+ STANDARD,+ /** Chosen deliberately by a person. */+ PRIVILEGED;++ String wireValue() {+ return name().charAt(0) + name().substring(1).toLowerCase(Locale.ROOT);+ }++ static AssignmentMethod parse(String value) {+ if (value == null) {+ return null;+ }+ try {+ return valueOf(value.trim().toUpperCase(Locale.ROOT));+ } catch (IllegalArgumentException e) {+ return null;+ }+ }+ }++ public static final String KEY_PREFIX = "MSIP_Label_";++ /** Content marks the labelling application applied; a bitmask, per the MIP contract. */+ public static final int CONTENT_BITS_HEADER = 0x1;++ public static final int CONTENT_BITS_FOOTER = 0x2;+ public static final int CONTENT_BITS_WATERMARK = 0x4;+ public static final int CONTENT_BITS_ENCRYPT = 0x8;++ /**+ * Extended ISO 8601, matching the {@code 2018-11-08T21:13:16-0800} form Microsoft documents.+ */+ private static final DateTimeFormatter SET_DATE =+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ROOT)+ .withZone(ZoneOffset.UTC);++ /**+ * Microsoft caps each key and value at 255 characters "to maintain compatibility across common+ * applications".+ */+ static final int MAX_VALUE_LENGTH = 255;++ /** The GUID shape a labelId must take, matching what the read path accepts from a document. */+ private static final Pattern LABEL_ID = Pattern.compile("^[0-9a-fA-F-]{36}$");++ public SensitivityLabel {+ if (labelId == null || labelId.isBlank()) {+ throw new IllegalArgumentException("a sensitivity label needs a labelId");+ }+ if (!LABEL_ID.matcher(labelId).matches()) {+ // labelId is spliced verbatim into XMP/info key names; a non-GUID would let a stray+ // character (a space, or <, >, &) corrupt or inject the metadata it is written into.+ throw new IllegalArgumentException("a sensitivity label needs a GUID labelId");+ }+ if (siteId == null || siteId.isBlank()) {+ throw new IllegalArgumentException("a sensitivity label needs a siteId (tenant id)");+ }+ }++ /** The {@code MSIP_Label_<GUID>_} prefix this label's keys share. */+ public String keyPrefix() {+ return KEY_PREFIX + labelId + "_";+ }++ /**+ * This label as the key/value pairs to persist. Optional attributes are omitted when unset+ * rather than written empty, so a reader cannot mistake "not recorded" for "recorded as blank".+ */+ public Map<String, String> toMetadata() {+ Map<String, String> out = new LinkedHashMap<>();+ String prefix = keyPrefix();+ out.put(prefix + "Enabled", "true");+ out.put(prefix + "SiteId", siteId);+ if (method != null) {+ out.put(prefix + "Method", method.wireValue());+ }+ if (setDate != null) {+ out.put(prefix + "SetDate", SET_DATE.format(setDate));+ }+ if (name != null && !name.isBlank()) {+ out.put(prefix + "Name", truncate(name));+ }+ if (contentBits != null) {+ out.put(prefix + "ContentBits", String.valueOf(contentBits));+ }+ return out;+ }++ /**+ * Rebuild a label from the pairs found on a document.+ *+ * @param labelId the GUID between the prefix and the attribute name+ * @param attributes attribute name (e.g. {@code Name}) to value, for that GUID only+ * @return null when the pairs do not describe an enabled label+ */+ static SensitivityLabel fromAttributes(String labelId, Map<String, String> attributes) {+ // "DLP products typically validate the existence of this key to identify the+ // classification label" - an absent or false Enabled means there is no label here.+ if (!"true".equalsIgnoreCase(attributes.get("Enabled"))) {+ return null;+ }+ String siteId = attributes.get("SiteId");+ if (siteId == null || siteId.isBlank()) {+ // SiteId is mandatory in the contract, but a label written by something non-compliant+ // is still a label; keep it readable rather than throwing on someone else's file.+ siteId = "unknown";+ }+ return new SensitivityLabel(+ labelId,+ attributes.get("Name"),+ siteId,+ AssignmentMethod.parse(attributes.get("Method")),+ parseDate(attributes.get("SetDate")),+ parseInt(attributes.get("ContentBits")));+ }++ private static Instant parseDate(String value) {+ if (value == null || value.isBlank()) {+ return null;+ }+ try {+ return SET_DATE.parse(value.trim(), Instant::from);+ } catch (RuntimeException e) {+ try {+ // Tolerate the plain ISO form some writers use instead.+ return Instant.parse(value.trim());+ } catch (RuntimeException ignored) {+ return null;+ }+ }+ }++ private static Integer parseInt(String value) {+ if (value == null || value.isBlank()) {+ return null;+ }+ try {+ return Integer.valueOf(value.trim());+ } catch (NumberFormatException e) {+ return null;+ }+ }++ private static String truncate(String value) {+ return value.length() <= MAX_VALUE_LENGTH ? value : value.substring(0, MAX_VALUE_LENGTH);+ }++ /** Whether the labelling application encrypted the content. */+ public boolean isProtected() {+ return contentBits != null && (contentBits & CONTENT_BITS_ENCRYPT) != 0;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.javaindex a7ef7d4512..a6650569a8 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/IntegrationConfigService.java@@ -13,6 +13,7 @@ import org.springframework.web.server.ResponseStatusException;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;+import stirling.software.common.model.ApplicationProperties;import stirling.software.proprietary.access.model.DefaultAccessPolicy;import stirling.software.proprietary.access.model.OwnerScope;import stirling.software.proprietary.access.model.ResourceType;@@ -43,6 +44,7 @@ public class IntegrationConfigService {private final OwnershipService ownership;private final SecretMasker secretMasker;private final ResourceGrantRepository grantRepository;+ private final ApplicationProperties applicationProperties;// Bean-discovered extension points: features that understand a type contribute its config// schema and report what still references a config, without this module depending on them.private final List<IntegrationConfigValidator> validators;@@ -62,6 +64,7 @@ public class IntegrationConfigService {&& !ownership.isAdmin(currentUser)) {throw forbidden("S3 connections can only be created by administrators or team owners");}+ requireCustomApiAllowed(cfg.getIntegrationType(), currentUser);cfg.setName(require(request.name(), "name"));cfg.setEnabled(request.enabled() == null || request.enabled());cfg.setLocked(request.locked() != null && request.locked());@@ -113,6 +116,9 @@ public class IntegrationConfigService {cfg.setDefaultAccess(request.defaultAccess());}if (request.config() != null) {+ // Editing the config of a custom integration is the same authoring power as creating+ // one - it is where the base URL and body live - so it is gated identically.+ requireCustomApiAllowed(cfg.getIntegrationType(), currentUser);Map<String, Object> merged =secretMasker.merge(readJson(cfg.getConfig()), request.config());validateConfig(cfg.getIntegrationType(), merged);@@ -121,6 +127,32 @@ public class IntegrationConfigService {return repository.save(cfg);}+ /**+ * A custom API integration names its own host, path and body, so it can point the server+ * anywhere. That is authoring power rather than self-serve configuration: admins only, and the+ * operator can withdraw it entirely. The vendor presets are not gated here - they carry a fixed+ * shape, so the worst a user can do is misconfigure their own connection.+ */+ private void requireCustomApiAllowed(IntegrationType type, User currentUser) {+ if (type != IntegrationType.API) {+ return;+ }+ if (!applicationProperties.getPolicies().isAllowCustomApiIntegrations()) {+ throw forbidden(+ "Custom API integrations are disabled on this server"+ + " (policies.allowCustomApiIntegrations)");+ }+ if (!ownership.isAdmin(currentUser)) {+ throw forbidden("Custom API integrations can only be created by administrators");+ }+ }++ /** Whether this caller may author custom API integrations, for the UI to offer or hide it. */+ public boolean canAuthorCustomApi(User currentUser) {+ return applicationProperties.getPolicies().isAllowCustomApiIntegrations()+ && ownership.isAdmin(currentUser);+ }+@Transactionalpublic void delete(Long id, User currentUser) {IntegrationConfig cfg = load(id);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.javaindex e0df6ba2b1..06172b8cbc 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@@ -123,7 +123,7 @@ public class PolicyController {throws IOException {stampPolicyAudit(definition);requireRunnable(definition);- validateAdHocOutput(definition);+ validateAdHocRun(definition);PolicyInputs inputs = toInputs(files);PolicyRunHandle handle =policyRunner.runAdHoc(definition, inputs, PolicyProgressListener.NOOP);@@ -144,7 +144,7 @@ public class PolicyController {throws IOException {stampPolicyAudit(definition);requireRunnable(definition);- validateAdHocOutput(definition);+ validateAdHocRun(definition);PolicyInputs inputs = toInputs(files);SseEmitter emitter =@@ -560,18 +560,22 @@ public class PolicyController {}/**- * Authorization-check an ad-hoc run's output while the caller's principal is present (this- * request thread). The worker thread that later delivers carries no security context, so an S3- * output's connection-access check would be skipped there; without this gate a caller could- * reference another tenant's connection by id and write to it (confused deputy). Stored- * policies are covered by save-time {@link PolicyValidator#validate} instead.+ * Authorization-check an ad-hoc run's steps and output while the caller's principal is present+ * (this request thread). The worker thread that later runs and delivers carries no security+ * context, so a connection-access check would be skipped there; without this gate a caller+ * could reference another tenant's connection by id and write to it, or make the server call it+ * with its stored credentials (confused deputy). Stored policies are covered by save-time+ * {@link PolicyValidator#validate} instead.*/- private void validateAdHocOutput(PipelineDefinition definition) {- if (definition.output() == null) {- return;- }+ private void validateAdHocRun(PipelineDefinition definition) {try {- policyValidator.validateOutput(definition.output());+ // Steps get the same treatment as the output, and for the same reason: an integration+ // step dereferences its connection by id on a principal-less worker thread, so this+ // request thread is the only place that reference can be checked against the caller.+ policyValidator.validateSteps(definition.steps());+ if (definition.output() != null) {+ policyValidator.validateOutput(definition.output());+ }} catch (IllegalArgumentException e) {throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PipelineStepValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PipelineStepValidator.javanew file mode 100644index 0000000000..fc440609a0--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PipelineStepValidator.java@@ -0,0 +1,22 @@+package stirling.software.proprietary.policy.engine;++import stirling.software.proprietary.policy.model.PipelineStep;++/**+ * Validates one step's parameters before a run is admitted. Implementations are beans discovered by+ * {@link PolicyValidator}, so the feature that understands a step's parameters owns their rules+ * without the engine depending on it.+ *+ * <p>Steps run on a worker thread with no {@code SecurityContext}, so anything a step dereferences+ * by id - an integration connection, say - cannot be authorization-checked at run time. A validator+ * that resolves such a reference must therefore be called while the caller's principal is still+ * present, which is what {@link PolicyValidator#validateSteps} guarantees.+ */+public interface PipelineStepValidator {++ /**+ * @throws IllegalArgumentException if the step is misconfigured or references something the+ * current caller may not use+ */+ void validate(PipelineStep step);+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.javaindex cac05765a0..c2d1357889 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyValidator.java@@ -9,6 +9,7 @@ import lombok.RequiredArgsConstructor;import stirling.software.proprietary.policy.input.InputSource;import stirling.software.proprietary.policy.model.InputSpec;import stirling.software.proprietary.policy.model.OutputSpec;+import stirling.software.proprietary.policy.model.PipelineStep;import stirling.software.proprietary.policy.model.Policy;import stirling.software.proprietary.policy.model.TriggerConfig;import stirling.software.proprietary.policy.output.PolicyOutputSink;@@ -17,10 +18,10 @@ import stirling.software.proprietary.policy.source.SourceStore;import stirling.software.proprietary.policy.trigger.PolicyTrigger;/**- * Validates a policy at save time by delegating each facet (trigger, sources, output) to the bean- * that handles its type, so a misconfiguration fails fast rather than at run time. A null trigger- * is a manual-only policy and skips trigger validation. Each referenced {@code sourceId} must- * resolve to a persisted {@link Source} whose config its {@link InputSource} bean accepts.+ * Validates a policy at save time by delegating each facet (trigger, sources, steps, output) to the+ * bean that handles its type, so a misconfiguration fails fast rather than at run time. A null+ * trigger is a manual-only policy and skips trigger validation. Each referenced {@code sourceId}+ * must resolve to a persisted {@link Source} whose config its {@link InputSource} bean accepts.*/@Service@RequiredArgsConstructor@@ -29,6 +30,7 @@ public class PolicyValidator {private final List<PolicyTrigger> triggers;private final List<InputSource> inputSources;private final List<PolicyOutputSink> outputSinks;+ private final List<PipelineStepValidator> stepValidators;private final SourceStore sourceStore;/**@@ -50,9 +52,27 @@ public class PolicyValidator {InputSpec spec = source.toInputSpec();inputSourceFor(spec).validate(spec);}+ validateSteps(policy.steps());validateOutput(policy.output());}+ /**+ * Validate each step against every registered {@link PipelineStepValidator}. Must be called on+ * a request thread (caller's principal present) for the same reason as {@link+ * #validateOutput(OutputSpec)}: a step that dereferences an integration connection by id is+ * access-checked here or nowhere, since the worker thread that later runs it has no principal.+ *+ * @throws IllegalArgumentException if any step is invalid or references an inaccessible+ * resource+ */+ public void validateSteps(List<PipelineStep> steps) {+ for (PipelineStep step : steps) {+ for (PipelineStepValidator validator : stepValidators) {+ validator.validate(step);+ }+ }+ }+/*** Validate an output spec against its sink. Must be called on a request thread (caller's* principal present) so an S3 output's connection is authorization-checked against the caller -diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/SecretMaskerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/SecretMaskerTest.javaindex 4f76b06b5c..dbd8c02131 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/access/service/SecretMaskerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/access/service/SecretMaskerTest.java@@ -77,6 +77,48 @@ class SecretMaskerTest {assertThat(clean).containsEntry("bucket", "b").doesNotContainKey("secretKey");}+ @Test+ void maskRedactsEveryHeaderValueRegardlessOfName() {+ Map<String, Object> headers = new LinkedHashMap<>();+ headers.put("X-API-Key", "real-secret"); // name carries no secret hint+ headers.put("Ocp-Apim-Subscription-Key", "abc123");+ headers.put("Content-Type", "application/json");+ Map<String, Object> config = new LinkedHashMap<>();+ config.put("baseUrl", "https://api.example");+ config.put("headers", headers);++ Map<String, Object> masked = masker.mask(config);++ assertThat(masked.get("baseUrl")).isEqualTo("https://api.example");+ @SuppressWarnings("unchecked")+ Map<String, Object> maskedHeaders = (Map<String, Object>) masked.get("headers");+ assertThat(maskedHeaders.get("X-API-Key")).isEqualTo(SecretMasker.MASK);+ assertThat(maskedHeaders.get("Ocp-Apim-Subscription-Key")).isEqualTo(SecretMasker.MASK);+ assertThat(maskedHeaders.get("Content-Type")).isEqualTo(SecretMasker.MASK);+ }++ @Test+ void mergeRestoresRedactedHeaderValuesFromStored() {+ Map<String, Object> storedHeaders = new LinkedHashMap<>();+ storedHeaders.put("X-API-Key", "REAL");+ storedHeaders.put("Content-Type", "application/json");+ Map<String, Object> stored = new LinkedHashMap<>();+ stored.put("headers", storedHeaders);++ Map<String, Object> incomingHeaders = new LinkedHashMap<>();+ incomingHeaders.put("X-API-Key", SecretMasker.MASK); // untouched secret comes back masked+ incomingHeaders.put("Content-Type", "text/plain"); // genuinely edited+ Map<String, Object> incoming = new LinkedHashMap<>();+ incoming.put("headers", incomingHeaders);++ Map<String, Object> merged = masker.merge(stored, incoming);++ @SuppressWarnings("unchecked")+ Map<String, Object> mergedHeaders = (Map<String, Object>) merged.get("headers");+ assertThat(mergedHeaders.get("X-API-Key")).isEqualTo("REAL"); // restored, not "********"+ assertThat(mergedHeaders.get("Content-Type")).isEqualTo("text/plain"); // updated+ }+@Testvoid deeplyNestedInputIsBoundedNotOverflowing() {// Build a structure far deeper than the recursion cap.diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ApiIntegrationValidatorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ApiIntegrationValidatorTest.javanew file mode 100644index 0000000000..e767aae34d--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ApiIntegrationValidatorTest.java@@ -0,0 +1,76 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThatCode;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.util.LinkedHashMap;+import java.util.Map;++import org.junit.jupiter.api.Test;++import stirling.software.common.model.ApplicationProperties;++/**+ * The private-endpoint opt-in is coarse by design (it lets an on-prem integration reach RFC1918),+ * but it must never open the cloud metadata service - the one internal address whose only use is+ * stealing the instance's credentials.+ */+class ApiIntegrationValidatorTest {++ private final ApiIntegrationValidator validator =+ new ApiIntegrationValidator(properties(false));++ private static ApplicationProperties properties(boolean allowPrivate) {+ ApplicationProperties p = new ApplicationProperties();+ p.getPolicies().setAllowPrivateApiEndpoints(allowPrivate);+ return p;+ }++ private static Map<String, Object> config(String baseUrl) {+ Map<String, Object> c = new LinkedHashMap<>();+ c.put("baseUrl", baseUrl);+ return c;+ }++ @Test+ void acceptsAnOrdinaryPublicHost() {+ // A public IP literal, so the check needs no network DNS (an unresolvable name would fail+ // closed at the resolve step, which is correct but not what this test is about).+ assertThatCode(() -> validator.validate(config("https://1.1.1.1/v1")))+ .doesNotThrowAnyException();+ }++ @Test+ void rejectsAPrivateHostByDefault() {+ assertThatThrownBy(() -> validator.validate(config("http://10.0.0.5/x")))+ .isInstanceOf(IllegalArgumentException.class);+ }++ @Test+ void rejectsTheCloudMetadataAddressEvenWithThePrivateOptInOn() {+ ApiIntegrationValidator opted = new ApiIntegrationValidator(properties(true));++ // The on-prem opt-in allows RFC1918, but the metadata endpoint stays blocked.+ assertThatThrownBy(() -> opted.validate(config("http://169.254.169.254/latest/meta-data/")))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("metadata service");+ }++ @Test+ void aPrivateOnPremHostIsAllowedWhenOptedIn() {+ ApiIntegrationValidator opted = new ApiIntegrationValidator(properties(true));++ assertThatCode(() -> opted.validate(config("http://10.10.0.20:8080/api")))+ .doesNotThrowAnyException();+ }++ @Test+ void theMetadataBlockRunsBeforeTheOptInSoItCannotBeBypassed() {+ // Also covers the Oracle/IBM variants that share the 169.254.169.x range.+ ApiIntegrationValidator opted = new ApiIntegrationValidator(properties(true));++ assertThatThrownBy(() -> opted.validate(config("http://169.254.169.253/")))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("metadata service");+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/DocumentContextTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/DocumentContextTest.javanew file mode 100644index 0000000000..4576584b58--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/DocumentContextTest.java@@ -0,0 +1,177 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThat;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.time.Instant;+import java.util.Base64;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.junit.jupiter.api.Test;+import org.springframework.mock.web.MockMultipartFile;++import stirling.software.common.service.PdfMetadataService;+import stirling.software.proprietary.integration.purview.PdfSensitivityLabels;+import stirling.software.proprietary.integration.purview.SensitivityLabel;+import stirling.software.proprietary.integration.purview.SensitivityLabel.AssignmentMethod;++import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ObjectNode;++/**+ * The context is what an external API gets told about the document, so it is asserted concretely.+ */+class DocumentContextTest {++ private static final String TENANT = "cb46c030-1825-4e81-a295-151c039dbf02";+ private final ObjectMapper objectMapper = new ObjectMapper();++ private static byte[] pdfBytes(java.util.function.Consumer<PDDocument> customise)+ throws IOException {+ try (PDDocument document = new PDDocument()) {+ document.addPage(new PDPage());+ document.addPage(new PDPage());+ customise.accept(document);+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ document.save(out);+ return out.toByteArray();+ }+ }++ private ObjectNode contextOf(byte[] content, String filename, String policyName, String runId) {+ MockMultipartFile file =+ new MockMultipartFile("fileInput", filename, "application/pdf", content);+ return DocumentContext.build(file, content, policyName, runId, objectMapper);+ }++ @Test+ void describesThePdfAndTheRun() throws IOException {+ byte[] content =+ pdfBytes(+ document -> {+ document.getDocumentInformation().setTitle("Q3 Invoice");+ document.getDocumentInformation().setAuthor("Anthony");+ });++ ObjectNode context = contextOf(content, "invoice.pdf", "Outbound review", "run-42");++ assertThat(context.at("/document/filename").asString()).isEqualTo("invoice.pdf");+ assertThat(context.at("/document/extension").asString()).isEqualTo("pdf");+ assertThat(context.at("/document/contentType").asString()).isEqualTo("application/pdf");+ assertThat(context.at("/document/sizeBytes").asInt()).isEqualTo(content.length);+ assertThat(context.at("/document/pageCount").asInt()).isEqualTo(2);+ assertThat(context.at("/document/encrypted").asBoolean()).isFalse();+ assertThat(context.at("/document/title").asString()).isEqualTo("Q3 Invoice");+ assertThat(context.at("/document/author").asString()).isEqualTo("Anthony");+ assertThat(context.at("/run/policyName").asString()).isEqualTo("Outbound review");+ assertThat(context.at("/run/runId").asString()).isEqualTo("run-42");+ assertThat(Instant.parse(context.at("/run/timestamp").asString())).isNotNull();+ }++ @Test+ void hashesTheContentTheApiWillReceive() throws IOException {+ byte[] content = pdfBytes(document -> {});++ String sha = contextOf(content, "a.pdf", null, null).at("/document/sha256").asString();++ assertThat(sha).hasSize(64).matches("[0-9a-f]{64}");+ // Same bytes, same hash: external systems key on this for dedupe and chain-of-custody.+ assertThat(contextOf(content, "renamed.pdf", null, null).at("/document/sha256").asString())+ .isEqualTo(sha);+ }++ @Test+ void carriesTheBytesAsBase64ForBodyPayloads() throws IOException {+ // Presets that attach or sign the document reference {{document.base64}}; without this the+ // placeholder is unknown and the whole step fails at resolution time.+ byte[] content = pdfBytes(document -> {});++ String base64 = contextOf(content, "a.pdf", null, null).at("/document/base64").asString();++ assertThat(Base64.getDecoder().decode(base64)).isEqualTo(content);+ }++ @Test+ void surfacesAnExistingPurviewLabel() throws IOException {+ byte[] content =+ pdfBytes(+ document -> {+ try {+ PdfSensitivityLabels.apply(+ document,+ new SensitivityLabel(+ "2096f6a2-d2f7-48be-b329-b73aaa526e5d",+ "Confidential",+ TENANT,+ AssignmentMethod.PRIVILEGED,+ null,+ null));+ } catch (IOException e) {+ throw new java.io.UncheckedIOException(e);+ }+ });++ ObjectNode context = contextOf(content, "secret.pdf", null, null);++ assertThat(context.at("/sensitivityLabel/name").asString()).isEqualTo("Confidential");+ assertThat(context.at("/sensitivityLabel/siteId").asString()).isEqualTo(TENANT);+ assertThat(context.at("/sensitivityLabel/method").asString()).isEqualTo("PRIVILEGED");+ assertThat(context.at("/sensitivityLabel/protected").asBoolean()).isFalse();+ }++ @Test+ void surfacesTheClassifierVerdictAsJson() throws IOException {+ byte[] content =+ pdfBytes(+ document ->+ document.getDocumentInformation()+ .setCustomMetadataValue(+ PdfMetadataService.CLASSIFICATION_KEY,+ "{\"label\":\"invoice\",\"confidence\":0.91}"));++ ObjectNode context = contextOf(content, "a.pdf", null, null);++ // Nested, not a JSON string, so {{classification.label}} resolves.+ assertThat(context.at("/classification/label").asString()).isEqualTo("invoice");+ assertThat(context.at("/classification/confidence").asDouble()).isEqualTo(0.91);+ }++ @Test+ void omitsWhatIsAbsentRatherThanInventingIt() throws IOException {+ ObjectNode context = contextOf(pdfBytes(document -> {}), "a.pdf", null, null);++ assertThat(context.has("sensitivityLabel")).isFalse();+ assertThat(context.has("classification")).isFalse();+ assertThat(context.at("/run/policyName").isNull()).isTrue();+ }++ @Test+ void aNonPdfStillGetsTheBasics() {+ byte[] content = "just text".getBytes();+ MockMultipartFile file =+ new MockMultipartFile("fileInput", "notes.txt", "text/plain", content);++ ObjectNode context = DocumentContext.build(file, content, null, null, objectMapper);++ assertThat(context.at("/document/filename").asString()).isEqualTo("notes.txt");+ assertThat(context.at("/document/extension").asString()).isEqualTo("txt");+ assertThat(context.at("/document/sizeBytes").asInt()).isEqualTo(content.length);+ assertThat(context.at("/document/sha256").asString()).hasSize(64);+ // No PDF facts, and no exception either.+ assertThat(context.at("/document/pageCount").isMissingNode()).isTrue();+ }++ @Test+ void unparseableBytesClaimingToBeAPdfDoNotFailTheStep() {+ byte[] content = "%PDF-1.7 but truncated".getBytes();+ MockMultipartFile file =+ new MockMultipartFile("fileInput", "broken.pdf", "application/pdf", content);++ ObjectNode context = DocumentContext.build(file, content, null, null, objectMapper);++ assertThat(context.at("/document/sha256").asString()).hasSize(64);+ assertThat(context.at("/document/pageCount").isMissingNode()).isTrue();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallControllerLiveTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallControllerLiveTest.javanew file mode 100644index 0000000000..462c1a348f--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallControllerLiveTest.java@@ -0,0 +1,615 @@+package stirling.software.proprietary.integration.api;++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.when;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.net.InetSocketAddress;+import java.net.http.HttpClient;+import java.nio.charset.StandardCharsets;+import java.util.Base64;+import java.util.LinkedHashMap;+import java.util.Map;+import java.util.zip.ZipEntry;+import java.util.zip.ZipOutputStream;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.junit.jupiter.api.AfterEach;+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.mockito.junit.jupiter.MockitoSettings;+import org.mockito.quality.Strictness;+import org.springframework.core.io.Resource;+import org.springframework.http.ResponseEntity;+import org.springframework.mock.web.MockMultipartFile;++import com.sun.net.httpserver.HttpExchange;+import com.sun.net.httpserver.HttpServer;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.PdfMetadataService;+import stirling.software.common.util.TempFileManager;+import stirling.software.common.util.TempFileRegistry;+import stirling.software.proprietary.integration.model.IntegrationType;+import stirling.software.proprietary.integration.purview.PdfSensitivityLabels;+import stirling.software.proprietary.integration.purview.SensitivityLabel;+import stirling.software.proprietary.integration.purview.SensitivityLabel.AssignmentMethod;+import stirling.software.proprietary.service.AiToolResponseHeaders;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;++/**+ * Drives the real {@link ExternalApiCallController} against a real HTTP server on loopback.+ *+ * <p>Everything below the connection lookup is genuine: a real PDF, real context extraction, real+ * placeholder resolution, a real JDK HTTP client, and a real receiver that records exactly what+ * arrived. Only {@link ApiConnectionResolver} is stubbed - resolving a connection means a database+ * and an authorization check, which belong to their own tests.+ *+ * <p>The receiver is the point. Asserting what a third party actually received is the only way to+ * know the document and its context left in the shape an integration expects; asserting our own+ * intentions would pass just as happily with the bytes never leaving.+ */+@ExtendWith(MockitoExtension.class)+@MockitoSettings(strictness = Strictness.LENIENT)+class ExternalApiCallControllerLiveTest {++ @Mock private ApiConnectionResolver connectionResolver;++ private HttpServer server;+ private String baseUrl;+ private ExternalApiCallController controller;+ private final ObjectMapper objectMapper = new ObjectMapper();+ private final ApplicationProperties properties = new ApplicationProperties();++ /** What the receiver saw, so assertions are about the wire rather than our intentions. */+ private volatile String receivedBody;++ private volatile String receivedContentType;+ private volatile String receivedMethod;+ private final Map<String, String> receivedHeaders = new LinkedHashMap<>();++ @BeforeEach+ void startReceiver() throws IOException {+ // Loopback is exactly what the host guard blocks by default; an operator opts in for an+ // on-prem integration, which is what a local receiver stands in for.+ properties.getPolicies().setAllowPrivateApiEndpoints(true);++ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);++ // Records, then answers with a verdict - the DLP/scanner shape.+ server.createContext(+ "/v1/scan",+ exchange -> {+ capture(exchange);+ respond(+ exchange,+ 200,+ "application/json",+ "{\"verdict\":\"clean\",\"score\":0.02}"+ .getBytes(StandardCharsets.UTF_8));+ });++ // Answers with a different document - the converter shape.+ server.createContext(+ "/v1/convert",+ exchange -> {+ capture(exchange);+ exchange.getResponseHeaders()+ .add("Content-Disposition", "attachment; filename=\"converted.docx\"");+ respond(+ exchange,+ 200,+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "DOCX-BYTES".getBytes(StandardCharsets.UTF_8));+ });++ // Answers with a link to the result - the async/large-file shape.+ server.createContext(+ "/v1/deferred",+ exchange -> {+ capture(exchange);+ respond(+ exchange,+ 200,+ "application/json",+ ("{\"status\":\"done\",\"data\":{\"downloadUrl\":\""+ + baseUrl+ + "/files/result.pdf\"}}")+ .getBytes(StandardCharsets.UTF_8));+ });++ // Answers with a link on a host the connection never authorised.+ server.createContext(+ "/v1/evil",+ exchange -> {+ capture(exchange);+ respond(+ exchange,+ 200,+ "application/json",+ "{\"data\":{\"downloadUrl\":\"http://169.254.169.254/latest/meta-data/\"}}"+ .getBytes(StandardCharsets.UTF_8));+ });++ server.createContext(+ "/files/result.pdf",+ exchange ->+ respond(+ exchange,+ 200,+ "application/pdf",+ "%PDF-1.7 fetched".getBytes(StandardCharsets.UTF_8)));++ // Answers with an archive - ConsignO's "PDF (single) or ZIP (multiple)" shape.+ server.createContext(+ "/v1/bundle",+ exchange -> {+ capture(exchange);+ respond(exchange, 200, "application/zip", zip());+ });++ server.createContext(+ "/v1/reject",+ exchange -> {+ capture(exchange);+ respond(+ exchange,+ 422,+ "application/json",+ "{\"error\":\"policy violation\"}".getBytes(StandardCharsets.UTF_8));+ });++ // Cloudmersive's scan shape: HTTP 200 with the verdict in the body, clean or not.+ server.createContext(+ "/v1/clean",+ exchange -> {+ capture(exchange);+ respond(+ exchange,+ 200,+ "application/json",+ "{\"CleanResult\":true}".getBytes(StandardCharsets.UTF_8));+ });+ server.createContext(+ "/v1/infected",+ exchange -> {+ capture(exchange);+ respond(+ exchange,+ 200,+ "application/json",+ "{\"CleanResult\":false,\"FoundViruses\":[{\"VirusName\":\"EICAR\"}]}"+ .getBytes(StandardCharsets.UTF_8));+ });++ server.start();+ baseUrl = "http://127.0.0.1:" + server.getAddress().getPort();++ ExternalApiCaller caller =+ new ExternalApiCaller(+ HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build(),+ properties,+ objectMapper);+ controller =+ new ExternalApiCallController(+ connectionResolver,+ caller,+ objectMapper,+ new TempFileManager(new TempFileRegistry(), properties),+ properties);+ }++ @AfterEach+ void stopReceiver() {+ server.stop(0);+ }++ private void capture(HttpExchange exchange) throws IOException {+ receivedMethod = exchange.getRequestMethod();+ receivedBody = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);+ receivedContentType = exchange.getRequestHeaders().getFirst("Content-Type");+ exchange.getRequestHeaders()+ .forEach((name, values) -> receivedHeaders.put(name, values.get(0)));+ }++ private static void respond(HttpExchange exchange, int status, String contentType, byte[] body)+ throws IOException {+ exchange.getResponseHeaders().add("Content-Type", contentType);+ exchange.sendResponseHeaders(status, body.length);+ exchange.getResponseBody().write(body);+ exchange.close();+ }++ private static byte[] zip() throws IOException {+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ try (ZipOutputStream zip = new ZipOutputStream(out)) {+ zip.putNextEntry(new ZipEntry("audit-trail.txt"));+ zip.write("who signed what".getBytes(StandardCharsets.UTF_8));+ zip.closeEntry();+ zip.putNextEntry(new ZipEntry("signed.pdf"));+ zip.write("%PDF-1.7 signed".getBytes(StandardCharsets.UTF_8));+ zip.closeEntry();+ }+ return out.toByteArray();+ }++ /** A labelled, classified PDF, so the context has something real to carry. */+ private static MockMultipartFile pdf() throws IOException {+ try (PDDocument document = new PDDocument()) {+ document.addPage(new PDPage());+ document.addPage(new PDPage());+ document.getDocumentInformation().setTitle("Q3 Claim");+ document.getDocumentInformation()+ .setCustomMetadataValue(+ PdfMetadataService.CLASSIFICATION_KEY,+ "{\"label\":\"invoice\",\"confidence\":0.91}");+ PdfSensitivityLabels.apply(+ document,+ new SensitivityLabel(+ "2096f6a2-d2f7-48be-b329-b73aaa526e5d",+ "Confidential",+ "cb46c030-1825-4e81-a295-151c039dbf02",+ AssignmentMethod.PRIVILEGED,+ null,+ null));+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ document.save(out);+ return new MockMultipartFile(+ "fileInput", "claim.pdf", "application/pdf", out.toByteArray());+ }+ }++ private void connection(Map<String, Object> extra) {+ Map<String, Object> config = new LinkedHashMap<>();+ config.put("baseUrl", baseUrl);+ config.putAll(extra);+ when(connectionResolver.resolve(eq(7L))).thenReturn(ApiConnectionSettings.from(config));+ when(connectionResolver.resolveConfig(eq(7L), any(IntegrationType.class)))+ .thenReturn(config);+ }++ /**+ * The step's parameters, named. The controller takes seventeen positional arguments, which is+ * unreadable and easy to mis-order at a call site; this lets each test state only what it+ * varies.+ */+ private final class Step {+ private String path = "/v1/scan";+ private String method = "POST";+ private String bodyMode = "multipart";+ private String fileFieldName = "file";+ private String responseMode = "report";+ private String resultUrlPath;+ private String resultUrlHeader;+ private String responseSelect;+ private String requireTrue;+ private String fields;+ private String bodyTemplate;+ private String headers;+ private boolean includeContext;+ private boolean includeFile = true;+ private String policyName;+ private String runId;++ Step path(String v) {+ path = v;+ return this;+ }++ Step method(String v) {+ method = v;+ return this;+ }++ Step bodyMode(String v) {+ bodyMode = v;+ return this;+ }++ Step responseMode(String v) {+ responseMode = v;+ return this;+ }++ Step resultUrlPath(String v) {+ resultUrlPath = v;+ return this;+ }++ Step responseSelect(String v) {+ responseSelect = v;+ return this;+ }++ Step requireTrue(String v) {+ requireTrue = v;+ return this;+ }++ Step fields(String v) {+ fields = v;+ return this;+ }++ Step bodyTemplate(String v) {+ bodyTemplate = v;+ return this;+ }++ Step headers(String v) {+ headers = v;+ return this;+ }++ Step includeContext(boolean v) {+ includeContext = v;+ return this;+ }++ Step run(String policy, String id) {+ policyName = policy;+ runId = id;+ return this;+ }++ ResponseEntity<Resource> go() throws IOException {+ return controller.call(+ pdf(),+ "7",+ path,+ method,+ bodyMode,+ fileFieldName,+ responseMode,+ resultUrlPath,+ resultUrlHeader,+ responseSelect,+ requireTrue,+ fields,+ bodyTemplate,+ headers,+ includeContext,+ includeFile,+ policyName,+ runId);+ }+ }++ private Step step() {+ return new Step();+ }++ @Test+ void sendsTheDocumentAndWhatWeKnowAboutItToTheReceiver() throws IOException {+ connection(Map.of());++ ResponseEntity<Resource> response =+ step().path("/v1/scan")+ .fields(+ "{\"sha256\":\"{{document.sha256}}\",\"label\":\"{{sensitivityLabel.name}}\","+ + "\"class\":\"{{classification.label}}\",\"pages\":\"{{document.pageCount}}\"}")+ .includeContext(true)+ .run("Outbound review", "run-42")+ .go();++ assertThat(receivedMethod).isEqualTo("POST");+ assertThat(receivedContentType).startsWith("multipart/form-data");+ // Fields the vendor asked for, filled from what Stirling already knew - no extra calls.+ assertThat(receivedBody).contains("name=\"label\"").contains("Confidential");+ assertThat(receivedBody).contains("name=\"class\"").contains("invoice");+ assertThat(receivedBody).contains("name=\"pages\"").contains("2");+ assertThat(receivedBody).containsPattern("name=\"sha256\"[\\s\\S]{0,24}[0-9a-f]{64}");+ // The document itself, under the field name the vendor expects.+ assertThat(receivedBody).contains("name=\"file\"; filename=\"claim.pdf\"").contains("%PDF");+ // The context, including which policy and run sent it.+ assertThat(receivedBody)+ .contains("stirlingContext")+ .contains("Outbound review")+ .contains("run-42");++ JsonNode report =+ objectMapper.readTree(+ response.getHeaders().getFirst(AiToolResponseHeaders.TOOL_REPORT));+ assertThat(report.at("/status").asInt()).isEqualTo(200);+ assertThat(report.at("/body/verdict").asString()).isEqualTo("clean");+ }++ @Test+ void reportModeReturnsTheDocumentUntouched() throws IOException {+ connection(Map.of());++ ResponseEntity<Resource> response = step().path("/v1/scan").go();++ // Byte-for-byte: an inspecting call-out must not perturb what it inspected.+ assertThat(response.getBody().getInputStream().readAllBytes())+ .startsWith("%PDF".getBytes());+ assertThat(response.getHeaders().getFirst("Content-Disposition")).contains("claim.pdf");+ }++ @Test+ void replaceModeAdoptsTheReturnedDocumentAndItsRealName() throws IOException {+ connection(Map.of());++ ResponseEntity<Resource> response =+ step().path("/v1/convert").bodyMode("binary").responseMode("replace").go();++ assertThat(receivedContentType).isEqualTo("application/pdf");+ assertThat(receivedBody).startsWith("%PDF");+ assertThat(response.getBody().getInputStream().readAllBytes())+ .isEqualTo("DOCX-BYTES".getBytes(StandardCharsets.UTF_8));+ // Named for what came back, not what went out: a DOCX must not be called .pdf.+ assertThat(response.getHeaders().getFirst("Content-Disposition"))+ .contains("converted.docx");+ }++ @Test+ void followsAResultUrlOnTheConnectionsOwnHost() throws IOException {+ connection(Map.of());++ ResponseEntity<Resource> response =+ step().path("/v1/deferred")+ .responseMode("replace")+ .resultUrlPath("data.downloadUrl")+ .go();++ assertThat(response.getBody().getInputStream().readAllBytes())+ .isEqualTo("%PDF-1.7 fetched".getBytes(StandardCharsets.UTF_8));+ }++ @Test+ void refusesAResultUrlTheConnectionNeverAuthorised() {+ connection(Map.of());++ // The URL is chosen by the remote service at run time; obeying it would be an SSRF.+ assertThatThrownBy(+ () ->+ step().path("/v1/evil")+ .responseMode("replace")+ .resultUrlPath("data.downloadUrl")+ .go())+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("does not allow");+ }++ @Test+ void picksTheWantedFileOutOfAReturnedArchive() throws IOException {+ connection(Map.of());++ ResponseEntity<Resource> response =+ step().path("/v1/bundle").responseMode("replace").responseSelect("*.pdf").go();++ assertThat(response.getBody().getInputStream().readAllBytes())+ .isEqualTo("%PDF-1.7 signed".getBytes(StandardCharsets.UTF_8));+ }++ @Test+ void anUnselectedArchiveFailsRatherThanBecomingTheDocument() {+ connection(Map.of());++ // Handing a .zip to a step that expects a PDF fails later and more obscurely.+ assertThatThrownBy(() -> step().path("/v1/bundle").responseMode("replace").go())+ .isInstanceOf(IOException.class)+ .hasMessageContaining("responseSelect");+ }++ @Test+ void aRejectedCallOutFailsTheStep() {+ connection(Map.of());++ // A policy that continued past a rejection would deliver documents the external system+ // believes it never approved.+ assertThatThrownBy(() -> step().path("/v1/reject").go())+ .isInstanceOf(IOException.class)+ .hasMessageContaining("HTTP 422")+ .hasMessageContaining("policy violation");+ }++ @Test+ void aCleanVerdictLetsTheDocumentThrough() throws IOException {+ connection(Map.of());++ // Cloudmersive answers HTTP 200 whether clean or not; the verdict is in the body. A clean+ // result must pass the document through untouched.+ ResponseEntity<Resource> response =+ step().path("/v1/clean").requireTrue("CleanResult").go();++ assertThat(response.getBody().getInputStream().readAllBytes())+ .startsWith("%PDF".getBytes());+ }++ @Test+ void anInfectedVerdictStopsTheRunEvenOnHttp200() {+ connection(Map.of());++ // The whole security proposition: HTTP 200 with CleanResult=false must NOT sail through.+ assertThatThrownBy(() -> step().path("/v1/infected").requireTrue("CleanResult").go())+ .isInstanceOf(IOException.class)+ .hasMessageContaining("CleanResult")+ .hasMessageContaining("not true");+ }++ @Test+ void aMissingVerdictFieldFailsClosed() {+ connection(Map.of());++ // /v1/scan answers {"verdict":"clean"} - it has no CleanResult field at all. A gate that+ // cannot find its verdict must stop the run, not wave the document through.+ assertThatThrownBy(() -> step().path("/v1/scan").requireTrue("CleanResult").go())+ .isInstanceOf(IOException.class)+ .hasMessageContaining("not true");+ }++ @Test+ void sendsAVendorShapedJsonBodyWithTheDocumentNestedInside() throws IOException {+ connection(Map.of());++ // ConsignO's submit shape: the PDF base64'd into documents[0].data.+ step().path("/v1/scan")+ .bodyMode("json")+ .bodyTemplate(+ "{\"name\":\"{{document.filename}}\",\"status\":1,"+ + "\"documents\":[{\"name\":\"{{document.filename}}\",\"data\":\"{{document.base64}}\"}],"+ + "\"actions\":[{\"mode\":\"remote\",\"signer\":{\"type\":\"certifio\"}}]}")+ .go();++ assertThat(receivedContentType).isEqualTo("application/json");+ JsonNode sent = objectMapper.readTree(receivedBody);+ assertThat(sent.at("/name").asString()).isEqualTo("claim.pdf");+ // Numbers keep their type; only strings are substituted.+ assertThat(sent.at("/status").isNumber()).isTrue();+ assertThat(sent.at("/actions/0/signer/type").asString()).isEqualTo("certifio");+ assertThat(Base64.getDecoder().decode(sent.at("/documents/0/data").asString()))+ .startsWith("%PDF".getBytes(StandardCharsets.UTF_8));+ }++ @Test+ void appliesTheConnectionsCredentialAndTheStepsHeadersAndVerb() throws IOException {+ connection(Map.of("authType", "BEARER", "token", "s3cr3t-token"));++ step().path("/v1/scan")+ .method("PUT")+ .headers("{\"X-Case-Id\":\"{{run.runId}}\"}")+ .run(null, "run-99")+ .go();++ assertThat(receivedMethod).isEqualTo("PUT");+ assertThat(receivedHeaders.get("X-case-id")).isEqualTo("run-99");+ // The connection's credential, which the step never supplies or sees.+ assertThat(receivedHeaders.get("Authorization")).isEqualTo("Bearer s3cr3t-token");+ }++ @Test+ void aStepCannotAimTheCallAtAnotherHost() {+ connection(Map.of());++ assertThatThrownBy(() -> step().path("//evil.example/x").go())+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("must be relative");+ }++ @Test+ void notifyStyleCallOutSendsTheFactsWithoutTheDocument() throws IOException {+ connection(Map.of());++ Step notify = step().path("/v1/scan").bodyMode("json").includeContext(true);+ notify.includeFile = false;+ notify.run("Outbound review", "run-7").go();++ JsonNode sent = objectMapper.readTree(receivedBody);+ assertThat(sent.at("/document/filename").asString()).isEqualTo("claim.pdf");+ assertThat(sent.at("/run/policyName").asString()).isEqualTo("Outbound review");+ // No document: the point of a notification is the facts, not the bytes.+ assertThat(sent.has("content")).isFalse();+ assertThat(receivedBody).doesNotContain("%PDF");+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallerAuthHeaderTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallerAuthHeaderTest.javanew file mode 100644index 0000000000..47aed03ae2--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallerAuthHeaderTest.java@@ -0,0 +1,145 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThat;++import java.io.IOException;+import java.net.InetSocketAddress;+import java.net.http.HttpClient;+import java.nio.charset.StandardCharsets;+import java.util.LinkedHashMap;+import java.util.Map;+import java.util.concurrent.ConcurrentHashMap;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import com.sun.net.httpserver.HttpServer;++import stirling.software.common.model.ApplicationProperties;++import tools.jackson.databind.ObjectMapper;++/**+ * Asserts the credential header {@link ExternalApiCaller} actually puts on the wire for each auth+ * shape, against a real local server.+ *+ * <p>The interesting case is {@code headerPrefix}. Vendors disagree about the scheme in front of a+ * token - PandaDoc wants {@code API-Key}, Rossum {@code token}, DeepL {@code DeepL-Auth-Key} - and+ * without it every one of those presets would have to make the operator paste the scheme into the+ * secret field, where a missing space silently becomes a 401.+ */+class ExternalApiCallerAuthHeaderTest {++ private HttpServer server;+ private String baseUrl;+ private final Map<String, String> seen = new ConcurrentHashMap<>();+ private final ObjectMapper objectMapper = new ObjectMapper();++ @BeforeEach+ void startServer() throws IOException {+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ server.createContext(+ "/ingest",+ exchange -> {+ seen.clear();+ exchange.getRequestHeaders()+ .forEach(+ (name, values) ->+ seen.put(+ name.toLowerCase(java.util.Locale.ROOT),+ String.join(", ", values)));+ exchange.getRequestBody().readAllBytes();+ byte[] body = "{\"ok\":true}".getBytes(StandardCharsets.UTF_8);+ exchange.getResponseHeaders().add("Content-Type", "application/json");+ exchange.sendResponseHeaders(200, body.length);+ exchange.getResponseBody().write(body);+ exchange.close();+ });+ server.start();+ baseUrl = "http://127.0.0.1:" + server.getAddress().getPort();+ }++ @AfterEach+ void stopServer() {+ server.stop(0);+ }++ @Test+ void headerAuthWithPrefixSendsSchemeAndToken() throws IOException {+ post(+ connection(+ Map.of(+ "authType",+ "HEADER",+ "headerName",+ "Authorization",+ "headerPrefix",+ "API-Key",+ "token",+ "pd-secret")));++ assertThat(seen).containsEntry("authorization", "API-Key pd-secret");+ }++ @Test+ void headerAuthWithoutPrefixSendsTheBareToken() throws IOException {+ post(+ connection(+ Map.of(+ "authType",+ "HEADER",+ "headerName",+ "x-api-key",+ "token",+ "sk-ant-secret")));++ // No scheme invented: a vendor that wants the raw key must receive exactly that.+ assertThat(seen).containsEntry("x-api-key", "sk-ant-secret");+ assertThat(seen).doesNotContainKey("authorization");+ }++ @Test+ void bearerAuthIsUnaffectedByAPrefix() throws IOException {+ // headerPrefix belongs to HEADER auth; BEARER must keep its own scheme regardless.+ post(+ connection(+ Map.of(+ "authType",+ "BEARER",+ "headerPrefix",+ "API-Key",+ "token",+ "sk-secret")));++ assertThat(seen).containsEntry("authorization", "Bearer sk-secret");+ }++ private void post(ApiConnectionSettings settings) throws IOException {+ ExternalApiCaller.Response response =+ caller().dispatch(+ settings,+ "POST",+ "/ingest",+ ExternalApiCaller.raw(+ "application/json", "{}".getBytes(StandardCharsets.UTF_8)),+ Map.of());+ assertThat(response.isSuccess()).isTrue();+ }++ private ApiConnectionSettings connection(Map<String, Object> options) {+ Map<String, Object> config = new LinkedHashMap<>(options);+ config.put("baseUrl", baseUrl);+ return ApiConnectionSettings.from(config);+ }++ private ExternalApiCaller caller() {+ ApplicationProperties properties = new ApplicationProperties();+ // The server is on loopback, which is exactly what the guard blocks by default.+ properties.getPolicies().setAllowPrivateApiEndpoints(true);+ return new ExternalApiCaller(+ HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build(),+ properties,+ objectMapper);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallerTokenLoginTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallerTokenLoginTest.javanew file mode 100644index 0000000000..7cfbb8cbe4--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiCallerTokenLoginTest.java@@ -0,0 +1,296 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.io.IOException;+import java.net.InetSocketAddress;+import java.net.http.HttpClient;+import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.Base64;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.atomic.AtomicInteger;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import com.sun.net.httpserver.HttpExchange;+import com.sun.net.httpserver.HttpServer;++import stirling.software.common.model.ApplicationProperties;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ObjectNode;++/**+ * Drives {@link ExternalApiCaller} against a real local HTTP server shaped like ConsignO Cloud's+ * auth: credentials in headers plus a JSON body, and the token handed back only in the {@code+ * X-Auth-Token} <em>response header</em>.+ *+ * <p>A real server rather than a mock, because what is being tested is the wire behaviour - that+ * the token is found in a header, reused rather than re-fetched, and re-obtained on a 401.+ */+class ExternalApiCallerTokenLoginTest {++ private HttpServer server;+ private String baseUrl;+ private final AtomicInteger logins = new AtomicInteger();+ private final List<Map<String, String>> callHeaders = new ArrayList<>();+ private final ObjectMapper objectMapper = new ObjectMapper();+ private volatile String issuedToken = "token-1";+ private volatile boolean rejectToken;+ private volatile String workflowBody;++ @BeforeEach+ void startServer() throws IOException {+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);++ server.createContext(+ "/api/v1/auth/login",+ exchange -> {+ logins.incrementAndGet();+ String body =+ new String(+ exchange.getRequestBody().readAllBytes(),+ StandardCharsets.UTF_8);+ // The vendor authenticates the app by header and the user by body.+ if (!"client-abc".equals(exchange.getRequestHeaders().getFirst("X-Client-Id"))+ || !"client-xyz"+ .equals(+ exchange.getRequestHeaders()+ .getFirst("X-Client-Secret"))+ || !body.contains("\"password\":\"s3cr3t\"")+ || !body.contains("\"tenantId\":\"acme\"")) {+ respond(exchange, 401, "{}");+ return;+ }+ exchange.getResponseHeaders().add("X-Auth-Token", issuedToken);+ respond(exchange, 200, "{\"msg\":\"ok\"}");+ });++ server.createContext(+ "/api/v1/documents",+ exchange -> {+ Map<String, String> headers = new LinkedHashMap<>();+ exchange.getRequestHeaders()+ .forEach((name, values) -> headers.put(name, values.get(0)));+ callHeaders.add(headers);+ String token = exchange.getRequestHeaders().getFirst("X-Auth-Token");+ if (rejectToken || token == null || !token.equals(issuedToken)) {+ respond(exchange, 401, "{\"msg\":\"expired\"}");+ return;+ }+ respond(+ exchange,+ 201,+ "{\"response\":{\"metadata\":{\"documentId\":\"doc-9\"}}}");+ });++ server.createContext(+ "/api/v1/workflows",+ exchange -> {+ if (!issuedToken.equals(+ exchange.getRequestHeaders().getFirst("X-Auth-Token"))) {+ respond(exchange, 401, "{\"msg\":\"expired\"}");+ return;+ }+ workflowBody =+ new String(+ exchange.getRequestBody().readAllBytes(),+ StandardCharsets.UTF_8);+ respond(exchange, 201, "{\"response\":{\"id\":\"wf-7\",\"status\":1}}");+ });++ server.start();+ baseUrl = "http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1";+ }++ @AfterEach+ void stopServer() {+ server.stop(0);+ }++ private static void respond(HttpExchange exchange, int status, String body) throws IOException {+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);+ exchange.getResponseHeaders().add("Content-Type", "application/json");+ exchange.sendResponseHeaders(status, bytes.length);+ exchange.getResponseBody().write(bytes);+ exchange.close();+ }++ private ExternalApiCaller caller() {+ ApplicationProperties properties = new ApplicationProperties();+ // The server is on loopback, which is exactly what the guard blocks by default.+ properties.getPolicies().setAllowPrivateApiEndpoints(true);+ return new ExternalApiCaller(+ HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).build(),+ properties,+ objectMapper);+ }++ /** The ConsignO connection an operator would configure. */+ private ApiConnectionSettings consignoConnection() {+ Map<String, Object> config = new LinkedHashMap<>();+ config.put("baseUrl", baseUrl);+ config.put("authType", "TOKEN_LOGIN");+ config.put("loginPath", "/auth/login");+ config.put(+ "loginBody",+ Map.of("username", "[email protected]", "password", "s3cr3t", "tenantId", "acme"));+ config.put(+ "loginHeaders",+ Map.of("X-Client-Id", "client-abc", "X-Client-Secret", "client-xyz"));+ config.put("tokenResponseHeader", "X-Auth-Token");+ config.put("tokenHeaderName", "X-Auth-Token");+ return ApiConnectionSettings.from(config);+ }++ private ExternalApiCaller.Response upload(ExternalApiCaller caller) throws IOException {+ return caller.postFile(+ consignoConnection(),+ "/documents",+ "file",+ "contract.pdf",+ "application/pdf",+ "%PDF-1.7".getBytes(StandardCharsets.UTF_8),+ Map.of());+ }++ @Test+ void logsInAndSendsTheTokenFromTheResponseHeader() throws IOException {+ ExternalApiCaller.Response response = upload(caller());++ assertThat(response.status()).isEqualTo(201);+ assertThat(response.bodyAsText()).contains("doc-9");+ assertThat(logins.get()).isEqualTo(1);+ // The token was found in a response header and presented on the next call.+ assertThat(callHeaders)+ .singleElement()+ .extracting(h -> h.get("X-auth-token"))+ .isEqualTo("token-1");+ }++ @Test+ void reusesTheTokenAcrossCallsRatherThanLoggingInPerDocument() throws IOException {+ ExternalApiCaller caller = caller();+ upload(caller);+ upload(caller);+ upload(caller);++ // A 100-document policy must not perform 100 logins.+ assertThat(logins.get()).isEqualTo(1);+ assertThat(callHeaders).hasSize(3);+ }++ @Test+ void reAuthenticatesOnceWhenTheTokenIsRejected() throws IOException {+ ExternalApiCaller caller = caller();+ upload(caller);+ assertThat(logins.get()).isEqualTo(1);++ // The vendor expires the token early and starts issuing a new one.+ issuedToken = "token-2";+ ExternalApiCaller.Response response = upload(caller);++ assertThat(response.status()).isEqualTo(201);+ assertThat(logins.get()).isEqualTo(2);+ assertThat(callHeaders).last().extracting(h -> h.get("X-auth-token")).isEqualTo("token-2");+ }++ @Test+ void aPersistent401SurfacesRatherThanLoopingForever() throws IOException {+ rejectToken = true;++ ExternalApiCaller.Response response = upload(caller());++ assertThat(response.status()).isEqualTo(401);+ // Exactly one retry: the initial login plus one re-auth, then give up.+ assertThat(logins.get()).isEqualTo(2);+ }++ /**+ * The whole ConsignO submit, as an operator would configure it: log in, then post their real+ * workflow shape with the PDF base64'd into {@code documents[0].data}. Their API takes the+ * document inline, so {@code POST /documents} is not needed and the submit is a single call -+ * which is what brings it within reach of the generic step.+ */+ @Test+ void submitsAConsignoSignatureWorkflowEndToEnd() throws IOException {+ byte[] pdf = "%PDF-1.7 contract".getBytes(StandardCharsets.UTF_8);+ ObjectNode context = objectMapper.createObjectNode();+ ObjectNode document = context.putObject("document");+ document.put("filename", "contract.pdf");+ document.put("base64", Base64.getEncoder().encodeToString(pdf));++ String template =+ """+ {+ "name": "{{document.filename}}",+ "status": 1,+ "documents": [+ {"name": "{{document.filename}}", "data": "{{document.base64}}"}+ ],+ "actions": [+ {"mode":"remote","ref":"1",+ "signer":{"type":"certifio","email":"[email protected]","lang":"en"}}+ ]+ }+ """;+ JsonNode body = Placeholders.resolveTree(objectMapper.readTree(template), context);++ ExternalApiCaller.Response response =+ caller().dispatch(+ consignoConnection(),+ "POST",+ "/workflows",+ ExternalApiCaller.raw(+ "application/json", objectMapper.writeValueAsBytes(body)),+ Map.of());++ assertThat(response.status()).isEqualTo(201);+ // The workflow id the vendor hands back - the thing a later fetch would need, and which a+ // step currently has no way to carry to the next step.+ assertThat(objectMapper.readTree(response.bodyAsText()).at("/response/id").asString())+ .isEqualTo("wf-7");+ assertThat(logins.get()).isEqualTo(1);++ // The document really arrived, nested where ConsignO expects it.+ JsonNode received = objectMapper.readTree(workflowBody);+ assertThat(received.at("/actions/0/signer/type").asString()).isEqualTo("certifio");+ assertThat(Base64.getDecoder().decode(received.at("/documents/0/data").asString()))+ .isEqualTo(pdf);+ }++ @Test+ void badCredentialsFailTheStepWithoutEchoingThem() {+ Map<String, Object> config = new LinkedHashMap<>();+ config.put("baseUrl", baseUrl);+ config.put("authType", "TOKEN_LOGIN");+ config.put("loginPath", "/auth/login");+ config.put("loginBody", Map.of("username", "[email protected]", "password", "wrong"));+ config.put("loginHeaders", Map.of("X-Client-Id", "client-abc", "X-Client-Secret", "nope"));+ config.put("tokenResponseHeader", "X-Auth-Token");+ config.put("tokenHeaderName", "X-Auth-Token");+ ApiConnectionSettings settings = ApiConnectionSettings.from(config);++ assertThatThrownBy(+ () ->+ caller().postFile(+ settings,+ "/documents",+ "file",+ "c.pdf",+ "application/pdf",+ "%PDF".getBytes(StandardCharsets.UTF_8),+ Map.of()))+ .isInstanceOf(IOException.class)+ .hasMessageContaining("returned HTTP 401")+ // The login body is echoed by some vendors; the message must not carry it onward.+ .hasMessageNotContaining("wrong");+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiPathsTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiPathsTest.javanew file mode 100644index 0000000000..e03b330095--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ExternalApiPathsTest.java@@ -0,0 +1,135 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.net.URI;++import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Nested;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++/**+ * {@link ExternalApiPaths} is the control that stops the external-API step becoming an SSRF+ * primitive, so these lean on the ways a step author might try to leave the connection's base URL.+ */+class ExternalApiPathsTest {++ private static final URI BASE = URI.create("https://api.example.com/v1");++ @Nested+ @DisplayName("resolves paths under the base")+ class Resolves {++ @Test+ void appendsARelativePath() {+ assertThat(ExternalApiPaths.resolve(BASE, "/scan"))+ .isEqualTo(URI.create("https://api.example.com/v1/scan"));+ }++ @Test+ void addsTheLeadingSlashWhenOmitted() {+ assertThat(ExternalApiPaths.resolve(BASE, "scan"))+ .isEqualTo(URI.create("https://api.example.com/v1/scan"));+ }++ @Test+ void blankPathIsTheBaseItself() {+ assertThat(ExternalApiPaths.resolve(BASE, " ")).isEqualTo(BASE);+ assertThat(ExternalApiPaths.resolve(BASE, null)).isEqualTo(BASE);+ }++ @Test+ void keepsAQueryString() {+ assertThat(ExternalApiPaths.resolve(BASE, "/scan?mode=strict"))+ .isEqualTo(URI.create("https://api.example.com/v1/scan?mode=strict"));+ }++ @Test+ void allowsATraversalThatStaysUnderTheBase() {+ // "/v1/a/../b" normalises to "/v1/b", which is still under the base.+ assertThat(ExternalApiPaths.resolve(BASE, "/a/../b"))+ .isEqualTo(URI.create("https://api.example.com/v1/b"));+ }++ @Test+ void baseWithNoPathAcceptsAnyPath() {+ assertThat(ExternalApiPaths.resolve(URI.create("https://api.example.com"), "/scan"))+ .isEqualTo(URI.create("https://api.example.com/scan"));+ }++ @Test+ void keepsAnEncodedSlashFromASubstitutedValue() {+ // Placeholders percent-encodes what it substitutes, so a filename containing '/'+ // arrives as %2F. That is data inside one segment and must survive.+ assertThat(ExternalApiPaths.resolve(BASE, "/docs/my%2Ffile.pdf"))+ .isEqualTo(URI.create("https://api.example.com/v1/docs/my%2Ffile.pdf"));+ }+ }++ @Nested+ @DisplayName("refuses to leave the base")+ class Refuses {++ @Test+ void protocolRelativeUrlCannotChangeHost() {+ // The reason URI.resolve is not used: it would yield https://evil.example/x here.+ assertThatThrownBy(() -> ExternalApiPaths.resolve(BASE, "//evil.example/x"))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("must be relative");+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "https://evil.example/x",+ "http://evil.example/x",+ "HTTPS://evil.example/x",+ "file:///etc/passwd"+ })+ void absoluteUrlIsRejected(String path) {+ assertThatThrownBy(() -> ExternalApiPaths.resolve(BASE, path))+ .isInstanceOf(IllegalArgumentException.class);+ }++ @Test+ void traversalAboveTheBasePathIsRejected() {+ assertThatThrownBy(() -> ExternalApiPaths.resolve(BASE, "/../admin"))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("escapes");+ }++ @Test+ void percentEncodedTraversalIsRejected() {+ // normalize() would not decode these, so the target server would do the escaping.+ assertThatThrownBy(() -> ExternalApiPaths.resolve(BASE, "/%2e%2e/admin"))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("percent-encode");+ }++ @ParameterizedTest+ @ValueSource(strings = {"/scan\r\nX-Injected: 1", "/scan\nfoo", "/sc an", "/scan\\..\\x"})+ void requestSplittingCharactersAreRejected(String path) {+ assertThatThrownBy(() -> ExternalApiPaths.resolve(BASE, path))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("illegal character");+ }++ @Test+ void siblingPathThatMerelySharesAPrefixIsRejected() {+ // "/v1betray" starts with "/v1" textually but is a different resource tree.+ assertThatThrownBy(() -> ExternalApiPaths.resolve(BASE, "/../v1betray/x"))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("escapes");+ }++ @Test+ void fragmentIsRejected() {+ assertThatThrownBy(() -> ExternalApiPaths.resolve(BASE, "/scan#frag"))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("fragment");+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/MultipartBodyTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/MultipartBodyTest.javanew file mode 100644index 0000000000..c059de14d4--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/MultipartBodyTest.java@@ -0,0 +1,111 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.Map;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++/**+ * The name/value asymmetry here is easy to get wrong in either direction: too lax on names is+ * header injection, too strict on values silently rejects ordinary JSON.+ */+class MultipartBodyTest {++ private static String render(MultipartBody body) throws IOException {+ // The publisher is what actually goes on the wire.+ java.net.http.HttpRequest.BodyPublisher publisher = body.build();+ StringBuilder out = new StringBuilder();+ publisher.subscribe(+ new java.util.concurrent.Flow.Subscriber<>() {+ @Override+ public void onSubscribe(java.util.concurrent.Flow.Subscription s) {+ s.request(Long.MAX_VALUE);+ }++ @Override+ public void onNext(java.nio.ByteBuffer item) {+ byte[] bytes = new byte[item.remaining()];+ item.get(bytes);+ out.append(new String(bytes, StandardCharsets.UTF_8));+ }++ @Override+ public void onError(Throwable t) {}++ @Override+ public void onComplete() {}+ });+ return out.toString();+ }++ @Test+ void carriesAJsonValueThroughUntouched() throws IOException {+ // Regression: values were once checked like headers, which rejected every JSON value —+ // including the auto-populated context, so includeContext could never be sent.+ String json = "{\"document\":{\"title\":\"Q3 \\\"final\\\"\"},\"n\":2}";+ MultipartBody body = new MultipartBody();+ body.addField("stirlingContext", json);++ assertThat(render(body)).contains(json);+ }++ @Test+ void carriesAValueWithNewlinesAndBackslashes() throws IOException {+ MultipartBody body = new MultipartBody();+ body.addField("notes", "line one\nline two\\end");++ assertThat(render(body)).contains("line one\nline two\\end");+ }++ @Test+ void writesTheDocumentUnderItsFieldNameAndFilename() throws IOException {+ MultipartBody body = new MultipartBody();+ body.addFields(Map.of("policy", "strict"));+ body.addFile(+ "file",+ "claim.pdf",+ "application/pdf",+ "%PDF-1.7".getBytes(StandardCharsets.UTF_8));++ String rendered = render(body);+ assertThat(rendered).contains("name=\"policy\"").contains("strict");+ assertThat(rendered)+ .contains("name=\"file\"; filename=\"claim.pdf\"")+ .contains("Content-Type: application/pdf")+ .contains("%PDF-1.7");+ assertThat(body.contentType()).startsWith("multipart/form-data; boundary=StirlingBoundary");+ }++ @ParameterizedTest+ @ValueSource(strings = {"na\"me", "na\rme", "na\nme", "na\\me"})+ void refusesAFieldNameThatCouldForgeItsOwnHeaders(String name) {+ MultipartBody body = new MultipartBody();++ assertThatThrownBy(() -> body.addField(name, "v"))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("illegal character");+ }++ @ParameterizedTest+ @ValueSource(strings = {"a\".pdf", "a\r.pdf", "a\n.pdf"})+ void refusesAFilenameThatCouldForgeItsOwnHeaders(String filename) {+ MultipartBody body = new MultipartBody();++ assertThatThrownBy(() -> body.addFile("file", filename, "application/pdf", new byte[] {1}))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("illegal character");+ }++ @Test+ void eachBodyGetsItsOwnBoundary() {+ // A value cannot end its own part because it cannot know the boundary in advance.+ assertThat(new MultipartBody().contentType())+ .isNotEqualTo(new MultipartBody().contentType());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/PlaceholdersTemplateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/PlaceholdersTemplateTest.javanew file mode 100644index 0000000000..3d91d0230f--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/PlaceholdersTemplateTest.java@@ -0,0 +1,110 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.util.Base64;++import org.junit.jupiter.api.Test;++import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ObjectNode;++/**+ * Body templating is what decides whether a vendor with a nested payload needs bespoke code, so the+ * headline case here is ConsignO Cloud's real {@code POST /workflows} shape.+ */+class PlaceholdersTemplateTest {++ private final ObjectMapper objectMapper = new ObjectMapper();++ private ObjectNode context() {+ ObjectNode root = objectMapper.createObjectNode();+ ObjectNode document = root.putObject("document");+ document.put("filename", "contract.pdf");+ document.put("base64", Base64.getEncoder().encodeToString("%PDF-1.7".getBytes()));+ document.put("pageCount", 4);+ root.putObject("run").put("policyName", "Signature run");+ root.putObject("sensitivityLabel").put("name", "Confidential");+ return root;+ }++ private JsonNode resolve(String template) {+ return Placeholders.resolveTree(objectMapper.readTree(template), context());+ }++ @Test+ void buildsConsignOsWorkflowPayload() {+ // Lifted from the ConsignO Cloud API reference: the document rides base64 in+ // documents[0].data, and `certifio` is the Notarius professional-certificate signer.+ String template =+ """+ {+ "name": "{{document.filename}}",+ "status": 1,+ "documents": [+ {"name": "{{document.filename}}", "data": "{{document.base64}}"}+ ],+ "actions": [+ {+ "mode": "remote",+ "ref": "1",+ "signer": {+ "type": "certifio",+ "email": "[email protected]",+ "lang": "en"+ }+ }+ ]+ }+ """;++ JsonNode body = resolve(template);++ assertThat(body.at("/name").asString()).isEqualTo("contract.pdf");+ // Numbers and booleans keep their type; only strings are substituted.+ assertThat(body.at("/status").isNumber()).isTrue();+ assertThat(body.at("/status").asInt()).isEqualTo(1);+ assertThat(body.at("/documents/0/name").asString()).isEqualTo("contract.pdf");+ assertThat(new String(Base64.getDecoder().decode(body.at("/documents/0/data").asString())))+ .isEqualTo("%PDF-1.7");+ assertThat(body.at("/actions/0/signer/type").asString()).isEqualTo("certifio");+ assertThat(body.at("/actions/0/ref").asString()).isEqualTo("1");+ }++ @Test+ void resolvesInsideNestedObjectsAndArrays() {+ JsonNode body =+ resolve(+ "{\"a\":{\"b\":[{\"c\":\"{{document.filename}}\"},"+ + "\"{{run.policyName}}\"]}}");++ assertThat(body.at("/a/b/0/c").asString()).isEqualTo("contract.pdf");+ assertThat(body.at("/a/b/1").asString()).isEqualTo("Signature run");+ }++ @Test+ void leavesNonStringsAlone() {+ JsonNode body = resolve("{\"n\":3,\"b\":true,\"z\":null,\"arr\":[1,2]}");++ assertThat(body.at("/n").asInt()).isEqualTo(3);+ assertThat(body.at("/b").asBoolean()).isTrue();+ assertThat(body.at("/z").isNull()).isTrue();+ assertThat(body.at("/arr/1").asInt()).isEqualTo(2);+ }++ @Test+ void substitutesWithinSurroundingText() {+ JsonNode body = resolve("{\"subject\":\"{{run.policyName}}: {{document.filename}}\"}");++ assertThat(body.at("/subject").asString()).isEqualTo("Signature run: contract.pdf");+ }++ @Test+ void aTypoInATemplateIsAnErrorNotASilentlyEmptyPayload() {+ assertThatThrownBy(() -> resolve("{\"x\":\"{{document.flename}}\"}"))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("unknown placeholder");+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/PlaceholdersTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/PlaceholdersTest.javanew file mode 100644index 0000000000..cd82e7997f--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/PlaceholdersTest.java@@ -0,0 +1,127 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.net.URI;++import org.junit.jupiter.api.Test;++import stirling.software.proprietary.integration.api.Placeholders.Escaping;++import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ObjectNode;++class PlaceholdersTest {++ private final ObjectMapper objectMapper = new ObjectMapper();++ private ObjectNode context() {+ ObjectNode root = objectMapper.createObjectNode();+ ObjectNode document = root.putObject("document");+ document.put("filename", "invoice.pdf");+ document.put("sha256", "abc123");+ document.put("pageCount", 3);+ document.putNull("title");+ ObjectNode label = root.putObject("sensitivityLabel");+ label.put("name", "Confidential");+ root.putObject("run").put("policyName", "Outbound review");+ return root;+ }++ @Test+ void substitutesADottedPath() {+ assertThat(Placeholders.resolve("{{document.filename}}", context(), Escaping.NONE))+ .isEqualTo("invoice.pdf");+ }++ @Test+ void substitutesSeveralWithSurroundingText() {+ assertThat(+ Placeholders.resolve(+ "{{document.filename}} ({{document.pageCount}}p) is"+ + " {{sensitivityLabel.name}}",+ context(),+ Escaping.NONE))+ .isEqualTo("invoice.pdf (3p) is Confidential");+ }++ @Test+ void toleratesWhitespaceInsideBraces() {+ assertThat(Placeholders.resolve("{{ document.sha256 }}", context(), Escaping.NONE))+ .isEqualTo("abc123");+ }++ @Test+ void aNullValueRendersEmptyNotTheWordNull() {+ // "null" in a vendor's field would read as a value rather than an absence.+ assertThat(Placeholders.resolve("[{{document.title}}]", context(), Escaping.NONE))+ .isEqualTo("[]");+ }++ @Test+ void textWithNoPlaceholderIsUntouched() {+ assertThat(Placeholders.resolve("/scan", context(), Escaping.NONE)).isEqualTo("/scan");+ assertThat(Placeholders.resolve(null, context(), Escaping.NONE)).isNull();+ }++ @Test+ void anUnknownPathIsAnErrorRatherThanAnEmptyValue() {+ // A typo that silently sent "" could mean an external system files a document wrongly.+ assertThatThrownBy(+ () -> Placeholders.resolve("{{document.nope}}", context(), Escaping.NONE))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("unknown placeholder");+ assertThatThrownBy(() -> Placeholders.resolve("{{nope.at.all}}", context(), Escaping.NONE))+ .isInstanceOf(IllegalArgumentException.class);+ }++ @Test+ void anObjectRendersAsJson() {+ assertThat(Placeholders.resolve("{{sensitivityLabel}}", context(), Escaping.NONE))+ .isEqualTo("{\"name\":\"Confidential\"}");+ }++ @Test+ void pathEscapingEncodesSeparatorsButNotDots() {+ ObjectNode context = context();+ context.putObject("x").put("weird", "a/b c.pdf");++ // The dot survives (it is unreserved); the slash and space cannot pass as structure.+ assertThat(Placeholders.resolve("{{x.weird}}", context, Escaping.URL_PATH))+ .isEqualTo("a%2Fb%20c.pdf");+ }++ @Test+ void aTraversalInAValueIsNeutralisedRatherThanObeyed() {+ ObjectNode context = context();+ context.putObject("x").put("nasty", "../../admin");++ // Encoding the separators leaves one inert segment, so there is no traversal left to+ // normalise: the request stays under the base and the value arrives as data.+ String resolved = Placeholders.resolve("/docs/{{x.nasty}}", context, Escaping.URL_PATH);+ assertThat(resolved).isEqualTo("/docs/..%2F..%2Fadmin");++ assertThat(ExternalApiPaths.resolve(URI.create("https://api.example.com/v1"), resolved))+ .isEqualTo(URI.create("https://api.example.com/v1/docs/..%2F..%2Fadmin"));+ }++ @Test+ void aTraversalWrittenIntoTheTemplateItselfIsStillRejected() {+ // The operator's own text is not encoded, so a literal ".." normalises and the base check+ // sees it. This is why dots are deliberately left unencoded above.+ assertThatThrownBy(+ () ->+ ExternalApiPaths.resolve(+ URI.create("https://api.example.com/v1"), "/docs/../../x"))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("escapes");+ }++ @Test+ void detectsWhetherTextReferencesAnything() {+ assertThat(Placeholders.hasPlaceholder("{{a.b}}")).isTrue();+ assertThat(Placeholders.hasPlaceholder("plain")).isFalse();+ assertThat(Placeholders.hasPlaceholder(null)).isFalse();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ResultUrlsTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ResultUrlsTest.javanew file mode 100644index 0000000000..a46cd115a7--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/api/ResultUrlsTest.java@@ -0,0 +1,193 @@+package stirling.software.proprietary.integration.api;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.net.URI;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import stirling.software.common.model.ApplicationProperties;++/**+ * A result URL is picked by the remote service at run time, so these lean on the ways a hostile or+ * compromised integration might use that to aim a server-side fetch somewhere it should not go.+ */+class ResultUrlsTest {++ private final ApplicationProperties properties = new ApplicationProperties();++ private ApiConnectionSettings connection(List<String> resultUrlHosts) {+ Map<String, Object> config = new LinkedHashMap<>();+ config.put("baseUrl", "https://api.vendor.example/v1");+ if (resultUrlHosts != null) {+ config.put("resultUrlHosts", resultUrlHosts);+ }+ return ApiConnectionSettings.from(config);+ }++ // The host-matching rule is asserted directly: validate() also resolves the host, which fails+ // closed, so it cannot be exercised against reserved .example names without real DNS.++ @Test+ void allowsTheConnectionsOwnHostWithoutBeingDeclared() {+ assertThat(ResultUrls.isAllowedHost(connection(null), "api.vendor.example")).isTrue();+ }++ @Test+ void allowsADeclaredResultHost() {+ // The common real case: the API answers on one host, the file lives on a CDN.+ assertThat(+ ResultUrls.isAllowedHost(+ connection(List.of("cdn.vendor.example")), "cdn.vendor.example"))+ .isTrue();+ }++ @Test+ void allowsASubdomainOfADeclaredHost() {+ assertThat(+ ResultUrls.isAllowedHost(+ connection(List.of("vendor.example")), "files.eu.vendor.example"))+ .isTrue();+ }++ @Test+ void hostMatchingIsCaseInsensitive() {+ assertThat(+ ResultUrls.isAllowedHost(+ connection(List.of("CDN.Vendor.Example")), "cdn.vendor.example"))+ .isTrue();+ }++ @Test+ void anUnresolvableHostIsRefusedRatherThanAssumedSafe() {+ // Fail closed: if we cannot see where a name points, we cannot say it is not internal.+ assertThatThrownBy(+ () ->+ ResultUrls.validate(+ connection(null),+ "https://api.vendor.example/files/signed.pdf",+ properties))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("Unable to resolve");+ }++ @Test+ void fetchesFromAnAllowedHostThatResolves() {+ properties.getPolicies().setAllowPrivateApiEndpoints(true);+ Map<String, Object> config = new LinkedHashMap<>();+ config.put("baseUrl", "http://127.0.0.1:9000/v1");+ ApiConnectionSettings settings = ApiConnectionSettings.from(config);++ assertThat(+ ResultUrls.validate(+ settings, "http://127.0.0.1:9000/files/signed.pdf", properties))+ .isEqualTo(URI.create("http://127.0.0.1:9000/files/signed.pdf"));+ }++ @Test+ void refusesAnUndeclaredHost() {+ assertThatThrownBy(+ () ->+ ResultUrls.validate(+ connection(null), "https://evil.example/x.pdf", properties))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("does not allow");+ }++ @Test+ void refusesAHostThatMerelyEndsWithADeclaredOne() {+ // "evilvendor.example" must not be admitted by an entry of "vendor.example".+ assertThatThrownBy(+ () ->+ ResultUrls.validate(+ connection(List.of("vendor.example")),+ "https://evilvendor.example/x.pdf",+ properties))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("does not allow");+ }++ @Test+ void refusesTheCloudMetadataServiceEvenIfDeclared() {+ // The headline SSRF: an integration answering with the metadata address.+ assertThatThrownBy(+ () ->+ ResultUrls.validate(+ connection(List.of("169.254.169.254")),+ "http://169.254.169.254/latest/meta-data/iam/",+ properties))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("private/link-local");+ }++ @Test+ void refusesLoopbackEvenIfDeclared() {+ assertThatThrownBy(+ () ->+ ResultUrls.validate(+ connection(List.of("localhost")),+ "http://localhost:8080/admin",+ properties))+ .isInstanceOf(IllegalArgumentException.class);+ }++ @Test+ void anOperatorCanOptInToPrivateResultHostsForOnPrem() {+ properties.getPolicies().setAllowPrivateApiEndpoints(true);++ assertThat(+ ResultUrls.validate(+ connection(List.of("localhost")),+ "http://localhost:8080/files/signed.pdf",+ properties))+ .hasHost("localhost");+ }++ @ParameterizedTest+ @ValueSource(+ strings = {+ "file:///etc/passwd",+ "jar:file:///tmp/x.jar!/y",+ "gopher://evil.example/x",+ "ftp://evil.example/x"+ })+ void refusesNonHttpSchemes(String url) {+ // A URL fetch that accepts file: is a local file read.+ assertThatThrownBy(() -> ResultUrls.validate(connection(null), url, properties))+ .isInstanceOf(IllegalArgumentException.class);+ }++ @Test+ void refusesCredentialsEmbeddedInTheUrl() {+ assertThatThrownBy(+ () ->+ ResultUrls.validate(+ connection(List.of("cdn.vendor.example")),+ "https://user:[email protected]/x.pdf",+ properties))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("credentials");+ }++ @Test+ void refusesGarbage() {+ assertThatThrownBy(() -> ResultUrls.validate(connection(null), "not a url", properties))+ .isInstanceOf(IllegalArgumentException.class);+ }++ @Test+ void resultUrlHostsMustBeBareHostnames() {+ // A URL or wildcard here reads as broader than it is.+ assertThatThrownBy(() -> connection(List.of("https://cdn.vendor.example/x")))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("bare hostnames");+ assertThatThrownBy(() -> connection(List.of("*.vendor.example")))+ .isInstanceOf(IllegalArgumentException.class);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/purview/PdfSensitivityLabelsTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/purview/PdfSensitivityLabelsTest.javanew file mode 100644index 0000000000..7e563c371a--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/purview/PdfSensitivityLabelsTest.java@@ -0,0 +1,282 @@+package stirling.software.proprietary.integration.purview;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.io.ByteArrayInputStream;+import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.nio.charset.StandardCharsets;+import java.time.Instant;++import org.apache.pdfbox.Loader;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.common.PDMetadata;+import org.junit.jupiter.api.Test;++import stirling.software.proprietary.integration.purview.SensitivityLabel.AssignmentMethod;++/**+ * Exercises the label round-trip against real PDFBox documents, including a save/reload so the+ * assertions reflect what actually lands on disk rather than in-memory state.+ */+class PdfSensitivityLabelsTest {++ private static final String LABEL_ID = "2096f6a2-d2f7-48be-b329-b73aaa526e5d";+ private static final String TENANT = "cb46c030-1825-4e81-a295-151c039dbf02";++ private static PDDocument newDocument() {+ PDDocument document = new PDDocument();+ document.addPage(new PDPage());+ return document;+ }++ private static PDDocument saveAndReload(PDDocument document) throws IOException {+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ document.save(out);+ document.close();+ return Loader.loadPDF(new ByteArrayInputStream(out.toByteArray()).readAllBytes());+ }++ private static String xmpString(PDDocument document) throws IOException {+ PDMetadata metadata = document.getDocumentCatalog().getMetadata();+ if (metadata == null) {+ return "";+ }+ try (InputStream is = metadata.exportXMPMetadata()) {+ return new String(is.readAllBytes(), StandardCharsets.UTF_8);+ }+ }++ private static SensitivityLabel confidential() {+ return new SensitivityLabel(+ LABEL_ID,+ "Confidential",+ TENANT,+ AssignmentMethod.STANDARD,+ Instant.parse("2026-07-17T10:15:30Z"),+ SensitivityLabel.CONTENT_BITS_FOOTER);+ }++ @Test+ void appliedLabelSurvivesSaveAndReload() throws IOException {+ PDDocument document = newDocument();+ PdfSensitivityLabels.apply(document, confidential());++ try (PDDocument reloaded = saveAndReload(document)) {+ SensitivityLabel read = PdfSensitivityLabels.read(reloaded).orElseThrow();+ assertThat(read.labelId()).isEqualTo(LABEL_ID);+ assertThat(read.name()).isEqualTo("Confidential");+ assertThat(read.siteId()).isEqualTo(TENANT);+ assertThat(read.method()).isEqualTo(AssignmentMethod.STANDARD);+ assertThat(read.setDate()).isEqualTo(Instant.parse("2026-07-17T10:15:30Z"));+ assertThat(read.contentBits()).isEqualTo(SensitivityLabel.CONTENT_BITS_FOOTER);+ }+ }++ @Test+ void writesTheDocumentedKeyNamesIntoTheInfoDictionary() throws IOException {+ try (PDDocument document = newDocument()) {+ PdfSensitivityLabels.apply(document, confidential());++ var info = document.getDocumentInformation();+ String prefix = "MSIP_Label_" + LABEL_ID + "_";+ assertThat(info.getCustomMetadataValue(prefix + "Enabled")).isEqualTo("true");+ assertThat(info.getCustomMetadataValue(prefix + "SiteId")).isEqualTo(TENANT);+ assertThat(info.getCustomMetadataValue(prefix + "Method")).isEqualTo("Standard");+ assertThat(info.getCustomMetadataValue(prefix + "Name")).isEqualTo("Confidential");+ assertThat(info.getCustomMetadataValue(prefix + "ContentBits")).isEqualTo("2");+ // Extended ISO 8601, as the MIP contract specifies.+ assertThat(info.getCustomMetadataValue(prefix + "SetDate"))+ .isEqualTo("2026-07-17T10:15:30+0000");+ }+ }++ @Test+ void readsALabelPresentOnlyInTheInfoDictionary() throws IOException {+ // What a third-party labeller may leave behind: no XMP copy at all.+ try (PDDocument document = newDocument()) {+ var info = document.getDocumentInformation();+ String prefix = "MSIP_Label_" + LABEL_ID + "_";+ info.setCustomMetadataValue(prefix + "Enabled", "true");+ info.setCustomMetadataValue(prefix + "SiteId", TENANT);+ info.setCustomMetadataValue(prefix + "Name", "Secret");++ SensitivityLabel read = PdfSensitivityLabels.read(document).orElseThrow();+ assertThat(read.name()).isEqualTo("Secret");+ assertThat(read.method()).isNull();+ }+ }++ @Test+ void unlabelledDocumentReadsAsEmpty() throws IOException {+ try (PDDocument document = newDocument()) {+ assertThat(PdfSensitivityLabels.read(document)).isEmpty();+ }+ }++ @Test+ void enabledFalseIsNotALabel() throws IOException {+ try (PDDocument document = newDocument()) {+ var info = document.getDocumentInformation();+ info.setCustomMetadataValue("MSIP_Label_" + LABEL_ID + "_Enabled", "false");+ info.setCustomMetadataValue("MSIP_Label_" + LABEL_ID + "_SiteId", TENANT);++ assertThat(PdfSensitivityLabels.read(document)).isEmpty();+ }+ }++ @Test+ void relabellingReplacesTheSameTenantsLabel() throws IOException {+ // "An object can only have one label from the same organization."+ String otherLabel = "11111111-2222-3333-4444-555555555555";+ try (PDDocument document = newDocument()) {+ PdfSensitivityLabels.apply(document, confidential());+ PdfSensitivityLabels.apply(+ document,+ new SensitivityLabel(+ otherLabel, "Public", TENANT, AssignmentMethod.PRIVILEGED, null, null));++ assertThat(PdfSensitivityLabels.readAll(document))+ .singleElement()+ .satisfies(+ label -> {+ assertThat(label.labelId()).isEqualTo(otherLabel);+ assertThat(label.name()).isEqualTo("Public");+ });+ }+ }++ @Test+ void aDifferentTenantsLabelIsLeftAlone() throws IOException {+ String foreignTenant = "99999999-8888-7777-6666-555555555555";+ try (PDDocument document = newDocument()) {+ PdfSensitivityLabels.apply(+ document,+ new SensitivityLabel(+ "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",+ "Foreign",+ foreignTenant,+ null,+ null,+ null));+ PdfSensitivityLabels.apply(document, confidential());++ assertThat(PdfSensitivityLabels.readAll(document))+ .hasSize(2)+ .extracting(SensitivityLabel::siteId)+ .containsExactlyInAnyOrder(foreignTenant, TENANT);+ }+ }++ @Test+ void aDifferentTenantsLabelStaysInTheXmpSurfaceToo() throws IOException {+ String foreignLabel = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";+ PDDocument document = newDocument();+ PdfSensitivityLabels.apply(+ document,+ new SensitivityLabel(+ foreignLabel,+ "Foreign",+ "99999999-8888-7777-6666-555555555555",+ null,+ null,+ null));+ PdfSensitivityLabels.apply(document, confidential());++ try (PDDocument reloaded = saveAndReload(document)) {+ // The foreign label must survive on the XMP copy, not only in the info dictionary:+ // re-labelling replaces this tenant's labels, not everyone else's.+ String xmp = xmpString(reloaded);+ assertThat(xmp).contains("MSIP_Label_" + foreignLabel + "_");+ assertThat(xmp).contains("MSIP_Label_" + LABEL_ID + "_");+ }+ }++ @Test+ void clearRemovesEveryLabel() throws IOException {+ PDDocument document = newDocument();+ PdfSensitivityLabels.apply(document, confidential());+ PdfSensitivityLabels.clear(document);++ try (PDDocument reloaded = saveAndReload(document)) {+ assertThat(PdfSensitivityLabels.readAll(reloaded)).isEmpty();+ }+ }++ @Test+ void refusesALabelThatClaimsEncryption() throws IOException {+ try (PDDocument document = newDocument()) {+ SensitivityLabel encrypting =+ new SensitivityLabel(+ LABEL_ID,+ "Highly Confidential",+ TENANT,+ AssignmentMethod.STANDARD,+ null,+ SensitivityLabel.CONTENT_BITS_ENCRYPT);++ // Marking content as protected without protecting it would mislead every reader.+ assertThatThrownBy(() -> PdfSensitivityLabels.apply(document, encrypting))+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("cannot protect");+ }+ }++ @Test+ void preservesUnrelatedXmpAndInfoMetadata() throws IOException {+ PDDocument document = newDocument();+ document.getDocumentInformation().setAuthor("Anthony");+ document.getDocumentInformation().setCustomMetadataValue("StirlingPDFClassification", "{}");+ PdfSensitivityLabels.apply(document, confidential());++ try (PDDocument reloaded = saveAndReload(document)) {+ assertThat(reloaded.getDocumentInformation().getAuthor()).isEqualTo("Anthony");+ assertThat(+ reloaded.getDocumentInformation()+ .getCustomMetadataValue("StirlingPDFClassification"))+ .isEqualTo("{}");+ assertThat(PdfSensitivityLabels.read(reloaded)).isPresent();+ }+ }++ @Test+ void labelValuesAreCappedAtTheDocumentedLength() {+ SensitivityLabel longName =+ new SensitivityLabel(LABEL_ID, "x".repeat(400), TENANT, null, null, null);+ assertThat(longName.toMetadata().get("MSIP_Label_" + LABEL_ID + "_Name"))+ .hasSize(SensitivityLabel.MAX_VALUE_LENGTH);+ }++ @Test+ void labelRequiresIdAndTenant() {+ assertThatThrownBy(() -> new SensitivityLabel(null, "n", TENANT, null, null, null))+ .isInstanceOf(IllegalArgumentException.class);+ assertThatThrownBy(() -> new SensitivityLabel(LABEL_ID, "n", " ", null, null, null))+ .isInstanceOf(IllegalArgumentException.class);+ }++ @Test+ void rejectsALabelIdThatIsNotAGuid() {+ // labelId is written into XMP/info key names verbatim; a space or markup char must not+ // pass,+ // or it would corrupt or inject the metadata packet it lands in.+ assertThatThrownBy(+ () ->+ new SensitivityLabel(+ "not a guid", "Public", TENANT, null, null, null))+ .isInstanceOf(IllegalArgumentException.class);+ assertThatThrownBy(+ () ->+ new SensitivityLabel(+ "<inject>-2222-3333-4444-5555555555",+ "Public",+ TENANT,+ null,+ null,+ null))+ .isInstanceOf(IllegalArgumentException.class);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/service/IntegrationConfigServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/service/IntegrationConfigServiceTest.javaindex fbfef15721..90842612d1 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/integration/service/IntegrationConfigServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/service/IntegrationConfigServiceTest.java@@ -55,6 +55,9 @@ class IntegrationConfigServiceTest {@Mock private IntegrationConfigValidator validator;@Mock private IntegrationConfigUsageCheck usageCheck;+ private final stirling.software.common.model.ApplicationProperties applicationProperties =+ new stirling.software.common.model.ApplicationProperties();+private IntegrationConfigService service;@BeforeEach@@ -65,6 +68,7 @@ class IntegrationConfigServiceTest {ownership,secretMasker,grantRepository,+ applicationProperties,List.of(validator),List.of(usageCheck));}@@ -72,15 +76,15 @@ class IntegrationConfigServiceTest {@Testvoid createRejectsAConfigItsTypeValidatorRefuses() {when(secretMasker.sanitize(any())).thenReturn(Map.of());- when(validator.type()).thenReturn(IntegrationType.API);- org.mockito.Mockito.doThrow(new IllegalArgumentException("api config needs a 'url'"))+ when(validator.type()).thenReturn(IntegrationType.MCP);+ org.mockito.Mockito.doThrow(new IllegalArgumentException("mcp config needs a 'url'")).when(validator).validate(any());assertThatThrownBy(() ->service.create(- request(IntegrationType.API, OwnerScope.USER, null),+ request(IntegrationType.MCP, OwnerScope.USER, null),user(7))).isInstanceOf(ResponseStatusException.class).satisfies(@@ -89,6 +93,92 @@ class IntegrationConfigServiceTest {.isEqualTo(HttpStatus.BAD_REQUEST));}+ @Test+ void anAdminCanAuthorACustomApiIntegration() {+ when(secretMasker.sanitize(any())).thenReturn(Map.of());+ when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));+ when(ownership.isAdmin(any())).thenReturn(true);++ IntegrationConfig created =+ service.create(request(IntegrationType.API, OwnerScope.USER, null), user(7));++ assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.API);+ }++ @Test+ void aNonAdminCannotAuthorACustomApiIntegration() {+ // A custom integration names its own host and body, so it can aim the server anywhere;+ // that is admin authoring power, not self-serve config like a vendor preset.+ when(ownership.isAdmin(any())).thenReturn(false);++ assertThatThrownBy(+ () ->+ service.create(+ request(IntegrationType.API, OwnerScope.USER, null),+ user(7)))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.FORBIDDEN);+ }++ @Test+ void theOperatorCanWithdrawCustomApiAuthoringEntirely() {+ applicationProperties.getPolicies().setAllowCustomApiIntegrations(false);++ // Off for everyone, admins included.+ assertThatThrownBy(+ () ->+ service.create(+ request(IntegrationType.API, OwnerScope.USER, null),+ user(7)))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.FORBIDDEN);+ assertThat(service.canAuthorCustomApi(user(7))).isFalse();+ }++ @Test+ void vendorPresetsAreNotGatedByTheCustomApiFlag() {+ // Purview/ConsignO carry a fixed shape: the worst a user can do is misconfigure their own+ // connection, so they stay self-serve even with custom authoring switched off.+ applicationProperties.getPolicies().setAllowCustomApiIntegrations(false);+ when(secretMasker.sanitize(any())).thenReturn(Map.of());+ when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));++ IntegrationConfig created =+ service.create(request(IntegrationType.PURVIEW, OwnerScope.USER, null), user(7));++ assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.PURVIEW);+ }++ @Test+ void editingACustomApisConfigNeedsTheSameRightsAsCreatingIt() {+ // Otherwise the base URL and body could be rewritten by someone who could never have+ // authored them.+ IntegrationConfig cfg = config(5L);+ cfg.setIntegrationType(IntegrationType.API);+ when(repository.findById(5L)).thenReturn(Optional.of(cfg));+ when(ownership.canManage(any(), eq(cfg), any())).thenReturn(true);+ when(ownership.isAdmin(any())).thenReturn(false);++ assertThatThrownBy(+ () ->+ service.update(+ 5L,+ request(IntegrationType.API, OwnerScope.USER, null),+ user(7)))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.FORBIDDEN);+ }++ @Test+ void customApiAuthoringIsOnByDefaultForAdmins() {+ when(ownership.isAdmin(any())).thenReturn(true);++ assertThat(service.canAuthorCustomApi(user(7))).isTrue();+ }+@Testvoid deleteRefusedWhileAnythingStillReferencesTheConfig() {IntegrationConfig cfg = config(9L);@@ -112,9 +202,9 @@ class IntegrationConfigServiceTest {User user = user(7);IntegrationConfig created =- service.create(request(IntegrationType.API, OwnerScope.USER, null), user);+ service.create(request(IntegrationType.MCP, OwnerScope.USER, null), user);- assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.API);+ assertThat(created.getIntegrationType()).isEqualTo(IntegrationType.MCP);assertThat(created.getName()).isEqualTo("name");verify(ownership).assignOwnership(eq(created), eq(OwnerScope.USER), isNull(), eq(user), any());diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.javaindex 21a9f3e42e..2e9613a024 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyValidatorTest.java@@ -35,6 +35,7 @@ class PolicyValidatorTest {@Mock private PolicyTrigger trigger;@Mock private InputSource inputSource;@Mock private PolicyOutputSink outputSink;+ @Mock private PipelineStepValidator stepValidator;private final SourceStore sourceStore = new InProcessSourceStore();private PolicyValidator validator;@@ -43,7 +44,11 @@ class PolicyValidatorTest {void setUp() {validator =new PolicyValidator(- List.of(trigger), List.of(inputSource), List.of(outputSink), sourceStore);+ List.of(trigger),+ List.of(inputSource),+ List.of(outputSink),+ List.of(stepValidator),+ sourceStore);}@Testdiff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 6cf87f4252..e3c636b49e 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -4775,13 +4775,13 @@ hint = "Upload a PNG, JPG, SVG, or other image file to place on the PDF. SVG fillabel = "Upload Image"placeholder = "Select image file"-[imageToPdf]-tags = "conversion,img,jpg,picture,photo"-[imageToPDF]header = "Image to PDF"title = "Image to PDF"+[imageToPdf]+tags = "conversion,img,jpg,picture,photo"+[infoBanner]dismiss = "Dismiss"@@ -6499,33 +6499,297 @@ beta = "Beta"ga = "GA"[portal.connections]-createTitle = "New S3 connection"+createTitle = "New connection"+createTitleFor = "Connect {{name}}"delete = "Delete"edit = "Edit"-editTitle = "Edit S3 connection"-subtitle = "Reusable S3 credentials that sources and pipeline outputs connect to."+editTitle = "Edit connection"+subtitle = "Reusable credentials that sources, pipeline outputs and integration steps connect to."+unsupportedType = "This connection type cannot be edited here."[portal.connections.actions]new = "New connection"+[portal.connections.categories.advanced]+description = "For a service we do not support yet."+label = "Advanced"++[portal.connections.categories.audit]+description = "Record what happened to a document, where your auditors already look."+label = "Audit & compliance logging"++[portal.connections.categories.notify]+description = "Tell another system that something happened."+label = "Notify & workflow"++[portal.connections.categories.security]+description = "Scan or label a document before it moves on."+label = "Security & classification"++[portal.connections.categories.signing]+description = "Send a document out to be signed or notarized."+label = "E-signature & notarization"++[portal.connections.categories.storage]+description = "Where processed documents end up - a bucket, a drive, a ticket or a page."+label = "File & attach"++[portal.connections.commonFields.accessToken]+helperText = "Stirling stores this encrypted and never shows it again."+label = "Access token"++[portal.connections.commonFields.apiKey]+label = "API key"++[portal.connections.commonFields.apiToken]+label = "API token"++[portal.connections.commonFields.baseUrl]+helperText = "Steps using this connection can only call paths under this URL, never another host."+label = "Server URL"++[portal.connections.commonFields.email]+label = "Email"++[portal.connections.commonFields.password]+label = "Password"++[portal.connections.commonFields.username]+label = "Username"++[portal.connections.commonFields.webhookUrl]+helperText = "Paste the URL the service gave you. Only paths under it can be called."+label = "Webhook URL"+[portal.connections.empty]-description = "Add an S3 connection to reuse the same bucket and credentials across sources and pipeline outputs."+description = "Add a connection to reuse the same credentials across sources, pipeline outputs and integration steps."title = "No connections yet"+[portal.connections.fields]+name = "Connection name"+namePlaceholder = "e.g. Claims bucket"+[portal.connections.picker]cancel = "Cancel"createNew = "New connection..."placeholder = "Select a connection"save = "Save connection"-[portal.connections.s3.fields]-name = "Connection name"-namePlaceholder = "e.g. Claims bucket"+[portal.connections.picker2]+back = "Change integration"+heading = "What do you want to connect?"+noResultsBody = "We do not support it yet - tell us about it and we will look at adding it."+noResultsTitle = "Nothing matches \"{{query}}\""+searchPlaceholder = "Search integrations - try \"sign\", \"ocr\" or a product name"[portal.connections.table]-bucket = "Bucket"+detail = "Details"name = "Name"-region = "Region"+type = "Type"++[portal.connections.types.api]+description = "Call any HTTP API from a policy. You choose the URL, authentication and payload."+label = "Custom API"++[portal.connections.types.api.fields.authType]+label = "Authentication"++[portal.connections.types.api.fields.authType.options.basic]+label = "Username and password"++[portal.connections.types.api.fields.authType.options.bearer]+label = "Bearer token"++[portal.connections.types.api.fields.authType.options.header]+label = "Token in a custom header"++[portal.connections.types.api.fields.authType.options.none]+label = "None"++[portal.connections.types.api.fields.authType.options.tokenLogin]+label = "Log in for a token"++[portal.connections.types.api.fields.baseUrl]+helperText = "Steps using this connection can only call paths under this URL, never another host."+label = "Base URL"+placeholder = "https://api.example.com/v1"++[portal.connections.types.api.fields.headerName]+label = "Header name"+placeholder = "X-API-Key"++[portal.connections.types.api.fields.loginPath]+label = "Login path"+placeholder = "/auth/login"++[portal.connections.types.api.fields.password]+label = "Password"++[portal.connections.types.api.fields.resultUrlHosts]+helperText = "If the API replies with a download link, only these hosts may be fetched. Separate with commas. Leave blank to allow only the base URL's own host."+label = "Allowed result hosts"++[portal.connections.types.api.fields.token]+label = "Token"++[portal.connections.types.api.fields.tokenHeaderName]+label = "Send the token as this header"++[portal.connections.types.api.fields.tokenResponseHeader]+helperText = "The response header the login call returns the token in, e.g. X-Auth-Token."+label = "Token response header"++[portal.connections.types.api.fields.username]+label = "Username"++[portal.connections.types.clamav]+baseUrlPlaceholder = "http://clamav-rest:9000"+description = "Scan documents for malware on a server you run - nothing leaves your network."+label = "ClamAV (self-hosted)"++[portal.connections.types.cloudmersive]+description = "Virus and content scanning for documents in a policy."+label = "Cloudmersive"++[portal.connections.types.cloudmersiveadvanced]+description = "Block documents containing macros, executables, scripts or embedded objects - not just known malware."+label = "Cloudmersive Advanced Scan"++[portal.connections.types.confluence]+baseUrlPlaceholder = "https://your-site.atlassian.net/wiki/api/v2"+description = "Attach processed documents to a Confluence page."+label = "Confluence"++[portal.connections.types.consigno]+description = "Send documents to ConsignO Cloud (Notarius) for electronic signature and notarization."+label = "ConsignO Cloud"++[portal.connections.types.consigno.fields.baseUrl]+helperText = "Your ConsignO Cloud environment, including /api/v1."+label = "Server URL"+placeholder = "https://your-org.consignocloud.com/api/v1"++[portal.connections.types.consigno.fields.clientId]+label = "API key"++[portal.connections.types.consigno.fields.clientSecret]+label = "API secret"++[portal.connections.types.consigno.fields.password]+label = "Password"++[portal.connections.types.consigno.fields.tenantId]+helperText = "Only needed if your organisation uses tenants."+label = "Tenant"++[portal.connections.types.consigno.fields.username]+label = "Username"++[portal.connections.types.discord]+baseUrlPlaceholder = "https://discord.com/api/webhooks/..."+description = "Post a message to Discord when a policy processes a document."+label = "Discord"++[portal.connections.types.elastic]+baseUrlPlaceholder = "https://your-cluster:9200"+description = "Index an audit event in Elasticsearch each time a policy handles a document."+label = "Elasticsearch"++[portal.connections.types.googlechat]+baseUrlPlaceholder = "https://chat.googleapis.com/v1/spaces/..."+description = "Post a message to a Google Chat space when a policy runs."+label = "Google Chat"++[portal.connections.types.jira]+baseUrlPlaceholder = "https://your-site.atlassian.net"+description = "Attach processed documents to a Jira issue."+label = "Jira"++[portal.connections.types.mailgun]+description = "Email a document or a notification when a policy runs."+label = "Mailgun"++[portal.connections.types.nextcloud]+baseUrlPlaceholder = "https://your-server/remote.php/dav"+description = "File processed documents into Nextcloud."+label = "Nextcloud"++[portal.connections.types.nextcloud.fields.appPassword]+label = "App password"++[portal.connections.types.presidio]+baseUrlPlaceholder = "http://presidio-analyzer:3000"+description = "Detect personal data in document text using a Presidio server you run."+label = "Presidio (self-hosted)"++[portal.connections.types.purview]+description = "Read and apply Microsoft Purview sensitivity labels on PDFs."+label = "Microsoft Purview"++[portal.connections.types.purview.fields.clientId]+helperText = "Optional. Only needed to pick labels by name; labelling works without it."+label = "Application (client) ID"++[portal.connections.types.purview.fields.clientSecret]+label = "Client secret"++[portal.connections.types.purview.fields.tenantId]+helperText = "Stamped onto every label as its SiteId, so Purview-aware tools know which organisation applied it."+label = "Directory (tenant) ID"+placeholder = "cb46c030-1825-4e81-a295-151c039dbf02"++[portal.connections.types.s3]+description = "An S3 bucket that sources can read from and pipeline outputs can write to."+label = "S3 storage"++[portal.connections.types.s3.fields.accessKeyId]+label = "Access key ID"++[portal.connections.types.s3.fields.bucket]+label = "Bucket"++[portal.connections.types.s3.fields.endpoint]+helperText = "Leave blank for AWS. Set this for MinIO or another S3-compatible store."+label = "Endpoint"++[portal.connections.types.s3.fields.region]+label = "Region"++[portal.connections.types.s3.fields.secretAccessKey]+label = "Secret access key"++[portal.connections.types.sendgrid]+description = "Email a document or a notification when a policy runs."+label = "SendGrid"++[portal.connections.types.slack]+description = "Post a message to Slack when a policy processes a document."+label = "Slack"++[portal.connections.types.splunk]+baseUrlPlaceholder = "https://your-splunk:8088"+description = "Send an audit event to Splunk each time a policy handles a document."+label = "Splunk"++[portal.connections.types.sumologic]+baseUrlPlaceholder = "https://endpoint.collection.sumologic.com/receiver/v1/http/..."+description = "Send an audit event to a Sumo Logic HTTP collector."+label = "Sumo Logic"++[portal.connections.types.teams]+baseUrlPlaceholder = "https://your-org.webhook.office.com/webhookb2/..."+description = "Post a message to a Teams channel when a policy runs."+label = "Microsoft Teams"++[portal.connections.types.webhook]+baseUrlPlaceholder = "https://example.com/hooks/documents"+description = "Post each document, or just the details, to a URL you choose."+label = "Webhook"++[portal.connections.types.zapier]+baseUrlPlaceholder = "https://hooks.zapier.com/hooks/catch/..."+description = "Trigger a Zap or Make scenario from a policy."+label = "Zapier & Make"[portal.docs]browse = "Browse docs"@@ -7300,6 +7564,8 @@ newPipeline = "New pipeline"[portal.pipelines.builder]addStep = "Add tool"back = "Back to pipelines"+chooseAccount = "Choose an account"+chooseOperation = "Choose what this step does"discard = "Discard changes"enabled = "Enabled"keepEditing = "Keep editing"@@ -7309,6 +7575,8 @@ pipelineSettings = "Pipeline settings"searchTools = "Search tools"selectToolBody = "Add a tool to build your pipeline."selectToolTitle = "No tools yet"+sendToSystem = "Send to another system"+stepsNeedSetup = "These steps still need an operation and an account chosen before saving: {{tools}}."toolSettings = "Tool settings"unknownStep = "Unrecognized operation, kept as-is."unsavedBody = "You have unsaved changes. Save them before leaving, or discard them?"@@ -7474,6 +7742,29 @@ minConfidence = "Min confidence"2 = "Name"3 = "Normalize"+[portal.policies.config.purview]+label = "Apply a Microsoft Purview sensitivity label"++[portal.policies.config.purview.fields]+connection = "Purview tenant"+labelId = "Label ID"+labelIdHelp = "The label's GUID, from the Purview portal. Applying a label writes its metadata onto the PDF; it cannot encrypt, which needs the Microsoft client."+labelName = "Label name (optional)"+labelNameHelp = "Recorded alongside the ID so people and tools can recognise the label."++[portal.policies.config.purview.fields.method]+help = "Purview distinguishes a label a policy applied from one a person chose."+label = "How the label is recorded"+privileged = "As chosen by a person"+standard = "As applied automatically"++[portal.policies.config.purviewRead]+label = "Read a Microsoft Purview label"++[portal.policies.config.purviewRead.fields]+connection = "Purview tenant"+connectionHelp = "Reads the label the document already carries, so later steps can act on it."+[portal.policies.config.retention]summary = "Enforces how long documents are kept, when to archive, and when to delete."@@ -7552,6 +7843,183 @@ description = "Your policies are saved and will appear once the connection is reretry = "Retry"title = "Backend unavailable"+[portal.policies.operations]+change = "Change what this step does"+noResults = "No step matches that. Try a product name, or \"scan\", \"notify\", \"attach\"."+searchPlaceholder = "Search steps - try \"scan\", \"attach\" or a product name"++[portal.policies.operations.bodyMode]+binary = "Raw file bytes"+json = "Inside a JSON payload"+multipart = "As a file upload (multipart)"++[portal.policies.operations.clamavScan]+description = "Your own ClamAV server checks the document; nothing leaves your network."+label = "Scan for viruses (self-hosted)"++[portal.policies.operations.cloudmersiveAdvancedScan]+description = "Rejects documents carrying macros, executables, scripts or embedded objects."+label = "Block active content"++[portal.policies.operations.cloudmersiveScan]+description = "Cloudmersive checks the document and the run stops if it is not clean."+label = "Scan for viruses"++[portal.policies.operations.confluenceAttach]+description = "Files the processed document onto a page."+label = "Attach to a Confluence page"++[portal.policies.operations.consignoSubmit]+description = "Submits the document to ConsignO Cloud for signing."+label = "Send for signature (ConsignO)"+note = "Submits the document. Retrieving the signed copy is not yet supported, because a step cannot pass a result to a later step."++[portal.policies.operations.customApiCall]+description = "Author the call yourself: path, method, body and response handling."+label = "Call a custom API"++[portal.policies.operations.discordNotify]+description = "Tells a channel that the policy handled a document."+label = "Post a message to Discord"++[portal.policies.operations.elasticIndex]+description = "Records what the policy did as a searchable document."+label = "Index an audit event in Elasticsearch"++[portal.policies.operations.fields.bodyMode]+helperText = "Multipart suits upload APIs; JSON suits APIs that want the file inside a payload; binary sends the raw bytes."+label = "How to send the document"++[portal.policies.operations.fields.bodyTemplate]+helperText = "A JSON body sent as-is. {{document.base64}} carries the file; {{document.*}} and {{run.*}} are filled in per document."+label = "JSON body"++[portal.policies.operations.fields.connection]+label = "Account"++[portal.policies.operations.fields.domain]+label = "Mailgun domain"+placeholder = "mg.acme.com"++[portal.policies.operations.fields.fileFieldName]+helperText = "The form field the API expects the document under."+label = "File field name"+placeholder = "file"++[portal.policies.operations.fields.from]+label = "From"+placeholder = "[email protected]"++[portal.policies.operations.fields.headers]+helperText = "A JSON object of header name/value pairs. The connection's credential is added for you."+label = "Headers"++[portal.policies.operations.fields.index]+label = "Index"+placeholder = "stirling-audit"++[portal.policies.operations.fields.issueKey]+label = "Issue key"+placeholder = "OPS-42"++[portal.policies.operations.fields.message]+helperText = "Sent as the message body. {{document.*}} and {{run.*}} are filled in per document."+label = "Message"++[portal.policies.operations.fields.method]+label = "Method"++[portal.policies.operations.fields.pageId]+label = "Page ID"+placeholder = "66186"++[portal.policies.operations.fields.path]+helperText = "Appended to the connection's base URL. It can never reach another host."+label = "Path"+placeholder = "/v1/scan"++[portal.policies.operations.fields.remotePath]+helperText = "Where in the drive to write it. {{document.filename}} is filled in per document."+label = "Destination path"+placeholder = "Processed/{{document.filename}}"++[portal.policies.operations.fields.responseMode]+helperText = "Report leaves the document untouched. Replace swaps it for whatever comes back."+label = "What to do with the reply"++[portal.policies.operations.fields.signerEmail]+label = "Signer's email"+placeholder = "[email protected]"++[portal.policies.operations.fields.subject]+label = "Subject"+placeholder = "Processed: {{document.filename}}"++[portal.policies.operations.fields.text]+helperText = "Presidio analyses this text. Use {{document.title}} or paste the text you want checked."+label = "Text to check"++[portal.policies.operations.fields.to]+label = "To"+placeholder = "[email protected]"++[portal.policies.operations.fields.username]+label = "Nextcloud username"+placeholder = "svc-stirling"++[portal.policies.operations.googlechatNotify]+description = "Tells a space that the policy handled a document."+label = "Post a message to Google Chat"++[portal.policies.operations.jiraAttach]+description = "Files the processed document onto an issue."+label = "Attach to a Jira issue"++[portal.policies.operations.mailgunEmail]+description = "Sends the processed document as an attachment."+label = "Email the document (Mailgun)"++[portal.policies.operations.nextcloudUpload]+description = "Writes the processed document into a folder."+label = "Upload to Nextcloud"++[portal.policies.operations.presidioAnalyze]+description = "Your own Presidio server reports the personal data it finds."+label = "Detect personal data"+note = "Presidio reads text, not files. Give it the text you want checked — the document itself is not uploaded."++[portal.policies.operations.responseMode]+replace = "Replace the document with the reply"+report = "Keep the document, record the reply"++[portal.policies.operations.sendgridEmail]+description = "Sends the processed document as an attachment."+label = "Email the document (SendGrid)"++[portal.policies.operations.slackNotify]+description = "Tells a channel that the policy handled a document."+label = "Post a message to Slack"++[portal.policies.operations.splunkEvent]+description = "Records what the policy did, where your auditors already look."+label = "Send an audit event to Splunk"++[portal.policies.operations.sumologicEvent]+description = "Records what the policy did to an HTTP collector."+label = "Send an audit event to Sumo Logic"++[portal.policies.operations.teamsNotify]+description = "Tells a channel that the policy handled a document."+label = "Post a message to Teams"++[portal.policies.operations.webhookPost]+description = "Sends the document itself to a URL you choose."+label = "Post the document to a webhook"++[portal.policies.operations.zapierNotify]+description = "Hands the run's details to your automation."+label = "Trigger a Zap or Make scenario"+[portal.policies.stats]activeFor = "Active"dataProcessed = "Data processed"@@ -8108,22 +8576,10 @@ top = "Top level only"description = "Pull documents from an Amazon S3 or S3-compatible bucket."label = "Amazon S3"-[portal.sources.types.s3.fields.accessKeyId]-label = "Access key ID"--[portal.sources.types.s3.fields.bucket]-label = "Bucket"-placeholder = "my-company-inbox"-[portal.sources.types.s3.fields.connection]helperText = "The stored connection holding the bucket and credentials. Reused by every source and pipeline output that references it."label = "Connection"-[portal.sources.types.s3.fields.endpoint]-helperText = "Leave blank for Amazon S3. Set to use an S3-compatible service such as MinIO."-label = "Custom endpoint"-placeholder = "https://s3.example.com"-[portal.sources.types.s3.fields.mode]helperText = "Consume removes each object from the bucket once every policy has processed it."label = "Read mode"@@ -8137,13 +8593,6 @@ helperText = "Only objects whose keys start with this prefix are processed."label = "Key prefix"placeholder = "incoming/"-[portal.sources.types.s3.fields.region]-label = "Region"-placeholder = "us-east-1"--[portal.sources.types.s3.fields.secretAccessKey]-label = "Secret access key"-[portal.sources.types.unknown]label = "Source"@@ -8868,12 +9317,12 @@ label = "Remove XMP Metadata"[sanitize.steps]settings = "Settings"-[sanitizePdf]-tags = "clean,secure,safe,remove-threats"-[sanitizePDF]title = "Sanitize PDF"+[sanitizePdf]+tags = "clean,secure,safe,remove-threats"+[scalePages]tags = "resize,adjust,scale,page size,resize page,scale page,change size,adjust size,enlarge,shrink page,fit to page,A4,letter size"title = "Adjust page-scale"@@ -8881,18 +9330,6 @@ title = "Adjust page-scale"[scannerEffect]tags = "scan,simulate,create,fake scan,look scanned,scanner effect,make look scanned,photocopy effect,simulate scanner,realistic scan"-[ScannerImageSplit.selectText]-1 = "Angle Threshold:"-10 = "Extra padding (in pixels) around each saved photo so edges aren't cut."-2 = "Tilt (in degrees) needed before we auto-straighten a photo."-3 = "Tolerance:"-4 = "How closely a color must match the page background to count as background. Higher = looser, lower = stricter."-5 = "Minimum Area:"-6 = "Smallest photo size (in pixels²) we'll keep to avoid tiny fragments."-7 = "Minimum Contour Area:"-8 = "Smallest edge/shape we consider when finding photos (filters dust and specks)."-9 = "Border Size:"-[scannerImageSplit]submit = "Extract Image Scans"tags = "separate,auto-detect,scans,multi-photo,organize"@@ -8924,6 +9361,18 @@ whatThisDoes = "What this does"whatThisDoesDesc = "Automatically finds and extracts each photo from a scanned page or composite image-no manual cropping."whenToUse = "When to use"+[ScannerImageSplit.selectText]+1 = "Angle Threshold:"+10 = "Extra padding (in pixels) around each saved photo so edges aren't cut."+2 = "Tilt (in degrees) needed before we auto-straighten a photo."+3 = "Tolerance:"+4 = "How closely a color must match the page background to count as background. Higher = looser, lower = stricter."+5 = "Minimum Area:"+6 = "Smallest photo size (in pixels²) we'll keep to avoid tiny fragments."+7 = "Minimum Contour Area:"+8 = "Smallest edge/shape we consider when finding photos (filters dust and specks)."+9 = "Border Size:"+[search]noResults = "No results found"placeholder = "Enter search term..."diff --git a/frontend/editor/src/core/i18n/translationAudit.ts b/frontend/editor/src/core/i18n/translationAudit.tsindex 79fee63a7c..9e4e57a8a5 100644--- a/frontend/editor/src/core/i18n/translationAudit.ts+++ b/frontend/editor/src/core/i18n/translationAudit.ts@@ -89,6 +89,10 @@ export const I18N_PROJECTS: TranslationProject[] = [// components/sources/sourceTypes.ts (t(field.labelKey)), invisible to the// static scan./^portal\.sources\.types\./,+ // The connection catalogue (connectionTypes.ts) mirrors source types: every key is+ // t(`${PREFIX}.${id}.label`) / t(`${COMMON}.${field}.label`) with multi-segment const+ // prefixes, so the whole family is matched here rather than by the shape heuristic.+ /^portal\.connections\.(types|commonFields)\./,// Portal catalogue copy stored as i18n keys in api/<surface>.ts constants// (label maps, role/policy/journey catalogues) and rendered via// t(constant), invisible to the static scan.@@ -99,6 +103,11 @@ export const I18N_PROJECTS: TranslationProject[] = [/^portal\.procurement\.journeySteps\./,/^portal\.users\.roles\./,/^portal\.policies\.(categories|config|endpoints)\./,+ // The integration operations catalogue (stepOperations.ts) assembles every key as+ // t(`${PREFIX}.${id}.label`) where PREFIX is the multi-segment const+ // "portal.policies.operations" - the shape heuristic treats that interpolation as one+ // segment, so this whole catalogue-driven family is matched here instead.+ /^portal\.policies\.operations\./,// Policy field labels + option display copy are looked up with keys// derived from catalogue data (t(`policies.field.${key}`),// t(`policyOption.${id}`)) in the PolicyFieldRows and setup wizards —diff --git a/frontend/editor/src/core/theme/colors.css b/frontend/editor/src/core/theme/colors.cssindex ba0e5466f5..ced2c5dcb6 100644--- a/frontend/editor/src/core/theme/colors.css+++ b/frontend/editor/src/core/theme/colors.css@@ -73,6 +73,13 @@ html[data-app-theme="light"] {--c-avatar-5: var(--p-amber-500);--c-avatar-6: var(--p-cyan-500);+ /* Connection picker: muted categorical marks + brand-red accent. */+ --c-conn-accent: var(--p-art-red-muted);+ --c-conn-storage: var(--p-art-blue-muted);+ --c-conn-signing: var(--p-art-green-muted);+ --c-conn-notify: var(--p-art-amber-muted);+ --c-conn-neutral: var(--p-gray-mid);+/* Always-dark marketing/product hero strip (portal). Same in both themes. */--c-hero-dark: var(--p-zinc-950);--c-hero-dark-cta-text: var(--p-navy-700);diff --git a/frontend/editor/src/core/theme/primitives.css b/frontend/editor/src/core/theme/primitives.cssindex 22716816a2..6ea844e9ed 100644--- a/frontend/editor/src/core/theme/primitives.css+++ b/frontend/editor/src/core/theme/primitives.css@@ -147,6 +147,10 @@--p-c-acacac: #acacac;--p-c-c084fc: #c084fc;--p-art-red-muted: #c56565;+ /* Muted category hues for connection-picker marks. */+ --p-art-blue-muted: #4a7ab5;+ --p-art-green-muted: #5d8348;+ --p-art-amber-muted: #ac7a2c;--p-c-cf222e: #cf222e;--p-c-d0d6dc: #d0d6dc;--p-c-d0d7de: #d0d7de;diff --git a/frontend/editor/src/portal/api/integrations.ts b/frontend/editor/src/portal/api/integrations.tsindex 19f88fea29..01eebe96ab 100644--- a/frontend/editor/src/portal/api/integrations.ts+++ b/frontend/editor/src/portal/api/integrations.ts@@ -1,12 +1,12 @@/**- * Integrations service layer: stored connections (S3 today; MCP/API later) that- * policy sources and pipeline outputs reference by id instead of embedding+ * Integrations service layer: stored connections (S3, Purview, ConsignO, and free-form API) that+ * policy sources, pipeline outputs and integration steps reference by id instead of embedding* credentials. Secrets are write-only - reads return them masked, and sending* the mask back on update keeps the stored value.*/import { apiClient } from "@portal/api/http";-export type IntegrationType = "S3" | "MCP" | "API";+export type IntegrationType = "S3" | "MCP" | "API" | "PURVIEW" | "CONSIGNO";export type OwnerScope = "USER" | "TEAM" | "SERVER";/** Mirrors the backend IntegrationConfigResponse; `config` values are masked. */@@ -47,6 +47,20 @@ export async function fetchS3Connections(): Promise<IntegrationConfig[]> {);}+/**+ * What this caller may set up. Answered by the server because the custom-API gate is an+ * authorization decision, not a presentation one - the create call is refused regardless.+ */+export interface IntegrationCapabilities {+ customApi: boolean;+}++export async function fetchIntegrationCapabilities(): Promise<IntegrationCapabilities> {+ return apiClient.local.json<IntegrationCapabilities>(+ "/api/v1/integrations/capabilities",+ );+}+export async function createIntegration(body: IntegrationConfigRequest,): Promise<IntegrationConfig> {diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.tsindex a26556f5a2..fb3788dc76 100644--- a/frontend/editor/src/portal/api/policies.ts+++ b/frontend/editor/src/portal/api/policies.ts@@ -291,7 +291,14 @@ export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {"portal.policies.config.compliance.rules.2",],scopeLabel: "portal.policies.config.scopeAll",- defaultOperations: [policyStep("sanitize"), policyStep("flatten")],+ // Apply writes our sensitivity label into the document after it is sanitised and flattened.+ // Offered only once a Purview tenant is connected (it needs a tenant connection and a label+ // GUID, which no default can guess), and hidden entirely until then.+ defaultOperations: [+ policyStep("sanitize"),+ policyStep("flatten"),+ policyStep("purviewApplyLabel"),+ ],fields: [{label: "portal.policies.config.compliance.fields.frameworks",diff --git a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsxindex 672383ecd3..213217de5b 100644--- a/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx+++ b/frontend/editor/src/portal/components/pipelines/PipelineStepSettings.tsx@@ -7,6 +7,10 @@ import { type ToolRegistry } from "@app/data/toolsTaxonomy";import { type ErasedToolParams } from "@app/hooks/tools/shared/toolOperationTypes";import { type WorkingToolStep } from "@app/hooks/tools/shared/toolAutomation";+import { PolicyExternalApiConfig } from "@portal/components/policies/PolicyExternalApiConfig";+import { isIntegrationStep } from "@portal/components/pipelines/integrationStep";+import type { ExternalApiStepParams } from "@portal/components/policies/stepOperations";+interface PipelineStepSettingsProps {step: WorkingToolStep;registry: Partial<ToolRegistry>;@@ -23,8 +27,21 @@ export function PipelineStepSettings({registry,onChange,}: PipelineStepSettingsProps) {+ // Hooks first: selecting a different step re-renders this same instance, so an early return+ // above useTranslation would change the hook count between renders and crash.const { t } = useTranslation();+ // An integration step is configured by the operations catalogue, not by a tool's settings UI:+ // it has no registry entry to look one up from.+ if (isIntegrationStep(step)) {+ return (+ <PolicyExternalApiConfig+ parameters={step.params as unknown as ExternalApiStepParams}+ onChange={(params) => onChange(params as never)}+ />+ );+ }+if (step.support === "noSettings") {return (<Bannerdiff --git a/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx b/frontend/editor/src/portal/components/pipelines/ToolPicker.tsxindex e031854ec1..0c531a6874 100644--- a/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx+++ b/frontend/editor/src/portal/components/pipelines/ToolPicker.tsx@@ -7,21 +7,46 @@ import {type SubcategoryId,} from "@app/data/toolsTaxonomy";import { type ExecutableTool } from "@app/hooks/tools/shared/toolAutomation";+import {+ searchOperations,+ type StepOperation,+} from "@portal/components/policies/stepOperations";interface ToolPickerProps {tools: ExecutableTool[];onPick: (tool: ExecutableTool) => void;onClose: () => void;+ /**+ * Catalogue operations that hand the document to an outside system. Kept apart from the tool+ * groups because they are a different species - a tool transforms the document in place, these+ * call somebody else - and grouping them under a tool subcategory would bury that.+ */+ operations?: StepOperation[];+ onPickOperation?: (operation: StepOperation) => void;}/*** Type-to-filter, category-grouped tool picker for adding a step to a pipeline. Replaces the flat* wall of tool pills so the list stays usable as the tool count grows.*/-export function ToolPicker({ tools, onPick, onClose }: ToolPickerProps) {+export function ToolPicker({+ tools,+ onPick,+ onClose,+ operations = [],+ onPickOperation,+}: ToolPickerProps) {const { t } = useTranslation();const [query, setQuery] = useState("");+ const matchedOperations = useMemo(+ () =>+ onPickOperation+ ? searchOperations(operations, query, (key) => t(key))+ : [],+ [operations, onPickOperation, query, t],+ );+const groups = useMemo(() => {const q = query.trim().toLowerCase();const matched = q@@ -58,7 +83,7 @@ export function ToolPicker({ tools, onPick, onClose }: ToolPickerProps) {/></div><div className="portal-pipelines__picker-list">- {groups.length === 0 ? (+ {groups.length === 0 && matchedOperations.length === 0 ? (<p className="portal-pipelines__picker-empty">{t("portal.pipelines.builder.noToolMatches")}</p>@@ -93,6 +118,36 @@ export function ToolPicker({ tools, onPick, onClose }: ToolPickerProps) {</div>)))}++ {matchedOperations.length > 0 && onPickOperation ? (+ <div className="portal-pipelines__picker-group">+ <div className="portal-pipelines__picker-group-label">+ {t("portal.pipelines.builder.sendToSystem")}+ </div>+ {matchedOperations.map((op) => (+ <Button+ key={op.id}+ variant="quiet"+ justify="start"+ fullWidth+ className="portal-pipelines__picker-item"+ onClick={() => onPickOperation(op)}+ leftSection={+ <span+ className="portal-pipelines__picker-icon"+ aria-hidden="true"+ >+ {t(op.labelKey).slice(0, 1)}+ </span>+ }+ >+ <span className="portal-pipelines__picker-name">+ {t(op.labelKey)}+ </span>+ </Button>+ ))}+ </div>+ ) : null}</div></div>);diff --git a/frontend/editor/src/portal/components/pipelines/integrationStep.test.ts b/frontend/editor/src/portal/components/pipelines/integrationStep.test.tsnew file mode 100644index 0000000000..e8ea993088--- /dev/null+++ b/frontend/editor/src/portal/components/pipelines/integrationStep.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from "vitest";++import {+ INTEGRATION_ENDPOINT,+ integrationStepConfigured,+ isIntegrationStep,+ newIntegrationStep,+ stepOperation,+} from "@portal/components/pipelines/integrationStep";+import {+ buildStepParameters,+ operationById,+} from "@portal/components/policies/stepOperations";+import {+ serializeToolStep,+ type WorkingToolStep,+} from "@app/hooks/tools/shared/toolAutomation";++describe("integration steps in a pipeline", () => {+ it("creates a step the backend will dispatch generically", () => {+ const step = newIntegrationStep(operationById("discordNotify")!);++ expect(step.toolId).toBeNull();+ expect(step.operation).toBe(INTEGRATION_ENDPOINT);+ expect(isIntegrationStep(step)).toBe(true);+ });++ it("survives serialisation verbatim, so the saved pipeline keeps its config", () => {+ // toolId null takes serializeToolStep's unmapped path; if that ever changed, an integration+ // step would be rewritten on save and silently lose its parameters.+ const op = operationById("jiraAttach")!;+ const step = newIntegrationStep(op);+ // Configure it the way the inspector does: rebuild from the catalogue with real answers.+ step.params = buildStepParameters(op, "12", {+ issueKey: "OPS-42",+ }) as never;++ const wire = serializeToolStep(step, {});++ expect(wire.operation).toBe(INTEGRATION_ENDPOINT);+ expect(wire.parameters.connectionId).toBe("12");+ expect(wire.parameters.path).toBe("/rest/api/3/issue/OPS-42/attachments");+ expect(JSON.parse(wire.parameters.headers as string)).toEqual({+ "X-Atlassian-Token": "no-check",+ });+ });++ it("leaves an unfilled field blank rather than shipping the placeholder", () => {+ // A freshly added step is deliberately unconfigured. What matters is that {{issueKey}} does+ // not survive into the wire call, where Jira would receive it as a literal path segment.+ const step = newIntegrationStep(operationById("jiraAttach")!);+ expect(step.params.path).not.toContain("{{");+ expect(integrationStepConfigured(step)).toBe(false);+ });++ it("remembers which operation it is, so the builder can name and edit it", () => {+ const step = newIntegrationStep(operationById("splunkEvent")!);+ expect(stepOperation(step)?.id).toBe("splunkEvent");+ });++ it("is not configured until an account is chosen", () => {+ const step = newIntegrationStep(operationById("clamavScan")!);+ // Created deliberately blank so the operator sees it in the chain and fills it in.+ expect(integrationStepConfigured(step)).toBe(false);++ (step.params as Record<string, unknown>).connectionId = "4";+ expect(integrationStepConfigured(step)).toBe(true);+ });++ it("leaves ordinary tool steps alone", () => {+ const toolStep = {+ toolId: "compress",+ operation: "/api/v1/misc/compress-pdf",+ params: {},+ support: "supported",+ } as unknown as WorkingToolStep;+ expect(isIntegrationStep(toolStep)).toBe(false);+ expect(stepOperation(toolStep)).toBeUndefined();+ expect(integrationStepConfigured(toolStep)).toBe(true);+ });+});diff --git a/frontend/editor/src/portal/components/pipelines/integrationStep.ts b/frontend/editor/src/portal/components/pipelines/integrationStep.tsnew file mode 100644index 0000000000..93754ccefb--- /dev/null+++ b/frontend/editor/src/portal/components/pipelines/integrationStep.ts@@ -0,0 +1,62 @@+/**+ * Integration operations as pipeline steps.+ *+ * A pipeline step is an endpoint path plus parameters, and the engine dispatches it generically —+ * so an integration operation is already a legal step. What it lacked was a way to *pick* one and+ * *configure* it in the builder, whose picker is fed by the editor's tool registry and does not+ * know about them.+ *+ * These steps deliberately stay `toolId: null`. They are not registry tools, and pretending+ * otherwise would mean inventing a fake tool id that `serializeToolStep` would then try to resolve+ * an endpoint from. The unmapped path already round-trips a step verbatim, which is exactly the+ * behaviour wanted here; the only thing added is that the builder can now recognise and edit them+ * rather than showing them as an opaque "unknown step".+ */++import type { ErasedToolParams } from "@app/hooks/tools/shared/toolOperationTypes";+import type { WorkingToolStep } from "@app/hooks/tools/shared/toolAutomation";+import {+ buildStepParameters,+ emptyOperationValues,+ operationById,+ type StepOperation,+} from "@portal/components/policies/stepOperations";++/** The one endpoint every catalogue operation dispatches through. */+export const INTEGRATION_ENDPOINT = "/api/v1/integration/external-api-call";++export function isIntegrationStep(step: WorkingToolStep): boolean {+ return step.toolId === null && step.operation === INTEGRATION_ENDPOINT;+}++/** A new pipeline step for a chosen operation, seeded with the catalogue's defaults. */+export function newIntegrationStep(op: StepOperation): WorkingToolStep {+ const values = emptyOperationValues(op);+ return {+ toolId: null,+ operation: INTEGRATION_ENDPOINT,+ // Connection is chosen in the inspector; the step is created unconfigured on purpose so the+ // operator sees it in the chain and fills it in, rather than the picker blocking on a modal.+ params: buildStepParameters(op, "", values) as unknown as ErasedToolParams,+ support: "unknown",+ };+}++/**+ * The operation a step was built from, or undefined if it predates the catalogue (a pipeline+ * authored through the API can name the endpoint without an operationId).+ */+export function stepOperation(+ step: WorkingToolStep,+): StepOperation | undefined {+ if (!isIntegrationStep(step)) return undefined;+ const id = (step.params as Record<string, unknown>).operationId;+ return typeof id === "string" && id ? operationById(id) : undefined;+}++/** True once the step can actually run: an operation chosen and an account selected. */+export function integrationStepConfigured(step: WorkingToolStep): boolean {+ if (!isIntegrationStep(step)) return true;+ const params = step.params as Record<string, unknown>;+ return Boolean(params.operationId) && Boolean(params.connectionId);+}diff --git a/frontend/editor/src/portal/components/policies/PolicyExternalApiConfig.test.tsx b/frontend/editor/src/portal/components/policies/PolicyExternalApiConfig.test.tsxnew file mode 100644index 0000000000..7f1c232429--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicyExternalApiConfig.test.tsx@@ -0,0 +1,81 @@+import { useState } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ fireEvent,+ render as baseRender,+ screen,+ waitFor,+} from "@testing-library/react";+import { MantineProvider } from "@mantine/core";++import { PolicyExternalApiConfig } from "@portal/components/policies/PolicyExternalApiConfig";+import {+ buildStepParameters,+ operationById,+ type ExternalApiStepParams,+} from "@portal/components/policies/stepOperations";++const render = (ui: Parameters<typeof baseRender>[0]) =>+ baseRender(ui, { wrapper: MantineProvider });++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ i18n: { changeLanguage: vi.fn() },+ }),+}));++vi.mock("@portal/api/integrations", () => ({+ fetchIntegrations: () => Promise.resolve([]),+ fetchIntegrationCapabilities: () => Promise.resolve({ customApi: false }),+ createIntegration: vi.fn(),+ updateIntegration: vi.fn(),+}));++vi.mock("@portal/api/http", () => ({+ errorMessage: (e: unknown) => String(e),+}));++// A stateful host so the controlled component behaves as it does in the builder, and the test can+// read the parameters after each change.+let latest: ExternalApiStepParams;+function Harness({ initial }: { initial: ExternalApiStepParams }) {+ const [params, setParams] = useState(initial);+ latest = params;+ return (+ <PolicyExternalApiConfig+ parameters={params}+ onChange={(p) => {+ latest = p;+ setParams(p);+ }}+ />+ );+}++describe("switching an operation's vendor", () => {+ beforeEach(() => {+ latest = undefined as unknown as ExternalApiStepParams;+ });++ it("drops the account, so a Slack webhook is never carried into a Jira step", async () => {+ const discord = buildStepParameters(operationById("discordNotify")!, "5", {+ message: "hi",+ });+ render(<Harness initial={discord} />);++ // Start on the Discord form with its account chosen.+ expect(latest.operationId).toBe("discordNotify");+ expect(latest.connectionId).toBe("5");++ // Change the operation, then pick a different vendor.+ fireEvent.click(screen.getByText("portal.policies.operations.change"));+ fireEvent.click(+ await screen.findByText("portal.policies.operations.jiraAttach.label"),+ );++ await waitFor(() => expect(latest.operationId).toBe("jiraAttach"));+ // The Discord account did not ride across to the Jira step.+ expect(latest.connectionId).toBe("");+ });+});diff --git a/frontend/editor/src/portal/components/policies/PolicyExternalApiConfig.tsx b/frontend/editor/src/portal/components/policies/PolicyExternalApiConfig.tsxnew file mode 100644index 0000000000..9299f26071--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicyExternalApiConfig.tsx@@ -0,0 +1,416 @@+import { useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import SearchRoundedIcon from "@mui/icons-material/SearchRounded";+import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";+import { Banner, Button, FormField, Input, Select } from "@app/ui";+import { fetchIntegrationCapabilities } from "@portal/api/integrations";+import { ConnectionPicker } from "@portal/components/sources/ConnectionPicker";+import {+ CONNECTION_CATEGORIES,+ type ConnectionCategory,+} from "@portal/components/sources/connectionTypes";+import {+ STEP_OPERATIONS,+ buildStepParameters,+ emptyOperationValues,+ operationById,+ operationsByCategory,+ searchOperations,+ type ExternalApiStepParams,+ type StepOperation,+} from "@portal/components/policies/stepOperations";++/**+ * Configures a "send the document to another system" step.+ *+ * The step's own API takes seventeen parameters — path, body mode, file field name, response mode+ * and so on. Asking an operator for those is asking them to have read the vendor's API docs, which+ * is the difference between supporting a vendor and merely being able to reach it. So this screen+ * asks two questions instead: *what do you want to do*, and *with which account*. The catalogue+ * fills in the rest.+ *+ * The escape hatch stays: choosing Custom API reveals the raw call, because an operator connecting+ * something we do not ship a template for still needs a way through.+ */+/**+ * Every step parameter is a flat string (the pipeline serialises them as form fields), so the+ * operator's answers travel JSON-encoded in `operationValues` and are decoded here.+ */+export type ExternalApiParams = ExternalApiStepParams;++function decodeValues(raw: string | undefined): Record<string, string> {+ if (!raw) return {};+ try {+ const parsed: unknown = JSON.parse(raw);+ return parsed && typeof parsed === "object"+ ? (parsed as Record<string, string>)+ : {};+ } catch {+ // A hand-edited or truncated value should not break the form.+ return {};+ }+}++interface PolicyExternalApiConfigProps {+ parameters: ExternalApiParams;+ onChange: (parameters: ExternalApiParams) => void;+}++export function PolicyExternalApiConfig({+ parameters,+ onChange,+}: PolicyExternalApiConfigProps) {+ const { t } = useTranslation();+ const [query, setQuery] = useState("");+ // Whether to OFFER the escape hatch. The server refuses it regardless of what the client+ // believes, so this is presentation only - the same contract the connections tab uses.+ const [allowCustom, setAllowCustom] = useState(true);++ useEffect(() => {+ fetchIntegrationCapabilities().then(+ (c) => setAllowCustom(c.customApi !== false),+ () => undefined,+ );+ }, []);++ const selected = parameters.operationId+ ? operationById(parameters.operationId)+ : undefined;+ const values = decodeValues(parameters.operationValues);++ const available = useMemo(+ () => STEP_OPERATIONS.filter((op) => allowCustom || !op.custom),+ [allowCustom],+ );+ const matches = useMemo(+ () => searchOperations(available, query, (key) => t(key)),+ [available, query, t],+ );+ const grouped = useMemo(() => operationsByCategory(matches), [matches]);+ const searching = query.trim() !== "";++ function choose(op: StepOperation) {+ // Picking from the grid always starts the operation fresh with no account: a Slack webhook is+ // not a valid Jira account, and reaching the grid means the operator is choosing anew. The+ // account chosen for a previous operation would otherwise ride along, unlisted by the vendor+ // filter yet still saved.+ onChange(buildStepParameters(op, "", emptyOperationValues(op)));+ }++ function setValue(key: string, value: string) {+ if (!selected) return;+ const next = { ...values, [key]: value };+ onChange(+ buildStepParameters(selected, parameters.connectionId ?? "", next),+ );+ }++ function setConnection(id: string) {+ if (!selected) {+ onChange({ ...parameters, connectionId: id });+ return;+ }+ onChange(buildStepParameters(selected, id, values));+ }++ // ---- step 1: pick what the step should do ---------------------------------------------------+ if (!selected) {+ const sections: ConnectionCategory[] = searching+ ? []+ : CONNECTION_CATEGORIES.filter((c) => (grouped.get(c)?.length ?? 0) > 0);++ return (+ <div className="portal-policies__capability-config">+ <div className="portal-conn-picker__search">+ <SearchRoundedIcon className="portal-conn-picker__search-icon" />+ <input+ type="search"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t("portal.policies.operations.searchPlaceholder")}+ aria-label={t("portal.policies.operations.searchPlaceholder")}+ />+ </div>++ {matches.length === 0 ? (+ <p className="portal-conn-picker__empty-body">+ {t("portal.policies.operations.noResults")}+ </p>+ ) : searching ? (+ <OperationGrid operations={matches} onPick={choose} />+ ) : (+ sections.map((category) => (+ <section key={category} className="portal-conn-picker__section">+ <h4 className="portal-conn-picker__section-title">+ {t(`portal.connections.categories.${category}.label`)}+ </h4>+ <OperationGrid+ operations={grouped.get(category) ?? []}+ onPick={choose}+ />+ </section>+ ))+ )}+ </div>+ );+ }++ // ---- step 2: the two questions that remain --------------------------------------------------+ return (+ <div className="portal-policies__capability-config">+ <Button+ variant="quiet"+ size="sm"+ className="portal-sources__connection-back"+ leftSection={<ArrowBackRoundedIcon fontSize="inherit" />}+ onClick={() =>+ onChange({+ ...parameters,+ operationId: "",+ operationValues: "",+ // Forget the account too: it belonged to this operation's vendor, and the next pick+ // starts clean rather than carrying it to a mismatched one.+ connectionId: "",+ })+ }+ >+ {t("portal.policies.operations.change")}+ </Button>++ <p className="portal-policies__capability-summary">+ {t(selected.descriptionKey)}+ </p>++ {selected.noteKey && (+ <Banner tone="warning" description={t(selected.noteKey)} />+ )}++ <FormField+ label={t("portal.policies.operations.fields.connection.label")}+ required+ >+ <ConnectionPicker+ value={parameters.connectionId ?? ""}+ onChange={setConnection}+ integrationType={selected.integrationType}+ createTypeId={selected.connectionTypeId}+ presetId={selected.connectionTypeId}+ />+ </FormField>++ {(selected.fields ?? []).map((field) => (+ <FormField+ key={field.key}+ label={t(field.labelKey)}+ required={field.required}+ helperText={field.helperTextKey ? t(field.helperTextKey) : undefined}+ >+ {field.control === "textarea" ? (+ <textarea+ className="portal-sources__connection-textarea"+ rows={3}+ value={values[field.key] ?? ""}+ onChange={(e) => setValue(field.key, e.target.value)}+ />+ ) : field.control === "select" ? (+ <Select+ value={values[field.key] ?? ""}+ options={(field.options ?? []).map((o) => ({+ value: o.value,+ label: t(o.labelKey),+ }))}+ onChange={(v) => v && setValue(field.key, v)}+ />+ ) : (+ <Input+ value={values[field.key] ?? ""}+ placeholder={+ field.placeholderKey ? t(field.placeholderKey) : undefined+ }+ onChange={(e) => setValue(field.key, e.target.value)}+ />+ )}+ </FormField>+ ))}++ {selected.custom && (+ <CustomCallFields parameters={parameters} onChange={onChange} />+ )}+ </div>+ );+}++function OperationGrid({+ operations,+ onPick,+}: {+ operations: StepOperation[];+ onPick: (op: StepOperation) => void;+}) {+ const { t } = useTranslation();+ return (+ <div className="portal-conn-picker__grid">+ {operations.map((op) => {+ const label = t(op.labelKey);+ return (+ <button+ key={op.id}+ type="button"+ className={+ "portal-conn-picker__card" ++ (op.custom ? " portal-conn-picker__card--advanced" : "")+ }+ onClick={() => onPick(op)}+ >+ <span+ className={`portal-conn-picker__mark portal-conn-picker__mark--${op.category}`}+ aria-hidden+ >+ {label.slice(0, 1)}+ </span>+ <span className="portal-conn-picker__card-text">+ <span className="portal-conn-picker__card-name">{label}</span>+ <span className="portal-conn-picker__card-desc">+ {t(op.descriptionKey)}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ );+}++/**+ * The raw call, shown only for Custom API. These are the same parameters a preset fills in+ * silently — exposed here because there is no template to fill them.+ */+function CustomCallFields({+ parameters,+ onChange,+}: {+ parameters: ExternalApiParams;+ onChange: (p: ExternalApiParams) => void;+}) {+ const { t } = useTranslation();+ const set = (key: keyof ExternalApiParams, value: string) =>+ onChange({ ...parameters, [key]: value });+ const str = (key: keyof ExternalApiParams) => parameters[key] ?? "";++ return (+ <>+ <FormField+ label={t("portal.policies.operations.fields.path.label")}+ helperText={t("portal.policies.operations.fields.path.helperText")}+ required+ >+ <Input+ value={str("path")}+ placeholder="/v1/scan"+ onChange={(e) => set("path", e.target.value)}+ />+ </FormField>++ <FormField label={t("portal.policies.operations.fields.method.label")}>+ <Select+ value={str("method") || "POST"}+ options={["POST", "PUT", "PATCH", "GET"].map((m) => ({+ value: m,+ label: m,+ }))}+ onChange={(v) => v && set("method", v)}+ />+ </FormField>++ <FormField+ label={t("portal.policies.operations.fields.bodyMode.label")}+ helperText={t("portal.policies.operations.fields.bodyMode.helperText")}+ >+ <Select+ value={str("bodyMode") || "multipart"}+ options={[+ {+ value: "multipart",+ label: t("portal.policies.operations.bodyMode.multipart"),+ },+ {+ value: "json",+ label: t("portal.policies.operations.bodyMode.json"),+ },+ {+ value: "binary",+ label: t("portal.policies.operations.bodyMode.binary"),+ },+ ]}+ onChange={(v) => v && set("bodyMode", v)}+ />+ </FormField>++ {(str("bodyMode") || "multipart") === "multipart" && (+ <FormField+ label={t("portal.policies.operations.fields.fileFieldName.label")}+ helperText={t(+ "portal.policies.operations.fields.fileFieldName.helperText",+ )}+ >+ <Input+ value={str("fileFieldName") || "file"}+ onChange={(e) => set("fileFieldName", e.target.value)}+ />+ </FormField>+ )}++ <FormField+ label={t("portal.policies.operations.fields.responseMode.label")}+ helperText={t(+ "portal.policies.operations.fields.responseMode.helperText",+ )}+ >+ <Select+ value={str("responseMode") || "report"}+ options={[+ {+ value: "report",+ label: t("portal.policies.operations.responseMode.report"),+ },+ {+ value: "replace",+ label: t("portal.policies.operations.responseMode.replace"),+ },+ ]}+ onChange={(v) => v && set("responseMode", v)}+ />+ </FormField>++ <FormField+ label={t("portal.policies.operations.fields.headers.label")}+ helperText={t("portal.policies.operations.fields.headers.helperText")}+ >+ <textarea+ className="portal-sources__connection-textarea"+ rows={2}+ value={str("headers")}+ placeholder='{"X-Api-Version": "2"}'+ onChange={(e) => set("headers", e.target.value)}+ />+ </FormField>++ {(str("bodyMode") || "multipart") === "json" && (+ <FormField+ label={t("portal.policies.operations.fields.bodyTemplate.label")}+ helperText={t(+ "portal.policies.operations.fields.bodyTemplate.helperText",+ )}+ >+ <textarea+ className="portal-sources__connection-textarea"+ rows={4}+ value={str("bodyTemplate")}+ placeholder='{"file": "{{document.base64}}"}'+ onChange={(e) => set("bodyTemplate", e.target.value)}+ />+ </FormField>+ )}+ </>+ );+}diff --git a/frontend/editor/src/portal/components/policies/PolicyPurviewConfig.tsx b/frontend/editor/src/portal/components/policies/PolicyPurviewConfig.tsxnew file mode 100644index 0000000000..685fa49ffb--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicyPurviewConfig.tsx@@ -0,0 +1,93 @@+import { useTranslation } from "react-i18next";+import { FormField, Input, Select } from "@app/ui";+import { ConnectionPicker } from "@portal/components/sources/ConnectionPicker";++/**+ * Configures the Purview labelling step: which tenant, and which label.+ *+ * The label is entered as its GUID. Listing labels by name needs Graph and an app registration,+ * which a connection may not have — so the GUID is the honest lowest common denominator, and the+ * name is optional metadata written alongside it (Microsoft stopped writing friendly names, but a+ * label carrying one is still easier to recognise downstream).+ */+export interface PurviewLabelParams {+ connectionId: string;+ labelId: string;+ labelName: string;+ method: string;+}++interface PolicyPurviewConfigProps {+ parameters: PurviewLabelParams;+ onChange: (parameters: PurviewLabelParams) => void;+}++export function PolicyPurviewConfig({+ parameters,+ onChange,+}: PolicyPurviewConfigProps) {+ const { t } = useTranslation();+ const set = (key: keyof PurviewLabelParams, value: string) =>+ onChange({ ...parameters, [key]: value });++ return (+ <div className="portal-policies__capability-config">+ <FormField+ label={t("portal.policies.config.purview.fields.connection")}+ required+ >+ <ConnectionPicker+ value={parameters.connectionId ?? ""}+ onChange={(id) => set("connectionId", id)}+ integrationType="PURVIEW"+ createTypeId="purview"+ />+ </FormField>++ <FormField+ label={t("portal.policies.config.purview.fields.labelId")}+ helperText={t("portal.policies.config.purview.fields.labelIdHelp")}+ required+ >+ <Input+ value={parameters.labelId ?? ""}+ placeholder="2096f6a2-d2f7-48be-b329-b73aaa526e5d"+ onChange={(e) => set("labelId", e.target.value)}+ />+ </FormField>++ <FormField+ label={t("portal.policies.config.purview.fields.labelName")}+ helperText={t("portal.policies.config.purview.fields.labelNameHelp")}+ >+ <Input+ value={parameters.labelName ?? ""}+ placeholder="Confidential"+ onChange={(e) => set("labelName", e.target.value)}+ />+ </FormField>++ <FormField+ label={t("portal.policies.config.purview.fields.method.label")}+ helperText={t("portal.policies.config.purview.fields.method.help")}+ >+ <Select+ value={parameters.method || "STANDARD"}+ options={[+ {+ value: "STANDARD",+ label: t("portal.policies.config.purview.fields.method.standard"),+ },+ {+ value: "PRIVILEGED",+ label: t(+ "portal.policies.config.purview.fields.method.privileged",+ ),+ },+ ]}+ onChange={(value) => set("method", value ?? "STANDARD")}+ />+ </FormField>+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.tsx b/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.tsxnew file mode 100644index 0000000000..1b5c9ec7bc--- /dev/null+++ b/frontend/editor/src/portal/components/policies/PolicyPurviewReadConfig.tsx@@ -0,0 +1,45 @@+import { useTranslation } from "react-i18next";+import { FormField } from "@app/ui";+import { ConnectionPicker } from "@portal/components/sources/ConnectionPicker";++/**+ * Configures the "read a Purview label" step: which tenant to read against.+ *+ * This is the join-don't-beat primitive. Purview classifies documents; this reads the label it+ * applied so the rest of the policy can act on it - redact, watermark, route - which is the+ * PDF-specific work Purview does not do. Only the tenant matters here; the report the step emits+ * carries whatever label the document already holds.+ */+export interface PurviewReadParams {+ connectionId: string;+}++interface PolicyPurviewReadConfigProps {+ parameters: PurviewReadParams;+ onChange: (parameters: PurviewReadParams) => void;+}++export function PolicyPurviewReadConfig({+ parameters,+ onChange,+}: PolicyPurviewReadConfigProps) {+ const { t } = useTranslation();+ return (+ <div className="portal-policies__capability-config">+ <FormField+ label={t("portal.policies.config.purviewRead.fields.connection")}+ helperText={t(+ "portal.policies.config.purviewRead.fields.connectionHelp",+ )}+ required+ >+ <ConnectionPicker+ value={parameters.connectionId ?? ""}+ onChange={(id) => onChange({ ...parameters, connectionId: id })}+ integrationType="PURVIEW"+ createTypeId="purview"+ />+ </FormField>+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsxindex 91765fe0e7..503811eeda 100644--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx@@ -37,12 +37,21 @@ vi.mock("@portal/api/sources", () => ({fetchSources: () => fetchSources(),}));+const fetchIntegrations = vi.fn();+vi.mock("@portal/api/integrations", () => ({+ fetchIntegrations: () => fetchIntegrations(),+}));+const CONTINUE = "portal.policies.wizard.actions.continue";const SAVE_CHANGES = "portal.policies.wizard.actions.saveChanges";const ENABLE = "portal.policies.wizard.actions.enablePolicy";const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;const securityConfig = POLICY_CONFIG.security;+const compliance = POLICY_CATEGORIES.find((c) => c.id === "compliance")!;+const complianceConfig = POLICY_CONFIG.compliance;++const PURVIEW_LABEL = "Apply a Microsoft Purview sensitivity label";function editEntry(steps: PipelineStep[]): CatalogueEntry {const policy: DecoratedPolicy = {@@ -80,6 +89,7 @@ async function submitWizard(saveLabel: string) {describe("PolicySetupWizard", () => {beforeEach(() => {fetchSources.mockResolvedValue({ sources: [] });+ fetchIntegrations.mockResolvedValue([]);});it("round-trips a saved step's backend params on edit", async () => {@@ -107,6 +117,43 @@ describe("PolicySetupWizard", () => {]);});+ it("hides the Purview step when no Purview tenant is connected", async () => {+ fetchIntegrations.mockResolvedValue([]);+ const entry: CatalogueEntry = {+ category: compliance,+ config: complianceConfig,+ policy: null,+ };++ render(+ <PolicySetupWizard entry={entry} onClose={vi.fn()} onSubmit={vi.fn()} />,+ );++ // Sanitize is in the same chain and always shows, so once it renders the chain has loaded.+ await screen.findByText("Strip active content");+ // The Purview option can only fail without a connection, so it is not offered at all.+ expect(screen.queryByText(PURVIEW_LABEL)).toBeNull();+ });++ it("offers the Purview step once a Purview connection exists", async () => {+ fetchIntegrations.mockResolvedValue([+ { id: 1, name: "Corp Purview", integrationType: "PURVIEW", config: {} },+ ]);+ const entry: CatalogueEntry = {+ category: compliance,+ config: complianceConfig,+ policy: null,+ };++ render(+ <PolicySetupWizard entry={entry} onClose={vi.fn()} onSubmit={vi.fn()} />,+ );++ await waitFor(() =>+ expect(screen.getByText(PURVIEW_LABEL)).toBeInTheDocument(),+ );+ });+it("seeds the preset chain for a new policy (redact + sanitize on, watermark off)", async () => {const onSubmit = vi.fn().mockResolvedValue(undefined);const entry: CatalogueEntry = {diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsxindex 6c5d73786c..e56065ce48 100644--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx@@ -32,11 +32,14 @@ import {type PolicyToolStep,} from "@app/policies/operations";import { fetchSources } from "@portal/api/sources";+import { fetchIntegrations } from "@portal/api/integrations";+import { errorMessage } from "@portal/api/http";import { useAsync } from "@portal/hooks/useAsync";import { PolicyFieldRow } from "@portal/components/policies/PolicyFieldRow";import { PolicyCategoryBadge } from "@portal/components/policies/PolicyCategoryIcon";import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";+import { PolicyPurviewConfig } from "@portal/components/policies/PolicyPurviewConfig";import { ClassificationLabelsSection } from "@portal/components/policies/ClassificationLabelsSection";import "@portal/views/Policies.css";@@ -87,7 +90,21 @@ function resolveFieldValues(* starts enabled — the user toggles tools off in the workflow.*/// Temporary until the catalogue carries a defaultEnabled flag.-const DISABLED_BY_DEFAULT = new Set<PolicyToolId>(["watermark"]);+// Steps that cannot work until someone configures them, so they start off rather than failing+// every run of a freshly created policy. Purview needs a tenant connection and a label GUID.+const DISABLED_BY_DEFAULT = new Set<PolicyToolId>([+ "watermark",+ "purviewApplyLabel",+ "purviewReadLabel",+ "externalApiCall",+]);++// Steps that cannot work without a Purview tenant connection, so they are hidden entirely until one+// is configured rather than offered as an option that can only fail.+const PURVIEW_TOOLS = new Set<PolicyToolId>([+ "purviewApplyLabel",+ "purviewReadLabel",+]);/*** Policy-facing framing for each capability a policy can include. Labels and@@ -154,6 +171,27 @@ const CAPABILITY_META: Record<descEn:"Identifies the document's type from your team's labels and tags it, so it files and searches by category.",},+ purviewApplyLabel: {+ labelKey: "portal.policies.wizard.capability.purviewApplyLabel.label",+ labelEn: "Apply a Microsoft Purview sensitivity label",+ descKey: "portal.policies.wizard.capability.purviewApplyLabel.desc",+ descEn:+ "Marks the document with one of your organisation's Purview labels, so Purview-aware tools recognise how sensitive it is.",+ },+ purviewReadLabel: {+ labelKey: "portal.policies.wizard.capability.purviewReadLabel.label",+ labelEn: "Read the document's Purview label",+ descKey: "portal.policies.wizard.capability.purviewReadLabel.desc",+ descEn:+ "Reports the Purview label a document already carries, so the rest of the policy can act on how sensitive it is.",+ },+ externalApiCall: {+ labelKey: "portal.policies.wizard.capability.externalApiCall.label",+ labelEn: "Send the document to another system",+ descKey: "portal.policies.wizard.capability.externalApiCall.desc",+ descEn:+ "Hands the document to a system you have connected, and records what it answered.",+ },};function seedTools(entry: CatalogueEntry): ToolState[] {@@ -278,7 +316,31 @@ function PolicySetupWizardBody({const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);- const enabledTools = useMemo(() => tools.filter((tl) => tl.enabled), [tools]);+ const integrationsAsync = useAsync(() => fetchIntegrations(), []);+ const hasPurviewConnection = useMemo(+ () =>+ (integrationsAsync.data ?? []).some(+ (c) => c.integrationType === "PURVIEW",+ ),+ [integrationsAsync.data],+ );++ // Purview steps only appear once a tenant is connected. An already-enabled one (a saved policy,+ // or a tenant connected earlier) stays visible so editing a policy never silently drops it.+ const visibleTools = useMemo(+ () =>+ tools.filter(+ (tl) =>+ !PURVIEW_TOOLS.has(tl.toolId) || hasPurviewConnection || tl.enabled,+ ),+ [tools, hasPurviewConnection],+ );++ // Derive from the visible list: a hidden step is never submitted (hidden implies disabled).+ const enabledTools = useMemo(+ () => visibleTools.filter((tl) => tl.enabled),+ [visibleTools],+ );function setToolEnabled(toolId: PolicyToolId, enabled: boolean) {setTools((prev) =>@@ -329,9 +391,13 @@ function PolicySetupWizardBody({retryDelayMinutes,steps,});- } catch {+ } catch (e) {setSubmitting(false);- setError(t("portal.policies.wizard.errors.saveFailed"));+ // Surface the backend's actual reason (e.g. a step missing its account) rather than a+ // generic failure the operator cannot act on.+ setError(+ errorMessage(e) || t("portal.policies.wizard.errors.saveFailed"),+ );}}@@ -433,7 +499,7 @@ function PolicySetupWizardBody({</p><Card padding="none"><div className="portal-policies__capabilities">- {tools.map((tl) => {+ {visibleTools.map((tl) => {const meta = CAPABILITY_META[tl.toolId];const label = meta? t(meta.labelKey, meta.labelEn)@@ -479,6 +545,14 @@ function PolicySetupWizardBody({}/>)}+ {tl.toolId === "purviewApplyLabel" && (+ <PolicyPurviewConfig+ parameters={tl.params}+ onChange={(params) =>+ setToolParams("purviewApplyLabel", params)+ }+ />+ )}</div>)}</div>diff --git a/frontend/editor/src/portal/components/policies/stepOperations.test.ts b/frontend/editor/src/portal/components/policies/stepOperations.test.tsnew file mode 100644index 0000000000..3c2dd1c29c--- /dev/null+++ b/frontend/editor/src/portal/components/policies/stepOperations.test.ts@@ -0,0 +1,251 @@+import { describe, expect, it } from "vitest";++import {+ STEP_OPERATIONS,+ buildStepParameters,+ emptyOperationValues,+ operationById,+ operationFormValid,+ searchOperations,+} from "@portal/components/policies/stepOperations";+import { CREATABLE_CONNECTION_TYPES } from "@portal/components/sources/connectionTypes";++const t = (key: string) => key;++describe("STEP_OPERATIONS", () => {+ it("every operation rides a connection type that exists", () => {+ // An operation whose credential cannot be created is unusable, and the picker would offer+ // inline creation of a type that isn't in the catalogue.+ const ids = new Set(CREATABLE_CONNECTION_TYPES.map((c) => c.id));+ for (const op of STEP_OPERATIONS) {+ expect(ids, `${op.id} -> ${op.connectionTypeId}`).toContain(+ op.connectionTypeId,+ );+ }+ });++ it("has no duplicate ids", () => {+ const ids = STEP_OPERATIONS.map((o) => o.id);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it("every placeholder in a call is backed by a field the operator can fill", () => {+ // A {{token}} with no matching field would reach the backend unresolved and be sent literally.+ const contextual = /^(document|run|classification|sensitivityLabel)\./;+ for (const op of STEP_OPERATIONS) {+ const blob = [+ op.call.path,+ op.call.bodyTemplate ?? "",+ JSON.stringify(op.call.headers ?? {}),+ JSON.stringify(op.call.fields ?? {}),+ ].join(" ");+ const used = [...blob.matchAll(/\{\{([a-zA-Z0-9_.]+)\}\}/g)].map(+ (m) => m[1],+ );+ const declared = new Set((op.fields ?? []).map((f) => f.key));+ for (const token of used) {+ if (contextual.test(token)) continue; // resolved per document by the backend+ expect(declared, `${op.id} uses {{${token}}}`).toContain(token);+ }+ }+ });+});++describe("buildStepParameters", () => {+ it("substitutes the operator's answers into the path", () => {+ const jira = operationById("jiraAttach")!;+ const params = buildStepParameters(jira, "7", { issueKey: "OPS-42" });++ expect(params.path).toBe("/rest/api/3/issue/OPS-42/attachments");+ expect(params.connectionId).toBe("7");+ expect(params.fileFieldName).toBe("file");+ // The header Jira rejects the upload without.+ expect(JSON.parse(params.headers)).toEqual({+ "X-Atlassian-Token": "no-check",+ });+ });++ it("leaves per-document placeholders for the backend to resolve", () => {+ const splunk = operationById("splunkEvent")!;+ const params = buildStepParameters(splunk, "1", {});++ // These are resolved per document at run time, not here.+ expect(params.bodyTemplate).toContain("{{document.sha256}}");+ expect(params.bodyTemplate).toContain("{{run.policyName}}");+ expect(params.includeFile).toBe("false");+ });++ it("emits a complete parameter set even for a minimal operation", () => {+ const clamav = operationById("clamavScan")!;+ const params = buildStepParameters(clamav, "3", {});++ for (const key of [+ "connectionId",+ "path",+ "method",+ "bodyMode",+ "fileFieldName",+ "responseMode",+ "responseSelect",+ "resultUrlPath",+ "resultUrlHeader",+ "headers",+ "fields",+ "bodyTemplate",+ "includeContext",+ "includeFile",+ "operationId",+ "operationValues",+ ]) {+ expect(params, key).toHaveProperty(key);+ }+ expect(params.operationId).toBe("clamavScan");+ });++ it("remembers the operation and answers so a saved step reopens configured", () => {+ const nextcloud = operationById("nextcloudUpload")!;+ const values = { username: "svc", remotePath: "Processed/x.pdf" };+ const params = buildStepParameters(nextcloud, "9", values);++ expect(params.operationId).toBe("nextcloudUpload");+ expect(JSON.parse(params.operationValues)).toEqual(values);+ expect(params.method).toBe("PUT");+ expect(params.bodyMode).toBe("binary");+ });+});++describe("operation form", () => {+ it("seeds defaults and enforces required fields", () => {+ const elastic = operationById("elasticIndex")!;+ const seeded = emptyOperationValues(elastic);++ expect(seeded.index).toBe("stirling-audit");+ expect(operationFormValid(elastic, seeded)).toBe(true);+ expect(operationFormValid(elastic, { index: " " })).toBe(false);+ });++ it("an operation with no fields is immediately valid", () => {+ const cloudmersive = operationById("cloudmersiveScan")!;+ expect(operationFormValid(cloudmersive, {})).toBe(true);+ });+});++describe("searchOperations", () => {+ it("matches the job word, not just the product name", () => {+ const hits = searchOperations(STEP_OPERATIONS, "malware", t).map(+ (o) => o.id,+ );+ expect(hits).toContain("cloudmersiveScan");+ expect(hits).toContain("clamavScan");+ expect(hits).not.toContain("jiraAttach");+ });++ it("returns everything for an empty query", () => {+ expect(searchOperations(STEP_OPERATIONS, " ", t)).toHaveLength(+ STEP_OPERATIONS.length,+ );+ });+});++describe("substituting operator answers into a JSON body", () => {+ it("escapes an answer so a quote does not break the body", () => {+ // The operator types prose, not JSON. An apostrophe is fine; a double quote or a backslash+ // used to land raw inside the serialised template and the backend rejected the whole step+ // with "bodyTemplate must be valid JSON".+ const op = operationById("discordNotify")!;+ const params = buildStepParameters(op, "9", {+ message: 'Tagged the "processed" batch \\ archived',+ });++ const body: unknown = JSON.parse(params.bodyTemplate);+ expect(body).toEqual({+ content: 'Tagged the "processed" batch \\ archived',+ });+ });++ it("leaves the backend's own placeholders for the server pass", () => {+ // {{document.filename}} carries a dot, so the client substituter must not touch it.+ const op = operationById("discordNotify")!;+ const params = buildStepParameters(op, "9", {+ message: "{{run.policyName}} did {{document.filename}}",+ });++ expect(params.bodyTemplate).toContain("{{document.filename}}");+ expect(JSON.parse(params.bodyTemplate)).toEqual({+ content: "{{run.policyName}} did {{document.filename}}",+ });+ });++ it("escapes a quoted answer substituted into the fields map", () => {+ // Mailgun is the entry that actually templates `fields`, and a subject line is exactly the+ // kind of free text an operator puts quotes in.+ const op = operationById("mailgunEmail")!;+ const params = buildStepParameters(op, "3", {+ domain: "mg.example.test",+ to: "[email protected]",+ from: "[email protected]",+ subject: 'Re: the "urgent" batch',+ });++ expect(JSON.parse(params.fields)).toMatchObject({+ subject: 'Re: the "urgent" batch',+ to: "[email protected]",+ });+ // The path is not JSON, so it keeps the plain substitution.+ expect(params.path).toBe("/v3/mg.example.test/messages");+ });+});++describe("the Cloudmersive scan gate", () => {+ it("sends CleanResult as a verdict gate, not a no-op archive selector", () => {+ // The old shape put "CleanResult" in responseSelect, which the backend only reads in replace+ // mode as a ZIP-entry name - so an infected file (HTTP 200, CleanResult:false) sailed through.+ // It must ride requireTrue, which the backend enforces in report mode.+ const params = buildStepParameters(+ operationById("cloudmersiveScan")!,+ "3",+ {},+ );++ expect(params.requireTrue).toBe("CleanResult");+ expect(params.responseSelect).toBe("");+ expect(params.responseMode).toBe("report");+ });++ it("gates the advanced scan too", () => {+ const params = buildStepParameters(+ operationById("cloudmersiveAdvancedScan")!,+ "3",+ {},+ );+ expect(params.requireTrue).toBe("CleanResult");+ });++ it("leaves requireTrue blank for operations that do not gate", () => {+ const params = buildStepParameters(operationById("discordNotify")!, "3", {+ message: "hi",+ });+ expect(params.requireTrue).toBe("");+ });+});++describe("substituting an answer into the URL path", () => {+ it("percent-encodes the answer so a slash stays a value, not a new segment", () => {+ // A Jira key like "OPS/1" (or a space) must not add a path segment or reach another endpoint.+ const params = buildStepParameters(operationById("jiraAttach")!, "3", {+ issueKey: "OPS 1/2",+ });++ expect(params.path).toBe("/rest/api/3/issue/OPS%201%2F2/attachments");+ expect(params.path).not.toContain(" ");+ });++ it("leaves the backend's own {{document.*}} placeholders in the path untouched", () => {+ // Mailgun's path carries {{domain}} (an operator field) but backend placeholders would have+ // dots; only the operator field is substituted and encoded here.+ const params = buildStepParameters(operationById("mailgunEmail")!, "3", {+ domain: "mg.acme.com",+ });+ expect(params.path).toBe("/v3/mg.acme.com/messages");+ });+});diff --git a/frontend/editor/src/portal/components/policies/stepOperations.ts b/frontend/editor/src/portal/components/policies/stepOperations.tsnew file mode 100644index 0000000000..5c6e0958d9--- /dev/null+++ b/frontend/editor/src/portal/components/policies/stepOperations.ts@@ -0,0 +1,672 @@+/**+ * What a connection can actually *do* — the operations catalogue.+ *+ * A connection stores credentials; it does not know how to call anything. This file supplies the+ * other half: for each vendor, the exact call that makes it useful. Without it, picking+ * "Cloudmersive" gets an operator a saved API key and a blank form asking for a URL path, a body+ * mode and a field name they would have to read the vendor's docs to discover.+ *+ * Mirrors {@link CREATABLE_CONNECTION_TYPES} deliberately: an operation is added by describing the+ * call, not by writing a component. Adding a vendor operation is an entry here plus two lines of+ * copy — the same bar that made the connection catalogue maintainable.+ *+ * Every `call` below was exercised against the real vendor or a contract-accurate mock; the shapes+ * are not guesses. Where a vendor needs something only the operator knows (a Jira issue key, a+ * Splunk index), that becomes a `field` and is substituted into the path or body via the backend's+ * `{{placeholder}}` resolution — which also gives the operator `{{document.*}}` and `{{run.*}}`.+ */++import type { IntegrationType } from "@portal/api/integrations";+import type { ConnectionCategory } from "@portal/components/sources/connectionTypes";++/**+ * The complete parameter set of the `external-api-call` step. Every key is present and every+ * value is a string, because the pipeline serialises steps as form fields.+ */+export interface ExternalApiStepParams {+ connectionId: string;+ path: string;+ method: string;+ bodyMode: string;+ fileFieldName: string;+ responseMode: string;+ resultUrlPath: string;+ resultUrlHeader: string;+ responseSelect: string;+ requireTrue: string;+ fields: string;+ headers: string;+ bodyTemplate: string;+ includeContext: string;+ includeFile: string;+ operationId: string;+ operationValues: string;+}++const PREFIX = "portal.policies.operations";++/** One value the operator supplies per step, substituted into the call. */+export interface OperationFieldDef {+ key: string;+ labelKey: string;+ control: "text" | "textarea" | "select";+ required?: boolean;+ placeholderKey?: string;+ helperTextKey?: string;+ defaultValue?: string;+ options?: { value: string; labelKey: string }[];+}++/**+ * The wire call, in the vocabulary the `external-api-call` step already accepts. Anything omitted+ * falls back to the step's own defaults, so an entry states only what is distinctive about it.+ */+export interface OperationCall {+ /** Relative to the connection's base URL. May carry `{{field}}` and `{{document.*}}`. */+ path: string;+ method?: "POST" | "PUT" | "PATCH" | "GET";+ bodyMode?: "multipart" | "json" | "binary";+ /** Multipart only: the form field the vendor expects the document under. */+ fileFieldName?: string;+ /** `report` leaves the document untouched; `replace` swaps it for what came back. */+ responseMode?: "report" | "replace";+ /** Archive-entry selector for `replace` mode (e.g. `*.pdf`); not a JSON verdict. */+ responseSelect?: string;+ /**+ * A dotted path into the JSON response that must be `true`, or the step fails and the document is+ * parked. This is the scan gate: Cloudmersive's `CleanResult` stops the run when a file is not+ * clean, rather than the verdict being merely reported and ignored.+ */+ requireTrue?: string;+ headers?: Record<string, string>;+ fields?: Record<string, string>;+ bodyTemplate?: string;+ /** False for notify-style calls that send facts rather than the document. */+ includeFile?: boolean;+}++export interface StepOperation {+ id: string;+ /** The connection preset this rides, so the picker can offer inline creation of the right type. */+ connectionTypeId: string;+ integrationType: IntegrationType;+ category: ConnectionCategory;+ labelKey: string;+ descriptionKey: string;+ searchTerms?: string[];+ call: OperationCall;+ fields?: OperationFieldDef[];+ /**+ * True for the escape hatch, where the operator authors the call themselves. Admin-gated by the+ * same server flag as the custom connection; the UI only decides whether to offer it.+ */+ custom?: boolean;+ /** Shown as a caveat in the picker when a vendor has a known limitation. */+ noteKey?: string;+}++const f = (+ key: string,+ control: OperationFieldDef["control"] = "text",+ required = true,+): OperationFieldDef => ({+ key,+ labelKey: `${PREFIX}.fields.${key}.label`,+ control,+ required,+ placeholderKey: `${PREFIX}.fields.${key}.placeholder`,+});++/** A notify call: JSON facts, no document, posted straight at the webhook URL. */+function notify(+ id: string,+ connectionTypeId: string,+ bodyKey: string,+ searchTerms: string[],+): StepOperation {+ return {+ id,+ connectionTypeId,+ integrationType: "API",+ category: "notify",+ labelKey: `${PREFIX}.${id}.label`,+ descriptionKey: `${PREFIX}.${id}.description`,+ searchTerms,+ call: {+ // The webhook URL is the whole endpoint, so the step adds no path of its own.+ path: "",+ bodyMode: "json",+ includeFile: false,+ bodyTemplate: JSON.stringify({ [bodyKey]: "{{message}}" }),+ },+ fields: [+ {+ key: "message",+ labelKey: `${PREFIX}.fields.message.label`,+ control: "textarea",+ required: true,+ helperTextKey: `${PREFIX}.fields.message.helperText`,+ defaultValue:+ "{{run.policyName}} processed {{document.filename}} ({{document.pageCount}} pages)",+ },+ ],+ };+}++export const STEP_OPERATIONS: StepOperation[] = [+ // ---- scan & classify: the verdict gates the run ------------------------------------------+ {+ id: "cloudmersiveScan",+ connectionTypeId: "cloudmersive",+ integrationType: "API",+ category: "security",+ labelKey: `${PREFIX}.cloudmersiveScan.label`,+ descriptionKey: `${PREFIX}.cloudmersiveScan.description`,+ searchTerms: ["virus", "malware", "scan", "av", "antivirus"],+ // Verified against the live API: a clean PDF returns {"CleanResult":true}. The verdict gates+ // the run - CleanResult=false fails the step even though the HTTP status is 200.+ call: {+ path: "/virus/scan/file",+ bodyMode: "multipart",+ fileFieldName: "inputFile",+ responseMode: "report",+ requireTrue: "CleanResult",+ },+ },+ {+ id: "cloudmersiveAdvancedScan",+ connectionTypeId: "cloudmersiveadvanced",+ integrationType: "API",+ category: "security",+ labelKey: `${PREFIX}.cloudmersiveAdvancedScan.label`,+ descriptionKey: `${PREFIX}.cloudmersiveAdvancedScan.description`,+ searchTerms: [+ "macro",+ "executable",+ "script",+ "active content",+ "ole",+ "scan",+ ],+ // The block-list is expressed as headers; each defaults to false, i.e. blocking is ON. The+ // CleanResult verdict gates the run, so a blocked file stops the pipeline rather than passing.+ call: {+ path: "/virus/scan/file/advanced",+ bodyMode: "multipart",+ fileFieldName: "inputFile",+ responseMode: "report",+ requireTrue: "CleanResult",+ headers: {+ allowExecutables: "false",+ allowMacros: "false",+ allowScripts: "false",+ allowUnsafeArchives: "false",+ allowOleEmbeddedObject: "false",+ },+ },+ },+ {+ id: "clamavScan",+ connectionTypeId: "clamav",+ integrationType: "API",+ category: "security",+ labelKey: `${PREFIX}.clamavScan.label`,+ descriptionKey: `${PREFIX}.clamavScan.description`,+ searchTerms: ["virus", "malware", "scan", "self-hosted", "on-prem"],+ // Verified against a real ClamAV container: an infected file answers non-2xx, failing the step.+ call: {+ path: "/scan",+ bodyMode: "multipart",+ fileFieldName: "file",+ responseMode: "report",+ },+ },+ {+ id: "presidioAnalyze",+ connectionTypeId: "presidio",+ integrationType: "API",+ category: "security",+ labelKey: `${PREFIX}.presidioAnalyze.label`,+ descriptionKey: `${PREFIX}.presidioAnalyze.description`,+ searchTerms: ["pii", "personal data", "dlp", "gdpr", "detect"],+ noteKey: `${PREFIX}.presidioAnalyze.note`,+ // Presidio's analyser takes text, not a file - so the document is described, not uploaded.+ call: {+ path: "/analyze",+ bodyMode: "json",+ includeFile: false,+ responseMode: "report",+ bodyTemplate: JSON.stringify({ text: "{{text}}", language: "en" }),+ },+ fields: [+ {+ key: "text",+ labelKey: `${PREFIX}.fields.text.label`,+ control: "textarea",+ required: true,+ helperTextKey: `${PREFIX}.fields.text.helperText`,+ },+ ],+ },++ // ---- file & attach ------------------------------------------------------------------------+ {+ id: "jiraAttach",+ connectionTypeId: "jira",+ integrationType: "API",+ category: "storage",+ labelKey: `${PREFIX}.jiraAttach.label`,+ descriptionKey: `${PREFIX}.jiraAttach.description`,+ searchTerms: ["jira", "issue", "ticket", "attach", "atlassian"],+ // Verified against a real Jira Cloud site. The anti-XSRF header is mandatory.+ call: {+ path: "/rest/api/3/issue/{{issueKey}}/attachments",+ bodyMode: "multipart",+ fileFieldName: "file",+ responseMode: "report",+ headers: { "X-Atlassian-Token": "no-check" },+ },+ fields: [f("issueKey")],+ },+ {+ id: "confluenceAttach",+ connectionTypeId: "confluence",+ integrationType: "API",+ category: "storage",+ labelKey: `${PREFIX}.confluenceAttach.label`,+ descriptionKey: `${PREFIX}.confluenceAttach.description`,+ searchTerms: ["confluence", "page", "wiki", "attach", "atlassian"],+ // Verified against a real Confluence site. Note "nocheck" here vs Jira's "no-check", and that+ // only the v1 API can create an attachment.+ call: {+ path: "/wiki/rest/api/content/{{pageId}}/child/attachment",+ bodyMode: "multipart",+ fileFieldName: "file",+ responseMode: "report",+ headers: { "X-Atlassian-Token": "nocheck" },+ fields: { minorEdit: "true" },+ },+ fields: [f("pageId")],+ },+ {+ id: "nextcloudUpload",+ connectionTypeId: "nextcloud",+ integrationType: "API",+ category: "storage",+ labelKey: `${PREFIX}.nextcloudUpload.label`,+ descriptionKey: `${PREFIX}.nextcloudUpload.description`,+ searchTerms: ["nextcloud", "webdav", "upload", "file", "owncloud"],+ // Verified byte-identical against a real Nextcloud: WebDAV takes the raw bytes on a PUT.+ call: {+ path: "/remote.php/dav/files/{{username}}/{{remotePath}}",+ method: "PUT",+ bodyMode: "binary",+ responseMode: "report",+ },+ fields: [+ f("username"),+ {+ key: "remotePath",+ labelKey: `${PREFIX}.fields.remotePath.label`,+ control: "text",+ required: true,+ helperTextKey: `${PREFIX}.fields.remotePath.helperText`,+ defaultValue: "Processed/{{document.filename}}",+ },+ ],+ },++ // ---- audit & compliance logging -------------------------------------------------------------+ {+ id: "splunkEvent",+ connectionTypeId: "splunk",+ integrationType: "API",+ category: "audit",+ labelKey: `${PREFIX}.splunkEvent.label`,+ descriptionKey: `${PREFIX}.splunkEvent.description`,+ searchTerms: ["splunk", "hec", "siem", "audit", "log", "event"],+ // Verified against a real Splunk HEC; the event was found by Splunk's own search.+ call: {+ path: "/services/collector/event",+ bodyMode: "json",+ includeFile: false,+ responseMode: "report",+ bodyTemplate: JSON.stringify({+ sourcetype: "stirling:policy",+ event: {+ action: "policy.document.processed",+ policy: "{{run.policyName}}",+ runId: "{{run.runId}}",+ filename: "{{document.filename}}",+ sha256: "{{document.sha256}}",+ pages: "{{document.pageCount}}",+ },+ }),+ },+ },+ {+ id: "elasticIndex",+ connectionTypeId: "elastic",+ integrationType: "API",+ category: "audit",+ labelKey: `${PREFIX}.elasticIndex.label`,+ descriptionKey: `${PREFIX}.elasticIndex.description`,+ searchTerms: ["elastic", "elasticsearch", "siem", "audit", "index", "log"],+ // Verified against a real Elasticsearch: the event was queried back out afterwards.+ call: {+ path: "/{{index}}/_doc",+ bodyMode: "json",+ includeFile: false,+ responseMode: "report",+ bodyTemplate: JSON.stringify({+ event: "policy.document.processed",+ policy: "{{run.policyName}}",+ runId: "{{run.runId}}",+ filename: "{{document.filename}}",+ sha256: "{{document.sha256}}",+ }),+ },+ fields: [+ {+ key: "index",+ labelKey: `${PREFIX}.fields.index.label`,+ control: "text",+ required: true,+ defaultValue: "stirling-audit",+ },+ ],+ },+ {+ id: "sumologicEvent",+ connectionTypeId: "sumologic",+ integrationType: "API",+ category: "audit",+ labelKey: `${PREFIX}.sumologicEvent.label`,+ descriptionKey: `${PREFIX}.sumologicEvent.description`,+ searchTerms: ["sumo", "sumologic", "siem", "audit", "log"],+ call: {+ path: "",+ bodyMode: "json",+ includeFile: false,+ responseMode: "report",+ bodyTemplate: JSON.stringify({+ event: "policy.document.processed",+ policy: "{{run.policyName}}",+ filename: "{{document.filename}}",+ sha256: "{{document.sha256}}",+ }),+ },+ },++ // ---- email the document ----------------------------------------------------------------------+ {+ id: "sendgridEmail",+ connectionTypeId: "sendgrid",+ integrationType: "API",+ category: "notify",+ labelKey: `${PREFIX}.sendgridEmail.label`,+ descriptionKey: `${PREFIX}.sendgridEmail.description`,+ searchTerms: ["email", "mail", "send", "attachment", "sendgrid"],+ call: {+ path: "/v3/mail/send",+ bodyMode: "json",+ responseMode: "report",+ bodyTemplate: JSON.stringify({+ personalizations: [{ to: [{ email: "{{to}}" }] }],+ from: { email: "{{from}}" },+ subject: "{{subject}}",+ content: [+ { type: "text/plain", value: "Attached: {{document.filename}}" },+ ],+ attachments: [+ {+ content: "{{document.base64}}",+ filename: "{{document.filename}}",+ type: "application/pdf",+ disposition: "attachment",+ },+ ],+ }),+ },+ fields: [+ f("to"),+ f("from"),+ {+ key: "subject",+ labelKey: `${PREFIX}.fields.subject.label`,+ control: "text",+ required: true,+ defaultValue: "Processed: {{document.filename}}",+ },+ ],+ },+ {+ id: "mailgunEmail",+ connectionTypeId: "mailgun",+ integrationType: "API",+ category: "notify",+ labelKey: `${PREFIX}.mailgunEmail.label`,+ descriptionKey: `${PREFIX}.mailgunEmail.description`,+ searchTerms: ["email", "mail", "send", "attachment", "mailgun"],+ call: {+ path: "/v3/{{domain}}/messages",+ bodyMode: "multipart",+ fileFieldName: "attachment",+ responseMode: "report",+ responseSelect: "id",+ fields: {+ from: "{{from}}",+ to: "{{to}}",+ subject: "{{subject}}",+ text: "Attached: {{document.filename}}",+ },+ },+ fields: [+ f("domain"),+ f("to"),+ f("from"),+ {+ key: "subject",+ labelKey: `${PREFIX}.fields.subject.label`,+ control: "text",+ required: true,+ defaultValue: "Processed: {{document.filename}}",+ },+ ],+ },++ // ---- notify: one shape, several vendors -------------------------------------------------------+ notify("slackNotify", "slack", "text", [+ "slack",+ "chat",+ "notify",+ "message",+ ]),+ notify("teamsNotify", "teams", "text", [+ "teams",+ "microsoft",+ "chat",+ "notify",+ ]),+ notify("discordNotify", "discord", "content", ["discord", "chat", "notify"]),+ notify("googlechatNotify", "googlechat", "text", [+ "google",+ "chat",+ "notify",+ ]),+ notify("zapierNotify", "zapier", "text", [+ "zapier",+ "make",+ "automation",+ "trigger",+ ]),++ {+ id: "webhookPost",+ connectionTypeId: "webhook",+ integrationType: "API",+ category: "notify",+ labelKey: `${PREFIX}.webhookPost.label`,+ descriptionKey: `${PREFIX}.webhookPost.description`,+ searchTerms: ["webhook", "http", "post", "callback", "custom"],+ call: {+ path: "",+ bodyMode: "multipart",+ fileFieldName: "file",+ responseMode: "report",+ },+ },++ // ---- sign ---------------------------------------------------------------------------------------+ {+ id: "consignoSubmit",+ connectionTypeId: "consigno",+ integrationType: "CONSIGNO",+ category: "signing",+ labelKey: `${PREFIX}.consignoSubmit.label`,+ descriptionKey: `${PREFIX}.consignoSubmit.description`,+ searchTerms: ["consigno", "notarius", "sign", "signature", "esign"],+ noteKey: `${PREFIX}.consignoSubmit.note`,+ call: {+ path: "/workflows",+ bodyMode: "json",+ responseMode: "report",+ bodyTemplate: JSON.stringify({+ name: "{{document.filename}}",+ documents: [+ { name: "{{document.filename}}", data: "{{document.base64}}" },+ ],+ signers: [{ email: "{{signerEmail}}", type: "certifio" }],+ }),+ },+ fields: [f("signerEmail")],+ },++ // ---- the escape hatch ---------------------------------------------------------------------------+ {+ id: "customApiCall",+ connectionTypeId: "api",+ integrationType: "API",+ category: "advanced",+ labelKey: `${PREFIX}.customApiCall.label`,+ descriptionKey: `${PREFIX}.customApiCall.description`,+ searchTerms: ["custom", "api", "http", "advanced", "anything"],+ custom: true,+ // Nothing baked in: every part of the call is the operator's to author.+ call: {+ path: "",+ bodyMode: "multipart",+ fileFieldName: "file",+ responseMode: "report",+ },+ },+];++/** Operations grouped for the picker, in the catalogue's own category order. */+export function operationsByCategory(+ operations: StepOperation[],+): Map<ConnectionCategory, StepOperation[]> {+ const map = new Map<ConnectionCategory, StepOperation[]>();+ for (const op of operations) {+ const list = map.get(op.category) ?? [];+ list.push(op);+ map.set(op.category, list);+ }+ return map;+}++/** Matches label, description and the vendor's own aliases, like the connection picker. */+export function searchOperations(+ operations: StepOperation[],+ query: string,+ t: (key: string) => string,+): StepOperation[] {+ const q = query.trim().toLowerCase();+ if (!q) return operations;+ return operations.filter((op) => {+ const haystack = [+ t(op.labelKey),+ t(op.descriptionKey),+ op.id,+ ...(op.searchTerms ?? []),+ ]+ .join(" ")+ .toLowerCase();+ return haystack.includes(q);+ });+}++/** The operator-supplied defaults for a freshly chosen operation. */+export function emptyOperationValues(+ op: StepOperation,+): Record<string, string> {+ const values: Record<string, string> = {};+ for (const field of op.fields ?? []) {+ values[field.key] = field.defaultValue ?? "";+ }+ return values;+}++export function operationFormValid(+ op: StepOperation,+ values: Record<string, string>,+): boolean {+ return (op.fields ?? []).every(+ (field) => !field.required || (values[field.key] ?? "").trim() !== "",+ );+}++/**+ * Turn a chosen operation plus the operator's answers into the parameters the+ * `external-api-call` step takes.+ *+ * Operator values are substituted into the call's own `{{placeholders}}` here, in the client,+ * because they are step configuration rather than per-document context. The backend's placeholder+ * pass then resolves the remaining `{{document.*}}` and `{{run.*}}` at run time, per document.+ */+export function buildStepParameters(+ op: StepOperation,+ connectionId: string,+ values: Record<string, string>,+): ExternalApiStepParams {+ // Substituted into the URL path: the answer is percent-encoded, so a space or slash in a key+ // (a Jira "OPS 1", a path-shaped id) is a value, not a change to the target. Matches the+ // backend's URL_PATH escaping for its own {{document.*}} pass.+ const substitutePath = (text: string): string =>+ text.replace(/\{\{([a-zA-Z0-9_]+)\}\}/g, (whole, key: string) =>+ key in values ? encodeURIComponent(values[key]) : whole,+ );+ // Substituted into an already-serialised JSON string: a quote or backslash in an answer would+ // otherwise break the body, and the backend rejects it as invalid JSON.+ const substituteJson = (text: string): string =>+ text.replace(/\{\{([a-zA-Z0-9_]+)\}\}/g, (whole, key: string) =>+ key in values ? JSON.stringify(values[key]).slice(1, -1) : whole,+ );++ const call = op.call;+ // Every declared parameter is emitted, blank where the operation does not use it, so the result+ // is a complete step rather than a partial one the caller has to top up.+ return {+ connectionId,+ path: substitutePath(call.path ?? ""),+ method: call.method ?? "POST",+ bodyMode: call.bodyMode ?? "multipart",+ fileFieldName: call.fileFieldName ?? "file",+ responseMode: call.responseMode ?? "report",+ responseSelect: call.responseSelect ?? "",+ requireTrue: call.requireTrue ?? "",+ resultUrlPath: "",+ resultUrlHeader: "",+ headers: call.headers ? substituteJson(JSON.stringify(call.headers)) : "",+ fields: call.fields ? substituteJson(JSON.stringify(call.fields)) : "",+ bodyTemplate: call.bodyTemplate ? substituteJson(call.bodyTemplate) : "",+ includeContext: "false",+ includeFile: String(call.includeFile ?? true),+ operationId: op.id,+ operationValues: JSON.stringify(values),+ };+}++export function operationById(id: string): StepOperation | undefined {+ return STEP_OPERATIONS.find((op) => op.id === id);+}diff --git a/frontend/editor/src/portal/components/sources/ConnectionForm.tsx b/frontend/editor/src/portal/components/sources/ConnectionForm.tsxnew file mode 100644index 0000000000..a6cd42da89--- /dev/null+++ b/frontend/editor/src/portal/components/sources/ConnectionForm.tsx@@ -0,0 +1,105 @@+import { useTranslation } from "react-i18next";+import { FormField, Input, Select } from "@app/ui";+import {+ isFieldVisible,+ type ConnectionFieldDef,+ type CreatableConnectionType,+} from "@portal/components/sources/connectionTypes";++/**+ * Renders whatever fields a connection type declares, rather than knowing any vendor's shape.+ *+ * Mirrors how {@code SourceBuilder} renders {@code CREATABLE_SOURCE_TYPES}: adding Purview or+ * ConsignO is a descriptor, not a component. Secrets are write-only — on edit the backend returns+ * them masked and keeps the stored value when the mask is sent back untouched.+ */+interface ConnectionFormProps {+ type: CreatableConnectionType;+ /** Answers keyed by field key, plus `name`. Dotted keys nest at build time. */+ values: Record<string, string>;+ onChange: (values: Record<string, string>) => void;+}++export function ConnectionForm({+ type,+ values,+ onChange,+}: ConnectionFormProps) {+ const { t } = useTranslation();+ const set = (key: string, value: string) =>+ onChange({ ...values, [key]: value });++ return (+ <div className="portal-sources__connection-form">+ <FormField label={t("portal.connections.fields.name")} required>+ <Input+ value={values.name ?? ""}+ placeholder={t("portal.connections.fields.namePlaceholder")}+ onChange={(e) => set("name", e.target.value)}+ />+ </FormField>++ {type.fields+ // A hidden field keeps its value in state so switching auth type and back does not+ // silently discard what was typed; buildConnectionConfig sends only what is filled.+ .filter((field) => isFieldVisible(field, values))+ .map((field) => (+ <ConnectionField+ key={field.key}+ field={field}+ value={values[field.key] ?? ""}+ onChange={(value) => set(field.key, value)}+ />+ ))}+ </div>+ );+}++function ConnectionField({+ field,+ value,+ onChange,+}: {+ field: ConnectionFieldDef;+ value: string;+ onChange: (value: string) => void;+}) {+ const { t } = useTranslation();+ return (+ <FormField+ label={t(field.labelKey)}+ required={field.required}+ helperText={field.helperTextKey ? t(field.helperTextKey) : undefined}+ >+ {field.control === "select" ? (+ <Select+ value={value}+ options={(field.options ?? []).map((option) => ({+ value: option.value,+ label: t(option.labelKey),+ }))}+ onChange={(next) => onChange(next ?? "")}+ />+ ) : field.control === "textarea" || field.control === "hostList" ? (+ <textarea+ className="portal-sources__connection-textarea"+ rows={field.control === "hostList" ? 2 : 5}+ value={value}+ placeholder={+ field.placeholderKey ? t(field.placeholderKey) : undefined+ }+ onChange={(e) => onChange(e.target.value)}+ />+ ) : (+ <Input+ type={field.control === "password" ? "password" : undefined}+ value={value}+ placeholder={+ field.placeholderKey ? t(field.placeholderKey) : undefined+ }+ onChange={(e) => onChange(e.target.value)}+ />+ )}+ </FormField>+ );+}diff --git a/frontend/editor/src/portal/components/sources/ConnectionModal.test.tsx b/frontend/editor/src/portal/components/sources/ConnectionModal.test.tsxnew file mode 100644index 0000000000..c1a152ab8d--- /dev/null+++ b/frontend/editor/src/portal/components/sources/ConnectionModal.test.tsx@@ -0,0 +1,309 @@+import { MantineProvider } from "@mantine/core";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { ConnectionModal } from "@portal/components/sources/ConnectionModal";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@portal/api/integrations", () => ({+ createIntegration: vi.fn(),+ updateIntegration: vi.fn(),+}));++vi.mock("@portal/api/http", () => ({+ errorMessage: (e: unknown) => String(e),+}));++const { createIntegration, updateIntegration } =+ await import("@portal/api/integrations");++const wrap = (ui: React.ReactNode) => <MantineProvider>{ui}</MantineProvider>;++const fill = async (label: string, value: string) => {+ const field = screen.getByLabelText(label, { exact: false });+ await userEvent.clear(field);+ await userEvent.type(field, value);+};++describe("ConnectionModal", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(createIntegration).mockResolvedValue({ id: 7 } as never);+ vi.mocked(updateIntegration).mockResolvedValue({ id: 7 } as never);+ });++ it("creates a Purview connection with its tenant id", async () => {+ const onSaved = vi.fn();+ render(+ wrap(+ <ConnectionModal+ open+ fixedTypeId="purview"+ onClose={vi.fn()}+ onSaved={onSaved}+ />,+ ),+ );++ await fill("portal.connections.fields.name", "Corp Purview");+ await fill(+ "portal.connections.types.purview.fields.tenantId",+ "cb46c030-1825-4e81-a295-151c039dbf02",+ );+ await userEvent.click(screen.getByText("portal.connections.picker.save"));++ await waitFor(() =>+ expect(createIntegration).toHaveBeenCalledWith({+ integrationType: "PURVIEW",+ name: "Corp Purview",+ scope: "TEAM",+ config: {+ presetId: "purview",+ tenantId: "cb46c030-1825-4e81-a295-151c039dbf02",+ },+ }),+ );+ expect(onSaved).toHaveBeenCalled();+ });++ it("bakes the ConsignO preset into the saved config", async () => {+ render(+ wrap(+ <ConnectionModal+ open+ fixedTypeId="consigno"+ onClose={vi.fn()}+ onSaved={vi.fn()}+ />,+ ),+ );++ await fill("portal.connections.fields.name", "Notarius");+ await fill(+ "portal.connections.types.consigno.fields.baseUrl",+ "https://acme.consignocloud.com/api/v1",+ );+ await fill("portal.connections.types.consigno.fields.clientId", "cid");+ await fill(+ "portal.connections.types.consigno.fields.clientSecret",+ "csecret",+ );+ await fill(+ "portal.connections.types.consigno.fields.username",+ "[email protected]",+ );+ await fill("portal.connections.types.consigno.fields.password", "pw");+ await userEvent.click(screen.getByText("portal.connections.picker.save"));++ await waitFor(() => expect(createIntegration).toHaveBeenCalled());+ const body = vi.mocked(createIntegration).mock.calls[0][0];+ expect(body.integrationType).toBe("CONSIGNO");+ // The operator supplied credentials; the vendor's auth mechanics came from the preset.+ expect(body.config).toMatchObject({+ authType: "TOKEN_LOGIN",+ loginPath: "/auth/login",+ tokenResponseHeader: "X-Auth-Token",+ loginHeaders: { "X-Client-Id": "cid", "X-Client-Secret": "csecret" },+ loginBody: { username: "[email protected]", password: "pw" },+ });+ });++ it("round-trips a masked secret so the stored value is kept", async () => {+ render(+ wrap(+ <ConnectionModal+ open+ connection={+ {+ id: 3,+ integrationType: "S3",+ name: "Existing",+ config: {+ bucket: "b",+ region: "eu-west-2",+ accessKeyId: "AK",+ secretAccessKey: "********",+ },+ } as never+ }+ onClose={vi.fn()}+ onSaved={vi.fn()}+ />,+ ),+ );++ await userEvent.click(screen.getByText("portal.connections.picker.save"));++ await waitFor(() => expect(updateIntegration).toHaveBeenCalled());+ const [id, body] = vi.mocked(updateIntegration).mock.calls[0];+ expect(id).toBe(3);+ // Sending the mask back unchanged is what tells the backend to keep the real secret.+ expect(body.config).toMatchObject({+ secretAccessKey: "********",+ bucket: "b",+ });+ });++ it("cannot be saved until the required fields are filled", async () => {+ render(+ wrap(+ <ConnectionModal+ open+ fixedTypeId="purview"+ onClose={vi.fn()}+ onSaved={vi.fn()}+ />,+ ),+ );++ const save = screen.getByText("portal.connections.picker.save");+ expect(save.closest("button")).toBeDisabled();++ await fill("portal.connections.fields.name", "Corp");+ // Name alone is not enough: Purview needs a tenant id.+ expect(save.closest("button")).toBeDisabled();+ });++ it("offers custom API only to admins, and only under Advanced", async () => {+ const { rerender } = render(+ wrap(+ <ConnectionModal+ open+ capabilities={{ customApi: false }}+ onClose={vi.fn()}+ onSaved={vi.fn()}+ />,+ ),+ );+ // Not an admin: the escape hatch is not offered at all.+ expect(screen.queryByText("portal.connections.types.api.label")).toBeNull();+ expect(+ screen.queryByText("portal.connections.categories.advanced.label"),+ ).toBeNull();++ rerender(+ wrap(+ <ConnectionModal+ open+ capabilities={{ customApi: true }}+ onClose={vi.fn()}+ onSaved={vi.fn()}+ />,+ ),+ );+ // Admin: reachable, but filed under Advanced rather than sitting among the vendors.+ await waitFor(() =>+ expect(+ screen.getByText("portal.connections.types.api.label"),+ ).toBeInTheDocument(),+ );+ expect(+ screen.getByText("portal.connections.categories.advanced.label"),+ ).toBeInTheDocument();+ });++ it("pins the custom API form even without capabilities, rather than blanking", async () => {+ // The pipeline's Custom API step opens this modal pinned to "api" and passes no capabilities+ // (it has none to hand). Filtering the pin through capabilities dropped the gated custom entry+ // and left the picker with nothing - a blank screen. A pinned slot is already vetted upstream,+ // so its form must always render.+ render(+ wrap(+ <ConnectionModal+ open+ fixedTypeId="api"+ onClose={vi.fn()}+ onSaved={vi.fn()}+ />,+ ),+ );++ // Straight to the api form (its base URL field), not an empty grid.+ await waitFor(() =>+ expect(+ screen.getByLabelText(+ /portal\.connections\.types\.api\.fields\.baseUrl/,+ {+ exact: false,+ },+ ),+ ).toBeInTheDocument(),+ );+ // The picker's search box is a tell for the empty-grid state; it must not be here.+ expect(+ screen.queryByPlaceholderText(+ "portal.connections.picker2.searchPlaceholder",+ ),+ ).toBeNull();+ });++ it("searches across vendor aliases rather than just the label", async () => {+ render(wrap(<ConnectionModal open onClose={vi.fn()} onSaved={vi.fn()} />));++ // "siem" is nobody's product name - it is the job. Someone who wants audit logging should+ // find Splunk without having to guess we filed it under "audit".+ await userEvent.type(+ screen.getByPlaceholderText(+ "portal.connections.picker2.searchPlaceholder",+ ),+ "siem",+ );++ await waitFor(() =>+ expect(+ screen.getByText("portal.connections.types.splunk.label"),+ ).toBeInTheDocument(),+ );+ // A flat result list, not every category heading it happens to fall under.+ expect(screen.queryByText("portal.connections.types.s3.label")).toBeNull();+ });++ it("picking a vendor opens its form, and the back link returns to the grid", async () => {+ render(wrap(<ConnectionModal open onClose={vi.fn()} onSaved={vi.fn()} />));++ await userEvent.click(+ screen.getByText("portal.connections.types.purview.label"),+ );+ // The chosen vendor's own fields, not a generic form.+ await waitFor(() =>+ expect(+ screen.getByLabelText(+ "portal.connections.types.purview.fields.tenantId",+ {+ exact: false,+ },+ ),+ ).toBeInTheDocument(),+ );++ await userEvent.click(screen.getByText("portal.connections.picker2.back"));+ await waitFor(() =>+ expect(+ screen.getByText("portal.connections.types.s3.label"),+ ).toBeInTheDocument(),+ );+ });++ it("says so when a search matches nothing", async () => {+ render(wrap(<ConnectionModal open onClose={vi.fn()} onSaved={vi.fn()} />));++ await userEvent.type(+ screen.getByPlaceholderText(+ "portal.connections.picker2.searchPlaceholder",+ ),+ "Fabrikam",+ );++ await waitFor(() =>+ expect(+ screen.getByText("portal.connections.picker2.noResultsTitle"),+ ).toBeInTheDocument(),+ );+ // No cards left over from the unfiltered grid.+ expect(screen.queryByText("portal.connections.types.s3.label")).toBeNull();+ });+});diff --git a/frontend/editor/src/portal/components/sources/ConnectionModal.tsx b/frontend/editor/src/portal/components/sources/ConnectionModal.tsxnew file mode 100644index 0000000000..b2845da0ba--- /dev/null+++ b/frontend/editor/src/portal/components/sources/ConnectionModal.tsx@@ -0,0 +1,221 @@+import ArrowBackRoundedIcon from "@mui/icons-material/ArrowBackRounded";+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Banner, Button, Modal } from "@app/ui";+import { errorMessage } from "@portal/api/http";+import {+ createIntegration,+ updateIntegration,+ type IntegrationCapabilities,+ type IntegrationConfig,+} from "@portal/api/integrations";+import { ConnectionTypePicker } from "@portal/components/sources/ConnectionTypePicker";+import { ConnectionForm } from "@portal/components/sources/ConnectionForm";+import {+ CREATABLE_CONNECTION_TYPES,+ buildConnectionConfig,+ connectionFormValid,+ connectionFormValues,+ connectionTypeOf,+ creatableConnectionTypes,+ emptyConnectionValues,+ type CreatableConnectionType,+} from "@portal/components/sources/connectionTypes";++/**+ * The one place connections are created and edited, for every type.+ *+ * Launched from the Connections tab, the source builder's picker, and the pipeline builder output,+ * so setup is always a modal rather than inline splat. What can be created comes from the server's+ * capabilities (`customApi`), not from anything decided here — hiding the option is presentation;+ * the backend refuses the call regardless.+ *+ * Saving validates backend-side (schema, host, credentials). On edit the type is fixed: an+ * integration's type is what its stored config means, so changing it would reinterpret the config+ * rather than convert it.+ */+interface ConnectionModalProps {+ open: boolean;+ /** When set, edit this connection; otherwise create a new one. */+ connection?: IntegrationConfig | null;+ /** Pin the type (e.g. an S3 picker creating inline) instead of offering a choice. */+ fixedTypeId?: string;+ capabilities?: IntegrationCapabilities;+ onClose: () => void;+ /** The saved connection, so callers can select or refresh it. */+ onSaved: (connection: IntegrationConfig) => void;+}++export function ConnectionModal({+ open,+ connection,+ fixedTypeId,+ capabilities,+ onClose,+ onSaved,+}: ConnectionModalProps) {+ const { t } = useTranslation();+ const [type, setType] = useState<CreatableConnectionType | null>(null);+ const [values, setValues] = useState<Record<string, string>>({ name: "" });+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ // "pick" chooses what to connect to; "form" fills it in.+ const [mode, setMode] = useState<"pick" | "form">("pick");+ const isEdit = Boolean(connection);++ // A pinned slot is an explicit choice, already vetted where it was offered (the S3 field, or the+ // custom-API operation, which is itself capability-gated). Resolve it from the full catalogue so+ // the modal always has its form - the open picker still respects capabilities. Filtering the pin+ // through capabilities is what blanked the modal: the custom-API type is gated, so it dropped out+ // and left the picker with nothing to show.+ const available = fixedTypeId+ ? CREATABLE_CONNECTION_TYPES.filter((entry) => entry.id === fixedTypeId)+ : creatableConnectionTypes(capabilities);+ // The picker is only worth showing when there is actually a choice - not for a pinned slot+ // (an S3 field on a source) or an edit, where the type is already decided.+ const canPick = !isEdit && !fixedTypeId;++ // Seed each time the modal opens (or its target changes).+ useEffect(() => {+ if (!open) return;+ setError(null);+ if (connection) {+ setMode("form");+ const existing = connectionTypeOf(+ connection.integrationType,+ connection.config,+ );+ setType(existing ?? null);+ setValues(+ existing+ ? connectionFormValues(existing, {+ name: connection.name,+ config: connection.config ?? {},+ })+ : { name: connection.name },+ );+ return;+ }+ // A pinned slot (an S3 field on a source) has nothing to choose, so skip straight to the form.+ // Stay on the form even if the pin resolves to nothing: the form branch shows a clear+ // "unsupported type" banner, whereas the picker would render an empty grid - a blank screen.+ const pinned = fixedTypeId ? (available[0] ?? null) : null;+ setMode(fixedTypeId ? "form" : "pick");+ setType(pinned);+ setValues(pinned ? emptyConnectionValues(pinned) : { name: "" });+ // `available` is derived from props each render; depending on it would reseed on every+ // keystroke and wipe the form.+ }, [open, connection, fixedTypeId, capabilities]);++ function pickType(next: CreatableConnectionType) {+ setType(next);+ setValues((current) => ({+ ...emptyConnectionValues(next),+ name: current.name ?? "",+ }));+ setMode("form");+ }++ async function save() {+ if (saving || !type || !connectionFormValid(type, values)) return;+ setSaving(true);+ setError(null);+ try {+ const config = buildConnectionConfig(type, values);+ const saved = connection+ ? await updateIntegration(connection.id, {+ name: values.name.trim(),+ config,+ })+ : // TEAM scope suits the team-based portal (the backend defaults the team to the+ // caller's own). A teamless single-operator self-hosted deployment would need a+ // USER/SERVER scope choice here - follow-up if the portal ships there.+ await createIntegration({+ integrationType: type.integrationType,+ name: values.name.trim(),+ scope: "TEAM",+ config,+ });+ onSaved(saved);+ onClose();+ } catch (e) {+ setError(errorMessage(e));+ } finally {+ setSaving(false);+ }+ }++ return (+ <Modal+ open={open}+ onClose={onClose}+ // The grid wants room to breathe; a form is easier to read narrow.+ width={mode === "pick" ? "lg" : "md"}+ title={+ isEdit+ ? t("portal.connections.editTitle")+ : mode === "pick"+ ? t("portal.connections.picker2.heading")+ : // Once something is chosen the title says what, so the form is self-describing.+ t("portal.connections.createTitleFor", {+ name: type ? t(type.labelKey) : "",+ })+ }+ footer={+ // The picker commits on click, so the modal's footer belongs to the form step alone.+ mode === "form" ? (+ <div className="portal-sources__connection-create-actions">+ <Button+ variant="tertiary"+ size="sm"+ disabled={saving}+ onClick={onClose}+ >+ {t("portal.connections.picker.cancel")}+ </Button>+ <Button+ size="sm"+ loading={saving}+ disabled={!type || !connectionFormValid(type, values)}+ onClick={() => void save()}+ >+ {t("portal.connections.picker.save")}+ </Button>+ </div>+ ) : undefined+ }+ >+ {mode === "pick" ? (+ <ConnectionTypePicker types={available} onPick={pickType} />+ ) : (+ <>+ {canPick && (+ // The choice is made in the picker now; this just gets them back to it, so the+ // selection stays visible without a dropdown that duplicates the grid.+ <Button+ variant="quiet"+ size="sm"+ className="portal-sources__connection-back"+ leftSection={<ArrowBackRoundedIcon fontSize="inherit" />}+ onClick={() => setMode("pick")}+ >+ {t("portal.connections.picker2.back")}+ </Button>+ )}++ {type ? (+ <ConnectionForm type={type} values={values} onChange={setValues} />+ ) : (+ // An unknown stored type (e.g. MCP, which has no form) must not render a blank editor+ // that would save an empty config over whatever is there.+ <Banner+ tone="warning"+ description={t("portal.connections.unsupportedType")}+ />+ )}+ {error && <Banner tone="danger" description={error} />}+ </>+ )}+ </Modal>+ );+}diff --git a/frontend/editor/src/portal/components/sources/ConnectionPicker.test.tsx b/frontend/editor/src/portal/components/sources/ConnectionPicker.test.tsxnew file mode 100644index 0000000000..f68c89156a--- /dev/null+++ b/frontend/editor/src/portal/components/sources/ConnectionPicker.test.tsx@@ -0,0 +1,111 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ fireEvent,+ render as baseRender,+ screen,+ waitFor,+} from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { ConnectionPicker } from "@portal/components/sources/ConnectionPicker";++const render = (ui: Parameters<typeof baseRender>[0]) =>+ baseRender(ui, { wrapper: MantineProvider });++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ i18n: { changeLanguage: vi.fn() },+ }),+}));++const fetchIntegrations = vi.fn();+vi.mock("@portal/api/integrations", () => ({+ fetchIntegrations: () => fetchIntegrations(),+ fetchIntegrationCapabilities: () => Promise.resolve({ customApi: false }),+ createIntegration: vi.fn(),+ updateIntegration: vi.fn(),+}));++vi.mock("@portal/api/http", () => ({+ errorMessage: (e: unknown) => String(e),+}));++// Three API connections sharing integrationType "API": a Slack webhook, a Jira account, and a+// hand-authored custom API. Only presetId tells them apart.+const CONNECTIONS = [+ {+ id: 1,+ name: "Team Slack",+ integrationType: "API",+ config: { presetId: "slack" },+ },+ {+ id: 2,+ name: "Ops Jira",+ integrationType: "API",+ config: { presetId: "jira" },+ },+ {+ id: 3,+ name: "House API",+ integrationType: "API",+ config: { presetId: "api" },+ },+];++describe("ConnectionPicker vendor filtering", () => {+ beforeEach(() => {+ fetchIntegrations.mockReset();+ fetchIntegrations.mockResolvedValue(CONNECTIONS);+ });++ it("offers only the named vendor's accounts, plus custom API, never another webhook", async () => {+ render(+ <ConnectionPicker+ value=""+ onChange={vi.fn()}+ integrationType="API"+ createTypeId="jira"+ presetId="jira"+ />,+ );++ // Open the Mantine Select so its options render.+ fireEvent.click(+ await screen.findByPlaceholderText(+ "portal.connections.picker.placeholder",+ ),+ );++ // Jira (the vendor asked for) and the free-form custom API (which can point anywhere).+ await waitFor(() =>+ expect(screen.getByText("Ops Jira")).toBeInTheDocument(),+ );+ expect(screen.getByText("House API")).toBeInTheDocument();+ // A Jira step must not offer a Slack webhook as its account.+ expect(screen.queryByText("Team Slack")).toBeNull();+ });++ it("without a presetId falls back to every connection of the backend type", async () => {+ render(+ <ConnectionPicker+ value=""+ onChange={vi.fn()}+ integrationType="API"+ createTypeId="api"+ />,+ );++ fireEvent.click(+ await screen.findByPlaceholderText(+ "portal.connections.picker.placeholder",+ ),+ );++ await waitFor(() =>+ expect(screen.getByText("Team Slack")).toBeInTheDocument(),+ );+ expect(screen.getByText("Ops Jira")).toBeInTheDocument();+ expect(screen.getByText("House API")).toBeInTheDocument();+ });+});diff --git a/frontend/editor/src/portal/components/sources/ConnectionPicker.tsx b/frontend/editor/src/portal/components/sources/ConnectionPicker.tsxnew file mode 100644index 0000000000..be54916726--- /dev/null+++ b/frontend/editor/src/portal/components/sources/ConnectionPicker.tsx@@ -0,0 +1,103 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Banner, Button, Select } from "@app/ui";+import { errorMessage } from "@portal/api/http";+import {+ fetchIntegrations,+ type IntegrationConfig,+ type IntegrationType,+} from "@portal/api/integrations";+import { ConnectionModal } from "@portal/components/sources/ConnectionModal";+import { connectionTypeOf } from "@portal/components/sources/connectionTypes";++/**+ * Selects a stored connection of one type by id — an S3 bucket for a source, a Purview tenant for a+ * labelling step. Creating a new one opens the shared modal (saved immediately and validated+ * backend-side), so the parent only ever sees a real connection id.+ *+ * The type is fixed by the slot rather than chosen here: a field that wants a Purview tenant is not+ * satisfied by an S3 bucket, so offering the choice would only invite an error the backend then has+ * to reject.+ */+interface ConnectionPickerProps {+ value: string;+ onChange: (connectionId: string) => void;+ /** The backend type this slot accepts. */+ integrationType: IntegrationType;+ /** The catalogue entry used when creating inline; defaults to the type's own. */+ createTypeId: string;+ /**+ * The specific vendor this slot wants (e.g. "jira"). Seventeen presets share the "API" backend+ * type, so filtering on `integrationType` alone offers a Jira step your Slack webhook. When set,+ * only connections that resolve to this preset are shown - plus any free-form custom API+ * connection, which can point anywhere and so fits any API operation.+ */+ presetId?: string;+}++export function ConnectionPicker({+ value,+ onChange,+ integrationType,+ createTypeId,+ presetId,+}: ConnectionPickerProps) {+ const { t } = useTranslation();+ const [connections, setConnections] = useState<IntegrationConfig[] | null>(+ null,+ );+ const [modalOpen, setModalOpen] = useState(false);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ let mounted = true;+ fetchIntegrations()+ .then((list) => {+ if (!mounted) return;+ // A connection fits this slot when the backend type matches and, if a vendor is named,+ // when it is that vendor - or a free-form custom API connection, which points wherever+ // its base URL says and so serves any API operation.+ setConnections(+ list.filter((c) => {+ if (c.integrationType !== integrationType) return false;+ if (!presetId) return true;+ const resolved = connectionTypeOf(c.integrationType, c.config);+ return resolved?.id === presetId || resolved?.kind === "custom";+ }),+ );+ })+ .catch((e) => {+ if (mounted) setError(errorMessage(e));+ });+ return () => {+ mounted = false;+ };+ }, [integrationType, presetId]);++ return (+ <div className="portal-sources__connection-picker">+ <Select+ value={value || null}+ placeholder={t("portal.connections.picker.placeholder")}+ options={(connections ?? []).map((connection) => ({+ value: String(connection.id),+ label: connection.name,+ }))}+ onChange={(selected) => onChange(selected ?? "")}+ />+ <Button variant="tertiary" size="sm" onClick={() => setModalOpen(true)}>+ {t("portal.connections.picker.createNew")}+ </Button>+ {error && <Banner tone="danger" description={error} />}+ <ConnectionModal+ open={modalOpen}+ fixedTypeId={createTypeId}+ onClose={() => setModalOpen(false)}+ onSaved={(created) => {+ setConnections((list) => [...(list ?? []), created]);+ onChange(String(created.id));+ }}+ />+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/sources/ConnectionTypePicker.tsx b/frontend/editor/src/portal/components/sources/ConnectionTypePicker.tsxnew file mode 100644index 0000000000..7d1ea67fa9--- /dev/null+++ b/frontend/editor/src/portal/components/sources/ConnectionTypePicker.tsx@@ -0,0 +1,142 @@+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import SearchRoundedIcon from "@mui/icons-material/SearchRounded";+import {+ CONNECTION_CATEGORIES,+ searchConnectionTypes,+ type ConnectionCategory,+ type CreatableConnectionType,+} from "@portal/components/sources/connectionTypes";++/**+ * Choose what to connect to.+ *+ * A dropdown was right for three vendors and is wrong for thirty: you cannot scan it, and it hides+ * the answer to "do you support X?" behind a click. This is a searchable, categorised grid instead,+ * grouped by the job someone is trying to do - because a person who has never heard of ConsignO+ * still knows they want "signing".+ *+ * Search matches the vendor's own aliases and the job words too ("siem", "ocr", "notify"), because+ * people search for the problem as often as the product.+ */+interface ConnectionTypePickerProps {+ types: CreatableConnectionType[];+ onPick: (type: CreatableConnectionType) => void;+}++export function ConnectionTypePicker({+ types,+ onPick,+}: ConnectionTypePickerProps) {+ const { t } = useTranslation();+ const [query, setQuery] = useState("");++ const matches = useMemo(+ () => searchConnectionTypes(types, query, (key) => t(key)),+ [types, query, t],+ );++ const grouped = useMemo(() => {+ const map = new Map<ConnectionCategory, CreatableConnectionType[]>();+ for (const type of matches) {+ const list = map.get(type.category) ?? [];+ list.push(type);+ map.set(type.category, list);+ }+ return map;+ }, [matches]);++ const searching = query.trim() !== "";+ // While searching, one flat relevance-ordered list reads better than seven tiny sections.+ const sections: ConnectionCategory[] = searching+ ? []+ : CONNECTION_CATEGORIES.filter((c) => (grouped.get(c)?.length ?? 0) > 0);++ return (+ <div className="portal-conn-picker">+ <div className="portal-conn-picker__search">+ <SearchRoundedIcon className="portal-conn-picker__search-icon" />+ <input+ type="search"+ autoFocus+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t("portal.connections.picker2.searchPlaceholder")}+ aria-label={t("portal.connections.picker2.searchPlaceholder")}+ />+ </div>++ {matches.length === 0 ? (+ <div className="portal-conn-picker__empty">+ <p className="portal-conn-picker__empty-title">+ {t("portal.connections.picker2.noResultsTitle", { query })}+ </p>+ <p className="portal-conn-picker__empty-body">+ {t("portal.connections.picker2.noResultsBody")}+ </p>+ </div>+ ) : searching ? (+ <Grid types={matches} onPick={onPick} />+ ) : (+ sections.map((category) => (+ <section key={category} className="portal-conn-picker__section">+ <h4 className="portal-conn-picker__section-title">+ {t(`portal.connections.categories.${category}.label`)}+ </h4>+ <p className="portal-conn-picker__section-desc">+ {t(`portal.connections.categories.${category}.description`)}+ </p>+ <Grid types={grouped.get(category) ?? []} onPick={onPick} />+ </section>+ ))+ )}+ </div>+ );+}++function Grid({+ types,+ onPick,+}: {+ types: CreatableConnectionType[];+ onPick: (type: CreatableConnectionType) => void;+}) {+ const { t } = useTranslation();+ return (+ <div className="portal-conn-picker__grid">+ {types.map((type) => {+ const label = t(type.labelKey);+ return (+ <button+ key={type.id}+ type="button"+ className={+ "portal-conn-picker__card" ++ (type.kind === "custom"+ ? " portal-conn-picker__card--advanced"+ : "")+ }+ onClick={() => onPick(type)}+ >+ {/* A monogram rather than a logo: no third-party assets to ship, licence or keep+ current, and it still gives each card something to recognise at a glance. Tinted+ by category so the colour still carries meaning while searching, when the section+ headings that would otherwise group them are gone. */}+ <span+ className={`portal-conn-picker__mark portal-conn-picker__mark--${type.category}`}+ aria-hidden+ >+ {label.slice(0, 1)}+ </span>+ <span className="portal-conn-picker__card-text">+ <span className="portal-conn-picker__card-name">{label}</span>+ <span className="portal-conn-picker__card-desc">+ {t(type.descriptionKey)}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/sources/ConnectionsTab.test.tsx b/frontend/editor/src/portal/components/sources/ConnectionsTab.test.tsxindex 938dfa832b..157a674e5c 100644--- a/frontend/editor/src/portal/components/sources/ConnectionsTab.test.tsx+++ b/frontend/editor/src/portal/components/sources/ConnectionsTab.test.tsx@@ -23,6 +23,9 @@ vi.mock("react-i18next", () => ({const fetchS3Connections = vi.fn();const deleteIntegration = vi.fn();vi.mock("@portal/api/integrations", () => ({+ fetchIntegrations: () => fetchS3Connections(),+ // Custom-API authoring is a server decision; these tests assert the default view.+ fetchIntegrationCapabilities: () => Promise.resolve({ customApi: false }),fetchS3Connections: () => fetchS3Connections(),deleteIntegration: (id: number) => deleteIntegration(id),createIntegration: vi.fn(),diff --git a/frontend/editor/src/portal/components/sources/ConnectionsTab.tsx b/frontend/editor/src/portal/components/sources/ConnectionsTab.tsxindex 136f557032..c249afcbae 100644--- a/frontend/editor/src/portal/components/sources/ConnectionsTab.tsx+++ b/frontend/editor/src/portal/components/sources/ConnectionsTab.tsx@@ -12,17 +12,20 @@ import {import { errorMessage } from "@portal/api/http";import {deleteIntegration,- fetchS3Connections,+ fetchIntegrationCapabilities,+ fetchIntegrations,+ type IntegrationCapabilities,type IntegrationConfig,} from "@portal/api/integrations";import { SourcesIcon } from "@portal/components/icons";-import { S3ConnectionModal } from "@portal/components/sources/S3ConnectionModal";+import { ConnectionModal } from "@portal/components/sources/ConnectionModal";+import { connectionTypeOf } from "@portal/components/sources/connectionTypes";/**- * The Connections tab of the Sources page: stored S3 connections that sources- * and pipeline outputs reference by id. Create/edit go through the shared- * {@link S3ConnectionModal}; deleting one the backend still references returns a- * 409, surfaced inline.+ * The Connections tab of the Sources page: the stored connections that sources, pipeline outputs+ * and integration steps reference by id — S3, Purview, ConsignO, and admin-authored custom APIs.+ * Create/edit go through the shared {@link ConnectionModal}; deleting one the backend still+ * references returns a 409, surfaced inline.*/export function ConnectionsTab() {const { t } = useTranslation();@@ -33,10 +36,13 @@ export function ConnectionsTab() {const [editing, setEditing] = useState<IntegrationConfig | null>(null);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ const [capabilities, setCapabilities] = useState<+ IntegrationCapabilities | undefined+ >(undefined);const refresh = useCallback(async () => {try {- setConnections(await fetchS3Connections());+ setConnections(await fetchIntegrations());} catch (e) {setError(errorMessage(e));}@@ -46,6 +52,12 @@ export function ConnectionsTab() {void refresh();}, [refresh]);+ // What this caller may author. Left undefined on failure, which withholds the custom-API+ // option rather than offering something the backend would refuse.+ useEffect(() => {+ fetchIntegrationCapabilities().then(setCapabilities, () => undefined);+ }, []);+function openCreate() {setEditing(null);setModalOpen(true);@@ -78,19 +90,22 @@ export function ConnectionsTab() {render: (c) => <strong>{c.name}</strong>,},{- key: "bucket",- header: t("portal.connections.table.bucket"),+ key: "type",+ header: t("portal.connections.table.type"),+ render: (c) => {+ const type = connectionTypeOf(c.integrationType, c.config);+ return type ? t(type.labelKey) : c.integrationType;+ },+ },+ {+ key: "detail",+ header: t("portal.connections.table.detail"),render: (c) => (<span className="portal-sources__connections-bucket">- {String(c.config?.bucket ?? "")}+ {connectionDetail(c)}</span>),},- {- key: "region",- header: t("portal.connections.table.region"),- render: (c) => String(c.config?.region ?? ""),- },{key: "actions",header: "",@@ -128,17 +143,21 @@ export function ConnectionsTab() {return (<section className="portal-sources__connections">- <div className="portal-sources__connections-head">- <p className="portal-sources__connections-sub">- {t("portal.connections.subtitle")}- </p>- <Button- onClick={openCreate}- leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}- >- {t("portal.connections.actions.new")}- </Button>- </div>+ {/* The empty state carries its own heading and call to action, so the header row would+ only double the button and the copy - show it once there are connections to head. */}+ {!isEmpty && (+ <div className="portal-sources__connections-head">+ <p className="portal-sources__connections-sub">+ {t("portal.connections.subtitle")}+ </p>+ <Button+ onClick={openCreate}+ leftSection={<AddRoundedIcon style={{ fontSize: "1.125rem" }} />}+ >+ {t("portal.connections.actions.new")}+ </Button>+ </div>+ )}{error && <Banner tone="danger" description={error} />}@@ -175,12 +194,30 @@ export function ConnectionsTab() {/>)}- <S3ConnectionModal+ <ConnectionModalopen={modalOpen}connection={editing}+ capabilities={capabilities}onClose={() => setModalOpen(false)}onSaved={() => void refresh()}/></section>);}++/**+ * The one line that identifies a connection at a glance. Per type, because "bucket" means nothing+ * to a Purview tenant and a base URL means nothing to S3. Never a secret: config arrives masked,+ * but only non-secret keys are shown regardless.+ */+function connectionDetail(connection: IntegrationConfig): string {+ const config = connection.config ?? {};+ switch (connection.integrationType) {+ case "S3":+ return String(config.bucket ?? "");+ case "PURVIEW":+ return String(config.tenantId ?? "");+ default:+ return String(config.baseUrl ?? "");+ }+}diff --git a/frontend/editor/src/portal/components/sources/S3ConnectionForm.tsx b/frontend/editor/src/portal/components/sources/S3ConnectionForm.tsxdeleted file mode 100644index 0158025d83..0000000000--- a/frontend/editor/src/portal/components/sources/S3ConnectionForm.tsx+++ /dev/null@@ -1,116 +0,0 @@-import { useTranslation } from "react-i18next";-import { FormField, Input } from "@app/ui";--/**- * The connection-level S3 fields (per-use settings like prefix/mode live on the- * source or output referencing the connection). Secrets are write-only: when- * editing, the backend returns them masked and keeps the stored value if the- * mask is sent back unchanged.- */-export interface S3ConnectionFormValues {- name: string;- bucket: string;- region: string;- endpoint: string;- accessKeyId: string;- secretAccessKey: string;-}--export const EMPTY_S3_CONNECTION: S3ConnectionFormValues = {- name: "",- bucket: "",- region: "us-east-1",- endpoint: "",- accessKeyId: "",- secretAccessKey: "",-};--export function s3ConnectionRequestConfig(- values: S3ConnectionFormValues,-): Record<string, unknown> {- return {- bucket: values.bucket.trim(),- region: values.region.trim(),- endpoint: values.endpoint.trim(),- accessKeyId: values.accessKeyId.trim(),- secretAccessKey: values.secretAccessKey,- };-}--export function s3ConnectionFormValid(values: S3ConnectionFormValues): boolean {- return (- values.name.trim() !== "" &&- values.bucket.trim() !== "" &&- values.accessKeyId.trim() !== "" &&- values.secretAccessKey.trim() !== ""- );-}--interface S3ConnectionFormProps {- values: S3ConnectionFormValues;- onChange: (values: S3ConnectionFormValues) => void;-}--export function S3ConnectionForm({ values, onChange }: S3ConnectionFormProps) {- const { t } = useTranslation();- const set = (key: keyof S3ConnectionFormValues, value: string) =>- onChange({ ...values, [key]: value });-- return (- <div className="portal-sources__connection-form">- <FormField label={t("portal.connections.s3.fields.name")} required>- <Input- value={values.name}- placeholder={t("portal.connections.s3.fields.namePlaceholder")}- onChange={(e) => set("name", e.target.value)}- />- </FormField>- <FormField- label={t("portal.sources.types.s3.fields.bucket.label")}- required- >- <Input- value={values.bucket}- placeholder="my-company-inbox"- onChange={(e) => set("bucket", e.target.value)}- />- </FormField>- <FormField label={t("portal.sources.types.s3.fields.region.label")}>- <Input- value={values.region}- placeholder="us-east-1"- onChange={(e) => set("region", e.target.value)}- />- </FormField>- <FormField- label={t("portal.sources.types.s3.fields.accessKeyId.label")}- required- >- <Input- value={values.accessKeyId}- onChange={(e) => set("accessKeyId", e.target.value)}- />- </FormField>- <FormField- label={t("portal.sources.types.s3.fields.secretAccessKey.label")}- required- >- <Input- type="password"- value={values.secretAccessKey}- onChange={(e) => set("secretAccessKey", e.target.value)}- />- </FormField>- <FormField- label={t("portal.sources.types.s3.fields.endpoint.label")}- helperText={t("portal.sources.types.s3.fields.endpoint.helperText")}- >- <Input- value={values.endpoint}- placeholder="https://s3.example.com"- onChange={(e) => set("endpoint", e.target.value)}- />- </FormField>- </div>- );-}diff --git a/frontend/editor/src/portal/components/sources/S3ConnectionModal.test.tsx b/frontend/editor/src/portal/components/sources/S3ConnectionModal.test.tsxdeleted file mode 100644index e052243fe9..0000000000--- a/frontend/editor/src/portal/components/sources/S3ConnectionModal.test.tsx+++ /dev/null@@ -1,131 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import {- fireEvent,- render as baseRender,- screen,- waitFor,-} from "@testing-library/react";-import { MantineProvider } from "@mantine/core";-import { S3ConnectionModal } from "@portal/components/sources/S3ConnectionModal";-import type { IntegrationConfig } from "@portal/api/integrations";--const render = (ui: Parameters<typeof baseRender>[0]) =>- baseRender(ui, { wrapper: MantineProvider });--vi.mock("react-i18next", () => ({- useTranslation: () => ({- t: (key: string) => key,- i18n: { changeLanguage: vi.fn() },- }),-}));--const createIntegration = vi.fn();-const updateIntegration = vi.fn();-vi.mock("@portal/api/integrations", () => ({- createIntegration: (...a: unknown[]) => createIntegration(...a),- updateIntegration: (...a: unknown[]) => updateIntegration(...a),-}));--function setField(labelPattern: RegExp, value: string) {- fireEvent.change(screen.getByLabelText(labelPattern), { target: { value } });-}--describe("S3ConnectionModal", () => {- beforeEach(() => {- createIntegration.mockReset();- updateIntegration.mockReset();- });-- it("creates a team-scoped connection from the entered fields", async () => {- createIntegration.mockResolvedValue({ id: 5, name: "Claims bucket" });- const onSaved = vi.fn();- const onClose = vi.fn();- render(<S3ConnectionModal open onClose={onClose} onSaved={onSaved} />);-- setField(/portal\.connections\.s3\.fields\.name/, "Claims bucket");- setField(/portal\.sources\.types\.s3\.fields\.bucket\.label/, "inbox");- setField(/portal\.sources\.types\.s3\.fields\.accessKeyId\.label/, "AKIA");- setField(- /portal\.sources\.types\.s3\.fields\.secretAccessKey\.label/,- "shh",- );- fireEvent.click(screen.getByText("portal.connections.picker.save"));-- await waitFor(() => expect(createIntegration).toHaveBeenCalledTimes(1));- expect(createIntegration).toHaveBeenCalledWith({- integrationType: "S3",- name: "Claims bucket",- scope: "TEAM",- config: {- bucket: "inbox",- region: "us-east-1",- endpoint: "",- accessKeyId: "AKIA",- secretAccessKey: "shh",- },- });- await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));- expect(onClose).toHaveBeenCalled();- });-- it("round-trips a masked secret unchanged on edit (keeps the stored value)", async () => {- updateIntegration.mockResolvedValue({ id: 5, name: "Claims bucket" });- // The API returns secrets masked; the modal must resend the sentinel verbatim- // so the backend keeps the stored secret rather than overwriting it.- const connection = {- id: 5,- integrationType: "S3",- name: "Claims bucket",- config: {- bucket: "inbox",- region: "us-east-1",- accessKeyId: "AKIA",- secretAccessKey: "********",- },- canManage: true,- } as unknown as IntegrationConfig;-- render(- <S3ConnectionModal- open- connection={connection}- onClose={vi.fn()}- onSaved={vi.fn()}- />,- );-- const secret = screen.getByLabelText(- /portal\.sources\.types\.s3\.fields\.secretAccessKey\.label/,- ) as HTMLInputElement;- expect(secret.value).toBe("********");- // Change only the name; leave the masked secret untouched.- setField(/portal\.connections\.s3\.fields\.name/, "Renamed bucket");- fireEvent.click(screen.getByText("portal.connections.picker.save"));-- await waitFor(() => expect(updateIntegration).toHaveBeenCalledTimes(1));- expect(updateIntegration).toHaveBeenCalledWith(- 5,- expect.objectContaining({- name: "Renamed bucket",- config: expect.objectContaining({ secretAccessKey: "********" }),- }),- );- });-- it("keeps save disabled until the required fields are present", () => {- render(<S3ConnectionModal open onClose={vi.fn()} onSaved={vi.fn()} />);- const save = () =>- screen.getByText("portal.connections.picker.save").closest("button");-- expect(save()).toBeDisabled();- setField(/portal\.connections\.s3\.fields\.name/, "Only a name");- expect(save()).toBeDisabled();- setField(/portal\.sources\.types\.s3\.fields\.bucket\.label/, "inbox");- setField(/portal\.sources\.types\.s3\.fields\.accessKeyId\.label/, "AKIA");- setField(- /portal\.sources\.types\.s3\.fields\.secretAccessKey\.label/,- "shh",- );- expect(save()).not.toBeDisabled();- });-});diff --git a/frontend/editor/src/portal/components/sources/S3ConnectionModal.tsx b/frontend/editor/src/portal/components/sources/S3ConnectionModal.tsxdeleted file mode 100644index c4e649df4e..0000000000--- a/frontend/editor/src/portal/components/sources/S3ConnectionModal.tsx+++ /dev/null@@ -1,127 +0,0 @@-import { useEffect, useState } from "react";-import { useTranslation } from "react-i18next";-import { Banner, Button, Modal } from "@app/ui";-import { errorMessage } from "@portal/api/http";-import {- createIntegration,- updateIntegration,- type IntegrationConfig,-} from "@portal/api/integrations";-import {- EMPTY_S3_CONNECTION,- S3ConnectionForm,- s3ConnectionFormValid,- s3ConnectionRequestConfig,- type S3ConnectionFormValues,-} from "@portal/components/sources/S3ConnectionForm";--/**- * The one place S3 connections are created and edited. Launched from the- * Connections tab, the source builder's connection picker, and the pipeline- * builder output - so connection setup is always a modal, never inline splat.- * Saving validates backend-side (schema, SSRF, credentials); on edit the secret- * arrives masked and round-trips unchanged to keep the stored value.- */-interface S3ConnectionModalProps {- open: boolean;- /** When set, edit this connection; otherwise create a new one. */- connection?: IntegrationConfig | null;- onClose: () => void;- /** The saved connection, so callers can select or refresh it. */- onSaved: (connection: IntegrationConfig) => void;-}--export function S3ConnectionModal({- open,- connection,- onClose,- onSaved,-}: S3ConnectionModalProps) {- const { t } = useTranslation();- const [form, setForm] = useState<S3ConnectionFormValues>(EMPTY_S3_CONNECTION);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string | null>(null);- const isEdit = Boolean(connection);-- // Seed the form each time the modal opens (or its target changes).- useEffect(() => {- if (!open) return;- if (connection) {- const config = connection.config ?? {};- setForm({- name: connection.name,- bucket: String(config.bucket ?? ""),- region: String(config.region ?? "us-east-1"),- endpoint: String(config.endpoint ?? ""),- accessKeyId: String(config.accessKeyId ?? ""),- secretAccessKey: String(config.secretAccessKey ?? ""),- });- } else {- setForm(EMPTY_S3_CONNECTION);- }- setError(null);- }, [open, connection]);-- async function save() {- if (saving || !s3ConnectionFormValid(form)) return;- setSaving(true);- setError(null);- try {- const saved = connection- ? await updateIntegration(connection.id, {- name: form.name.trim(),- config: s3ConnectionRequestConfig(form),- })- : // TEAM scope suits the team-based portal (the backend defaults the team to the- // caller's own). A teamless single-operator self-hosted deployment would need a- // USER/SERVER scope choice here - follow-up if the portal ships there.- await createIntegration({- integrationType: "S3",- name: form.name.trim(),- scope: "TEAM",- config: s3ConnectionRequestConfig(form),- });- onSaved(saved);- onClose();- } catch (e) {- setError(errorMessage(e));- } finally {- setSaving(false);- }- }-- return (- <Modal- open={open}- onClose={onClose}- title={t(- isEdit- ? "portal.connections.editTitle"- : "portal.connections.createTitle",- )}- footer={- <div className="portal-sources__connection-create-actions">- <Button- variant="tertiary"- size="sm"- disabled={saving}- onClick={onClose}- >- {t("portal.connections.picker.cancel")}- </Button>- <Button- size="sm"- loading={saving}- disabled={!s3ConnectionFormValid(form)}- onClick={() => void save()}- >- {t("portal.connections.picker.save")}- </Button>- </div>- }- >- <S3ConnectionForm values={form} onChange={setForm} />- {error && <Banner tone="danger" description={error} />}- </Modal>- );-}diff --git a/frontend/editor/src/portal/components/sources/S3ConnectionPicker.test.tsx b/frontend/editor/src/portal/components/sources/S3ConnectionPicker.test.tsxindex 8800fdfd15..1eb7c64db6 100644--- a/frontend/editor/src/portal/components/sources/S3ConnectionPicker.test.tsx+++ b/frontend/editor/src/portal/components/sources/S3ConnectionPicker.test.tsx@@ -21,6 +21,9 @@ vi.mock("react-i18next", () => ({const fetchS3Connections = vi.fn();const createIntegration = vi.fn();vi.mock("@portal/api/integrations", () => ({+ fetchIntegrations: () => fetchS3Connections(),+ // Custom-API authoring is a server decision; these tests assert the default view.+ fetchIntegrationCapabilities: () => Promise.resolve({ customApi: false }),fetchS3Connections: () => fetchS3Connections(),createIntegration: (...a: unknown[]) => createIntegration(...a),updateIntegration: vi.fn(),@@ -42,24 +45,24 @@ describe("S3ConnectionPicker", () => {await screen.findByText("portal.connections.picker.createNew"),);fireEvent.change(- screen.getByLabelText(/portal\.connections\.s3\.fields\.name/),+ screen.getByLabelText(/portal\.connections\.fields\.name/),{ target: { value: "New bucket" } },);fireEvent.change(screen.getByLabelText(- /portal\.sources\.types\.s3\.fields\.bucket\.label/,+ /portal\.connections\.types\.s3\.fields\.bucket\.label/,),{ target: { value: "inbox" } },);fireEvent.change(screen.getByLabelText(- /portal\.sources\.types\.s3\.fields\.accessKeyId\.label/,+ /portal\.connections\.types\.s3\.fields\.accessKeyId\.label/,),{ target: { value: "AKIA" } },);fireEvent.change(screen.getByLabelText(- /portal\.sources\.types\.s3\.fields\.secretAccessKey\.label/,+ /portal\.connections\.types\.s3\.fields\.secretAccessKey\.label/,),{ target: { value: "shh" } },);diff --git a/frontend/editor/src/portal/components/sources/S3ConnectionPicker.tsx b/frontend/editor/src/portal/components/sources/S3ConnectionPicker.tsxindex 58b559e23b..cc36aef29e 100644--- a/frontend/editor/src/portal/components/sources/S3ConnectionPicker.tsx+++ b/frontend/editor/src/portal/components/sources/S3ConnectionPicker.tsx@@ -1,17 +1,8 @@-import { useEffect, useState } from "react";-import { useTranslation } from "react-i18next";-import { Banner, Button, Select } from "@app/ui";-import { errorMessage } from "@portal/api/http";-import {- fetchS3Connections,- type IntegrationConfig,-} from "@portal/api/integrations";-import { S3ConnectionModal } from "@portal/components/sources/S3ConnectionModal";+import { ConnectionPicker } from "@portal/components/sources/ConnectionPicker";/**- * Selects a stored S3 connection by id. Creating a new one opens the shared- * connection modal (saved immediately and validated backend-side), so the- * parent only ever sees a real connection id.+ * The S3 slot on a source or pipeline output. A thin alias over {@link ConnectionPicker} so the+ * `control: "s3Connection"` field descriptor keeps its name and call sites stay untouched.*/interface S3ConnectionPickerProps {value: string;@@ -22,50 +13,12 @@ export function S3ConnectionPicker({value,onChange,}: S3ConnectionPickerProps) {- const { t } = useTranslation();- const [connections, setConnections] = useState<IntegrationConfig[] | null>(- null,- );- const [modalOpen, setModalOpen] = useState(false);- const [error, setError] = useState<string | null>(null);-- useEffect(() => {- let mounted = true;- fetchS3Connections()- .then((list) => {- if (mounted) setConnections(list);- })- .catch((e) => {- if (mounted) setError(errorMessage(e));- });- return () => {- mounted = false;- };- }, []);-return (- <div className="portal-sources__connection-picker">- <Select- value={value || null}- placeholder={t("portal.connections.picker.placeholder")}- options={(connections ?? []).map((connection) => ({- value: String(connection.id),- label: connection.name,- }))}- onChange={(selected) => onChange(selected ?? "")}- />- <Button variant="tertiary" size="sm" onClick={() => setModalOpen(true)}>- {t("portal.connections.picker.createNew")}- </Button>- {error && <Banner tone="danger" description={error} />}- <S3ConnectionModal- open={modalOpen}- onClose={() => setModalOpen(false)}- onSaved={(created) => {- setConnections((list) => [...(list ?? []), created]);- onChange(String(created.id));- }}- />- </div>+ <ConnectionPicker+ value={value}+ onChange={onChange}+ integrationType="S3"+ createTypeId="s3"+ />);}diff --git a/frontend/editor/src/portal/components/sources/connectionTypes.test.ts b/frontend/editor/src/portal/components/sources/connectionTypes.test.tsnew file mode 100644index 0000000000..8de257e88b--- /dev/null+++ b/frontend/editor/src/portal/components/sources/connectionTypes.test.ts@@ -0,0 +1,217 @@+import { describe, expect, it } from "vitest";++import {+ CREATABLE_CONNECTION_TYPES,+ PRESET_ID_KEY,+ buildConnectionConfig,+ connectionFormValues,+ connectionTypeOf,+ creatableConnectionTypes,+ isFieldVisible,+} from "@portal/components/sources/connectionTypes";++const byId = (id: string) => {+ const type = CREATABLE_CONNECTION_TYPES.find((entry) => entry.id === id);+ if (!type) throw new Error(`no connection type ${id}`);+ return type;+};++describe("connection type catalogue", () => {+ it("offers the vendor presets to everyone", () => {+ const offered = creatableConnectionTypes({ customApi: false }).map(+ (t) => t.id,+ );++ expect(offered).toContain("s3");+ expect(offered).toContain("purview");+ expect(offered).toContain("consigno");+ });++ it("offers custom API only when the server says the caller may author one", () => {+ expect(+ creatableConnectionTypes({ customApi: true }).map((t) => t.id),+ ).toContain("api");+ expect(+ creatableConnectionTypes({ customApi: false }).map((t) => t.id),+ ).not.toContain("api");+ // Capabilities not loaded yet: withhold rather than offer something that would be refused.+ expect(creatableConnectionTypes(undefined).map((t) => t.id)).not.toContain(+ "api",+ );+ });++ it("only the custom API entry is gated", () => {+ const gated = CREATABLE_CONNECTION_TYPES.filter(+ (t) => t.requiresCustomApi,+ ).map((t) => t.id);+ expect(gated).toEqual(["api"]);+ });+});++describe("buildConnectionConfig", () => {+ it("bakes the ConsignO preset in and nests the operator's credentials", () => {+ const config = buildConnectionConfig(byId("consigno"), {+ baseUrl: "https://acme.consignocloud.com/api/v1",+ "loginHeaders.X-Client-Id": "client-abc",+ "loginHeaders.X-Client-Secret": "client-xyz",+ "loginBody.username": "[email protected]",+ "loginBody.password": "s3cr3t",+ "loginBody.tenantId": "acme",+ });++ // The vendor's mechanics come from the preset, not from the operator.+ expect(config.authType).toBe("TOKEN_LOGIN");+ expect(config.loginPath).toBe("/auth/login");+ expect(config.tokenResponseHeader).toBe("X-Auth-Token");+ expect(config.tokenHeaderName).toBe("X-Auth-Token");++ // Dotted keys nest, so SecretMasker can recurse and mask password/secret by key name.+ expect(config.loginBody).toEqual({+ username: "[email protected]",+ password: "s3cr3t",+ tenantId: "acme",+ });+ expect(config.loginHeaders).toEqual({+ "X-Client-Id": "client-abc",+ "X-Client-Secret": "client-xyz",+ });+ });++ it("omits blanks rather than sending empty values", () => {+ const config = buildConnectionConfig(byId("purview"), {+ tenantId: "cb46c030-1825-4e81-a295-151c039dbf02",+ clientId: "",+ clientSecret: "",+ });++ // presetId records which preset built this, so a saved connection can be mapped back to the+ // right form; the blank optional fields are still omitted.+ expect(config).toEqual({+ presetId: "purview",+ tenantId: "cb46c030-1825-4e81-a295-151c039dbf02",+ });+ });++ it("splits the result-host allowlist into a list", () => {+ const config = buildConnectionConfig(byId("api"), {+ baseUrl: "https://api.vendor.example",+ authType: "NONE",+ resultUrlHosts: "cdn.vendor.example, files.vendor.example",+ });++ expect(config.resultUrlHosts).toEqual([+ "cdn.vendor.example",+ "files.vendor.example",+ ]);+ });++ it("carries no preset for the free-form type", () => {+ expect(byId("api").presetConfig).toBeUndefined();+ });+});++describe("isFieldVisible", () => {+ const api = byId("api");+ const field = (key: string) => {+ const found = api.fields.find((f) => f.key === key);+ if (!found) throw new Error(`no field ${key}`);+ return found;+ };++ it("shows auth fields only for the auth type that uses them", () => {+ expect(isFieldVisible(field("token"), { authType: "BEARER" })).toBe(true);+ expect(isFieldVisible(field("token"), { authType: "BASIC" })).toBe(false);+ expect(isFieldVisible(field("username"), { authType: "BASIC" })).toBe(true);+ expect(isFieldVisible(field("username"), { authType: "NONE" })).toBe(false);+ expect(+ isFieldVisible(field("loginPath"), { authType: "TOKEN_LOGIN" }),+ ).toBe(true);+ expect(isFieldVisible(field("loginPath"), { authType: "BEARER" })).toBe(+ false,+ );+ });++ it("shows unconditional fields always", () => {+ expect(isFieldVisible(field("baseUrl"), {})).toBe(true);+ });+});++describe("resolving a stored connection back to its preset", () => {+ it("keeps a Discord connection as Discord, not the first API preset", () => {+ // Seventeen presets share integrationType "API". Matching on that alone returned whichever+ // came first in the catalogue, so every API connection displayed as Cloudmersive - and the+ // edit form then rewrote a Discord webhook as a Cloudmersive endpoint on save.+ const discord = CREATABLE_CONNECTION_TYPES.find((t) => t.id === "discord")!;+ const config = buildConnectionConfig(discord, {+ name: "Team Discord",+ baseUrl: "https://discord.com/api/webhooks/1/abc",+ });++ expect(connectionTypeOf("API", config)?.id).toBe("discord");+ });++ it("round-trips an edit without destroying the stored config", () => {+ const discord = CREATABLE_CONNECTION_TYPES.find((t) => t.id === "discord")!;+ const url = "https://discord.com/api/webhooks/1/abc";+ const config = buildConnectionConfig(discord, { name: "d", baseUrl: url });++ const reopened = connectionTypeOf("API", config)!;+ const values = connectionFormValues(reopened, { name: "d", config });++ expect(buildConnectionConfig(reopened, values).baseUrl).toBe(url);+ });++ it("recovers a markerless Discord connection from its webhook host", () => {+ // A connection made before the marker carries no presetId, only its URL. Discord webhooks are+ // always discord.com, so the host names the vendor - it must not show as "Custom API".+ const legacy = { baseUrl: "https://discord.com/api/webhooks/1/abc" };+ expect(connectionTypeOf("API", legacy)?.id).toBe("discord");+ });++ it("recovers a Teams connection from a webhook subdomain", () => {+ // Teams posts from a per-tenant subdomain, so the match is on the domain suffix, not the host.+ const legacy = {+ baseUrl: "https://acme.webhook.office.com/webhookb2/abc/IncomingWebhook",+ };+ expect(connectionTypeOf("API", legacy)?.id).toBe("teams");+ });++ it("falls back to the free-form entry when the host names no vendor", () => {+ // Naming a specific vendor would be a guess, and the wrong guess loses data; the custom entry+ // shows the base URL and auth it really has.+ const legacy = { baseUrl: "https://api.acme.test/v2", authType: "BEARER" };+ const resolved = connectionTypeOf("API", legacy)!;++ expect(resolved.kind).toBe("custom");+ const values = connectionFormValues(resolved, {+ name: "l",+ config: legacy,+ });+ expect(buildConnectionConfig(resolved, values).baseUrl).toBe(+ legacy.baseUrl,+ );+ });++ it("does not guess between vendors that share a host", () => {+ // The two Cloudmersive presets both live at api.cloudmersive.com, so a markerless connection+ // there is genuinely ambiguous - resolve to the safe free-form form, not one of them at random.+ const legacy = {+ baseUrl: "https://api.cloudmersive.com",+ authType: "HEADER",+ };+ expect(connectionTypeOf("API", legacy)?.kind).toBe("custom");+ });++ it("still prefers the marker over the host when both are present", () => {+ // A webhook preset pointed at a custom relay: the marker is authoritative, not the URL.+ const config = {+ [PRESET_ID_KEY]: "slack",+ baseUrl: "https://discord.com/x",+ };+ expect(connectionTypeOf("API", config)?.id).toBe("slack");+ });++ it("still resolves exactly when only one preset owns the type", () => {+ expect(connectionTypeOf("PURVIEW", {})?.id).toBe("purview");+ });+});diff --git a/frontend/editor/src/portal/components/sources/connectionTypes.ts b/frontend/editor/src/portal/components/sources/connectionTypes.tsnew file mode 100644index 0000000000..ad5dfa3f17--- /dev/null+++ b/frontend/editor/src/portal/components/sources/connectionTypes.ts@@ -0,0 +1,844 @@+/**+ * The connection types an operator can set up, as data rather than components.+ *+ * Mirrors {@link CREATABLE_SOURCE_TYPES} deliberately: a vendor is added by describing its fields,+ * not by writing a form. That is what makes "support a load of things out of the box" true rather+ * than aspirational — a preset is an entry here plus, at most, a body template.+ *+ * Two kinds of entry:+ *+ * - **Presets** (S3, Purview, ConsignO) — a fixed shape. The operator supplies credentials and+ * whichever endpoint their tenant lives on; they cannot change what the integration *does*.+ * - **Custom API** — a free-form base URL, path, body and headers. This is authoring power: it can+ * aim the server at any host, so the backend restricts it to admins and lets an operator withdraw+ * it entirely (`policies.allowCustomApiIntegrations`). `requiresCustomApi` only decides whether to+ * *offer* it; `IntegrationConfigService` refuses the call regardless of what the client believed.+ */++import type { IntegrationType } from "@portal/api/integrations";++/** One configurable field. `control` mirrors the source builder's vocabulary. */+export interface ConnectionFieldDef {+ key: string;+ labelKey: string;+ control: "text" | "password" | "select" | "textarea" | "hostList";+ required?: boolean;+ placeholderKey?: string;+ helperTextKey?: string;+ options?: { value: string; labelKey: string }[];+ defaultValue?: string;+ /** Shown only when another field has one of these values, e.g. auth fields per authType. */+ visibleWhen?: { key: string; oneOf: string[] };+}++export interface CreatableConnectionType {+ /** Stable id; distinct from `integrationType` so several presets can share a backend type. */+ id: string;+ integrationType: IntegrationType;+ /**+ * "preset" — a supported vendor, the primary path: pick it and fill in credentials. "custom" —+ * the free-form escape hatch, deliberately set apart because it needs a developer's grasp of the+ * target API, and steering everyone here would both confuse non-technical operators and give away+ * the customisation an enterprise deal is negotiated around. Most people should never need it;+ * the answer to "my vendor isn't listed" is to request it, not to build it.+ */+ kind: "preset" | "custom";+ /** Groups the picker; also what someone scans by when they don't know the vendor's name. */+ category: ConnectionCategory;+ labelKey: string;+ descriptionKey: string;+ /**+ * Extra words search should match: former names (HelloSign), the job someone is trying to do+ * ("ocr", "notify"), and the stack it belongs to ("microsoft 365"). People search for the problem+ * as often as the product.+ */+ searchTerms?: string[];+ /** Config baked in rather than asked for — what makes a preset a preset. */+ presetConfig?: Record<string, unknown>;+ /**+ * Hostnames that identify this vendor from a stored connection whose `presetId` is absent (one+ * made before the marker, or through the API). A Discord webhook is always discord.com, so the+ * URL recovers the vendor with no marker. Matched against the host and any subdomain of it.+ */+ identifyHosts?: string[];+ /** True for entries that need admin + the server flag; see the module comment. */+ requiresCustomApi?: boolean;+ fields: ConnectionFieldDef[];+}++export type ConnectionCategory =+ | "storage"+ | "signing"+ | "security"+ | "audit"+ | "notify"+ | "advanced";++/** Display order of the category sections in the picker. */+// Substantial sections first; the two deliberate one-card sections (signing = the ConsignO+// flagship, advanced = the admin escape hatch) close the list rather than opening it.+export const CONNECTION_CATEGORIES: ConnectionCategory[] = [+ "storage",+ "security",+ "audit",+ "notify",+ "signing",+ "advanced",+];++const PREFIX = "portal.connections.types";+const COMMON = "portal.connections.commonFields";++const S3_FIELDS: ConnectionFieldDef[] = [+ {+ key: "bucket",+ labelKey: `${PREFIX}.s3.fields.bucket.label`,+ control: "text",+ required: true,+ },+ {+ key: "region",+ labelKey: `${PREFIX}.s3.fields.region.label`,+ control: "text",+ defaultValue: "us-east-1",+ },+ {+ key: "endpoint",+ labelKey: `${PREFIX}.s3.fields.endpoint.label`,+ control: "text",+ helperTextKey: `${PREFIX}.s3.fields.endpoint.helperText`,+ },+ {+ key: "accessKeyId",+ labelKey: `${PREFIX}.s3.fields.accessKeyId.label`,+ control: "text",+ required: true,+ },+ {+ key: "secretAccessKey",+ labelKey: `${PREFIX}.s3.fields.secretAccessKey.label`,+ control: "password",+ required: true,+ },+];++const PURVIEW_FIELDS: ConnectionFieldDef[] = [+ {+ key: "tenantId",+ labelKey: `${PREFIX}.purview.fields.tenantId.label`,+ control: "text",+ required: true,+ placeholderKey: `${PREFIX}.purview.fields.tenantId.placeholder`,+ helperTextKey: `${PREFIX}.purview.fields.tenantId.helperText`,+ },+ // Optional: labelling is local and needs only the tenant id. These buy the label picker.+ {+ key: "clientId",+ labelKey: `${PREFIX}.purview.fields.clientId.label`,+ control: "text",+ helperTextKey: `${PREFIX}.purview.fields.clientId.helperText`,+ },+ {+ key: "clientSecret",+ labelKey: `${PREFIX}.purview.fields.clientSecret.label`,+ control: "password",+ },+];++const CONSIGNO_FIELDS: ConnectionFieldDef[] = [+ {+ key: "baseUrl",+ labelKey: `${PREFIX}.consigno.fields.baseUrl.label`,+ control: "text",+ required: true,+ placeholderKey: `${PREFIX}.consigno.fields.baseUrl.placeholder`,+ helperTextKey: `${PREFIX}.consigno.fields.baseUrl.helperText`,+ },+ {+ key: "loginHeaders.X-Client-Id",+ labelKey: `${PREFIX}.consigno.fields.clientId.label`,+ control: "text",+ required: true,+ },+ {+ key: "loginHeaders.X-Client-Secret",+ labelKey: `${PREFIX}.consigno.fields.clientSecret.label`,+ control: "password",+ required: true,+ },+ {+ key: "loginBody.username",+ labelKey: `${PREFIX}.consigno.fields.username.label`,+ control: "text",+ required: true,+ },+ {+ key: "loginBody.password",+ labelKey: `${PREFIX}.consigno.fields.password.label`,+ control: "password",+ required: true,+ },+ {+ key: "loginBody.tenantId",+ labelKey: `${PREFIX}.consigno.fields.tenantId.label`,+ control: "text",+ helperTextKey: `${PREFIX}.consigno.fields.tenantId.helperText`,+ },+];++const CUSTOM_API_FIELDS: ConnectionFieldDef[] = [+ {+ key: "baseUrl",+ labelKey: `${PREFIX}.api.fields.baseUrl.label`,+ control: "text",+ required: true,+ placeholderKey: `${PREFIX}.api.fields.baseUrl.placeholder`,+ helperTextKey: `${PREFIX}.api.fields.baseUrl.helperText`,+ },+ {+ key: "authType",+ labelKey: `${PREFIX}.api.fields.authType.label`,+ control: "select",+ defaultValue: "NONE",+ options: [+ {+ value: "NONE",+ labelKey: `${PREFIX}.api.fields.authType.options.none.label`,+ },+ {+ value: "BEARER",+ labelKey: `${PREFIX}.api.fields.authType.options.bearer.label`,+ },+ {+ value: "BASIC",+ labelKey: `${PREFIX}.api.fields.authType.options.basic.label`,+ },+ {+ value: "HEADER",+ labelKey: `${PREFIX}.api.fields.authType.options.header.label`,+ },+ {+ value: "TOKEN_LOGIN",+ labelKey: `${PREFIX}.api.fields.authType.options.tokenLogin.label`,+ },+ ],+ },+ {+ key: "token",+ labelKey: `${PREFIX}.api.fields.token.label`,+ control: "password",+ required: true,+ visibleWhen: { key: "authType", oneOf: ["BEARER", "HEADER"] },+ },+ {+ key: "headerName",+ labelKey: `${PREFIX}.api.fields.headerName.label`,+ control: "text",+ required: true,+ placeholderKey: `${PREFIX}.api.fields.headerName.placeholder`,+ visibleWhen: { key: "authType", oneOf: ["HEADER"] },+ },+ {+ key: "username",+ labelKey: `${PREFIX}.api.fields.username.label`,+ control: "text",+ required: true,+ visibleWhen: { key: "authType", oneOf: ["BASIC"] },+ },+ {+ key: "password",+ labelKey: `${PREFIX}.api.fields.password.label`,+ control: "password",+ required: true,+ visibleWhen: { key: "authType", oneOf: ["BASIC"] },+ },+ {+ key: "loginPath",+ labelKey: `${PREFIX}.api.fields.loginPath.label`,+ control: "text",+ required: true,+ placeholderKey: `${PREFIX}.api.fields.loginPath.placeholder`,+ visibleWhen: { key: "authType", oneOf: ["TOKEN_LOGIN"] },+ },+ {+ key: "tokenResponseHeader",+ labelKey: `${PREFIX}.api.fields.tokenResponseHeader.label`,+ control: "text",+ required: true,+ helperTextKey: `${PREFIX}.api.fields.tokenResponseHeader.helperText`,+ visibleWhen: { key: "authType", oneOf: ["TOKEN_LOGIN"] },+ },+ {+ key: "tokenHeaderName",+ labelKey: `${PREFIX}.api.fields.tokenHeaderName.label`,+ control: "text",+ required: true,+ visibleWhen: { key: "authType", oneOf: ["TOKEN_LOGIN"] },+ },+ {+ key: "resultUrlHosts",+ labelKey: `${PREFIX}.api.fields.resultUrlHosts.label`,+ control: "hostList",+ helperTextKey: `${PREFIX}.api.fields.resultUrlHosts.helperText`,+ },+];++/**+ * Fields shared across vendors. "API key" reads the same for VirusTotal and Mindee, so it is+ * translated once here rather than 25 times under each vendor's namespace; only genuinely+ * vendor-specific wording (Purview's "Directory (tenant) ID") lives under the vendor.+ */+const field = {+ /** Tenant-specific server URL. `id` names the vendor whose placeholder/help to show. */+ baseUrl: (id: string): ConnectionFieldDef => ({+ key: "baseUrl",+ labelKey: `${COMMON}.baseUrl.label`,+ control: "text",+ required: true,+ placeholderKey: `${PREFIX}.${id}.baseUrlPlaceholder`,+ helperTextKey: `${COMMON}.baseUrl.helperText`,+ }),+ /** The URL a vendor hands you to post to (Teams/Zapier/webhook), which IS the whole endpoint. */+ webhookUrl: (id: string): ConnectionFieldDef => ({+ key: "baseUrl",+ labelKey: `${COMMON}.webhookUrl.label`,+ control: "text",+ required: true,+ placeholderKey: `${PREFIX}.${id}.baseUrlPlaceholder`,+ helperTextKey: `${COMMON}.webhookUrl.helperText`,+ }),+ apiKey: (): ConnectionFieldDef => ({+ key: "token",+ labelKey: `${COMMON}.apiKey.label`,+ control: "password",+ required: true,+ }),+ accessToken: (): ConnectionFieldDef => ({+ key: "token",+ labelKey: `${COMMON}.accessToken.label`,+ control: "password",+ required: true,+ helperTextKey: `${COMMON}.accessToken.helperText`,+ }),+ username: (labelKey = `${COMMON}.username.label`): ConnectionFieldDef => ({+ key: "username",+ labelKey,+ control: "text",+ required: true,+ }),+ password: (labelKey = `${COMMON}.password.label`): ConnectionFieldDef => ({+ key: "password",+ labelKey,+ control: "password",+ required: true,+ }),+};++/**+ * A vendor whose integration is "an HTTP API with known mechanics". The auth shape, and the base+ * URL when the vendor has a single global one, are baked into `preset`; the operator supplies only+ * credentials. Adding a vendor is this entry plus two lines of copy — no component, no backend.+ */+function apiPreset(spec: {+ id: string;+ category: ConnectionCategory;+ preset: Record<string, unknown>;+ fields: ConnectionFieldDef[];+ searchTerms?: string[];+ identifyHosts?: string[];+}): CreatableConnectionType {+ return {+ id: spec.id,+ integrationType: "API",+ kind: "preset",+ category: spec.category,+ labelKey: `${PREFIX}.${spec.id}.label`,+ descriptionKey: `${PREFIX}.${spec.id}.description`,+ searchTerms: spec.searchTerms,+ presetConfig: spec.preset,+ identifyHosts: spec.identifyHosts,+ fields: spec.fields,+ };+}++/**+ * Vendors whose HTTP contract has been verified against their published documentation.+ *+ * The bar is deliberately narrow, because the pipeline can make exactly ONE call per step and+ * carries nothing from one step to the next. A vendor earns a place here only if it is:+ *+ * 1. **one call** - no submit-then-poll, no upload-then-attach;+ * 2. **a static credential** - no OAuth2 refresh, no per-request signature;+ * 3. **useful in that one call** - the answer comes back, or the call itself is the point.+ *+ * That excludes most of the obvious names. Every e-signature vendor is multi-call (create, send,+ * then retrieve the signed file later). Azure Document Intelligence, ABBYY, VirusTotal, Rossum and+ * Mindee are all submit-then-poll. SharePoint, Drive, Box, Salesforce and the rest are OAuth. They+ * are not missing by oversight - they cannot work correctly here yet, and listing them would be a+ * promise the engine cannot keep.+ */+const API_PRESETS: CreatableConnectionType[] = [+ // ---- malware & active content -------------------------------------------------------------+ apiPreset({+ id: "cloudmersive",+ category: "security",+ preset: {+ authType: "HEADER",+ headerName: "Apikey",+ baseUrl: "https://api.cloudmersive.com",+ },+ fields: [field.apiKey()],+ searchTerms: ["malware", "antivirus", "virus", "scan", "threat"],+ }),+ apiPreset({+ id: "cloudmersiveadvanced",+ category: "security",+ preset: {+ authType: "HEADER",+ headerName: "Apikey",+ baseUrl: "https://api.cloudmersive.com",+ },+ fields: [field.apiKey()],+ searchTerms: [+ "macro",+ "executable",+ "script",+ "active content",+ "malware",+ "ole",+ "scan",+ ],+ }),+ apiPreset({+ id: "clamav",+ category: "security",+ // Self-hosted: no vendor account, no key, and the document never leaves the estate - which is+ // the whole argument for on-prem customers who cannot send files to a cloud scanner.+ preset: { authType: "NONE" },+ fields: [field.baseUrl("clamav")],+ searchTerms: [+ "virus",+ "malware",+ "antivirus",+ "scan",+ "self-hosted",+ "on-prem",+ ],+ }),++ // ---- audit & SIEM ---------------------------------------------------------------------------+ apiPreset({+ id: "splunk",+ category: "audit",+ preset: {+ authType: "HEADER",+ headerName: "Authorization",+ headerPrefix: "Splunk",+ },+ fields: [field.baseUrl("splunk"), field.apiKey()],+ searchTerms: ["siem", "hec", "audit", "log", "event", "compliance"],+ }),+ apiPreset({+ id: "elastic",+ category: "audit",+ preset: {+ authType: "HEADER",+ headerName: "Authorization",+ headerPrefix: "ApiKey",+ },+ fields: [field.baseUrl("elastic"), field.apiKey()],+ searchTerms: ["siem", "elasticsearch", "kibana", "audit", "log", "index"],+ }),+ apiPreset({+ id: "sumologic",+ category: "audit",+ preset: { authType: "NONE" },+ fields: [field.webhookUrl("sumologic")],+ searchTerms: ["siem", "audit", "log", "collector"],+ }),++ // ---- PII detection ---------------------------------------------------------------------------+ apiPreset({+ id: "presidio",+ category: "security",+ // Self-hosted and unauthenticated by design; takes TEXT, so it needs extracted text rather+ // than the document itself.+ preset: { authType: "NONE" },+ fields: [field.baseUrl("presidio")],+ searchTerms: ["pii", "dlp", "sensitive", "redact", "gdpr", "self-hosted"],+ }),++ // ---- email the document ----------------------------------------------------------------------+ apiPreset({+ id: "sendgrid",+ category: "notify",+ preset: { authType: "BEARER", baseUrl: "https://api.sendgrid.com/v3" },+ fields: [field.apiKey()],+ searchTerms: ["email", "mail", "send", "attachment", "twilio"],+ }),+ apiPreset({+ id: "mailgun",+ category: "notify",+ // Region matters: EU domains must use api.eu.mailgun.net and are not auto-detected.+ preset: { authType: "BASIC", username: "api" },+ fields: [+ field.baseUrl("mailgun"),+ field.password(`${COMMON}.apiKey.label`),+ ],+ searchTerms: ["email", "mail", "send", "attachment"],+ }),++ // ---- notify ------------------------------------------------------------------------------------+ apiPreset({+ id: "slack",+ category: "notify",+ preset: { authType: "NONE" },+ fields: [field.webhookUrl("slack")],+ searchTerms: ["chat", "notify", "message", "alert"],+ identifyHosts: ["slack.com"],+ }),+ apiPreset({+ id: "teams",+ category: "notify",+ preset: { authType: "NONE" },+ fields: [field.webhookUrl("teams")],+ searchTerms: ["microsoft", "chat", "notify", "message", "alert"],+ // Classic incoming webhooks post from *.webhook.office.com; Workflows from *.logic.azure.com.+ identifyHosts: ["webhook.office.com", "logic.azure.com"],+ }),+ apiPreset({+ id: "discord",+ category: "notify",+ preset: { authType: "NONE" },+ fields: [field.webhookUrl("discord")],+ searchTerms: ["chat", "notify", "message"],+ identifyHosts: ["discord.com", "discordapp.com"],+ }),+ apiPreset({+ id: "googlechat",+ category: "notify",+ preset: { authType: "NONE" },+ fields: [field.webhookUrl("googlechat")],+ searchTerms: ["google", "chat", "notify", "workspace", "message"],+ identifyHosts: ["chat.googleapis.com"],+ }),+ apiPreset({+ id: "zapier",+ category: "notify",+ preset: { authType: "NONE" },+ fields: [field.webhookUrl("zapier")],+ searchTerms: ["make", "automation", "workflow", "trigger", "no-code"],+ identifyHosts: ["zapier.com"],+ }),+ apiPreset({+ id: "webhook",+ category: "notify",+ preset: { authType: "NONE" },+ fields: [field.webhookUrl("webhook")],+ searchTerms: ["http", "post", "callback", "custom", "notify"],+ }),++ // ---- file & attach: tickets and pages are destinations just like buckets -----------------------+ apiPreset({+ id: "jira",+ category: "storage",+ preset: { authType: "BASIC" },+ fields: [+ field.baseUrl("jira"),+ field.username(`${COMMON}.email.label`),+ field.password(`${COMMON}.apiToken.label`),+ ],+ searchTerms: ["atlassian", "issue", "ticket", "attach", "project"],+ }),+ apiPreset({+ id: "confluence",+ category: "storage",+ preset: { authType: "BASIC" },+ fields: [+ field.baseUrl("confluence"),+ field.username(`${COMMON}.email.label`),+ field.password(`${COMMON}.apiToken.label`),+ ],+ searchTerms: ["atlassian", "wiki", "page", "attach", "space"],+ }),++ // ---- file to storage ------------------------------------------------------------------------------+ apiPreset({+ id: "nextcloud",+ category: "storage",+ preset: { authType: "BASIC" },+ fields: [+ field.baseUrl("nextcloud"),+ field.username(),+ field.password(`${PREFIX}.nextcloud.fields.appPassword`),+ ],+ searchTerms: ["owncloud", "webdav", "files", "self-hosted", "upload"],+ }),+];++export const CREATABLE_CONNECTION_TYPES: CreatableConnectionType[] = [+ {+ id: "s3",+ integrationType: "S3",+ kind: "preset",+ category: "storage",+ labelKey: `${PREFIX}.s3.label`,+ descriptionKey: `${PREFIX}.s3.description`,+ searchTerms: ["aws", "bucket", "minio", "object storage"],+ fields: S3_FIELDS,+ },+ {+ id: "purview",+ integrationType: "PURVIEW",+ kind: "preset",+ category: "security",+ labelKey: `${PREFIX}.purview.label`,+ descriptionKey: `${PREFIX}.purview.description`,+ searchTerms: ["microsoft", "sensitivity", "label", "classification", "mip"],+ fields: PURVIEW_FIELDS,+ },+ {+ id: "consigno",+ integrationType: "CONSIGNO",+ kind: "preset",+ category: "signing",+ labelKey: `${PREFIX}.consigno.label`,+ descriptionKey: `${PREFIX}.consigno.description`,+ searchTerms: ["notarius", "notarize", "esign", "sign", "certifio"],+ // The vendor's auth shape, baked in: the operator supplies credentials, never the mechanics.+ presetConfig: {+ authType: "TOKEN_LOGIN",+ loginPath: "/auth/login",+ tokenResponseHeader: "X-Auth-Token",+ tokenHeaderName: "X-Auth-Token",+ },+ fields: CONSIGNO_FIELDS,+ },+ ...API_PRESETS,+ {+ id: "api",+ integrationType: "API",+ kind: "custom",+ category: "advanced",+ labelKey: `${PREFIX}.api.label`,+ descriptionKey: `${PREFIX}.api.description`,+ requiresCustomApi: true,+ fields: CUSTOM_API_FIELDS,+ },+];++/** Free-text match over name, description-agnostic keywords and category. */+export function searchConnectionTypes(+ types: CreatableConnectionType[],+ query: string,+ label: (key: string) => string,+): CreatableConnectionType[] {+ const q = query.trim().toLowerCase();+ if (!q) return types;+ return types.filter((type) => {+ const haystack = [+ label(type.labelKey),+ type.id,+ type.category,+ ...(type.searchTerms ?? []),+ ]+ .join(" ")+ .toLowerCase();+ return q.split(/\s+/).every((word) => haystack.includes(word));+ });+}++/** The types this caller may create. `customApi` comes from the server, never inferred here. */+export function creatableConnectionTypes(+ capabilities: { customApi: boolean } | undefined,+): CreatableConnectionType[] {+ return CREATABLE_CONNECTION_TYPES.filter(+ (type) => !type.requiresCustomApi || capabilities?.customApi === true,+ );+}++/** The supported vendors — the primary path an operator picks from. */+export function presetConnectionTypes(): CreatableConnectionType[] {+ return CREATABLE_CONNECTION_TYPES.filter((type) => type.kind === "preset");+}++/**+ * Build the config payload for a type: its preset, then the operator's answers.+ *+ * Dotted keys (`loginBody.password`) nest, so a preset's credentials land where the backend expects+ * them *and* where `SecretMasker` can see them — it recurses into nested maps and masks by key name,+ * so a flat `loginBody` string would hand the password back in clear on every read.+ */+/**+ * Reserved config key recording which preset created a connection.+ *+ * A stored connection only carries an `integrationType`, and most presets share `"API"` - Discord,+ * Splunk, Jira and fourteen others are all `API`. Without this, mapping a saved connection back to+ * its preset is guesswork, and guessing wrong means the edit form renders another vendor's fields+ * and overwrites the config on save. The backend keeps `config` as a free-form map and ignores keys+ * it does not model, so this rides along without a schema change.+ */+export const PRESET_ID_KEY = "presetId";++export function buildConnectionConfig(+ type: CreatableConnectionType,+ values: Record<string, string>,+): Record<string, unknown> {+ const config: Record<string, unknown> = {+ ...(type.presetConfig ?? {}),+ [PRESET_ID_KEY]: type.id,+ };+ for (const field of type.fields) {+ const raw = values[field.key];+ if (raw === undefined || raw === "") continue;+ const value: unknown =+ field.control === "hostList"+ ? raw+ .split(/[\s,]+/)+ .map((entry) => entry.trim())+ .filter(Boolean)+ : raw;+ setPath(config, field.key, value);+ }+ return config;+}++/** Whether a field should be shown given the answers so far. */+export function isFieldVisible(+ field: ConnectionFieldDef,+ values: Record<string, string>,+): boolean {+ if (!field.visibleWhen) return true;+ const current = values[field.visibleWhen.key] ?? "";+ return field.visibleWhen.oneOf.includes(current);+}++/** The hostname of a URL, lowercased, or undefined if it is missing or unparseable. */+function hostOf(url: unknown): string | undefined {+ if (typeof url !== "string" || url === "") return undefined;+ try {+ return new URL(url).hostname.toLowerCase();+ } catch {+ return undefined;+ }+}++/**+ * The vendor a stored connection points at, recovered from its URL when the `presetId` marker is+ * absent. Only an unambiguous host wins: two presets sharing a host (the Cloudmersive pair) is+ * treated as unknown rather than guessed, since guessing wrong would show the wrong form.+ */+function presetByHost(host: string): CreatableConnectionType | undefined {+ const matches = new Set<CreatableConnectionType>();+ for (const type of CREATABLE_CONNECTION_TYPES) {+ // Webhook vendors: the operator supplies the URL, so match the vendor's domain and subdomains.+ for (const sig of type.identifyHosts ?? []) {+ if (host === sig || host.endsWith(`.${sig}`)) matches.add(type);+ }+ // Fixed-host presets: the base URL is baked in, so an exact host match identifies them.+ if (hostOf(type.presetConfig?.baseUrl) === host) matches.add(type);+ }+ return matches.size === 1 ? [...matches][0] : undefined;+}++/** The type an existing connection was made from, so editing reuses its form. */+export function connectionTypeOf(+ integrationType: IntegrationType,+ config?: Record<string, unknown> | null,+): CreatableConnectionType | undefined {+ const presetId = config?.[PRESET_ID_KEY];+ if (typeof presetId === "string") {+ const exact = CREATABLE_CONNECTION_TYPES.find((t) => t.id === presetId);+ if (exact) return exact;+ }++ const candidates = CREATABLE_CONNECTION_TYPES.filter(+ (type) => type.integrationType === integrationType,+ );+ if (candidates.length === 1) return candidates[0];++ // No marker (made before it existed, or through the API): recover the vendor from the URL it+ // points at, since a Discord webhook is always discord.com and so on. Showing "Custom API" for+ // something the operator set up as Discord is both confusing and, on save, what rewrote the+ // webhook as another vendor's endpoint.+ const host = hostOf(config?.baseUrl);+ if (host) {+ const byHost = presetByHost(host);+ if (byHost && byHost.integrationType === integrationType) return byHost;+ }++ // Still unknown: fall back to the free-form entry rather than naming a vendor at random. It shows+ // the base URL and auth the connection actually has, so editing preserves them.+ return candidates.find((type) => type.kind === "custom") ?? candidates[0];+}++/** Blank answers for a new connection: the fields' defaults, plus an empty name. */+export function emptyConnectionValues(+ type: CreatableConnectionType,+): Record<string, string> {+ const values: Record<string, string> = { name: "" };+ for (const field of type.fields) {+ values[field.key] = field.defaultValue ?? "";+ }+ return values;+}++/**+ * Seed the form from a stored connection. Secrets arrive masked and are carried back verbatim,+ * which is what tells the backend to keep the stored value (`SecretMasker.merge`).+ */+export function connectionFormValues(+ type: CreatableConnectionType,+ connection: { name: string; config: Record<string, unknown> },+): Record<string, string> {+ const values = emptyConnectionValues(type);+ values.name = connection.name;+ for (const field of type.fields) {+ const stored = getPath(connection.config, field.key);+ if (stored === undefined || stored === null) continue;+ values[field.key] = Array.isArray(stored)+ ? stored.join(", ")+ : String(stored);+ }+ return values;+}++/** Name plus every required field that is actually on screen. */+export function connectionFormValid(+ type: CreatableConnectionType,+ values: Record<string, string>,+): boolean {+ if ((values.name ?? "").trim() === "") return false;+ return type.fields.every(+ (field) =>+ !field.required ||+ !isFieldVisible(field, values) ||+ (values[field.key] ?? "").trim() !== "",+ );+}++function getPath(source: Record<string, unknown>, path: string): unknown {+ let node: unknown = source;+ for (const segment of path.split(".")) {+ if (typeof node !== "object" || node === null) return undefined;+ node = (node as Record<string, unknown>)[segment];+ }+ return node;+}++function setPath(+ target: Record<string, unknown>,+ path: string,+ value: unknown,+): void {+ const segments = path.split(".");+ let node = target;+ for (let i = 0; i < segments.length - 1; i++) {+ const next = node[segments[i]];+ if (typeof next !== "object" || next === null) {+ node[segments[i]] = {};+ }+ node = node[segments[i]] as Record<string, unknown>;+ }+ node[segments[segments.length - 1]] = value;+}diff --git a/frontend/editor/src/portal/mocks/handlers/index.ts b/frontend/editor/src/portal/mocks/handlers/index.tsindex 8163c10e4d..0600656524 100644--- a/frontend/editor/src/portal/mocks/handlers/index.ts+++ b/frontend/editor/src/portal/mocks/handlers/index.ts@@ -15,6 +15,7 @@ import { classificationHandlers } from "@portal/mocks/handlers/classification";import { documentsHandlers } from "@portal/mocks/handlers/documents";import { editorDeployHandlers } from "@portal/mocks/handlers/editorDeploy";import { linkHandlers } from "@portal/mocks/handlers/link";+import { integrationsHandlers } from "@portal/mocks/handlers/integrations";export const handlers = [...authHandlers,@@ -34,6 +35,7 @@ export const handlers = [...documentsHandlers,...editorDeployHandlers,...linkHandlers,+ ...integrationsHandlers,];export { resetNotificationsStore } from "@portal/mocks/handlers/notifications";diff --git a/frontend/editor/src/portal/mocks/handlers/integrations.ts b/frontend/editor/src/portal/mocks/handlers/integrations.tsnew file mode 100644index 0000000000..ed71db265c--- /dev/null+++ b/frontend/editor/src/portal/mocks/handlers/integrations.ts@@ -0,0 +1,128 @@+import { http, HttpResponse } from "msw";++/**+ * Stored connections, for stories and the demo tour.+ *+ * Secrets are returned masked, exactly as the backend does — a fixture that handed back a real+ * secret would quietly teach the wrong thing about the contract.+ */+const CONNECTIONS = [+ {+ id: 1,+ integrationType: "S3",+ name: "Claims intake bucket",+ scope: "TEAM",+ ownerUserId: null,+ ownerTeamId: 1,+ enabled: true,+ locked: false,+ defaultAccess: "EXPLICIT_ONLY",+ config: {+ bucket: "acme-claims-inbox",+ region: "eu-west-2",+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "********",+ },+ canManage: true,+ createdAt: "2026-07-02T09:12:00",+ updatedAt: "2026-07-02T09:12:00",+ },+ {+ id: 2,+ integrationType: "PURVIEW",+ name: "Contoso Purview",+ scope: "TEAM",+ ownerUserId: null,+ ownerTeamId: 1,+ enabled: true,+ locked: false,+ defaultAccess: "EXPLICIT_ONLY",+ config: {+ tenantId: "cb46c030-1825-4e81-a295-151c039dbf02",+ clientId: "8f2a1c44-9b21-4d0e-9c33-2b7e5a10d4f1",+ clientSecret: "********",+ },+ canManage: true,+ createdAt: "2026-07-11T14:03:00",+ updatedAt: "2026-07-16T08:40:00",+ },+ {+ id: 3,+ integrationType: "CONSIGNO",+ name: "Notarius (production)",+ scope: "TEAM",+ ownerUserId: null,+ ownerTeamId: 1,+ enabled: true,+ locked: false,+ defaultAccess: "EXPLICIT_ONLY",+ config: {+ baseUrl: "https://acme.consignocloud.com/api/v1",+ authType: "TOKEN_LOGIN",+ loginPath: "/auth/login",+ tokenResponseHeader: "X-Auth-Token",+ tokenHeaderName: "X-Auth-Token",+ loginHeaders: {+ "X-Client-Id": "acme-prod",+ "X-Client-Secret": "********",+ },+ loginBody: {+ username: "[email protected]",+ password: "********",+ tenantId: "acme",+ },+ },+ canManage: true,+ createdAt: "2026-07-14T11:25:00",+ updatedAt: "2026-07-14T11:25:00",+ },+ {+ id: 4,+ integrationType: "API",+ name: "Acme DLP scanner",+ scope: "TEAM",+ ownerUserId: null,+ ownerTeamId: 1,+ enabled: true,+ locked: false,+ defaultAccess: "EXPLICIT_ONLY",+ config: {+ baseUrl: "https://dlp.acme-security.example/v2",+ authType: "BEARER",+ token: "********",+ resultUrlHosts: ["cdn.acme-security.example"],+ },+ canManage: true,+ createdAt: "2026-07-15T16:47:00",+ updatedAt: "2026-07-15T16:47:00",+ },+];++export const integrationsHandlers = [+ http.get("*/api/v1/integrations", () => HttpResponse.json(CONNECTIONS)),+ // Stories show the admin's view; the server is the real gate.+ http.get("*/api/v1/integrations/capabilities", () =>+ HttpResponse.json({ customApi: true }),+ ),+ http.post("*/api/v1/integrations", async ({ request }) => {+ const body = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({+ ...CONNECTIONS[0],+ id: 99,+ ...body,+ canManage: true,+ });+ }),+ http.put("*/api/v1/integrations/:id", async ({ request, params }) => {+ const body = (await request.json()) as Record<string, unknown>;+ return HttpResponse.json({+ ...CONNECTIONS[0],+ id: Number(params.id),+ ...body,+ });+ }),+ http.delete(+ "*/api/v1/integrations/:id",+ () => new HttpResponse(null, { status: 204 }),+ ),+];diff --git a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx b/frontend/editor/src/portal/views/PipelineBuilder.test.tsxindex a9a8aab0f7..6f40b82764 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx@@ -53,6 +53,9 @@ vi.mock("@portal/api/policies", () => ({const fetchS3Connections = vi.fn();const createIntegration = vi.fn();vi.mock("@portal/api/integrations", () => ({+ fetchIntegrations: () => fetchS3Connections(),+ // Custom-API authoring is a server decision; these tests assert the default view.+ fetchIntegrationCapabilities: () => Promise.resolve({ customApi: false }),fetchS3Connections: () => fetchS3Connections(),createIntegration: (...args: unknown[]) => createIntegration(...args),}));@@ -209,24 +212,24 @@ describe("PipelineBuilder", () => {await screen.findByText("portal.connections.picker.createNew"),);fireEvent.change(- screen.getByLabelText(/portal\.connections\.s3\.fields\.name/),+ screen.getByLabelText(/portal\.connections\.fields\.name/),{ target: { value: "Claims bucket" } },);fireEvent.change(screen.getByLabelText(- /portal\.sources\.types\.s3\.fields\.bucket\.label/,+ /portal\.connections\.types\.s3\.fields\.bucket\.label/,),{ target: { value: "claims-processed" } },);fireEvent.change(screen.getByLabelText(- /portal\.sources\.types\.s3\.fields\.accessKeyId\.label/,+ /portal\.connections\.types\.s3\.fields\.accessKeyId\.label/,),{ target: { value: "AKIAEXAMPLE" } },);fireEvent.change(screen.getByLabelText(- /portal\.sources\.types\.s3\.fields\.secretAccessKey\.label/,+ /portal\.connections\.types\.s3\.fields\.secretAccessKey\.label/,),{ target: { value: "shh-secret" } },);@@ -330,6 +333,28 @@ describe("PipelineBuilder", () => {).toBeDisabled();});+ it("blocks saving an integration step with no account chosen", async () => {+ // A Discord step added but left without an account would fail at run time with a raw backend+ // rejection; the builder must refuse to save it and say why, where the fix is one click away.+ renderBuilder("/processor/pipelines/new");++ fireEvent.change(await screen.findByRole("textbox"), {+ target: { value: "Notify only" },+ });+ fireEvent.click(screen.getByRole("button", { name: /addTool/ }));+ fireEvent.click(+ await screen.findByText("portal.policies.operations.discordNotify.label"),+ );++ // Operation chosen, account not: still not saveable.+ expect(+ await screen.findByText("portal.pipelines.builder.stepsNeedSetup"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("portal.pipelines.composer.create").closest("button"),+ ).toBeDisabled();+ });+it("deletes an existing pipeline after confirmation", async () => {renderBuilder("/processor/pipelines/plc-1");@@ -355,6 +380,49 @@ describe("PipelineBuilder", () => {expect(await screen.findByText("pipelines list")).toBeInTheDocument();});+ it("keeps the account chosen for an integration step", async () => {+ // The regression: integration steps are deliberately toolId-less, and the builder's param+ // update used to skip exactly those, so picking an account looked like it did nothing.+ fetchS3Connections.mockResolvedValue([+ {+ id: 9,+ name: "Ops alerts",+ integrationType: "API",+ config: { presetId: "discord" },+ },+ ]);+ renderBuilder("/processor/pipelines/new");++ fireEvent.change(await screen.findByRole("textbox"), {+ target: { value: "Notify on processed" },+ });++ fireEvent.click(screen.getByRole("button", { name: /addTool/ }));+ fireEvent.click(+ await screen.findByText("portal.policies.operations.discordNotify.label"),+ );++ fireEvent.click(+ await screen.findByPlaceholderText(+ "portal.connections.picker.placeholder",+ ),+ );+ fireEvent.click(await screen.findByText("Ops alerts"));++ fireEvent.click(screen.getByText("portal.pipelines.composer.create"));++ await waitFor(() => expect(savePipeline).toHaveBeenCalledTimes(1));+ const saved = savePipeline.mock.calls[0][0] as Policy;+ const step = saved.steps[0] as unknown as {+ operation: string;+ parameters: Record<string, string>;+ };+ expect(step.operation).toBe("/api/v1/integration/external-api-call");+ // The selection survived all the way to the wire, not just to the dropdown.+ expect(step.parameters.connectionId).toBe("9");+ expect(step.parameters.operationId).toBe("discordNotify");+ });+it("leaves immediately when there are no unsaved edits", async () => {renderBuilder("/processor/pipelines/new");diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsxindex 28e040bcce..66c5748e85 100644--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx@@ -58,6 +58,13 @@ import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";import { humanizeOperation } from "@portal/components/pipelines/pipelineOperations";import { PipelineStepSettings } from "@portal/components/pipelines/PipelineStepSettings";import { ToolPicker } from "@portal/components/pipelines/ToolPicker";+import { STEP_OPERATIONS } from "@portal/components/policies/stepOperations";+import {+ integrationStepConfigured,+ isIntegrationStep,+ newIntegrationStep,+ stepOperation,+} from "@portal/components/pipelines/integrationStep";import "@portal/views/PipelineBuilder.css";type OutputMode = PipelineOutputMode;@@ -271,6 +278,15 @@ export function PipelineBuilder() {);}+ function addOperationStep(op: (typeof STEP_OPERATIONS)[number]) {+ setSteps((current) => {+ const next = [...current, newIntegrationStep(op)];+ setSelectedIndex(next.length - 1);+ return next;+ });+ setPickerOpen(false);+ }+function addStep(tool: ExecutableTool) {setSteps((current) => {const next = [...current, newWorkingToolStep(tool, allTools)];@@ -299,12 +315,22 @@ export function PipelineBuilder() {function updateStepParams(index: number, params: ErasedToolParams) {setSteps((current) =>current.map((step, i) =>- i === index && step.toolId !== null ? { ...step, params } : step,+ // Integration steps are deliberately toolId-less, so they must be editable too; only a+ // genuinely unrecognised step has no editor to send changes from.+ i === index && (step.toolId !== null || isIntegrationStep(step))+ ? { ...step, params }+ : step,),);}function stepLabel(step: WorkingToolStep): string {+ // An integration step's endpoint is the same for every vendor, so the raw path would read+ // "External api call" for all of them. Name it by the operation instead.+ const op = stepOperation(step);+ if (op) return t(op.labelKey);+ if (isIntegrationStep(step))+ return t("portal.pipelines.builder.sendToSystem");const entry = step.toolId ? allTools[step.toolId] : undefined;return entry?.name ?? humanizeOperation(step.operation);}@@ -314,6 +340,13 @@ export function PipelineBuilder() {const uploadStepLabels = steps.filter(stepRequiresUpload).map(stepLabel);const hasUploadSteps = uploadStepLabels.length > 0;+ // An integration step with no operation or no account chosen would fail at run time with a raw+ // backend rejection, so block saving on it here where the fix is one click away.+ const unconfiguredStepLabels = steps+ .filter((step) => !integrationStepConfigured(step))+ .map(stepLabel);+ const hasUnconfiguredSteps = unconfiguredStepLabels.length > 0;+// Track unsaved edits: snapshot the form and compare against the state captured just after// seeding, so leaving the builder can prompt to save or discard.const snapshot = JSON.stringify({@@ -346,6 +379,7 @@ export function PipelineBuilder() {scheduleCountValid &&outputValid &&!hasUploadSteps &&+ !hasUnconfiguredSteps &&!submitting;const triggerOptions = [@@ -644,6 +678,14 @@ export function PipelineBuilder() {})}/>)}+ {hasUnconfiguredSteps && (+ <Banner+ tone="warning"+ description={t("portal.pipelines.builder.stepsNeedSetup", {+ tools: unconfiguredStepLabels.join(", "),+ })}+ />+ )}{/* Pipeline-level settings, above the operation list. */}<section className="portal-builder__settings">@@ -819,7 +861,17 @@ export function PipelineBuilder() {<span className="portal-builder__step-name">{stepLabel(step)}</span>- {stepRequiresUpload(step) ? (+ {isIntegrationStep(step) ? (+ !stepOperation(step) ? (+ <span className="portal-builder__step-note">+ {t("portal.pipelines.builder.chooseOperation")}+ </span>+ ) : !integrationStepConfigured(step) ? (+ <span className="portal-builder__step-note">+ {t("portal.pipelines.builder.chooseAccount")}+ </span>+ ) : null+ ) : stepRequiresUpload(step) ? (<span className="portal-builder__step-note">{t("portal.pipelines.builder.needsUpload")}</span>@@ -874,6 +926,8 @@ export function PipelineBuilder() {<ToolPickertools={executableTools}onPick={addStep}+ operations={STEP_OPERATIONS}+ onPickOperation={addOperationStep}onClose={() => setPickerOpen(false)}/>) : (diff --git a/frontend/editor/src/portal/views/SourceBuilder.test.tsx b/frontend/editor/src/portal/views/SourceBuilder.test.tsxindex 517b28f515..60a9f13b93 100644--- a/frontend/editor/src/portal/views/SourceBuilder.test.tsx+++ b/frontend/editor/src/portal/views/SourceBuilder.test.tsx@@ -30,6 +30,8 @@ vi.mock("@portal/api/sources", () => ({const fetchS3Connections = vi.fn();vi.mock("@portal/api/integrations", () => ({+ fetchIntegrations: () => Promise.resolve([]),+ fetchIntegrationCapabilities: () => Promise.resolve({ customApi: false }),fetchS3Connections: () => fetchS3Connections(),createIntegration: vi.fn(),}));diff --git a/frontend/editor/src/portal/views/Sources.css b/frontend/editor/src/portal/views/Sources.cssindex 96bd2dc5f3..0fd4646f17 100644--- a/frontend/editor/src/portal/views/Sources.css+++ b/frontend/editor/src/portal/views/Sources.css@@ -526,6 +526,71 @@gap: 0.75rem;}+/* Back to the grid from the form. Sits above the fields, where the type dropdown used to be. */+.portal-sources__connection-back {+ display: inline-flex;+ align-items: center;+ gap: 0.35rem;+ margin-bottom: 1rem;+ padding: 0;+ background: none;+ border: none;+ cursor: pointer;+ font: inherit;+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}++.portal-sources__connection-back:hover {+ color: var(--text-default, inherit);+}++/* The "request an integration" / "advanced" affordances, set below the form so presets read as+ the primary path and these as the way out of it. */+.portal-sources__connection-secondary {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem;+ margin-top: 1rem;+ padding-top: 0.75rem;+ border-top: 1px solid var(--c-border-subtle);+}++.portal-sources__connection-link {+ background: none;+ border: none;+ padding: 0;+ cursor: pointer;+ font: inherit;+ font-size: 0.8125rem;+ color: var(--c-conn-accent);+ text-decoration: underline;+ text-underline-offset: 2px;+}++.portal-sources__connection-link:hover {+ opacity: 0.8;+}++/* Free-text fields (result-host list, body template) that outgrow a single-line input. */+.portal-sources__connection-textarea {+ width: 100%;+ padding: 0.5rem 0.75rem;+ border: 1px solid var(--c-border);+ border-radius: var(--radius-sm, 0.375rem);+ background: var(--surface-input, transparent);+ color: inherit;+ font-family: var(--font-mono, ui-monospace, monospace);+ font-size: 0.8125rem;+ line-height: 1.5;+ resize: vertical;+}++.portal-sources__connection-textarea:focus-visible {+ outline: 2px solid var(--c-conn-accent);+ outline-offset: -1px;+}+.portal-sources__connections {margin-top: 1.5rem;}@@ -589,3 +654,182 @@gap: 0.25rem;justify-content: flex-end;}++/* ---- Integration picker ---------------------------------------------------------------------+ A searchable grid of what we can connect to. Sized so a full category is visible without+ scrolling on a laptop, and so the search box is the first thing focus lands on. */+.portal-conn-picker {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ /* Bounded rather than free-growing: the modal should not become the page. */+ max-height: min(60vh, 32rem);+ overflow-y: auto;+}++.portal-conn-picker__search {+ position: sticky;+ top: 0;+ z-index: 1;+ display: flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.5rem 0.75rem;+ border: 1px solid var(--c-border);+ border-radius: var(--radius-sm, 0.375rem);+ /* Real theme token with a transparent fallback so it never falls back to opaque white in dark;+ the border alone is enough to read as an input. */+ background: var(--color-bg-subtle, transparent);+}++.portal-conn-picker__search-icon {+ flex: none;+ font-size: 1.125rem;+ color: var(--c-text-muted);+}++.portal-conn-picker__search input {+ flex: 1;+ min-width: 0;+ border: none;+ background: none;+ outline: none;+ font: inherit;+ color: inherit;+}++.portal-conn-picker__section {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+}++.portal-conn-picker__section-title {+ margin: 0;+ font-size: 0.8125rem;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--c-text-muted);+}++.portal-conn-picker__section-desc {+ margin: 0 0 0.5rem;+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}++.portal-conn-picker__grid {+ display: grid;+ /* auto-fill so the grid reflows to the modal rather than to a fixed column count. */+ grid-template-columns: repeat(auto-fill, minmax(13.5rem, 1fr));+ gap: 0.5rem;+}++.portal-conn-picker__card {+ display: flex;+ align-items: flex-start;+ gap: 0.625rem;+ padding: 0.625rem 0.75rem;+ text-align: left;+ cursor: pointer;+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-sm, 0.375rem);+ background: var(--surface-subtle, transparent);+ font: inherit;+ color: inherit;+}++.portal-conn-picker__card:hover {+ border-color: var(--c-conn-accent);+ background: color-mix(in srgb, var(--c-conn-neutral) 6%, transparent);+}++/* The custom-API card is an escape hatch, not a vendor: dashed, so it reads as "something else". */+.portal-conn-picker__card--advanced {+ border-style: dashed;+}++.portal-conn-picker__mark {+ flex: none;+ display: grid;+ place-items: center;+ width: 1.75rem;+ height: 1.75rem;+ border-radius: var(--radius-sm, 0.375rem);+ background: color-mix(in srgb, var(--c-conn-accent) 14%, transparent);+ color: var(--c-conn-accent);+ font-size: 0.875rem;+ font-weight: 600;+}++/* One hue per category. Muted on purpose - these sit 60-odd to a page, and saturated marks would+ turn the grid into confetti. */+.portal-conn-picker__mark--storage {+ background: color-mix(in srgb, var(--c-conn-storage) 16%, transparent);+ color: var(--c-conn-storage);+}++.portal-conn-picker__mark--signing {+ background: color-mix(in srgb, var(--c-conn-signing) 18%, transparent);+ color: var(--c-conn-signing);+}++.portal-conn-picker__mark--security {+ background: color-mix(in srgb, var(--c-conn-accent) 16%, transparent);+ color: var(--c-conn-accent);+}++.portal-conn-picker__mark--notify {+ background: color-mix(in srgb, var(--c-conn-notify) 18%, transparent);+ color: var(--c-conn-notify);+}++.portal-conn-picker__mark--advanced {+ background: color-mix(in srgb, var(--c-conn-neutral) 16%, transparent);+ color: var(--c-text-muted);+}++.portal-conn-picker__card-text {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+}++.portal-conn-picker__card-name {+ font-size: 0.875rem;+ font-weight: 500;+}++.portal-conn-picker__card-desc {+ font-size: 0.75rem;+ line-height: 1.35;+ color: var(--c-text-muted);+ /* Two lines keeps every card the same height without truncating most descriptions. */+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++.portal-conn-picker__empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 0.5rem;+ padding: 2rem 1rem;+ text-align: center;+}++.portal-conn-picker__empty-title {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+}++.portal-conn-picker__empty-body {+ margin: 0 0 0.5rem;+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}diff --git a/frontend/editor/src/portal/views/Sources.test.tsx b/frontend/editor/src/portal/views/Sources.test.tsxindex 2bdda1b64b..e3b42356c0 100644--- a/frontend/editor/src/portal/views/Sources.test.tsx+++ b/frontend/editor/src/portal/views/Sources.test.tsx@@ -27,6 +27,9 @@ vi.mock("@portal/api/sources", () => ({const fetchS3Connections = vi.fn();vi.mock("@portal/api/integrations", () => ({+ fetchIntegrations: () => fetchS3Connections(),+ // Custom-API authoring is a server decision; these tests assert the default view.+ fetchIntegrationCapabilities: () => Promise.resolve({ customApi: false }),fetchS3Connections: () => fetchS3Connections(),deleteIntegration: vi.fn(),}));diff --git a/frontend/editor/src/proprietary/policies/operations.test.ts b/frontend/editor/src/proprietary/policies/operations.test.tsindex 30326722e6..c0aa97e153 100644--- a/frontend/editor/src/proprietary/policies/operations.test.ts+++ b/frontend/editor/src/proprietary/policies/operations.test.ts@@ -17,8 +17,11 @@ describe("POLICY_OPERATIONS", () => {expect(ALL_TOOL_IDS.sort()).toEqual(["classify","compress",+ "externalApiCall","flatten","ocr",+ "purviewApplyLabel",+ "purviewReadLabel","redact","sanitize","timestampPdf",diff --git a/frontend/editor/src/proprietary/policies/operations.ts b/frontend/editor/src/proprietary/policies/operations.tsindex 315f1a463a..092d8b50de 100644--- a/frontend/editor/src/proprietary/policies/operations.ts+++ b/frontend/editor/src/proprietary/policies/operations.ts@@ -22,9 +22,24 @@ import type { WirePipelineStep } from "@app/policies/types";*/export type AiPolicyEndpoint = "/api/v1/ai/tools/classify-and-label";-/** An AI tool usable in a policy — the AI-endpoint analogue of a standard tool descriptor. */+/**+ * Endpoints for third-party integration steps. Excluded from the generated {@link ToolEndpoint}+ * union for the same reason as the AI tools: `/api/v1/integration/` is not one of the tool+ * namespaces the generator reads.+ */+export type IntegrationPolicyEndpoint =+ | "/api/v1/integration/external-api-call"+ | "/api/v1/integration/purview-apply-label"+ | "/api/v1/integration/purview-read-label";++/** An endpoint typed here rather than by the generator. */+export type UntypedPolicyEndpoint =+ | AiPolicyEndpoint+ | IntegrationPolicyEndpoint;++/** A tool usable in a policy whose endpoint isn't in the generated union. */export interface AiToolDescriptor<TParams> {- readonly endpoint: AiPolicyEndpoint;+ readonly endpoint: UntypedPolicyEndpoint;readonly defaultParameters: TParams;toApi(params: TParams): Record<string, unknown>;fromApi(api: Record<string, unknown>): TParams;@@ -45,6 +60,35 @@ export function describeAiToolOperation(};}+/**+ * Describe an integration step. Unlike AI tools these carry real parameters, so each supplies its+ * own defaults; every one of them needs a `connectionId` naming the stored connection that holds+ * the endpoint and credentials. Values cross the wire as form fields, hence the string round-trip.+ */+function describeIntegrationOperation<TParams extends Record<string, string>>(+ endpoint: IntegrationPolicyEndpoint,+ defaultParameters: TParams,+): AiToolDescriptor<TParams> {+ return {+ endpoint,+ defaultParameters,+ // Drop blanks rather than send empty fields: the backend distinguishes "absent" from+ // "empty" for optional params like `path` and `labelName`.+ toApi: (params) =>+ Object.fromEntries(+ Object.entries(params).filter(([, value]) => value !== ""),+ ),+ fromApi: (api) => {+ const out = { ...defaultParameters } as Record<string, string>;+ for (const key of Object.keys(defaultParameters)) {+ const value = api[key];+ if (value !== undefined && value !== null) out[key] = String(value);+ }+ return out as TParams;+ },+ };+}+export const POLICY_OPERATIONS = {redact: describeToolOperation("/api/v1/security/auto-redact",@@ -74,6 +118,48 @@ export const POLICY_OPERATIONS = {compressOperationConfig,),classify: describeAiToolOperation("/api/v1/ai/tools/classify-and-label"),+ purviewApplyLabel: describeIntegrationOperation(+ "/api/v1/integration/purview-apply-label",+ { connectionId: "", labelId: "", labelName: "", method: "STANDARD" },+ ),+ purviewReadLabel: describeIntegrationOperation(+ "/api/v1/integration/purview-read-label",+ { connectionId: "" },+ ),+ externalApiCall: describeIntegrationOperation(+ "/api/v1/integration/external-api-call",+ {+ connectionId: "",+ path: "",+ method: "POST",+ // multipart | json | binary — how the document reaches the API.+ bodyMode: "multipart",+ fileFieldName: "file",+ // Default to leaving the document alone; `replace` opts in to the response becoming it.+ responseMode: "report",+ // For `replace`, where the document actually is: inline (leave both blank), behind a URL in+ // the response body / a header, and/or inside a returned archive.+ resultUrlPath: "",+ resultUrlHeader: "",+ responseSelect: "",+ // A dotted path into the JSON response that must be true, or the step fails: the scan gate.+ requireTrue: "",+ // JSON objects whose values may reference {{document.*}}, {{classification.*}},+ // {{sensitivityLabel.*}} and {{run.*}}.+ fields: "",+ headers: "",+ // A vendor-shaped JSON body; wins over bodyMode/fields when set. {{document.base64}}+ // carries the file, for APIs that nest it inside a JSON document.+ bodyTemplate: "",+ includeContext: "false",+ includeFile: "true",+ // Which catalogue entry the operator chose, and their answers to its fields. Persisted so a+ // saved step reopens on the same operation rather than back at the picker; JSON-encoded to+ // keep every step parameter a flat string, as `fields` and `headers` already are.+ operationId: "",+ operationValues: "",+ },+ ),} as const;export type PolicyToolId = keyof typeof POLICY_OPERATIONS;@@ -97,8 +183,8 @@ const TOOL_ID_BY_ENDPOINT = new Map<string, PolicyToolId>(POLICY_TOOL_IDS.map((id) => [POLICY_OPERATIONS[id].endpoint, id]),);-/** A policy step's endpoint: a standard {@link ToolEndpoint} or an {@link AiPolicyEndpoint}. */-export type PolicyEndpoint = ToolEndpoint | AiPolicyEndpoint;+/** A policy step's endpoint: a generated {@link ToolEndpoint} or one typed here. */+export type PolicyEndpoint = ToolEndpoint | UntypedPolicyEndpoint;export function policyEndpoint(toolId: PolicyToolId): PolicyEndpoint {return POLICY_OPERATIONS[toolId].endpoint;diff --git a/frontend/eslint.config.mjs b/frontend/eslint.config.mjsindex 9793c60ac8..76daf03315 100644--- a/frontend/eslint.config.mjs+++ b/frontend/eslint.config.mjs@@ -268,6 +268,17 @@ export default defineConfig("no-restricted-syntax": ["error", ...mantineComponentImportRestrictions],},},+ // TEMPORARY (same rationale as procurement above): the connection/operation catalogues render+ // bespoke preset tiles (tinted monogram + two-line text). Raw-<button> rule only; migrate later.+ {+ files: [+ "editor/src/portal/components/sources/ConnectionTypePicker.tsx",+ "editor/src/portal/components/policies/PolicyExternalApiConfig.tsx",+ ],+ rules: {+ "no-restricted-syntax": ["error", ...mantineComponentImportRestrictions],+ },+ },// Stricter rules that not all sub-folders are conformant to yet.{files: srcGlobs,