| 1 | package com.renomad.minum.utils; | |
| 2 | ||
| 3 | import com.renomad.minum.state.Constants; | |
| 4 | import com.renomad.minum.logging.ILogger; | |
| 5 | ||
| 6 | import java.io.IOException; | |
| 7 | import java.nio.charset.StandardCharsets; | |
| 8 | import java.nio.file.Files; | |
| 9 | import java.nio.file.LinkOption; | |
| 10 | import java.nio.file.Path; | |
| 11 | import java.util.*; | |
| 12 | import java.util.stream.Stream; | |
| 13 | ||
| 14 | /** | |
| 15 | * Helper functions for working with files. | |
| 16 | */ | |
| 17 | public final class FileUtils { | |
| 18 | ||
| 19 | private final ILogger logger; | |
| 20 | private final IFileReader fileReader; | |
| 21 | ||
| 22 | public FileUtils(ILogger logger, Constants constants) { | |
| 23 | this( | |
| 24 | logger, | |
| 25 | new FileReader( | |
| 26 | LRUCache.getLruCache(constants.maxElementsLruCacheStaticFiles), | |
| 27 | constants.useCacheForStaticFiles, | |
| 28 | logger)); | |
| 29 | } | |
| 30 | ||
| 31 | /** | |
| 32 | * This version of the constructor is mainly for testing | |
| 33 | */ | |
| 34 | FileUtils(ILogger logger, IFileReader fileReader) { | |
| 35 | this.logger = logger; | |
| 36 | this.fileReader = fileReader; | |
| 37 | } | |
| 38 | ||
| 39 | /** | |
| 40 | * Write a string to a path on disk. | |
| 41 | * <br> | |
| 42 | * <p> | |
| 43 | * <em>Note: This does *not* protect against untrusted data on its own. Call {@link #safeResolve(String, String)} first against | |
| 44 | * the path to ensure it uses valid characters and prevent it escaping the expected directory.</em> | |
| 45 | * </p> | |
| 46 | */ | |
| 47 | public void writeString(Path path, String content) { | |
| 48 |
1
1. writeString : negated conditional → TIMED_OUT |
if (path.toString().isEmpty()) { |
| 49 | logger.logDebug(() -> "an empty path was provided to writeString"); | |
| 50 | return; | |
| 51 | } | |
| 52 | try { | |
| 53 | Files.writeString(path, content); | |
| 54 | } catch (IOException e) { | |
| 55 | throw new UtilsException(e); | |
| 56 | } | |
| 57 | } | |
| 58 | ||
| 59 | /** | |
| 60 | * Deletes a directory, deleting everything inside it | |
| 61 | * recursively afterwards. A more dangerous method than | |
| 62 | * many others, take care. | |
| 63 | * <br> | |
| 64 | * <p> | |
| 65 | * <em>Note: This does *not* protect against untrusted data on its own. Call {@link #safeResolve(String, String)} first against | |
| 66 | * the path to ensure it uses valid characters and prevent it escaping the expected directory.</em> | |
| 67 | * </p> | |
| 68 | */ | |
| 69 | public void deleteDirectoryRecursivelyIfExists(Path myPath) { | |
| 70 |
1
1. deleteDirectoryRecursivelyIfExists : negated conditional → KILLED |
if (!Files.exists(myPath)) { |
| 71 | logger.logDebug(() -> "system was requested to delete directory: "+myPath+", but it did not exist"); | |
| 72 | } else { | |
| 73 |
1
1. deleteDirectoryRecursivelyIfExists : removed call to com/renomad/minum/utils/FileUtils::walkPathDeleting → KILLED |
walkPathDeleting(myPath); |
| 74 | } | |
| 75 | } | |
| 76 | ||
| 77 | void walkPathDeleting(Path myPath) { | |
| 78 | try (Stream<Path> walk = Files.walk(myPath)) { | |
| 79 | ||
| 80 | final var files = walk.sorted(Comparator.reverseOrder()) | |
| 81 | .map(Path::toFile).toList(); | |
| 82 | ||
| 83 | for(var file: files) { | |
| 84 | logger.logTrace(() -> "deleting " + file); | |
| 85 |
1
1. walkPathDeleting : removed call to java/nio/file/Files::delete → KILLED |
Files.delete(file.toPath()); |
| 86 | } | |
| 87 | } catch (IOException ex) { | |
| 88 | throw new UtilsException("Error during deleteDirectoryRecursivelyIfExists: " + ex); | |
| 89 | } | |
| 90 | } | |
| 91 | ||
| 92 | /** | |
| 93 | * Creates a directory if it doesn't already exist. | |
| 94 | * <br> | |
| 95 | * <p> | |
| 96 | * <em>Note: This does *not* protect against untrusted data on its own. Call {@link #safeResolve(String, String)} first against | |
| 97 | * the path to ensure it uses valid characters and prevent it escaping the expected directory.</em> | |
| 98 | * </p> | |
| 99 | * <p> | |
| 100 | * If the directory does exist, the program will simply skip | |
| 101 | * building it, and mention it in the logs. | |
| 102 | * </p> | |
| 103 | */ | |
| 104 | public void makeDirectory(Path directory) { | |
| 105 | logger.logDebug(() -> "Creating a directory " + directory); | |
| 106 | boolean directoryExists = Files.exists(directory); | |
| 107 | logger.logDebug(() -> "Directory: " + directory + ". Already exists: " + directory); | |
| 108 |
1
1. makeDirectory : negated conditional → KILLED |
if (!directoryExists) { |
| 109 | logger.logDebug(() -> "Creating directory, since it does not already exist: " + directory); | |
| 110 |
1
1. makeDirectory : removed call to com/renomad/minum/utils/FileUtils::innerCreateDirectory → KILLED |
innerCreateDirectory(directory); |
| 111 | logger.logDebug(() -> "Directory: " + directory + " created"); | |
| 112 | } | |
| 113 | } | |
| 114 | ||
| 115 | static void innerCreateDirectory(Path directory) { | |
| 116 | try { | |
| 117 | Files.createDirectories(directory); | |
| 118 | } catch (Exception e) { | |
| 119 | throw new UtilsException(e); | |
| 120 | } | |
| 121 | } | |
| 122 | ||
| 123 | /** | |
| 124 | * Read a binary file, return as a byte array | |
| 125 | * <br> | |
| 126 | * <p> | |
| 127 | * <em>Note: This does *not* protect against untrusted data on its own. Call {@link #safeResolve(String, String)} first against | |
| 128 | * the path to ensure it uses valid characters and prevent it escaping the expected directory.</em> | |
| 129 | * </p> | |
| 130 | * <p> | |
| 131 | * If there is an error, this will return an empty byte array. | |
| 132 | * </p> | |
| 133 | */ | |
| 134 | public byte[] readBinaryFile(String path) { | |
| 135 | try { | |
| 136 |
1
1. readBinaryFile : replaced return value with null for com/renomad/minum/utils/FileUtils::readBinaryFile → KILLED |
return fileReader.readFile(path); |
| 137 | } catch (IOException e) { | |
| 138 | logger.logDebug(() -> String.format("Error while reading file %s, returning empty byte array. %s", path, e)); | |
| 139 |
1
1. readBinaryFile : replaced return value with null for com/renomad/minum/utils/FileUtils::readBinaryFile → KILLED |
return new byte[0]; |
| 140 | } | |
| 141 | } | |
| 142 | ||
| 143 | /** | |
| 144 | * Read a text file from the given path, return as a string. | |
| 145 | * <br> | |
| 146 | * <p> | |
| 147 | * <em>Note: This does *not* protect against untrusted data on its own. Call {@link #safeResolve(String, String)} first against | |
| 148 | * the path to ensure it uses valid characters and prevent it escaping the expected directory.</em> | |
| 149 | * </p> | |
| 150 | * <p> | |
| 151 | * If there is an error, this will return an empty string. | |
| 152 | * </p> | |
| 153 | */ | |
| 154 | public String readTextFile(String path) { | |
| 155 | try { | |
| 156 |
1
1. readTextFile : replaced return value with "" for com/renomad/minum/utils/FileUtils::readTextFile → KILLED |
return new String(fileReader.readFile(path), StandardCharsets.UTF_8); |
| 157 | } catch (IOException e) { | |
| 158 | logger.logDebug(() -> String.format("Error while reading file %s, returning empty string. %s", path, e)); | |
| 159 | return ""; | |
| 160 | } | |
| 161 | } | |
| 162 | ||
| 163 | /** | |
| 164 | * This method is to provide assurance that the file specified by the path | |
| 165 | * parameter is within the directory specified by directoryPath. Use this | |
| 166 | * for any code that reads from files where the user provides untrusted input. | |
| 167 | * @throws InvariantException if the file is not within the directory | |
| 168 | */ | |
| 169 | public static void checkFileIsWithinDirectory(String path, String directoryPath) { | |
| 170 | Path directoryRealPath; | |
| 171 | Path fullRealPath; | |
| 172 | try { | |
| 173 | directoryRealPath = Path.of(directoryPath).toRealPath(LinkOption.NOFOLLOW_LINKS); | |
| 174 | fullRealPath = directoryRealPath.resolve(path).toRealPath(LinkOption.NOFOLLOW_LINKS); | |
| 175 | } catch (IOException ex) { | |
| 176 | throw new InvariantException(ex.toString()); | |
| 177 | } | |
| 178 |
1
1. checkFileIsWithinDirectory : negated conditional → KILLED |
if (! fullRealPath.startsWith(directoryRealPath)) { |
| 179 | throw new InvariantException(String.format("path (%s) was not within directory (%s)", path, directoryPath)); | |
| 180 | } | |
| 181 | } | |
| 182 | ||
| 183 | /** | |
| 184 | * Checks that the path string avoids bad patterns and meets our | |
| 185 | * whitelist for acceptable characters. | |
| 186 | * @throws InvariantException if there are any issues with the path string, such | |
| 187 | * as being an empty string, containing known bad patterns | |
| 188 | * or including characters other than the set of characters we will allow for filenames. | |
| 189 | * It is a small set of ascii characters - alphanumerics, underscore, dash, period, | |
| 190 | * forward and backward slash. | |
| 191 | */ | |
| 192 | public static void checkForBadFilePatterns(String path) { | |
| 193 |
1
1. checkForBadFilePatterns : negated conditional → KILLED |
if (path.isBlank()) { |
| 194 | throw new InvariantException("filename was empty"); | |
| 195 | } | |
| 196 | char firstChar = path.charAt(0); | |
| 197 |
2
1. checkForBadFilePatterns : negated conditional → KILLED 2. checkForBadFilePatterns : negated conditional → KILLED |
if (firstChar == '\\' || firstChar == '/') { |
| 198 | throw new InvariantException("filename ("+path+") contained invalid characters"); | |
| 199 | } | |
| 200 | boolean isPreviousCharDot = false; | |
| 201 | boolean isPreviousCharSlash = false; | |
| 202 |
2
1. checkForBadFilePatterns : changed conditional boundary → KILLED 2. checkForBadFilePatterns : negated conditional → KILLED |
for (int i = 0; i < path.length(); i++) { |
| 203 | char c = path.charAt(i); | |
| 204 |
17
1. checkForBadFilePatterns : changed conditional boundary → TIMED_OUT 2. checkForBadFilePatterns : changed conditional boundary → KILLED 3. checkForBadFilePatterns : negated conditional → KILLED 4. checkForBadFilePatterns : negated conditional → KILLED 5. checkForBadFilePatterns : negated conditional → KILLED 6. checkForBadFilePatterns : negated conditional → KILLED 7. checkForBadFilePatterns : negated conditional → KILLED 8. checkForBadFilePatterns : changed conditional boundary → KILLED 9. checkForBadFilePatterns : negated conditional → KILLED 10. checkForBadFilePatterns : changed conditional boundary → KILLED 11. checkForBadFilePatterns : negated conditional → KILLED 12. checkForBadFilePatterns : changed conditional boundary → KILLED 13. checkForBadFilePatterns : negated conditional → KILLED 14. checkForBadFilePatterns : negated conditional → KILLED 15. checkForBadFilePatterns : negated conditional → KILLED 16. checkForBadFilePatterns : changed conditional boundary → KILLED 17. checkForBadFilePatterns : negated conditional → KILLED |
boolean isWhitelistedChar = c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || |
| 205 | c == '-' || c == '_' || c == '.' || c == '\\' || c == '/'; | |
| 206 |
1
1. checkForBadFilePatterns : negated conditional → KILLED |
if (!isWhitelistedChar) { |
| 207 | throw new InvariantException("filename (" + path + ") contained invalid characters (" + c + "). Allowable characters are alpha-numeric ascii both cases, underscore, forward and backward-slash, period, and dash"); | |
| 208 | } | |
| 209 |
1
1. checkForBadFilePatterns : negated conditional → KILLED |
if (c == '.') { |
| 210 |
1
1. checkForBadFilePatterns : negated conditional → KILLED |
if (isPreviousCharDot) { |
| 211 | throw new InvariantException("filename ("+path+") contained invalid characters"); | |
| 212 | } | |
| 213 | isPreviousCharDot = true; | |
| 214 | } else { | |
| 215 | isPreviousCharDot = false; | |
| 216 | } | |
| 217 |
1
1. checkForBadFilePatterns : negated conditional → KILLED |
if (c == '/') { |
| 218 |
1
1. checkForBadFilePatterns : negated conditional → KILLED |
if (isPreviousCharSlash) { |
| 219 | throw new InvariantException("filename ("+path+") contained invalid characters"); | |
| 220 | } | |
| 221 | isPreviousCharSlash = true; | |
| 222 | } else { | |
| 223 | isPreviousCharSlash = false; | |
| 224 | } | |
| 225 | } | |
| 226 | } | |
| 227 | ||
| 228 | /** | |
| 229 | * This helper method will ensure that the requested path is | |
| 230 | * within the parent directory and using safe characters | |
| 231 | */ | |
| 232 | public static Path safeResolve(String parentDirectory, String path) { | |
| 233 |
1
1. safeResolve : removed call to com/renomad/minum/utils/FileUtils::checkForBadFilePatterns → KILLED |
checkForBadFilePatterns(path); |
| 234 |
1
1. safeResolve : removed call to com/renomad/minum/utils/FileUtils::checkFileIsWithinDirectory → SURVIVED |
checkFileIsWithinDirectory(path, parentDirectory); |
| 235 |
1
1. safeResolve : replaced return value with null for com/renomad/minum/utils/FileUtils::safeResolve → KILLED |
return Path.of(parentDirectory).resolve(path); |
| 236 | } | |
| 237 | ||
| 238 | } | |
Mutations | ||
| 48 |
1.1 |
|
| 70 |
1.1 |
|
| 73 |
1.1 |
|
| 85 |
1.1 |
|
| 108 |
1.1 |
|
| 110 |
1.1 |
|
| 136 |
1.1 |
|
| 139 |
1.1 |
|
| 156 |
1.1 |
|
| 178 |
1.1 |
|
| 193 |
1.1 |
|
| 197 |
1.1 2.2 |
|
| 202 |
1.1 2.2 |
|
| 204 |
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10 11.11 12.12 13.13 14.14 15.15 16.16 17.17 |
|
| 206 |
1.1 |
|
| 209 |
1.1 |
|
| 210 |
1.1 |
|
| 217 |
1.1 |
|
| 218 |
1.1 |
|
| 233 |
1.1 |
|
| 234 |
1.1 |
|
| 235 |
1.1 |