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
60 changes: 37 additions & 23 deletions src/prerna/auth/external/ExternalAuthorizationHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import prerna.cluster.util.ClusterUtil;
import prerna.engine.api.IEngine;
import prerna.engine.impl.pipeline.PlatformOperation;
import prerna.engine.impl.SmssUtilities;
import prerna.engine.impl.rdbms.RDBMSNativeEngine;
import prerna.security.HttpHelperUtility;
import prerna.util.BeanFiller;
Expand Down Expand Up @@ -94,7 +95,6 @@ public static void updateEnginePermissionsBasedOnApiCall(User user) throws Excep
String engineName = (String) newE.get("engineName");
IEngine.CATALOG_TYPE engineType = (IEngine.CATALOG_TYPE) newE.get("engineType");
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)) {
Expand All @@ -103,35 +103,49 @@ public static void updateEnginePermissionsBasedOnApiCall(User user) throws Excep
continue;
}

// TODO: need to expand on logic for the class to initialize
String engineClass = null;
if(engineType == IEngine.CATALOG_TYPE.DATABASE) {
engineClass = RDBMSNativeEngine.class.getName();

properties = new HashMap<>();
properties.put(Constants.RDBMS_TYPE, engineSubType);
properties.put(Constants.OWL, Constants.DATABASE_FOLDER+"/@ENGINE@/"+engineName+"_OWL.OWL");
// one engine that cannot be written (e.g. a name the file system refuses) does not stop the others
try {
createExternalEngine(engineId, engineName, engineType, engineSubType);
} catch (IllegalArgumentException e) {
classLogger.warn("Skipping the external engine '{}' ('{}'): {}", Utility.cleanLogString(engineId),
Utility.cleanLogString(engineName), Utility.cleanLogString(e.getMessage()));
}

File tempSmss = UploadUtilities.createTemporaryEngineSmss(engineType, engineId, engineName, engineClass, properties);
InternalUtility.setEngineSmssPath(engineId, tempSmss.getAbsolutePath());
File smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss"));
FileUtils.copyFile(tempSmss, smssFile);
InternalUtility.setEngineSmssPath(engineId, smssFile.getAbsolutePath());
tempSmss.delete();

// also make the folder to persist... even if empty
String engineFolder = EngineUtility.getSpecificEngineBaseFolder(engineType, engineId, engineName);
File eFolder = new File(engineFolder);
eFolder.mkdir();

ClusterUtil.pushEngine(engineId);
}
} catch (Exception e) {
classLogger.error(Constants.STACKTRACE, e);
throw e;
}
}

// writes the smss and folder of an engine the external API granted, then pushes it
private static void createExternalEngine(String engineId, String engineName, IEngine.CATALOG_TYPE engineType,
String engineSubType) throws Exception {
Map<String, Object> properties = null;
// TODO: need to expand on logic for the class to initialize
String engineClass = null;
if(engineType == IEngine.CATALOG_TYPE.DATABASE) {
engineClass = RDBMSNativeEngine.class.getName();

properties = new HashMap<>();
properties.put(Constants.RDBMS_TYPE, engineSubType);
properties.put(Constants.OWL, Constants.DATABASE_FOLDER+"/@ENGINE@/"+engineName+"_OWL.OWL");
}

File tempSmss = UploadUtilities.createTemporaryEngineSmss(engineType, engineId, engineName, engineClass, properties);
InternalUtility.setEngineSmssPath(engineId, tempSmss.getAbsolutePath());
File smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss"));
FileUtils.copyFile(tempSmss, smssFile);
InternalUtility.setEngineSmssPath(engineId, smssFile.getAbsolutePath());
tempSmss.delete();

// also make the folder to persist... even if empty
String engineFolder = Utility.childPath(EngineUtility.getLocalEngineBaseDirectory(engineType),
SmssUtilities.getUniqueName(engineName, engineId), "engine folder");
File eFolder = new File(engineFolder);
eFolder.mkdir();

ClusterUtil.pushEngine(engineId);
}

/**
*
Expand Down
5 changes: 2 additions & 3 deletions src/prerna/engine/impl/model/Room.java
Original file line number Diff line number Diff line change
Expand Up @@ -2427,9 +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;
// every room folder is built here, so the id has to be a single folder name inside the room folder
return Utility.childPath(Utility.getBaseFolder() + File.separator + "room", roomId, "room id");
}

// Core message accessors
Expand Down
40 changes: 32 additions & 8 deletions src/prerna/engine/impl/pipeline/EngineProxyFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import prerna.engine.api.ICustomEmbeddingsFunctionEngine;
import prerna.engine.api.IDatabaseEngine;
import prerna.engine.api.IEmbeddedRDBMSServerEngine;
Expand All @@ -51,13 +54,16 @@
import prerna.engine.api.IVenvEngine;
import prerna.project.api.IProject;
import prerna.util.EngineUtility;
import prerna.util.Utility;

/**
* Factory for creating a dynamic proxy that wraps an IEngine instance to apply
* input and output processing pipelines.
*/
public class EngineProxyFactory {

private static final Logger classLogger = LogManager.getLogger(EngineProxyFactory.class);

/**
*
* @param engine
Expand Down Expand Up @@ -89,7 +95,7 @@ private static IModelEngine createGuardedModelEngine(IModelEngine engine, boolea
if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) {
String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE);
if (pipelineValue != null && !pipelineValue.isBlank()) {
jsonFile = pipelineFile(engine, pipelineValue);
jsonFile = checkedPipelineFile(engine, pipelineValue);
}
}

Expand Down Expand Up @@ -124,7 +130,7 @@ public static IDatabaseEngine createGuardedDatabaseEngine(IDatabaseEngine engine
if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) {
String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE);
if (pipelineValue != null && !pipelineValue.isBlank()) {
jsonFile = pipelineFile(engine, pipelineValue);
jsonFile = checkedPipelineFile(engine, pipelineValue);
}
}

Expand Down Expand Up @@ -157,7 +163,7 @@ public static IStorageEngine createGuardedStorageEngine(IStorageEngine engine) {
if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) {
String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE);
if (pipelineValue != null && !pipelineValue.isBlank()) {
jsonFile = pipelineFile(engine, pipelineValue);
jsonFile = checkedPipelineFile(engine, pipelineValue);
}
}

Expand Down Expand Up @@ -185,7 +191,7 @@ public static IFunctionEngine createGuardedFunctionEngine(IFunctionEngine engine
if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) {
String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE);
if (pipelineValue != null && !pipelineValue.isBlank()) {
jsonFile = pipelineFile(engine, pipelineValue);
jsonFile = checkedPipelineFile(engine, pipelineValue);
}
}

Expand Down Expand Up @@ -221,7 +227,7 @@ public static IVectorDatabaseEngine createGuardedVectorEngine(IVectorDatabaseEng
if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) {
String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE);
if (pipelineValue != null && !pipelineValue.isBlank()) {
jsonFile = pipelineFile(engine, pipelineValue);
jsonFile = checkedPipelineFile(engine, pipelineValue);
}
}

Expand All @@ -244,7 +250,7 @@ public static IProject createGuardedProject(IProject engine) {
if (engine != null && engine.getSmssProp().containsKey(IEngine.PIPELINE)) {
String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE);
if (pipelineValue != null && !pipelineValue.isBlank()) {
jsonFile = pipelineFile(engine, pipelineValue);
jsonFile = checkedPipelineFile(engine, pipelineValue);
}
}

Expand All @@ -267,7 +273,7 @@ public static IVenvEngine createGuardedVenvEngine(IVenvEngine engine) {
if (engine != null && engine.getSmssProp().containsKey(IEngine.PIPELINE)) {
String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE);
if (pipelineValue != null && !pipelineValue.isBlank()) {
jsonFile = pipelineFile(engine, pipelineValue);
jsonFile = checkedPipelineFile(engine, pipelineValue);
}
}

Expand All @@ -287,7 +293,25 @@ public static IVenvEngine createGuardedVenvEngine(IVenvEngine engine) {
public static File pipelineFile(IEngine engine, String pipelineFileName) {
String assetsFolder = EngineUtility.getSpecificEngineAssetsFolder(engine.getCatalogType(), engine.getEngineId(),
engine.getEngineName());
return new File((assetsFolder + "/" + pipelineFileName.trim()).replace("\\", "/"));
if (pipelineFileName == null) {
throw new IllegalArgumentException("Not a valid pipeline file");
}
// the PIPELINE value is a path inside the assets folder (a leading slash was always ignored)
String relative = pipelineFileName.trim().replaceFirst("^[/\\\\]+", "");
return new File(Utility.pathWithin(assetsFolder, relative, "pipeline file").replace("\\", "/"));
}

// a PIPELINE value that is not a file in the assets folder holds guardrails that cannot be applied, so the
// engine is refused, as it is when its pipeline file cannot be read
private static File checkedPipelineFile(IEngine engine, String pipelineFileName) {
try {
return pipelineFile(engine, pipelineFileName);
} catch (IllegalArgumentException e) {
classLogger.error("The PIPELINE value of engine {} is not a file inside its assets folder: {}",
engine.getEngineId(), Utility.cleanLogString(pipelineFileName));
throw new IllegalStateException("The guardrail configuration for engine " + engine.getEngineId()
+ " is not inside its assets folder, so it will not run without its guardrails", e);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -1256,7 +1256,12 @@ public static long download(String url, Map<String, String> headers, File file,
// with the token the link has to be Graph's own; without it, a plain https link
url = headers == null ? ConnectorGuards.requirePreAuthenticated(url)
: ConnectorGuards.requireUnder(url, MicrosoftTokenFiller.MS_GRAPH_BASE_API);
temp = HttpHelperUtility.getRequestFileDownload(url, headers, null, null, null, folder, temp.getName());
File saved = HttpHelperUtility.getRequestFileDownload(url, headers, null, null, null, folder,
temp.getName());
// only the temp file named above is moved or deleted, never a path the helper hands back
if (saved == null || !temp.getCanonicalFile().equals(saved.getCanonicalFile())) {
throw new IllegalStateException("The download was not saved as " + temp.getName());
}
long size = temp.length();
checkDownloadSize(size, name);
if (size > 0) {
Expand Down
6 changes: 3 additions & 3 deletions src/prerna/util/InternalUtility.java
Original file line number Diff line number Diff line change
Expand Up @@ -1239,13 +1239,13 @@ public static Properties getEngineDetails(String engineId) {
// write the properties file or not
// return the properties
String baseFolder = Utility.getDIHelperProperty(Constants.BASE_FOLDER);
File engineDir = new File(
Utility.normalizeParam(baseFolder) + File.separator + "engines" + File.separator + engineId);
File engineDir = new File(Utility.childPath(
Utility.normalizeParam(baseFolder) + File.separator + "engines", engineId, "engine id"));
if (!engineDir.exists()) {
engineDir.mkdirs();
}

File owlFile = new File(engineDir.getAbsolutePath() + File.separator + engineId + ".owl");
File owlFile = new File(Utility.childPath(engineDir.getAbsolutePath(), engineId + ".owl", "engine id"));
// engine owlFileName
FileUtils.writeStringToFile(owlFile, owl);
prop.replace(Constants.OWL, owlFile.getAbsolutePath());
Expand Down
13 changes: 11 additions & 2 deletions src/prerna/util/UploadUtilities.java
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,9 @@ public static void validateEngine(IEngine.CATALOG_TYPE engineType, User user, St
if (engineName == null || engineName.isEmpty()) {
throw new IllegalArgumentException("Need to provide a name for the database");
}
// both become the engine folder and file names, so check them before anything is written
Utility.requireSafePathSegment(engineName, "engine name");
Utility.requireSafePathSegment(engineId, "engine id");

// need to make sure engine folder doesn't already exist
String engineLocation = EngineUtility.getSpecificEngineBaseFolder(engineType, engineId, engineName);
Expand Down Expand Up @@ -1540,8 +1543,14 @@ private static void writeSmssProperty(BufferedWriter bufferedWriter, String key,
* @return
*/
private static String getEngineTempSmssLoc(IEngine.CATALOG_TYPE engineType, String engineId, String engineName) {
return EngineUtility.getLocalEngineBaseDirectory(engineType) + "/"
+ SmssUtilities.getUniqueName(engineName, engineId) + ".temp";
// the id and name come from callers and remote APIs, so the file has to stay in the engine folder;
// each is checked on its own, since the unique name normalizes away segments such as ..
Utility.requireSafePathSegment(engineId, "engine id");
if (engineName != null) {
Utility.requireSafePathSegment(engineName, "engine name");
}
return Utility.childPath(EngineUtility.getLocalEngineBaseDirectory(engineType),
SmssUtilities.getUniqueName(engineName, engineId) + ".temp", "engine name");
}

/**
Expand Down
89 changes: 89 additions & 0 deletions src/prerna/util/Utility.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.security.SecureRandom;
Expand Down Expand Up @@ -1813,6 +1814,94 @@ public static String requireSafePathSegment(String value, String what) {
return value;
}

// one name (e.g. an id from the DB or a remote API) under a folder; logs and throws IllegalArgumentException
// unless it is a single safe name whose normalized path is a direct child of the folder
public static String childPath(String folder, String name, String what) {
requireSafePathSegment(name, what);
Path base = checkedBaseFolder(folder, what);
Path child = base.resolve(checkedPath(name, what)).normalize();
if (!child.startsWith(base) || !base.equals(child.getParent())) {
classLogger.warn("Refused {} that leaves its folder: {}", what, cleanLogString(name));
throw new IllegalArgumentException("Not a valid " + what);
}
// same string form callers had before (folder + separator + name), from the checked name
return folder + File.separator + child.getFileName();
}

// a relative path (sub folders allowed) under a folder; logs and throws IllegalArgumentException when it is
// blank, absolute, changes under NFKC or would leave the folder; returns the normalized path
public static String pathWithin(String folder, String relative, String what) {
if (relative == null || relative.isBlank() || relative.indexOf('\0') >= 0
|| !relative.equals(Normalizer.normalize(relative, Form.NFKC))) {
classLogger.warn("Refused {} that is not a plain relative path: {}", what, cleanLogString(relative));
throw new IllegalArgumentException("Not a valid " + what);
}
Path rel = checkedPath(relative.replace('\\', '/'), what);
// real path of the folder, so a link above it compares as it really is
Path base = realPathOfExisting(checkedBaseFolder(folder, what));
Path target = base.resolve(rel).normalize();
if (rel.isAbsolute() || !target.startsWith(base) || target.equals(base) || leavesThroughLink(base, target)) {
classLogger.warn("Refused {} that leaves its folder: {}", what, cleanLogString(relative));
throw new IllegalArgumentException("Not a valid " + what);
}
return target.toString();
}

// a blank folder would resolve against the working directory
private static Path checkedBaseFolder(String folder, String what) {
if (folder == null || folder.isBlank()) {
throw new IllegalArgumentException("The folder for the " + what + " must not be blank");
}
return Path.of(folder).toAbsolutePath().normalize();
}

// characters the file system does not allow (e.g. : on Windows) are logged like any other refused value
private static Path checkedPath(String value, String what) {
try {
return Path.of(value);
} catch (InvalidPathException e) {
classLogger.warn("Refused {} that is not a valid path: {}", what, cleanLogString(value));
throw new IllegalArgumentException("Not a valid " + what, e);
}
}

// the real path of the nearest existing part, so a folder that is not created yet still compares true
private static Path realPathOfExisting(Path path) {
Path existing = path;
while (existing != null && !Files.exists(existing)) {
existing = existing.getParent();
}
if (existing == null) {
return path;
}
try {
return existing.toRealPath().resolve(existing.relativize(path)).normalize();
} catch (IOException e) {
throw new IllegalArgumentException("The folder cannot be resolved: " + path, e);
}
}

// a link below the folder (or the target itself) must not lead outside it
private static boolean leavesThroughLink(Path base, Path target) {
Path existing = target;
while (existing != null && !Files.exists(existing, LinkOption.NOFOLLOW_LINKS)) {
existing = existing.getParent();
}
if (existing == null) {
return true;
}
if (!existing.startsWith(base)) {
// nothing below the folder exists yet
return false;
}
try {
return !existing.toRealPath().startsWith(base);
} catch (IOException e) {
// e.g. a link to nothing
return true;
}
}

/**
* 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
Expand Down
Loading