From e325d5c10e55572983852aa7b203e614d3e7e7c7 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 09:52:52 -0500 Subject: [PATCH 1/5] fix(agent): build room folders only from a single safe room id and keep delegation files in the room --- .../cluster/util/clients/CentralCloudStorage.java | 9 +++++---- .../engine/impl/model/ClaudeCodeManager.java | 4 ++-- .../engine/impl/model/GitHubCopilotPyManager.java | 2 +- src/prerna/engine/impl/model/Room.java | 2 ++ .../agent/ClaudeCodeTranscriptLocator.java | 6 +++--- .../agent/GitHubCopilotTranscriptLocator.java | 6 +++--- .../reactor/agent/run/HumanDelegationService.java | 8 +++++++- src/prerna/util/Utility.java | 15 +++++++++++++++ 8 files changed, 38 insertions(+), 14 deletions(-) diff --git a/src/prerna/cluster/util/clients/CentralCloudStorage.java b/src/prerna/cluster/util/clients/CentralCloudStorage.java index ba4411e612c..98b436db501 100644 --- a/src/prerna/cluster/util/clients/CentralCloudStorage.java +++ b/src/prerna/cluster/util/clients/CentralCloudStorage.java @@ -53,6 +53,7 @@ import prerna.engine.api.IEngine.CATALOG_TYPE; import prerna.engine.impl.AbstractDatabaseEngine; import prerna.engine.impl.SmssUtilities; +import prerna.engine.impl.model.Room; import prerna.engine.impl.owl.WriteOWLEngine; import prerna.engine.impl.storage.AbstractStorageEngine; import prerna.engine.impl.storage.AzureBlobStorageEngine; @@ -586,6 +587,8 @@ public void pullEngine(String engineId, IEngine.CATALOG_TYPE engineType, boolean classLogger.warn("Engine id '{}' is being requested but does not exist", engineId); return; } + // the id makes up the local folder name below + Utility.requireSafePathSegment(engineId, "engine id"); // We need to pull the folder alias__databaseId and the file // alias__databaseId.smss @@ -1865,8 +1868,7 @@ public void pushUserAsset(String projectId) throws IOException, InterruptedExcep * @throws InterruptedException */ public void pullRoomFolderFromCloud(String roomId) throws IOException, InterruptedException { - String localFolderPath = Utility.getBaseFolder() + File.separator + Constants.ROOM_FOLDER + File.separator - + roomId; + String localFolderPath = Room.roomFolderPath(roomId); // copy, not sync - a sync deletes local files that are missing on the cloud // side, which wipes in-flight session state mid turn when the cloud is empty. storageCopyToLocal(ROOM_CONTAINER_PREFIX + roomId, localFolderPath); @@ -1879,8 +1881,7 @@ public void pullRoomFolderFromCloud(String roomId) throws IOException, Interrupt * @throws InterruptedException */ public void pushRoomFolderToCloud(String roomId) throws IOException, InterruptedException { - String localFolderPath = Utility.getBaseFolder() + File.separator + Constants.ROOM_FOLDER + File.separator - + roomId; + String localFolderPath = Room.roomFolderPath(roomId); if (Utility.folderIsNotEmpty(localFolderPath)) { storageSyncLocalToStorage(localFolderPath, ROOM_CONTAINER_PREFIX + roomId); diff --git a/src/prerna/engine/impl/model/ClaudeCodeManager.java b/src/prerna/engine/impl/model/ClaudeCodeManager.java index 71a4bb9e73d..10cad9f52b1 100644 --- a/src/prerna/engine/impl/model/ClaudeCodeManager.java +++ b/src/prerna/engine/impl/model/ClaudeCodeManager.java @@ -82,7 +82,7 @@ private String createInitScript(String roomId, String filePath, String accessKey String localProtocol = ThreadStore.getLocalProtocol(); String baseUrl = localProtocol + "://" + "localhost" + ":" + localPort + "/Monolith/api/model/anthropic"; String mcpBaseUrl = localProtocol + "://" + "localhost" + ":" + localPort + "/Monolith/api/ext/mcp/"; - String roomFolderPath = Utility.getBaseFolder() + File.separator + "room" + File.separator + roomId; + String roomFolderPath = Room.roomFolderPath(roomId); boolean agentHistoryExists = agentHistoryExists(roomFolderPath, roomId); String allowedToolsLiteral; @@ -219,7 +219,7 @@ public String query(Insight insight, User user, String engineId, String filePath classLogger.debug("InsightID for this query is {} and the roomId is {}", insightId, roomId); String finalFilePath = (filePath != null && !filePath.trim().isEmpty()) ? filePath - : Utility.getBaseFolder() + File.separator + "room" + File.separator + roomId; + : Room.roomFolderPath(roomId); String[] keyPair = user.createCachedTemporalAccessSecretKey(); String accessKey = keyPair[0]; diff --git a/src/prerna/engine/impl/model/GitHubCopilotPyManager.java b/src/prerna/engine/impl/model/GitHubCopilotPyManager.java index 2d11e33bf32..32e89dd54c5 100644 --- a/src/prerna/engine/impl/model/GitHubCopilotPyManager.java +++ b/src/prerna/engine/impl/model/GitHubCopilotPyManager.java @@ -110,7 +110,7 @@ public String query(Insight insight, User user, String engineId, String filePath String insightId = insight.getInsightId(); classLogger.debug("InsightID for this query is {} and the roomId is {}", insightId, roomId); - String roomFolderPath = Utility.getBaseFolder() + File.separator + "room" + File.separator + roomId; + String roomFolderPath = Room.roomFolderPath(roomId); Files.createDirectories(Paths.get(roomFolderPath)); String workingDir = (filePath != null && !filePath.trim().isEmpty()) ? filePath : roomFolderPath; diff --git a/src/prerna/engine/impl/model/Room.java b/src/prerna/engine/impl/model/Room.java index 5f8e2829cbd..192d26ffc77 100644 --- a/src/prerna/engine/impl/model/Room.java +++ b/src/prerna/engine/impl/model/Room.java @@ -2427,6 +2427,8 @@ public String getRoomFolderPath() { * @return the room folder path */ public static String roomFolderPath(String roomId) { + // every room folder is built here, so the id has to be a single folder name + Utility.requireSafePathSegment(roomId, "room id"); return Utility.getBaseFolder() + File.separator + "room" + File.separator + roomId; } diff --git a/src/prerna/reactor/agent/ClaudeCodeTranscriptLocator.java b/src/prerna/reactor/agent/ClaudeCodeTranscriptLocator.java index 2ec4c6e5cb8..025ebf4e96f 100644 --- a/src/prerna/reactor/agent/ClaudeCodeTranscriptLocator.java +++ b/src/prerna/reactor/agent/ClaudeCodeTranscriptLocator.java @@ -27,13 +27,13 @@ *******************************************************************************/ package prerna.reactor.agent; -import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; +import prerna.engine.impl.model.Room; import prerna.util.Utility; /** @@ -55,11 +55,11 @@ private ClaudeCodeTranscriptLocator() { * {@code null} if the room dir or file doesn't exist */ public static Path findJsonlFile(String roomId) { - if (roomId == null || roomId.isEmpty()) { + if (!Utility.isSafePathSegment(roomId)) { return null; } - String roomFolderPath = Utility.getBaseFolder() + File.separator + "room" + File.separator + roomId; + String roomFolderPath = Room.roomFolderPath(roomId); Path rootDir = Paths.get(roomFolderPath); if (!Files.isDirectory(rootDir)) { diff --git a/src/prerna/reactor/agent/GitHubCopilotTranscriptLocator.java b/src/prerna/reactor/agent/GitHubCopilotTranscriptLocator.java index 3d2cfc60afd..8ac52308d4d 100644 --- a/src/prerna/reactor/agent/GitHubCopilotTranscriptLocator.java +++ b/src/prerna/reactor/agent/GitHubCopilotTranscriptLocator.java @@ -27,11 +27,11 @@ *******************************************************************************/ package prerna.reactor.agent; -import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import prerna.engine.impl.model.Room; import prerna.util.Utility; @@ -45,11 +45,11 @@ private GitHubCopilotTranscriptLocator() { } public static Path findJsonlFile(String roomId) { - if (roomId == null || roomId.isEmpty()) { + if (!Utility.isSafePathSegment(roomId)) { return null; } - String roomFolderPath = Utility.getBaseFolder() + File.separator + "room" + File.separator + roomId; + String roomFolderPath = Room.roomFolderPath(roomId); Path eventsLog = Paths.get(roomFolderPath, "session-state", roomId, "events.jsonl"); return Files.exists(eventsLog) ? eventsLog : null; } diff --git a/src/prerna/reactor/agent/run/HumanDelegationService.java b/src/prerna/reactor/agent/run/HumanDelegationService.java index 0e77484f832..2f98dca113b 100644 --- a/src/prerna/reactor/agent/run/HumanDelegationService.java +++ b/src/prerna/reactor/agent/run/HumanDelegationService.java @@ -474,7 +474,8 @@ public static ToolExecutionResult delegateFromTool(Insight insight, String paren public static List> returnedFiles(String parentRoomId, String childRunId) { List> out = new ArrayList<>(); Path roomRoot = Paths.get(Room.roomFolderPath(parentRoomId)); - Path dir = roomRoot.resolve(FILES_FOLDER).resolve(childRunId); + // the run id is a folder name below the room folder + Path dir = roomRoot.resolve(FILES_FOLDER).resolve(Utility.requireSafePathSegment(childRunId, "run id")); if (!Files.isDirectory(dir)) { return out; } @@ -503,6 +504,7 @@ private static void copyFilesToOwnerRoom(String assigneeRoomId, String childRunI if (assigneeRoomId == null || parentRoomId == null) { throw new IllegalStateException("Unable to find the rooms for this delegation"); } + Utility.requireSafePathSegment(childRunId, "run id"); List sources = validateFiles(Paths.get(Room.roomFolderPath(assigneeRoomId)), files); ClusterUtil.pullRoom(parentRoomId); @@ -514,6 +516,10 @@ private static void copyFilesToOwnerRoom(String assigneeRoomId, String childRunI // relative to the room folder. private static List copyFiles(List sources, Path target, String roomId) { Path roomRoot = Paths.get(Room.roomFolderPath(roomId)); + // nothing outside the room folder is ever cleared or written + if (!target.toAbsolutePath().normalize().startsWith(roomRoot.toAbsolutePath().normalize())) { + throw new IllegalArgumentException("The destination is outside the room folder"); + } List copied = new ArrayList<>(); try { // A retry after a failed push starts from a clean folder. diff --git a/src/prerna/util/Utility.java b/src/prerna/util/Utility.java index eee4d16f6e6..9fdc9334ec1 100644 --- a/src/prerna/util/Utility.java +++ b/src/prerna/util/Utility.java @@ -1793,6 +1793,21 @@ public static String normalizePath(String stringToNormalize) { return normalizedString; } + // true when the value (e.g. an id from the DB or a remote API) is one folder/file name: not blank, not . or .., no separator or NUL + public static boolean isSafePathSegment(String value) { + return value != null && !value.isBlank() && !".".equals(value) && !"..".equals(value) + && value.indexOf('/') < 0 && value.indexOf('\\') < 0 && value.indexOf('\0') < 0; + } + + // returns the value, or logs and throws IllegalArgumentException when it is not a single safe name + public static String requireSafePathSegment(String value, String what) { + if (!isSafePathSegment(value)) { + classLogger.warn("Refused {} that is not a single safe folder name: {}", what, cleanLogString(value)); + throw new IllegalArgumentException("Not a valid " + what); + } + return value; + } + /** * Resolves a file inside a folder and returns the real location of the file. * The file path must be relative to the folder. Both the folder and the file From ff09af673ea24fde65263a22336ca28654fe3b60 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 09:52:52 -0500 Subject: [PATCH 2/5] fix(auth): ignore external engines whose id or name is not a safe file name --- .../external/ExternalAuthorizationHelper.java | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/prerna/auth/external/ExternalAuthorizationHelper.java b/src/prerna/auth/external/ExternalAuthorizationHelper.java index a987b380474..2c241f4aa78 100644 --- a/src/prerna/auth/external/ExternalAuthorizationHelper.java +++ b/src/prerna/auth/external/ExternalAuthorizationHelper.java @@ -96,6 +96,13 @@ public static void updateEnginePermissionsBasedOnApiCall(User user) throws Excep String engineSubType = (String) newE.get("engineSubType"); Map properties = null; + // the id and name make up file and folder names below + if (!Utility.isSafePathSegment(engineId) || !Utility.isSafePathSegment(engineName)) { + classLogger.warn("Skipping the external engine '{}' because its id or name is not a safe file name", + Utility.cleanLogString(engineId)); + continue; + } + // TODO: need to expand on logic for the class to initialize String engineClass = null; if(engineType == IEngine.CATALOG_TYPE.DATABASE) { @@ -198,9 +205,16 @@ private static List> transformApiResponse(User user, String for (JsonNode detail : parsedJsonNode) { Map permissionMap = new HashMap<>(); - // these are mandatory - permissionMap.put("engineId", detail.path(ENGINEID_KEY).asText()); - permissionMap.put("engineName", detail.path(ENGINENAME_KEY).asText()); + // these are mandatory, and become file and folder names + String detailEngineId = detail.path(ENGINEID_KEY).asText(); + String detailEngineName = detail.path(ENGINENAME_KEY).asText(); + if (!Utility.isSafePathSegment(detailEngineId) || !Utility.isSafePathSegment(detailEngineName)) { + classLogger.warn("Ignoring an external engine for user {} whose id or name is not a safe file name: {}", + User.getSingleLogginName(user), Utility.cleanLogString(detailEngineId)); + continue; + } + permissionMap.put("engineId", detailEngineId); + permissionMap.put("engineName", detailEngineName); IEngine.CATALOG_TYPE engineType = null; if(ENGINETYPE_KEY != null && !ENGINETYPE_KEY.isEmpty() && detail.has(ENGINETYPE_KEY)) { From 096e84bf6a57cd4e4ef920bc94a5f8fb016a89cb Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 09:52:52 -0500 Subject: [PATCH 3/5] fix(vector): keep AWS S3 vector stored documents inside the documents folder --- .../engine/impl/vector/AwsS3VectorDatabaseEngine.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java b/src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java index 8daf00eec7d..9ea7e6f491f 100644 --- a/src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java +++ b/src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java @@ -335,9 +335,9 @@ public void removeDocument(List fileNames, Map parameter List filesToRemoveFromCloud = new ArrayList<>(); for (String name : fileNames) { String documentName = Paths.get(name).getFileName().toString(); - File documentFile = new File(DOCUMENT_FOLDER, documentName); + File documentFile = storedDocumentToRemove(new File(DOCUMENT_FOLDER), documentName); - if (documentFile.exists()) { + if (documentFile != null) { try { FileUtils.forceDelete(documentFile); } catch (IOException e) { @@ -499,8 +499,8 @@ public List> listDocuments(Map parameters) { Map fileInfo = new HashMap<>(); fileInfo.put("fileName", source); - File thisF = new File(documentsDir, source); - if (thisF.exists() && thisF.isFile()) { + File thisF = storedDocument(documentsDir, source); + if (thisF != null && thisF.isFile()) { long fileSizeInBytes = thisF.length(); double fileSizeInMB = (double) fileSizeInBytes / (1024); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); From 0c33505b981f16b1ee26a77d18d4c18e271edca6 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 09:52:53 -0500 Subject: [PATCH 4/5] fix(teams): keep Graph ids and remote file names in bounds in the Teams file helper --- .../ms/teams/MicrosoftTeamsHelper.java | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java index 60d32b50f8f..2b9ea1e578c 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java @@ -49,6 +49,7 @@ import com.google.gson.ToNumberPolicy; import com.google.gson.reflect.TypeToken; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.ms.MicrosoftLoginUtils; import prerna.io.connector.ms.MicrosoftTokenFiller; import prerna.io.connector.ms.onedrive.MicrosoftOneDriveHelper; @@ -165,7 +166,7 @@ public static List> listChannels(String accessToken, String try { requireValue(teamId, "Team ID is required to list Microsoft Teams channels."); Map headers = MicrosoftLoginUtils.getBearerHeader(accessToken); - String url = String.format(CHANNELS, teamId.trim()); + String url = String.format(CHANNELS, ConnectorGuards.segment(teamId)); String response = HttpHelperUtility.getRequest(url, headers, null, null, null); List> channels = new ArrayList<>(); for (Map channel : getValueList(response)) { @@ -209,7 +210,7 @@ public static Map getChannelFilesFolder(String accessToken, Stri requireValue(channelId, "Channel ID is required to resolve the Microsoft Teams channel folder."); Map headers = MicrosoftLoginUtils.getBearerHeader(accessToken); - String url = String.format(FILES_FOLDER, teamId.trim(), channelId.trim()); + String url = String.format(FILES_FOLDER, ConnectorGuards.segment(teamId), ConnectorGuards.segment(channelId)); String response = HttpHelperUtility.getRequest(url, headers, null, null, null); Map json = GSON.fromJson(response, new TypeToken>() { }.getType()); @@ -269,8 +270,9 @@ public static List> listChannelFiles(String accessToken, Str try { Map folder = getChannelFilesFolder(accessToken, teamId, channelId); - String driveId = folder.get(DRIVE_ID).toString(); - String folderId = folder.get(FOLDER_ID).toString(); + // ids Graph returned go into the url as one safe segment each + String driveId = ConnectorGuards.segment(folder.get(DRIVE_ID).toString()); + String folderId = ConnectorGuards.segment(folder.get(FOLDER_ID).toString()); String relativePath = encodeRelativePath(folderPath); String url; @@ -332,7 +334,7 @@ public static Map downloadFile(String accessToken, String teamId } Map headers = MicrosoftLoginUtils.getBearerHeader(accessToken); - String metadataUrl = String.format(ITEM, resolvedDriveId.trim(), itemId.trim()); + String metadataUrl = String.format(ITEM, ConnectorGuards.segment(resolvedDriveId), ConnectorGuards.segment(itemId)); String metadataResponse = HttpHelperUtility.getRequest(metadataUrl, headers, null, null, null); Map metadata = GSON.fromJson(metadataResponse, new TypeToken>() { }.getType()); @@ -353,7 +355,9 @@ public static Map downloadFile(String accessToken, String teamId if (normalizedFileName == null || normalizedFileName.isEmpty()) { targetPath = path; } else { - targetPath = Paths.get(path, normalizedFileName).toString(); + // the name may be the remote one, so it stays a single name inside the destination + targetPath = ConnectorGuards + .resolveWithin(Paths.get(path), MicrosoftOneDriveHelper.baseName(normalizedFileName)).toString(); } File file = new File(targetPath); File parent = file.getParentFile(); @@ -372,7 +376,8 @@ public static Map downloadFile(String accessToken, String teamId if (preAuthUrl != null && !preAuthUrl.toString().trim().isEmpty()) { size = MicrosoftOneDriveHelper.download(preAuthUrl.toString(), null, file, String.valueOf(itemName)); } else { - String contentUrl = String.format(ITEM_CONTENT, resolvedDriveId.trim(), itemId.trim()); + String contentUrl = String.format(ITEM_CONTENT, ConnectorGuards.segment(resolvedDriveId), + ConnectorGuards.segment(itemId)); size = MicrosoftOneDriveHelper.download(contentUrl, headers, file, String.valueOf(itemName)); } if (size == 0) { @@ -427,8 +432,8 @@ public static Map uploadFile(String accessToken, String teamId, String conflict = normalizeConflictBehavior(conflictBehavior); Map folder = getChannelFilesFolder(accessToken, teamId, channelId); - String driveId = folder.get(DRIVE_ID).toString(); - String folderId = folder.get(FOLDER_ID).toString(); + String driveId = ConnectorGuards.segment(folder.get(DRIVE_ID).toString()); + String folderId = ConnectorGuards.segment(folder.get(FOLDER_ID).toString()); String targetPath = buildTargetPath(folderPath, fileName); String response; From 938d0481d096c728f5a2c61df153798c225ff9b6 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 14:09:43 -0500 Subject: [PATCH 5/5] fix(paths): check normalized names, real room paths and own index classes - isSafePathSegment also checks the NFKC form, since normalizePath applies it - pullEngine and pushEngineSmss check the final engine paths stay in the engine folder - delegation copies and listings resolve real paths inside the room, never the room folder itself - room ids are checked before the room row is inserted - AWS S3 vector remove and list only use this engine's own index classes - Teams download returns the file name in the destination; listing returns the raw drive id; . and .. folder segments are refused --- .../external/ExternalAuthorizationHelper.java | 9 ++-- .../util/clients/CentralCloudStorage.java | 14 +++++++ src/prerna/engine/impl/model/RoomUtils.java | 7 ++-- .../vector/AwsS3VectorDatabaseEngine.java | 39 +++++++++++------- .../ms/teams/MicrosoftTeamsHelper.java | 18 +++++--- .../agent/run/HumanDelegationService.java | 41 +++++++++++-------- src/prerna/util/Utility.java | 9 +++- 7 files changed, 89 insertions(+), 48 deletions(-) diff --git a/src/prerna/auth/external/ExternalAuthorizationHelper.java b/src/prerna/auth/external/ExternalAuthorizationHelper.java index 2c241f4aa78..a6a49be9cac 100644 --- a/src/prerna/auth/external/ExternalAuthorizationHelper.java +++ b/src/prerna/auth/external/ExternalAuthorizationHelper.java @@ -98,8 +98,8 @@ public static void updateEnginePermissionsBasedOnApiCall(User user) throws Excep // the id and name make up file and folder names below if (!Utility.isSafePathSegment(engineId) || !Utility.isSafePathSegment(engineName)) { - classLogger.warn("Skipping the external engine '{}' because its id or name is not a safe file name", - Utility.cleanLogString(engineId)); + classLogger.warn("Skipping the external engine '{}' ('{}') because its id or name is not a safe file name", + Utility.cleanLogString(engineId), Utility.cleanLogString(engineName)); continue; } @@ -209,8 +209,9 @@ private static List> transformApiResponse(User user, String String detailEngineId = detail.path(ENGINEID_KEY).asText(); String detailEngineName = detail.path(ENGINENAME_KEY).asText(); if (!Utility.isSafePathSegment(detailEngineId) || !Utility.isSafePathSegment(detailEngineName)) { - classLogger.warn("Ignoring an external engine for user {} whose id or name is not a safe file name: {}", - User.getSingleLogginName(user), Utility.cleanLogString(detailEngineId)); + classLogger.warn("Ignoring an external engine for user {} whose id or name is not a safe file name: {} ('{}')", + User.getSingleLogginName(user), Utility.cleanLogString(detailEngineId), + Utility.cleanLogString(detailEngineName)); continue; } permissionMap.put("engineId", detailEngineId); diff --git a/src/prerna/cluster/util/clients/CentralCloudStorage.java b/src/prerna/cluster/util/clients/CentralCloudStorage.java index 98b436db501..eca576e1be4 100644 --- a/src/prerna/cluster/util/clients/CentralCloudStorage.java +++ b/src/prerna/cluster/util/clients/CentralCloudStorage.java @@ -604,6 +604,9 @@ public void pullEngine(String engineId, IEngine.CATALOG_TYPE engineType, boolean String localEngineFolder = localEngineBaseFolder + FILE_SEPARATOR + aliasAndEngineId; String localSmssFileName = aliasAndEngineId + ".smss"; String localSmssFilePath = Utility.normalizePath(localEngineBaseFolder + FILE_SEPARATOR + localSmssFileName); + // the stored alias and the id are normalized into these names, so check the final paths + requireInsideFolder(localEngineBaseFolder, localEngineFolder); + requireInsideFolder(localEngineBaseFolder, localSmssFilePath); String cloudContainerPrefix = getCloudPrefixForEngine(engineType); String cloudEngineFolder = cloudContainerPrefix + engineId; @@ -686,6 +689,7 @@ public void pushEngineSmss(String engineId, IEngine.CATALOG_TYPE engineType) String localSmssFileName = SmssUtilities.getUniqueName(engineName, engineId) + ".smss"; String localEngineBaseFolder = EngineUtility.getLocalEngineBaseDirectory(engineType); String localSmssFilePath = Utility.normalizePath(localEngineBaseFolder + FILE_SEPARATOR + localSmssFileName); + requireInsideFolder(localEngineBaseFolder, localSmssFilePath); String cloudContainerPrefix = getCloudPrefixForEngine(engineType); String cloudSmssFolder = cloudContainerPrefix + engineId + SMSS_POSTFIX; @@ -1857,6 +1861,16 @@ public void pushUserAsset(String projectId) throws IOException, InterruptedExcep } } + // the path has to be below the base folder, never the base folder itself or outside it + private static void requireInsideFolder(String baseFolder, String path) { + Path base = Paths.get(Utility.normalizePath(baseFolder)).toAbsolutePath().normalize(); + Path target = Paths.get(Utility.normalizePath(path)).toAbsolutePath().normalize(); + if (!target.startsWith(base) || target.equals(base)) { + classLogger.warn("Refused an engine path outside {}: {}", base, Utility.cleanLogString(path)); + throw new IllegalArgumentException("The engine folder is outside the engine base folder"); + } + } + /** * Rooms */ diff --git a/src/prerna/engine/impl/model/RoomUtils.java b/src/prerna/engine/impl/model/RoomUtils.java index 8cf15194e98..4c2c84711ab 100644 --- a/src/prerna/engine/impl/model/RoomUtils.java +++ b/src/prerna/engine/impl/model/RoomUtils.java @@ -178,10 +178,9 @@ public static Room createRoomIfNotExists(String roomId, Insight insight, IModelE } private static String resolveRoomId(String roomId, Insight insight) { - if (roomId == null || roomId.trim().isEmpty()) { - return insight.getInsightId(); - } - return roomId; + String resolved = (roomId == null || roomId.trim().isEmpty()) ? insight.getInsightId() : roomId; + // the id names the room folder, so refuse it before the room row is inserted + return Utility.requireSafePathSegment(resolved, "room id"); } private static void createRoomRowIfMissing(String roomId, Insight insight, IModelEngine modelEngine, diff --git a/src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java b/src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java index 9ea7e6f491f..66cd10e8eea 100644 --- a/src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java +++ b/src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java @@ -32,6 +32,7 @@ import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -263,13 +264,8 @@ public List addEmbeddings(VectorDatabaseCSVTable vectorCsvT @Override public void removeDocument(List fileNames, Map parameters) throws Exception { - String indexClass = this.defaultIndexClass; - if (parameters.containsKey("indexClass")) { - indexClass = (String) parameters.get("indexClass"); - } - - final String DOCUMENT_FOLDER = this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass - + FILE_SEPARATOR + AbstractVectorDatabaseEngine.DOCUMENTS_FOLDER_NAME; + // checked before anything is deleted, remotely or locally + final String DOCUMENT_FOLDER = ownDocumentsFolder(parameters); // 1. List vectors from S3 Vector DB JsonObject listRequest = new JsonObject(); @@ -334,7 +330,11 @@ public void removeDocument(List fileNames, Map parameter // 3. Delete files from local storage List filesToRemoveFromCloud = new ArrayList<>(); for (String name : fileNames) { - String documentName = Paths.get(name).getFileName().toString(); + Path namePath = Paths.get(name).getFileName(); + if (namePath == null) { + continue; + } + String documentName = namePath.toString(); File documentFile = storedDocumentToRemove(new File(DOCUMENT_FOLDER), documentName); if (documentFile != null) { @@ -355,6 +355,21 @@ public void removeDocument(List fileNames, Map parameter } } + // the documents folder of one of this engine's own index classes, so it never leaves this engine's schema folder + private String ownDocumentsFolder(Map parameters) { + String indexClass = this.defaultIndexClass; + if (parameters != null && parameters.containsKey("indexClass")) { + indexClass = (String) parameters.get("indexClass"); + } + boolean known = indexClass != null + && (indexClass.equals(this.defaultIndexClass) || this.indexClasses.contains(indexClass)); + if (!known || !Utility.isSafePathSegment(indexClass)) { + classLogger.warn("Refused an index class this engine does not have: {}", Utility.cleanLogString(indexClass)); + throw new IllegalArgumentException("Unknown index class: " + indexClass); + } + return this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass + FILE_SEPARATOR + DOCUMENTS_FOLDER_NAME; + } + @Override protected List> nearestNeighborCall(Insight insight, String searchStatement, @@ -462,13 +477,7 @@ protected List> nearestNeighborCall(Insight insight, @Override public List> listDocuments(Map parameters) { - String indexClass = this.defaultIndexClass; - if (parameters.containsKey("indexClass")) { - indexClass = (String) parameters.get("indexClass"); - } - - File documentsDir = new File(this.schemaFolder.getAbsolutePath() + FILE_SEPARATOR + indexClass + FILE_SEPARATOR - + DOCUMENTS_FOLDER_NAME); + File documentsDir = new File(ownDocumentsFolder(parameters)); List> filesInS3Vector = new ArrayList<>(); Set uniqueSources = new HashSet<>(); diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java index 2b9ea1e578c..944cbe6fa5a 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java @@ -31,7 +31,6 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; @@ -270,8 +269,9 @@ public static List> listChannelFiles(String accessToken, Str try { Map folder = getChannelFilesFolder(accessToken, teamId, channelId); - // ids Graph returned go into the url as one safe segment each - String driveId = ConnectorGuards.segment(folder.get(DRIVE_ID).toString()); + // ids Graph returned go into the url as one safe segment each; the raw id goes back to the caller + String rawDriveId = folder.get(DRIVE_ID).toString(); + String driveId = ConnectorGuards.segment(rawDriveId); String folderId = ConnectorGuards.segment(folder.get(FOLDER_ID).toString()); String relativePath = encodeRelativePath(folderPath); @@ -284,7 +284,7 @@ public static List> listChannelFiles(String accessToken, Str List> items = new ArrayList<>(); for (Map item : MicrosoftTeamsMessageHelper.getPagedValues(accessToken, url, limit)) { - items.add(toDriveItemMap(item, driveId)); + items.add(toDriveItemMap(item, rawDriveId)); } return items; } catch (Exception e) { @@ -352,12 +352,16 @@ public static Map downloadFile(String accessToken, String teamId normalizedFileName = itemName.toString(); } String targetPath; + String resultPath; if (normalizedFileName == null || normalizedFileName.isEmpty()) { targetPath = path; + resultPath = ""; } else { // the name may be the remote one, so it stays a single name inside the destination targetPath = ConnectorGuards .resolveWithin(Paths.get(path), MicrosoftOneDriveHelper.baseName(normalizedFileName)).toString(); + // a direct child of the destination, whatever real path the destination resolved to + resultPath = new File(targetPath).getName(); } File file = new File(targetPath); File parent = file.getParentFile(); @@ -387,7 +391,7 @@ public static Map downloadFile(String accessToken, String teamId Map result = new HashMap<>(); result.put(ID, itemId); result.put(NAME, itemName); - result.put(FILE_PATH, Path.of(path).relativize(file.toPath()).toString()); + result.put(FILE_PATH, resultPath); result.put(SUCCESS, true); return result; } catch (Exception e) { @@ -575,6 +579,10 @@ private static String encodeRelativePath(String path) { if (segment.isEmpty()) { continue; } + // path-addressed calls stay below the channel folder + if (segment.trim().equals(".") || segment.trim().equals("..")) { + throw new IllegalArgumentException("The folder path must not contain . or .. segments: " + path); + } if (encoded.length() > 0) { encoded.append("/"); } diff --git a/src/prerna/reactor/agent/run/HumanDelegationService.java b/src/prerna/reactor/agent/run/HumanDelegationService.java index 2f98dca113b..6ac3400163c 100644 --- a/src/prerna/reactor/agent/run/HumanDelegationService.java +++ b/src/prerna/reactor/agent/run/HumanDelegationService.java @@ -65,6 +65,7 @@ import prerna.engine.impl.model.RoomMessageStore; import prerna.engine.impl.model.RoomUtils; import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; +import prerna.io.connector.ConnectorGuards; import prerna.notifications.NotificationDbUtils; import prerna.notifications.NotificationService; import prerna.om.Insight; @@ -165,8 +166,7 @@ public static Map delegate(Map args, String pare packet.put("responseFormat", responseFormat); packet.put("dueAt", dueAt); if (!sources.isEmpty()) { - packet.put("files", copyFiles(sources, - Paths.get(Room.roomFolderPath(assigneeRoomId)).resolve(REQUEST_FILES_FOLDER), assigneeRoomId)); + packet.put("files", copyFiles(sources, assigneeRoomId, REQUEST_FILES_FOLDER)); } if (!links.isEmpty()) { packet.put("links", links); @@ -473,16 +473,16 @@ public static ToolExecutionResult delegateFromTool(Insight insight, String paren */ public static List> returnedFiles(String parentRoomId, String childRunId) { List> out = new ArrayList<>(); - Path roomRoot = Paths.get(Room.roomFolderPath(parentRoomId)); - // the run id is a folder name below the room folder - Path dir = roomRoot.resolve(FILES_FOLDER).resolve(Utility.requireSafePathSegment(childRunId, "run id")); + // the run id is a folder name below the room folder; real paths, so a link cannot lead out of the room + String relative = FILES_FOLDER + "/" + Utility.requireSafePathSegment(childRunId, "run id"); + Path dir = ConnectorGuards.resolveWithin(Paths.get(Room.roomFolderPath(parentRoomId)), relative); if (!Files.isDirectory(dir)) { return out; } try (Stream paths = Files.list(dir)) { - paths.filter(Files::isRegularFile).sorted().forEach(path -> { + paths.filter(path -> isFileDirectlyIn(dir, path)).sorted().forEach(path -> { Map file = new LinkedHashMap<>(); - file.put("path", roomRoot.relativize(path).toString().replace('\\', '/')); + file.put("path", relative + "/" + path.getFileName()); file.put("name", path.getFileName().toString()); try { file.put("size", Files.size(path)); @@ -508,18 +508,14 @@ private static void copyFilesToOwnerRoom(String assigneeRoomId, String childRunI List sources = validateFiles(Paths.get(Room.roomFolderPath(assigneeRoomId)), files); ClusterUtil.pullRoom(parentRoomId); - copyFiles(sources, Paths.get(Room.roomFolderPath(parentRoomId)).resolve(FILES_FOLDER).resolve(childRunId), - parentRoomId); + copyFiles(sources, parentRoomId, FILES_FOLDER + "/" + childRunId); } - // Replace target with copies of sources, then push the room; returns paths - // relative to the room folder. - private static List copyFiles(List sources, Path target, String roomId) { - Path roomRoot = Paths.get(Room.roomFolderPath(roomId)); - // nothing outside the room folder is ever cleared or written - if (!target.toAbsolutePath().normalize().startsWith(roomRoot.toAbsolutePath().normalize())) { - throw new IllegalArgumentException("The destination is outside the room folder"); - } + // Replace the folder at relativeTarget (below the room folder) with copies of + // sources, then push the room; returns paths relative to the room folder. + private static List copyFiles(List sources, String roomId, String relativeTarget) { + // real paths, so nothing outside the room folder (or the room folder itself) is ever cleared or written + Path target = ConnectorGuards.resolveWithin(Paths.get(Room.roomFolderPath(roomId)), relativeTarget); List copied = new ArrayList<>(); try { // A retry after a failed push starts from a clean folder. @@ -528,7 +524,7 @@ private static List copyFiles(List sources, Path target, String ro for (Path source : sources) { Path dest = uniqueTarget(target, source.getFileName().toString()); Files.copy(source, dest, StandardCopyOption.COPY_ATTRIBUTES); - copied.add(roomRoot.relativize(dest).toString().replace('\\', '/')); + copied.add(relativeTarget + "/" + dest.getFileName()); } } catch (IOException e) { throw new IllegalStateException("Unable to copy files: " + e.getMessage(), e); @@ -627,6 +623,15 @@ private static Path uniqueTarget(Path dir, String name) { return candidate; } + // a regular file directly in the folder, also once links are followed + private static boolean isFileDirectlyIn(Path dir, Path path) { + try { + return Files.isRegularFile(path) && dir.toRealPath().equals(path.toRealPath().getParent()); + } catch (IOException e) { + return false; + } + } + private static void deleteRecursively(Path path) throws IOException { if (!Files.exists(path)) { return; diff --git a/src/prerna/util/Utility.java b/src/prerna/util/Utility.java index 9fdc9334ec1..3111d0d5156 100644 --- a/src/prerna/util/Utility.java +++ b/src/prerna/util/Utility.java @@ -1794,9 +1794,14 @@ public static String normalizePath(String stringToNormalize) { } // true when the value (e.g. an id from the DB or a remote API) is one folder/file name: not blank, not . or .., no separator or NUL + // checked again after NFKC, since normalizePath applies it and full-width forms can turn into / \ or . public static boolean isSafePathSegment(String value) { - return value != null && !value.isBlank() && !".".equals(value) && !"..".equals(value) - && value.indexOf('/') < 0 && value.indexOf('\\') < 0 && value.indexOf('\0') < 0; + return value != null && isSingleName(value) && isSingleName(Normalizer.normalize(value, Form.NFKC)); + } + + private static boolean isSingleName(String value) { + return !value.isBlank() && !".".equals(value) && !"..".equals(value) && value.indexOf('/') < 0 + && value.indexOf('\\') < 0 && value.indexOf('\0') < 0; } // returns the value, or logs and throws IllegalArgumentException when it is not a single safe name