Skip to content

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

Connect OneDrive, SharePoint and Google Drive accounts to pipelines (#8697)

Anthony Stirlingbbbbbd0d5543
diff --git a/AGENTS.md b/AGENTS.md
index 0adf8b15c1..efb31d8f1e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -507,6 +507,7 @@ Never sleep in tests (`page.waitForTimeout`, `Thread.sleep`, etc.) - it causes f
- **Backend**: Designed to be stateless - files are processed in memory/temp locations only
- **Frontend**: Uses IndexedDB for client-side file storage and caching (with thumbnails)
- **Security**: When `DOCKER_ENABLE_SECURITY=false`, security-related classes are excluded from compilation
+- **Fail Closed**: When a credential, owner, team or scope is missing or can't be resolved, refuse or use the narrowest option (the caller's own identity or personal scope). Never substitute a broader principal's credentials (the server's, an admin's or a service account's), treat an unknown caller as trusted, or widen scope. Open access (login disabled, desktop local mode, SaaS guests, share links) must come from explicit configuration or identity, never from a null or a failed request
- **Import Paths**: ALWAYS use `@editor/*` for imports - never use `@editor-core/*` or `@editor-proprietary/*` unless explicitly wrapping/extending a lower layer
- **FileContext**: All file operations MUST go through FileContext - never bypass with direct File handling
- **Memory Management**: Manual cleanup required for PDF.js documents and blob URLs - don't remove cleanup code
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index a7b110491c..7e3f7bcaba 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
@@ -15,6 +15,7 @@ import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import java.util.UUID;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -1885,6 +1886,7 @@ public class ApplicationProperties {
private boolean database;
private CustomMetadata customMetadata = new CustomMetadata();
private GoogleDrive googleDrive = new GoogleDrive();
+ private Microsoft microsoft = new Microsoft();
@Data
public static class GoogleDrive {
@@ -1892,6 +1894,42 @@ public class ApplicationProperties {
private String clientId = "";
private String apiKey = "";
private String appId = "";
+ @ToString.Exclude private String clientSecret = "";
+ private boolean allowAccountConnections = true;
+ private String accountScope = "drive";
+
+ private static final Set<String> ACCOUNT_SCOPES =
+ Set.of("drive", "drive.file", "drive.readonly");
+
+ public boolean accountConnectionsReady() {
+ return enabled
+ && allowAccountConnections
+ && !clientId.isBlank()
+ && !clientSecret.isBlank()
+ && validAccountScope() != null;
+ }
+
+ /** The trimmed {@code accountScope}, or null when it is not a Drive scope. */
+ public String validAccountScope() {
+ String scope = accountScope == null ? "" : accountScope.trim();
+ return ACCOUNT_SCOPES.contains(scope) ? scope : null;
+ }
+ }
+
+ @Data
+ public static class Microsoft {
+ private boolean enabled = false;
+ private String clientId = "";
+ private String tenant = "common";
+ @ToString.Exclude private String clientSecret = "";
+ private boolean allowAccountConnections = true;
+
+ public boolean accountConnectionsReady() {
+ return enabled
+ && allowAccountConnections
+ && !clientId.isBlank()
+ && !clientSecret.isBlank();
+ }
}
@Data
diff --git a/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java b/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java
index c3c4757acf..154a494ce8 100644
--- a/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/RequestUriUtils.java
@@ -215,6 +215,7 @@ public class RequestUriUtils {
// The phone that scans the QR code has no credentials
|| MOBILE_SCANNER_PHONE_PATTERN.matcher(trimmedUri).matches()
|| trimmedUri.startsWith("/api/v1/webhooks/")
+ || trimmedUri.startsWith("/api/v1/connected-accounts/callback/")
|| trimmedUri.startsWith("/v1/api-docs")
// Workflow participant endpoints - access controlled by share tokens, not login
|| trimmedUri.startsWith("/api/v1/workflow/participant/")
diff --git a/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java b/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java
index 5756ed5632..3f9b707ba8 100644
--- a/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/RequestUriUtilsTest.java
@@ -212,6 +212,12 @@ class RequestUriUtilsTest {
void testIsPublicAuthEndpoint_webhookReceiver() {
// The webhook source receiver authenticates each delivery by HMAC signature, not a session.
assertTrue(RequestUriUtils.isPublicAuthEndpoint("/api/v1/webhooks/whk_abc123", ""));
+ assertTrue(
+ RequestUriUtils.isPublicAuthEndpoint(
+ "/api/v1/connected-accounts/callback/microsoft", ""));
+ assertFalse(
+ RequestUriUtils.isPublicAuthEndpoint(
+ "/api/v1/connected-accounts/12/access-token", ""));
assertTrue(RequestUriUtils.isPublicAuthEndpoint("/app/api/v1/webhooks/whk_abc123", "/app"));
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
index 31e09834f4..4de84ea7a8 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
@@ -256,6 +256,15 @@ public class ConfigController {
boolean enableLogin =
applicationProperties.getSecurity().isEnableLogin() && userService != null;
configData.put("enableLogin", enableLogin);
+
+ configData.put(
+ "googleDriveAccountConnections",
+ enableLogin && googleDrive.accountConnectionsReady());
+ ApplicationProperties.Premium.ProFeatures.Microsoft microsoft =
+ applicationProperties.getPremium().getProFeatures().getMicrosoft();
+ configData.put(
+ "microsoftAccountConnections",
+ enableLogin && microsoft.accountConnectionsReady());
configData.put(
"honorOwnerPasswords",
applicationProperties.getSecurity().isHonorOwnerPasswords());
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index 63d337527e..483876b5cf 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -106,6 +106,15 @@ premium:
clientId: "" # Google OAuth 2.0 client ID (obtain from Google Cloud Console)
apiKey: "" # Google API key for Google Picker API (obtain from Google Cloud Console)
appId: "" # Google Drive app ID
+ clientSecret: "" # OAuth client secret; lets users connect their Google account so pipelines can use their Drive (redirect URI <server>/api/v1/connected-accounts/callback/google)
+ allowAccountConnections: true # set to 'false' to stop users connecting their own Google account
+ accountScope: drive # Drive scope requested when a user connects: 'drive' (every file) or 'drive.file' (only files they pick or Stirling creates)
+ microsoft:
+ enabled: false # Enable OneDrive and SharePoint (connected accounts, pipeline locations)
+ clientId: "" # Application (client) ID of the Microsoft Entra app registration
+ tenant: common # 'common' (work, school and personal accounts), 'organizations' (work and school only), or a tenant ID/domain to admit one organisation
+ clientSecret: "" # Client secret; needed for connected accounts (redirect URI <server>/api/v1/connected-accounts/callback/microsoft)
+ allowAccountConnections: true # set to 'false' to stop users connecting their own Microsoft account
enterpriseFeatures:
audit:
enabled: true # Enable audit logging for security and compliance tracking
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
index 25c36d3692..9ec80f4d45 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java
@@ -217,6 +217,24 @@ class ConfigControllerMoreTest {
assertThat(body).containsEntry("googleDriveApiKey", "key");
}
+ @Test
+ @DisplayName("gates Microsoft account connections and never exposes the secret")
+ void microsoftAccountConnections() {
+ ApplicationProperties.Premium.ProFeatures.Microsoft microsoft =
+ applicationProperties.getPremium().getProFeatures().getMicrosoft();
+ microsoft.setClientId("app-id");
+ microsoft.setClientSecret("server-only");
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ assertThat(bodyOf(newController().getAppConfig(request)))
+ .containsEntry("microsoftAccountConnections", false);
+
+ microsoft.setEnabled(true);
+ Map<String, Object> body = bodyOf(newController().getAppConfig(request));
+
+ assertThat(body).containsKey("microsoftAccountConnections");
+ assertThat(body.values()).doesNotContain("server-only");
+ }
+
@Test
@DisplayName("includes version/machine info beans when available")
void versionAndMachineBeans() {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/AccountReconnectRequiredException.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/AccountReconnectRequiredException.java
new file mode 100644
index 0000000000..74dc913247
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/AccountReconnectRequiredException.java
@@ -0,0 +1,12 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.IOException;
+
+public class AccountReconnectRequiredException extends IOException {
+
+ private static final long serialVersionUID = 1L;
+
+ public AccountReconnectRequiredException(String message) {
+ super(message);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/CloudOAuthClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/CloudOAuthClient.java
new file mode 100644
index 0000000000..19985681db
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/CloudOAuthClient.java
@@ -0,0 +1,20 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.IOException;
+import java.util.List;
+
+public interface CloudOAuthClient {
+
+ CloudProvider provider();
+
+ boolean available();
+
+ String authorizationUrl(String state, String codeChallenge, String redirectUri);
+
+ OAuthTokens exchangeCode(String code, String codeVerifier, String redirectUri)
+ throws IOException;
+
+ OAuthTokens refresh(String refreshToken, List<String> scopes) throws IOException;
+
+ void revoke(String refreshToken);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/CloudProvider.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/CloudProvider.java
new file mode 100644
index 0000000000..5288cbb7c1
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/CloudProvider.java
@@ -0,0 +1,31 @@
+package stirling.software.proprietary.connectedaccount;
+
+public enum CloudProvider {
+ MICROSOFT("microsoft", "Microsoft"),
+ GOOGLE("google", "Google");
+
+ private final String id;
+ private final String displayName;
+
+ CloudProvider(String id, String displayName) {
+ this.id = id;
+ this.displayName = displayName;
+ }
+
+ public String id() {
+ return id;
+ }
+
+ public String displayName() {
+ return displayName;
+ }
+
+ public static CloudProvider fromId(String id) {
+ for (CloudProvider provider : values()) {
+ if (provider.id.equalsIgnoreCase(id)) {
+ return provider;
+ }
+ }
+ throw new IllegalArgumentException("unknown provider '" + id + "'");
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccount.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccount.java
new file mode 100644
index 0000000000..59ffcec2b5
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccount.java
@@ -0,0 +1,90 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+import org.hibernate.annotations.CreationTimestamp;
+import org.hibernate.annotations.UpdateTimestamp;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Convert;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Index;
+import jakarta.persistence.Table;
+import jakarta.persistence.UniqueConstraint;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+import stirling.software.proprietary.integration.crypto.EncryptedStringConverter;
+
+@Entity
+@Table(
+ name = "connected_accounts",
+ indexes = @Index(name = "idx_connected_accounts_owner", columnList = "owner_user_id"),
+ uniqueConstraints =
+ @UniqueConstraint(
+ name = "uk_connected_accounts_identity",
+ columnNames = {"owner_user_id", "provider", "external_id"}))
+@NoArgsConstructor
+@Getter
+@Setter
+public class ConnectedAccount implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public static final String STATUS_CONNECTED = "CONNECTED";
+ public static final String STATUS_NEEDS_RECONNECT = "NEEDS_RECONNECT";
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "connected_account_id")
+ private Long id;
+
+ @Column(name = "owner_user_id", nullable = false)
+ private Long ownerUserId;
+
+ @Column(name = "provider", nullable = false, length = 32)
+ private String provider;
+
+ @Column(name = "external_id", nullable = false)
+ private String externalId;
+
+ @Column(name = "tenant_id")
+ private String tenantId;
+
+ @Column(name = "email")
+ private String email;
+
+ @Column(name = "display_name")
+ private String displayName;
+
+ @Convert(converter = EncryptedStringConverter.class)
+ @Column(name = "refresh_token_encrypted", columnDefinition = "text")
+ private String refreshToken;
+
+ @Column(name = "granted_scopes", columnDefinition = "text")
+ private String grantedScopes;
+
+ @Column(name = "status", nullable = false, length = 32)
+ private String status = STATUS_CONNECTED;
+
+ @Column(name = "last_error", columnDefinition = "text")
+ private String lastError;
+
+ @CreationTimestamp
+ @Column(name = "created_at", updatable = false)
+ private LocalDateTime createdAt;
+
+ @UpdateTimestamp
+ @Column(name = "updated_at")
+ private LocalDateTime updatedAt;
+
+ public CloudProvider cloudProvider() {
+ return CloudProvider.fromId(provider);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountAccess.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountAccess.java
new file mode 100644
index 0000000000..2911539590
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountAccess.java
@@ -0,0 +1,58 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.util.Map;
+
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.integration.service.ConnectionLookup;
+import stirling.software.proprietary.security.model.User;
+
+@Service
+@RequiredArgsConstructor
+public class ConnectedAccountAccess {
+
+ public static final String ACCOUNT_OPTION = "accountId";
+
+ private final ConnectedAccountService service;
+ private final ConnectionLookup connections;
+
+ public static boolean usesAccount(Map<String, Object> options) {
+ Object value = options.get(ACCOUNT_OPTION);
+ return value != null && !value.toString().isBlank();
+ }
+
+ public ConnectedAccount require(
+ Map<String, Object> options, CloudProvider provider, String owner) {
+ long id;
+ try {
+ id = Long.parseLong(options.get(ACCOUNT_OPTION).toString().trim());
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException("'accountId' is not a valid account reference");
+ }
+ if (!service.isAvailable(provider)) {
+ throw new IllegalArgumentException(
+ "connecting your own "
+ + provider.id()
+ + " account is turned off on this server; use an organisation"
+ + " connection");
+ }
+ User actingUser = connections.actingUser(owner);
+ if (actingUser == null) {
+ throw new IllegalArgumentException(
+ "a connected "
+ + provider.id()
+ + " account can only be used by a pipeline with a known owner");
+ }
+ return service.find(id)
+ .filter(account -> account.getProvider().equals(provider.id()))
+ .filter(account -> account.getOwnerUserId().equals(actingUser.getId()))
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ "choose one of your own connected "
+ + provider.id()
+ + " accounts"));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountController.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountController.java
new file mode 100644
index 0000000000..2f10793c50
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountController.java
@@ -0,0 +1,259 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseCookie;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.core.annotation.AuthenticationPrincipal;
+import org.springframework.web.bind.annotation.CookieValue;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+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.server.ResponseStatusException;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+
+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.proprietary.security.model.User;
+
+@Slf4j
+@RestController
+@RequestMapping("/api/v1/connected-accounts")
+@RequiredArgsConstructor
+@Tag(name = "Connected accounts", description = "Users' own OneDrive, SharePoint and Google Drive")
+public class ConnectedAccountController {
+
+ static final String CALLBACK_PATH = "/api/v1/connected-accounts/callback/";
+ private static final String NONCE_COOKIE = "stirling_connect_nonce";
+ private static final String CONNECT_FAILED = "The account could not be connected.";
+ private static final String PERSONAL_MICROSOFT_TENANT = "9188040d-6c67-4c5b-b112-36a304b66dad";
+
+ private final ConnectedAccountService service;
+ private final ApplicationProperties applicationProperties;
+
+ @GetMapping
+ public ConnectedAccountsResponse list(@AuthenticationPrincipal User user) {
+ requireUser(user);
+ return new ConnectedAccountsResponse(
+ Arrays.stream(CloudProvider.values())
+ .collect(Collectors.toMap(CloudProvider::id, service::isAvailable)),
+ service.list(user).stream().map(ConnectedAccountController::view).toList());
+ }
+
+ @PostMapping("/{provider}/connect")
+ public ResponseEntity<Map<String, String>> connect(
+ @PathVariable String provider, @AuthenticationPrincipal User user) {
+ requireUser(user);
+ CloudProvider cloud = provider(provider);
+ if (!service.isAvailable(cloud)) {
+ throw new ResponseStatusException(
+ HttpStatus.CONFLICT,
+ cloud.displayName() + " account connections are not set up on this server.");
+ }
+ String base = publicBaseUrl();
+ ConnectedAccountService.ConnectStart start =
+ service.startConnect(user, cloud, callbackUri(base, cloud));
+ ResponseCookie cookie =
+ ResponseCookie.from(NONCE_COOKIE, start.nonce())
+ .httpOnly(true)
+ .secure(base.startsWith("https"))
+ .sameSite("Lax")
+ .path("/")
+ .maxAge(ConnectedAccountService.STATE_LIFETIME)
+ .build();
+ return ResponseEntity.ok()
+ .header(HttpHeaders.SET_COOKIE, cookie.toString())
+ .body(Map.of("authorizationUrl", start.authorizationUrl()));
+ }
+
+ @GetMapping("/redirect-uris")
+ public Map<String, String> redirectUris(@AuthenticationPrincipal User user) {
+ requireUser(user);
+ String base = publicBaseUrl();
+ return Arrays.stream(CloudProvider.values())
+ .collect(Collectors.toMap(CloudProvider::id, cloud -> callbackUri(base, cloud)));
+ }
+
+ @GetMapping(value = "/callback/{provider}", produces = MediaType.TEXT_HTML_VALUE)
+ public ResponseEntity<String> callback(
+ @PathVariable String provider,
+ @RequestParam(required = false) String code,
+ @RequestParam(required = false) String state,
+ @RequestParam(required = false) String error,
+ @RequestParam(name = "error_description", required = false) String errorDescription,
+ @CookieValue(name = NONCE_COOKIE, required = false) String nonce) {
+ ResponseCookie clearNonce =
+ ResponseCookie.from(NONCE_COOKIE, "").path("/").maxAge(Duration.ZERO).build();
+ String providerId = "unknown";
+ String status;
+ String message;
+ try {
+ CloudProvider cloud = provider(provider);
+ providerId = cloud.id();
+ if (error != null) {
+ status = "access_denied".equals(error) ? "cancelled" : "error";
+ message =
+ "cancelled".equals(status)
+ ? "Sign-in was cancelled."
+ : "The provider refused the sign-in.";
+ log.info(
+ "{} sign-in refused: {} {}",
+ providerId,
+ forLog(error),
+ forLog(errorDescription));
+ } else if (code == null || state == null) {
+ status = "error";
+ message = "The sign-in response was incomplete.";
+ } else {
+ ConnectedAccount account = service.completeConnect(cloud, state, code, nonce);
+ status = "connected";
+ message = "Connected " + (account.getEmail() == null ? "" : account.getEmail());
+ }
+ } catch (IllegalArgumentException | IllegalStateException | IOException e) {
+ log.warn("Connecting a {} account failed: {}", providerId, forLog(e.getMessage()));
+ status = "error";
+ message = CONNECT_FAILED;
+ } catch (ResponseStatusException e) {
+ status = "error";
+ message = CONNECT_FAILED;
+ }
+ return ResponseEntity.ok()
+ .header(HttpHeaders.SET_COOKIE, clearNonce.toString())
+ .header(HttpHeaders.CACHE_CONTROL, "no-store")
+ .contentType(MediaType.TEXT_HTML)
+ .body(
+ callbackPage(
+ providerId,
+ status,
+ message,
+ publicBaseUrl() + "/settings/connectedAccounts"));
+ }
+
+ @DeleteMapping("/{id}")
+ public ResponseEntity<Void> disconnect(
+ @PathVariable long id, @AuthenticationPrincipal User user) {
+ requireUser(user);
+ try {
+ service.disconnect(user, id);
+ } catch (IllegalArgumentException e) {
+ throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
+ }
+ return ResponseEntity.noContent().build();
+ }
+
+ private String publicBaseUrl() {
+ String configured = applicationProperties.getSystem().getFrontendUrl();
+ if (configured != null && !configured.isBlank()) {
+ return configured.endsWith("/")
+ ? configured.substring(0, configured.length() - 1)
+ : configured;
+ }
+ return ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();
+ }
+
+ private static String callbackUri(String base, CloudProvider cloud) {
+ return base + CALLBACK_PATH + cloud.id();
+ }
+
+ private static String forLog(String value) {
+ return value == null ? "" : value.replaceAll("[\\r\\n\\t]", "_");
+ }
+
+ private static CloudProvider provider(String id) {
+ try {
+ return CloudProvider.fromId(id);
+ } catch (IllegalArgumentException e) {
+ throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
+ }
+ }
+
+ private static void requireUser(User user) {
+ if (user == null) {
+ throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
+ }
+ }
+
+ static AccountView view(ConnectedAccount account) {
+ return new AccountView(
+ account.getId(),
+ account.getProvider(),
+ account.getEmail(),
+ account.getDisplayName(),
+ account.getStatus(),
+ PERSONAL_MICROSOFT_TENANT.equals(account.getTenantId()),
+ account.getLastError(),
+ account.getCreatedAt());
+ }
+
+ static String callbackPage(String provider, String status, String message, String returnUrl) {
+ String safeMessage = escape(message == null ? "" : message);
+ String payload =
+ "{\"source\":\"stirling-connected-account\",\"provider\":\""
+ + jsString(provider)
+ + "\",\"status\":\""
+ + jsString(status)
+ + "\"}";
+ String heading =
+ "connected".equals(status)
+ ? "Account connected"
+ : "cancelled".equals(status) ? "Sign-in cancelled" : "Couldn't connect";
+ return "<!doctype html><html><head><meta charset=\"utf-8\"><title>"
+ + heading
+ + "</title><meta name=\"viewport\" content=\"width=device-width\"></head>"
+ + "<body style=\"font-family:system-ui,sans-serif;padding:32px\"><h1"
+ + " style=\"font-size:20px\">"
+ + heading
+ + "</h1><p>"
+ + safeMessage
+ + "</p><p><a href=\""
+ + escape(returnUrl)
+ + "\">Back to Stirling</a></p><script>(function(){try{if(window.opener){"
+ + "window.opener.postMessage("
+ + payload
+ + ",'*');"
+ + ("connected".equals(status) ? "setTimeout(function(){window.close();},400);" : "")
+ + "}}catch(e){}})();</script></body></html>";
+ }
+
+ private static String escape(String text) {
+ return text.replace("&", "&amp;")
+ .replace("<", "&lt;")
+ .replace(">", "&gt;")
+ .replace("\"", "&quot;")
+ .replace("'", "&#39;");
+ }
+
+ private static String jsString(String text) {
+ return text.replaceAll("[^a-z_]", "");
+ }
+
+ public record ConnectedAccountsResponse(
+ Map<String, Boolean> providers, List<AccountView> accounts) {}
+
+ public record AccountView(
+ Long id,
+ String provider,
+ String email,
+ String displayName,
+ String status,
+ boolean personal,
+ String lastError,
+ LocalDateTime createdAt) {}
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountRepository.java
new file mode 100644
index 0000000000..26d21210b2
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountRepository.java
@@ -0,0 +1,16 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.util.List;
+import java.util.Optional;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface ConnectedAccountRepository extends JpaRepository<ConnectedAccount, Long> {
+
+ List<ConnectedAccount> findByOwnerUserIdOrderByCreatedAtAsc(Long ownerUserId);
+
+ Optional<ConnectedAccount> findByOwnerUserIdAndProviderAndExternalId(
+ Long ownerUserId, String provider, String externalId);
+
+ void deleteByOwnerUserId(Long ownerUserId);
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountService.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountService.java
new file mode 100644
index 0000000000..9288fe1744
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/ConnectedAccountService.java
@@ -0,0 +1,286 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.integration.crypto.CredentialEncryption;
+import stirling.software.proprietary.policy.remote.ExpiringTokenCache;
+import stirling.software.proprietary.security.model.User;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+@Slf4j
+@Service
+public class ConnectedAccountService {
+
+ static final Duration STATE_LIFETIME = Duration.ofMinutes(10);
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final SecureRandom RANDOM = new SecureRandom();
+
+ private final ConnectedAccountRepository accounts;
+ private final Map<CloudProvider, CloudOAuthClient> clients = new EnumMap<>(CloudProvider.class);
+ private final ExpiringTokenCache accessCache = new ExpiringTokenCache(Duration.ofMinutes(2));
+ private final Map<Long, Object> refreshLocks = new ConcurrentHashMap<>();
+
+ public ConnectedAccountService(
+ ConnectedAccountRepository accounts, List<CloudOAuthClient> clients) {
+ this.accounts = accounts;
+ for (CloudOAuthClient client : clients) {
+ this.clients.put(client.provider(), client);
+ }
+ }
+
+ public boolean isAvailable(CloudProvider provider) {
+ CloudOAuthClient client = clients.get(provider);
+ return client != null && client.available();
+ }
+
+ public ConnectStart startConnect(User user, CloudProvider provider, String redirectUri) {
+ CloudOAuthClient client = requireAvailable(provider);
+ String verifier = randomToken();
+ String nonce = randomToken();
+ ObjectNode state = JSON.createObjectNode();
+ state.put("n", nonce);
+ state.put("u", user.getId());
+ state.put("p", provider.id());
+ state.put("v", verifier);
+ state.put("r", redirectUri);
+ state.put("e", Instant.now().plus(STATE_LIFETIME).getEpochSecond());
+ String sealed =
+ Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(
+ CredentialEncryption.encryptBytes(
+ state.toString().getBytes(StandardCharsets.UTF_8)));
+ return new ConnectStart(
+ client.authorizationUrl(sealed, challenge(verifier), redirectUri), nonce);
+ }
+
+ public record ConnectStart(String authorizationUrl, String nonce) {}
+
+ public ConnectedAccount completeConnect(
+ CloudProvider provider, String sealedState, String code, String browserNonce)
+ throws IOException {
+ JsonNode state = openState(sealedState);
+ if (browserNonce == null
+ || !MessageDigest.isEqual(
+ browserNonce.getBytes(StandardCharsets.UTF_8),
+ state.path("n").asString().getBytes(StandardCharsets.UTF_8))) {
+ throw new IllegalArgumentException(
+ "this sign-in was started in another browser; start it again from Stirling");
+ }
+ if (!provider.id().equals(state.path("p").asString())) {
+ throw new IllegalArgumentException("sign-in response is for a different provider");
+ }
+ if (Instant.now().getEpochSecond() > state.path("e").asLong()) {
+ throw new IllegalArgumentException("sign-in took too long; please try again");
+ }
+ CloudOAuthClient client = requireAvailable(provider);
+ OAuthTokens tokens =
+ client.exchangeCode(code, state.path("v").asString(), state.path("r").asString());
+ if (tokens.refreshToken() == null) {
+ throw new IOException(
+ "the provider did not grant offline access, so pipelines could not use it");
+ }
+ long userId = state.path("u").asLong();
+ OAuthTokens.AccountIdentity identity = tokens.identity();
+ ConnectedAccount account =
+ accounts.findByOwnerUserIdAndProviderAndExternalId(
+ userId, provider.id(), identity.externalId())
+ .orElseGet(ConnectedAccount::new);
+ account.setOwnerUserId(userId);
+ account.setProvider(provider.id());
+ account.setExternalId(identity.externalId());
+ account.setTenantId(identity.tenantId());
+ account.setEmail(identity.email());
+ account.setDisplayName(identity.displayName());
+ account.setRefreshToken(tokens.refreshToken());
+ account.setGrantedScopes(tokens.scope());
+ account.setStatus(ConnectedAccount.STATUS_CONNECTED);
+ account.setLastError(null);
+ ConnectedAccount saved = accounts.save(account);
+ evict(saved.getId());
+ cache(saved.getId(), List.of(), tokens);
+ return saved;
+ }
+
+ public List<ConnectedAccount> list(User user) {
+ return accounts.findByOwnerUserIdOrderByCreatedAtAsc(user.getId());
+ }
+
+ public Optional<ConnectedAccount> findOwned(User user, long accountId) {
+ return accounts.findById(accountId)
+ .filter(account -> account.getOwnerUserId().equals(user.getId()));
+ }
+
+ public Optional<ConnectedAccount> find(long accountId) {
+ return accounts.findById(accountId);
+ }
+
+ public void disconnect(User user, long accountId) {
+ ConnectedAccount account =
+ findOwned(user, accountId)
+ .orElseThrow(() -> new IllegalArgumentException("no such account"));
+ revoke(account);
+ accounts.delete(account);
+ evict(accountId);
+ }
+
+ public void removeAllFor(long userId) {
+ List<ConnectedAccount> owned = accounts.findByOwnerUserIdOrderByCreatedAtAsc(userId);
+ if (owned.isEmpty()) {
+ return;
+ }
+ accounts.deleteByOwnerUserId(userId);
+ owned.forEach(account -> evict(account.getId()));
+ Runnable afterDelete =
+ () ->
+ owned.forEach(
+ account -> {
+ evict(account.getId());
+ revoke(account);
+ });
+ if (!TransactionSynchronizationManager.isSynchronizationActive()) {
+ afterDelete.run();
+ return;
+ }
+ TransactionSynchronizationManager.registerSynchronization(
+ new TransactionSynchronization() {
+ @Override
+ public void afterCommit() {
+ afterDelete.run();
+ }
+ });
+ }
+
+ private void revoke(ConnectedAccount account) {
+ CloudOAuthClient client = clients.get(account.cloudProvider());
+ if (client != null && account.getRefreshToken() != null) {
+ client.revoke(account.getRefreshToken());
+ }
+ }
+
+ public String accessToken(long accountId, List<String> scopes) throws IOException {
+ String key = cacheKey(accountId, scopes);
+ String cached = accessCache.peek(key);
+ if (cached != null) {
+ return cached;
+ }
+ synchronized (refreshLocks.computeIfAbsent(accountId, id -> new Object())) {
+ cached = accessCache.peek(key);
+ if (cached != null) {
+ return cached;
+ }
+ ConnectedAccount account =
+ accounts.findById(accountId)
+ .orElseThrow(
+ () ->
+ new AccountReconnectRequiredException(
+ "the connected account was removed"));
+ if (!ConnectedAccount.STATUS_CONNECTED.equals(account.getStatus())) {
+ throw new AccountReconnectRequiredException(reconnectMessage(account));
+ }
+ CloudOAuthClient client = clients.get(account.cloudProvider());
+ if (client == null || !client.available()) {
+ throw new IOException(
+ account.cloudProvider().id()
+ + " account connections are turned off on this server");
+ }
+ OAuthTokens tokens;
+ try {
+ tokens = client.refresh(account.getRefreshToken(), scopes);
+ } catch (OAuthException e) {
+ if (e.isRevoked()) {
+ account.setStatus(ConnectedAccount.STATUS_NEEDS_RECONNECT);
+ account.setLastError(e.getMessage());
+ accounts.save(account);
+ evict(accountId);
+ throw new AccountReconnectRequiredException(reconnectMessage(account));
+ }
+ throw e;
+ }
+ if (tokens.refreshToken() != null
+ && !tokens.refreshToken().equals(account.getRefreshToken())) {
+ account.setRefreshToken(tokens.refreshToken());
+ accounts.save(account);
+ }
+ return cache(accountId, scopes, tokens);
+ }
+ }
+
+ private String cache(long accountId, List<String> scopes, OAuthTokens tokens) {
+ return accessCache.put(
+ cacheKey(accountId, scopes),
+ new ExpiringTokenCache.Token(tokens.accessToken(), tokens.expiresInSeconds()));
+ }
+
+ private void evict(long accountId) {
+ String prefix = accountId + "|";
+ accessCache.evictIf(key -> key.startsWith(prefix));
+ }
+
+ private static String cacheKey(long accountId, List<String> scopes) {
+ return accountId + "|" + (scopes == null ? "" : String.join(" ", scopes));
+ }
+
+ private static String reconnectMessage(ConnectedAccount account) {
+ String who = account.getEmail() == null ? "the connected account" : account.getEmail();
+ return "Stirling can no longer use "
+ + who
+ + "; sign in again from Settings > Connected accounts";
+ }
+
+ private CloudOAuthClient requireAvailable(CloudProvider provider) {
+ CloudOAuthClient client = clients.get(provider);
+ if (client == null || !client.available()) {
+ throw new IllegalStateException(
+ provider.id() + " account connections are not set up on this server");
+ }
+ return client;
+ }
+
+ private static JsonNode openState(String sealed) {
+ try {
+ byte[] plain = CredentialEncryption.decryptBytes(Base64.getUrlDecoder().decode(sealed));
+ return JSON.readTree(new String(plain, StandardCharsets.UTF_8));
+ } catch (RuntimeException e) {
+ throw new IllegalArgumentException("sign-in response could not be verified");
+ }
+ }
+
+ private static String randomToken() {
+ byte[] bytes = new byte[32];
+ RANDOM.nextBytes(bytes);
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
+ }
+
+ private static String challenge(String verifier) {
+ try {
+ byte[] digest =
+ MessageDigest.getInstance("SHA-256")
+ .digest(verifier.getBytes(StandardCharsets.US_ASCII));
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 unavailable", e);
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClient.java
new file mode 100644
index 0000000000..d969391193
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClient.java
@@ -0,0 +1,127 @@
+package stirling.software.proprietary.connectedaccount;
+
+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.time.Duration;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.google.GoogleEndpoints;
+
+import tools.jackson.databind.JsonNode;
+
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class GoogleOAuthClient implements CloudOAuthClient {
+
+ private static final HttpClient HTTP =
+ HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
+
+ private final ApplicationProperties applicationProperties;
+ private final GoogleEndpoints endpoints;
+
+ @Override
+ public CloudProvider provider() {
+ return CloudProvider.GOOGLE;
+ }
+
+ @Override
+ public boolean available() {
+ return app().accountConnectionsReady();
+ }
+
+ @Override
+ public String authorizationUrl(String state, String codeChallenge, String redirectUri) {
+ Map<String, String> query = new LinkedHashMap<>();
+ query.put("client_id", app().getClientId());
+ query.put("response_type", "code");
+ query.put("redirect_uri", redirectUri);
+ query.put("scope", "openid email profile " + driveScope());
+ query.put("access_type", "offline");
+ query.put("prompt", "consent");
+ query.put("include_granted_scopes", "true");
+ query.put("state", state);
+ query.put("code_challenge", codeChallenge);
+ query.put("code_challenge_method", "S256");
+ return endpoints.authorizeUrl() + "?" + OAuthHttp.form(query);
+ }
+
+ @Override
+ public OAuthTokens exchangeCode(String code, String codeVerifier, String redirectUri)
+ throws IOException {
+ JsonNode body =
+ OAuthHttp.postTokenRequest(
+ endpoints.tokenUrl(),
+ OAuthHttp.authorizationCodeGrant(
+ app().getClientId(),
+ app().getClientSecret(),
+ code,
+ codeVerifier,
+ redirectUri));
+ JsonNode claims = OAuthHttp.idTokenClaims(OAuthHttp.text(body, "id_token"));
+ String subject = OAuthHttp.text(claims, "sub");
+ if (subject == null) {
+ throw new IOException("Google returned no account identity");
+ }
+ return OAuthHttp.tokens(
+ body,
+ new OAuthTokens.AccountIdentity(
+ subject,
+ null,
+ OAuthHttp.text(claims, "email"),
+ OAuthHttp.text(claims, "name")));
+ }
+
+ @Override
+ public OAuthTokens refresh(String refreshToken, List<String> scopes) throws IOException {
+ return OAuthHttp.tokens(
+ OAuthHttp.postTokenRequest(
+ endpoints.tokenUrl(),
+ OAuthHttp.refreshGrant(
+ app().getClientId(), app().getClientSecret(), refreshToken)),
+ null);
+ }
+
+ @Override
+ public void revoke(String refreshToken) {
+ try {
+ HTTP.send(
+ HttpRequest.newBuilder(URI.create(endpoints.revokeUrl()))
+ .timeout(Duration.ofSeconds(10))
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .POST(
+ HttpRequest.BodyPublishers.ofString(
+ OAuthHttp.form(Map.of("token", refreshToken))))
+ .build(),
+ HttpResponse.BodyHandlers.discarding());
+ } catch (IOException e) {
+ log.debug("Google token revocation failed: {}", e.getMessage());
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ String driveScope() {
+ String scope = app().validAccountScope();
+ if (scope == null) {
+ throw new IllegalStateException(
+ "googleDrive.accountScope must be drive, drive.file or drive.readonly");
+ }
+ return "https://www.googleapis.com/auth/" + scope;
+ }
+
+ private ApplicationProperties.Premium.ProFeatures.GoogleDrive app() {
+ return applicationProperties.getPremium().getProFeatures().getGoogleDrive();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/MicrosoftOAuthClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/MicrosoftOAuthClient.java
new file mode 100644
index 0000000000..d5e9b74ba5
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/MicrosoftOAuthClient.java
@@ -0,0 +1,113 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.microsoft.GraphEndpoints;
+
+import tools.jackson.databind.JsonNode;
+
+@Component
+@RequiredArgsConstructor
+public class MicrosoftOAuthClient implements CloudOAuthClient {
+
+ static final String DEFAULT_SCOPES = "offline_access User.Read Files.ReadWrite.All";
+
+ public static final String BROWSER_SCOPE = "Files.Read.All";
+
+ private static final String SIGN_IN_SCOPES =
+ "openid profile email " + DEFAULT_SCOPES + " " + BROWSER_SCOPE;
+
+ private final ApplicationProperties applicationProperties;
+ private final GraphEndpoints endpoints;
+
+ @Override
+ public CloudProvider provider() {
+ return CloudProvider.MICROSOFT;
+ }
+
+ @Override
+ public boolean available() {
+ return app().accountConnectionsReady();
+ }
+
+ @Override
+ public String authorizationUrl(String state, String codeChallenge, String redirectUri) {
+ Map<String, String> query = new LinkedHashMap<>();
+ query.put("client_id", app().getClientId());
+ query.put("response_type", "code");
+ query.put("response_mode", "query");
+ query.put("redirect_uri", redirectUri);
+ query.put("scope", SIGN_IN_SCOPES);
+ query.put("state", state);
+ query.put("code_challenge", codeChallenge);
+ query.put("code_challenge_method", "S256");
+ query.put("prompt", "select_account");
+ return endpoints.authorizeUrl(tenant()) + "?" + OAuthHttp.form(query);
+ }
+
+ @Override
+ public OAuthTokens exchangeCode(String code, String codeVerifier, String redirectUri)
+ throws IOException {
+ Map<String, String> form =
+ OAuthHttp.authorizationCodeGrant(
+ app().getClientId(),
+ app().getClientSecret(),
+ code,
+ codeVerifier,
+ redirectUri);
+ form.put("scope", SIGN_IN_SCOPES);
+ JsonNode body = OAuthHttp.postTokenRequest(endpoints.tokenUrl(tenant()), form);
+ JsonNode claims = OAuthHttp.idTokenClaims(OAuthHttp.text(body, "id_token"));
+ String objectId = OAuthHttp.text(claims, "oid");
+ if (objectId == null) {
+ objectId = OAuthHttp.text(claims, "sub");
+ }
+ if (objectId == null) {
+ throw new IOException("Microsoft returned no account identity");
+ }
+ String email = OAuthHttp.text(claims, "preferred_username");
+ if (email == null) {
+ email = OAuthHttp.text(claims, "email");
+ }
+ return OAuthHttp.tokens(
+ body,
+ new OAuthTokens.AccountIdentity(
+ objectId,
+ OAuthHttp.text(claims, "tid"),
+ email,
+ OAuthHttp.text(claims, "name")));
+ }
+
+ @Override
+ public OAuthTokens refresh(String refreshToken, List<String> scopes) throws IOException {
+ Map<String, String> form =
+ OAuthHttp.refreshGrant(app().getClientId(), app().getClientSecret(), refreshToken);
+ form.put(
+ "scope",
+ scopes == null || scopes.isEmpty()
+ ? DEFAULT_SCOPES
+ : "offline_access " + String.join(" ", scopes));
+ return OAuthHttp.tokens(
+ OAuthHttp.postTokenRequest(endpoints.tokenUrl(tenant()), form), null);
+ }
+
+ @Override
+ public void revoke(String refreshToken) {}
+
+ private String tenant() {
+ String tenant = app().getTenant();
+ return tenant == null || tenant.isBlank() ? "common" : tenant.trim();
+ }
+
+ private ApplicationProperties.Premium.ProFeatures.Microsoft app() {
+ return applicationProperties.getPremium().getProFeatures().getMicrosoft();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthException.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthException.java
new file mode 100644
index 0000000000..2de866beba
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthException.java
@@ -0,0 +1,19 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.IOException;
+
+public class OAuthException extends IOException {
+
+ private static final long serialVersionUID = 1L;
+
+ private final boolean revoked;
+
+ public OAuthException(String message, boolean revoked) {
+ super(message);
+ this.revoked = revoked;
+ }
+
+ public boolean isRevoked() {
+ return revoked;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthHttp.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthHttp.java
new file mode 100644
index 0000000000..dd234076df
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthHttp.java
@@ -0,0 +1,148 @@
+package stirling.software.proprietary.connectedaccount;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URLEncoder;
+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 java.util.stream.Collectors;
+
+import stirling.software.proprietary.policy.remote.CloudHttp;
+import stirling.software.proprietary.policy.remote.ExpiringTokenCache;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+
+public final class OAuthHttp {
+
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final HttpClient HTTP =
+ HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(20)).build();
+
+ private OAuthHttp() {}
+
+ public static String form(Map<String, String> fields) {
+ return fields.entrySet().stream()
+ .filter(e -> e.getValue() != null)
+ .map(e -> encode(e.getKey()) + "=" + encode(e.getValue()))
+ .collect(Collectors.joining("&"));
+ }
+
+ public static String encode(String value) {
+ return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
+ }
+
+ public static Map<String, String> authorizationCodeGrant(
+ String clientId,
+ String clientSecret,
+ String code,
+ String codeVerifier,
+ String redirectUri) {
+ Map<String, String> form = clientGrant(clientId, clientSecret, "authorization_code");
+ form.put("code", code);
+ form.put("code_verifier", codeVerifier);
+ form.put("redirect_uri", redirectUri);
+ return form;
+ }
+
+ public static Map<String, String> refreshGrant(
+ String clientId, String clientSecret, String refreshToken) {
+ Map<String, String> form = clientGrant(clientId, clientSecret, "refresh_token");
+ form.put("refresh_token", refreshToken);
+ return form;
+ }
+
+ private static Map<String, String> clientGrant(
+ String clientId, String clientSecret, String grantType) {
+ Map<String, String> form = new LinkedHashMap<>();
+ form.put("client_id", clientId);
+ form.put("client_secret", clientSecret);
+ form.put("grant_type", grantType);
+ return form;
+ }
+
+ public static JsonNode postTokenRequest(String url, Map<String, String> fields)
+ throws IOException {
+ HttpRequest request =
+ HttpRequest.newBuilder(URI.create(url))
+ .timeout(Duration.ofSeconds(30))
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .header("Accept", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(form(fields)))
+ .build();
+ HttpResponse<String> response;
+ try {
+ response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException("Interrupted calling the sign-in service", e);
+ } catch (IOException e) {
+ throw new IOException(
+ "Could not reach the sign-in service ("
+ + (e.getMessage() == null
+ ? e.getClass().getSimpleName()
+ : e.getMessage())
+ + ")",
+ e);
+ }
+ JsonNode body = parse(response.body());
+ if (response.statusCode() >= 200
+ && response.statusCode() < 300
+ && body.hasNonNull("access_token")) {
+ return body;
+ }
+ String error = text(body, "error");
+ String description = text(body, "error_description");
+ String detail = description != null ? firstLine(description) : error;
+ throw new OAuthException(
+ "sign-in refused: " + (detail == null ? "HTTP " + response.statusCode() : detail),
+ "invalid_grant".equals(error));
+ }
+
+ public static JsonNode idTokenClaims(String idToken) {
+ if (idToken == null) {
+ return JSON.createObjectNode();
+ }
+ String[] parts = idToken.split("\\.");
+ if (parts.length < 2) {
+ return JSON.createObjectNode();
+ }
+ return parse(new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8));
+ }
+
+ public static String text(JsonNode node, String field) {
+ return CloudHttp.text(node, field);
+ }
+
+ public static OAuthTokens tokens(JsonNode body, OAuthTokens.AccountIdentity identity) {
+ return new OAuthTokens(
+ text(body, "access_token"),
+ text(body, "refresh_token"),
+ expiresInSeconds(body),
+ text(body, "scope"),
+ identity);
+ }
+
+ public static ExpiringTokenCache.Token accessToken(JsonNode body) {
+ return new ExpiringTokenCache.Token(text(body, "access_token"), expiresInSeconds(body));
+ }
+
+ private static long expiresInSeconds(JsonNode body) {
+ return body.hasNonNull("expires_in") ? body.get("expires_in").asLong() : 3599;
+ }
+
+ private static JsonNode parse(String body) {
+ return CloudHttp.parse(body);
+ }
+
+ private static String firstLine(String text) {
+ int newline = text.indexOf('\n');
+ return (newline < 0 ? text : text.substring(0, newline)).trim();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthTokens.java b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthTokens.java
new file mode 100644
index 0000000000..cd198e0c51
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/connectedaccount/OAuthTokens.java
@@ -0,0 +1,12 @@
+package stirling.software.proprietary.connectedaccount;
+
+public record OAuthTokens(
+ String accessToken,
+ String refreshToken,
+ long expiresInSeconds,
+ String scope,
+ AccountIdentity identity) {
+
+ public record AccountIdentity(
+ String externalId, String tenantId, String email, String displayName) {}
+}
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.java
index 74b7c652ae..4bc4a1d99f 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
@@ -12,5 +12,7 @@ public enum IntegrationType {
PURVIEW,
/** ConsignO Cloud (Notarius) e-signature and notarization. */
CONSIGNO,
- VECTOR_DB
+ VECTOR_DB,
+ MICROSOFT_365,
+ GOOGLE_WORKSPACE
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/repository/IntegrationTypeColumnWidening.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/repository/IntegrationTypeColumnWidening.java
new file mode 100644
index 0000000000..69d0c1dae1
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/repository/IntegrationTypeColumnWidening.java
@@ -0,0 +1,93 @@
+package stirling.software.proprietary.integration.repository;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.sql.DataSource;
+
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.beans.factory.SmartInitializingSingleton;
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class IntegrationTypeColumnWidening implements SmartInitializingSingleton {
+
+ private final ObjectProvider<DataSource> dataSource;
+
+ @Override
+ public void afterSingletonsInstantiated() {
+ DataSource source = dataSource.getIfAvailable();
+ if (source == null) {
+ return;
+ }
+ try (Connection connection = source.getConnection()) {
+ String product = connection.getMetaData().getDatabaseProductName();
+ if (product.startsWith("H2")) {
+ widenH2Enum(connection);
+ } else if (product.startsWith("PostgreSQL")) {
+ dropPostgresCheck(connection);
+ }
+ } catch (SQLException e) {
+ log.warn(
+ "Could not widen integration_configs.integration_type; connection types added"
+ + " since this database was created may fail to save: {}",
+ e.getMessage());
+ }
+ }
+
+ private static void widenH2Enum(Connection connection) throws SQLException {
+ String type;
+ try (PreparedStatement query =
+ connection.prepareStatement(
+ "SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE"
+ + " TABLE_NAME = 'INTEGRATION_CONFIGS' AND COLUMN_NAME ="
+ + " 'INTEGRATION_TYPE'")) {
+ try (ResultSet rows = query.executeQuery()) {
+ type = rows.next() ? rows.getString(1) : null;
+ }
+ }
+ if (!"ENUM".equalsIgnoreCase(type)) {
+ return;
+ }
+ try (Statement alter = connection.createStatement()) {
+ alter.execute(
+ "ALTER TABLE INTEGRATION_CONFIGS ALTER COLUMN INTEGRATION_TYPE SET DATA TYPE"
+ + " VARCHAR(32)");
+ }
+ log.info("Widened integration_configs.integration_type from ENUM to VARCHAR(32)");
+ }
+
+ private static void dropPostgresCheck(Connection connection) throws SQLException {
+ List<String> constraints = new ArrayList<>();
+ try (PreparedStatement query =
+ connection.prepareStatement(
+ "SELECT con.conname FROM pg_constraint con WHERE con.conrelid ="
+ + " to_regclass('integration_configs') AND con.contype = 'c' AND"
+ + " pg_get_constraintdef(con.oid) LIKE '%integration_type%'")) {
+ try (ResultSet rows = query.executeQuery()) {
+ while (rows.next()) {
+ constraints.add(rows.getString(1));
+ }
+ }
+ }
+ for (String name : constraints) {
+ try (Statement alter = connection.createStatement()) {
+ alter.execute(
+ "ALTER TABLE integration_configs DROP CONSTRAINT \""
+ + name.replace("\"", "\"\"")
+ + "\"");
+ }
+ log.info("Dropped integration_configs CHECK constraint {}", name);
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/ConnectionLookup.java b/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/ConnectionLookup.java
new file mode 100644
index 0000000000..1aae54ddba
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/integration/service/ConnectionLookup.java
@@ -0,0 +1,128 @@
+package stirling.software.proprietary.integration.service;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+
+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;
+
+@Service
+@RequiredArgsConstructor
+@Transactional(readOnly = true)
+public class ConnectionLookup {
+
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ private final IntegrationConfigRepository connections;
+ private final OwnershipService ownership;
+ private final UserService userService;
+
+ public Map<String, Object> load(
+ Map<String, Object> options,
+ IntegrationType type,
+ String label,
+ Set<String> perUseKeys,
+ String pipelineOwner) {
+ User acting = actingUser(pipelineOwner);
+
+ long connectionId = connectionId(options, label);
+ IntegrationConfig connection =
+ connections
+ .findById(connectionId)
+ .filter(cfg -> cfg.getIntegrationType() == type)
+ .filter(cfg -> usableBy(acting, cfg))
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ "unknown or inaccessible "
+ + label
+ + " connection"));
+ if (!connection.isEnabled()) {
+ throw new IllegalArgumentException(label + " connection is disabled");
+ }
+ Map<String, Object> merged = new LinkedHashMap<>(config(connection, label));
+ for (String key : perUseKeys) {
+ Object value = options.get(key);
+ if (value != null && !value.toString().isBlank()) {
+ merged.put(key, value);
+ }
+ }
+ return merged;
+ }
+
+ public User actingUser(String pipelineOwner) {
+ return pipelineOwner != null
+ ? userService.findByUsername(pipelineOwner).orElse(null)
+ : currentUser();
+ }
+
+ 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 boolean usableBy(User user, IntegrationConfig connection) {
+ return user != null && ownership.canUse(ResourceType.INTEGRATION_CONFIG, connection, user);
+ }
+
+ private static long connectionId(Map<String, Object> options, String label) {
+ Object reference = options.get("connectionId");
+ if (reference == null || reference.toString().isBlank()) {
+ throw new IllegalArgumentException(
+ "choose your connected account or a " + label + " connection");
+ }
+ if (reference instanceof Number number) {
+ return number.longValue();
+ }
+ try {
+ return Long.parseLong(reference.toString().trim());
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(
+ "'connectionId' is not a valid connection reference: " + reference);
+ }
+ }
+
+ private static Map<String, Object> config(IntegrationConfig connection, String label) {
+ 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(
+ label + " connection '" + connection.getName() + "' has unreadable config", e);
+ }
+ }
+}
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.java
index 0674009864..93beddd66a 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
@@ -154,7 +154,9 @@ public class IntegrationConfigService {
private static boolean isInfrastructureType(IntegrationType type) {
return type == IntegrationType.S3
|| type == IntegrationType.NETWORK
- || type == IntegrationType.VECTOR_DB;
+ || type == IntegrationType.VECTOR_DB
+ || type == IntegrationType.MICROSOFT_365
+ || type == IntegrationType.GOOGLE_WORKSPACE;
}
/** Whether this caller may author custom API integrations, for the UI to offer or hide it. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
index 295905362a..337e89e3b2 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/engine/PolicyEngine.java
@@ -219,7 +219,8 @@ public class PolicyEngine {
sourceId,
fileIdentity,
triggeringUser,
- fileOwner);
+ fileOwner,
+ billingPrincipal);
String message = "Policy run could not start: " + e.getMessage();
run.fail(message);
taskManager.setError(run.getRunId(), message);
@@ -252,7 +253,13 @@ public class PolicyEngine {
Semaphore admission) {
PolicyRun run =
registerRun(
- policyId, definition, sourceId, fileIdentity, triggeringUser, fileOwner);
+ policyId,
+ definition,
+ sourceId,
+ fileIdentity,
+ triggeringUser,
+ fileOwner,
+ billingPrincipal);
String runId = run.getRunId();
CompletableFuture<PolicyRun> completion = new CompletableFuture<>();
PolicyProgressListener tracking = trackingListener(runId, run, listener);
@@ -314,7 +321,8 @@ public class PolicyEngine {
String sourceId,
String fileIdentity,
String triggeringUser,
- String fileOwner) {
+ String fileOwner,
+ String pipelineOwner) {
String runId =
jobOwnershipService.createScopedJobKey(UUID.randomUUID().toString(), fileOwner);
taskManager.createTask(runId);
@@ -330,7 +338,8 @@ public class PolicyEngine {
sourceId,
fileIdentity,
triggeringUser,
- fileOwner);
+ fileOwner,
+ pipelineOwner);
taskManager.putMetadata(runId, "externalOutput", String.valueOf(run.externalOutput()));
registry.register(run);
return run;
@@ -579,7 +588,13 @@ public class PolicyEngine {
PolicyRun run, String runId, PolicyInputs inputs, List<Resource> files)
throws IOException {
OutputDelivery delivery =
- new OutputDelivery(runId, run.getPolicyId(), inputs, JobContext.getOwner());
+ new OutputDelivery(
+ runId,
+ run.getPolicyId(),
+ inputs,
+ JobContext.getOwner(),
+ null,
+ run.getPipelineOwner());
List<OutputSpec> fallback = run.getDefinition().outputs();
if (fallback.isEmpty()) {
// No destinations means inline delivery (results returned to the caller), preserving
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleCloudDrive.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleCloudDrive.java
new file mode 100644
index 0000000000..7a0ebf8b39
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleCloudDrive.java
@@ -0,0 +1,106 @@
+package stirling.software.proprietary.policy.google;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.policy.remote.CloudDrive;
+import stirling.software.proprietary.policy.remote.ContentHasher;
+
+@Component
+@RequiredArgsConstructor
+public class GoogleCloudDrive implements CloudDrive<GoogleDriveConfig, GoogleFile> {
+
+ private final GoogleConnectionResolver resolver;
+ private final GoogleDriveClient drive;
+
+ @Override
+ public Set<String> types() {
+ return Set.of(GoogleDriveInputSource.TYPE);
+ }
+
+ @Override
+ public GoogleDriveConfig resolve(String type, Map<String, Object> options, String owner) {
+ return resolver.resolve(options, owner);
+ }
+
+ @Override
+ public void checkReadable(GoogleDriveConfig location) throws IOException {
+ drive.folderId(location);
+ }
+
+ @Override
+ public void checkWritable(GoogleDriveConfig location) throws IOException {
+ drive.folderId(location);
+ }
+
+ @Override
+ public List<GoogleFile> list(GoogleDriveConfig location) throws IOException {
+ return drive.list(location);
+ }
+
+ @Override
+ public Optional<GoogleFile> stat(GoogleDriveConfig location, GoogleFile file)
+ throws IOException {
+ return drive.stat(location, file);
+ }
+
+ @Override
+ public InputStream open(GoogleDriveConfig location, GoogleFile file) throws IOException {
+ return drive.open(location, file);
+ }
+
+ @Override
+ public boolean remove(GoogleDriveConfig location, GoogleFile file) throws IOException {
+ drive.trash(location, file);
+ return true;
+ }
+
+ @Override
+ public String outputIdentity(GoogleDriveConfig location, String name) throws IOException {
+ return GoogleFile.identity(drive.folderId(location), name);
+ }
+
+ @Override
+ public ContentHasher newHasher() {
+ MessageDigest md5;
+ try {
+ md5 = MessageDigest.getInstance("MD5");
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("MD5 unavailable", e);
+ }
+ return new ContentHasher() {
+ @Override
+ public void update(byte[] bytes, int offset, int length) {
+ md5.update(bytes, offset, length);
+ }
+
+ @Override
+ public String gate() {
+ return GoogleFile.gate(HexFormat.of().formatHex(md5.digest()), null);
+ }
+ };
+ }
+
+ @Override
+ public Optional<GoogleFile> upload(GoogleDriveConfig location, String name, Path content)
+ throws IOException {
+ return drive.upload(location, drive.folderId(location), name, content);
+ }
+
+ @Override
+ public String label() {
+ return "Google Drive";
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleConnectionResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleConnectionResolver.java
new file mode 100644
index 0000000000..fbbe4b1940
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleConnectionResolver.java
@@ -0,0 +1,36 @@
+package stirling.software.proprietary.policy.google;
+
+import java.util.Map;
+
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.connectedaccount.CloudProvider;
+import stirling.software.proprietary.connectedaccount.ConnectedAccount;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountAccess;
+import stirling.software.proprietary.integration.model.IntegrationType;
+import stirling.software.proprietary.integration.service.ConnectionLookup;
+import stirling.software.proprietary.policy.remote.LocationOptions;
+
+@Service
+@RequiredArgsConstructor
+public class GoogleConnectionResolver {
+
+ private final ConnectionLookup connections;
+ private final ConnectedAccountAccess accountAccess;
+
+ public GoogleDriveConfig resolve(Map<String, Object> options, String owner) {
+ if (ConnectedAccountAccess.usesAccount(options)) {
+ ConnectedAccount account = accountAccess.require(options, CloudProvider.GOOGLE, owner);
+ return GoogleDriveConfig.forAccount(account.getId(), options);
+ }
+ return GoogleDriveConfig.fromConnection(
+ connections.load(
+ options,
+ IntegrationType.GOOGLE_WORKSPACE,
+ "Google Workspace",
+ LocationOptions.PER_USE_KEYS,
+ owner));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveClient.java
new file mode 100644
index 0000000000..38cb14d5f2
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveClient.java
@@ -0,0 +1,419 @@
+package stirling.software.proprietary.policy.google;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+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.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import stirling.software.proprietary.connectedaccount.OAuthHttp;
+import stirling.software.proprietary.policy.remote.CloudDrive;
+import stirling.software.proprietary.policy.remote.CloudHttp;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+@Component
+public class GoogleDriveClient {
+
+ static final long SIMPLE_UPLOAD_LIMIT = 5L * 1024 * 1024;
+ static final int UPLOAD_CHUNK = 256 * 1024 * 32;
+
+ static final String FOLDER_MIME = "application/vnd.google-apps.folder";
+ private static final String NATIVE_PREFIX = "application/vnd.google-apps.";
+ private static final String FILE_FIELDS = "id,name,mimeType,size,md5Checksum,version,parents";
+
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ private final GoogleEndpoints endpoints;
+ private final GoogleTokenProvider tokens;
+ private final HttpClient http;
+ private final Map<String, String> folderIds = new ConcurrentHashMap<>();
+
+ @Autowired
+ public GoogleDriveClient(GoogleEndpoints endpoints, GoogleTokenProvider tokens) {
+ this(endpoints, tokens, CloudHttp.newClient());
+ }
+
+ GoogleDriveClient(GoogleEndpoints endpoints, GoogleTokenProvider tokens, HttpClient http) {
+ this.endpoints = endpoints;
+ this.tokens = tokens;
+ this.http = http;
+ }
+
+ public String folderId(GoogleDriveConfig config) throws IOException {
+ String cached = folderIds.get(config.location());
+ if (cached != null) {
+ return cached;
+ }
+ String id = config.folderId();
+ if (id == null) {
+ id = "root";
+ for (String segment :
+ config.folder().isEmpty() ? new String[0] : config.folder().split("/")) {
+ id = childFolder(config, id, segment);
+ }
+ }
+ JsonNode folder =
+ getJson(
+ config,
+ "/files/"
+ + OAuthHttp.encode(id)
+ + "?fields=id,mimeType,trashed&supportsAllDrives=true",
+ "open the folder");
+ if (!FOLDER_MIME.equals(text(folder, "mimeType"))) {
+ throw new IOException("That Drive item is not a folder");
+ }
+ if (folder.path("trashed").asBoolean(false)) {
+ throw new IOException("That Drive folder is in the bin");
+ }
+ String resolved = text(folder, "id");
+ folderIds.put(config.location(), resolved);
+ return resolved;
+ }
+
+ private String childFolder(GoogleDriveConfig config, String parentId, String name)
+ throws IOException {
+ JsonNode page =
+ getJson(
+ config,
+ "/files?q="
+ + OAuthHttp.encode(
+ "name = '"
+ + escapeQuery(name)
+ + "' and '"
+ + escapeQuery(parentId)
+ + "' in parents and mimeType = '"
+ + FOLDER_MIME
+ + "' and trashed = false")
+ + "&fields=files(id)&supportsAllDrives=true&includeItemsFromAllDrives=true",
+ "find folder '" + name + "'");
+ JsonNode files = page.path("files");
+ if (files.size() == 0) {
+ throw new IOException("No folder named '" + name + "' in Google Drive");
+ }
+ if (files.size() > 1) {
+ throw new IOException(
+ "More than one folder is named '"
+ + name
+ + "'; paste the folder's link instead");
+ }
+ return text(files.get(0), "id");
+ }
+
+ public List<GoogleFile> list(GoogleDriveConfig config) throws IOException {
+ List<GoogleFile> files = new ArrayList<>();
+ Deque<String> folders = new ArrayDeque<>();
+ folders.add(folderId(config));
+ while (!folders.isEmpty() && files.size() < CloudDrive.MAX_FILES) {
+ String folder = folders.removeFirst();
+ String pageToken = null;
+ do {
+ String url =
+ endpoints.driveUrl()
+ + "/files?q="
+ + OAuthHttp.encode(
+ "'"
+ + escapeQuery(folder)
+ + "' in parents and trashed = false")
+ + "&fields="
+ + OAuthHttp.encode("nextPageToken,files(" + FILE_FIELDS + ")")
+ + "&pageSize=1000&supportsAllDrives=true&includeItemsFromAllDrives=true"
+ + (pageToken == null
+ ? ""
+ : "&pageToken=" + OAuthHttp.encode(pageToken));
+ JsonNode page = getJsonAbsolute(config, url, "list the folder");
+ for (JsonNode item : page.path("files")) {
+ String name = text(item, "name");
+ String mime = text(item, "mimeType");
+ if (name == null || name.startsWith(".")) {
+ continue;
+ }
+ if (FOLDER_MIME.equals(mime)) {
+ if (config.recursive()) {
+ folders.add(text(item, "id"));
+ }
+ } else if (mime == null || !mime.startsWith(NATIVE_PREFIX)) {
+ files.add(toFile(folder, item));
+ if (files.size() >= CloudDrive.MAX_FILES) {
+ break;
+ }
+ }
+ }
+ pageToken = text(page, "nextPageToken");
+ } while (pageToken != null && files.size() < CloudDrive.MAX_FILES);
+ }
+ return files;
+ }
+
+ public Optional<GoogleFile> stat(GoogleDriveConfig config, GoogleFile file) throws IOException {
+ HttpResponse<String> response =
+ send(
+ authorized(
+ config,
+ endpoints.driveUrl()
+ + "/files/"
+ + OAuthHttp.encode(file.id())
+ + "?fields="
+ + OAuthHttp.encode(FILE_FIELDS + ",trashed")
+ + "&supportsAllDrives=true")
+ .GET()
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() == 404) {
+ return Optional.empty();
+ }
+ requireSuccess(response, "read " + file.name());
+ JsonNode item = parse(response.body());
+ if (item.path("trashed").asBoolean(false)) {
+ return Optional.empty();
+ }
+ return Optional.of(toFile(file.parentId(), item));
+ }
+
+ public InputStream open(GoogleDriveConfig config, GoogleFile file) throws IOException {
+ HttpResponse<InputStream> response =
+ send(
+ authorized(
+ config,
+ endpoints.driveUrl()
+ + "/files/"
+ + OAuthHttp.encode(file.id())
+ + "?alt=media&supportsAllDrives=true")
+ .GET()
+ .build(),
+ HttpResponse.BodyHandlers.ofInputStream());
+ return CloudHttp.download(http, response, file.name(), "Google Drive");
+ }
+
+ public void trash(GoogleDriveConfig config, GoogleFile file) throws IOException {
+ HttpResponse<String> response =
+ send(
+ authorized(
+ config,
+ endpoints.driveUrl()
+ + "/files/"
+ + OAuthHttp.encode(file.id())
+ + "?supportsAllDrives=true")
+ .header("Content-Type", "application/json")
+ .method(
+ "PATCH",
+ HttpRequest.BodyPublishers.ofString("{\"trashed\":true}"))
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() == 404) {
+ return;
+ }
+ requireSuccess(response, "move " + file.name() + " to the bin");
+ }
+
+ public Optional<GoogleFile> upload(
+ GoogleDriveConfig config, String folderId, String name, Path content)
+ throws IOException {
+ if (nameTaken(config, folderId, name)) {
+ return Optional.empty();
+ }
+ ObjectNode metadata = JSON.createObjectNode();
+ metadata.put("name", name);
+ metadata.putArray("parents").add(folderId);
+ long size = Files.size(content);
+ String query = "&supportsAllDrives=true&fields=" + OAuthHttp.encode(FILE_FIELDS);
+ if (size <= SIMPLE_UPLOAD_LIMIT) {
+ String boundary = "stirling-" + UUID.randomUUID();
+ ByteArrayOutputStream body = new ByteArrayOutputStream();
+ body.writeBytes(
+ ("--"
+ + boundary
+ + "\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n"
+ + metadata
+ + "\r\n--"
+ + boundary
+ + "\r\nContent-Type: application/octet-stream\r\n\r\n")
+ .getBytes(StandardCharsets.UTF_8));
+ body.writeBytes(Files.readAllBytes(content));
+ body.writeBytes(("\r\n--" + boundary + "--").getBytes(StandardCharsets.UTF_8));
+ HttpResponse<String> response =
+ send(
+ authorized(
+ config,
+ endpoints.uploadUrl()
+ + "/files?uploadType=multipart"
+ + query)
+ .header(
+ "Content-Type",
+ "multipart/related; boundary=" + boundary)
+ .POST(
+ HttpRequest.BodyPublishers.ofByteArray(
+ body.toByteArray()))
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ requireSuccess(response, "upload " + name);
+ return Optional.of(toFile(folderId, parse(response.body())));
+ }
+ return Optional.of(uploadResumable(config, folderId, name, metadata, content, size, query));
+ }
+
+ private GoogleFile uploadResumable(
+ GoogleDriveConfig config,
+ String folderId,
+ String name,
+ ObjectNode metadata,
+ Path content,
+ long size,
+ String query)
+ throws IOException {
+ HttpResponse<String> started =
+ send(
+ authorized(
+ config,
+ endpoints.uploadUrl()
+ + "/files?uploadType=resumable"
+ + query)
+ .header("Content-Type", "application/json; charset=UTF-8")
+ .header("X-Upload-Content-Length", String.valueOf(size))
+ .POST(HttpRequest.BodyPublishers.ofString(metadata.toString()))
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ requireSuccess(started, "start uploading " + name);
+ String session =
+ started.headers()
+ .firstValue("Location")
+ .orElseThrow(() -> new IOException("Google returned no upload session"));
+ byte[] buffer = new byte[(int) Math.min(UPLOAD_CHUNK, size)];
+ try (RandomAccessFile file = new RandomAccessFile(content.toFile(), "r")) {
+ long offset = 0;
+ while (offset < size) {
+ int length = (int) Math.min(buffer.length, size - offset);
+ file.readFully(buffer, 0, length);
+ HttpResponse<String> chunk =
+ send(
+ authorized(config, session)
+ .header(
+ "Content-Range",
+ "bytes "
+ + offset
+ + "-"
+ + (offset + length - 1)
+ + "/"
+ + size)
+ .PUT(
+ HttpRequest.BodyPublishers.ofByteArray(
+ buffer, 0, length))
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ offset += length;
+ if (chunk.statusCode() == 308) {
+ continue;
+ }
+ requireSuccess(chunk, "upload " + name);
+ return toFile(folderId, parse(chunk.body()));
+ }
+ }
+ throw new IOException("Upload of " + name + " ended without a completed file");
+ }
+
+ private boolean nameTaken(GoogleDriveConfig config, String folderId, String name)
+ throws IOException {
+ JsonNode page =
+ getJson(
+ config,
+ "/files?q="
+ + OAuthHttp.encode(
+ "name = '"
+ + escapeQuery(name)
+ + "' and '"
+ + escapeQuery(folderId)
+ + "' in parents and trashed = false")
+ + "&fields=files(id)&supportsAllDrives=true&includeItemsFromAllDrives=true",
+ "check for " + name);
+ return page.path("files").size() > 0;
+ }
+
+ private JsonNode getJson(GoogleDriveConfig config, String relativeUrl, String action)
+ throws IOException {
+ return getJsonAbsolute(config, endpoints.driveUrl() + relativeUrl, action);
+ }
+
+ private JsonNode getJsonAbsolute(GoogleDriveConfig config, String url, String action)
+ throws IOException {
+ HttpResponse<String> response =
+ send(authorized(config, url).GET().build(), HttpResponse.BodyHandlers.ofString());
+ requireSuccess(response, action);
+ return parse(response.body());
+ }
+
+ private HttpRequest.Builder authorized(GoogleDriveConfig config, String url)
+ throws IOException {
+ return HttpRequest.newBuilder(URI.create(url))
+ .timeout(Duration.ofMinutes(2))
+ .header("Authorization", "Bearer " + tokens.token(config))
+ .header("Accept", "application/json");
+ }
+
+ private <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> handler)
+ throws IOException {
+ return CloudHttp.send(http, request, handler, "Google Drive");
+ }
+
+ private static void requireSuccess(HttpResponse<String> response, String action)
+ throws IOException {
+ int status = response.statusCode();
+ if (status >= 200 && status < 300) {
+ return;
+ }
+ JsonNode error = parse(response.body()).path("error");
+ String message = text(error, "message");
+ StringBuilder detail =
+ new StringBuilder("Could not ").append(action).append(": HTTP ").append(status);
+ if (message != null) {
+ detail.append(" - ").append(message);
+ }
+ if (status == 401 || status == 403) {
+ detail.append(
+ " (check the account can open this folder, or that the service account has"
+ + " access)");
+ }
+ throw new IOException(detail.toString());
+ }
+
+ private static GoogleFile toFile(String parentId, JsonNode item) {
+ return new GoogleFile(
+ text(item, "id"),
+ parentId,
+ text(item, "name"),
+ item.path("size").asLong(0),
+ text(item, "md5Checksum"),
+ text(item, "version"));
+ }
+
+ static String escapeQuery(String value) {
+ return value.replace("\\", "\\\\").replace("'", "\\'");
+ }
+
+ private static JsonNode parse(String body) {
+ return CloudHttp.parse(body);
+ }
+
+ private static String text(JsonNode node, String field) {
+ return CloudHttp.text(node, field);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveConfig.java
new file mode 100644
index 0000000000..7453243f72
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveConfig.java
@@ -0,0 +1,147 @@
+package stirling.software.proprietary.policy.google;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import stirling.software.proprietary.policy.remote.CloudHttp;
+import stirling.software.proprietary.policy.remote.CloudLocation;
+import stirling.software.proprietary.policy.remote.LocationOptions;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+
+public record GoogleDriveConfig(
+ Credential credential, String folder, boolean snapshot, boolean recursive)
+ implements CloudLocation {
+
+ public sealed interface Credential permits AccountCredential, ServiceAccountCredential {}
+
+ public record AccountCredential(long accountId) implements Credential {}
+
+ public record ServiceAccountCredential(String clientEmail, String privateKeyPem, String subject)
+ implements Credential {
+ @Override
+ public String toString() {
+ return "ServiceAccountCredential[clientEmail="
+ + clientEmail
+ + ", subject="
+ + subject
+ + "]";
+ }
+ }
+
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final Pattern FOLDER_LINK = Pattern.compile("/folders/([A-Za-z0-9_-]+)");
+ private static final Pattern ID_QUERY = Pattern.compile("[?&]id=([A-Za-z0-9_-]+)");
+ private static final Pattern EMAIL = Pattern.compile("[^@\\s]+@[^@\\s]+");
+
+ public static GoogleDriveConfig forAccount(long accountId, Map<String, Object> options) {
+ return new GoogleDriveConfig(
+ new AccountCredential(accountId),
+ folder(options.get("directory")),
+ LocationOptions.snapshot(options),
+ LocationOptions.recursive(options));
+ }
+
+ public static GoogleDriveConfig fromConnection(Map<String, Object> options) {
+ return new GoogleDriveConfig(
+ serviceAccount(options),
+ folder(options.get("directory")),
+ LocationOptions.snapshot(options),
+ LocationOptions.recursive(options));
+ }
+
+ public static ServiceAccountCredential serviceAccount(Map<String, Object> options) {
+ String json = LocationOptions.trimmed(options.get("credentialsJson"));
+ if (json == null) {
+ throw new IllegalArgumentException(
+ "paste the service account's JSON key into 'credentialsJson'");
+ }
+ JsonNode key;
+ try {
+ key = JSON.readTree(json);
+ } catch (RuntimeException e) {
+ throw new IllegalArgumentException("the service account key is not valid JSON");
+ }
+ String clientEmail = text(key, "client_email");
+ String privateKey = text(key, "private_key");
+ if (clientEmail == null || privateKey == null || !privateKey.contains("PRIVATE KEY")) {
+ throw new IllegalArgumentException(
+ "the JSON key must be a service account key with client_email and private_key");
+ }
+ String subject = LocationOptions.trimmed(options.get("subject"));
+ if (subject != null && !EMAIL.matcher(subject).matches()) {
+ throw new IllegalArgumentException("'subject' must be the email of the user to act as");
+ }
+ return new ServiceAccountCredential(clientEmail, privateKey, subject);
+ }
+
+ /** The folder ID a pasted link names, or null when the folder is a path from My Drive. */
+ public String folderId() {
+ if (!folder.startsWith("https://")) {
+ return null;
+ }
+ Matcher link = FOLDER_LINK.matcher(folder);
+ if (link.find()) {
+ return link.group(1);
+ }
+ Matcher query = ID_QUERY.matcher(folder);
+ if (query.find()) {
+ return query.group(1);
+ }
+ throw new IllegalArgumentException(
+ "that link does not name a Drive folder; open the folder and copy its link");
+ }
+
+ public String location() {
+ String who =
+ switch (credential) {
+ case AccountCredential account -> "account:" + account.accountId();
+ case ServiceAccountCredential service ->
+ service.clientEmail()
+ + (service.subject() == null ? "" : " as " + service.subject());
+ };
+ return who + " folder:" + folder;
+ }
+
+ public GoogleDriveConfig withRecursive(boolean value) {
+ return new GoogleDriveConfig(credential, folder, snapshot, value);
+ }
+
+ private static String folder(Object value) {
+ String text = LocationOptions.trimmed(value);
+ if (text == null) {
+ return "";
+ }
+ if (text.regionMatches(true, 0, "https://", 0, 8)) {
+ try {
+ URI uri = new URI(text);
+ if (uri.getHost() == null || uri.getUserInfo() != null) {
+ throw new IllegalArgumentException("folder link is not a valid URL");
+ }
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("folder link is not a valid URL", e);
+ }
+ return text;
+ }
+ return LocationOptions.folderPath(text);
+ }
+
+ private static String text(JsonNode node, String field) {
+ return CloudHttp.text(node, field);
+ }
+
+ @Override
+ public String toString() {
+ return "GoogleDriveConfig[location="
+ + location()
+ + ", snapshot="
+ + snapshot
+ + ", recursive="
+ + recursive
+ + "]";
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveInputSource.java
new file mode 100644
index 0000000000..c937245be6
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleDriveInputSource.java
@@ -0,0 +1,15 @@
+package stirling.software.proprietary.policy.google;
+
+import org.springframework.stereotype.Service;
+
+import stirling.software.proprietary.policy.remote.CloudDriveInputSource;
+
+@Service
+public class GoogleDriveInputSource extends CloudDriveInputSource<GoogleDriveConfig, GoogleFile> {
+
+ public static final String TYPE = "googledrive";
+
+ public GoogleDriveInputSource(GoogleCloudDrive drive) {
+ super(drive);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleEndpoints.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleEndpoints.java
new file mode 100644
index 0000000000..4f8dbc0a95
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleEndpoints.java
@@ -0,0 +1,56 @@
+package stirling.software.proprietary.policy.google;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+@Component
+public class GoogleEndpoints {
+
+ private final String authorizeUrl;
+ private final String tokenUrl;
+ private final String revokeUrl;
+ private final String driveUrl;
+ private final String uploadUrl;
+
+ public GoogleEndpoints(
+ @Value("${stirling.google.authorize-url:https://accounts.google.com/o/oauth2/v2/auth}")
+ String authorizeUrl,
+ @Value("${stirling.google.token-url:https://oauth2.googleapis.com/token}")
+ String tokenUrl,
+ @Value("${stirling.google.revoke-url:https://oauth2.googleapis.com/revoke}")
+ String revokeUrl,
+ @Value("${stirling.google.drive-url:https://www.googleapis.com/drive/v3}")
+ String driveUrl,
+ @Value("${stirling.google.upload-url:https://www.googleapis.com/upload/drive/v3}")
+ String uploadUrl) {
+ this.authorizeUrl = authorizeUrl;
+ this.tokenUrl = tokenUrl;
+ this.revokeUrl = revokeUrl;
+ this.driveUrl = stripTrailingSlash(driveUrl);
+ this.uploadUrl = stripTrailingSlash(uploadUrl);
+ }
+
+ public String authorizeUrl() {
+ return authorizeUrl;
+ }
+
+ public String tokenUrl() {
+ return tokenUrl;
+ }
+
+ public String revokeUrl() {
+ return revokeUrl;
+ }
+
+ public String driveUrl() {
+ return driveUrl;
+ }
+
+ public String uploadUrl() {
+ return uploadUrl;
+ }
+
+ private static String stripTrailingSlash(String url) {
+ return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleFile.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleFile.java
new file mode 100644
index 0000000000..cc45d38378
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleFile.java
@@ -0,0 +1,34 @@
+package stirling.software.proprietary.policy.google;
+
+import stirling.software.proprietary.policy.remote.CloudFile;
+
+public record GoogleFile(
+ String id, String parentId, String name, long size, String md5, String revision)
+ implements CloudFile {
+
+ @Override
+ public String identity() {
+ return identity(parentId, name);
+ }
+
+ @Override
+ public String version() {
+ return gate(md5, revision);
+ }
+
+ @Override
+ public boolean hasContentHash() {
+ return md5 != null && !md5.isBlank();
+ }
+
+ public static String identity(String parentId, String name) {
+ return "gdrive://" + parentId + "/" + name;
+ }
+
+ public static String gate(String md5, String revision) {
+ if (md5 != null && !md5.isBlank()) {
+ return "md5:" + md5;
+ }
+ return "ver:" + (revision == null ? "" : revision);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleIntegrationValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleIntegrationValidator.java
new file mode 100644
index 0000000000..82255e5f81
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleIntegrationValidator.java
@@ -0,0 +1,22 @@
+package stirling.software.proprietary.policy.google;
+
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import stirling.software.proprietary.integration.model.IntegrationType;
+import stirling.software.proprietary.integration.service.IntegrationConfigValidator;
+
+@Component
+public class GoogleIntegrationValidator implements IntegrationConfigValidator {
+
+ @Override
+ public IntegrationType type() {
+ return IntegrationType.GOOGLE_WORKSPACE;
+ }
+
+ @Override
+ public void validate(Map<String, Object> config) {
+ GoogleDriveConfig.serviceAccount(config);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleTokenProvider.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleTokenProvider.java
new file mode 100644
index 0000000000..bb85bb9a94
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/google/GoogleTokenProvider.java
@@ -0,0 +1,107 @@
+package stirling.software.proprietary.policy.google;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.KeyFactory;
+import java.security.PrivateKey;
+import java.security.Signature;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
+import stirling.software.proprietary.connectedaccount.OAuthHttp;
+import stirling.software.proprietary.policy.remote.ExpiringTokenCache;
+
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ObjectNode;
+
+@Component
+@RequiredArgsConstructor
+public class GoogleTokenProvider {
+
+ static final String DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ private final GoogleEndpoints endpoints;
+ private final ConnectedAccountService connectedAccounts;
+ private final ExpiringTokenCache cache = new ExpiringTokenCache(Duration.ofMinutes(5));
+
+ public String token(GoogleDriveConfig config) throws IOException {
+ return switch (config.credential()) {
+ case GoogleDriveConfig.AccountCredential account ->
+ connectedAccounts.accessToken(account.accountId(), List.of());
+ case GoogleDriveConfig.ServiceAccountCredential service -> serviceToken(service);
+ };
+ }
+
+ private String serviceToken(GoogleDriveConfig.ServiceAccountCredential service)
+ throws IOException {
+ String key =
+ service.clientEmail()
+ + "|"
+ + service.subject()
+ + "|"
+ + Integer.toHexString(service.privateKeyPem().hashCode());
+ return cache.get(
+ key,
+ () -> {
+ Map<String, String> form = new LinkedHashMap<>();
+ form.put("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
+ form.put("assertion", assertion(service));
+ return OAuthHttp.accessToken(
+ OAuthHttp.postTokenRequest(endpoints.tokenUrl(), form));
+ });
+ }
+
+ String assertion(GoogleDriveConfig.ServiceAccountCredential service) throws IOException {
+ long now = Instant.now().getEpochSecond();
+ ObjectNode header = JSON.createObjectNode();
+ header.put("alg", "RS256");
+ header.put("typ", "JWT");
+ ObjectNode claims = JSON.createObjectNode();
+ claims.put("iss", service.clientEmail());
+ claims.put("scope", DRIVE_SCOPE);
+ claims.put("aud", endpoints.tokenUrl());
+ claims.put("iat", now);
+ claims.put("exp", now + 3600);
+ if (service.subject() != null) {
+ claims.put("sub", service.subject());
+ }
+ String signingInput = base64(header.toString()) + "." + base64(claims.toString());
+ try {
+ Signature signer = Signature.getInstance("SHA256withRSA");
+ signer.initSign(privateKey(service.privateKeyPem()));
+ signer.update(signingInput.getBytes(StandardCharsets.US_ASCII));
+ return signingInput
+ + "."
+ + Base64.getUrlEncoder().withoutPadding().encodeToString(signer.sign());
+ } catch (GeneralSecurityException | IllegalArgumentException e) {
+ throw new IOException("the service account's private key could not be used", e);
+ }
+ }
+
+ private static PrivateKey privateKey(String pem) throws GeneralSecurityException {
+ String body =
+ pem.replace("-----BEGIN PRIVATE KEY-----", "")
+ .replace("-----END PRIVATE KEY-----", "")
+ .replaceAll("\\s", "");
+ return KeyFactory.getInstance("RSA")
+ .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(body)));
+ }
+
+ private static String base64(String json) {
+ return Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(json.getBytes(StandardCharsets.UTF_8));
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/DriveFile.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/DriveFile.java
new file mode 100644
index 0000000000..6c909a1a76
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/DriveFile.java
@@ -0,0 +1,31 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import stirling.software.proprietary.policy.remote.CloudFile;
+
+public record DriveFile(
+ String driveId,
+ String root,
+ String itemId,
+ String path,
+ String name,
+ long size,
+ String eTag,
+ String quickXorHash,
+ String cTag)
+ implements CloudFile {
+
+ @Override
+ public String identity() {
+ return MicrosoftDriveIdentities.identity(driveId, root, path);
+ }
+
+ @Override
+ public String version() {
+ return MicrosoftDriveIdentities.gate(quickXorHash, cTag);
+ }
+
+ @Override
+ public boolean hasContentHash() {
+ return quickXorHash != null && !quickXorHash.isBlank();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/DriveRoot.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/DriveRoot.java
new file mode 100644
index 0000000000..f76f81af4d
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/DriveRoot.java
@@ -0,0 +1,8 @@
+package stirling.software.proprietary.policy.microsoft;
+
+public record DriveRoot(String driveId, String itemId) {
+
+ public String key() {
+ return itemId == null ? "root" : itemId;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphDriveClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphDriveClient.java
new file mode 100644
index 0000000000..1c445debd0
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphDriveClient.java
@@ -0,0 +1,489 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+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.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Deque;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.connectedaccount.OAuthHttp;
+import stirling.software.proprietary.policy.remote.CloudDrive;
+import stirling.software.proprietary.policy.remote.CloudHttp;
+
+import tools.jackson.databind.JsonNode;
+
+@Slf4j
+@Component
+public class GraphDriveClient {
+
+ static final long SIMPLE_UPLOAD_LIMIT = 4L * 1024 * 1024;
+ static final int UPLOAD_CHUNK = 320 * 1024 * 32;
+
+ private static final String ITEM_FIELDS = "id,name,size,file,folder,package,eTag,cTag";
+
+ private final GraphEndpoints endpoints;
+ private final GraphTokenProvider tokens;
+ private final HttpClient http;
+ private final Map<String, DriveRoot> roots = new ConcurrentHashMap<>();
+
+ @Autowired
+ public GraphDriveClient(GraphEndpoints endpoints, GraphTokenProvider tokens) {
+ this(endpoints, tokens, CloudHttp.newClient());
+ }
+
+ GraphDriveClient(GraphEndpoints endpoints, GraphTokenProvider tokens, HttpClient http) {
+ this.endpoints = endpoints;
+ this.tokens = tokens;
+ this.http = http;
+ }
+
+ public DriveRoot root(MicrosoftDriveConfig config) throws IOException {
+ String key = config.location();
+ DriveRoot cached = roots.get(key);
+ if (cached != null) {
+ return cached;
+ }
+ DriveRoot root;
+ if (config.folderLink() != null) {
+ root = linkedFolder(config);
+ } else if (config.credential() instanceof MicrosoftDriveConfig.AccountCredential) {
+ root =
+ new DriveRoot(
+ requireId(
+ getJson(config, "/me/drive?$select=id", "find your OneDrive"),
+ config),
+ null);
+ } else if (config.drive() == MicrosoftDrive.ONEDRIVE) {
+ root =
+ new DriveRoot(
+ requireId(
+ getJson(
+ config,
+ "/users/"
+ + segment(config.user())
+ + "/drive?$select=id",
+ "find the OneDrive of " + config.user()),
+ config),
+ null);
+ } else {
+ root = new DriveRoot(sharePointDriveId(config), null);
+ }
+ roots.put(key, root);
+ return root;
+ }
+
+ private DriveRoot linkedFolder(MicrosoftDriveConfig config) throws IOException {
+ String shareId =
+ "u!"
+ + Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(
+ config.folderLink().getBytes(StandardCharsets.UTF_8));
+ JsonNode item =
+ getJson(
+ config,
+ "/shares/" + shareId + "/driveItem?$select=id,name,folder,parentReference",
+ "open the folder link");
+ if (!item.has("folder")) {
+ throw new IOException("The link is to a file, not a folder");
+ }
+ String driveId = text(item.path("parentReference"), "driveId");
+ if (driveId == null || text(item, "id") == null) {
+ throw new IOException("Microsoft Graph could not resolve the folder link");
+ }
+ return new DriveRoot(driveId, text(item, "id"));
+ }
+
+ private static String requireId(JsonNode node, MicrosoftDriveConfig config) throws IOException {
+ String id = text(node, "id");
+ if (id == null) {
+ throw new IOException("Microsoft Graph returned no drive id for " + config.location());
+ }
+ return id;
+ }
+
+ public List<DriveFile> list(MicrosoftDriveConfig config) throws IOException {
+ DriveRoot root = root(config);
+ List<DriveFile> files = new ArrayList<>();
+ Deque<String> folders = new ArrayDeque<>();
+ folders.add(config.directory());
+ while (!folders.isEmpty() && files.size() < CloudDrive.MAX_FILES) {
+ String folder = folders.removeFirst();
+ String url =
+ endpoints.graphUrl()
+ + itemPath(root, folder)
+ + (folder.isEmpty() ? "/children" : ":/children")
+ + "?$select="
+ + ITEM_FIELDS
+ + "&$top=200";
+ while (url != null && files.size() < CloudDrive.MAX_FILES) {
+ JsonNode page = getJsonAbsolute(config, url, "list folder '" + folder + "'");
+ for (JsonNode item : page.path("value")) {
+ String name = text(item, "name");
+ if (name == null || name.startsWith(".")) {
+ continue;
+ }
+ String path = MicrosoftDriveIdentities.childPath(folder, name);
+ if (item.has("folder") && !item.has("package")) {
+ if (config.recursive()) {
+ folders.add(path);
+ }
+ } else if (item.has("file")) {
+ files.add(toFile(root.driveId(), root.key(), path, item));
+ if (files.size() >= CloudDrive.MAX_FILES) {
+ break;
+ }
+ }
+ }
+ url = nextLink(page);
+ }
+ }
+ return files;
+ }
+
+ public Optional<DriveFile> stat(MicrosoftDriveConfig config, DriveFile file)
+ throws IOException {
+ HttpResponse<String> response =
+ send(
+ authorized(
+ config,
+ endpoints.graphUrl()
+ + "/drives/"
+ + segment(file.driveId())
+ + "/items/"
+ + segment(file.itemId())
+ + "?$select="
+ + ITEM_FIELDS)
+ .GET()
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() == 404) {
+ return Optional.empty();
+ }
+ requireSuccess(response, "read " + file.path());
+ return Optional.of(
+ toFile(file.driveId(), file.root(), file.path(), parse(response.body())));
+ }
+
+ public InputStream open(MicrosoftDriveConfig config, DriveFile file) throws IOException {
+ HttpResponse<InputStream> response =
+ send(
+ authorized(
+ config,
+ endpoints.graphUrl()
+ + "/drives/"
+ + segment(file.driveId())
+ + "/items/"
+ + segment(file.itemId())
+ + "/content")
+ .GET()
+ .build(),
+ HttpResponse.BodyHandlers.ofInputStream());
+ return CloudHttp.download(http, response, file.path(), "Microsoft Graph");
+ }
+
+ public boolean delete(MicrosoftDriveConfig config, DriveFile file) throws IOException {
+ HttpRequest.Builder request =
+ authorized(
+ config,
+ endpoints.graphUrl()
+ + "/drives/"
+ + segment(file.driveId())
+ + "/items/"
+ + segment(file.itemId()))
+ .DELETE();
+ if (file.eTag() != null) {
+ request.header("If-Match", file.eTag());
+ }
+ HttpResponse<String> response = send(request.build(), HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() == 412) {
+ return false;
+ }
+ if (response.statusCode() == 404) {
+ return true;
+ }
+ requireSuccess(response, "delete " + file.path());
+ return true;
+ }
+
+ public Optional<DriveFile> upload(
+ MicrosoftDriveConfig config, String directory, String name, Path content)
+ throws IOException {
+ DriveRoot root = root(config);
+ String path = MicrosoftDriveIdentities.childPath(directory, name);
+ long size = Files.size(content);
+ if (size <= SIMPLE_UPLOAD_LIMIT) {
+ HttpResponse<String> response =
+ send(
+ authorized(
+ config,
+ endpoints.graphUrl()
+ + itemPath(root, path)
+ + ":/[email protected]=fail")
+ .header("Content-Type", "application/octet-stream")
+ .PUT(HttpRequest.BodyPublishers.ofFile(content))
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() == 409) {
+ return Optional.empty();
+ }
+ requireSuccess(response, "upload " + path);
+ return Optional.of(toFile(root.driveId(), root.key(), path, parse(response.body())));
+ }
+ return uploadInSession(config, root, path, content, size);
+ }
+
+ private Optional<DriveFile> uploadInSession(
+ MicrosoftDriveConfig config, DriveRoot root, String path, Path content, long size)
+ throws IOException {
+ HttpResponse<String> created =
+ send(
+ authorized(
+ config,
+ endpoints.graphUrl()
+ + itemPath(root, path)
+ + ":/createUploadSession")
+ .header("Content-Type", "application/json")
+ .POST(
+ HttpRequest.BodyPublishers.ofString(
+ "{\"item\":{\"@microsoft.graph.conflictBehavior\":\"fail\"}}"))
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ if (created.statusCode() == 409) {
+ return Optional.empty();
+ }
+ requireSuccess(created, "start uploading " + path);
+ String uploadUrl = text(parse(created.body()), "uploadUrl");
+ if (uploadUrl == null) {
+ throw new IOException("Microsoft Graph returned no upload URL for " + path);
+ }
+
+ byte[] buffer = new byte[(int) Math.min(UPLOAD_CHUNK, size)];
+ try (RandomAccessFile file = new RandomAccessFile(content.toFile(), "r")) {
+ long offset = 0;
+ while (offset < size) {
+ int length = (int) Math.min(buffer.length, size - offset);
+ file.readFully(buffer, 0, length);
+ HttpResponse<String> chunk =
+ send(
+ HttpRequest.newBuilder(URI.create(uploadUrl))
+ .timeout(Duration.ofMinutes(10))
+ .header(
+ "Content-Range",
+ "bytes "
+ + offset
+ + "-"
+ + (offset + length - 1)
+ + "/"
+ + size)
+ .PUT(
+ HttpRequest.BodyPublishers.ofByteArray(
+ buffer, 0, length))
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ offset += length;
+ if (chunk.statusCode() == 409) {
+ cancelSession(uploadUrl);
+ return Optional.empty();
+ }
+ if (chunk.statusCode() >= 300) {
+ cancelSession(uploadUrl);
+ requireSuccess(chunk, "upload " + path);
+ }
+ if (offset >= size) {
+ return Optional.of(
+ toFile(root.driveId(), root.key(), path, parse(chunk.body())));
+ }
+ }
+ }
+ throw new IOException("Upload of " + path + " ended without a completed item");
+ }
+
+ private void cancelSession(String uploadUrl) {
+ try {
+ send(
+ HttpRequest.newBuilder(URI.create(uploadUrl)).DELETE().build(),
+ HttpResponse.BodyHandlers.discarding());
+ } catch (IOException e) {
+ log.debug("Could not cancel upload session: {}", e.getMessage());
+ }
+ }
+
+ private String sharePointDriveId(MicrosoftDriveConfig config) throws IOException {
+ String site =
+ "/sites/"
+ + segment(config.siteHost())
+ + (config.sitePath().isEmpty()
+ ? ""
+ : ":/" + encodePath(config.sitePath()) + ":");
+ String siteId =
+ text(
+ getJson(
+ config,
+ site + "?$select=id",
+ "find SharePoint site " + config.location()),
+ "id");
+ if (siteId == null) {
+ throw new IOException("Microsoft Graph returned no site id for " + config.location());
+ }
+ if (config.library() == null) {
+ return text(
+ getJson(
+ config,
+ "/sites/" + segment(siteId) + "/drive?$select=id",
+ "find the default library of " + config.location()),
+ "id");
+ }
+ JsonNode drives =
+ getJson(
+ config,
+ "/sites/" + segment(siteId) + "/drives?$select=id,name",
+ "list libraries of " + config.location());
+ List<String> names = new ArrayList<>();
+ for (JsonNode drive : drives.path("value")) {
+ String name = text(drive, "name");
+ if (config.library().equalsIgnoreCase(name)) {
+ return text(drive, "id");
+ }
+ names.add(name);
+ }
+ throw new IOException(
+ "SharePoint site has no library named '"
+ + config.library()
+ + "' (found: "
+ + String.join(", ", names)
+ + ")");
+ }
+
+ private JsonNode getJson(MicrosoftDriveConfig config, String relativeUrl, String action)
+ throws IOException {
+ return getJsonAbsolute(config, endpoints.graphUrl() + relativeUrl, action);
+ }
+
+ private JsonNode getJsonAbsolute(MicrosoftDriveConfig config, String url, String action)
+ throws IOException {
+ HttpResponse<String> response =
+ send(authorized(config, url).GET().build(), HttpResponse.BodyHandlers.ofString());
+ requireSuccess(response, action);
+ return parse(response.body());
+ }
+
+ private String nextLink(JsonNode page) throws IOException {
+ String next = text(page, "@odata.nextLink");
+ if (next == null) {
+ return null;
+ }
+ URI graph = URI.create(endpoints.graphUrl());
+ URI link = URI.create(next);
+ if (!graph.getScheme().equalsIgnoreCase(link.getScheme())
+ || !graph.getAuthority().equalsIgnoreCase(link.getAuthority())) {
+ throw new IOException("Microsoft Graph paged to an unexpected host: " + link.getHost());
+ }
+ return next;
+ }
+
+ private HttpRequest.Builder authorized(MicrosoftDriveConfig config, String url)
+ throws IOException {
+ return HttpRequest.newBuilder(URI.create(url))
+ .timeout(Duration.ofMinutes(2))
+ .header("Authorization", "Bearer " + tokens.token(config))
+ .header("Accept", "application/json");
+ }
+
+ private <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> handler)
+ throws IOException {
+ return CloudHttp.send(http, request, handler, "Microsoft Graph");
+ }
+
+ private static void requireSuccess(HttpResponse<String> response, String action)
+ throws IOException {
+ int status = response.statusCode();
+ if (status >= 200 && status < 300) {
+ return;
+ }
+ JsonNode error = parse(response.body()).path("error");
+ String code = text(error, "code");
+ String message = text(error, "message");
+ StringBuilder detail =
+ new StringBuilder("Could not ").append(action).append(": HTTP ").append(status);
+ if (code != null) {
+ detail.append(' ').append(code);
+ }
+ if (message != null) {
+ detail.append(" - ").append(message);
+ }
+ if (status == 401 || status == 403) {
+ detail.append(
+ " (check the app registration's Microsoft Graph application permissions and"
+ + " that an administrator granted consent)");
+ }
+ throw new IOException(detail.toString());
+ }
+
+ private static DriveFile toFile(String driveId, String root, String path, JsonNode item) {
+ String name = text(item, "name");
+ return new DriveFile(
+ driveId,
+ root,
+ text(item, "id"),
+ path,
+ name == null ? path.substring(path.lastIndexOf('/') + 1) : name,
+ item.path("size").asLong(0),
+ text(item, "eTag"),
+ text(item.path("file").path("hashes"), "quickXorHash"),
+ text(item, "cTag"));
+ }
+
+ private String itemPath(DriveRoot root, String path) {
+ String base =
+ "/drives/"
+ + segment(root.driveId())
+ + (root.itemId() == null ? "/root" : "/items/" + segment(root.itemId()));
+ return path.isEmpty() ? base : base + ":/" + encodePath(path);
+ }
+
+ private static String encodePath(String path) {
+ StringBuilder out = new StringBuilder();
+ for (String part : path.split("/")) {
+ if (part.isEmpty()) {
+ continue;
+ }
+ if (!out.isEmpty()) {
+ out.append('/');
+ }
+ out.append(segment(part));
+ }
+ return out.toString();
+ }
+
+ private static String segment(String value) {
+ return OAuthHttp.encode(value);
+ }
+
+ private static JsonNode parse(String body) {
+ return CloudHttp.parse(body);
+ }
+
+ private static String text(JsonNode node, String field) {
+ return CloudHttp.text(node, field);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphEndpoints.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphEndpoints.java
new file mode 100644
index 0000000000..e565403bc6
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphEndpoints.java
@@ -0,0 +1,44 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.net.URI;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+@Component
+public class GraphEndpoints {
+
+ public static final String DEFAULT_GRAPH_URL = "https://graph.microsoft.com/v1.0";
+ public static final String DEFAULT_LOGIN_URL = "https://login.microsoftonline.com";
+
+ private final String graphUrl;
+ private final String loginUrl;
+
+ public GraphEndpoints(
+ @Value("${stirling.microsoft.graph-url:" + DEFAULT_GRAPH_URL + "}") String graphUrl,
+ @Value("${stirling.microsoft.login-url:" + DEFAULT_LOGIN_URL + "}") String loginUrl) {
+ this.graphUrl = stripTrailingSlash(graphUrl);
+ this.loginUrl = stripTrailingSlash(loginUrl);
+ }
+
+ public String graphUrl() {
+ return graphUrl;
+ }
+
+ public String tokenUrl(String tenantId) {
+ return loginUrl + "/" + tenantId + "/oauth2/v2.0/token";
+ }
+
+ public String authorizeUrl(String tenant) {
+ return loginUrl + "/" + tenant + "/oauth2/v2.0/authorize";
+ }
+
+ public String graphScope() {
+ URI uri = URI.create(graphUrl);
+ return uri.getScheme() + "://" + uri.getAuthority() + "/.default";
+ }
+
+ private static String stripTrailingSlash(String url) {
+ return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphTokenProvider.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphTokenProvider.java
new file mode 100644
index 0000000000..1a47b72c91
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/GraphTokenProvider.java
@@ -0,0 +1,62 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Duration;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
+import stirling.software.proprietary.connectedaccount.OAuthHttp;
+import stirling.software.proprietary.policy.remote.ExpiringTokenCache;
+
+@Component
+@RequiredArgsConstructor
+public class GraphTokenProvider {
+
+ private final GraphEndpoints endpoints;
+ private final ConnectedAccountService connectedAccounts;
+ private final ExpiringTokenCache cache = new ExpiringTokenCache(Duration.ofMinutes(5));
+
+ public String token(MicrosoftDriveConfig config) throws IOException {
+ return switch (config.credential()) {
+ case MicrosoftDriveConfig.AccountCredential account ->
+ connectedAccounts.accessToken(account.accountId(), List.of());
+ case MicrosoftDriveConfig.AppCredential app -> appToken(app);
+ };
+ }
+
+ private String appToken(MicrosoftDriveConfig.AppCredential app) throws IOException {
+ String key = app.tenantId() + "\n" + app.clientId() + "\n" + sha256(app.clientSecret());
+ return cache.get(
+ key,
+ () -> {
+ Map<String, String> form = new LinkedHashMap<>();
+ form.put("grant_type", "client_credentials");
+ form.put("client_id", app.clientId());
+ form.put("client_secret", app.clientSecret());
+ form.put("scope", endpoints.graphScope());
+ return OAuthHttp.accessToken(
+ OAuthHttp.postTokenRequest(endpoints.tokenUrl(app.tenantId()), form));
+ });
+ }
+
+ private static String sha256(String value) {
+ try {
+ return HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(value.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 unavailable", e);
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftCloudDrive.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftCloudDrive.java
new file mode 100644
index 0000000000..74fd8cd0d3
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftCloudDrive.java
@@ -0,0 +1,108 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import org.springframework.stereotype.Component;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.policy.remote.CloudDrive;
+import stirling.software.proprietary.policy.remote.ContentHasher;
+
+@Component
+@RequiredArgsConstructor
+public class MicrosoftCloudDrive implements CloudDrive<MicrosoftDriveConfig, DriveFile> {
+
+ private static final Set<String> TYPES =
+ new LinkedHashSet<>(
+ List.of(
+ MicrosoftDrive.ONEDRIVE.sourceType(),
+ MicrosoftDrive.SHAREPOINT.sourceType()));
+
+ private final MicrosoftConnectionResolver resolver;
+ private final GraphDriveClient graph;
+
+ @Override
+ public Set<String> types() {
+ return TYPES;
+ }
+
+ @Override
+ public MicrosoftDriveConfig resolve(String type, Map<String, Object> options, String owner) {
+ return resolver.resolve(options, MicrosoftDrive.fromOption(type), owner);
+ }
+
+ @Override
+ public void checkReadable(MicrosoftDriveConfig location) throws IOException {
+ graph.list(location.withRecursive(false));
+ }
+
+ @Override
+ public void checkWritable(MicrosoftDriveConfig location) throws IOException {
+ graph.root(location);
+ }
+
+ @Override
+ public List<DriveFile> list(MicrosoftDriveConfig location) throws IOException {
+ return graph.list(location);
+ }
+
+ @Override
+ public Optional<DriveFile> stat(MicrosoftDriveConfig location, DriveFile file)
+ throws IOException {
+ return graph.stat(location, file);
+ }
+
+ @Override
+ public InputStream open(MicrosoftDriveConfig location, DriveFile file) throws IOException {
+ return graph.open(location, file);
+ }
+
+ @Override
+ public boolean remove(MicrosoftDriveConfig location, DriveFile file) throws IOException {
+ return graph.delete(location, file);
+ }
+
+ @Override
+ public String outputIdentity(MicrosoftDriveConfig location, String name) throws IOException {
+ DriveRoot root = graph.root(location);
+ return MicrosoftDriveIdentities.identity(
+ root.driveId(),
+ root.key(),
+ MicrosoftDriveIdentities.childPath(location.directory(), name));
+ }
+
+ @Override
+ public ContentHasher newHasher() {
+ QuickXorHash hash = new QuickXorHash();
+ return new ContentHasher() {
+ @Override
+ public void update(byte[] bytes, int offset, int length) {
+ hash.update(bytes, offset, length);
+ }
+
+ @Override
+ public String gate() {
+ return MicrosoftDriveIdentities.gate(hash.digestBase64(), null);
+ }
+ };
+ }
+
+ @Override
+ public Optional<DriveFile> upload(MicrosoftDriveConfig location, String name, Path content)
+ throws IOException {
+ return graph.upload(location, location.directory(), name, content);
+ }
+
+ @Override
+ public String label() {
+ return "OneDrive/SharePoint";
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftConnectionResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftConnectionResolver.java
new file mode 100644
index 0000000000..7ba475dd34
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftConnectionResolver.java
@@ -0,0 +1,53 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.util.Map;
+
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.proprietary.connectedaccount.CloudProvider;
+import stirling.software.proprietary.connectedaccount.ConnectedAccount;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountAccess;
+import stirling.software.proprietary.integration.model.IntegrationType;
+import stirling.software.proprietary.integration.service.ConnectionLookup;
+import stirling.software.proprietary.policy.remote.LocationOptions;
+
+@Service
+@RequiredArgsConstructor
+public class MicrosoftConnectionResolver {
+
+ private final ConnectionLookup connections;
+ private final ConnectedAccountAccess accountAccess;
+
+ public MicrosoftDriveConfig resolve(
+ Map<String, Object> options, MicrosoftDrive expected, String owner) {
+ if (ConnectedAccountAccess.usesAccount(options)) {
+ ConnectedAccount account =
+ accountAccess.require(options, CloudProvider.MICROSOFT, owner);
+ return MicrosoftDriveConfig.forAccount(
+ expected == null ? MicrosoftDrive.ONEDRIVE : expected,
+ account.getId(),
+ options);
+ }
+ MicrosoftDriveConfig config =
+ MicrosoftDriveConfig.fromConnection(
+ connections.load(
+ options,
+ IntegrationType.MICROSOFT_365,
+ "Microsoft 365",
+ LocationOptions.PER_USE_KEYS,
+ owner));
+ if (expected != null && config.drive() != expected) {
+ throw new IllegalArgumentException(
+ "a "
+ + expected.sourceType()
+ + " location needs a "
+ + expected.sourceType()
+ + " connection, not a "
+ + config.drive().sourceType()
+ + " one");
+ }
+ return config;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDrive.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDrive.java
new file mode 100644
index 0000000000..5155cff519
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDrive.java
@@ -0,0 +1,29 @@
+package stirling.software.proprietary.policy.microsoft;
+
+public enum MicrosoftDrive {
+ ONEDRIVE("onedrive"),
+ SHAREPOINT("sharepoint");
+
+ private final String sourceType;
+
+ MicrosoftDrive(String sourceType) {
+ this.sourceType = sourceType;
+ }
+
+ public String sourceType() {
+ return sourceType;
+ }
+
+ public static MicrosoftDrive fromOption(String value) {
+ if (value == null) {
+ return null;
+ }
+ String normalized = value.trim().toLowerCase();
+ for (MicrosoftDrive drive : values()) {
+ if (drive.sourceType.equals(normalized)) {
+ return drive;
+ }
+ }
+ return null;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveConfig.java
new file mode 100644
index 0000000000..d00a78f5db
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveConfig.java
@@ -0,0 +1,230 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import stirling.software.proprietary.policy.remote.CloudLocation;
+import stirling.software.proprietary.policy.remote.LocationOptions;
+
+public record MicrosoftDriveConfig(
+ MicrosoftDrive drive,
+ Credential credential,
+ String user,
+ String siteHost,
+ String sitePath,
+ String library,
+ String folderLink,
+ String directory,
+ boolean snapshot,
+ boolean recursive)
+ implements CloudLocation {
+
+ public sealed interface Credential permits AppCredential, AccountCredential {}
+
+ public record AppCredential(String tenantId, String clientId, String clientSecret)
+ implements Credential {
+ @Override
+ public String toString() {
+ return "AppCredential[tenantId=" + tenantId + ", clientId=" + clientId + "]";
+ }
+ }
+
+ public record AccountCredential(long accountId) implements Credential {}
+
+ private static final Pattern TENANT = Pattern.compile("[A-Za-z0-9][A-Za-z0-9.-]{0,252}");
+ private static final Pattern USER = Pattern.compile("[^/\\\\?#\\s]{1,256}");
+
+ public static MicrosoftDriveConfig fromConnection(Map<String, Object> options) {
+ MicrosoftDrive drive = requireDrive(options);
+ AppCredential credential =
+ new AppCredential(
+ tenant(options),
+ required(options, "clientId"),
+ required(options, "clientSecret"));
+
+ String user = null;
+ String siteHost = null;
+ String sitePath = null;
+ String library = null;
+ if (drive == MicrosoftDrive.ONEDRIVE) {
+ user = required(options, "user");
+ if (!USER.matcher(user).matches()) {
+ throw new IllegalArgumentException(
+ "OneDrive 'user' must be a user principal name such as"
+ + " [email protected], or a user object ID");
+ }
+ } else {
+ URI site = httpsUrl(required(options, "siteUrl"), "SharePoint 'siteUrl'");
+ if (site.getRawQuery() != null || site.getRawFragment() != null) {
+ throw new IllegalArgumentException(
+ "SharePoint 'siteUrl' must look like"
+ + " https://contoso.sharepoint.com/sites/Finance");
+ }
+ siteHost = site.getHost();
+ sitePath = trimSlashes(site.getPath() == null ? "" : site.getPath());
+ library = LocationOptions.trimmed(options.get("library"));
+ }
+ Folder folder = folder(options.get("directory"));
+ return new MicrosoftDriveConfig(
+ drive,
+ credential,
+ user,
+ siteHost,
+ sitePath,
+ library,
+ folder.link(),
+ folder.path(),
+ LocationOptions.snapshot(options),
+ LocationOptions.recursive(options));
+ }
+
+ public static MicrosoftDriveConfig forAccount(
+ MicrosoftDrive drive, long accountId, Map<String, Object> options) {
+ Folder folder = folder(options.get("directory"));
+ if (drive == MicrosoftDrive.SHAREPOINT && folder.link() == null) {
+ throw new IllegalArgumentException(
+ "paste a link to the SharePoint folder (Copy link in SharePoint)");
+ }
+ return new MicrosoftDriveConfig(
+ drive,
+ new AccountCredential(accountId),
+ null,
+ null,
+ null,
+ null,
+ folder.link(),
+ folder.path(),
+ LocationOptions.snapshot(options),
+ LocationOptions.recursive(options));
+ }
+
+ public String location() {
+ StringBuilder label = new StringBuilder();
+ switch (credential) {
+ case AccountCredential account -> label.append("account:").append(account.accountId());
+ case AppCredential app when drive == MicrosoftDrive.ONEDRIVE ->
+ label.append(app.tenantId()).append(":onedrive:").append(user);
+ case AppCredential app ->
+ label.append(app.tenantId())
+ .append(":sharepoint:")
+ .append(siteHost)
+ .append(sitePath.isEmpty() ? "" : "/" + sitePath)
+ .append(library == null ? "" : "#" + library);
+ }
+ if (folderLink != null) {
+ label.append(" link:").append(folderLink);
+ }
+ return label.toString();
+ }
+
+ public MicrosoftDriveConfig withRecursive(boolean value) {
+ return new MicrosoftDriveConfig(
+ drive,
+ credential,
+ user,
+ siteHost,
+ sitePath,
+ library,
+ folderLink,
+ directory,
+ snapshot,
+ value);
+ }
+
+ private record Folder(String link, String path) {}
+
+ private static Folder folder(Object value) {
+ String text = LocationOptions.trimmed(value);
+ if (text == null) {
+ return new Folder(null, "");
+ }
+ if (text.regionMatches(true, 0, "https://", 0, 8)) {
+ return new Folder(httpsUrl(text, "folder link").toString(), "");
+ }
+ return new Folder(null, directory(text));
+ }
+
+ private static MicrosoftDrive requireDrive(Map<String, Object> options) {
+ MicrosoftDrive drive =
+ MicrosoftDrive.fromOption(LocationOptions.trimmed(options.get("drive")));
+ if (drive == null) {
+ throw new IllegalArgumentException(
+ "Microsoft 365 connection requires a 'drive' of onedrive or sharepoint");
+ }
+ return drive;
+ }
+
+ private static String tenant(Map<String, Object> options) {
+ String tenant = LocationOptions.trimmed(options.get("tenantId"));
+ if (tenant == null) {
+ throw new IllegalArgumentException(
+ "Microsoft 365 connection requires a 'tenantId' (directory ID or domain)");
+ }
+ if (!TENANT.matcher(tenant).matches() || !isSpecificTenant(tenant)) {
+ throw new IllegalArgumentException(
+ "Microsoft 365 'tenantId' must be a directory (tenant) ID or a domain such as"
+ + " contoso.onmicrosoft.com");
+ }
+ return tenant;
+ }
+
+ private static boolean isSpecificTenant(String tenant) {
+ String value = tenant.trim().toLowerCase();
+ return !value.isEmpty()
+ && !value.equals("common")
+ && !value.equals("organizations")
+ && !value.equals("consumers");
+ }
+
+ private static URI httpsUrl(String value, String label) {
+ URI uri;
+ try {
+ uri = new URI(value);
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException(label + " is not a valid URL", e);
+ }
+ if (!"https".equalsIgnoreCase(uri.getScheme())
+ || uri.getHost() == null
+ || uri.getUserInfo() != null
+ || uri.getPort() != -1) {
+ throw new IllegalArgumentException(label + " must be an https:// link");
+ }
+ return uri;
+ }
+
+ private static String directory(String text) {
+ if (text.indexOf(':') >= 0) {
+ throw new IllegalArgumentException("folder contains a character OneDrive rejects");
+ }
+ return LocationOptions.folderPath(text);
+ }
+
+ private static String required(Map<String, Object> options, String key) {
+ String value = LocationOptions.trimmed(options.get(key));
+ if (value == null) {
+ throw new IllegalArgumentException("Microsoft 365 connection requires a '" + key + "'");
+ }
+ return value;
+ }
+
+ static String trimSlashes(String value) {
+ return LocationOptions.trimSlashes(value);
+ }
+
+ @Override
+ public String toString() {
+ return "MicrosoftDriveConfig[location="
+ + location()
+ + ", credential="
+ + credential
+ + ", directory="
+ + directory
+ + ", snapshot="
+ + snapshot
+ + ", recursive="
+ + recursive
+ + "]";
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveIdentities.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveIdentities.java
new file mode 100644
index 0000000000..dcfc396008
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveIdentities.java
@@ -0,0 +1,22 @@
+package stirling.software.proprietary.policy.microsoft;
+
+public final class MicrosoftDriveIdentities {
+
+ private MicrosoftDriveIdentities() {}
+
+ public static String identity(String driveId, String root, String path) {
+ return "msgraph://" + driveId + "/" + root + "/" + MicrosoftDriveConfig.trimSlashes(path);
+ }
+
+ public static String gate(String quickXorHash, String cTag) {
+ if (quickXorHash != null && !quickXorHash.isBlank()) {
+ return "qxh:" + quickXorHash;
+ }
+ return "ctag:" + (cTag == null ? "" : cTag);
+ }
+
+ public static String childPath(String directory, String name) {
+ String parent = MicrosoftDriveConfig.trimSlashes(directory);
+ return parent.isEmpty() ? name : parent + "/" + name;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveInputSource.java
new file mode 100644
index 0000000000..a7a0ae8d50
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveInputSource.java
@@ -0,0 +1,14 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import org.springframework.stereotype.Service;
+
+import stirling.software.proprietary.policy.remote.CloudDriveInputSource;
+
+@Service
+public class MicrosoftDriveInputSource
+ extends CloudDriveInputSource<MicrosoftDriveConfig, DriveFile> {
+
+ public MicrosoftDriveInputSource(MicrosoftCloudDrive drive) {
+ super(drive);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftIntegrationValidator.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftIntegrationValidator.java
new file mode 100644
index 0000000000..cace1cf760
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/MicrosoftIntegrationValidator.java
@@ -0,0 +1,22 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.util.Map;
+
+import org.springframework.stereotype.Component;
+
+import stirling.software.proprietary.integration.model.IntegrationType;
+import stirling.software.proprietary.integration.service.IntegrationConfigValidator;
+
+@Component
+public class MicrosoftIntegrationValidator implements IntegrationConfigValidator {
+
+ @Override
+ public IntegrationType type() {
+ return IntegrationType.MICROSOFT_365;
+ }
+
+ @Override
+ public void validate(Map<String, Object> config) {
+ MicrosoftDriveConfig.fromConnection(config);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/QuickXorHash.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/QuickXorHash.java
new file mode 100644
index 0000000000..cd8480015a
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/microsoft/QuickXorHash.java
@@ -0,0 +1,65 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.util.Base64;
+
+public final class QuickXorHash {
+
+ private static final int WIDTH_IN_BITS = 160;
+ private static final int SHIFT = 11;
+
+ private final long[] data = new long[(WIDTH_IN_BITS - 1) / 64 + 1];
+ private int shiftSoFar;
+ private long lengthSoFar;
+
+ public void update(byte[] array, int start, int size) {
+ int currentShift = shiftSoFar;
+ int vectorArrayIndex = currentShift / 64;
+ int vectorOffset = currentShift % 64;
+ int iterations = Math.min(size, WIDTH_IN_BITS);
+
+ for (int i = 0; i < iterations; i++) {
+ boolean isLastCell = vectorArrayIndex == data.length - 1;
+ int bitsInVectorCell = isLastCell ? WIDTH_IN_BITS % 64 : 64;
+
+ if (vectorOffset <= bitsInVectorCell - 8) {
+ for (int j = start + i; j < size + start; j += WIDTH_IN_BITS) {
+ data[vectorArrayIndex] ^= (array[j] & 0xFFL) << vectorOffset;
+ }
+ } else {
+ int index1 = vectorArrayIndex;
+ int index2 = isLastCell ? 0 : vectorArrayIndex + 1;
+ int low = bitsInVectorCell - vectorOffset;
+ int xoredByte = 0;
+ for (int j = start + i; j < size + start; j += WIDTH_IN_BITS) {
+ xoredByte ^= array[j] & 0xFF;
+ }
+ data[index1] ^= ((long) xoredByte) << vectorOffset;
+ data[index2] ^= ((long) xoredByte) >>> low;
+ }
+
+ vectorOffset += SHIFT;
+ while (vectorOffset >= bitsInVectorCell) {
+ vectorArrayIndex = isLastCell ? 0 : vectorArrayIndex + 1;
+ vectorOffset -= bitsInVectorCell;
+ }
+ }
+
+ shiftSoFar = (int) ((shiftSoFar + (long) SHIFT * (size % WIDTH_IN_BITS)) % WIDTH_IN_BITS);
+ lengthSoFar += size;
+ }
+
+ public String digestBase64() {
+ byte[] result = new byte[(WIDTH_IN_BITS - 1) / 8 + 1];
+ for (int i = 0; i < data.length; i++) {
+ int bytes = Math.min(8, result.length - i * 8);
+ for (int b = 0; b < bytes; b++) {
+ result[i * 8 + b] = (byte) (data[i] >>> (8 * b));
+ }
+ }
+ int lengthOffset = WIDTH_IN_BITS / 8 - Long.BYTES;
+ for (int b = 0; b < Long.BYTES; b++) {
+ result[lengthOffset + b] ^= (byte) (lengthSoFar >>> (8 * b));
+ }
+ return Base64.getEncoder().encodeToString(result);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java
index 574b5f1f18..37de034404 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyRun.java
@@ -49,6 +49,8 @@ public class PolicyRun {
*/
private final String triggeringUser;
+ private final String pipelineOwner;
+
private final Instant createdAt = Instant.now();
private volatile PolicyRunStatus status = PolicyRunStatus.PENDING;
@@ -92,7 +94,8 @@ public class PolicyRun {
String sourceId,
String fileIdentity,
String triggeringUser,
- String fileOwner) {
+ String fileOwner,
+ String pipelineOwner) {
this.runId = runId;
this.policyId = policyId;
this.sourceId = sourceId;
@@ -100,6 +103,7 @@ public class PolicyRun {
this.fileIdentity = fileIdentity;
this.triggeringUser = triggeringUser;
this.fileOwner = fileOwner;
+ this.pipelineOwner = pipelineOwner;
}
/**
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/CloudDriveOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/CloudDriveOutputSink.java
new file mode 100644
index 0000000000..be98f11b3f
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/CloudDriveOutputSink.java
@@ -0,0 +1,148 @@
+package stirling.software.proprietary.policy.output;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+
+import org.springframework.core.io.Resource;
+import org.springframework.http.MediaType;
+import org.springframework.http.MediaTypeFactory;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.job.ResultFile;
+import stirling.software.proprietary.policy.ledger.ProcessedLedger;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.remote.CloudDrive;
+import stirling.software.proprietary.policy.remote.CloudFile;
+import stirling.software.proprietary.policy.remote.CloudLocation;
+import stirling.software.proprietary.policy.remote.ContentHasher;
+
+@Slf4j
+public abstract class CloudDriveOutputSink<L extends CloudLocation, F extends CloudFile>
+ implements PolicyOutputSink {
+
+ private static final int MAX_NAME_ATTEMPTS = 100;
+
+ private final CloudDrive<L, F> drive;
+ private final ProcessedLedger processedLedger;
+
+ protected CloudDriveOutputSink(CloudDrive<L, F> drive, ProcessedLedger processedLedger) {
+ this.drive = drive;
+ this.processedLedger = processedLedger;
+ }
+
+ @Override
+ public String type() {
+ return drive.types().iterator().next();
+ }
+
+ @Override
+ public boolean supports(OutputSpec spec) {
+ return spec != null && drive.types().contains(spec.type());
+ }
+
+ @Override
+ public void validate(OutputSpec spec) {
+ try {
+ drive.checkWritable(drive.resolve(spec.type(), spec.options(), null));
+ } catch (IOException e) {
+ throw new IllegalArgumentException(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public List<ResultFile> deliver(
+ OutputDelivery delivery, List<Resource> outputs, OutputSpec spec) throws IOException {
+ L location = drive.resolve(spec.type(), spec.options(), delivery.pipelineOwner());
+ List<ResultFile> results = new ArrayList<>();
+ for (int i = 0; i < outputs.size(); i++) {
+ Resource resource = outputs.get(i);
+ String name = OutputNames.safeName(resource.getFilename(), i);
+ Path staged = Files.createTempFile("cloud-output-", ".tmp");
+ try {
+ String gate = stage(resource, staged);
+ F uploaded = upload(delivery, location, name, staged, gate);
+ results.add(
+ ResultFile.builder()
+ .fileId(UUID.randomUUID().toString())
+ .fileName(uploaded.identity())
+ .contentType(
+ MediaTypeFactory.getMediaType(uploaded.name())
+ .orElse(MediaType.APPLICATION_OCTET_STREAM)
+ .toString())
+ .fileSize(uploaded.size())
+ .build());
+ } finally {
+ try {
+ Files.deleteIfExists(staged);
+ } catch (IOException e) {
+ log.warn("Could not remove staging file {}: {}", staged, e.getMessage());
+ }
+ }
+ }
+ return results;
+ }
+
+ private F upload(OutputDelivery delivery, L location, String name, Path staged, String gate)
+ throws IOException {
+ for (int attempt = 0; attempt < MAX_NAME_ATTEMPTS; attempt++) {
+ String candidate = attempt == 0 ? name : OutputNames.numbered(name, attempt);
+ String identity = drive.outputIdentity(location, candidate);
+ if (delivery.policyId() != null) {
+ processedLedger.recordOutput(delivery.policyId(), identity, gate, null);
+ }
+ Optional<F> uploaded;
+ try {
+ uploaded = drive.upload(location, candidate, staged);
+ } catch (IOException | RuntimeException e) {
+ forget(delivery, identity, gate);
+ throw e;
+ }
+ if (uploaded.isPresent()) {
+ F file = uploaded.get();
+ if (delivery.policyId() != null
+ && file.hasContentHash()
+ && !file.version().equals(gate)) {
+ processedLedger.recordOutput(
+ delivery.policyId(), identity, file.version(), null);
+ }
+ return file;
+ }
+ forget(delivery, identity, gate);
+ log.debug("{} already exists; trying the next name", identity);
+ }
+ throw new IOException(
+ "Could not find a free name for "
+ + name
+ + " after "
+ + MAX_NAME_ATTEMPTS
+ + " tries");
+ }
+
+ private void forget(OutputDelivery delivery, String identity, String gate) {
+ if (delivery.policyId() != null) {
+ processedLedger.forgetOutput(delivery.policyId(), identity, gate);
+ }
+ }
+
+ private String stage(Resource resource, Path staged) throws IOException {
+ ContentHasher hasher = drive.newHasher();
+ byte[] buffer = new byte[64 * 1024];
+ try (InputStream in = resource.getInputStream();
+ OutputStream out = Files.newOutputStream(staged)) {
+ int read;
+ while ((read = in.read(buffer)) != -1) {
+ hasher.update(buffer, 0, read);
+ out.write(buffer, 0, read);
+ }
+ }
+ return hasher.gate();
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/GoogleDriveOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/GoogleDriveOutputSink.java
new file mode 100644
index 0000000000..c37c533cfa
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/GoogleDriveOutputSink.java
@@ -0,0 +1,16 @@
+package stirling.software.proprietary.policy.output;
+
+import org.springframework.stereotype.Service;
+
+import stirling.software.proprietary.policy.google.GoogleCloudDrive;
+import stirling.software.proprietary.policy.google.GoogleDriveConfig;
+import stirling.software.proprietary.policy.google.GoogleFile;
+import stirling.software.proprietary.policy.ledger.ProcessedLedger;
+
+@Service
+public class GoogleDriveOutputSink extends CloudDriveOutputSink<GoogleDriveConfig, GoogleFile> {
+
+ public GoogleDriveOutputSink(GoogleCloudDrive drive, ProcessedLedger processedLedger) {
+ super(drive, processedLedger);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/MicrosoftDriveOutputSink.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/MicrosoftDriveOutputSink.java
new file mode 100644
index 0000000000..88e3ca98e8
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/MicrosoftDriveOutputSink.java
@@ -0,0 +1,17 @@
+package stirling.software.proprietary.policy.output;
+
+import org.springframework.stereotype.Service;
+
+import stirling.software.proprietary.policy.ledger.ProcessedLedger;
+import stirling.software.proprietary.policy.microsoft.DriveFile;
+import stirling.software.proprietary.policy.microsoft.MicrosoftCloudDrive;
+import stirling.software.proprietary.policy.microsoft.MicrosoftDriveConfig;
+
+@Service
+public class MicrosoftDriveOutputSink
+ extends CloudDriveOutputSink<MicrosoftDriveConfig, DriveFile> {
+
+ public MicrosoftDriveOutputSink(MicrosoftCloudDrive drive, ProcessedLedger processedLedger) {
+ super(drive, processedLedger);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java
index 8b0f06f224..ff01a40358 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/output/OutputDelivery.java
@@ -19,22 +19,32 @@ public record OutputDelivery(
String policyId,
PolicyInputs inputs,
String fileOwner,
- String documentIdentity) {
+ String documentIdentity,
+ String pipelineOwner) {
public OutputDelivery {
inputs = inputs == null ? PolicyInputs.of(List.of()) : inputs;
}
+ public OutputDelivery(
+ String runId,
+ String policyId,
+ PolicyInputs inputs,
+ String fileOwner,
+ String documentIdentity) {
+ this(runId, policyId, inputs, fileOwner, documentIdentity, null);
+ }
+
public OutputDelivery(String runId, String policyId, PolicyInputs inputs, String fileOwner) {
- this(runId, policyId, inputs, fileOwner, null);
+ this(runId, policyId, inputs, fileOwner, null, null);
}
public OutputDelivery(String runId, String policyId, PolicyInputs inputs) {
- this(runId, policyId, inputs, null, null);
+ this(runId, policyId, inputs, null, null, null);
}
public OutputDelivery(String runId, String policyId) {
- this(runId, policyId, null, null, null);
+ this(runId, policyId, null, null, null, null);
}
/** Reuses the run's document reference, scoped to its source or submitting user. */
@@ -51,6 +61,7 @@ public record OutputDelivery(
identity = "user:" + run.getTriggeringUser() + "\n" + run.getFileIdentity();
}
}
- return new OutputDelivery(run.getRunId(), run.getPolicyId(), inputs, null, identity);
+ return new OutputDelivery(
+ run.getRunId(), run.getPolicyId(), inputs, null, identity, run.getPipelineOwner());
}
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudDrive.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudDrive.java
new file mode 100644
index 0000000000..9df785e1ff
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudDrive.java
@@ -0,0 +1,38 @@
+package stirling.software.proprietary.policy.remote;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+public interface CloudDrive<L extends CloudLocation, F extends CloudFile> {
+
+ int MAX_FILES = 10_000;
+
+ Set<String> types();
+
+ L resolve(String type, Map<String, Object> options, String owner);
+
+ void checkReadable(L location) throws IOException;
+
+ void checkWritable(L location) throws IOException;
+
+ List<F> list(L location) throws IOException;
+
+ Optional<F> stat(L location, F file) throws IOException;
+
+ InputStream open(L location, F file) throws IOException;
+
+ boolean remove(L location, F file) throws IOException;
+
+ String outputIdentity(L location, String name) throws IOException;
+
+ ContentHasher newHasher();
+
+ Optional<F> upload(L location, String name, Path content) throws IOException;
+
+ String label();
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudDriveInputSource.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudDriveInputSource.java
new file mode 100644
index 0000000000..3554b976c6
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudDriveInputSource.java
@@ -0,0 +1,166 @@
+package stirling.software.proprietary.policy.remote;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+import org.springframework.core.io.AbstractResource;
+import org.springframework.core.io.Resource;
+
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.policy.input.InputSource;
+import stirling.software.proprietary.policy.input.ResolveContext;
+import stirling.software.proprietary.policy.input.ResolvedInput;
+import stirling.software.proprietary.policy.model.InputSpec;
+import stirling.software.proprietary.policy.model.PolicyInputs;
+import stirling.software.proprietary.policy.source.Source;
+
+@Slf4j
+public abstract class CloudDriveInputSource<L extends CloudLocation, F extends CloudFile>
+ implements InputSource {
+
+ private final CloudDrive<L, F> drive;
+
+ protected CloudDriveInputSource(CloudDrive<L, F> drive) {
+ this.drive = drive;
+ }
+
+ @Override
+ public String type() {
+ return drive.types().iterator().next();
+ }
+
+ @Override
+ public boolean supports(InputSpec spec) {
+ return spec != null && drive.types().contains(spec.type());
+ }
+
+ @Override
+ public void validate(InputSpec spec) {
+ L location = drive.resolve(spec.type(), spec.options(), null);
+ try {
+ drive.checkReadable(location);
+ } catch (IOException e) {
+ throw new IllegalArgumentException(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public List<ResolvedInput> resolve(Source source, ResolveContext ctx, String policyOwner)
+ throws IOException {
+ return resolve(source.toInputSpec(), ctx, policyOwner);
+ }
+
+ @Override
+ public List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx) throws IOException {
+ return resolve(spec, ctx, null);
+ }
+
+ private List<ResolvedInput> resolve(InputSpec spec, ResolveContext ctx, String owner)
+ throws IOException {
+ L location = drive.resolve(spec.type(), spec.options(), owner);
+ List<F> files = drive.list(location);
+ if (files.size() >= CloudDrive.MAX_FILES) {
+ log.warn(
+ "{} listing of {} hit the {}-file cap; the rest are picked up later",
+ drive.label(),
+ location.location(),
+ CloudDrive.MAX_FILES);
+ }
+ if (location.snapshot()) {
+ return files.stream()
+ .map(
+ file ->
+ ResolvedInput.of(
+ PolicyInputs.of(List.of(resource(location, file)))))
+ .toList();
+ }
+ ctx.reportPresent(files.stream().map(CloudFile::identity).toList());
+ boolean track = !"consume".equals(String.valueOf(spec.options().get("mode")).trim());
+ List<ResolvedInput> work = new ArrayList<>();
+ for (F file : files) {
+ String gate = file.version();
+ if (!ctx.claim(file.identity(), gate, null)) {
+ continue;
+ }
+ work.add(
+ ResolvedInput.forFile(
+ PolicyInputs.of(List.of(resource(location, file))),
+ file.identity(),
+ success -> complete(ctx, location, file, gate, success, track)));
+ }
+ return work;
+ }
+
+ private void complete(
+ ResolveContext ctx,
+ L location,
+ F file,
+ String claimGate,
+ boolean success,
+ boolean track) {
+ ctx.settle(file.identity(), claimGate, null, success);
+ if (!success || track) {
+ return;
+ }
+ try {
+ Optional<F> current = drive.stat(location, file);
+ if (current.isEmpty()
+ || !current.get().version().equals(claimGate)
+ || !ctx.allSettledDone(file.identity())) {
+ return;
+ }
+ if (!drive.remove(location, current.get())) {
+ log.debug("{} changed before it could be consumed; keeping it", file.identity());
+ }
+ } catch (IOException e) {
+ log.warn("Could not remove consumed file {}: {}", file.identity(), e.getMessage());
+ }
+ }
+
+ private Resource resource(L location, F file) {
+ return new CloudFileResource<>(drive, location, file);
+ }
+
+ private static final class CloudFileResource<L extends CloudLocation, F extends CloudFile>
+ extends AbstractResource {
+
+ private final CloudDrive<L, F> drive;
+ private final L location;
+ private final F file;
+
+ CloudFileResource(CloudDrive<L, F> drive, L location, F file) {
+ this.drive = drive;
+ this.location = location;
+ this.file = file;
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return drive.open(location, file);
+ }
+
+ @Override
+ public boolean exists() {
+ return true;
+ }
+
+ @Override
+ public long contentLength() {
+ return file.size();
+ }
+
+ @Override
+ public String getFilename() {
+ return file.name();
+ }
+
+ @Override
+ public String getDescription() {
+ return drive.label() + " file " + file.identity();
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudFile.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudFile.java
new file mode 100644
index 0000000000..4e0a7013c7
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudFile.java
@@ -0,0 +1,14 @@
+package stirling.software.proprietary.policy.remote;
+
+public interface CloudFile {
+
+ String identity();
+
+ String version();
+
+ String name();
+
+ long size();
+
+ boolean hasContentHash();
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudHttp.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudHttp.java
new file mode 100644
index 0000000000..75c008cb07
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudHttp.java
@@ -0,0 +1,127 @@
+package stirling.software.proprietary.policy.remote;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.time.Duration;
+import java.util.Optional;
+import java.util.Set;
+
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectMapper;
+
+public final class CloudHttp {
+
+ private static final int MAX_ATTEMPTS = 4;
+ private static final Set<String> IDEMPOTENT = Set.of("GET", "HEAD", "PUT", "DELETE", "OPTIONS");
+ private static final long MAX_RETRY_WAIT_SECONDS = 60;
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ private CloudHttp() {}
+
+ public static HttpClient newClient() {
+ return HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(20))
+ .followRedirects(HttpClient.Redirect.NEVER)
+ .build();
+ }
+
+ public static <T> HttpResponse<T> send(
+ HttpClient http,
+ HttpRequest request,
+ HttpResponse.BodyHandler<T> handler,
+ String service)
+ throws IOException {
+ for (int attempt = 1; ; attempt++) {
+ HttpResponse<T> response;
+ try {
+ response = http.send(request, handler);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException("Interrupted calling " + service, e);
+ } catch (IOException e) {
+ throw new IOException(
+ "Could not reach "
+ + service
+ + " ("
+ + (e.getMessage() == null
+ ? e.getClass().getSimpleName()
+ : e.getMessage())
+ + ")",
+ e);
+ }
+ int status = response.statusCode();
+ boolean serverError = status == 500 || status == 502 || status == 503 || status == 504;
+ boolean retry = status == 429 || (serverError && IDEMPOTENT.contains(request.method()));
+ if (!retry || attempt >= MAX_ATTEMPTS) {
+ return response;
+ }
+ if (response.body() instanceof InputStream stream) {
+ stream.close();
+ }
+ long wait =
+ response.headers()
+ .firstValue("Retry-After")
+ .map(CloudHttp::seconds)
+ .orElse((long) attempt * 2);
+ try {
+ Thread.sleep(Duration.ofSeconds(Math.min(wait, MAX_RETRY_WAIT_SECONDS)));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IOException("Interrupted waiting out " + service + " throttling", e);
+ }
+ }
+ }
+
+ public static InputStream download(
+ HttpClient http, HttpResponse<InputStream> response, String what, String service)
+ throws IOException {
+ if (response.statusCode() == 200) {
+ return response.body();
+ }
+ response.body().close();
+ Optional<String> location = response.headers().firstValue("Location");
+ if (response.statusCode() / 100 == 3 && location.isPresent()) {
+ HttpResponse<InputStream> redirected =
+ send(
+ http,
+ HttpRequest.newBuilder(URI.create(location.get()))
+ .timeout(Duration.ofMinutes(30))
+ .GET()
+ .build(),
+ HttpResponse.BodyHandlers.ofInputStream(),
+ service);
+ if (redirected.statusCode() == 200) {
+ return redirected.body();
+ }
+ redirected.body().close();
+ throw new IOException(
+ "Could not download " + what + ": HTTP " + redirected.statusCode());
+ }
+ throw new IOException("Could not download " + what + ": HTTP " + response.statusCode());
+ }
+
+ public static JsonNode parse(String body) {
+ try {
+ return JSON.readTree(body == null || body.isBlank() ? "{}" : body);
+ } catch (RuntimeException e) {
+ return JSON.createObjectNode();
+ }
+ }
+
+ public static String text(JsonNode node, String field) {
+ JsonNode value = node == null ? null : node.get(field);
+ return value == null || value.isNull() ? null : value.asString();
+ }
+
+ static long seconds(String value) {
+ try {
+ return Math.max(0, Long.parseLong(value.trim()));
+ } catch (NumberFormatException e) {
+ return 5;
+ }
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudLocation.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudLocation.java
new file mode 100644
index 0000000000..20b3e9c1ed
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/CloudLocation.java
@@ -0,0 +1,8 @@
+package stirling.software.proprietary.policy.remote;
+
+public interface CloudLocation {
+
+ boolean snapshot();
+
+ String location();
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/ContentHasher.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/ContentHasher.java
new file mode 100644
index 0000000000..77cae7aa64
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/ContentHasher.java
@@ -0,0 +1,8 @@
+package stirling.software.proprietary.policy.remote;
+
+public interface ContentHasher {
+
+ void update(byte[] bytes, int offset, int length);
+
+ String gate();
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/ExpiringTokenCache.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/ExpiringTokenCache.java
new file mode 100644
index 0000000000..7708d11717
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/ExpiringTokenCache.java
@@ -0,0 +1,53 @@
+package stirling.software.proprietary.policy.remote;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Predicate;
+
+public final class ExpiringTokenCache {
+
+ public record Token(String value, long expiresInSeconds) {}
+
+ @FunctionalInterface
+ public interface Fetch {
+ Token fetch() throws IOException;
+ }
+
+ private record Entry(String value, Instant refreshAfter) {}
+
+ private final Duration margin;
+ private final Map<String, Entry> entries = new ConcurrentHashMap<>();
+
+ public ExpiringTokenCache(Duration margin) {
+ this.margin = margin;
+ }
+
+ public String get(String key, Fetch fetch) throws IOException {
+ String cached = peek(key);
+ if (cached != null) {
+ return cached;
+ }
+ return put(key, fetch.fetch());
+ }
+
+ public String peek(String key) {
+ Entry entry = entries.get(key);
+ return entry != null && Instant.now().isBefore(entry.refreshAfter()) ? entry.value() : null;
+ }
+
+ public String put(String key, Token token) {
+ entries.put(
+ key,
+ new Entry(
+ token.value(),
+ Instant.now().plusSeconds(token.expiresInSeconds()).minus(margin)));
+ return token.value();
+ }
+
+ public void evictIf(Predicate<String> keyMatches) {
+ entries.keySet().removeIf(keyMatches);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/LocationOptions.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/LocationOptions.java
new file mode 100644
index 0000000000..2f76c46364
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/remote/LocationOptions.java
@@ -0,0 +1,62 @@
+package stirling.software.proprietary.policy.remote;
+
+import java.util.Map;
+import java.util.Set;
+
+public final class LocationOptions {
+
+ public static final Set<String> PER_USE_KEYS = Set.of("directory", "mode", "recursive");
+
+ private LocationOptions() {}
+
+ public static boolean snapshot(Map<String, Object> options) {
+ String mode = trimmed(options.get("mode"));
+ if (mode == null) {
+ return false;
+ }
+ return switch (mode) {
+ case "consume", "track" -> false;
+ case "snapshot" -> true;
+ default ->
+ throw new IllegalArgumentException(
+ "'mode' must be 'consume', 'track' or 'snapshot'");
+ };
+ }
+
+ public static boolean recursive(Map<String, Object> options) {
+ return Boolean.parseBoolean(String.valueOf(options.get("recursive")).trim());
+ }
+
+ public static String folderPath(String text) {
+ String normalized = text.replace('\\', '/');
+ for (String segment : normalized.split("/")) {
+ if (segment.equals("..") || segment.equals(".")) {
+ throw new IllegalArgumentException("folder must not contain '.' or '..' segments");
+ }
+ if (segment.indexOf('\0') >= 0) {
+ throw new IllegalArgumentException("folder contains a null character");
+ }
+ }
+ return trimSlashes(normalized.replaceAll("/{2,}", "/"));
+ }
+
+ public static String trimmed(Object value) {
+ if (value == null) {
+ return null;
+ }
+ String text = value.toString().trim();
+ return text.isEmpty() ? null : text;
+ }
+
+ public static String trimSlashes(String value) {
+ int start = 0;
+ int end = value.length();
+ while (start < end && value.charAt(start) == '/') {
+ start++;
+ }
+ while (end > start && value.charAt(end - 1) == '/') {
+ end--;
+ }
+ return value.substring(start, end);
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
index a176176d47..dde04fbc97 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/DatabaseConfig.java
@@ -39,6 +39,7 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
"stirling.software.proprietary.accountlink",
"stirling.software.proprietary.access.repository",
"stirling.software.proprietary.integration.repository",
+ "stirling.software.proprietary.connectedaccount",
"stirling.software.proprietary.failure"
})
@EntityScan({
@@ -54,6 +55,7 @@ import stirling.software.common.model.exception.UnsupportedProviderException;
"stirling.software.proprietary.accountlink",
"stirling.software.proprietary.access.model",
"stirling.software.proprietary.integration.model",
+ "stirling.software.proprietary.connectedaccount",
"stirling.software.proprietary.failure"
})
public class DatabaseConfig {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
index 078dbac03b..8d5cddab29 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
@@ -48,6 +48,7 @@ import stirling.software.common.service.UserServiceInterface;
import stirling.software.proprietary.access.model.PrincipalType;
import stirling.software.proprietary.access.model.ResourceType;
import stirling.software.proprietary.access.repository.ResourceGrantRepository;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
import stirling.software.proprietary.integration.model.IntegrationConfig;
import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
import stirling.software.proprietary.model.Team;
@@ -110,6 +111,7 @@ public class UserService implements UserServiceInterface {
private final FileShareAccessRepository fileShareAccessRepository;
private final ResourceGrantRepository resourceGrantRepository;
private final IntegrationConfigRepository integrationConfigRepository;
+ private final ConnectedAccountService connectedAccountService;
private final TeamMembershipService teamMembershipService;
private final ApiKeyAuthenticationService apiKeyAuthenticationService;
private final ToolUsageStatRepository toolUsageStatRepository;
@@ -303,6 +305,7 @@ public class UserService implements UserServiceInterface {
ResourceType.INTEGRATION_CONFIG, String.valueOf(cfg.getId()));
}
integrationConfigRepository.deleteByOwnerUser(user);
+ connectedAccountService.removeAllFor(user.getId());
// Membership rows and invitation references would dangle once the user row is gone
teamMembershipService.deleteAllForUser(user);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackPageTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackPageTest.java
new file mode 100644
index 0000000000..84a77f2ed0
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackPageTest.java
@@ -0,0 +1,45 @@
+package stirling.software.proprietary.connectedaccount;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+class ConnectedAccountCallbackPageTest {
+
+ @Test
+ void escapesTheProviderMessageAndOnlyClosesAPopup() {
+ String page =
+ ConnectedAccountController.callbackPage(
+ "microsoft",
+ "error",
+ "<script>alert(1)</script>",
+ "https://stirling.example/settings/connectedAccounts");
+
+ assertThat(page).doesNotContain("<script>alert(1)</script>");
+ assertThat(page).contains("&lt;script&gt;alert(1)&lt;/script&gt;");
+ assertThat(page).contains("href=\"https://stirling.example/settings/connectedAccounts\"");
+ assertThat(page).doesNotContain("window.close");
+ }
+
+ @Test
+ void aConnectedPopupClosesItselfButOnlyWhenItHasAnOpener() {
+ String page =
+ ConnectedAccountController.callbackPage(
+ "google", "connected", "Connected [email protected]", "/settings");
+
+ int opener = page.indexOf("if(window.opener){");
+ int close = page.indexOf("window.close()");
+ assertThat(opener).isPositive();
+ assertThat(close).isGreaterThan(opener);
+ assertThat(page).contains("\"provider\":\"google\"").contains("\"status\":\"connected\"");
+ }
+
+ @Test
+ void anUntrustedProviderSegmentCannotBreakOutOfTheScript() {
+ String page =
+ ConnectedAccountController.callbackPage(
+ "x\"});alert(1);//", "connected", "ok", "/settings");
+
+ assertThat(page).doesNotContain("alert(1)");
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackTest.java
new file mode 100644
index 0000000000..d72b6c6dd1
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountCallbackTest.java
@@ -0,0 +1,88 @@
+package stirling.software.proprietary.connectedaccount;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.server.ResponseStatusException;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.security.model.User;
+
+class ConnectedAccountCallbackTest {
+
+ private final ConnectedAccountService service = mock(ConnectedAccountService.class);
+
+ private ConnectedAccountController controller() {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getSystem().setFrontendUrl("https://stirling.example");
+ return new ConnectedAccountController(service, properties);
+ }
+
+ @Test
+ void neverEchoesTheProviderErrorText() {
+ String page =
+ controller()
+ .callback(
+ "microsoft",
+ null,
+ null,
+ "server_error",
+ "Visit evil.example to fix your account",
+ null)
+ .getBody();
+
+ assertThat(page).doesNotContain("evil.example").doesNotContain("server_error");
+ assertThat(page).contains("The provider refused the sign-in.");
+ }
+
+ @Test
+ void neverEchoesAnUnknownProviderSegment() {
+ String page = controller().callback("evilprovider", "c", "s", null, null, null).getBody();
+
+ assertThat(page).doesNotContain("evilprovider");
+ assertThat(page).contains("The account could not be connected.");
+ }
+
+ @Test
+ void hidesTheExceptionDetailWhenConnectingFails() throws Exception {
+ when(service.completeConnect(any(), anyString(), anyString(), any()))
+ .thenThrow(new IOException("token endpoint said secret-detail"));
+
+ String page =
+ controller().callback("microsoft", "code", "state", null, null, "n").getBody();
+
+ assertThat(page).doesNotContain("secret-detail");
+ assertThat(page).contains("The account could not be connected.");
+ }
+
+ @Test
+ void redirectUrisUseTheConfiguredFrontendUrl() {
+ assertThat(controller().redirectUris(new User()))
+ .containsEntry(
+ "microsoft",
+ "https://stirling.example/api/v1/connected-accounts/callback/microsoft")
+ .containsEntry(
+ "google",
+ "https://stirling.example/api/v1/connected-accounts/callback/google");
+ }
+
+ @Test
+ void explainsWhichProviderIsNotSetUp() {
+ ResponseStatusException failure =
+ assertThrows(
+ ResponseStatusException.class,
+ () -> controller().connect("google", new User()));
+
+ assertThat(failure.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
+ assertThat(failure.getReason())
+ .isEqualTo("Google account connections are not set up on this server.");
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountServiceTest.java
new file mode 100644
index 0000000000..f5aab6809e
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/ConnectedAccountServiceTest.java
@@ -0,0 +1,228 @@
+package stirling.software.proprietary.connectedaccount;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.net.URI;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.integration.crypto.TestCredentialKey;
+import stirling.software.proprietary.policy.microsoft.FakeGraphServer;
+import stirling.software.proprietary.security.model.User;
+
+class ConnectedAccountServiceTest {
+
+ private static final String REDIRECT =
+ "https://stirling.example/api/v1/connected-accounts/callback/microsoft";
+
+ private FakeGraphServer microsoft;
+ private InMemoryConnectedAccounts store;
+ private ApplicationProperties properties;
+ private ConnectedAccountService service;
+ private User pat;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ TestCredentialKey.install();
+ microsoft = new FakeGraphServer();
+ properties = FakeGraphServer.serverApp();
+ store = new InMemoryConnectedAccounts();
+ service =
+ new ConnectedAccountService(
+ store.repository,
+ List.of(new MicrosoftOAuthClient(properties, microsoft.endpoints())));
+ pat = new User();
+ pat.setId(5L);
+ }
+
+ @AfterEach
+ void tearDown() {
+ microsoft.close();
+ }
+
+ @Test
+ void connectingStoresTheAccountWithItsRefreshToken() throws Exception {
+ ConnectedAccountService.ConnectStart start =
+ service.startConnect(pat, CloudProvider.MICROSOFT, REDIRECT);
+ Map<String, String> query = query(start.authorizationUrl());
+
+ assertThat(start.authorizationUrl()).startsWith(microsoft.baseUrl() + "/login/common/");
+ assertThat(query).containsEntry("client_id", "client-1");
+ assertThat(query).containsEntry("code_challenge_method", "S256");
+ assertThat(query.get("scope")).contains("offline_access").contains("Files.ReadWrite.All");
+
+ ConnectedAccount account =
+ service.completeConnect(
+ CloudProvider.MICROSOFT,
+ query.get("state"),
+ FakeGraphServer.GOOD_CODE,
+ start.nonce());
+
+ assertThat(account.getOwnerUserId()).isEqualTo(5L);
+ assertThat(account.getEmail()).isEqualTo("[email protected]");
+ assertThat(account.getTenantId()).isEqualTo("tenant-guid");
+ assertThat(account.getRefreshToken()).isEqualTo("rt-1");
+ assertThat(account.getStatus()).isEqualTo(ConnectedAccount.STATUS_CONNECTED);
+ Map<String, String> exchange = microsoft.tokenForms.getLast();
+ assertThat(exchange.get("code_verifier")).isNotBlank();
+ assertThat(exchange).containsEntry("redirect_uri", REDIRECT);
+ }
+
+ @Test
+ void aSignInFinishedInAnotherBrowserIsRejected() {
+ ConnectedAccountService.ConnectStart start =
+ service.startConnect(pat, CloudProvider.MICROSOFT, REDIRECT);
+ String state = query(start.authorizationUrl()).get("state");
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ service.completeConnect(
+ CloudProvider.MICROSOFT, state, FakeGraphServer.GOOD_CODE, null));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ service.completeConnect(
+ CloudProvider.MICROSOFT,
+ state,
+ FakeGraphServer.GOOD_CODE,
+ "someone-elses-nonce"));
+ assertThat(store.rows).isEmpty();
+ }
+
+ @Test
+ void aForgedOrMismatchedStateIsRejected() {
+ ConnectedAccountService.ConnectStart start =
+ service.startConnect(pat, CloudProvider.MICROSOFT, REDIRECT);
+ String state = query(start.authorizationUrl()).get("state");
+ String tampered =
+ state.substring(0, state.length() - 2) + (state.endsWith("A") ? "BB" : "AA");
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ service.completeConnect(
+ CloudProvider.MICROSOFT,
+ tampered,
+ FakeGraphServer.GOOD_CODE,
+ start.nonce()));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ service.completeConnect(
+ CloudProvider.GOOGLE,
+ state,
+ FakeGraphServer.GOOD_CODE,
+ start.nonce()));
+ }
+
+ @Test
+ void reconnectingUpdatesTheSameAccount() throws Exception {
+ connect();
+ connect();
+ assertThat(store.rows).hasSize(1);
+ assertThat(store.rows.values().iterator().next().getRefreshToken()).isEqualTo("rt-2");
+ }
+
+ @Test
+ void accessTokensAreCachedAndRefreshTokensRotate() throws Exception {
+ ConnectedAccount account = connect();
+ int requestsAfterConnect = microsoft.tokenRequests.get();
+
+ String first = service.accessToken(account.getId(), List.of());
+ assertThat(microsoft.tokenRequests.get()).isEqualTo(requestsAfterConnect);
+
+ String sharePoint =
+ service.accessToken(
+ account.getId(), List.of("https://contoso.sharepoint.com/.default"));
+ assertThat(sharePoint).isNotEqualTo(first);
+ assertThat(microsoft.tokenForms.getLast().get("scope"))
+ .isEqualTo("offline_access https://contoso.sharepoint.com/.default");
+ assertThat(store.rows.get(account.getId()).getRefreshToken()).isEqualTo("rt-2");
+ }
+
+ @Test
+ void aRevokedGrantAsksTheUserToReconnect() throws Exception {
+ ConnectedAccount account = connect();
+ microsoft.revokedRefreshTokens.add("rt-1");
+
+ AccountReconnectRequiredException failure =
+ assertThrows(
+ AccountReconnectRequiredException.class,
+ () -> service.accessToken(account.getId(), List.of("Sites.Read.All")));
+
+ assertThat(failure.getMessage()).contains("[email protected]").contains("sign in again");
+ ConnectedAccount stored = store.rows.get(account.getId());
+ assertThat(stored.getStatus()).isEqualTo(ConnectedAccount.STATUS_NEEDS_RECONNECT);
+ assertThat(stored.getLastError()).contains("AADSTS700082").doesNotContain("Trace ID");
+ int before = microsoft.tokenRequests.get();
+ assertThrows(
+ AccountReconnectRequiredException.class,
+ () -> service.accessToken(account.getId(), List.of("Sites.Read.All")));
+ assertThat(microsoft.tokenRequests.get()).isEqualTo(before);
+ }
+
+ @Test
+ void connectionsCanBeTurnedOffByTheAdmin() {
+ properties.getPremium().getProFeatures().getMicrosoft().setAllowAccountConnections(false);
+ assertThat(service.isAvailable(CloudProvider.MICROSOFT)).isFalse();
+ assertThrows(
+ IllegalStateException.class,
+ () -> service.startConnect(pat, CloudProvider.MICROSOFT, REDIRECT));
+ }
+
+ @Test
+ void onlyTheOwnerCanDisconnect() throws Exception {
+ ConnectedAccount account = connect();
+ User other = new User();
+ other.setId(9L);
+
+ assertThrows(
+ IllegalArgumentException.class, () -> service.disconnect(other, account.getId()));
+ service.disconnect(pat, account.getId());
+ assertThat(store.rows).isEmpty();
+ }
+
+ @Test
+ void removingAUsersAccountsDropsTheirCachedTokens() throws Exception {
+ ConnectedAccount account = connect();
+ service.accessToken(account.getId(), List.of());
+
+ service.removeAllFor(pat.getId());
+
+ assertThat(store.rows).isEmpty();
+ assertThrows(
+ AccountReconnectRequiredException.class,
+ () -> service.accessToken(account.getId(), List.of()));
+ }
+
+ private ConnectedAccount connect() throws Exception {
+ ConnectedAccountService.ConnectStart start =
+ service.startConnect(pat, CloudProvider.MICROSOFT, REDIRECT);
+ return service.completeConnect(
+ CloudProvider.MICROSOFT,
+ query(start.authorizationUrl()).get("state"),
+ FakeGraphServer.GOOD_CODE,
+ start.nonce());
+ }
+
+ private static Map<String, String> query(String url) {
+ Map<String, String> params = new HashMap<>();
+ for (String pair : URI.create(url).getRawQuery().split("&")) {
+ int eq = pair.indexOf('=');
+ params.put(
+ pair.substring(0, eq),
+ URLDecoder.decode(pair.substring(eq + 1), StandardCharsets.UTF_8));
+ }
+ return params;
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClientTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClientTest.java
new file mode 100644
index 0000000000..5b9912c7e5
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/GoogleOAuthClientTest.java
@@ -0,0 +1,47 @@
+package stirling.software.proprietary.connectedaccount;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.policy.google.GoogleEndpoints;
+
+class GoogleOAuthClientTest {
+
+ private static GoogleOAuthClient client(String accountScope) {
+ ApplicationProperties properties = new ApplicationProperties();
+ ApplicationProperties.Premium.ProFeatures.GoogleDrive app =
+ properties.getPremium().getProFeatures().getGoogleDrive();
+ app.setEnabled(true);
+ app.setClientId("google-client");
+ app.setClientSecret("google-secret");
+ app.setAccountScope(accountScope);
+ return new GoogleOAuthClient(properties, mock(GoogleEndpoints.class));
+ }
+
+ @Test
+ void requestsTheConfiguredScope() {
+ GoogleOAuthClient client = client(" drive.file ");
+
+ assertTrue(client.available());
+ assertEquals("https://www.googleapis.com/auth/drive.file", client.driveScope());
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @ValueSource(strings = {"drive.full", "https://www.googleapis.com/auth/drive"})
+ void anUnknownScopeTurnsConnectionsOffInsteadOfAskingForAllOfDrive(String accountScope) {
+ GoogleOAuthClient client = client(accountScope);
+
+ assertFalse(client.available());
+ assertThrows(IllegalStateException.class, client::driveScope);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/InMemoryConnectedAccounts.java b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/InMemoryConnectedAccounts.java
new file mode 100644
index 0000000000..dd653a6bd0
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/connectedaccount/InMemoryConnectedAccounts.java
@@ -0,0 +1,86 @@
+package stirling.software.proprietary.connectedaccount;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.time.LocalDateTime;
+import java.util.Comparator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+public final class InMemoryConnectedAccounts {
+
+ public final Map<Long, ConnectedAccount> rows = new ConcurrentHashMap<>();
+ public final ConnectedAccountRepository repository = mock(ConnectedAccountRepository.class);
+ private final AtomicLong ids = new AtomicLong();
+
+ public InMemoryConnectedAccounts() {
+ when(repository.save(any(ConnectedAccount.class)))
+ .thenAnswer(
+ call -> {
+ ConnectedAccount account = call.getArgument(0);
+ if (account.getId() == null) {
+ account.setId(ids.incrementAndGet());
+ account.setCreatedAt(LocalDateTime.now());
+ }
+ rows.put(account.getId(), account);
+ return account;
+ });
+ when(repository.findById(anyLong()))
+ .thenAnswer(call -> Optional.ofNullable(rows.get(call.<Long>getArgument(0))));
+ when(repository.findByOwnerUserIdAndProviderAndExternalId(
+ anyLong(), anyString(), anyString()))
+ .thenAnswer(
+ call ->
+ rows.values().stream()
+ .filter(
+ a ->
+ a.getOwnerUserId()
+ .equals(call.getArgument(0))
+ && a.getProvider()
+ .equals(call.getArgument(1))
+ && a.getExternalId()
+ .equals(
+ call.getArgument(
+ 2)))
+ .findFirst());
+ when(repository.findByOwnerUserIdOrderByCreatedAtAsc(anyLong()))
+ .thenAnswer(
+ call ->
+ rows.values().stream()
+ .filter(a -> a.getOwnerUserId().equals(call.getArgument(0)))
+ .sorted(Comparator.comparing(ConnectedAccount::getId))
+ .toList());
+ doAnswer(
+ call -> {
+ rows.remove(call.<ConnectedAccount>getArgument(0).getId());
+ return null;
+ })
+ .when(repository)
+ .delete(any(ConnectedAccount.class));
+ doAnswer(
+ call -> {
+ rows.values()
+ .removeIf(a -> a.getOwnerUserId().equals(call.getArgument(0)));
+ return null;
+ })
+ .when(repository)
+ .deleteByOwnerUserId(anyLong());
+ }
+
+ public ConnectedAccount add(long ownerUserId, CloudProvider provider, String refreshToken) {
+ ConnectedAccount account = new ConnectedAccount();
+ account.setOwnerUserId(ownerUserId);
+ account.setProvider(provider.id());
+ account.setExternalId("ext-" + ids.get());
+ account.setEmail("[email protected]");
+ account.setRefreshToken(refreshToken);
+ return repository.save(account);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/integration/crypto/TestCredentialKey.java b/app/proprietary/src/test/java/stirling/software/proprietary/integration/crypto/TestCredentialKey.java
new file mode 100644
index 0000000000..8e654e8af1
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/integration/crypto/TestCredentialKey.java
@@ -0,0 +1,20 @@
+package stirling.software.proprietary.integration.crypto;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+
+public final class TestCredentialKey {
+
+ private TestCredentialKey() {}
+
+ public static void install() {
+ try {
+ KeyGenerator generator = KeyGenerator.getInstance("AES");
+ generator.init(256);
+ SecretKey key = generator.generateKey();
+ CredentialEncryption.initialiseForTesting(key);
+ } catch (java.security.NoSuchAlgorithmException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
index 1c51dc71f2..af503a4903 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
@@ -256,7 +256,8 @@ class PolicyControllerTest {
}
private static PolicyRunHandle handle(String runId) {
- PolicyRun run = new PolicyRun(runId, null, definitionWithStep(), null, null, null, null);
+ PolicyRun run =
+ new PolicyRun(runId, null, definitionWithStep(), null, null, null, null, null);
return new PolicyRunHandle(runId, CompletableFuture.completedFuture(run));
}
@@ -537,7 +538,8 @@ class PolicyControllerTest {
@DisplayName("returns the run view when present")
void found() {
PolicyRun run =
- new PolicyRun("run-3", null, definitionWithStep(), null, null, null, null);
+ new PolicyRun(
+ "run-3", null, definitionWithStep(), null, null, null, null, null);
when(runRegistry.get("run-3")).thenReturn(run);
when(jobOwnershipService.extractJobId("run-3")).thenReturn("run-3");
when(jobOwnershipService.createScopedJobKey("run-3")).thenReturn("run-3");
@@ -599,13 +601,28 @@ class PolicyControllerTest {
@DisplayName("excludes ad-hoc runs and runs owned by others")
void filtersRuns() {
PolicyRun adHoc =
- new PolicyRun("adhoc", null, definitionWithStep(), null, null, null, null);
+ new PolicyRun(
+ "adhoc", null, definitionWithStep(), null, null, null, null, null);
PolicyRun ownedStored =
new PolicyRun(
- "owned", "policy-A", definitionWithStep(), null, null, null, null);
+ "owned",
+ "policy-A",
+ definitionWithStep(),
+ null,
+ null,
+ null,
+ null,
+ null);
PolicyRun otherStored =
new PolicyRun(
- "other", "policy-B", definitionWithStep(), null, null, null, null);
+ "other",
+ "policy-B",
+ definitionWithStep(),
+ null,
+ null,
+ null,
+ null,
+ null);
when(runRegistry.all()).thenReturn(List.of(adHoc, ownedStored, otherStored));
// ownedByCurrentUser: strip then re-apply scope reproduces the key only for the owned
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java
index 75a7c384b4..0d58b6113e 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/engine/PolicyRunRegistryTest.java
@@ -103,6 +103,7 @@ class PolicyRunRegistryTest {
null,
null,
null,
+ null,
null);
registry.register(run);
return run;
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/FakeGoogleServer.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/FakeGoogleServer.java
new file mode 100644
index 0000000000..9a7d0987c9
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/FakeGoogleServer.java
@@ -0,0 +1,400 @@
+package stirling.software.proprietary.policy.google;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.MessageDigest;
+import java.security.Signature;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+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.ArrayNode;
+import tools.jackson.databind.node.ObjectNode;
+
+public final class FakeGoogleServer implements AutoCloseable {
+
+ public static final String GOOD_CODE = "google-code";
+ public static final String CLIENT_SECRET = "google-secret";
+ public static final String SERVICE_EMAIL = "[email protected]";
+
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final Pattern QUERY_NAME = Pattern.compile("name = '((?:[^'\\\\]|\\\\.)*)'");
+ private static final Pattern QUERY_PARENT = Pattern.compile("'([^']+)' in parents");
+
+ public final Map<String, Item> items = new ConcurrentHashMap<>();
+ public final KeyPair serviceAccountKeys;
+ public final List<JsonNode> assertions = new CopyOnWriteArrayList<>();
+ public final AtomicInteger uploads = new AtomicInteger();
+ private final AtomicInteger ids = new AtomicInteger();
+ private final java.util.Set<String> validTokens = ConcurrentHashMap.newKeySet();
+ private final Map<String, Resumable> resumables = new ConcurrentHashMap<>();
+ private final HttpServer server;
+
+ public static final class Item {
+ public final String id;
+ public final String parent;
+ public final String name;
+ public final boolean folder;
+ public volatile byte[] content;
+ public volatile int version = 1;
+ public volatile boolean trashed;
+
+ Item(String id, String parent, String name, boolean folder, byte[] content) {
+ this.id = id;
+ this.parent = parent;
+ this.name = name;
+ this.folder = folder;
+ this.content = content;
+ }
+ }
+
+ private record Resumable(String parent, String name, ByteArrayOutputStream received) {}
+
+ public FakeGoogleServer() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ serviceAccountKeys = generator.generateKeyPair();
+ items.put("root", new Item("root", null, "My Drive", true, null));
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext("/", this::handle);
+ server.start();
+ }
+
+ public String baseUrl() {
+ return "http://127.0.0.1:" + server.getAddress().getPort();
+ }
+
+ public static ApplicationProperties serverApp() {
+ ApplicationProperties properties = new ApplicationProperties();
+ ApplicationProperties.Premium.ProFeatures.GoogleDrive app =
+ properties.getPremium().getProFeatures().getGoogleDrive();
+ app.setEnabled(true);
+ app.setClientId("google-client");
+ app.setClientSecret(CLIENT_SECRET);
+ return properties;
+ }
+
+ public GoogleEndpoints endpoints() {
+ return new GoogleEndpoints(
+ baseUrl() + "/o/oauth2/v2/auth",
+ baseUrl() + "/token",
+ baseUrl() + "/revoke",
+ baseUrl() + "/drive/v3",
+ baseUrl() + "/upload/drive/v3");
+ }
+
+ public String serviceAccountJson() {
+ String pem =
+ "-----BEGIN PRIVATE KEY-----\n"
+ + Base64.getMimeEncoder()
+ .encodeToString(serviceAccountKeys.getPrivate().getEncoded())
+ + "\n-----END PRIVATE KEY-----\n";
+ ObjectNode key = JSON.createObjectNode();
+ key.put("type", "service_account");
+ key.put("client_email", SERVICE_EMAIL);
+ key.put("private_key", pem);
+ key.put("token_uri", "https://evil.example/token");
+ return key.toString();
+ }
+
+ public String folder(String parent, String name) {
+ String id = "fld" + ids.incrementAndGet() + "xxxxxxxx";
+ items.put(id, new Item(id, parent, name, true, null));
+ return id;
+ }
+
+ public String file(String parent, String name, String content) {
+ String id = "fil" + ids.incrementAndGet() + "xxxxxxxx";
+ items.put(id, new Item(id, parent, name, false, content.getBytes(StandardCharsets.UTF_8)));
+ return id;
+ }
+
+ public Item named(String parent, String name) {
+ return items.values().stream()
+ .filter(i -> !i.trashed && name.equals(i.name) && parent.equals(i.parent))
+ .findFirst()
+ .orElse(null);
+ }
+
+ @Override
+ public void close() {
+ server.stop(0);
+ }
+
+ private void handle(HttpExchange exchange) throws IOException {
+ try (exchange) {
+ String path = exchange.getRequestURI().getPath();
+ if (path.equals("/token")) {
+ token(exchange);
+ return;
+ }
+ if (path.equals("/revoke")) {
+ read(exchange);
+ exchange.sendResponseHeaders(200, -1);
+ return;
+ }
+ String auth = exchange.getRequestHeaders().getFirst("Authorization");
+ if (auth == null || !validTokens.contains(auth.substring(7))) {
+ json(exchange, 401, "{\"error\":{\"message\":\"Invalid Credentials\"}}");
+ return;
+ }
+ Map<String, String> query = query(exchange.getRequestURI().getRawQuery());
+ if (path.startsWith("/upload/drive/v3/files")) {
+ upload(exchange, path, query);
+ } else if (path.equals("/drive/v3/files")) {
+ list(exchange, query);
+ } else if (path.startsWith("/drive/v3/files/")) {
+ item(exchange, path.substring("/drive/v3/files/".length()), query);
+ } else {
+ json(exchange, 404, "{\"error\":{\"message\":\"not found\"}}");
+ }
+ }
+ }
+
+ private void token(HttpExchange exchange) throws IOException {
+ Map<String, String> form = query(new String(read(exchange), StandardCharsets.UTF_8));
+ String grant = form.get("grant_type");
+ if ("urn:ietf:params:oauth:grant-type:jwt-bearer".equals(grant)) {
+ JsonNode claims = verify(form.get("assertion"));
+ if (claims == null) {
+ json(
+ exchange,
+ 400,
+ "{\"error\":\"invalid_grant\",\"error_description\":\"bad sig\"}");
+ return;
+ }
+ assertions.add(claims);
+ json(exchange, 200, accessToken(null));
+ return;
+ }
+ if (!CLIENT_SECRET.equals(form.get("client_secret"))) {
+ json(exchange, 401, "{\"error\":\"invalid_client\"}");
+ return;
+ }
+ if ("authorization_code".equals(grant) && GOOD_CODE.equals(form.get("code"))) {
+ ObjectNode claims = JSON.createObjectNode();
+ claims.put("sub", "google-sub-1");
+ claims.put("email", "[email protected]");
+ claims.put("name", "Pat");
+ String idToken =
+ "e30."
+ + Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(
+ claims.toString().getBytes(StandardCharsets.UTF_8))
+ + ".sig";
+ json(exchange, 200, accessToken(idToken));
+ return;
+ }
+ if ("refresh_token".equals(grant) && "google-refresh".equals(form.get("refresh_token"))) {
+ json(exchange, 200, accessToken(null));
+ return;
+ }
+ json(exchange, 400, "{\"error\":\"invalid_grant\"}");
+ }
+
+ private String accessToken(String idToken) {
+ String token = "gtoken-" + ids.incrementAndGet();
+ validTokens.add(token);
+ ObjectNode body = JSON.createObjectNode();
+ body.put("access_token", token);
+ body.put("expires_in", 3600);
+ if (idToken != null) {
+ body.put("id_token", idToken);
+ body.put("refresh_token", "google-refresh");
+ }
+ return body.toString();
+ }
+
+ private JsonNode verify(String assertion) {
+ try {
+ String[] parts = assertion.split("\\.");
+ Signature verifier = Signature.getInstance("SHA256withRSA");
+ verifier.initVerify(serviceAccountKeys.getPublic());
+ verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.US_ASCII));
+ if (!verifier.verify(Base64.getUrlDecoder().decode(parts[2]))) {
+ return null;
+ }
+ return JSON.readTree(Base64.getUrlDecoder().decode(parts[1]));
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ private void list(HttpExchange exchange, Map<String, String> query) throws IOException {
+ String q = query.getOrDefault("q", "");
+ Matcher parentMatch = QUERY_PARENT.matcher(q);
+ String parent = parentMatch.find() ? parentMatch.group(1) : null;
+ Matcher nameMatch = QUERY_NAME.matcher(q);
+ String name = nameMatch.find() ? nameMatch.group(1).replace("\\'", "'") : null;
+ boolean foldersOnly = q.contains("mimeType = 'application/vnd.google-apps.folder'");
+ ObjectNode page = JSON.createObjectNode();
+ ArrayNode files = page.putArray("files");
+ items.values().stream()
+ .filter(i -> !i.trashed && !"root".equals(i.id))
+ .filter(i -> parent == null || parent.equals(i.parent))
+ .filter(i -> name == null || name.equals(i.name))
+ .filter(i -> !foldersOnly || i.folder)
+ .sorted((a, b) -> a.name.compareTo(b.name))
+ .forEach(i -> files.add(describe(i)));
+ json(exchange, 200, page.toString());
+ }
+
+ private void item(HttpExchange exchange, String id, Map<String, String> query)
+ throws IOException {
+ Item item = items.get(id);
+ if (item == null) {
+ json(exchange, 404, "{\"error\":{\"message\":\"File not found\"}}");
+ return;
+ }
+ if ("PATCH".equals(exchange.getRequestMethod())) {
+ JsonNode body = JSON.readTree(read(exchange));
+ item.trashed = body.path("trashed").asBoolean(false);
+ json(exchange, 200, describe(item).toString());
+ } else if ("media".equals(query.get("alt"))) {
+ exchange.sendResponseHeaders(200, item.content.length);
+ exchange.getResponseBody().write(item.content);
+ } else {
+ ObjectNode node = describe(item);
+ node.put("trashed", item.trashed);
+ json(exchange, 200, node.toString());
+ }
+ }
+
+ private void upload(HttpExchange exchange, String path, Map<String, String> query)
+ throws IOException {
+ if (path.startsWith("/upload/drive/v3/files/session-")) {
+ Resumable session = resumables.get(path.substring("/upload/drive/v3/files/".length()));
+ session.received().write(read(exchange));
+ String range = exchange.getRequestHeaders().getFirst("Content-Range");
+ long total = Long.parseLong(range.substring(range.indexOf('/') + 1));
+ if (session.received().size() < total) {
+ exchange.sendResponseHeaders(308, -1);
+ return;
+ }
+ json(
+ exchange,
+ 200,
+ describe(
+ store(
+ session.parent(),
+ session.name(),
+ session.received().toByteArray()))
+ .toString());
+ return;
+ }
+ byte[] body = read(exchange);
+ if ("resumable".equals(query.get("uploadType"))) {
+ JsonNode metadata = JSON.readTree(body);
+ String session = "session-" + ids.incrementAndGet();
+ resumables.put(
+ session,
+ new Resumable(
+ metadata.path("parents").get(0).asString(),
+ metadata.path("name").asString(),
+ new ByteArrayOutputStream()));
+ exchange.getResponseHeaders()
+ .add("Location", baseUrl() + "/upload/drive/v3/files/" + session);
+ exchange.sendResponseHeaders(200, -1);
+ return;
+ }
+ String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
+ String boundary = "--" + contentType.substring(contentType.indexOf("boundary=") + 9);
+ String text = new String(body, StandardCharsets.ISO_8859_1);
+ String[] parts = text.split(java.util.regex.Pattern.quote(boundary));
+ String metadataPart = parts[1].substring(parts[1].indexOf("\r\n\r\n") + 4).trim();
+ String contentPart = parts[2].substring(parts[2].indexOf("\r\n\r\n") + 4);
+ contentPart = contentPart.substring(0, contentPart.length() - 2);
+ JsonNode metadata = JSON.readTree(metadataPart);
+ Item stored =
+ store(
+ metadata.path("parents").get(0).asString(),
+ metadata.path("name").asString(),
+ contentPart.getBytes(StandardCharsets.ISO_8859_1));
+ json(exchange, 200, describe(stored).toString());
+ }
+
+ private Item store(String parent, String name, byte[] content) {
+ uploads.incrementAndGet();
+ String id = "fil" + ids.incrementAndGet() + "xxxxxxxx";
+ Item item = new Item(id, parent, name, false, content);
+ items.put(id, item);
+ return item;
+ }
+
+ private static ObjectNode describe(Item item) {
+ ObjectNode node = JSON.createObjectNode();
+ node.put("id", item.id);
+ node.put("name", item.name);
+ node.putArray("parents").add(item.parent == null ? "" : item.parent);
+ if (item.folder) {
+ node.put("mimeType", "application/vnd.google-apps.folder");
+ } else {
+ node.put("mimeType", "application/pdf");
+ node.put("size", String.valueOf(item.content.length));
+ node.put("md5Checksum", md5(item.content));
+ node.put("version", String.valueOf(item.version));
+ }
+ return node;
+ }
+
+ private static String md5(byte[] content) {
+ try {
+ return HexFormat.of().formatHex(MessageDigest.getInstance("MD5").digest(content));
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private static Map<String, String> query(String raw) {
+ Map<String, String> params = new HashMap<>();
+ if (raw == null) {
+ return params;
+ }
+ for (String pair : raw.split("&")) {
+ int eq = pair.indexOf('=');
+ if (eq > 0) {
+ params.put(
+ URLDecoder.decode(pair.substring(0, eq), StandardCharsets.UTF_8),
+ URLDecoder.decode(pair.substring(eq + 1), StandardCharsets.UTF_8));
+ }
+ }
+ return params;
+ }
+
+ private static byte[] read(HttpExchange exchange) throws IOException {
+ try (InputStream in = exchange.getRequestBody()) {
+ return in.readAllBytes();
+ }
+ }
+
+ private static void json(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);
+ try (OutputStream out = exchange.getResponseBody()) {
+ out.write(bytes);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/GoogleCloudDriveContractTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/GoogleCloudDriveContractTest.java
new file mode 100644
index 0000000000..b410770ea4
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/GoogleCloudDriveContractTest.java
@@ -0,0 +1,100 @@
+package stirling.software.proprietary.policy.google;
+
+import static org.mockito.Mockito.mock;
+
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.AfterEach;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import stirling.software.proprietary.access.service.OwnershipService;
+import stirling.software.proprietary.connectedaccount.CloudProvider;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountAccess;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
+import stirling.software.proprietary.connectedaccount.GoogleOAuthClient;
+import stirling.software.proprietary.connectedaccount.InMemoryConnectedAccounts;
+import stirling.software.proprietary.integration.crypto.TestCredentialKey;
+import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
+import stirling.software.proprietary.integration.service.ConnectionLookup;
+import stirling.software.proprietary.policy.remote.CloudDrive;
+import stirling.software.proprietary.policy.remote.CloudDriveContract;
+import stirling.software.proprietary.policy.remote.CloudDriveFixtures;
+import stirling.software.proprietary.security.service.UserService;
+
+class GoogleCloudDriveContractTest extends CloudDriveContract<GoogleDriveConfig, GoogleFile> {
+
+ private FakeGoogleServer google;
+ private long accountId;
+ private final Map<String, String> folders = new HashMap<>();
+
+ @Override
+ protected CloudDrive<GoogleDriveConfig, GoogleFile> drive() throws Exception {
+ TestCredentialKey.install();
+ google = new FakeGoogleServer();
+ InMemoryConnectedAccounts accounts = new InMemoryConnectedAccounts();
+ accountId = accounts.add(5L, CloudProvider.GOOGLE, "google-refresh").getId();
+ CloudDriveFixtures.signIn(CloudDriveFixtures.user(5L, "pat"));
+ ConnectedAccountService connected =
+ new ConnectedAccountService(
+ accounts.repository,
+ List.of(
+ new GoogleOAuthClient(
+ FakeGoogleServer.serverApp(), google.endpoints())));
+ ConnectionLookup lookup =
+ new ConnectionLookup(
+ mock(IntegrationConfigRepository.class),
+ mock(OwnershipService.class),
+ mock(UserService.class));
+ String scans = google.folder("root", "Scans");
+ folders.put("Inbox", google.folder(scans, "Inbox"));
+ folders.put("Done", google.folder(scans, "Done"));
+ return new GoogleCloudDrive(
+ new GoogleConnectionResolver(lookup, new ConnectedAccountAccess(connected, lookup)),
+ new GoogleDriveClient(
+ google.endpoints(),
+ new GoogleTokenProvider(google.endpoints(), connected)));
+ }
+
+ @AfterEach
+ void stop() {
+ SecurityContextHolder.clearContext();
+ google.close();
+ }
+
+ @Override
+ protected String type() {
+ return "googledrive";
+ }
+
+ @Override
+ protected Map<String, Object> options(String folder, Map<String, Object> extra) {
+ Map<String, Object> options = new HashMap<>(extra);
+ options.put("accountId", accountId);
+ String id = folders.get(folder);
+ options.put(
+ "directory",
+ id == null ? "Scans/" + folder : "https://drive.google.com/drive/folders/" + id);
+ return options;
+ }
+
+ @Override
+ protected void put(String folder, String name, String content) {
+ String parent = folders.get(folder);
+ FakeGoogleServer.Item existing = google.named(parent, name);
+ if (existing == null) {
+ google.file(parent, name, content);
+ } else {
+ existing.content = content.getBytes(StandardCharsets.UTF_8);
+ existing.version++;
+ }
+ }
+
+ @Override
+ protected String content(String folder, String name) {
+ FakeGoogleServer.Item item = google.named(folders.get(folder), name);
+ return item == null ? null : new String(item.content, StandardCharsets.UTF_8);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/GoogleDriveTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/GoogleDriveTest.java
new file mode 100644
index 0000000000..82c22009c4
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/google/GoogleDriveTest.java
@@ -0,0 +1,207 @@
+package stirling.software.proprietary.policy.google;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.ledgerContext;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.named;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.signIn;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.user;
+
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Random;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.core.io.Resource;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import stirling.software.proprietary.access.service.OwnershipService;
+import stirling.software.proprietary.connectedaccount.CloudProvider;
+import stirling.software.proprietary.connectedaccount.ConnectedAccount;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountAccess;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
+import stirling.software.proprietary.connectedaccount.GoogleOAuthClient;
+import stirling.software.proprietary.connectedaccount.InMemoryConnectedAccounts;
+import stirling.software.proprietary.integration.crypto.TestCredentialKey;
+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.integration.service.ConnectionLookup;
+import stirling.software.proprietary.policy.input.ResolveContext;
+import stirling.software.proprietary.policy.input.ResolvedInput;
+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
+import stirling.software.proprietary.policy.model.InputSpec;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.output.GoogleDriveOutputSink;
+import stirling.software.proprietary.policy.output.OutputDelivery;
+import stirling.software.proprietary.security.service.UserService;
+
+import tools.jackson.databind.ObjectMapper;
+
+class GoogleDriveTest {
+
+ private static final String POLICY = "p1";
+ private static final long CONNECTION = 11L;
+
+ private FakeGoogleServer google;
+ private InMemoryConnectedAccounts accounts;
+ private IntegrationConfigRepository connections;
+ private GoogleDriveInputSource source;
+ private GoogleDriveOutputSink sink;
+ private ResolveContext ctx;
+ private ConnectedAccount account;
+ private String inbox;
+ private final OwnershipService ownership = mock(OwnershipService.class);
+
+ @BeforeEach
+ void setUp() throws Exception {
+ TestCredentialKey.install();
+ google = new FakeGoogleServer();
+ accounts = new InMemoryConnectedAccounts();
+ ConnectedAccountService connected =
+ new ConnectedAccountService(
+ accounts.repository,
+ List.of(
+ new GoogleOAuthClient(
+ FakeGoogleServer.serverApp(), google.endpoints())));
+ GoogleDriveClient drive =
+ new GoogleDriveClient(
+ google.endpoints(), new GoogleTokenProvider(google.endpoints(), connected));
+ UserService users = mock(UserService.class);
+ connections = mock(IntegrationConfigRepository.class);
+ ConnectionLookup lookup = new ConnectionLookup(connections, ownership, users);
+ GoogleConnectionResolver resolver =
+ new GoogleConnectionResolver(lookup, new ConnectedAccountAccess(connected, lookup));
+ GoogleCloudDrive cloud = new GoogleCloudDrive(resolver, drive);
+ InProcessProcessedLedger ledger = new InProcessProcessedLedger();
+ source = new GoogleDriveInputSource(cloud);
+ sink = new GoogleDriveOutputSink(cloud, ledger);
+ ctx = ledgerContext(ledger, POLICY);
+ account = accounts.add(5L, CloudProvider.GOOGLE, "google-refresh");
+ signIn(user(5L, "pat"));
+ String scans = google.folder("root", "Scans");
+ inbox = google.folder(scans, "Inbox");
+ }
+
+ @AfterEach
+ void tearDown() {
+ SecurityContextHolder.clearContext();
+ google.close();
+ }
+
+ private Map<String, Object> mine(String directory) {
+ return Map.of("accountId", account.getId(), "directory", directory);
+ }
+
+ @Test
+ void aMyDrivePathResolvesAndConsumeBinsTheProcessedFile() throws Exception {
+ String id = google.file(inbox, "scan.pdf", "pdf bytes");
+
+ Map<String, Object> options = new HashMap<>(mine("Scans/Inbox"));
+ options.put("mode", "consume");
+ List<ResolvedInput> work = source.resolve(new InputSpec("googledrive", options), ctx);
+
+ assertThat(work).hasSize(1);
+ Resource resource = work.getFirst().inputs().primary().getFirst();
+ assertThat(resource.getFilename()).isEqualTo("scan.pdf");
+ try (InputStream in = resource.getInputStream()) {
+ assertThat(new String(in.readAllBytes(), StandardCharsets.UTF_8))
+ .isEqualTo("pdf bytes");
+ }
+ work.getFirst().onComplete().accept(true);
+ assertThat(google.items.get(id).trashed).isTrue();
+ }
+
+ @Test
+ void aFolderLinkWorksAndAMissingFolderIsAnError() throws Exception {
+ google.file(inbox, "a.pdf", "a");
+ String link = "https://drive.google.com/drive/folders/" + inbox + "?usp=sharing";
+
+ assertThat(source.resolve(new InputSpec("googledrive", mine(link)), ctx)).hasSize(1);
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> source.validate(new InputSpec("googledrive", mine("Scans/Nope"))));
+ }
+
+ @Test
+ void aFolderNameThatLooksLikeAnIdIsStillAPath() throws Exception {
+ google.file(google.folder("root", "Statements"), "a.pdf", "a");
+
+ assertThat(source.resolve(new InputSpec("googledrive", mine("Statements")), ctx))
+ .hasSize(1);
+ }
+
+ @Test
+ void largeOutputsUseAResumableUpload() throws Exception {
+ byte[] large = new byte[(int) GoogleDriveClient.SIMPLE_UPLOAD_LIMIT + 1234];
+ new Random(3).nextBytes(large);
+
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY),
+ List.of(named(large, "big.pdf")),
+ new OutputSpec("googledrive", mine("Scans/Inbox")));
+
+ assertThat(google.named(inbox, "big.pdf").content).isEqualTo(large);
+ }
+
+ @Test
+ void aServiceAccountSignsItsOwnAssertionAndActsAsTheSubject() throws Exception {
+ when(ownership.canUse(any(), any(), any())).thenReturn(true);
+ IntegrationConfig connection = new IntegrationConfig();
+ connection.setId(CONNECTION);
+ connection.setName("Workspace bot");
+ connection.setIntegrationType(IntegrationType.GOOGLE_WORKSPACE);
+ connection.setEnabled(true);
+ connection.setConfig(
+ new ObjectMapper()
+ .createObjectNode()
+ .put("credentialsJson", google.serviceAccountJson())
+ .put("subject", "[email protected]")
+ .toString());
+ when(connections.findById(CONNECTION)).thenReturn(Optional.of(connection));
+ google.file(inbox, "org.pdf", "org");
+
+ List<ResolvedInput> work =
+ source.resolve(
+ new InputSpec(
+ "googledrive",
+ Map.of(
+ "connectionId",
+ CONNECTION,
+ "directory",
+ "Scans/Inbox",
+ "mode",
+ "snapshot")),
+ ctx);
+
+ assertThat(work).hasSize(1);
+ assertThat(google.assertions).hasSize(1);
+ assertThat(google.assertions.getFirst().path("iss").asString())
+ .isEqualTo(FakeGoogleServer.SERVICE_EMAIL);
+ assertThat(google.assertions.getFirst().path("sub").asString())
+ .isEqualTo("[email protected]");
+ assertThat(google.assertions.getFirst().path("aud").asString())
+ .isEqualTo(google.baseUrl() + "/token");
+ }
+
+ @Test
+ void aServiceAccountKeyWithoutAPrivateKeyIsRejected() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ GoogleDriveConfig.serviceAccount(
+ Map.of("credentialsJson", "{\"client_email\":\"x@y\"}")));
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> GoogleDriveConfig.serviceAccount(Map.of("credentialsJson", "not json")));
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/FakeGraphServer.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/FakeGraphServer.java
new file mode 100644
index 0000000000..cdc590f770
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/FakeGraphServer.java
@@ -0,0 +1,441 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+
+import stirling.software.common.model.ApplicationProperties;
+
+import tools.jackson.databind.ObjectMapper;
+import tools.jackson.databind.node.ArrayNode;
+import tools.jackson.databind.node.ObjectNode;
+
+public final class FakeGraphServer implements AutoCloseable {
+
+ public static final String USER = "[email protected]";
+ public static final String DRIVE = "drive-1";
+ public static final String APP_TOKEN = "fake-token";
+ public static final String USER_TOKEN_PREFIX = "user-token-";
+ public static final String GOOD_CODE = "good-code";
+
+ private static final ObjectMapper JSON = new ObjectMapper();
+
+ public final Map<String, byte[]> files = new ConcurrentHashMap<>();
+ public final Map<String, Integer> versions = new ConcurrentHashMap<>();
+ public final List<String> authorizedOffGraph = new CopyOnWriteArrayList<>();
+ public final AtomicInteger tokenRequests = new AtomicInteger();
+ public final AtomicInteger throttleNext = new AtomicInteger();
+ public final Set<String> revokedRefreshTokens = ConcurrentHashMap.newKeySet();
+ public final List<Map<String, String>> tokenForms = new CopyOnWriteArrayList<>();
+ private final AtomicInteger refreshSerial = new AtomicInteger();
+ private final AtomicInteger accessSerial = new AtomicInteger();
+ private final Set<String> validUserTokens = ConcurrentHashMap.newKeySet();
+ private final Map<String, Session> sessions = new ConcurrentHashMap<>();
+ private final HttpServer server;
+
+ private record Session(String path, ByteArrayOutputStream received) {}
+
+ public FakeGraphServer() throws IOException {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext("/", this::handle);
+ server.start();
+ }
+
+ public String baseUrl() {
+ return "http://127.0.0.1:" + server.getAddress().getPort();
+ }
+
+ public static ApplicationProperties serverApp() {
+ ApplicationProperties properties = new ApplicationProperties();
+ ApplicationProperties.Premium.ProFeatures.Microsoft app =
+ properties.getPremium().getProFeatures().getMicrosoft();
+ app.setEnabled(true);
+ app.setClientId("client-1");
+ app.setClientSecret("server-secret");
+ return properties;
+ }
+
+ public GraphEndpoints endpoints() {
+ return new GraphEndpoints(baseUrl() + "/v1.0", baseUrl() + "/login");
+ }
+
+ public void put(String path, String content) {
+ put(path, content.getBytes(StandardCharsets.UTF_8));
+ }
+
+ public void put(String path, byte[] content) {
+ files.put(path, content);
+ versions.merge(path, 1, Integer::sum);
+ }
+
+ public String content(String path) {
+ byte[] content = files.get(path);
+ return content == null ? null : new String(content, StandardCharsets.UTF_8);
+ }
+
+ public static String id(String path) {
+ return "id-"
+ + Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(path.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private static String pathOf(String id) {
+ return new String(Base64.getUrlDecoder().decode(id.substring(3)), StandardCharsets.UTF_8);
+ }
+
+ public static String folderLink(String path) {
+ return "https://contoso.sharepoint.com/:f:/s/Finance/" + id(path);
+ }
+
+ @Override
+ public void close() {
+ server.stop(0);
+ }
+
+ private void handle(HttpExchange exchange) throws IOException {
+ try (exchange) {
+ String path = exchange.getRequestURI().getPath();
+ if (path.startsWith("/login/")) {
+ token(exchange);
+ return;
+ }
+ if (!path.startsWith("/v1.0/")) {
+ if (exchange.getRequestHeaders().containsKey("Authorization")) {
+ authorizedOffGraph.add(path);
+ }
+ offGraph(exchange, path);
+ return;
+ }
+ String auth = exchange.getRequestHeaders().getFirst("Authorization");
+ boolean app = ("Bearer " + APP_TOKEN).equals(auth);
+ boolean user = auth != null && validUserTokens.contains(auth.substring(7));
+ if (!app && !user) {
+ json(exchange, 401, error("InvalidAuthenticationToken", "no token"));
+ return;
+ }
+ if (throttleNext.getAndUpdate(n -> Math.max(0, n - 1)) > 0) {
+ exchange.getResponseHeaders().add("Retry-After", "0");
+ json(exchange, 429, error("activityLimitReached", "slow down"));
+ return;
+ }
+ graph(exchange, path.substring("/v1.0".length()), user);
+ }
+ }
+
+ private void token(HttpExchange exchange) throws IOException {
+ tokenRequests.incrementAndGet();
+ Map<String, String> form = form(new String(read(exchange), StandardCharsets.UTF_8));
+ tokenForms.add(form);
+ String grant = form.get("grant_type");
+ if ("client_credentials".equals(grant)) {
+ json(exchange, 200, "{\"access_token\":\"" + APP_TOKEN + "\",\"expires_in\":3600}");
+ return;
+ }
+ if (!"server-secret".equals(form.get("client_secret"))) {
+ json(
+ exchange,
+ 401,
+ "{\"error\":\"invalid_client\",\"error_description\":\"bad secret\"}");
+ return;
+ }
+ if ("authorization_code".equals(grant)) {
+ if (!GOOD_CODE.equals(form.get("code")) || form.get("code_verifier") == null) {
+ json(exchange, 400, "{\"error\":\"invalid_grant\"}");
+ return;
+ }
+ json(exchange, 200, userTokens(true));
+ return;
+ }
+ if ("refresh_token".equals(grant)) {
+ if (revokedRefreshTokens.contains(form.get("refresh_token"))) {
+ json(
+ exchange,
+ 400,
+ "{\"error\":\"invalid_grant\",\"error_description\":\"AADSTS700082: The"
+ + " refresh token has expired.\\nTrace ID: 1\"}");
+ return;
+ }
+ json(exchange, 200, userTokens(false));
+ return;
+ }
+ json(exchange, 400, "{\"error\":\"unsupported_grant_type\"}");
+ }
+
+ private String userTokens(boolean withIdentity) {
+ String access = USER_TOKEN_PREFIX + accessSerial.incrementAndGet();
+ validUserTokens.add(access);
+ ObjectNode body = JSON.createObjectNode();
+ body.put("access_token", access);
+ body.put("refresh_token", "rt-" + refreshSerial.incrementAndGet());
+ body.put("expires_in", 3600);
+ body.put("scope", "Files.ReadWrite.All User.Read");
+ if (withIdentity) {
+ ObjectNode claims = JSON.createObjectNode();
+ claims.put("oid", "user-oid");
+ claims.put("tid", "tenant-guid");
+ claims.put("preferred_username", "[email protected]");
+ claims.put("name", "Pat Example");
+ body.put(
+ "id_token",
+ "e30."
+ + Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(
+ claims.toString().getBytes(StandardCharsets.UTF_8))
+ + ".sig");
+ }
+ return body.toString();
+ }
+
+ private void graph(HttpExchange exchange, String path, boolean user) throws IOException {
+ String method = exchange.getRequestMethod();
+ if (path.equals("/users/" + USER + "/drive") || (user && path.equals("/me/drive"))) {
+ json(exchange, 200, "{\"id\":\"" + DRIVE + "\"}");
+ return;
+ }
+ if (path.startsWith("/shares/") && path.endsWith("/driveItem")) {
+ String token =
+ path.substring("/shares/u!".length(), path.length() - "/driveItem".length());
+ String url = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
+ String folderId = url.substring(url.lastIndexOf('/') + 1);
+ String folder = pathOf(folderId);
+ if (!isFolder(folder)) {
+ json(exchange, 404, error("itemNotFound", "link"));
+ return;
+ }
+ ObjectNode item = JSON.createObjectNode();
+ item.put("id", folderId);
+ item.putObject("folder").put("childCount", 1);
+ item.putObject("parentReference").put("driveId", DRIVE);
+ json(exchange, 200, item.toString());
+ return;
+ }
+ String prefix = "/drives/" + DRIVE;
+ if (!path.startsWith(prefix)) {
+ json(exchange, 404, error("itemNotFound", "drive"));
+ return;
+ }
+ Addressed target = address(path.substring(prefix.length()));
+ if (target == null) {
+ json(exchange, 404, error("itemNotFound", path));
+ return;
+ }
+ switch (target.suffix()) {
+ case "/children" -> {
+ if (!target.path().isEmpty() && !isFolder(target.path())) {
+ json(exchange, 404, error("itemNotFound", "folder"));
+ return;
+ }
+ json(exchange, 200, children(target.path()));
+ }
+ case "/content" -> {
+ if (method.equals("PUT")) {
+ if (files.containsKey(target.path())) {
+ json(exchange, 409, error("nameAlreadyExists", "taken"));
+ return;
+ }
+ put(target.path(), read(exchange));
+ json(exchange, 201, item(target.path()).toString());
+ } else if (files.containsKey(target.path())) {
+ exchange.getResponseHeaders()
+ .add("Location", baseUrl() + "/download/" + id(target.path()));
+ exchange.sendResponseHeaders(302, -1);
+ } else {
+ json(exchange, 404, error("itemNotFound", "file"));
+ }
+ }
+ case "/createUploadSession" -> {
+ read(exchange);
+ if (files.containsKey(target.path())) {
+ json(exchange, 409, error("nameAlreadyExists", "taken"));
+ return;
+ }
+ String session = "session-" + sessions.size();
+ sessions.put(session, new Session(target.path(), new ByteArrayOutputStream()));
+ json(exchange, 200, "{\"uploadUrl\":\"" + baseUrl() + "/upload/" + session + "\"}");
+ }
+ case "" -> {
+ if (!files.containsKey(target.path())) {
+ json(exchange, 404, error("itemNotFound", "item"));
+ } else if (method.equals("DELETE")) {
+ String ifMatch = exchange.getRequestHeaders().getFirst("If-Match");
+ if (ifMatch != null && !ifMatch.equals(eTag(target.path()))) {
+ json(exchange, 412, error("preconditionFailed", "changed"));
+ return;
+ }
+ files.remove(target.path());
+ exchange.sendResponseHeaders(204, -1);
+ } else {
+ json(exchange, 200, item(target.path()).toString());
+ }
+ }
+ default -> json(exchange, 404, error("itemNotFound", target.suffix()));
+ }
+ }
+
+ private record Addressed(String path, String suffix) {}
+
+ private static Addressed address(String rest) {
+ String base;
+ String remainder;
+ if (rest.startsWith("/root")) {
+ base = "";
+ remainder = rest.substring("/root".length());
+ } else if (rest.startsWith("/items/")) {
+ String afterItems = rest.substring("/items/".length());
+ int end = afterItems.length();
+ for (int i = 0; i < afterItems.length(); i++) {
+ char c = afterItems.charAt(i);
+ if (c == '/' || c == ':') {
+ end = i;
+ break;
+ }
+ }
+ base = pathOf(afterItems.substring(0, end));
+ remainder = afterItems.substring(end);
+ } else {
+ return null;
+ }
+ String path = base;
+ if (remainder.startsWith(":/")) {
+ int close = remainder.indexOf(':', 2);
+ if (close < 0) {
+ return null;
+ }
+ String relative = remainder.substring(2, close);
+ path = base.isEmpty() ? relative : base + "/" + relative;
+ remainder = remainder.substring(close + 1);
+ }
+ return new Addressed(path, remainder);
+ }
+
+ private void offGraph(HttpExchange exchange, String path) throws IOException {
+ if (path.startsWith("/download/")) {
+ byte[] content = files.get(pathOf(path.substring("/download/".length())));
+ if (content == null) {
+ exchange.sendResponseHeaders(404, -1);
+ return;
+ }
+ exchange.sendResponseHeaders(200, content.length);
+ exchange.getResponseBody().write(content);
+ return;
+ }
+ if (path.startsWith("/upload/")) {
+ Session session = sessions.get(path.substring("/upload/".length()));
+ if (session == null || exchange.getRequestMethod().equals("DELETE")) {
+ exchange.sendResponseHeaders(session == null ? 404 : 204, -1);
+ return;
+ }
+ session.received().write(read(exchange));
+ String range = exchange.getRequestHeaders().getFirst("Content-Range");
+ long total = Long.parseLong(range.substring(range.indexOf('/') + 1));
+ if (session.received().size() < total) {
+ json(exchange, 202, "{}");
+ return;
+ }
+ put(session.path(), session.received().toByteArray());
+ json(exchange, 201, item(session.path()).toString());
+ return;
+ }
+ exchange.sendResponseHeaders(404, -1);
+ }
+
+ private boolean isFolder(String folder) {
+ return folder.isEmpty()
+ || files.keySet().stream().anyMatch(p -> p.startsWith(folder + "/"));
+ }
+
+ private String children(String folder) {
+ String prefix = folder.isEmpty() ? "" : folder + "/";
+ Map<String, ObjectNode> entries = new TreeMap<>();
+ for (String path : files.keySet()) {
+ if (!path.startsWith(prefix)) {
+ continue;
+ }
+ String remainder = path.substring(prefix.length());
+ int slash = remainder.indexOf('/');
+ if (slash < 0) {
+ entries.put(remainder, item(path));
+ } else {
+ String name = remainder.substring(0, slash);
+ ObjectNode node = JSON.createObjectNode();
+ node.put("id", id(prefix + name));
+ node.put("name", name);
+ node.putObject("folder").put("childCount", 1);
+ entries.putIfAbsent(name, node);
+ }
+ }
+ ObjectNode page = JSON.createObjectNode();
+ ArrayNode value = page.putArray("value");
+ new ArrayList<>(entries.values()).forEach(value::add);
+ return page.toString();
+ }
+
+ private String eTag(String path) {
+ return "\"{" + id(path) + "}," + versions.getOrDefault(path, 1) + "\"";
+ }
+
+ private ObjectNode item(String path) {
+ byte[] content = files.get(path);
+ QuickXorHash hash = new QuickXorHash();
+ hash.update(content, 0, content.length);
+ ObjectNode node = JSON.createObjectNode();
+ node.put("id", id(path));
+ node.put("name", path.substring(path.lastIndexOf('/') + 1));
+ node.put("size", content.length);
+ node.put("eTag", eTag(path));
+ node.put("cTag", "\"c:" + eTag(path) + "\"");
+ node.putObject("file").putObject("hashes").put("quickXorHash", hash.digestBase64());
+ return node;
+ }
+
+ private static Map<String, String> form(String body) {
+ Map<String, String> form = new HashMap<>();
+ for (String pair : body.split("&")) {
+ int eq = pair.indexOf('=');
+ if (eq > 0) {
+ form.put(
+ URLDecoder.decode(pair.substring(0, eq), StandardCharsets.UTF_8),
+ URLDecoder.decode(pair.substring(eq + 1), StandardCharsets.UTF_8));
+ }
+ }
+ return form;
+ }
+
+ private static byte[] read(HttpExchange exchange) throws IOException {
+ try (InputStream in = exchange.getRequestBody()) {
+ return in.readAllBytes();
+ }
+ }
+
+ private static String error(String code, String message) {
+ return "{\"error\":{\"code\":\"" + code + "\",\"message\":\"" + message + "\"}}";
+ }
+
+ private static void json(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);
+ try (OutputStream out = exchange.getResponseBody()) {
+ out.write(bytes);
+ }
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftCloudDriveContractTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftCloudDriveContractTest.java
new file mode 100644
index 0000000000..5c8be9e71f
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftCloudDriveContractTest.java
@@ -0,0 +1,87 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import static org.mockito.Mockito.mock;
+
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.AfterEach;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.access.service.OwnershipService;
+import stirling.software.proprietary.connectedaccount.CloudProvider;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountAccess;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
+import stirling.software.proprietary.connectedaccount.InMemoryConnectedAccounts;
+import stirling.software.proprietary.connectedaccount.MicrosoftOAuthClient;
+import stirling.software.proprietary.integration.crypto.TestCredentialKey;
+import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;
+import stirling.software.proprietary.integration.service.ConnectionLookup;
+import stirling.software.proprietary.policy.remote.CloudDrive;
+import stirling.software.proprietary.policy.remote.CloudDriveContract;
+import stirling.software.proprietary.policy.remote.CloudDriveFixtures;
+import stirling.software.proprietary.security.service.UserService;
+
+class MicrosoftCloudDriveContractTest extends CloudDriveContract<MicrosoftDriveConfig, DriveFile> {
+
+ private FakeGraphServer graph;
+ private long accountId;
+
+ @Override
+ protected CloudDrive<MicrosoftDriveConfig, DriveFile> drive() throws Exception {
+ TestCredentialKey.install();
+ graph = new FakeGraphServer();
+ GraphEndpoints endpoints = graph.endpoints();
+ ApplicationProperties properties = FakeGraphServer.serverApp();
+ InMemoryConnectedAccounts accounts = new InMemoryConnectedAccounts();
+ accountId = accounts.add(5L, CloudProvider.MICROSOFT, "rt-0").getId();
+ CloudDriveFixtures.signIn(CloudDriveFixtures.user(5L, "pat"));
+ ConnectedAccountService connected =
+ new ConnectedAccountService(
+ accounts.repository,
+ List.of(new MicrosoftOAuthClient(properties, endpoints)));
+ ConnectionLookup lookup =
+ new ConnectionLookup(
+ mock(IntegrationConfigRepository.class),
+ mock(OwnershipService.class),
+ mock(UserService.class));
+ MicrosoftConnectionResolver resolver =
+ new MicrosoftConnectionResolver(
+ lookup, new ConnectedAccountAccess(connected, lookup));
+ return new MicrosoftCloudDrive(
+ resolver,
+ new GraphDriveClient(endpoints, new GraphTokenProvider(endpoints, connected)));
+ }
+
+ @AfterEach
+ void stop() {
+ SecurityContextHolder.clearContext();
+ graph.close();
+ }
+
+ @Override
+ protected String type() {
+ return "onedrive";
+ }
+
+ @Override
+ protected Map<String, Object> options(String folder, Map<String, Object> extra) {
+ Map<String, Object> options = new HashMap<>(extra);
+ options.put("accountId", accountId);
+ options.put("directory", folder);
+ return options;
+ }
+
+ @Override
+ protected void put(String folder, String name, String content) {
+ graph.put(folder + "/" + name, content.getBytes(StandardCharsets.UTF_8));
+ }
+
+ @Override
+ protected String content(String folder, String name) {
+ return graph.content(folder + "/" + name);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveConfigTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveConfigTest.java
new file mode 100644
index 0000000000..3afbefc3dc
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveConfigTest.java
@@ -0,0 +1,168 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class MicrosoftDriveConfigTest {
+
+ private static Map<String, Object> credentials(String drive) {
+ Map<String, Object> options = new HashMap<>();
+ options.put("drive", drive);
+ options.put("tenantId", "contoso.onmicrosoft.com");
+ options.put("clientId", "client");
+ options.put("clientSecret", "s3cret");
+ return options;
+ }
+
+ @Test
+ void parsesAOneDriveConnection() {
+ Map<String, Object> options = credentials("onedrive");
+ options.put("user", "[email protected]");
+ options.put("directory", "/Inbox/Scans/");
+ options.put("mode", "snapshot");
+ options.put("recursive", "true");
+
+ MicrosoftDriveConfig config = MicrosoftDriveConfig.fromConnection(options);
+
+ assertEquals(MicrosoftDrive.ONEDRIVE, config.drive());
+ assertEquals("Inbox/Scans", config.directory());
+ assertTrue(config.snapshot());
+ assertTrue(config.recursive());
+ assertEquals("contoso.onmicrosoft.com:onedrive:[email protected]", config.location());
+ }
+
+ @Test
+ void parsesASharePointSiteAndLibrary() {
+ Map<String, Object> options = credentials("sharepoint");
+ options.put("siteUrl", "https://contoso.sharepoint.com/sites/Finance/");
+ options.put("library", "Invoices");
+
+ MicrosoftDriveConfig config = MicrosoftDriveConfig.fromConnection(options);
+
+ assertEquals("contoso.sharepoint.com", config.siteHost());
+ assertEquals("sites/Finance", config.sitePath());
+ assertEquals("Invoices", config.library());
+ assertFalse(config.snapshot());
+ }
+
+ @Test
+ void theRootSiteHasNoPathAndTheDefaultLibraryIsOptional() {
+ Map<String, Object> options = credentials("sharepoint");
+ options.put("siteUrl", "https://contoso.sharepoint.com");
+
+ MicrosoftDriveConfig config = MicrosoftDriveConfig.fromConnection(options);
+
+ assertEquals("", config.sitePath());
+ assertNull(config.library());
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "http://contoso.sharepoint.com/sites/a",
+ "https://contoso.sharepoint.com/sites/a?x=1",
+ "https://[email protected]/sites/a",
+ "not a url"
+ })
+ void rejectsSiteUrlsThatAreNotPlainHttps(String url) {
+ Map<String, Object> options = credentials("sharepoint");
+ options.put("siteUrl", url);
+ assertThrows(
+ IllegalArgumentException.class, () -> MicrosoftDriveConfig.fromConnection(options));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"directory, Inbox/../../Other", "tenantId, evil/../x"})
+ void rejectsAnEscapingFolderOrTenant(String key, String value) {
+ Map<String, Object> options = credentials("onedrive");
+ options.put("user", "[email protected]");
+ options.put(key, value);
+ assertThrows(
+ IllegalArgumentException.class, () -> MicrosoftDriveConfig.fromConnection(options));
+ }
+
+ @Test
+ void requiresTheCredentialsAndTheLibraryOwner() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> MicrosoftDriveConfig.fromConnection(credentials("onedrive")));
+ Map<String, Object> noSecret = credentials("sharepoint");
+ noSecret.put("siteUrl", "https://contoso.sharepoint.com");
+ noSecret.remove("clientSecret");
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> MicrosoftDriveConfig.fromConnection(noSecret));
+ Map<String, Object> noDrive = credentials("dropbox");
+ assertThrows(
+ IllegalArgumentException.class, () -> MicrosoftDriveConfig.fromConnection(noDrive));
+ }
+
+ @Test
+ void neverPrintsTheSecret() {
+ Map<String, Object> options = credentials("onedrive");
+ options.put("user", "[email protected]");
+ assertFalse(MicrosoftDriveConfig.fromConnection(options).toString().contains("s3cret"));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"tenantId", "clientId", "clientSecret"})
+ void requiresItsOwnAppRegistration(String key) {
+ Map<String, Object> options = credentials("onedrive");
+ options.put("user", "[email protected]");
+ options.remove(key);
+ assertThrows(
+ IllegalArgumentException.class, () -> MicrosoftDriveConfig.fromConnection(options));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"common", "organizations", "consumers"})
+ void rejectsATenantThatIsNotOneOrganisation(String tenant) {
+ Map<String, Object> options = credentials("onedrive");
+ options.put("user", "[email protected]");
+ options.put("tenantId", tenant);
+ assertThrows(
+ IllegalArgumentException.class, () -> MicrosoftDriveConfig.fromConnection(options));
+ }
+
+ @Test
+ void aConnectedAccountTakesAPathOrAFolderLink() {
+ MicrosoftDriveConfig mine =
+ MicrosoftDriveConfig.forAccount(
+ MicrosoftDrive.ONEDRIVE, 7L, Map.of("directory", "/Scans/In/"));
+ assertEquals("Scans/In", mine.directory());
+ assertNull(mine.folderLink());
+ assertEquals("account:7", mine.location());
+
+ MicrosoftDriveConfig linked =
+ MicrosoftDriveConfig.forAccount(
+ MicrosoftDrive.SHAREPOINT,
+ 7L,
+ Map.of("directory", "https://contoso.sharepoint.com/:f:/s/Finance/abc"));
+ assertEquals("https://contoso.sharepoint.com/:f:/s/Finance/abc", linked.folderLink());
+ assertEquals("", linked.directory());
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ MicrosoftDriveConfig.forAccount(
+ MicrosoftDrive.SHAREPOINT, 7L, Map.of("directory", "Shared")));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ MicrosoftDriveConfig.forAccount(
+ MicrosoftDrive.ONEDRIVE,
+ 7L,
+ Map.of("directory", "https://user:[email protected]/x")));
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveGraphTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveGraphTest.java
new file mode 100644
index 0000000000..0f861342fe
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/MicrosoftDriveGraphTest.java
@@ -0,0 +1,391 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.ledgerContext;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.named;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.signIn;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.user;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Random;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.core.io.Resource;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.proprietary.access.service.OwnershipService;
+import stirling.software.proprietary.connectedaccount.CloudProvider;
+import stirling.software.proprietary.connectedaccount.ConnectedAccount;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountAccess;
+import stirling.software.proprietary.connectedaccount.ConnectedAccountService;
+import stirling.software.proprietary.connectedaccount.InMemoryConnectedAccounts;
+import stirling.software.proprietary.connectedaccount.MicrosoftOAuthClient;
+import stirling.software.proprietary.integration.crypto.TestCredentialKey;
+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.integration.service.ConnectionLookup;
+import stirling.software.proprietary.policy.input.ResolveContext;
+import stirling.software.proprietary.policy.input.ResolvedInput;
+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
+import stirling.software.proprietary.policy.model.InputSpec;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.output.MicrosoftDriveOutputSink;
+import stirling.software.proprietary.policy.output.OutputDelivery;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.service.UserService;
+
+class MicrosoftDriveGraphTest {
+
+ private static final String POLICY = "p1";
+ private static final long CONNECTION = 7L;
+ private static final String ORGANISATION_ONEDRIVE =
+ "{\"drive\":\"onedrive\",\"tenantId\":\"contoso.onmicrosoft.com\",\"clientId\":\"c\","
+ + "\"clientSecret\":\"s\",\"user\":\""
+ + FakeGraphServer.USER
+ + "\",\"siteUrl\":\"https://contoso.sharepoint.com/sites/x\"}";
+
+ private FakeGraphServer graph;
+ private IntegrationConfigRepository connections;
+ private MicrosoftDriveInputSource source;
+ private MicrosoftDriveOutputSink sink;
+ private ResolveContext ctx;
+
+ private InMemoryConnectedAccounts accounts;
+ private ApplicationProperties properties;
+
+ private final User alice = user(5L, "alice");
+ private final OwnershipService ownership = mock(OwnershipService.class);
+ private final User mallory = user(9L, "mallory");
+
+ @BeforeEach
+ void setUp() throws IOException {
+ TestCredentialKey.install();
+ graph = new FakeGraphServer();
+ GraphEndpoints endpoints = graph.endpoints();
+ properties = FakeGraphServer.serverApp();
+ accounts = new InMemoryConnectedAccounts();
+ ConnectedAccountService connectedAccounts =
+ new ConnectedAccountService(
+ accounts.repository,
+ List.of(new MicrosoftOAuthClient(properties, endpoints)));
+ GraphDriveClient client =
+ new GraphDriveClient(
+ endpoints, new GraphTokenProvider(endpoints, connectedAccounts));
+ connections = mock(IntegrationConfigRepository.class);
+ storeConnection(true, ORGANISATION_ONEDRIVE);
+ UserService users = mock(UserService.class);
+ when(ownership.canUse(any(), any(), eq(alice))).thenReturn(true);
+ signIn(alice);
+ when(users.findByUsername("alice")).thenReturn(Optional.of(alice));
+ when(users.findByUsername("mallory")).thenReturn(Optional.of(mallory));
+ ConnectionLookup lookup = new ConnectionLookup(connections, ownership, users);
+ MicrosoftConnectionResolver resolver =
+ new MicrosoftConnectionResolver(
+ lookup, new ConnectedAccountAccess(connectedAccounts, lookup));
+ MicrosoftCloudDrive drive = new MicrosoftCloudDrive(resolver, client);
+ InProcessProcessedLedger ledger = new InProcessProcessedLedger();
+ source = new MicrosoftDriveInputSource(drive);
+ sink = new MicrosoftDriveOutputSink(drive, ledger);
+ ctx = ledgerContext(ledger, POLICY);
+ }
+
+ @AfterEach
+ void tearDown() {
+ graph.close();
+ SecurityContextHolder.clearContext();
+ }
+
+ private void storeConnection(boolean enabled, String config) {
+ IntegrationConfig connection = new IntegrationConfig();
+ connection.setId(CONNECTION);
+ connection.setName("Finance OneDrive");
+ connection.setIntegrationType(IntegrationType.MICROSOFT_365);
+ connection.setEnabled(enabled);
+ connection.setConfig(config);
+ when(connections.findById(CONNECTION)).thenReturn(Optional.of(connection));
+ }
+
+ private static InputSpec onedrive(Map<String, Object> extra) {
+ Map<String, Object> options = new LinkedHashMap<>();
+ options.put("connectionId", CONNECTION);
+ options.put("directory", "Inbox");
+ options.putAll(extra);
+ return new InputSpec("onedrive", options);
+ }
+
+ private static OutputSpec onedriveOut(String directory) {
+ return new OutputSpec(
+ "onedrive",
+ Map.of("connectionId", String.valueOf(CONNECTION), "directory", directory));
+ }
+
+ @Test
+ void recursiveListingDescendsIntoSubfolders() throws Exception {
+ graph.put("Inbox/a.pdf", "a");
+ graph.put("Inbox/2026/October/b.pdf", "b");
+ graph.put("Inbox/.hidden.pdf", "skip");
+
+ assertEquals(1, source.resolve(onedrive(Map.of("mode", "snapshot")), ctx).size());
+ assertEquals(
+ 2,
+ source.resolve(onedrive(Map.of("mode", "snapshot", "recursive", "true")), ctx)
+ .size());
+ }
+
+ @Test
+ void downloadsNeverCarryTheBearerToken() throws Exception {
+ graph.put("Inbox/doc.pdf", "secret content");
+ Resource resource =
+ source.resolve(onedrive(Map.of("mode", "snapshot")), ctx)
+ .getFirst()
+ .inputs()
+ .primary()
+ .getFirst();
+ try (InputStream in = resource.getInputStream()) {
+ in.readAllBytes();
+ }
+ assertTrue(graph.authorizedOffGraph.isEmpty());
+ }
+
+ @Test
+ void aMissingFolderIsAnErrorNotAnEmptyListing() {
+ graph.put("Other/doc.pdf", "x");
+ assertThrows(IOException.class, () -> source.resolve(onedrive(Map.of()), ctx));
+ assertThrows(IllegalArgumentException.class, () -> source.validate(onedrive(Map.of())));
+ }
+
+ @Test
+ void throttledCallsAreRetried() throws Exception {
+ graph.put("Inbox/doc.pdf", "x");
+ graph.throttleNext.set(2);
+ assertEquals(1, source.resolve(onedrive(Map.of("mode", "snapshot")), ctx).size());
+ }
+
+ @Test
+ void tokensAreReusedAcrossCalls() throws Exception {
+ graph.put("Inbox/doc.pdf", "x");
+ source.resolve(onedrive(Map.of("mode", "snapshot")), ctx);
+ source.resolve(onedrive(Map.of("mode", "snapshot")), ctx);
+ assertEquals(1, graph.tokenRequests.get());
+ }
+
+ @Test
+ void aSharePointSourceRefusesAOneDriveConnection() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ source.resolve(
+ new InputSpec("sharepoint", Map.of("connectionId", CONNECTION)),
+ ctx));
+ }
+
+ @Test
+ void aDisabledConnectionCannotBeUsed() {
+ storeConnection(false, ORGANISATION_ONEDRIVE);
+ assertThrows(IllegalArgumentException.class, () -> source.resolve(onedrive(Map.of()), ctx));
+ }
+
+ @Test
+ void largeOutputsUseAnUploadSession() throws Exception {
+ byte[] large =
+ new byte
+ [(int) GraphDriveClient.SIMPLE_UPLOAD_LIMIT
+ + GraphDriveClient.UPLOAD_CHUNK
+ + 17];
+ new Random(1).nextBytes(large);
+
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY),
+ List.of(named(large, "big.pdf")),
+ onedriveOut("Done"));
+
+ assertEquals(large.length, graph.files.get("Done/big.pdf").length);
+ assertTrue(graph.authorizedOffGraph.isEmpty());
+ }
+
+ @Test
+ void aConnectedAccountWorksInItsOwnOneDrive() throws Exception {
+ signIn(alice);
+ ConnectedAccount account = accounts.add(5L, CloudProvider.MICROSOFT, "rt-0");
+ graph.put("Scans/in.pdf", "mine");
+
+ List<ResolvedInput> work =
+ source.resolve(
+ new InputSpec(
+ "onedrive",
+ Map.of(
+ "accountId",
+ account.getId(),
+ "directory",
+ "Scans",
+ "mode",
+ "consume")),
+ ctx);
+
+ assertEquals(1, work.size());
+ try (InputStream in = work.getFirst().inputs().primary().getFirst().getInputStream()) {
+ assertEquals("mine", new String(in.readAllBytes(), StandardCharsets.UTF_8));
+ }
+ work.getFirst().onComplete().accept(true);
+ assertNull(graph.content("Scans/in.pdf"));
+ }
+
+ @Test
+ void aPastedFolderLinkAnchorsAConnectedAccountsSharePointLocation() throws Exception {
+ signIn(alice);
+ ConnectedAccount account = accounts.add(5L, CloudProvider.MICROSOFT, "rt-0");
+ graph.put("Sites/Finance/Invoices/march.pdf", "invoice");
+ Map<String, Object> options =
+ Map.of(
+ "accountId",
+ account.getId(),
+ "directory",
+ FakeGraphServer.folderLink("Sites/Finance/Invoices"));
+
+ assertEquals(1, source.resolve(new InputSpec("sharepoint", options), ctx).size());
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY),
+ List.of(named("processed", "march-done.pdf")),
+ new OutputSpec("sharepoint", options));
+
+ assertEquals("processed", graph.content("Sites/Finance/Invoices/march-done.pdf"));
+ assertTrue(source.resolve(new InputSpec("sharepoint", options), ctx).isEmpty());
+ }
+
+ @Test
+ void someoneElsesConnectedAccountCannotBeUsed() {
+ ConnectedAccount account = accounts.add(5L, CloudProvider.MICROSOFT, "rt-0");
+ signIn(mallory);
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ source.validate(
+ new InputSpec(
+ "onedrive",
+ Map.of("accountId", account.getId(), "directory", "In"))));
+ }
+
+ @Test
+ void anUnattendedRunWritesToItsOwnersAccount() throws Exception {
+ ConnectedAccount account = accounts.add(5L, CloudProvider.MICROSOFT, "rt-0");
+
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY, null, null, null, "alice"),
+ List.of(named("processed", "done.pdf")),
+ new OutputSpec(
+ "onedrive", Map.of("accountId", account.getId(), "directory", "Out")));
+
+ assertEquals("processed", graph.content("Out/done.pdf"));
+ }
+
+ @Test
+ void anUnattendedRunCannotWriteToAnotherUsersAccount() {
+ ConnectedAccount account = accounts.add(5L, CloudProvider.MICROSOFT, "rt-0");
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY, null, null, null, "mallory"),
+ List.of(named("planted", "done.pdf")),
+ new OutputSpec(
+ "onedrive",
+ Map.of("accountId", account.getId(), "directory", "Out"))));
+ assertNull(graph.content("Out/done.pdf"));
+ }
+
+ @Test
+ void anOrganisationConnectionIsRefusedWhenNobodyIsActing() {
+ SecurityContextHolder.clearContext();
+
+ assertThrows(IllegalArgumentException.class, () -> source.resolve(onedrive(Map.of()), ctx));
+ }
+
+ @Test
+ void anUnattendedRunUsesAConnectionItsOwnerMayUse() throws Exception {
+ graph.put("Out/.keep", "x");
+ SecurityContextHolder.clearContext();
+
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY, null, null, null, "alice"),
+ List.of(named("processed", "done.pdf")),
+ onedriveOut("Out"));
+
+ assertEquals("processed", graph.content("Out/done.pdf"));
+ }
+
+ @Test
+ void anUnattendedRunCannotUseAConnectionItsOwnerMayNot() {
+ SecurityContextHolder.clearContext();
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY, null, null, null, "mallory"),
+ List.of(named("planted", "done.pdf")),
+ onedriveOut("Out")));
+ }
+
+ @Test
+ void anAccountIsRefusedWhenNobodyIsActing() {
+ ConnectedAccount account = accounts.add(5L, CloudProvider.MICROSOFT, "rt-0");
+ graph.put("Scans/in.pdf", "mine");
+ SecurityContextHolder.clearContext();
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ source.resolve(
+ new InputSpec(
+ "onedrive",
+ Map.of("accountId", account.getId(), "directory", "Scans")),
+ ctx));
+ }
+
+ @Test
+ void accountLocationsStopWhenTheAdminTurnsConnectionsOff() {
+ signIn(alice);
+ ConnectedAccount account = accounts.add(5L, CloudProvider.MICROSOFT, "rt-0");
+ properties.getPremium().getProFeatures().getMicrosoft().setAllowAccountConnections(false);
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ source.resolve(
+ new InputSpec("onedrive", Map.of("accountId", account.getId())),
+ ctx));
+ }
+
+ @Test
+ void aBlankConnectionSecretNeverBorrowsTheServersApp() {
+ storeConnection(
+ true,
+ "{\"drive\":\"onedrive\",\"tenantId\":\"contoso.onmicrosoft.com\",\"user\":\""
+ + FakeGraphServer.USER
+ + "\"}");
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> source.resolve(onedrive(Map.of("mode", "snapshot")), ctx));
+ assertTrue(graph.tokenForms.isEmpty());
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/QuickXorHashTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/QuickXorHashTest.java
new file mode 100644
index 0000000000..8df50417b5
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/microsoft/QuickXorHashTest.java
@@ -0,0 +1,55 @@
+package stirling.software.proprietary.policy.microsoft;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.Random;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+class QuickXorHashTest {
+
+ @ParameterizedTest
+ @CsvSource({
+ "'', AAAAAAAAAAAAAAAAAAAAAAAAAAA=",
+ "Sg==, SgAAAAAAAAAAAAAAAQAAAAAAAAA=",
+ "tbQ=, taAFAAAAAAAAAAAAAgAAAAAAAAA="
+ })
+ void matchesPublishedVectors(String contentBase64, String expected) {
+ assertEquals(expected, hash(Base64.getDecoder().decode(contentBase64)));
+ }
+
+ @Test
+ void isIndependentOfHowTheStreamIsChunked() {
+ byte[] content = new byte[100_003];
+ new Random(42).nextBytes(content);
+ String whole = hash(content);
+
+ QuickXorHash chunked = new QuickXorHash();
+ int offset = 0;
+ int[] sizes = {1, 7, 159, 160, 161, 4096, 65_536};
+ for (int i = 0; offset < content.length; i++) {
+ int size = Math.min(sizes[i % sizes.length], content.length - offset);
+ chunked.update(content, offset, size);
+ offset += size;
+ }
+ assertEquals(whole, chunked.digestBase64());
+ }
+
+ @Test
+ void differsWhenContentDiffers() {
+ String a = hash("a".repeat(500).getBytes(StandardCharsets.UTF_8));
+ String b = hash(("a".repeat(499) + "b").getBytes(StandardCharsets.UTF_8));
+ assertNotEquals(a, b);
+ }
+
+ private static String hash(byte[] content) {
+ QuickXorHash hash = new QuickXorHash();
+ hash.update(content, 0, content.length);
+ return hash.digestBase64();
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java
index 72afdfc6ce..ff11fcd409 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/model/PolicyRunTest.java
@@ -22,6 +22,7 @@ class PolicyRunTest {
null,
null,
null,
+ null,
null);
}
@@ -36,6 +37,7 @@ class PolicyRunTest {
null,
null,
null,
+ null,
null);
assertTrue(PolicyRunView.of(run).externalOutput());
assertFalse(PolicyRunView.of(run()).externalOutput());
@@ -64,6 +66,7 @@ class PolicyRunTest {
null,
null,
null,
+ null,
null);
assertEquals(
!"inline".equals(destination.type()),
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java
index ad58a0ca61..f3b2425e48 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/output/OutputDeliveryTest.java
@@ -20,6 +20,7 @@ class OutputDeliveryTest {
source,
document,
user,
+ null,
null);
return OutputDelivery.forRun(run, PolicyInputs.of(List.of(new FileSystemResource(path))));
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudDriveContract.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudDriveContract.java
new file mode 100644
index 0000000000..e6aa5f2af2
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudDriveContract.java
@@ -0,0 +1,186 @@
+package stirling.software.proprietary.policy.remote;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static stirling.software.proprietary.policy.remote.CloudDriveFixtures.named;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import stirling.software.proprietary.policy.input.ResolveContext;
+import stirling.software.proprietary.policy.input.ResolvedInput;
+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
+import stirling.software.proprietary.policy.model.InputSpec;
+import stirling.software.proprietary.policy.model.OutputSpec;
+import stirling.software.proprietary.policy.output.CloudDriveOutputSink;
+import stirling.software.proprietary.policy.output.OutputDelivery;
+
+public abstract class CloudDriveContract<L extends CloudLocation, F extends CloudFile> {
+
+ protected static final String POLICY = "p1";
+
+ protected InProcessProcessedLedger ledger;
+ private CloudDriveInputSource<L, F> source;
+ private CloudDriveOutputSink<L, F> sink;
+
+ protected abstract CloudDrive<L, F> drive() throws Exception;
+
+ protected abstract String type();
+
+ protected abstract Map<String, Object> options(String folder, Map<String, Object> extra);
+
+ protected abstract void put(String folder, String name, String content) throws Exception;
+
+ protected abstract String content(String folder, String name) throws Exception;
+
+ @BeforeEach
+ void wireContract() throws Exception {
+ CloudDrive<L, F> drive = drive();
+ ledger = new InProcessProcessedLedger();
+ source = new CloudDriveInputSource<>(drive) {};
+ sink = new CloudDriveOutputSink<>(drive, ledger) {};
+ }
+
+ private List<ResolvedInput> sweep(String mode, String policy) throws IOException {
+ return source.resolve(
+ new InputSpec(type(), options("Inbox", Map.of("mode", mode))), ctx(policy));
+ }
+
+ @Test
+ void deliveryGivesUpWhenEveryNameIsTaken() throws Exception {
+ put("Out", "busy.pdf", "original");
+ for (int i = 1; i < 100; i++) {
+ put("Out", "busy (" + i + ").pdf", "original");
+ }
+
+ assertThrows(
+ IOException.class,
+ () ->
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY),
+ List.of(named("new", "busy.pdf")),
+ new OutputSpec(type(), options("Out", Map.of()))));
+ }
+
+ @Test
+ void withoutAModeOriginalsAreKept() throws Exception {
+ put("Inbox", "a.pdf", "first");
+
+ List<ResolvedInput> work =
+ source.resolve(new InputSpec(type(), options("Inbox", Map.of())), ctx(POLICY));
+ work.getFirst().onComplete().accept(true);
+
+ assertThat(content("Inbox", "a.pdf")).isEqualTo("first");
+ }
+
+ @Test
+ void consumeReadsThenRemovesOnlyAfterSuccess() throws Exception {
+ put("Inbox", "a.pdf", "first");
+ put("Inbox", "b.pdf", "second");
+
+ List<ResolvedInput> work = sweep("consume", POLICY);
+
+ assertThat(work).hasSize(2);
+ ResolvedInput first =
+ work.stream()
+ .filter(w -> "a.pdf".equals(w.inputs().primary().getFirst().getFilename()))
+ .findFirst()
+ .orElseThrow();
+ try (InputStream in = first.inputs().primary().getFirst().getInputStream()) {
+ assertThat(new String(in.readAllBytes(), StandardCharsets.UTF_8)).isEqualTo("first");
+ }
+ assertThat(sweep("consume", POLICY)).isEmpty();
+ first.onComplete().accept(true);
+ work.stream().filter(w -> w != first).findFirst().orElseThrow().onComplete().accept(false);
+
+ assertThat(content("Inbox", "a.pdf")).isNull();
+ assertThat(content("Inbox", "b.pdf")).isEqualTo("second");
+ }
+
+ @Test
+ void aFileReplacedMidRunIsKeptAndClaimedAgain() throws Exception {
+ put("Inbox", "doc.pdf", "v1");
+ List<ResolvedInput> work = sweep("consume", POLICY);
+
+ put("Inbox", "doc.pdf", "v2 is a different version");
+ work.getFirst().onComplete().accept(true);
+
+ assertThat(content("Inbox", "doc.pdf")).isEqualTo("v2 is a different version");
+ assertThat(sweep("consume", POLICY)).hasSize(1);
+ }
+
+ @Test
+ void aSharedFileIsRemovedOnlyOnceEveryPolicyIsDone() throws Exception {
+ put("Inbox", "doc.pdf", "shared");
+ List<ResolvedInput> mine = sweep("consume", POLICY);
+ List<ResolvedInput> theirs = sweep("consume", "p2");
+
+ mine.getFirst().onComplete().accept(true);
+ assertThat(content("Inbox", "doc.pdf")).isEqualTo("shared");
+ theirs.getFirst().onComplete().accept(true);
+ assertThat(content("Inbox", "doc.pdf")).isNull();
+ }
+
+ @Test
+ void trackKeepsOriginalsAndProcessesEachVersionOnce() throws Exception {
+ put("Inbox", "doc.pdf", "v1");
+ sweep("track", POLICY).getFirst().onComplete().accept(true);
+
+ assertThat(content("Inbox", "doc.pdf")).isEqualTo("v1");
+ assertThat(sweep("track", POLICY)).isEmpty();
+ put("Inbox", "doc.pdf", "v2 changed");
+ assertThat(sweep("track", POLICY)).hasSize(1);
+ }
+
+ @Test
+ void snapshotSeesEverythingEveryTime() throws Exception {
+ put("Inbox", "doc.pdf", "x");
+ assertThat(sweep("snapshot", POLICY)).hasSize(1);
+ assertThat(sweep("snapshot", POLICY)).hasSize(1);
+ }
+
+ @Test
+ void outputsNeverReplaceAnExistingName() throws Exception {
+ put("Done", "report.pdf", "already here");
+
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY),
+ List.of(named("new one", "report.pdf"), named("newer", "report.pdf")),
+ new OutputSpec(type(), options("Done", Map.of())));
+
+ assertThat(content("Done", "report.pdf")).isEqualTo("already here");
+ assertThat(content("Done", "report (1).pdf")).isEqualTo("new one");
+ assertThat(content("Done", "report (2).pdf")).isEqualTo("newer");
+ }
+
+ @Test
+ void aPolicyNeverReingestsItsOwnOutput() throws Exception {
+ put("Inbox", "original.pdf", "original");
+ sweep("track", POLICY).getFirst().onComplete().accept(true);
+
+ sink.deliver(
+ new OutputDelivery("run-1", POLICY),
+ List.of(named("processed output", "processed.pdf")),
+ new OutputSpec(type(), options("Inbox", Map.of())));
+
+ assertThat(sweep("track", POLICY)).isEmpty();
+ assertThat(sweep("track", "p2")).hasSize(2);
+ }
+
+ @Test
+ void aMissingFolderIsAnErrorNotAnEmptyListing() {
+ InputSpec missing = new InputSpec(type(), options("Nowhere", Map.of()));
+ assertThrows(IOException.class, () -> source.resolve(missing, ctx(POLICY)));
+ assertThrows(IllegalArgumentException.class, () -> source.validate(missing));
+ }
+
+ private ResolveContext ctx(String policyId) {
+ return CloudDriveFixtures.ledgerContext(ledger, policyId);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudDriveFixtures.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudDriveFixtures.java
new file mode 100644
index 0000000000..33201e23a3
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudDriveFixtures.java
@@ -0,0 +1,66 @@
+package stirling.software.proprietary.policy.remote;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Collection;
+import java.util.List;
+import java.util.function.Supplier;
+
+import org.springframework.core.io.ByteArrayResource;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import stirling.software.proprietary.policy.input.ResolveContext;
+import stirling.software.proprietary.policy.ledger.InProcessProcessedLedger;
+import stirling.software.proprietary.security.model.User;
+
+public final class CloudDriveFixtures {
+
+ private CloudDriveFixtures() {}
+
+ public static ByteArrayResource named(String text, String name) {
+ return named(text.getBytes(StandardCharsets.UTF_8), name);
+ }
+
+ public static ByteArrayResource named(byte[] content, String name) {
+ return new ByteArrayResource(content) {
+ @Override
+ public String getFilename() {
+ return name;
+ }
+ };
+ }
+
+ public static User user(long id, String username) {
+ User user = new User();
+ user.setId(id);
+ user.setUsername(username);
+ return user;
+ }
+
+ public static void signIn(User user) {
+ SecurityContextHolder.getContext()
+ .setAuthentication(new UsernamePasswordAuthenticationToken(user, null, List.of()));
+ }
+
+ public static ResolveContext ledgerContext(InProcessProcessedLedger ledger, String policyId) {
+ return new ResolveContext() {
+ @Override
+ public boolean claim(String identity, String gate, Supplier<String> contentHash) {
+ return ledger.claim(policyId, identity, gate, contentHash);
+ }
+
+ @Override
+ public void settle(String identity, String gate, String hash, boolean success) {
+ ledger.settle(policyId, identity, gate, hash, success);
+ }
+
+ @Override
+ public boolean allSettledDone(String identity) {
+ return ledger.allSettledDone(identity);
+ }
+
+ @Override
+ public void reportPresent(Collection<String> identities) {}
+ };
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudHttpTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudHttpTest.java
new file mode 100644
index 0000000000..13035ecec4
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/remote/CloudHttpTest.java
@@ -0,0 +1,72 @@
+package stirling.software.proprietary.policy.remote;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+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.HttpServer;
+
+class CloudHttpTest {
+
+ private HttpServer server;
+ private final AtomicInteger calls = new AtomicInteger();
+
+ @BeforeEach
+ void start() throws Exception {
+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ server.createContext(
+ "/",
+ exchange -> {
+ int n = calls.incrementAndGet();
+ int status = n == 1 ? 503 : 200;
+ exchange.getResponseHeaders().add("Retry-After", "0");
+ exchange.sendResponseHeaders(status, -1);
+ exchange.close();
+ });
+ server.start();
+ }
+
+ @AfterEach
+ void stop() {
+ server.stop(0);
+ }
+
+ private HttpRequest.Builder request() {
+ return HttpRequest.newBuilder(
+ URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/x"));
+ }
+
+ @Test
+ void aServerErrorOnAnIdempotentRequestIsRetried() throws Exception {
+ HttpResponse<Void> response =
+ CloudHttp.send(
+ CloudHttp.newClient(),
+ request().GET().build(),
+ HttpResponse.BodyHandlers.discarding(),
+ "test");
+
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(calls).hasValue(2);
+ }
+
+ @Test
+ void aServerErrorOnAPostIsNotRepeated() throws Exception {
+ HttpResponse<Void> response =
+ CloudHttp.send(
+ CloudHttp.newClient(),
+ request().POST(HttpRequest.BodyPublishers.ofString("file")).build(),
+ HttpResponse.BodyHandlers.discarding(),
+ "test");
+
+ assertThat(response.statusCode()).isEqualTo(503);
+ assertThat(calls).hasValue(1);
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java
index f2939d9ddc..87acbb1b09 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/trigger/StorageFolderTriggerTest.java
@@ -131,6 +131,7 @@ class StorageFolderTriggerTest {
inv.<Source>getArgument(3).id(),
identity,
null,
+ null,
null);
CompletableFuture<PolicyRun> completion = new CompletableFuture<>();
Runnable finish =
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
index 98922b71e1..60c2dcfd4e 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java
@@ -79,6 +79,10 @@ class UserServiceTest {
private stirling.software.proprietary.integration.repository.IntegrationConfigRepository
integrationConfigRepository;
+ @Mock
+ private stirling.software.proprietary.connectedaccount.ConnectedAccountService
+ connectedAccountService;
+
@Mock private TeamMembershipService teamMembershipService;
@Mock private ApiKeyAuthenticationService apiKeyAuthenticationService;
@Mock private ToolUsageStatRepository toolUsageStatRepository;
diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
index 51db653118..622146f474 100644
--- a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
+++ b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java
@@ -90,6 +90,7 @@ public final class SaasSchemaOwnership {
"account_link_usage_counter",
"api_key_daily_usage",
"api_keys",
+ "connected_accounts",
"file_encryption_keys",
"file_share_accesses",
"file_shares",
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index f5a33cafdb..7ef51acb5c 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -4050,6 +4050,30 @@ failed = "Your sign-in could not be renewed. Try again, or dismiss this page and
lead = "This server is already linked to your account. Renew your sign-in to return to billing and usage on your server."
title = "Renew your server sign-in"
+[connectedAccounts]
+connect = "Connect"
+connectAnother = "Connect another"
+connectFailed = "The account couldn't be connected. Check that the server's app registration is set up, then try again."
+disconnect = "Disconnect"
+google = "Google Drive"
+intro = "Connect your own accounts once. Your pipelines can then read from and save to them as you."
+microsoft = "Microsoft (OneDrive & SharePoint)"
+needsReconnect = "Stirling can no longer reach this account, so pipelines using it are paused."
+none = "Your administrator hasn't turned on connected accounts."
+personal = "Personal account"
+popupBlocked = "Your browser blocked the sign-in window. Allow pop-ups for this site and try again."
+reconnect = "Sign in again"
+work = "Work account"
+
+[connectedAccounts.disconnectConfirm]
+body = "Sources and pipelines that use this account will stop until you connect it again."
+confirm = "Disconnect"
+title = "Disconnect {{account}}?"
+
+[connectedAccounts.status]
+connected = "Connected"
+needsSignIn = "Needs sign-in"
+
[convert]
autoRotate = "Auto Rotate"
autoRotateDescription = "Automatically rotate images to better fit the PDF page"
@@ -8849,6 +8873,19 @@ 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.googleworkspace]
+description = "A service account that reads and writes Google Drive for the organisation."
+label = "Google Workspace"
+
+[portal.connections.types.googleworkspace.fields.credentialsJson]
+helperText = "Paste the service account's JSON key from Google Cloud. It is encrypted and never shown again."
+label = "Service account key (JSON)"
+
+[portal.connections.types.googleworkspace.fields.subject]
+helperText = "Optional. With domain-wide delegation, the user whose Drive this acts as (a dedicated bot user keeps working when people leave). Blank reaches only shared drives and folders shared with the service account."
+label = "Act as user"
+placeholder = "[email protected]"
+
[portal.connections.types.jira]
baseUrlPlaceholder = "https://your-site.atlassian.net"
description = "Attach processed documents to a Jira issue."
@@ -8858,6 +8895,17 @@ label = "Jira"
description = "Email a document or a notification when a policy runs."
label = "Mailgun"
+[portal.connections.types.microsoft365.fields.clientId]
+helperText = "Needs Microsoft Graph application permissions with admin consent."
+label = "Application (client) ID"
+
+[portal.connections.types.microsoft365.fields.clientSecret]
+label = "Client secret"
+
+[portal.connections.types.microsoft365.fields.tenantId]
+label = "Directory (tenant) ID"
+placeholder = "contoso.onmicrosoft.com or tenant GUID"
+
[portal.connections.types.n8n]
baseUrlPlaceholder = "https://your-n8n/webhook/9f2c-..."
description = "Hand documents to an n8n workflow, and take back whatever it produces."
@@ -8892,6 +8940,15 @@ label = "Nextcloud"
[portal.connections.types.nextcloud.fields.appPassword]
label = "App password"
+[portal.connections.types.onedrive]
+description = "Read from and write to one user's OneDrive for Business."
+label = "OneDrive"
+
+[portal.connections.types.onedrive.fields.user]
+helperText = "Whose OneDrive this connection reaches. The app registration needs the Files.ReadWrite.All application permission."
+label = "OneDrive owner"
+placeholder = "[email protected]"
+
[portal.connections.types.presidio]
baseUrlPlaceholder = "http://presidio-analyzer:3000"
description = "Detect personal data in document text using a Presidio server you run."
@@ -8957,6 +9014,18 @@ helperText = "Leave blank if you authenticate with a private key instead."
helperText = "Optional. Paste an OpenSSH private key to authenticate with a key instead of a password."
label = "Private key"
+[portal.connections.types.sharepoint]
+description = "Read from and write to a SharePoint site's document library."
+label = "SharePoint"
+
+[portal.connections.types.sharepoint.fields.library]
+helperText = "Optional. Leave blank for the site's default Documents library."
+label = "Document library"
+
+[portal.connections.types.sharepoint.fields.siteUrl]
+label = "Site URL"
+placeholder = "https://contoso.sharepoint.com/sites/Finance"
+
[portal.connections.types.slack]
description = "Post a message to Slack when a policy processes a document."
label = "Slack"
@@ -10947,6 +11016,7 @@ subtitle = "Reusable input connections that feed documents into Stirling. Config
title = "Sources"
[portal.sources.actions]
+connectDestination = "Connect destination"
connectSource = "Connect source"
[portal.sources.builder]
@@ -10960,6 +11030,8 @@ chooseOutputHint = "Choose where processed documents go. Greyed-out connectors a
comingSoon = "Coming soon"
comingSoonHeading = "Coming soon"
create = "Create source"
+createDestination = "Create destination"
+createDestinationTitle = "Add a destination"
createTitle = "Connect a source"
delete = "Delete"
editTitle = "Edit source"
@@ -10970,6 +11042,41 @@ description = "Folder automations can only use folders an administrator has allo
openSettings = "Folder Access settings"
title = "This folder isn't allowed"
+[portal.sources.cloudFields.account]
+connect = "Connect your account"
+connectAnother = "Connect another account"
+connectFailed = "The account couldn't be connected. Try again, or ask your administrator to check the app registration."
+label = "Account"
+placeholder = "Choose an account"
+reconnect = "sign in again"
+unavailable = "Connecting your own account is turned off on this server. Choose an organisation connection instead."
+
+[portal.sources.cloudFields.authMode]
+accountsOff = "Personal accounts are turned off on this server."
+helperText = "Your account reaches what you can open and needs no admin. An organisation connection keeps working when people leave, and only reaches what an admin set up."
+label = "Sign in as"
+
+[portal.sources.cloudFields.authMode.options]
+account = "My account"
+organisation = "Organisation connection"
+
+[portal.sources.cloudFields.connection]
+helperText = "Set up by an administrator under Integrations. Shared by every location that uses it."
+label = "Organisation connection"
+
+[portal.sources.cloudFields.googledrive]
+helperText = "Paste the folder's link, or type a path from the top of My Drive. Leave empty for the top of My Drive. The folder must already exist."
+placeholder = "Folder link, or Scans/Inbox"
+
+[portal.sources.cloudFields.onedrive]
+helperText = "A folder in your OneDrive, or paste a folder link (Copy link in OneDrive). Leave empty for the top of the OneDrive. The folder must already exist."
+placeholder = "Scans/Inbox, or a folder link"
+
+[portal.sources.cloudFields.sharepoint]
+helperText = "With your account, paste the folder's link (Copy link in SharePoint). With an organisation connection, a folder inside its library; leave empty for the library root. The folder must already exist."
+organisationPlaceholder = "Folder link, or Scans/Inbox"
+placeholder = "Folder link"
+
[portal.sources.delete]
body = "Delete \"{{name}}\"? This can't be undone. Policies that reference it would need to be updated."
cancel = "Cancel"
@@ -11033,6 +11140,7 @@ label = "Email inbox"
[portal.sources.types.folder]
description = "Watch a directory on the server for new documents."
label = "Folder"
+outputDescription = "Save results to a directory on the server."
[portal.sources.types.folder.fields.directory]
helperText = "The absolute path to the folder to watch for new files."
@@ -11069,20 +11177,23 @@ description = "Poll an FTP or FTPS server folder for new documents."
label = "FTP"
[portal.sources.types.googledrive]
-description = "Pull documents from shared Google Drive folders."
+description = "Watch a Google Drive folder for new documents."
label = "Google Drive"
+outputDescription = "Save results to a Google Drive folder."
[portal.sources.types.network]
description = "Watch an SMB network share for new documents."
label = "Network drive"
[portal.sources.types.onedrive]
-description = "Watch OneDrive folders for new documents."
+description = "Watch a OneDrive folder for new documents."
label = "OneDrive"
+outputDescription = "Save results to a OneDrive folder."
[portal.sources.types.s3]
description = "Pull documents from an Amazon S3 or S3-compatible bucket."
label = "Amazon S3"
+outputDescription = "Save results to an Amazon S3 or S3-compatible bucket."
[portal.sources.types.s3.fields.connection]
helperText = "The saved connection with the bucket and credentials. Shared by every source and pipeline output that uses it."
@@ -11106,8 +11217,9 @@ description = "Poll an SFTP drop folder for new documents."
label = "SFTP"
[portal.sources.types.sharepoint]
-description = "Pull documents from SharePoint document libraries."
+description = "Watch a SharePoint document library folder."
label = "SharePoint"
+outputDescription = "Save results to a SharePoint document library folder."
[portal.sources.types.unknown]
label = "Source"
@@ -11284,7 +11396,15 @@ waiting = "Queued ..."
[provider.googledrive]
name = "Google Drive"
-scope = "File Import"
+scope = "Files & pipelines"
+
+[provider.googledrive.accountScope]
+description = "drive reaches every file (Google must verify a public app for it); drive.file only files people pick or Stirling creates"
+label = "Drive access"
+
+[provider.googledrive.allowAccountConnections]
+description = "One sign-in for the editor and their pipelines. Turn off to allow only organisation connections."
+label = "Let people connect their own account"
[provider.googledrive.apiKey]
description = "Google API Key for Google Picker API from Google Cloud Console"
@@ -11298,14 +11418,50 @@ label = "App ID"
description = "Google OAuth 2.0 Client ID from Google Cloud Console"
label = "Client ID"
+[provider.googledrive.clientSecret]
+description = "Lets people connect their Google account for their pipelines. Add the redirect URI below as an authorised redirect URI of the OAuth client."
+label = "Client secret"
+
[provider.googledrive.enabled]
-description = "Allow users to import files directly from Google Drive"
-label = "Enable Google Drive File Picker"
+description = "Covers opening files from Google Drive in the editor and connecting a Google account for pipelines. Organisation connections under Integrations work without it."
+label = "Enable Google Drive"
[provider.googledrive.errors]
notConfigured = "Google Drive is not configured"
pickerFailed = "Failed to open Google Drive picker"
+[provider.googledrive.redirectUri]
+description = "Add this as an authorised redirect URI of the OAuth client in Google Cloud Console."
+label = "Redirect URI"
+
+[provider.microsoft]
+name = "Microsoft 365 (OneDrive & SharePoint)"
+scope = "Files & pipelines"
+
+[provider.microsoft.allowAccountConnections]
+description = "One sign-in for the editor and their pipelines. Turn off to allow only organisation connections."
+label = "Let people connect their own account"
+
+[provider.microsoft.clientId]
+description = "From one Microsoft Entra app registration."
+label = "Application (client) ID"
+
+[provider.microsoft.clientSecret]
+description = "Needed for connected accounts. Stays on the server."
+label = "Client secret"
+
+[provider.microsoft.enabled]
+description = "Let people use OneDrive and SharePoint in pipelines"
+label = "Enable OneDrive & SharePoint"
+
+[provider.microsoft.redirectUri]
+description = "Add this as a Web redirect URI on the Entra app registration."
+label = "Redirect URI"
+
+[provider.microsoft.tenant]
+description = "common for work, school and personal accounts; organizations for work and school only; or a tenant ID to admit one organisation"
+label = "Directory (tenant) ID"
+
[provider.oauth2.generic]
name = "Generic OAuth2"
scope = "SSO"
@@ -12315,6 +12471,10 @@ privacy = "Privacy"
storageSharing = "File Storage & Sharing"
systemSettings = "System Settings"
+[settings.connectedAccounts]
+description = "Your own OneDrive, SharePoint and Google Drive, for your pipelines."
+title = "Connected accounts"
+
[settings.connectedInstances]
confirmBody = "This revokes the instance’s access to your team in Stirling Cloud. It does not delete local files or remove usage already recorded. To connect again, follow the original connection steps on the instance."
confirmTitle = "Remove {{name}}?"
diff --git a/frontend/public/og-metadata.json b/frontend/public/og-metadata.json
index f8a65193e2..f9b99d156f 100644
--- a/frontend/public/og-metadata.json
+++ b/frontend/public/og-metadata.json
@@ -470,6 +470,12 @@
"description": "A free, private PDF editor you can run on any infrastructure.",
"noindex": true
},
+ "/settings/connectedAccounts": {
+ "image": "/og_images/home.png",
+ "title": "Connected Accounts Settings - Stirling PDF",
+ "description": "A free, private PDF editor you can run on any infrastructure.",
+ "noindex": true
+ },
"/settings/hotkeys": {
"image": "/og_images/home.png",
"title": "Hotkeys Settings - Stirling PDF",
@@ -910,6 +916,7 @@
"/settings/requests": "/settings/requests",
"/settings/developer": "/settings/developer",
"/settings/api-keys": "/settings/api-keys",
+ "/settings/connectedAccounts": "/settings/connectedAccounts",
"/settings/hotkeys": "/settings/hotkeys",
"/settings/adminGeneral": "/settings/adminGeneral",
"/settings/adminSecurity": "/settings/adminSecurity",
diff --git a/frontend/public/og-metadata.saas.json b/frontend/public/og-metadata.saas.json
index 0962a39a45..f2f24b6773 100644
--- a/frontend/public/og-metadata.saas.json
+++ b/frontend/public/og-metadata.saas.json
@@ -472,6 +472,12 @@
"description": "A free, private PDF editor you can run on any infrastructure.",
"noindex": true
},
+ "/settings/connectedAccounts": {
+ "image": "/og_images/home.png",
+ "title": "Connected Accounts Settings - Stirling PDF",
+ "description": "A free, private PDF editor you can run on any infrastructure.",
+ "noindex": true
+ },
"/settings/hotkeys": {
"image": "/og_images/home.png",
"title": "Hotkeys Settings - Stirling PDF",
@@ -918,6 +924,7 @@
"/settings/requests": "/settings/requests",
"/settings/developer": "/settings/developer",
"/settings/api-keys": "/settings/api-keys",
+ "/settings/connectedAccounts": "/settings/connectedAccounts",
"/settings/hotkeys": "/settings/hotkeys",
"/settings/adminGeneral": "/settings/adminGeneral",
"/settings/adminSecurity": "/settings/adminSecurity",
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.test.tsx b/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.test.tsx
new file mode 100644
index 0000000000..2cbd3100b4
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.test.tsx
@@ -0,0 +1,114 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import ConnectedAccountsSection from "@editor/components/shared/config/configSections/ConnectedAccountsSection";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: unknown) =>
+ typeof options === "object" && options && "account" in options
+ ? `${key}:${String((options as { account: string }).account)}`
+ : key,
+ }),
+}));
+
+const state = vi.hoisted(() => ({
+ disconnect: vi.fn(),
+ connect: vi.fn(),
+}));
+
+vi.mock("@editor/hooks/useConnectedAccounts", () => ({
+ useConnectedAccounts: () => ({
+ available: (provider: string) => provider === "microsoft",
+ accounts: [
+ {
+ id: 4,
+ provider: "microsoft",
+ email: "[email protected]",
+ displayName: "Pat",
+ status: "CONNECTED",
+ personal: false,
+ lastError: null,
+ createdAt: null,
+ },
+ {
+ id: 5,
+ provider: "microsoft",
+ email: "[email protected]",
+ displayName: "Sam",
+ status: "NEEDS_RECONNECT",
+ personal: true,
+ lastError: null,
+ createdAt: null,
+ },
+ ],
+ connect: state.connect,
+ disconnect: state.disconnect,
+ }),
+}));
+
+function renderSection() {
+ render(
+ <MantineProvider>
+ <ConnectedAccountsSection />
+ </MantineProvider>,
+ );
+}
+
+function disconnectButtonFor(id: number) {
+ const row = screen.getByTestId(`connected-account-${id}`);
+ const button = row.querySelectorAll("button");
+ return button[button.length - 1];
+}
+
+describe("ConnectedAccountsSection", () => {
+ beforeEach(() => {
+ state.disconnect.mockReset();
+ state.disconnect.mockResolvedValue(undefined);
+ });
+
+ it("asks before disconnecting and names the account", async () => {
+ renderSection();
+ fireEvent.click(disconnectButtonFor(4));
+
+ expect(
+ await screen.findByText(
+ "connectedAccounts.disconnectConfirm.title:[email protected]",
+ ),
+ ).toBeTruthy();
+ expect(state.disconnect).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByTestId("confirm-disconnect"));
+ await waitFor(() => expect(state.disconnect).toHaveBeenCalledWith(4));
+ });
+
+ it("keeps the account when the confirmation is cancelled", async () => {
+ renderSection();
+ fireEvent.click(disconnectButtonFor(5));
+ await screen.findByText(
+ "connectedAccounts.disconnectConfirm.title:[email protected]",
+ );
+ fireEvent.click(screen.getByText("common.cancel"));
+ await waitFor(() =>
+ expect(
+ screen.queryByText(
+ "connectedAccounts.disconnectConfirm.title:[email protected]",
+ ),
+ ).toBeNull(),
+ );
+ expect(state.disconnect).not.toHaveBeenCalled();
+ });
+
+ it("labels each account with its status and type", () => {
+ renderSection();
+ const connected = screen.getByTestId("connected-account-4");
+ const stale = screen.getByTestId("connected-account-5");
+ expect(connected.textContent).toContain(
+ "connectedAccounts.status.connected",
+ );
+ expect(connected.textContent).toContain("connectedAccounts.work");
+ expect(stale.textContent).toContain("connectedAccounts.status.needsSignIn");
+ expect(stale.textContent).toContain("connectedAccounts.personal");
+ expect(stale.textContent).toContain("connectedAccounts.needsReconnect");
+ });
+});
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.tsx b/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.tsx
new file mode 100644
index 0000000000..9d47bfc4f1
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/config/configSections/ConnectedAccountsSection.tsx
@@ -0,0 +1,235 @@
+import { Fragment, useState } from "react";
+import { Group, Paper, Stack, Text } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { Banner, Button, Modal, SectionDivider, StatusBadge } from "@editor/ui";
+import { Icon } from "@editor/ui/Icon";
+import { Z_INDEX_OVER_CONFIG_MODAL } from "@editor/styles/zIndex";
+import { useConnectedAccounts } from "@editor/hooks/useConnectedAccounts";
+import {
+ accountLabel,
+ connectErrorMessage,
+ type CloudProvider,
+ type ConnectedAccount,
+} from "@editor/services/connectedAccountsService";
+
+const PROVIDERS: { id: CloudProvider; icon: "onedrive" | "googledrive" }[] = [
+ { id: "microsoft", icon: "onedrive" },
+ { id: "google", icon: "googledrive" },
+];
+
+export default function ConnectedAccountsSection() {
+ const { t } = useTranslation();
+ const { available, accounts, connect, disconnect } = useConnectedAccounts();
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [pendingDisconnect, setPendingDisconnect] =
+ useState<ConnectedAccount | null>(null);
+
+ const providerName = (provider: CloudProvider) =>
+ provider === "microsoft"
+ ? t("connectedAccounts.microsoft", "Microsoft (OneDrive & SharePoint)")
+ : t("connectedAccounts.google", "Google Drive");
+
+ async function run(key: string, action: () => Promise<unknown>) {
+ setBusy(key);
+ setError(null);
+ try {
+ const outcome = await action();
+ if (outcome === "error") {
+ setError(
+ t(
+ "connectedAccounts.connectFailed",
+ "The account couldn't be connected. Check that the server's app registration is set up, then try again.",
+ ),
+ );
+ }
+ } catch (e) {
+ setError(connectErrorMessage(e, t));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ const offered = PROVIDERS.filter((provider) => available(provider.id));
+
+ return (
+ <Stack gap="md" data-testid="connected-accounts">
+ <Text size="sm" c="dimmed">
+ {t(
+ "connectedAccounts.intro",
+ "Connect your own accounts once. Your pipelines can then read from and save to them as you.",
+ )}
+ </Text>
+ {error && (
+ <Banner tone="danger" onDismiss={() => setError(null)}>
+ {error}
+ </Banner>
+ )}
+ {offered.length === 0 && (
+ <Text size="sm">
+ {t(
+ "connectedAccounts.none",
+ "Your administrator hasn't turned on connected accounts.",
+ )}
+ </Text>
+ )}
+ {offered.map((provider) => {
+ const mine = accounts.filter((a) => a.provider === provider.id);
+ return (
+ <Paper
+ key={provider.id}
+ p="md"
+ radius="md"
+ withBorder
+ style={{ background: "var(--c-surface)" }}
+ >
+ <Group justify="space-between" gap="sm" mb={mine.length ? "sm" : 0}>
+ <Group gap="sm" wrap="nowrap">
+ <Icon name={provider.icon} size={20} />
+ <Text fw={600}>{providerName(provider.id)}</Text>
+ </Group>
+ <Button
+ variant="secondary"
+ size="sm"
+ loading={busy === `connect-${provider.id}`}
+ data-testid={`connect-${provider.id}`}
+ onClick={() =>
+ void run(`connect-${provider.id}`, () => connect(provider.id))
+ }
+ >
+ {mine.length
+ ? t("connectedAccounts.connectAnother", "Connect another")
+ : t("connectedAccounts.connect", "Connect")}
+ </Button>
+ </Group>
+ <Stack gap={0}>
+ {mine.map((account, index) => (
+ <Fragment key={account.id}>
+ {index > 0 && <SectionDivider spacing={10} />}
+ <AccountRow
+ account={account}
+ busy={busy}
+ onReconnect={() =>
+ void run(`connect-${provider.id}`, () =>
+ connect(provider.id),
+ )
+ }
+ onDisconnect={() => setPendingDisconnect(account)}
+ />
+ </Fragment>
+ ))}
+ </Stack>
+ </Paper>
+ );
+ })}
+ <Modal
+ open={pendingDisconnect !== null}
+ onClose={() => setPendingDisconnect(null)}
+ width="sm"
+ zIndex={Z_INDEX_OVER_CONFIG_MODAL}
+ title={t("connectedAccounts.disconnectConfirm.title", {
+ defaultValue: "Disconnect {{account}}?",
+ account: pendingDisconnect ? accountLabel(pendingDisconnect) : "",
+ })}
+ footer={
+ <Group justify="flex-end" gap="sm">
+ <Button
+ variant="secondary"
+ onClick={() => setPendingDisconnect(null)}
+ >
+ {t("common.cancel", "Cancel")}
+ </Button>
+ <Button
+ accent="danger"
+ data-testid="confirm-disconnect"
+ onClick={() => {
+ const account = pendingDisconnect;
+ setPendingDisconnect(null);
+ if (account) {
+ void run(`remove-${account.id}`, () =>
+ disconnect(account.id),
+ );
+ }
+ }}
+ >
+ {t("connectedAccounts.disconnectConfirm.confirm", "Disconnect")}
+ </Button>
+ </Group>
+ }
+ >
+ <Text size="sm">
+ {t(
+ "connectedAccounts.disconnectConfirm.body",
+ "Sources and pipelines that use this account will stop until you connect it again.",
+ )}
+ </Text>
+ </Modal>
+ </Stack>
+ );
+}
+
+interface AccountRowProps {
+ account: ConnectedAccount;
+ busy: string | null;
+ onReconnect: () => void;
+ onDisconnect: () => void;
+}
+
+function AccountRow({
+ account,
+ busy,
+ onReconnect,
+ onDisconnect,
+}: AccountRowProps) {
+ const { t } = useTranslation();
+ const needsReconnect = account.status === "NEEDS_RECONNECT";
+ return (
+ <Group
+ justify="space-between"
+ gap="xs"
+ data-testid={`connected-account-${account.id}`}
+ >
+ <Stack gap={4} style={{ flex: "1 1 16rem", minWidth: 0 }}>
+ <Group gap="xs">
+ <Text size="sm" style={{ overflowWrap: "anywhere" }}>
+ {accountLabel(account)}
+ </Text>
+ <StatusBadge tone={needsReconnect ? "danger" : "success"} size="sm">
+ {needsReconnect
+ ? t("connectedAccounts.status.needsSignIn", "Needs sign-in")
+ : t("connectedAccounts.status.connected", "Connected")}
+ </StatusBadge>
+ </Group>
+ <Text size="xs" style={{ color: "var(--c-text-muted)" }}>
+ {account.personal
+ ? t("connectedAccounts.personal", "Personal account")
+ : t("connectedAccounts.work", "Work account")}
+ </Text>
+ {needsReconnect && (
+ <Text size="xs" style={{ color: "var(--c-danger)" }}>
+ {t(
+ "connectedAccounts.needsReconnect",
+ "Stirling can no longer reach this account, so pipelines using it are paused.",
+ )}
+ </Text>
+ )}
+ </Stack>
+ <Group gap="xs" wrap="nowrap">
+ {needsReconnect && (
+ <Button variant="primary" size="sm" onClick={onReconnect}>
+ {t("connectedAccounts.reconnect", "Sign in again")}
+ </Button>
+ )}
+ <Button
+ variant="tertiary"
+ accent="danger"
+ size="sm"
+ loading={busy === `remove-${account.id}`}
+ onClick={onDisconnect}
+ >
+ {t("connectedAccounts.disconnect", "Disconnect")}
+ </Button>
+ </Group>
+ </Group>
+ );
+}
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.test.tsx b/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.test.tsx
new file mode 100644
index 0000000000..9350554ac9
--- /dev/null
+++ b/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.test.tsx
@@ -0,0 +1,86 @@
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import ProviderCard from "@editor/components/shared/config/configSections/ProviderCard";
+import type { Provider } from "@editor/components/shared/config/configSections/providerDefinitions";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const copyText = vi.hoisted(() => vi.fn());
+vi.mock("@editor/utils/copyText", () => ({
+ copyText: (text: string) => copyText(text),
+}));
+
+const provider: Provider = {
+ id: "microsoft",
+ category: "integration",
+ name: "Microsoft 365",
+ icon: "onedrive",
+ type: "microsoft",
+ scope: "Files & pipelines",
+ fields: [
+ {
+ key: "clientId",
+ type: "text",
+ label: "Client ID",
+ description: "From the app registration",
+ },
+ {
+ key: "redirectUri",
+ type: "copy",
+ label: "Redirect URI",
+ description: "Register this on the app",
+ value:
+ "https://pdf.example.com/api/v1/connected-accounts/callback/microsoft",
+ },
+ ],
+};
+
+function renderCard(onSave = vi.fn()) {
+ render(
+ <MantineProvider>
+ <ProviderCard
+ provider={provider}
+ isConfigured
+ settings={{ clientId: "abc" }}
+ onSave={onSave}
+ />
+ </MantineProvider>,
+ );
+ fireEvent.click(screen.getByText("admin.expand"));
+ return onSave;
+}
+
+describe("ProviderCard copy field", () => {
+ it("shows the value read-only with its description", () => {
+ renderCard();
+ const input = screen.getByTestId(
+ "provider-copy-redirectUri",
+ ) as HTMLInputElement;
+ expect(input.value).toBe(
+ "https://pdf.example.com/api/v1/connected-accounts/callback/microsoft",
+ );
+ expect(input.readOnly).toBe(true);
+ expect(screen.getByText("Register this on the app")).toBeTruthy();
+ });
+
+ it("copies the value and confirms it", async () => {
+ copyText.mockResolvedValue(true);
+ renderCard();
+ fireEvent.click(screen.getByText("common.copy"));
+ await waitFor(() =>
+ expect(copyText).toHaveBeenCalledWith(
+ "https://pdf.example.com/api/v1/connected-accounts/callback/microsoft",
+ ),
+ );
+ expect(await screen.findByText("common.copied")).toBeTruthy();
+ });
+
+ it("never saves the copied value as a setting", () => {
+ const onSave = renderCard();
+ fireEvent.click(screen.getByText("admin.settings.save"));
+ expect(onSave).toHaveBeenCalledWith({ clientId: "abc" });
+ });
+});
diff --git a/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.tsx b/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.tsx
index 7ac9a57405..74f65ea324 100644
--- a/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.tsx
+++ b/frontend/src/editor/core/components/shared/config/configSections/ProviderCard.tsx
@@ -22,6 +22,7 @@ import {
} from "@editor/components/shared/config/configSections/providerDefinitions";
import { Icon, isIconName } from "@editor/ui/Icon";
+import { copyText } from "@editor/utils/copyText";
import { privateContentClassName } from "@editor/components/shared/privateContentClassName";
interface ProviderCardProps {
provider: Provider;
@@ -81,6 +82,18 @@ export default function ProviderCard({
setExpanded(!expanded);
};
+ const [copiedField, setCopiedField] = useState<string | null>(null);
+
+ const copyField = async (key: string, value: string) => {
+ if (await copyText(value)) {
+ setCopiedField(key);
+ window.setTimeout(
+ () => setCopiedField((current) => (current === key ? null : current)),
+ 1500,
+ );
+ }
+ };
+
const handleFieldChange = (key: string, value: unknown) => {
if (disabled) return; // Block changes when disabled
const updated = { ...localSettings, [key]: value };
@@ -102,6 +115,39 @@ export default function ProviderCard({
const raw = localSettings[field.key] ?? field.defaultValue;
switch (field.type) {
+ case "copy":
+ return (
+ <TextInput
+ key={field.key}
+ label={field.label}
+ description={field.description}
+ value={field.value ?? ""}
+ readOnly
+ onFocus={(e) => e.currentTarget.select()}
+ data-testid={`provider-copy-${field.key}`}
+ rightSectionWidth="auto"
+ rightSectionPointerEvents="all"
+ rightSection={
+ <Button
+ size="sm"
+ variant="tertiary"
+ accent={copiedField === field.key ? "success" : undefined}
+ leftSection={
+ <Icon
+ name={copiedField === field.key ? "check" : "copy"}
+ size={14}
+ />
+ }
+ onClick={() => void copyField(field.key, field.value ?? "")}
+ >
+ {copiedField === field.key
+ ? t("common.copied", "Copied!")
+ : t("common.copy", "Copy")}
+ </Button>
+ }
+ />
+ );
+
case "switch":
return (
<SettingsToggleRow
diff --git a/frontend/src/editor/core/components/shared/config/configSections/providerDefinitions.ts b/frontend/src/editor/core/components/shared/config/configSections/providerDefinitions.ts
index 6d8079915e..35caa52112 100644
--- a/frontend/src/editor/core/components/shared/config/configSections/providerDefinitions.ts
+++ b/frontend/src/editor/core/components/shared/config/configSections/providerDefinitions.ts
@@ -1,5 +1,11 @@
import { useTranslation } from "react-i18next";
-export type ProviderType = "oauth2" | "saml2" | "telegram" | "googledrive";
+import { useConnectRedirectUri } from "@editor/hooks/useConnectRedirectUri";
+export type ProviderType =
+ | "oauth2"
+ | "saml2"
+ | "telegram"
+ | "googledrive"
+ | "microsoft";
/** Value of a provider field, keyed by its `type`: text/password/textarea -> string,
* number -> number, switch -> boolean, tags -> string[]. */
@@ -7,11 +13,19 @@ export type FieldValue = string | number | boolean | string[];
export interface ProviderField {
key: string;
- type: "text" | "password" | "switch" | "textarea" | "number" | "tags";
+ type:
+ | "text"
+ | "password"
+ | "switch"
+ | "textarea"
+ | "number"
+ | "tags"
+ | "copy";
label: string;
description: string;
placeholder?: string;
defaultValue?: FieldValue;
+ value?: string;
}
/** Signing in with this provider, versus wiring the server to another service. */
@@ -812,6 +826,7 @@ const useSAML2Provider = (): Provider => {
const useGoogleDriveProvider = (): Provider => {
const { t } = useTranslation();
+ const redirectUri = useConnectRedirectUri("google");
return {
id: "googledrive",
@@ -819,20 +834,17 @@ const useGoogleDriveProvider = (): Provider => {
name: t("provider.googledrive.name", "Google Drive"),
icon: "googledrive",
type: "googledrive",
- scope: t("provider.googledrive.scope", "File Import"),
+ scope: t("provider.googledrive.scope", "Files & pipelines"),
documentationUrl:
"https://docs.stirlingpdf.com/Configuration/Google%20Drive%20File%20Picker/",
fields: [
{
key: "enabled",
type: "switch",
- label: t(
- "provider.googledrive.enabled.label",
- "Enable Google Drive File Picker",
- ),
+ label: t("provider.googledrive.enabled.label", "Enable Google Drive"),
description: t(
"provider.googledrive.enabled.description",
- "Allow users to import files directly from Google Drive",
+ "Covers opening files from Google Drive in the editor and connecting a Google account for pipelines. Organisation connections under Integrations work without it.",
),
defaultValue: false,
},
@@ -866,6 +878,134 @@ const useGoogleDriveProvider = (): Provider => {
),
placeholder: "xxxxxxxxxxxxx",
},
+ {
+ key: "clientSecret",
+ type: "password",
+ label: t("provider.googledrive.clientSecret.label", "Client secret"),
+ description: t(
+ "provider.googledrive.clientSecret.description",
+ "Lets people connect their Google account for their pipelines. Add the redirect URI below as an authorised redirect URI of the OAuth client.",
+ ),
+ },
+ {
+ key: "redirectUri",
+ type: "copy",
+ label: t("provider.googledrive.redirectUri.label", "Redirect URI"),
+ description: t(
+ "provider.googledrive.redirectUri.description",
+ "Add this as an authorised redirect URI of the OAuth client in Google Cloud Console.",
+ ),
+ value: redirectUri,
+ },
+ {
+ key: "allowAccountConnections",
+ type: "switch",
+ label: t(
+ "provider.googledrive.allowAccountConnections.label",
+ "Let people connect their own account",
+ ),
+ description: t(
+ "provider.googledrive.allowAccountConnections.description",
+ "One sign-in for the editor and their pipelines. Turn off to allow only organisation connections.",
+ ),
+ defaultValue: true,
+ },
+ {
+ key: "accountScope",
+ type: "text",
+ label: t("provider.googledrive.accountScope.label", "Drive access"),
+ description: t(
+ "provider.googledrive.accountScope.description",
+ "drive reaches every file (Google must verify a public app for it); drive.file only files people pick or Stirling creates",
+ ),
+ placeholder: "drive",
+ defaultValue: "drive",
+ },
+ ],
+ };
+};
+
+const useMicrosoftProvider = (): Provider => {
+ const { t } = useTranslation();
+ const redirectUri = useConnectRedirectUri("microsoft");
+
+ return {
+ id: "microsoft",
+ category: "integration",
+ name: t("provider.microsoft.name", "Microsoft 365 (OneDrive & SharePoint)"),
+ icon: "onedrive",
+ type: "microsoft",
+ scope: t("provider.microsoft.scope", "Files & pipelines"),
+ fields: [
+ {
+ key: "enabled",
+ type: "switch",
+ label: t(
+ "provider.microsoft.enabled.label",
+ "Enable OneDrive & SharePoint",
+ ),
+ description: t(
+ "provider.microsoft.enabled.description",
+ "Let people use OneDrive and SharePoint in pipelines",
+ ),
+ defaultValue: false,
+ },
+ {
+ key: "clientId",
+ type: "text",
+ label: t(
+ "provider.microsoft.clientId.label",
+ "Application (client) ID",
+ ),
+ description: t(
+ "provider.microsoft.clientId.description",
+ "From one Microsoft Entra app registration.",
+ ),
+ placeholder: "00000000-0000-0000-0000-000000000000",
+ },
+ {
+ key: "redirectUri",
+ type: "copy",
+ label: t("provider.microsoft.redirectUri.label", "Redirect URI"),
+ description: t(
+ "provider.microsoft.redirectUri.description",
+ "Add this as a Web redirect URI on the Entra app registration.",
+ ),
+ value: redirectUri,
+ },
+ {
+ key: "tenant",
+ type: "text",
+ label: t("provider.microsoft.tenant.label", "Directory (tenant) ID"),
+ description: t(
+ "provider.microsoft.tenant.description",
+ "common for work, school and personal accounts; organizations for work and school only; or a tenant ID to admit one organisation",
+ ),
+ placeholder: "common",
+ defaultValue: "common",
+ },
+ {
+ key: "clientSecret",
+ type: "password",
+ label: t("provider.microsoft.clientSecret.label", "Client secret"),
+ description: t(
+ "provider.microsoft.clientSecret.description",
+ "Needed for connected accounts and organisation connections. Stays on the server.",
+ ),
+ },
+ {
+ key: "allowAccountConnections",
+ type: "switch",
+ label: t(
+ "provider.microsoft.allowAccountConnections.label",
+ "Let people connect their own account",
+ ),
+ description: t(
+ "provider.microsoft.allowAccountConnections.description",
+ "One sign-in for the editor and their pipelines. Turn off to allow only organisation connections.",
+ ),
+ defaultValue: true,
+ },
],
};
};
@@ -879,6 +1019,7 @@ export const useAllProviders = (): Provider[] => {
const telegramProvider = useTelegramProvider();
const saml2Provider = useSAML2Provider();
const googleDriveProvider = useGoogleDriveProvider();
+ const microsoftProvider = useMicrosoftProvider();
return [
googleProvider,
@@ -889,5 +1030,6 @@ export const useAllProviders = (): Provider[] => {
smtpProvider,
telegramProvider,
googleDriveProvider,
+ microsoftProvider,
];
};
diff --git a/frontend/src/editor/core/components/shared/config/types.ts b/frontend/src/editor/core/components/shared/config/types.ts
index e60cb752d2..ab5bf37e06 100644
--- a/frontend/src/editor/core/components/shared/config/types.ts
+++ b/frontend/src/editor/core/components/shared/config/types.ts
@@ -17,6 +17,7 @@ export const VALID_NAV_KEYS = [
"requests",
"developer",
"api-keys",
+ "connectedAccounts",
"hotkeys",
"adminGeneral",
"adminSecurity",
diff --git a/frontend/src/editor/core/hooks/useConnectRedirectUri.ts b/frontend/src/editor/core/hooks/useConnectRedirectUri.ts
new file mode 100644
index 0000000000..249c36cc76
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useConnectRedirectUri.ts
@@ -0,0 +1,35 @@
+import { useEffect, useState } from "react";
+import { absoluteWithBasePath } from "@editor/constants/app";
+import {
+ connectCallbackPath,
+ fetchRedirectUris,
+ type CloudProvider,
+} from "@editor/services/connectedAccountsService";
+
+let serverUris: Promise<Record<CloudProvider, string>> | null = null;
+
+function loadServerUris(): Promise<Record<CloudProvider, string>> {
+ serverUris ??= fetchRedirectUris().catch((error: unknown) => {
+ serverUris = null;
+ throw error;
+ });
+ return serverUris;
+}
+
+export function useConnectRedirectUri(provider: CloudProvider): string {
+ const [uri, setUri] = useState(() =>
+ absoluteWithBasePath(connectCallbackPath(provider)),
+ );
+ useEffect(() => {
+ let active = true;
+ loadServerUris()
+ .then((uris) => {
+ if (active && uris[provider]) setUri(uris[provider]);
+ })
+ .catch(() => undefined);
+ return () => {
+ active = false;
+ };
+ }, [provider]);
+ return uri;
+}
diff --git a/frontend/src/editor/core/hooks/useConnectedAccounts.disconnect.test.ts b/frontend/src/editor/core/hooks/useConnectedAccounts.disconnect.test.ts
new file mode 100644
index 0000000000..fb580772bb
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useConnectedAccounts.disconnect.test.ts
@@ -0,0 +1,104 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const fetchConnectedAccounts = vi.fn();
+const disconnectAccount = vi.fn();
+vi.mock("@editor/services/connectedAccountsService", () => ({
+ fetchConnectedAccounts: () => fetchConnectedAccounts(),
+ connectAccount: vi.fn(),
+ disconnectAccount: (id: number) => disconnectAccount(id),
+}));
+vi.mock("@editor/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: { microsoftAccountConnections: true } }),
+}));
+
+const {
+ clearConnectedAccounts,
+ refreshConnectedAccounts,
+ useConnectedAccounts,
+} = await import("@editor/hooks/useConnectedAccounts");
+
+function accountsState(...ids: number[]) {
+ return {
+ providers: { microsoft: true, google: false },
+ accounts: ids.map((id) => ({
+ id,
+ provider: "microsoft",
+ status: "CONNECTED",
+ })),
+ };
+}
+
+describe("disconnecting a connected account", () => {
+ beforeEach(() => {
+ clearConnectedAccounts();
+ fetchConnectedAccounts.mockReset();
+ disconnectAccount.mockReset();
+ });
+
+ it("removes it even when the refresh afterwards fails", async () => {
+ fetchConnectedAccounts.mockResolvedValue(accountsState(3, 4));
+ await refreshConnectedAccounts();
+ const { result } = renderHook(() => useConnectedAccounts());
+ disconnectAccount.mockResolvedValueOnce(undefined);
+ fetchConnectedAccounts.mockRejectedValueOnce(new Error("503"));
+
+ await act(() => result.current.disconnect(3));
+
+ expect(result.current.accounts.map((account) => account.id)).toEqual([4]);
+ });
+
+ it("keeps it when the disconnect itself fails", async () => {
+ fetchConnectedAccounts.mockResolvedValue(accountsState(3));
+ await refreshConnectedAccounts();
+ const { result } = renderHook(() => useConnectedAccounts());
+ disconnectAccount.mockRejectedValueOnce(new Error("500"));
+
+ await act(async () => {
+ await expect(result.current.disconnect(3)).rejects.toThrow("500");
+ });
+
+ expect(result.current.accounts.map((account) => account.id)).toEqual([3]);
+ });
+
+ it("ignores a refresh that started before the disconnect finished", async () => {
+ const both = accountsState(3, 4);
+ fetchConnectedAccounts.mockResolvedValueOnce(both);
+ await refreshConnectedAccounts();
+ const { result } = renderHook(() => useConnectedAccounts());
+
+ let finishStale: (value: typeof both) => void = () => undefined;
+ fetchConnectedAccounts.mockReturnValueOnce(
+ new Promise((resolve) => (finishStale = resolve)),
+ );
+ void refreshConnectedAccounts();
+ disconnectAccount.mockResolvedValueOnce(undefined);
+ fetchConnectedAccounts.mockResolvedValueOnce(accountsState(4));
+
+ await act(() => result.current.disconnect(3));
+ await act(async () => finishStale(both));
+
+ expect(result.current.accounts.map((account) => account.id)).toEqual([4]);
+ });
+
+ it("publishes nothing when the user signed out during the disconnect", async () => {
+ fetchConnectedAccounts.mockResolvedValueOnce(accountsState(3));
+ await refreshConnectedAccounts();
+ const { result } = renderHook(() => useConnectedAccounts());
+ let finishDisconnect: () => void = () => undefined;
+ disconnectAccount.mockReturnValueOnce(
+ new Promise<void>((resolve) => (finishDisconnect = resolve)),
+ );
+ fetchConnectedAccounts.mockClear();
+
+ const pending = result.current.disconnect(3);
+ act(() => clearConnectedAccounts());
+ await act(async () => {
+ finishDisconnect();
+ await pending;
+ });
+
+ expect(result.current.accounts).toEqual([]);
+ expect(fetchConnectedAccounts).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/editor/core/hooks/useConnectedAccounts.test.ts b/frontend/src/editor/core/hooks/useConnectedAccounts.test.ts
new file mode 100644
index 0000000000..e0444f5ee4
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useConnectedAccounts.test.ts
@@ -0,0 +1,56 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const fetchConnectedAccounts = vi.fn();
+vi.mock("@editor/services/connectedAccountsService", () => ({
+ fetchConnectedAccounts: () => fetchConnectedAccounts(),
+ connectAccount: vi.fn(),
+ disconnectAccount: vi.fn(),
+}));
+vi.mock("@editor/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: {} }),
+}));
+
+const {
+ latestConnectedAccounts,
+ refreshConnectedAccounts,
+ clearConnectedAccounts,
+} = await import("@editor/hooks/useConnectedAccounts");
+
+describe("refreshConnectedAccounts", () => {
+ beforeEach(() => {
+ clearConnectedAccounts();
+ fetchConnectedAccounts.mockReset();
+ });
+
+ it("keeps the known accounts when a refresh fails", async () => {
+ const accounts = [{ id: 3, provider: "microsoft", status: "CONNECTED" }];
+ fetchConnectedAccounts.mockResolvedValueOnce({
+ providers: { microsoft: true, google: false },
+ accounts,
+ });
+ await refreshConnectedAccounts();
+ fetchConnectedAccounts.mockRejectedValueOnce(new Error("503"));
+ await refreshConnectedAccounts();
+
+ expect(latestConnectedAccounts()).toEqual(accounts);
+ });
+
+ it("drops the previous user's accounts and ignores their late reply", async () => {
+ let answer: (value: unknown) => void = () => undefined;
+ fetchConnectedAccounts.mockReturnValueOnce(
+ new Promise((resolve) => {
+ answer = resolve;
+ }),
+ );
+ const pending = refreshConnectedAccounts();
+ clearConnectedAccounts();
+ answer({
+ providers: { microsoft: true, google: false },
+ accounts: [{ id: 9, provider: "microsoft", status: "CONNECTED" }],
+ });
+ await pending;
+
+ expect(latestConnectedAccounts()).toEqual([]);
+ });
+});
diff --git a/frontend/src/editor/core/hooks/useConnectedAccounts.ts b/frontend/src/editor/core/hooks/useConnectedAccounts.ts
new file mode 100644
index 0000000000..cfd2ede31e
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useConnectedAccounts.ts
@@ -0,0 +1,177 @@
+import { useCallback, useEffect, useSyncExternalStore } from "react";
+import { useAppConfig } from "@editor/contexts/AppConfigContext";
+import type { AppConfig } from "@editor/types/appConfig";
+import {
+ connectAccount,
+ disconnectAccount,
+ fetchConnectedAccounts,
+ type CloudProvider,
+ type ConnectedAccount,
+ type ConnectedAccountsState,
+ type ConnectOutcome,
+} from "@editor/services/connectedAccountsService";
+
+const EMPTY: ConnectedAccountsState = {
+ providers: { microsoft: false, google: false },
+ accounts: [],
+};
+
+let snapshot: ConnectedAccountsState = EMPTY;
+let loaded = false;
+let inflight: Promise<void> | null = null;
+let generation = 0;
+const listeners = new Set<() => void>();
+
+const CONFIG_FLAG: Record<
+ CloudProvider,
+ "microsoftAccountConnections" | "googleDriveAccountConnections"
+> = {
+ microsoft: "microsoftAccountConnections",
+ google: "googleDriveAccountConnections",
+};
+
+function providerOffered(
+ config: AppConfig | null | undefined,
+ provider: CloudProvider,
+): boolean {
+ return Boolean(config?.[CONFIG_FLAG[provider]]);
+}
+
+export function accountConnectionsOffered(
+ config: AppConfig | null | undefined,
+): boolean {
+ return (
+ providerOffered(config, "microsoft") || providerOffered(config, "google")
+ );
+}
+
+function findConnected(
+ accounts: ConnectedAccount[],
+ provider: CloudProvider,
+): ConnectedAccount | undefined {
+ return accounts.find(
+ (account) =>
+ account.provider === provider && account.status === "CONNECTED",
+ );
+}
+
+function publish(next: ConnectedAccountsState) {
+ snapshot = next;
+ loaded = true;
+ listeners.forEach((listener) => listener());
+}
+
+function subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function refreshConnectedAccounts(): Promise<void> {
+ if (!inflight) {
+ const started = generation;
+ const request: Promise<void> = fetchConnectedAccounts()
+ .then((next) => {
+ if (started === generation) publish(next);
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ if (inflight === request) inflight = null;
+ });
+ inflight = request;
+ }
+ return inflight;
+}
+
+export function clearConnectedAccounts() {
+ generation++;
+ snapshot = EMPTY;
+ loaded = false;
+ inflight = null;
+ listeners.forEach((listener) => listener());
+}
+
+export function connectedAccountFor(
+ provider: CloudProvider,
+): ConnectedAccount | undefined {
+ return findConnected(snapshot.accounts, provider);
+}
+
+export function latestConnectedAccounts(): ConnectedAccount[] {
+ return snapshot.accounts;
+}
+
+export async function ensureConnectedAccount(
+ provider: CloudProvider,
+ connect: (provider: CloudProvider) => Promise<ConnectOutcome>,
+): Promise<{ account?: ConnectedAccount; outcome?: ConnectOutcome }> {
+ const existing = connectedAccountFor(provider);
+ if (existing) {
+ return { account: existing };
+ }
+ const outcome = await connect(provider);
+ return { account: connectedAccountFor(provider), outcome };
+}
+
+export interface UseConnectedAccounts {
+ available: (provider: CloudProvider) => boolean;
+ accounts: ConnectedAccount[];
+ accountFor: (provider: CloudProvider) => ConnectedAccount | undefined;
+ loaded: boolean;
+ connect: (provider: CloudProvider) => Promise<ConnectOutcome>;
+ disconnect: (id: number) => Promise<void>;
+ refresh: () => Promise<void>;
+}
+
+export function useConnectedAccounts(): UseConnectedAccounts {
+ const { config } = useAppConfig();
+ const microsoftOffered = providerOffered(config, "microsoft");
+ const googleOffered = providerOffered(config, "google");
+ const offered = microsoftOffered || googleOffered;
+ const state = useSyncExternalStore(subscribe, () => snapshot);
+
+ useEffect(() => {
+ if (offered && !loaded) {
+ void refreshConnectedAccounts();
+ }
+ }, [offered]);
+
+ const available = useCallback(
+ (provider: CloudProvider) =>
+ provider === "microsoft" ? microsoftOffered : googleOffered,
+ [microsoftOffered, googleOffered],
+ );
+
+ const accountFor = useCallback(
+ (provider: CloudProvider) => findConnected(state.accounts, provider),
+ [state.accounts],
+ );
+
+ const connect = useCallback(async (provider: CloudProvider) => {
+ const outcome = await connectAccount(provider);
+ await refreshConnectedAccounts();
+ return outcome;
+ }, []);
+
+ const disconnect = useCallback(async (id: number) => {
+ const started = generation;
+ await disconnectAccount(id);
+ if (started !== generation) return;
+ generation++;
+ inflight = null;
+ publish({
+ ...snapshot,
+ accounts: snapshot.accounts.filter((account) => account.id !== id),
+ });
+ await refreshConnectedAccounts();
+ }, []);
+
+ return {
+ available,
+ accounts: state.accounts,
+ accountFor,
+ loaded: loaded || !offered,
+ connect,
+ disconnect,
+ refresh: refreshConnectedAccounts,
+ };
+}
diff --git a/frontend/src/editor/core/services/connectedAccountsService.test.ts b/frontend/src/editor/core/services/connectedAccountsService.test.ts
new file mode 100644
index 0000000000..73088f7860
--- /dev/null
+++ b/frontend/src/editor/core/services/connectedAccountsService.test.ts
@@ -0,0 +1,128 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { AxiosError, AxiosHeaders } from "axios";
+import type { TFunction } from "i18next";
+import {
+ connectAccount,
+ connectErrorMessage,
+ PopupBlockedError,
+} from "@editor/services/connectedAccountsService";
+
+const api = vi.hoisted(() => ({
+ post: vi.fn(),
+ get: vi.fn(),
+ delete: vi.fn(),
+}));
+vi.mock("@editor/services/apiClient", () => ({ default: api }));
+
+function fakePopup() {
+ return { closed: false, close: vi.fn(), location: { href: "" } };
+}
+
+describe("connectAccount", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ api.post.mockReset();
+ });
+
+ it("opens the window before asking the server, then sends it to the provider", async () => {
+ const popup = fakePopup();
+ const order: string[] = [];
+ vi.spyOn(window, "open").mockImplementation(() => {
+ order.push("open");
+ return popup as unknown as Window;
+ });
+ api.post.mockImplementation(async () => {
+ order.push("post");
+ return {
+ data: { authorizationUrl: "https://login.example/authorize?x=1" },
+ };
+ });
+
+ const outcome = connectAccount("microsoft");
+ await vi.waitFor(() =>
+ expect(popup.location.href).toBe("https://login.example/authorize?x=1"),
+ );
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { source: "stirling-connected-account", status: "connected" },
+ source: popup as unknown as Window,
+ }),
+ );
+
+ expect(await outcome).toBe("connected");
+ expect(order).toEqual(["open", "post"]);
+ expect(api.post).toHaveBeenCalledWith(
+ "/api/v1/connected-accounts/microsoft/connect",
+ undefined,
+ { suppressErrorToast: true },
+ );
+ });
+
+ it("ignores messages from other windows and reports a closed window", async () => {
+ const popup = fakePopup();
+ vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);
+ api.post.mockResolvedValue({ data: { authorizationUrl: "https://x" } });
+
+ const outcome = connectAccount("google");
+ await vi.waitFor(() => expect(popup.location.href).toBe("https://x"));
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ data: { source: "stirling-connected-account", status: "connected" },
+ }),
+ );
+ popup.closed = true;
+
+ expect(await outcome).toBe("closed");
+ });
+
+ it("fails clearly when the browser blocks the window", async () => {
+ vi.spyOn(window, "open").mockReturnValue(null);
+ await expect(connectAccount("google")).rejects.toBeInstanceOf(
+ PopupBlockedError,
+ );
+ expect(api.post).not.toHaveBeenCalled();
+ });
+});
+
+function httpError(status: number, data: unknown): AxiosError {
+ return new AxiosError(
+ `Request failed with status code ${status}`,
+ "ERR_BAD_REQUEST",
+ undefined,
+ undefined,
+ {
+ status,
+ statusText: "",
+ data,
+ headers: {},
+ config: { headers: new AxiosHeaders() },
+ },
+ );
+}
+
+describe("connectErrorMessage", () => {
+ const t = ((_key: string, fallback: string) => fallback) as TFunction;
+
+ it("shows the server's reason instead of the HTTP status", () => {
+ const error = httpError(409, {
+ status: 409,
+ title: "Conflict",
+ detail: "Google account connections are not set up on this server.",
+ });
+ expect(connectErrorMessage(error, t)).toBe(
+ "Google account connections are not set up on this server.",
+ );
+ });
+
+ it("falls back to a readable message when the server gives no reason", () => {
+ const message = connectErrorMessage(httpError(502, ""), t);
+ expect(message).not.toMatch(/status code/);
+ expect(message.trim()).not.toBe("");
+ });
+
+ it("explains a blocked pop-up", () => {
+ expect(connectErrorMessage(new PopupBlockedError(), t)).toMatch(
+ /blocked the sign-in window/,
+ );
+ });
+});
diff --git a/frontend/src/editor/core/services/connectedAccountsService.ts b/frontend/src/editor/core/services/connectedAccountsService.ts
new file mode 100644
index 0000000000..bb4f69ecbc
--- /dev/null
+++ b/frontend/src/editor/core/services/connectedAccountsService.ts
@@ -0,0 +1,134 @@
+import type { TFunction } from "i18next";
+import apiClient from "@editor/services/apiClient";
+import { extractAxiosErrorMessage } from "@editor/services/httpErrorUtils";
+
+export type CloudProvider = "microsoft" | "google";
+
+export interface ConnectedAccount {
+ id: number;
+ provider: CloudProvider;
+ email: string | null;
+ displayName: string | null;
+ status: "CONNECTED" | "NEEDS_RECONNECT";
+ personal: boolean;
+ lastError: string | null;
+ createdAt: string | null;
+}
+
+export interface ConnectedAccountsState {
+ providers: Record<CloudProvider, boolean>;
+ accounts: ConnectedAccount[];
+}
+
+const BASE = "/api/v1/connected-accounts";
+const CONNECT_MESSAGE_SOURCE = "stirling-connected-account";
+
+export function connectCallbackPath(provider: CloudProvider): string {
+ return `${BASE}/callback/${provider}`;
+}
+
+export function accountLabel(account: ConnectedAccount): string {
+ return account.email ?? account.displayName ?? String(account.id);
+}
+
+export async function fetchConnectedAccounts(): Promise<ConnectedAccountsState> {
+ const response = await apiClient.get<ConnectedAccountsState>(BASE, {
+ suppressErrorToast: true,
+ });
+ return response.data;
+}
+
+export async function fetchRedirectUris(): Promise<
+ Record<CloudProvider, string>
+> {
+ const response = await apiClient.get<Record<CloudProvider, string>>(
+ `${BASE}/redirect-uris`,
+ { suppressErrorToast: true },
+ );
+ return response.data;
+}
+
+export async function disconnectAccount(id: number): Promise<void> {
+ await apiClient.delete(`${BASE}/${id}`);
+}
+
+export type ConnectOutcome = "connected" | "cancelled" | "error" | "closed";
+
+export async function connectAccount(
+ provider: CloudProvider,
+): Promise<ConnectOutcome> {
+ const popup = window.open(
+ "",
+ `stirling-connect-${provider}`,
+ "width=520,height=680,menubar=no,toolbar=no",
+ );
+ if (!popup) {
+ throw new PopupBlockedError();
+ }
+ let url: string;
+ try {
+ const response = await apiClient.post<{ authorizationUrl: string }>(
+ `${BASE}/${provider}/connect`,
+ undefined,
+ { suppressErrorToast: true },
+ );
+ url = response.data.authorizationUrl;
+ } catch (error) {
+ popup.close();
+ throw error;
+ }
+ popup.location.href = url;
+ return waitForPopup(popup);
+}
+
+export function isPopupBlocked(error: unknown): boolean {
+ const failure = error as { code?: string; errorCode?: string } | null;
+ const code = failure?.errorCode ?? failure?.code;
+ return code === "popup_blocked" || code === "popup_window_error";
+}
+
+export function connectErrorMessage(error: unknown, t: TFunction): string {
+ if (isPopupBlocked(error)) {
+ return t(
+ "connectedAccounts.popupBlocked",
+ "Your browser blocked the sign-in window. Allow pop-ups for this site and try again.",
+ );
+ }
+ return extractAxiosErrorMessage(error).body;
+}
+
+export class PopupBlockedError extends Error {
+ readonly code = "popup_blocked";
+ constructor() {
+ super("popup_blocked");
+ }
+}
+
+function waitForPopup(popup: Window): Promise<ConnectOutcome> {
+ return new Promise((resolve) => {
+ let done = false;
+ const finish = (outcome: ConnectOutcome) => {
+ if (done) return;
+ done = true;
+ window.removeEventListener("message", onMessage);
+ window.clearInterval(watch);
+ resolve(outcome);
+ };
+ const onMessage = (event: MessageEvent) => {
+ const data = event.data as { source?: string; status?: string } | null;
+ if (event.source !== popup || data?.source !== CONNECT_MESSAGE_SOURCE) {
+ return;
+ }
+ const status = data.status;
+ finish(
+ status === "connected" || status === "cancelled" || status === "error"
+ ? status
+ : "error",
+ );
+ };
+ window.addEventListener("message", onMessage);
+ const watch = window.setInterval(() => {
+ if (popup.closed) finish("closed");
+ }, 500);
+ });
+}
diff --git a/frontend/src/editor/core/types/appConfig.ts b/frontend/src/editor/core/types/appConfig.ts
index cbf07f2817..c7a2b28829 100644
--- a/frontend/src/editor/core/types/appConfig.ts
+++ b/frontend/src/editor/core/types/appConfig.ts
@@ -75,6 +75,8 @@ export interface AppConfig {
googleDriveClientId?: string;
googleDriveApiKey?: string;
googleDriveAppId?: string;
+ googleDriveAccountConnections?: boolean;
+ microsoftAccountConnections?: boolean;
timestampDefaultTsaUrl?: string;
timestampCustomTsaUrls?: string[];
timestampTsaPresets?: { label: string; url: string }[];
diff --git a/frontend/src/editor/desktop/extensions/accountLogout.ts b/frontend/src/editor/desktop/extensions/accountLogout.ts
index ecac96f470..a48d3c0966 100644
--- a/frontend/src/editor/desktop/extensions/accountLogout.ts
+++ b/frontend/src/editor/desktop/extensions/accountLogout.ts
@@ -1,4 +1,5 @@
import { clearNotificationReadState } from "@editor/hooks/useNotifications";
+import { clearConnectedAccounts } from "@editor/hooks/useConnectedAccounts";
import { connectionModeService } from "@editor/services/connectionModeService";
import { suspendWorkbenchSession } from "@editor/services/workbenchSession";
@@ -24,6 +25,7 @@ export function useAccountLogout() {
suspendWorkbenchSession();
// Same reason: the next person's own failures must not arrive pre-read.
clearNotificationReadState();
+ clearConnectedAccounts();
await signOut();
const currentConfig = await connectionModeService.getCurrentConfig();
diff --git a/frontend/src/editor/proprietary/components/shared/config/configNavSections.tsx b/frontend/src/editor/proprietary/components/shared/config/configNavSections.tsx
index a303be9d96..57799774c0 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configNavSections.tsx
+++ b/frontend/src/editor/proprietary/components/shared/config/configNavSections.tsx
@@ -43,6 +43,9 @@ import AccountCards from "@editor-core/components/shared/config/configSections/p
import AdminAuditSection from "@editor/components/shared/config/configSections/AdminAuditSection";
import AdminUsageSection from "@editor/components/shared/config/configSections/AdminUsageSection";
import ApiKeys from "@editor/components/shared/config/configSections/ApiKeys";
+import ConnectedAccountsSection from "@editor/components/shared/config/configSections/ConnectedAccountsSection";
+import { useAppConfig } from "@editor/contexts/AppConfigContext";
+import { accountConnectionsOffered } from "@editor/hooks/useConnectedAccounts";
/**
* Self-hosted settings, grouped by who reaches for them and what they do there:
@@ -59,6 +62,7 @@ export const useConfigNavSections = (
showSettingsWhenNoLogin: boolean = true,
): ConfigNavSection[] => {
const { t } = useTranslation();
+ const { config } = useAppConfig();
// Core ships Preferences and About; About is the small print and stays last.
const coreSections = useCoreConfigNavSections(
@@ -91,6 +95,18 @@ export const useConfigNavSections = (
component: <ApiKeys />,
});
}
+ if (loginEnabled && accountConnectionsOffered(config)) {
+ preferences.items.push({
+ key: "connectedAccounts",
+ label: t("settings.connectedAccounts.title", "Connected accounts"),
+ description: t(
+ "settings.connectedAccounts.description",
+ "Your own OneDrive, SharePoint and Google Drive, for your pipelines.",
+ ),
+ icon: "cloud",
+ component: <ConnectedAccountsSection />,
+ });
+ }
}
const showAdmin = isAdmin || (!loginEnabled && showSettingsWhenNoLogin);
diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/connectionProviders.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/security/connectionProviders.ts
index 3de9693f2d..9205bc980e 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/connectionProviders.ts
+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/connectionProviders.ts
@@ -33,6 +33,10 @@ export function isProviderConfigured(
return settings?.googleDriveEnabled === true;
}
+ if (provider.id === "microsoft") {
+ return settings?.microsoft?.enabled === true;
+ }
+
if (provider.id === "oauth2-generic") {
return settings?.oauth2?.enabled === true;
}
@@ -64,10 +68,17 @@ export function getProviderSettings(
clientId: settings?.googleDriveClientId,
apiKey: settings?.googleDriveApiKey,
appId: settings?.googleDriveAppId,
+ clientSecret: settings?.googleDriveClientSecret,
+ allowAccountConnections: settings?.googleDriveAllowAccountConnections,
+ accountScope: settings?.googleDriveAccountScope,
};
return gd;
}
+ if (provider.id === "microsoft") {
+ return settings?.microsoft ?? {};
+ }
+
if (provider.id === "oauth2-generic") {
const generic: OAuth2GenericSettings = {
enabled: settings?.oauth2?.enabled,
@@ -108,7 +119,12 @@ export function updateProviderSettings(
googleDriveClientId: gd.clientId,
googleDriveApiKey: gd.apiKey,
googleDriveAppId: gd.appId,
+ googleDriveClientSecret: gd.clientSecret,
+ googleDriveAllowAccountConnections: gd.allowAccountConnections,
+ googleDriveAccountScope: gd.accountScope,
});
+ } else if (provider.id === "microsoft") {
+ setSettings({ ...settings, microsoft: updatedSettings });
} else if (provider.id === "saml2") {
setSettings({ ...settings, saml2: updatedSettings });
} else if (provider.id === "oauth2-generic") {
diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts
index 6883953879..fd058e74ab 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts
+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTransformers.ts
@@ -179,6 +179,20 @@ export async function fetchConnectionsSettings(): Promise<
googleDriveClientId: premiumData.proFeatures?.googleDrive?.clientId || "",
googleDriveApiKey: premiumData.proFeatures?.googleDrive?.apiKey || "",
googleDriveAppId: premiumData.proFeatures?.googleDrive?.appId || "",
+ googleDriveClientSecret:
+ premiumData.proFeatures?.googleDrive?.clientSecret || "",
+ googleDriveAllowAccountConnections:
+ premiumData.proFeatures?.googleDrive?.allowAccountConnections !== false,
+ googleDriveAccountScope:
+ premiumData.proFeatures?.googleDrive?.accountScope || "drive",
+ microsoft: {
+ enabled: premiumData.proFeatures?.microsoft?.enabled || false,
+ clientId: premiumData.proFeatures?.microsoft?.clientId || "",
+ tenant: premiumData.proFeatures?.microsoft?.tenant || "common",
+ clientSecret: premiumData.proFeatures?.microsoft?.clientSecret || "",
+ allowAccountConnections:
+ premiumData.proFeatures?.microsoft?.allowAccountConnections !== false,
+ },
};
// Merge pending blocks from all endpoints
@@ -235,6 +249,20 @@ export async function fetchConnectionsSettings(): Promise<
pendingBlock.googleDriveAppId =
premiumData._pending.proFeatures.googleDrive.appId;
}
+ const pendingGoogle = premiumData._pending?.proFeatures?.googleDrive;
+ if (pendingGoogle?.clientSecret !== undefined) {
+ pendingBlock.googleDriveClientSecret = pendingGoogle.clientSecret;
+ }
+ if (pendingGoogle?.allowAccountConnections !== undefined) {
+ pendingBlock.googleDriveAllowAccountConnections =
+ pendingGoogle.allowAccountConnections;
+ }
+ if (pendingGoogle?.accountScope !== undefined) {
+ pendingBlock.googleDriveAccountScope = pendingGoogle.accountScope;
+ }
+ if (premiumData._pending?.proFeatures?.microsoft !== undefined) {
+ pendingBlock.microsoft = premiumData._pending.proFeatures.microsoft;
+ }
if (Object.keys(pendingBlock).length > 0) {
result._pending = pendingBlock;
@@ -337,6 +365,24 @@ export function saveConnectionsSettings(
deltaSettings["premium.proFeatures.googleDrive.appId"] =
currentSettings.googleDriveAppId;
}
+ const googleExtras: [string, unknown][] = [
+ ["clientSecret", currentSettings?.googleDriveClientSecret],
+ [
+ "allowAccountConnections",
+ currentSettings?.googleDriveAllowAccountConnections,
+ ],
+ ["accountScope", currentSettings?.googleDriveAccountScope],
+ ];
+ for (const [key, value] of googleExtras) {
+ if (value !== undefined) {
+ deltaSettings[`premium.proFeatures.googleDrive.${key}`] = value;
+ }
+ }
+ for (const [key, value] of Object.entries(currentSettings?.microsoft ?? {})) {
+ if (value !== undefined) {
+ deltaSettings[`premium.proFeatures.microsoft.${key}`] = value;
+ }
+ }
return {
sectionData: {},
diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts
index a68ed0aab4..6a7cc877ed 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts
+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/security/securitySettingsTypes.ts
@@ -100,6 +100,17 @@ export interface GoogleDriveSettings {
clientId?: string;
apiKey?: string;
appId?: string;
+ clientSecret?: string;
+ allowAccountConnections?: boolean;
+ accountScope?: string;
+}
+
+export interface MicrosoftSettings {
+ enabled?: boolean;
+ clientId?: string;
+ tenant?: string;
+ clientSecret?: string;
+ allowAccountConnections?: boolean;
}
export interface OAuth2GenericSettings {
@@ -141,6 +152,7 @@ export type ProviderSettings =
| MailSettings
| TelegramSettingsData
| GoogleDriveSettings
+ | MicrosoftSettings
| OAuth2GenericSettings
| Saml2Settings
| OAuth2ClientSettings;
@@ -171,4 +183,8 @@ export interface ConnectionsSettingsData {
googleDriveClientId?: string;
googleDriveApiKey?: string;
googleDriveAppId?: string;
+ googleDriveClientSecret?: string;
+ googleDriveAllowAccountConnections?: boolean;
+ googleDriveAccountScope?: string;
+ microsoft?: MicrosoftSettings;
}
diff --git a/frontend/src/editor/proprietary/policies/outputModes.ts b/frontend/src/editor/proprietary/policies/outputModes.ts
index 158756715b..17a8a6b779 100644
--- a/frontend/src/editor/proprietary/policies/outputModes.ts
+++ b/frontend/src/editor/proprietary/policies/outputModes.ts
@@ -1,6 +1,20 @@
/** Writable destination types, matching the server's hosted filesystem restriction. */
export function availableOutputModes(
hosted = false,
-): ("folder" | "s3" | "vectordb")[] {
- return hosted ? ["s3", "vectordb"] : ["folder", "s3", "vectordb"];
+): (
+ | "folder"
+ | "s3"
+ | "onedrive"
+ | "sharepoint"
+ | "googledrive"
+ | "vectordb"
+)[] {
+ const remote = [
+ "s3",
+ "onedrive",
+ "sharepoint",
+ "googledrive",
+ "vectordb",
+ ] as const;
+ return hosted ? [...remote] : ["folder", ...remote];
}
diff --git a/frontend/src/processor/proprietary/api/integrations.ts b/frontend/src/processor/proprietary/api/integrations.ts
index 39f608cae8..1fa5793531 100644
--- a/frontend/src/processor/proprietary/api/integrations.ts
+++ b/frontend/src/processor/proprietary/api/integrations.ts
@@ -13,7 +13,9 @@ export type IntegrationType =
| "API"
| "PURVIEW"
| "CONSIGNO"
- | "VECTOR_DB";
+ | "VECTOR_DB"
+ | "MICROSOFT_365"
+ | "GOOGLE_WORKSPACE";
export type OwnerScope = "USER" | "TEAM" | "SERVER";
/** Mirrors the backend IntegrationConfigResponse; `config` values are masked. */
diff --git a/frontend/src/processor/proprietary/api/pipelines.ts b/frontend/src/processor/proprietary/api/pipelines.ts
index b2932140a7..c3f0c941b0 100644
--- a/frontend/src/processor/proprietary/api/pipelines.ts
+++ b/frontend/src/processor/proprietary/api/pipelines.ts
@@ -50,7 +50,13 @@ export interface OutputSpec {
}
/** Source types that can be written to (used as a pipeline's output destination). */
-export type PipelineOutputMode = "folder" | "s3" | "vectordb";
+export type PipelineOutputMode =
+ | "folder"
+ | "s3"
+ | "onedrive"
+ | "sharepoint"
+ | "googledrive"
+ | "vectordb";
/**
* The stored policy record: the create/update body (`id` blank on create) and what
diff --git a/frontend/src/processor/proprietary/components/BrandMarks.tsx b/frontend/src/processor/proprietary/components/BrandMarks.tsx
index 87ecb0425f..427cedf694 100644
--- a/frontend/src/processor/proprietary/components/BrandMarks.tsx
+++ b/frontend/src/processor/proprietary/components/BrandMarks.tsx
@@ -4,6 +4,7 @@ import { Icon, isIconName, type IconName } from "@editor/ui/Icon";
/** Ids whose registry name differs from the id itself. */
const ID_ALIASES: Record<string, IconName> = {
email: "mail",
+ googleworkspace: "googledrive",
smb: "hard-drive",
vectordb: "database",
};
diff --git a/frontend/src/processor/proprietary/components/pipelines/DestinationPicker.tsx b/frontend/src/processor/proprietary/components/pipelines/DestinationPicker.tsx
index f6e2cc66d9..b6e671bea5 100644
--- a/frontend/src/processor/proprietary/components/pipelines/DestinationPicker.tsx
+++ b/frontend/src/processor/proprietary/components/pipelines/DestinationPicker.tsx
@@ -40,7 +40,7 @@ export function DestinationPicker({
const chosen = value[0] ?? "";
const hasSources = sources.length > 0;
- // Mirrors the input row: the dropdown-plus-edit sits in a field, and "Connect source" lives on its
+ // Mirrors the input row: the dropdown-plus-edit sits in a field, and "Connect destination" lives on its
// own line below rather than inline. With nowhere to write to yet, only the connect button shows.
return (
<>
@@ -79,7 +79,7 @@ export function DestinationPicker({
onClick={onCreateNew}
leftSection={<Icon name="plus" size={"1.125rem"} />}
>
- {t("portal.sources.actions.connectSource")}
+ {t("portal.sources.actions.connectDestination")}
</Button>
</>
);
diff --git a/frontend/src/processor/proprietary/components/policies/PolicySetupInput.tsx b/frontend/src/processor/proprietary/components/policies/PolicySetupInput.tsx
index cf7bc5977e..eff6664568 100644
--- a/frontend/src/processor/proprietary/components/policies/PolicySetupInput.tsx
+++ b/frontend/src/processor/proprietary/components/policies/PolicySetupInput.tsx
@@ -192,9 +192,16 @@ export function PolicySetupInput({
)}
</div>
{selectedInput.data &&
- ["folder", "s3", "sftp", "ftp", "network"].includes(
- selectedInput.data.type,
- ) && (
+ [
+ "folder",
+ "s3",
+ "sftp",
+ "ftp",
+ "network",
+ "onedrive",
+ "sharepoint",
+ "googledrive",
+ ].includes(selectedInput.data.type) && (
<Banner
tone={
selectedInput.data.options.mode === "consume" ||
diff --git a/frontend/src/processor/proprietary/components/sources/ConnectedAccountPicker.test.tsx b/frontend/src/processor/proprietary/components/sources/ConnectedAccountPicker.test.tsx
new file mode 100644
index 0000000000..ad31469db7
--- /dev/null
+++ b/frontend/src/processor/proprietary/components/sources/ConnectedAccountPicker.test.tsx
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { PortalTestProviders } from "@processor/test/TestQueryProvider";
+import { ConnectedAccountPicker } from "@processor/components/sources/ConnectedAccountPicker";
+import { PopupBlockedError } from "@editor/services/connectedAccountsService";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+const state = vi.hoisted(() => ({
+ available: true,
+ accounts: [] as Array<{ id: number; provider: string; status: string }>,
+ connect: vi.fn(),
+}));
+vi.mock("@editor/hooks/useConnectedAccounts", () => ({
+ useConnectedAccounts: () => ({
+ available: () => state.available,
+ accounts: state.accounts,
+ connect: state.connect,
+ }),
+ latestConnectedAccounts: () => state.accounts,
+}));
+
+function account(status: string) {
+ return { id: 7, provider: "microsoft", status, email: "[email protected]" };
+}
+
+function renderPicker(onChange = vi.fn(), onUnavailable?: () => void) {
+ render(
+ <PortalTestProviders>
+ <ConnectedAccountPicker
+ provider="microsoft"
+ value=""
+ onChange={onChange}
+ onUnavailable={onUnavailable}
+ />
+ </PortalTestProviders>,
+ );
+ return onChange;
+}
+
+describe("ConnectedAccountPicker", () => {
+ beforeEach(() => {
+ state.available = true;
+ state.accounts = [];
+ state.connect.mockReset();
+ });
+
+ it("preselects the only account when it is connected", async () => {
+ state.accounts = [account("CONNECTED")];
+ const onChange = renderPicker();
+ await waitFor(() => expect(onChange).toHaveBeenCalledWith("7"));
+ });
+
+ it("does not preselect an account that needs signing in again", () => {
+ state.accounts = [account("NEEDS_RECONNECT")];
+ const onChange = renderPicker();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("explains a blocked sign-in window", async () => {
+ state.connect.mockRejectedValueOnce(new PopupBlockedError());
+ renderPicker();
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: /portal.sources.cloudFields.account.connect/,
+ }),
+ );
+ expect(
+ await screen.findByText("connectedAccounts.popupBlocked"),
+ ).toBeTruthy();
+ });
+
+ it("reports when connecting your own account is turned off", async () => {
+ state.available = false;
+ const onUnavailable = vi.fn();
+ renderPicker(vi.fn(), onUnavailable);
+ await waitFor(() => expect(onUnavailable).toHaveBeenCalled());
+ });
+
+ it("does not report an available provider", () => {
+ const onUnavailable = vi.fn();
+ renderPicker(vi.fn(), onUnavailable);
+ expect(onUnavailable).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/processor/proprietary/components/sources/ConnectedAccountPicker.tsx b/frontend/src/processor/proprietary/components/sources/ConnectedAccountPicker.tsx
new file mode 100644
index 0000000000..c32a565654
--- /dev/null
+++ b/frontend/src/processor/proprietary/components/sources/ConnectedAccountPicker.tsx
@@ -0,0 +1,129 @@
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Icon } from "@editor/ui/Icon";
+import { Banner, Button, Select } from "@editor/ui";
+import {
+ latestConnectedAccounts,
+ useConnectedAccounts,
+} from "@editor/hooks/useConnectedAccounts";
+import {
+ accountLabel,
+ connectErrorMessage,
+} from "@editor/services/connectedAccountsService";
+import type { CloudAccountProvider } from "@processor/components/sources/sourceTypes";
+import "@processor/components/sources/connections.css";
+
+interface ConnectedAccountPickerProps {
+ provider: CloudAccountProvider;
+ value: string;
+ onChange: (accountId: string) => void;
+ onUnavailable?: () => void;
+}
+
+export function ConnectedAccountPicker({
+ provider,
+ value,
+ onChange,
+ onUnavailable,
+}: ConnectedAccountPickerProps) {
+ const { t } = useTranslation();
+ const { available, accounts, connect } = useConnectedAccounts();
+ const [connecting, setConnecting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const mine = useMemo(
+ () => accounts.filter((account) => account.provider === provider),
+ [accounts, provider],
+ );
+
+ useEffect(() => {
+ if (!value && mine.length === 1 && mine[0].status === "CONNECTED") {
+ onChange(String(mine[0].id));
+ }
+ }, [value, mine, onChange]);
+
+ const unavailable = !available(provider);
+ useEffect(() => {
+ if (unavailable) {
+ onUnavailable?.();
+ }
+ }, [unavailable, onUnavailable]);
+
+ if (unavailable) {
+ return (
+ <Banner
+ tone="info"
+ description={t(
+ "portal.sources.cloudFields.account.unavailable",
+ "Connecting your own account is turned off on this server. Choose an organisation connection instead.",
+ )}
+ />
+ );
+ }
+
+ async function connectNew() {
+ setConnecting(true);
+ setError(null);
+ try {
+ const before = new Set(mine.map((account) => account.id));
+ const outcome = await connect(provider);
+ if (outcome === "error") {
+ setError(
+ t(
+ "portal.sources.cloudFields.account.connectFailed",
+ "The account couldn't be connected. Try again, or ask your administrator to check the app registration.",
+ ),
+ );
+ }
+ const added = latestConnectedAccounts().find(
+ (account) => account.provider === provider && !before.has(account.id),
+ );
+ if (added) {
+ onChange(String(added.id));
+ }
+ } catch (e) {
+ setError(connectErrorMessage(e, t));
+ } finally {
+ setConnecting(false);
+ }
+ }
+
+ return (
+ <div className="portal-sources__connection-picker">
+ {mine.length > 0 && (
+ <Select
+ value={value || null}
+ placeholder={t(
+ "portal.sources.cloudFields.account.placeholder",
+ "Choose an account",
+ )}
+ options={mine.map((account) => ({
+ value: String(account.id),
+ label:
+ account.status === "NEEDS_RECONNECT"
+ ? `${accountLabel(account)} (${t("portal.sources.cloudFields.account.reconnect", "sign in again")})`
+ : accountLabel(account),
+ }))}
+ onChange={(selected) => onChange(selected ?? "")}
+ />
+ )}
+ <Button
+ variant="secondary"
+ loading={connecting}
+ leftSection={<Icon name="plus" size="1em" />}
+ onClick={() => void connectNew()}
+ data-testid={`connect-account-${provider}`}
+ >
+ {mine.length > 0
+ ? t(
+ "portal.sources.cloudFields.account.connectAnother",
+ "Connect another account",
+ )
+ : t(
+ "portal.sources.cloudFields.account.connect",
+ "Connect your account",
+ )}
+ </Button>
+ {error && <Banner tone="danger" description={error} />}
+ </div>
+ );
+}
diff --git a/frontend/src/processor/proprietary/components/sources/SourceModal.test.tsx b/frontend/src/processor/proprietary/components/sources/SourceModal.test.tsx
index 9a4388af5e..58833fad90 100644
--- a/frontend/src/processor/proprietary/components/sources/SourceModal.test.tsx
+++ b/frontend/src/processor/proprietary/components/sources/SourceModal.test.tsx
@@ -48,6 +48,30 @@ vi.mock("@processor/api/integrations", () => ({
createIntegration: (body: unknown) => createIntegration(body),
}));
+const connectedAccounts = vi.hoisted(() => ({
+ available: true,
+ accounts: [
+ {
+ id: 12,
+ provider: "microsoft",
+ email: "[email protected]",
+ displayName: "Pat",
+ status: "CONNECTED",
+ personal: false,
+ lastError: null,
+ createdAt: null,
+ },
+ ],
+}));
+vi.mock("@editor/hooks/useConnectedAccounts", () => ({
+ useConnectedAccounts: () => ({
+ available: () => connectedAccounts.available,
+ accounts: connectedAccounts.accounts,
+ connect: vi.fn(),
+ }),
+ latestConnectedAccounts: () => connectedAccounts.accounts,
+}));
+
function renderModal(sourceId: string | null = null) {
const onClose = vi.fn();
const onSaved = vi.fn();
@@ -253,7 +277,7 @@ describe("SourceModal", () => {
it("lists coming-soon connectors as inert cards", () => {
renderModal();
- fireEvent.click(screen.getByText("portal.sources.types.sharepoint.label"));
+ fireEvent.click(screen.getByText("portal.sources.types.dropbox.label"));
// Still on the type stage: no configure form appeared.
expect(
screen.queryByLabelText(/portal\.sources\.wizard\.name/),
@@ -305,4 +329,161 @@ describe("SourceModal", () => {
await waitFor(() => expect(deleteSource).toHaveBeenCalledWith("src-9"));
expect(onSaved).toHaveBeenCalled();
});
+
+ it("saves a OneDrive location as the user's own connected account", async () => {
+ renderModal();
+ fireEvent.click(screen.getByText("portal.sources.types.onedrive.label"));
+ fireEvent.change(screen.getByLabelText(/portal\.sources\.wizard\.name/), {
+ target: { value: "My scans" },
+ });
+ fireEvent.change(
+ screen.getByLabelText(/portal\.sources\.networkFields\.directory\.label/),
+ { target: { value: "Scans/In" } },
+ );
+ expect(
+ screen.queryByText("portal.sources.cloudFields.connection.label"),
+ ).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByText("portal.sources.builder.create"));
+
+ await waitFor(() => expect(createSource).toHaveBeenCalledTimes(1));
+ const saved = createSource.mock.calls[0][0] as {
+ options: Record<string, string>;
+ };
+ expect(saved.options).toMatchObject({
+ authMode: "account",
+ accountId: "12",
+ directory: "Scans/In",
+ });
+ expect(saved.options).not.toHaveProperty("connectionId");
+ });
+
+ it("shows an API-created organisation location with its connection, not an account", async () => {
+ fetchSource.mockResolvedValue({
+ id: "src-5",
+ name: "Finance",
+ type: "sharepoint",
+ options: { connectionId: "7", directory: "Invoices" },
+ enabled: true,
+ });
+ renderModal("src-5");
+
+ expect(
+ await screen.findByText("portal.sources.cloudFields.connection.label"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("portal.sources.cloudFields.account.label"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("portal.sources.cloudFields.authMode.accountsOff"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByPlaceholderText(
+ "portal.sources.cloudFields.sharepoint.organisationPlaceholder",
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it("starts on an organisation connection when your own account is turned off", async () => {
+ connectedAccounts.available = false;
+ try {
+ renderModal();
+ fireEvent.click(
+ screen.getByText("portal.sources.types.googledrive.label"),
+ );
+ expect(
+ await screen.findByText("portal.sources.cloudFields.connection.label"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("portal.sources.cloudFields.account.label"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByText("portal.sources.cloudFields.authMode.accountsOff"),
+ ).toBeInTheDocument();
+ } finally {
+ connectedAccounts.available = true;
+ }
+ });
+
+ it("keeps My account when your own account can be connected", () => {
+ renderModal();
+ fireEvent.click(screen.getByText("portal.sources.types.onedrive.label"));
+ expect(
+ screen.getByText("portal.sources.cloudFields.account.label"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("portal.sources.cloudFields.connection.label"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("titles and describes the picker as a destination for outputs", () => {
+ render(<SourceModal open direction="output" onClose={vi.fn()} />);
+ expect(
+ screen.getByText("portal.sources.builder.createDestinationTitle"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("portal.sources.types.onedrive.outputDescription"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("portal.sources.types.onedrive.description"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("offers a destination only the settings that apply to writing", async () => {
+ render(<SourceModal open direction="output" onClose={vi.fn()} />);
+ fireEvent.click(screen.getByText("portal.sources.types.sharepoint.label"));
+ fireEvent.change(screen.getByLabelText(/portal\.sources\.wizard\.name/), {
+ target: { value: "Signed contracts" },
+ });
+ expect(
+ screen.getByPlaceholderText(
+ "portal.sources.cloudFields.sharepoint.placeholder",
+ ),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.queryByText("portal.sources.networkFields.recursive.label"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("portal.sources.builder.advanced"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("portal.sources.builder.create"),
+ ).not.toBeInTheDocument();
+
+ fireEvent.click(
+ screen.getByText("portal.sources.builder.createDestination"),
+ );
+ await waitFor(() => expect(createSource).toHaveBeenCalledTimes(1));
+ const saved = createSource.mock.calls[0][0] as {
+ type: string;
+ options: Record<string, string>;
+ };
+ expect(saved.type).toBe("sharepoint");
+ expect(saved.options).toMatchObject({
+ authMode: "account",
+ accountId: "12",
+ });
+ });
+
+ it("keeps the processing settings on a source", () => {
+ renderModal();
+ fireEvent.click(screen.getByText("portal.sources.types.sharepoint.label"));
+ expect(
+ screen.getByText("portal.sources.networkFields.recursive.label"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("portal.sources.builder.advanced"),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps source wording for inputs", () => {
+ renderModal();
+ expect(
+ screen.getByText("portal.sources.builder.createTitle"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("portal.sources.types.onedrive.description"),
+ ).toBeInTheDocument();
+ });
});
diff --git a/frontend/src/processor/proprietary/components/sources/SourceModal.tsx b/frontend/src/processor/proprietary/components/sources/SourceModal.tsx
index fa323cab40..6768533f8d 100644
--- a/frontend/src/processor/proprietary/components/sources/SourceModal.tsx
+++ b/frontend/src/processor/proprietary/components/sources/SourceModal.tsx
@@ -35,6 +35,8 @@ import {
import { BrandMark } from "@processor/components/BrandMarks";
import { S3ConnectionPicker } from "@processor/components/sources/S3ConnectionPicker";
import { ConnectionPicker } from "@processor/components/sources/ConnectionPicker";
+import { ConnectedAccountPicker } from "@processor/components/sources/ConnectedAccountPicker";
+import { useConnectedAccounts } from "@editor/hooks/useConnectedAccounts";
import { ConnectionForm } from "@processor/components/sources/ConnectionForm";
import {
CREATABLE_CONNECTION_TYPES,
@@ -71,6 +73,26 @@ function optionsFor(
for (const [key, value] of Object.entries(options ?? {})) {
out[key] = value == null ? "" : String(value);
}
+ if (
+ type.fields.some((field) => field.key === "authMode") &&
+ !options?.authMode
+ ) {
+ out.authMode = options?.connectionId ? "organisation" : "account";
+ }
+ return out;
+}
+
+function visibleOptions(
+ type: CreatableSourceType,
+ options: Record<string, string>,
+ visible: (field: SourceFieldDef) => boolean,
+): Record<string, string> {
+ const out = { ...options };
+ for (const field of type.fields) {
+ if (!visible(field)) {
+ delete out[field.key];
+ }
+ }
return out;
}
@@ -130,6 +152,7 @@ export function SourceModal({
}: SourceModalProps) {
const { t } = useTranslation();
const queryClient = useQueryClient();
+ const { available: accountsAvailable } = useConnectedAccounts();
const isEdit = Boolean(sourceId);
const offeredTypes = useMemo(
() =>
@@ -181,6 +204,7 @@ export function SourceModal({
// The "Advanced" disclosure starts closed; on edit it opens if a stored value
// there differs from its default, so nothing non-standard hides behind it.
const [showAdvanced, setShowAdvanced] = useState(false);
+ const [authModeChosen, setAuthModeChosen] = useState(false);
// Seed on every open: fresh catalogue for create, fetched record for edit.
useEffect(() => {
@@ -197,6 +221,7 @@ export function SourceModal({
setEnabled(true);
setLoaded(null);
setShowAdvanced(Boolean(initialOptions?.mode));
+ setAuthModeChosen(Boolean(initialOptions?.authMode));
return;
}
setStage("configure");
@@ -224,15 +249,22 @@ export function SourceModal({
setType(next);
setOptions({ ...defaultOptions(next), ...initialOptions });
setShowAdvanced(Boolean(initialOptions?.mode));
+ setAuthModeChosen(Boolean(initialOptions?.authMode));
setStage("configure");
}
function setOption(key: string, value: string) {
+ if (key === "authMode") {
+ setAuthModeChosen(true);
+ }
setOptions((current) => ({ ...current, [key]: value }));
}
const requiredComplete = type.fields.every(
- (field) => !field.required || (options[field.key] ?? "").trim() !== "",
+ (field) =>
+ !field.required ||
+ !fieldShown(field) ||
+ (options[field.key] ?? "").trim() !== "",
);
const canSave = name.trim() !== "" && requiredComplete && !submitting;
@@ -289,7 +321,7 @@ export function SourceModal({
id: isEdit ? (sourceId ?? undefined) : undefined,
name: name.trim(),
type: type.type,
- options,
+ options: visibleOptions(type, options, fieldVisible),
enabled,
});
await invalidateSources();
@@ -357,7 +389,9 @@ export function SourceModal({
return t(
isEdit
? "portal.sources.builder.editTitle"
- : "portal.sources.builder.createTitle",
+ : direction === "output"
+ ? "portal.sources.builder.createDestinationTitle"
+ : "portal.sources.builder.createTitle",
);
}
}
@@ -413,7 +447,9 @@ export function SourceModal({
>
{isEdit
? t("portal.sources.builder.save")
- : t("portal.sources.builder.create")}
+ : direction === "output"
+ ? t("portal.sources.builder.createDestination")
+ : t("portal.sources.builder.create")}
</Button>
</div>
);
@@ -501,13 +537,21 @@ export function SourceModal({
);
}
+ function placeholderFor(field: SourceFieldDef): string | undefined {
+ const when = field.placeholderWhen;
+ if (when && when.oneOf.includes(options[when.key] ?? "")) {
+ return t(when.placeholderKey);
+ }
+ return field.placeholderKey ? t(field.placeholderKey) : undefined;
+ }
+
function renderInputControl(field: SourceFieldDef) {
return (
<Input
type={field.control === "password" ? "password" : undefined}
value={options[field.key] ?? ""}
className={privateContentClassName}
- placeholder={field.placeholderKey ? t(field.placeholderKey) : undefined}
+ placeholder={placeholderFor(field)}
onChange={(e) => setOption(field.key, e.target.value)}
/>
);
@@ -519,6 +563,19 @@ export function SourceModal({
return renderS3ConnectionControl(field);
case "connection":
return renderConnectionControl(field);
+ case "account":
+ return (
+ <ConnectedAccountPicker
+ provider={field.provider ?? "microsoft"}
+ value={options[field.key] ?? ""}
+ onChange={(id) => setOption(field.key, id)}
+ onUnavailable={
+ isEdit || authModeChosen
+ ? undefined
+ : () => setOptions((o) => ({ ...o, authMode: "organisation" }))
+ }
+ />
+ );
case "select":
return renderSelectControl(field);
default:
@@ -526,12 +583,27 @@ export function SourceModal({
}
}
+ function personalAccountsOff(field: SourceFieldDef): boolean {
+ if (field.key !== "authMode" || options.authMode !== "organisation") {
+ return false;
+ }
+ const accountField = type.fields.find((f) => f.control === "account");
+ return Boolean(
+ accountField?.provider && !accountsAvailable(accountField.provider),
+ );
+ }
+
function renderField(field: SourceFieldDef) {
return (
<FormField
key={field.key}
label={t(field.labelKey)}
info={field.helperTextKey ? t(field.helperTextKey) : undefined}
+ helperText={
+ personalAccountsOff(field)
+ ? t("portal.sources.cloudFields.authMode.accountsOff")
+ : undefined
+ }
required={field.required}
>
{renderControl(field)}
@@ -546,7 +618,14 @@ export function SourceModal({
return !cond || cond.oneOf.includes(options[cond.key] ?? "");
}
- const visibleFields = type.fields.filter(fieldVisible);
+ function fieldShown(field: SourceFieldDef): boolean {
+ return (
+ fieldVisible(field) &&
+ !(field.inputOnly && direction === "output" && !isEdit)
+ );
+ }
+
+ const visibleFields = type.fields.filter(fieldShown);
const primaryFields = visibleFields.filter((field) => !field.advanced);
const advancedFields = visibleFields.filter((field) => field.advanced);
const back = stageBack();
@@ -592,7 +671,11 @@ export function SourceModal({
{t(ct.labelKey)}
</span>
<span className="portal-source-modal__card-desc">
- {t(ct.descriptionKey)}
+ {t(
+ direction === "output"
+ ? (ct.outputDescriptionKey ?? ct.descriptionKey)
+ : ct.descriptionKey,
+ )}
</span>
</span>
</button>
diff --git a/frontend/src/processor/proprietary/components/sources/connectionTypes.ts b/frontend/src/processor/proprietary/components/sources/connectionTypes.ts
index 23aa84bb99..efb175ec47 100644
--- a/frontend/src/processor/proprietary/components/sources/connectionTypes.ts
+++ b/frontend/src/processor/proprietary/components/sources/connectionTypes.ts
@@ -307,6 +307,75 @@ const PURVIEW_FIELDS: ConnectionFieldDef[] = [
},
];
+const MICROSOFT_APP_FIELDS: ConnectionFieldDef[] = [
+ {
+ key: "tenantId",
+ labelKey: `${PREFIX}.microsoft365.fields.tenantId.label`,
+ control: "text",
+ required: true,
+ placeholderKey: `${PREFIX}.microsoft365.fields.tenantId.placeholder`,
+ },
+ {
+ key: "clientId",
+ labelKey: `${PREFIX}.microsoft365.fields.clientId.label`,
+ control: "text",
+ required: true,
+ helperTextKey: `${PREFIX}.microsoft365.fields.clientId.helperText`,
+ },
+ {
+ key: "clientSecret",
+ labelKey: `${PREFIX}.microsoft365.fields.clientSecret.label`,
+ control: "password",
+ required: true,
+ },
+];
+
+const GOOGLE_WORKSPACE_FIELDS: ConnectionFieldDef[] = [
+ {
+ key: "credentialsJson",
+ labelKey: `${PREFIX}.googleworkspace.fields.credentialsJson.label`,
+ control: "textarea",
+ required: true,
+ helperTextKey: `${PREFIX}.googleworkspace.fields.credentialsJson.helperText`,
+ },
+ {
+ key: "subject",
+ labelKey: `${PREFIX}.googleworkspace.fields.subject.label`,
+ control: "text",
+ placeholderKey: `${PREFIX}.googleworkspace.fields.subject.placeholder`,
+ helperTextKey: `${PREFIX}.googleworkspace.fields.subject.helperText`,
+ },
+];
+
+const ONEDRIVE_FIELDS: ConnectionFieldDef[] = [
+ ...MICROSOFT_APP_FIELDS,
+ {
+ key: "user",
+ labelKey: `${PREFIX}.onedrive.fields.user.label`,
+ control: "text",
+ required: true,
+ placeholderKey: `${PREFIX}.onedrive.fields.user.placeholder`,
+ helperTextKey: `${PREFIX}.onedrive.fields.user.helperText`,
+ },
+];
+
+const SHAREPOINT_FIELDS: ConnectionFieldDef[] = [
+ ...MICROSOFT_APP_FIELDS,
+ {
+ key: "siteUrl",
+ labelKey: `${PREFIX}.sharepoint.fields.siteUrl.label`,
+ control: "text",
+ required: true,
+ placeholderKey: `${PREFIX}.sharepoint.fields.siteUrl.placeholder`,
+ },
+ {
+ key: "library",
+ labelKey: `${PREFIX}.sharepoint.fields.library.label`,
+ control: "text",
+ helperTextKey: `${PREFIX}.sharepoint.fields.library.helperText`,
+ },
+];
+
const CONSIGNO_FIELDS: ConnectionFieldDef[] = [
{
key: "baseUrl",
@@ -586,7 +655,7 @@ function apiPreset(spec: {
*
* 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
+ * Mindee are all submit-then-poll. Google 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.
*/
@@ -860,6 +929,44 @@ export const CREATABLE_CONNECTION_TYPES: CreatableConnectionType[] = [
presetConfig: { protocol: "SMB" },
fields: SMB_FIELDS,
},
+ {
+ id: "onedrive",
+ integrationType: "MICROSOFT_365",
+ kind: "preset",
+ category: "storage",
+ labelKey: `${PREFIX}.onedrive.label`,
+ descriptionKey: `${PREFIX}.onedrive.description`,
+ searchTerms: ["microsoft 365", "office 365", "m365", "entra", "azure"],
+ presetConfig: { drive: "onedrive" },
+ fields: ONEDRIVE_FIELDS,
+ },
+ {
+ id: "sharepoint",
+ integrationType: "MICROSOFT_365",
+ kind: "preset",
+ category: "storage",
+ labelKey: `${PREFIX}.sharepoint.label`,
+ descriptionKey: `${PREFIX}.sharepoint.description`,
+ searchTerms: [
+ "microsoft 365",
+ "office 365",
+ "m365",
+ "teams",
+ "document library",
+ ],
+ presetConfig: { drive: "sharepoint" },
+ fields: SHAREPOINT_FIELDS,
+ },
+ {
+ id: "googleworkspace",
+ integrationType: "GOOGLE_WORKSPACE",
+ kind: "preset",
+ category: "storage",
+ labelKey: `${PREFIX}.googleworkspace.label`,
+ descriptionKey: `${PREFIX}.googleworkspace.description`,
+ searchTerms: ["google", "drive", "workspace", "g suite", "service account"],
+ fields: GOOGLE_WORKSPACE_FIELDS,
+ },
{
id: "purview",
integrationType: "PURVIEW",
diff --git a/frontend/src/processor/proprietary/components/sources/sourceTypes.test.ts b/frontend/src/processor/proprietary/components/sources/sourceTypes.test.ts
new file mode 100644
index 0000000000..b892888bfd
--- /dev/null
+++ b/frontend/src/processor/proprietary/components/sources/sourceTypes.test.ts
@@ -0,0 +1,23 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+
+import { CREATABLE_SOURCE_TYPES } from "@processor/components/sources/sourceTypes";
+
+function modeDefault(type: string) {
+ return CREATABLE_SOURCE_TYPES.find(
+ (source) => source.type === type,
+ )?.fields.find((field) => field.key === "mode")?.defaultValue;
+}
+
+describe("cloud source modes", () => {
+ it.each(["onedrive", "sharepoint", "googledrive"])(
+ "%s keeps the user's originals unless consume is chosen",
+ (type) => {
+ expect(modeDefault(type)).toBe("track");
+ },
+ );
+
+ it("network folders still consume by default", () => {
+ expect(modeDefault("sftp")).toBe("consume");
+ });
+});
diff --git a/frontend/src/processor/proprietary/components/sources/sourceTypes.ts b/frontend/src/processor/proprietary/components/sources/sourceTypes.ts
index 5cae0c26de..bcbde43ad7 100644
--- a/frontend/src/processor/proprietary/components/sources/sourceTypes.ts
+++ b/frontend/src/processor/proprietary/components/sources/sourceTypes.ts
@@ -1,3 +1,4 @@
+import type { CloudProvider } from "@editor/services/connectedAccountsService";
import type { ChipAccent } from "@editor/ui";
/**
@@ -57,6 +58,18 @@ const SOURCE_TYPE_META: Record<string, SourceTypeMeta> = {
labelKey: "portal.sources.types.webhook.label",
accent: "warning",
},
+ googledrive: {
+ labelKey: "portal.sources.types.googledrive.label",
+ accent: "brand",
+ },
+ onedrive: {
+ labelKey: "portal.sources.types.onedrive.label",
+ accent: "brand",
+ },
+ sharepoint: {
+ labelKey: "portal.sources.types.sharepoint.label",
+ accent: "brand",
+ },
};
const UNKNOWN_TYPE_META: SourceTypeMeta = {
@@ -72,9 +85,16 @@ export function sourceTypeMeta(type: string): SourceTypeMeta {
export interface SourceFieldDef {
key: string;
labelKey: string;
- control: "text" | "password" | "select" | "s3Connection" | "connection";
+ control:
+ | "text"
+ | "password"
+ | "select"
+ | "s3Connection"
+ | "connection"
+ | "account";
required?: boolean;
placeholderKey?: string;
+ placeholderWhen?: { key: string; oneOf: string[]; placeholderKey: string };
helperTextKey?: string;
options?: { value: string; labelKey: string }[];
defaultValue?: string;
@@ -87,13 +107,18 @@ export interface SourceFieldDef {
* "sftp"). Filters the picker to matching connections and pins the inline "new connection" form.
*/
connectionTypeId?: string;
+ provider?: CloudAccountProvider;
+ inputOnly?: boolean;
}
+export type CloudAccountProvider = CloudProvider;
+
/** A source type the wizard can create, with the fields its config needs. */
export interface CreatableSourceType {
type: string;
labelKey: string;
descriptionKey: string;
+ outputDescriptionKey?: string;
fields: SourceFieldDef[];
readable?: boolean;
}
@@ -122,6 +147,7 @@ function networkSourceFields(connectionTypeId: string): SourceFieldDef[] {
},
{
key: "mode",
+ inputOnly: true,
labelKey: "portal.sources.networkFields.mode.label",
control: "select",
defaultValue: "consume",
@@ -144,6 +170,7 @@ function networkSourceFields(connectionTypeId: string): SourceFieldDef[] {
},
{
key: "recursive",
+ inputOnly: true,
labelKey: "portal.sources.networkFields.recursive.label",
control: "select",
defaultValue: "false",
@@ -162,11 +189,89 @@ function networkSourceFields(connectionTypeId: string): SourceFieldDef[] {
];
}
+const CLOUD_FOLDER_COPY = {
+ onedrive: {
+ placeholderKey: "portal.sources.cloudFields.onedrive.placeholder",
+ helperTextKey: "portal.sources.cloudFields.onedrive.helperText",
+ },
+ sharepoint: {
+ placeholderKey: "portal.sources.cloudFields.sharepoint.placeholder",
+ placeholderWhen: {
+ key: "authMode",
+ oneOf: ["organisation"],
+ placeholderKey:
+ "portal.sources.cloudFields.sharepoint.organisationPlaceholder",
+ },
+ helperTextKey: "portal.sources.cloudFields.sharepoint.helperText",
+ },
+ googledrive: {
+ placeholderKey: "portal.sources.cloudFields.googledrive.placeholder",
+ helperTextKey: "portal.sources.cloudFields.googledrive.helperText",
+ },
+};
+
+function cloudSourceFields(
+ provider: CloudAccountProvider,
+ organisationConnectionTypeId: string,
+ copyKey: keyof typeof CLOUD_FOLDER_COPY,
+): SourceFieldDef[] {
+ const network = networkSourceFields(organisationConnectionTypeId);
+ const modeAndDepth = network
+ .filter((field) => field.key === "mode" || field.key === "recursive")
+ .map((field) =>
+ field.key === "mode" ? { ...field, defaultValue: "track" } : field,
+ );
+ return [
+ {
+ key: "authMode",
+ labelKey: "portal.sources.cloudFields.authMode.label",
+ control: "select",
+ defaultValue: "account",
+ helperTextKey: "portal.sources.cloudFields.authMode.helperText",
+ options: [
+ {
+ value: "account",
+ labelKey: "portal.sources.cloudFields.authMode.options.account",
+ },
+ {
+ value: "organisation",
+ labelKey: "portal.sources.cloudFields.authMode.options.organisation",
+ },
+ ],
+ },
+ {
+ key: "accountId",
+ labelKey: "portal.sources.cloudFields.account.label",
+ control: "account",
+ provider,
+ required: true,
+ visibleWhen: { key: "authMode", oneOf: ["account"] },
+ },
+ {
+ key: "connectionId",
+ labelKey: "portal.sources.cloudFields.connection.label",
+ control: "connection",
+ connectionTypeId: organisationConnectionTypeId,
+ required: true,
+ helperTextKey: "portal.sources.cloudFields.connection.helperText",
+ visibleWhen: { key: "authMode", oneOf: ["organisation"] },
+ },
+ {
+ key: "directory",
+ labelKey: "portal.sources.networkFields.directory.label",
+ control: "text",
+ ...CLOUD_FOLDER_COPY[copyKey],
+ },
+ ...modeAndDepth,
+ ];
+}
+
export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
{
type: "folder",
labelKey: "portal.sources.types.folder.label",
descriptionKey: "portal.sources.types.folder.description",
+ outputDescriptionKey: "portal.sources.types.folder.outputDescription",
fields: [
{
key: "directory",
@@ -180,6 +285,7 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
},
{
key: "mode",
+ inputOnly: true,
labelKey: "portal.sources.types.folder.fields.mode.label",
control: "select",
defaultValue: "consume",
@@ -203,6 +309,7 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
},
{
key: "recursive",
+ inputOnly: true,
labelKey: "portal.sources.types.folder.fields.recursive.label",
control: "select",
defaultValue: "false",
@@ -223,6 +330,7 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
},
{
key: "identity",
+ inputOnly: true,
labelKey: "portal.sources.types.folder.fields.identity.label",
control: "select",
defaultValue: "stat",
@@ -250,6 +358,7 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
type: "s3",
labelKey: "portal.sources.types.s3.label",
descriptionKey: "portal.sources.types.s3.description",
+ outputDescriptionKey: "portal.sources.types.s3.outputDescription",
fields: [
{
key: "connectionId",
@@ -267,6 +376,7 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
},
{
key: "mode",
+ inputOnly: true,
labelKey: "portal.sources.types.s3.fields.mode.label",
control: "select",
defaultValue: "consume",
@@ -307,6 +417,27 @@ export const CREATABLE_SOURCE_TYPES: CreatableSourceType[] = [
descriptionKey: "portal.sources.types.network.description",
fields: networkSourceFields("smb"),
},
+ {
+ type: "onedrive",
+ labelKey: "portal.sources.types.onedrive.label",
+ descriptionKey: "portal.sources.types.onedrive.description",
+ outputDescriptionKey: "portal.sources.types.onedrive.outputDescription",
+ fields: cloudSourceFields("microsoft", "onedrive", "onedrive"),
+ },
+ {
+ type: "sharepoint",
+ labelKey: "portal.sources.types.sharepoint.label",
+ descriptionKey: "portal.sources.types.sharepoint.description",
+ outputDescriptionKey: "portal.sources.types.sharepoint.outputDescription",
+ fields: cloudSourceFields("microsoft", "sharepoint", "sharepoint"),
+ },
+ {
+ type: "googledrive",
+ labelKey: "portal.sources.types.googledrive.label",
+ descriptionKey: "portal.sources.types.googledrive.description",
+ outputDescriptionKey: "portal.sources.types.googledrive.outputDescription",
+ fields: cloudSourceFields("google", "googleworkspace", "googledrive"),
+ },
{
type: WEBHOOK_SOURCE_TYPE,
labelKey: "portal.sources.types.webhook.label",
@@ -364,9 +495,6 @@ export interface ComingSoonSourceType {
* nothing here can be created and the backend never sees these type strings.
*/
export const COMING_SOON_SOURCE_TYPES: ComingSoonSourceType[] = [
- "sharepoint",
- "onedrive",
- "googledrive",
"dropbox",
"box",
"email",
diff --git a/frontend/src/processor/proprietary/views/Integrations.test.tsx b/frontend/src/processor/proprietary/views/Integrations.test.tsx
index d4eb1f8290..eb37233fe4 100644
--- a/frontend/src/processor/proprietary/views/Integrations.test.tsx
+++ b/frontend/src/processor/proprietary/views/Integrations.test.tsx
@@ -76,9 +76,12 @@ describe("Integrations view", () => {
expect(
screen.getAllByText("portal.integrations.connect").length,
).toBeGreaterThan(5);
+ expect(
+ screen.getByText("portal.connections.types.sharepoint.label"),
+ ).toBeInTheDocument();
// Roadmap source connectors are listed greyed, not connectable.
expect(
- screen.getByText("portal.sources.types.sharepoint.label"),
+ screen.getByText("portal.sources.types.dropbox.label"),
).toBeInTheDocument();
});
diff --git a/frontend/src/processor/proprietary/views/Integrations.tsx b/frontend/src/processor/proprietary/views/Integrations.tsx
index 927c923c1f..078ebaab08 100644
--- a/frontend/src/processor/proprietary/views/Integrations.tsx
+++ b/frontend/src/processor/proprietary/views/Integrations.tsx
@@ -52,7 +52,8 @@ type WorksWith = "sources" | "policies" | "pipelines";
/** What a vendor plugs into, derived from the catalogues rather than declared. */
function worksWith(type: CreatableConnectionType): WorksWith[] {
- if (type.id === "s3") return ["sources", "pipelines"];
+ if (["s3", "onedrive", "sharepoint", "googleworkspace"].includes(type.id))
+ return ["sources", "pipelines"];
if (type.kind === "custom") return ["policies", "pipelines"];
const hasStep = STEP_OPERATIONS.some((op) => op.connectionTypeId === type.id);
// Catalogue operations surface in both the policy step and pipeline pickers.
@@ -67,6 +68,10 @@ function connectionDetail(connection: IntegrationConfig): string {
return String(config.bucket ?? "");
case "PURVIEW":
return String(config.tenantId ?? "");
+ case "MICROSOFT_365":
+ return String(config.user ?? config.siteUrl ?? "");
+ case "GOOGLE_WORKSPACE":
+ return String(config.subject ?? "");
default:
return String(config.baseUrl ?? "");
}
diff --git a/frontend/src/processor/saas/components/pipelines/outputModes.test.ts b/frontend/src/processor/saas/components/pipelines/outputModes.test.ts
index 646413d349..5bddd3f745 100644
--- a/frontend/src/processor/saas/components/pipelines/outputModes.test.ts
+++ b/frontend/src/processor/saas/components/pipelines/outputModes.test.ts
@@ -5,6 +5,12 @@ import { availableOutputModes } from "@processor/components/pipelines/outputMode
describe("availableOutputModes (SaaS)", () => {
it("offers durable destinations without exposing the server filesystem", () => {
- expect(availableOutputModes()).toEqual(["s3", "vectordb"]);
+ expect(availableOutputModes()).toEqual([
+ "s3",
+ "onedrive",
+ "sharepoint",
+ "googledrive",
+ "vectordb",
+ ]);
});
});