Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions src/prerna/auth/external/ExternalAuthorizationHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,13 @@ public static void updateEnginePermissionsBasedOnApiCall(User user) throws Excep
String engineSubType = (String) newE.get("engineSubType");
Map<String, Object> 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), Utility.cleanLogString(engineName));
continue;
}

// TODO: need to expand on logic for the class to initialize
String engineClass = null;
if(engineType == IEngine.CATALOG_TYPE.DATABASE) {
Expand Down Expand Up @@ -198,9 +205,17 @@ private static List<Map<String, Object>> transformApiResponse(User user, String
for (JsonNode detail : parsedJsonNode) {
Map<String, Object> 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),
Utility.cleanLogString(detailEngineName));
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)) {
Expand Down
23 changes: 19 additions & 4 deletions src/prerna/cluster/util/clients/CentralCloudStorage.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -601,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;
Expand Down Expand Up @@ -683,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;
Expand Down Expand Up @@ -1854,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
*/
Expand All @@ -1865,8 +1882,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);
Expand All @@ -1879,8 +1895,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);
Expand Down
4 changes: 2 additions & 2 deletions src/prerna/engine/impl/model/ClaudeCodeManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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];
Expand Down
2 changes: 1 addition & 1 deletion src/prerna/engine/impl/model/GitHubCopilotPyManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions src/prerna/engine/impl/model/Room.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
7 changes: 3 additions & 4 deletions src/prerna/engine/impl/model/RoomUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
47 changes: 28 additions & 19 deletions src/prerna/engine/impl/vector/AwsS3VectorDatabaseEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -263,13 +264,8 @@ public List<FileEmbeddingStatus> addEmbeddings(VectorDatabaseCSVTable vectorCsvT

@Override
public void removeDocument(List<String> fileNames, Map<String, Object> 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();
Expand Down Expand Up @@ -334,10 +330,14 @@ public void removeDocument(List<String> fileNames, Map<String, Object> parameter
// 3. Delete files from local storage
List<String> filesToRemoveFromCloud = new ArrayList<>();
for (String name : fileNames) {
String documentName = Paths.get(name).getFileName().toString();
File documentFile = new File(DOCUMENT_FOLDER, documentName);
Path namePath = Paths.get(name).getFileName();
if (namePath == null) {
continue;
}
String documentName = namePath.toString();
File documentFile = storedDocumentToRemove(new File(DOCUMENT_FOLDER), documentName);

if (documentFile.exists()) {
if (documentFile != null) {
try {
FileUtils.forceDelete(documentFile);
} catch (IOException e) {
Expand All @@ -355,6 +355,21 @@ public void removeDocument(List<String> fileNames, Map<String, Object> 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<String, Object> 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<Map<String, Object>> nearestNeighborCall(Insight insight,
String searchStatement,
Expand Down Expand Up @@ -462,13 +477,7 @@ protected List<Map<String, Object>> nearestNeighborCall(Insight insight,

@Override
public List<Map<String, Object>> listDocuments(Map<String, Object> 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<Map<String, Object>> filesInS3Vector = new ArrayList<>();
Set<String> uniqueSources = new HashSet<>();
Expand Down Expand Up @@ -499,8 +508,8 @@ public List<Map<String, Object>> listDocuments(Map<String, Object> parameters) {

Map<String, Object> 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");
Expand Down
37 changes: 25 additions & 12 deletions src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -49,6 +48,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;
Expand Down Expand Up @@ -165,7 +165,7 @@ public static List<Map<String, Object>> listChannels(String accessToken, String
try {
requireValue(teamId, "Team ID is required to list Microsoft Teams channels.");
Map<String, String> 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<Map<String, Object>> channels = new ArrayList<>();
for (Map<String, Object> channel : getValueList(response)) {
Expand Down Expand Up @@ -209,7 +209,7 @@ public static Map<String, Object> getChannelFilesFolder(String accessToken, Stri
requireValue(channelId, "Channel ID is required to resolve the Microsoft Teams channel folder.");

Map<String, String> 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<String, Object> json = GSON.fromJson(response, new TypeToken<Map<String, Object>>() {
}.getType());
Expand Down Expand Up @@ -269,8 +269,10 @@ public static List<Map<String, Object>> listChannelFiles(String accessToken, Str

try {
Map<String, Object> 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; 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);
String url;
Expand All @@ -282,7 +284,7 @@ public static List<Map<String, Object>> listChannelFiles(String accessToken, Str

List<Map<String, Object>> items = new ArrayList<>();
for (Map<String, Object> item : MicrosoftTeamsMessageHelper.getPagedValues(accessToken, url, limit)) {
items.add(toDriveItemMap(item, driveId));
items.add(toDriveItemMap(item, rawDriveId));
}
return items;
} catch (Exception e) {
Expand Down Expand Up @@ -332,7 +334,7 @@ public static Map<String, Object> downloadFile(String accessToken, String teamId
}

Map<String, String> 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<String, Object> metadata = GSON.fromJson(metadataResponse, new TypeToken<Map<String, Object>>() {
}.getType());
Expand All @@ -350,10 +352,16 @@ public static Map<String, Object> downloadFile(String accessToken, String teamId
normalizedFileName = itemName.toString();
}
String targetPath;
String resultPath;
if (normalizedFileName == null || normalizedFileName.isEmpty()) {
targetPath = path;
resultPath = "";
} 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();
// 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();
Expand All @@ -372,7 +380,8 @@ public static Map<String, Object> 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) {
Expand All @@ -382,7 +391,7 @@ public static Map<String, Object> downloadFile(String accessToken, String teamId
Map<String, Object> 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) {
Expand Down Expand Up @@ -427,8 +436,8 @@ public static Map<String, Object> uploadFile(String accessToken, String teamId,

String conflict = normalizeConflictBehavior(conflictBehavior);
Map<String, Object> 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;
Expand Down Expand Up @@ -570,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("/");
}
Expand Down
6 changes: 3 additions & 3 deletions src/prerna/reactor/agent/ClaudeCodeTranscriptLocator.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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)) {
Expand Down
Loading
Loading