diff --git a/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java index e117800a..cabfd62e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java @@ -20,12 +20,22 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.nio.file.FileSystemLoopException; import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +import java.nio.file.NotDirectoryException; import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Date; +import java.util.Deque; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.codehaus.plexus.archiver.util.ArchiveEntryUtils; @@ -34,7 +44,7 @@ import org.codehaus.plexus.components.io.filemappers.FileMapper; import org.codehaus.plexus.components.io.fileselectors.FileSelector; import org.codehaus.plexus.components.io.resources.PlexusIoResource; -import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,6 +57,9 @@ * @author Emmanuel Venisse */ public abstract class AbstractUnArchiver implements UnArchiver, FinalizerEnabled { + /** Whether to apply Windows-specific path and reparse point handling. */ + private static final boolean IS_WINDOWS = Os.isFamily(Os.FAMILY_WINDOWS); + private final Logger logger = LoggerFactory.getLogger(getClass()); protected Logger getLogger() { @@ -65,6 +78,17 @@ protected Logger getLogger() { private List finalizers; + /** Directory spellings are reused only after a fresh NOFOLLOW identity check, within one extraction. */ + private Map resolvedDirectories; + + /** + * A directory whose real path can be reused during the current extraction. + * + * @param fileKey the filesystem identity checked on each cache lookup + * @param path the real path observed for that identity + */ + private record ResolvedDirectory(Object fileKey, Path path) {} + private FileSelector[] fileSelectors; /** @@ -142,32 +166,42 @@ public void setFileMappers(final FileMapper[] fileMappers) { @Override public final void extract() throws ArchiverException { - validate(); - deferredSymlinks = new DeferredSymlinks(getLogger()); + resolvedDirectories = new LinkedHashMap<>(16, 0.75f, true); try { - execute(); - deferredSymlinks.resolve(); - } catch (IOException e) { - throw new ArchiverException("Error while copying symbolic link targets", e); + validate(); + deferredSymlinks = new DeferredSymlinks(getLogger()); + try { + execute(); + deferredSymlinks.resolve(); + } catch (IOException e) { + throw new ArchiverException("Error while copying symbolic link targets", e); + } finally { + deferredSymlinks = null; + } + runArchiveFinalizers(); } finally { - deferredSymlinks = null; + resolvedDirectories = null; } - runArchiveFinalizers(); } @Override public final void extract(final String path, final File outputDirectory) throws ArchiverException { - validate(path, outputDirectory); - deferredSymlinks = new DeferredSymlinks(getLogger()); + resolvedDirectories = new LinkedHashMap<>(16, 0.75f, true); try { - execute(path, outputDirectory); - deferredSymlinks.resolve(); - } catch (IOException e) { - throw new ArchiverException("Error while copying symbolic link targets", e); + validate(path, outputDirectory); + deferredSymlinks = new DeferredSymlinks(getLogger()); + try { + execute(path, outputDirectory); + deferredSymlinks.resolve(); + } catch (IOException e) { + throw new ArchiverException("Error while copying symbolic link targets", e); + } finally { + deferredSymlinks = null; + } + runArchiveFinalizers(); } finally { - deferredSymlinks = null; + resolvedDirectories = null; } - runArchiveFinalizers(); } @Override @@ -215,14 +249,19 @@ protected void validate() throws ArchiverException { throw new ArchiverException("You must choose between a destination directory and a destination file."); } - if (destDirectory != null && !destDirectory.isDirectory()) { - destFile = destDirectory; - destDirectory = null; - } + try { + // Use the same link/.. semantics for classification and extraction, retaining the configured spelling. + if (destDirectory != null && !Files.isDirectory(resolveExtractionRoot(destDirectory))) { + destFile = destDirectory; + destDirectory = null; + } - if (destFile != null && destFile.isDirectory()) { - destDirectory = destFile; - destFile = null; + if (destFile != null && Files.isDirectory(resolveExtractionRoot(destFile))) { + destDirectory = destFile; + destFile = null; + } + } catch (IOException e) { + throw new ArchiverException("Cannot resolve extraction destination", e); } } @@ -309,23 +348,13 @@ protected void extractFile( } } - // Hmm. Symlinks re-evaluate back to the original file here. Unsure if this is a good thing... - final File targetFileName = FileUtils.resolveFile(dir, entryName); - - // Make sure that the resolved path of the extracted file doesn't escape the destination directory - // getCanonicalFile().toPath() is used instead of getCanonicalPath() (returns String), - // because "/opt/directory".startsWith("/opt/dir") would return false negative. - Path canonicalDirPath = dir.getCanonicalFile().toPath(); - Path canonicalDestPath = targetFileName.getCanonicalFile().toPath(); - - if (!canonicalDestPath.startsWith(canonicalDirPath)) { - throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")"); - } - - // don't allow override target symlink by standard file - if (StringUtils.isEmpty(symlinkDestination) && Files.isSymbolicLink(canonicalDestPath)) { + final boolean symlink = !StringUtils.isEmpty(symlinkDestination); + PathUse use = isDirectory && !symlink ? PathUse.DIRECTORY_ENTRY : PathUse.OTHER_ENTRY; + final Path destination = resolveExtractionPath(dir, entryName, use); + if (!symlink && Files.isSymbolicLink(destination)) { throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")"); } + final File targetFileName = destination.toFile(); try { if (!shouldExtractEntry(dir, targetFileName, entryName, entryDate)) { @@ -338,8 +367,8 @@ protected void extractFile( dirF.mkdirs(); } - if (!StringUtils.isEmpty(symlinkDestination)) { - if (!createSymlinkEntry(canonicalDirPath, targetFileName, symlinkDestination, entryName)) { + if (symlink) { + if (!createSymlinkEntry(resolveExtractionRoot(dir), targetFileName, symlinkDestination, entryName)) { return; } } else if (isDirectory) { @@ -358,6 +387,248 @@ protected void extractFile( } } + /** + * Resolves the trusted root, following each link before processing subsequent parent components. + * @param directory the configured root, whose original spelling remains available to extraction hooks + * @return the physical root, including any not-yet-existing suffix + * @throws IOException if an existing component cannot be resolved + */ + protected final Path resolveExtractionRoot(File directory) throws IOException { + return resolvePath(directory.toPath(), PathUse.ROOT); + } + + /** + * Resolves the mapped entry name and checks containment of its canonical destination. + * @param directory the trusted extraction root + * @param name the mapped destination name + * @return the contained destination, using the existing canonical-file semantics for a final symbolic link + * @throws IOException if an existing component cannot be resolved + * @throws ArchiverException if the name is invalid, the destination is outside the root, or it ends at a + * redirected Windows reparse point + */ + protected final Path resolveExtractionPath(File directory, String name) throws IOException { + return resolveExtractionPath(directory, name, PathUse.OTHER_ENTRY); + } + + /** Determines how to handle a symbolic link or Windows reparse point at the final component. */ + private enum PathUse { + /** Follow the configured extraction root to its physical location. */ + ROOT, + /** Allow a junction to an existing directory. */ + DIRECTORY_ENTRY, + /** Reject a redirected Windows reparse point. */ + OTHER_ENTRY + } + + /** + * Parses a mapped name using either slash for absolute paths and native separators for relative paths. + * Windows drive-relative names use the working directory of the named drive. + * + * @param name the entry name after applying file mappers + * @return the parsed path, which may still be relative to the extraction root + * @throws ArchiverException if the host cannot represent the name + */ + private static Path mappedEntryPath(String name) { + Path entry; + try { + // Preserve the previous resolver's portable absolute names and platform-native relative names. + Path portable = Path.of(name.replace('/', File.separatorChar).replace('\\', File.separatorChar)); + if (portable.isAbsolute()) { + return portable; + } + entry = Path.of(name); + } catch (InvalidPathException e) { + throw new ArchiverException("Invalid archive entry name (" + name + ")", e); + } + Path entryRoot = entry.getRoot(); + // A Windows drive-relative name (C:file) starts at that drive's working directory. + if (entryRoot != null && entryRoot.toString().endsWith(":")) { + return entry.toAbsolutePath(); + } + return entry; + } + + /** + * Resolves a mapped entry against the physical extraction root and verifies containment. + * + * @param directory the configured extraction root + * @param name the mapped entry name + * @param use how to handle the entry's final component + * @return the resolved destination inside or equal to the extraction root + * @throws IOException if the root or an existing component cannot be resolved + * @throws ArchiverException if the name is invalid, the destination is outside the root, or the entry + * would replace a redirected Windows reparse point + */ + private Path resolveExtractionPath(File directory, String name, PathUse use) throws IOException { + Path root = resolveExtractionRoot(directory); + Path entry = mappedEntryPath(name); + // Only rootless entries can start at the resolved root. Windows rooted paths can be non-absolute. + Path destination = + entry.getRoot() == null ? resolvePath(root, entry, use) : resolvePath(root.resolve(entry), use); + if (!destination.startsWith(root)) { + throw new ArchiverException("Entry is outside of the target directory (" + name + ")"); + } + return destination; + } + + /** + * Resolves a path starting at its filesystem root. Intermediate links are followed before processing + * a subsequent {@code ..}, even when the leaf is missing. + * + * @param path the path to resolve, relative to the working directory if necessary + * @param use how to handle the final component + * @return the resolved absolute path, including any missing suffix + * @throws IOException if an existing component cannot be resolved + * @throws ArchiverException if the entry would replace a redirected Windows reparse point + */ + private Path resolvePath(Path path, PathUse use) throws IOException { + Path absolute = path.toAbsolutePath(); + return resolvePath(absolute.getRoot(), absolute, use); + } + + /** + * Resolves the name components from a known physical prefix. An ordinary existing directory can be + * verified in one real-path lookup. The component walk handles aliases, missing parents and the + * entry's final component. + * + * @param current the physical starting directory or filesystem root + * @param path the path whose name components remain to be resolved + * @param use how to handle the final component + * @return the resolved absolute path, including any missing suffix + * @throws IOException if a parent is not a directory, the link expansion limit is exceeded, + * or an existing component cannot be resolved + * @throws ArchiverException if the entry would replace a redirected Windows reparse point + */ + private Path resolvePath(Path current, Path path, PathUse use) throws IOException { + Path prefix = use == PathUse.ROOT ? path : path.getParent(); + if (prefix != null) { + Path directory = current.resolve(prefix); + if (isOrdinaryDirectory(directory)) { + if (use == PathUse.ROOT) { + return directory; + } + current = directory; + path = path.getFileName(); + } + } + Deque remaining = new ArrayDeque<>(); + path.forEach(remaining::addLast); + int links = 0; + while (!remaining.isEmpty()) { + Path name = remaining.removeFirst(); + if (name.toString().isEmpty() || name.toString().equals(".")) { + continue; + } + if (name.toString().equals("..")) { + if (current.getParent() != null) { + current = current.getParent(); + } + continue; + } + Path candidate = current.resolve(name); + BasicFileAttributes attributes; + try { + attributes = Files.readAttributes(candidate, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + } catch (NoSuchFileException ignored) { + current = candidate; + continue; + } + if (attributes.isSymbolicLink()) { + if (remaining.isEmpty() && use != PathUse.ROOT) { + // Keep the existing canonical-file treatment of a final link, including a dangling link. + return candidate.toFile().getCanonicalFile().toPath(); + } + if (++links > 64) { + throw new FileSystemLoopException(path.toString()); + } + // Resolve the target against the physical parent. Do not normalize away link/.. components. + Path target = current.resolve(Files.readSymbolicLink(candidate)).toAbsolutePath(); + for (int i = target.getNameCount() - 1; i >= 0; i--) { + remaining.addFirst(target.getName(i)); + } + current = target.getRoot(); + } else if (IS_WINDOWS && attributes.isOther()) { + // Windows reports junctions as "other", and from JDK 26 they no longer report as directories. + current = candidate.toRealPath(); + boolean directoryRequired = !remaining.isEmpty(); + if (use != PathUse.ROOT + && remaining.stream() + .allMatch(component -> component.toString().equals(".")) + && !current.equals(candidate.toRealPath(LinkOption.NOFOLLOW_LINKS))) { + if (use != PathUse.DIRECTORY_ENTRY) { + throw new ArchiverException( + "Cannot extract to a redirected Windows reparse point (" + candidate + ")"); + } + directoryRequired = true; + } + if (directoryRequired + && !Files.readAttributes(current, BasicFileAttributes.class) + .isDirectory()) { + throw new NotDirectoryException(candidate.toString()); + } + } else { + if (!remaining.isEmpty() && !attributes.isDirectory()) { + throw new NotDirectoryException(candidate.toString()); + } + // With no unresolved parent links or dots, this also handles Windows casing and short names. + current = resolveDirectory(candidate, attributes); + } + } + return current; + } + + /** + * Checks whether the directory spelling exactly matches its current real path, including case on Windows. + * + * @param directory the absolute path of the root or entry parent + * @return {@code true} if the path names a directory with that spelling and the component walk can be skipped + */ + private static boolean isOrdinaryDirectory(Path directory) { + try { + Path real = directory.toRealPath(); + // Windows Path.equals folds case; on Unix it compares the underlying filename bytes. + boolean sameSpelling = IS_WINDOWS ? directory.toString().equals(real.toString()) : directory.equals(real); + return sameSpelling && Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS); + } catch (IOException ignored) { + // The walk handles missing components, link expansion limits, and filesystem-specific errors. + return false; + } + } + + /** + * Resolves one existing component. An ordinary directory's real path can be reused when the + * freshly read file key matches the cached identity. + * + * @param candidate the component under its resolved parent + * @param attributes the attributes read without following the final link + * @return the component's real path + * @throws IOException if the real path cannot be obtained + */ + private Path resolveDirectory(Path candidate, BasicFileAttributes attributes) throws IOException { + Object key = attributes.fileKey(); + // Reparse points and providers without file identities need fresh resolution. Do not cache file leaves. + if (resolvedDirectories == null || !attributes.isDirectory() || attributes.isOther() || key == null) { + return candidate.toRealPath(); + } + ResolvedDirectory cached = resolvedDirectories.get(candidate); + if (cached != null && key.equals(cached.fileKey())) { + return cached.path(); + } + Path resolved = candidate.toRealPath(); + // Only retain spellings that already match the resolved path; aliases still need fresh resolution. + if (candidate.equals(resolved)) { + resolvedDirectories.put(candidate, new ResolvedDirectory(key, resolved)); + if (resolvedDirectories.size() > 1024) { + var oldest = resolvedDirectories.keySet().iterator(); + oldest.next(); + oldest.remove(); + } + } else { + resolvedDirectories.remove(candidate); + } + return resolved; + } + /** * Creates a symbolic link. Visible for testing, so a test can simulate a file system that refuses links. * @@ -429,24 +700,20 @@ protected boolean shouldExtractEntry(File targetDirectory, File targetFileName, return true; } - boolean entryIsDirectory = - entryName.endsWith("/"); // directory entries always end with '/', regardless of the OS. - String canonicalDestPath = targetFileName.getCanonicalPath(); - String suffix = (entryIsDirectory ? "/" : ""); - String relativeCanonicalDestPath = - canonicalDestPath.replace(targetDirectory.getCanonicalPath() + File.separatorChar, "") + suffix; + Path requestedPath = resolveExtractionRoot(targetDirectory).resolve(mappedEntryPath(entryName)); + String requestedName = requestedPath.toString(); + String existingName = + existingEntrySpelling(requestedPath, targetFileName.toPath()).toString(); boolean fileOnDiskIsOlderThanEntry = targetFileName.lastModified() < entryDate.getTime(); - boolean differentCasing = - !normalizedFileSeparator(entryName).equals(normalizedFileSeparator(relativeCanonicalDestPath)); // Warn for case (4) and (5) if the file system is case-insensitive - if (differentCasing) { + if (!requestedName.equals(existingName) && requestedName.equalsIgnoreCase(existingName)) { String casingMessage = String.format( Locale.ENGLISH, "Archive entry '%s' and existing file '%s' names differ only by case." + " This may lead to an unexpected outcome on case-insensitive filesystems.", entryName, - canonicalDestPath); + existingName); getLogger().warn(casingMessage); casingMessageEmitted.incrementAndGet(); } @@ -456,7 +723,24 @@ protected boolean shouldExtractEntry(File targetDirectory, File targetFileName, return isOverwrite() || fileOnDiskIsOlderThanEntry; } - private String normalizedFileSeparator(String pathOrEntry) { - return pathOrEntry.replace("/", File.separator); + /** + * Looks up the spelling used on disk for the case-mismatch warning. On Windows the lookup keeps + * junction names in the requested path. If that spelling cannot be looked up, it uses the resolved destination. + * + * @param requestedPath the path with the spelling supplied by the entry or mapper + * @param destination the existing destination selected by the resolver + * @return the path spelling to compare with the requested name + * @throws IOException if the destination spelling cannot be determined + */ + private Path existingEntrySpelling(Path requestedPath, Path destination) throws IOException { + if (IS_WINDOWS) { + try { + // Look up each name as stored on disk, keeping the junction name in the path. + return requestedPath.toRealPath(LinkOption.NOFOLLOW_LINKS); + } catch (IOException ignored) { + // A mapped name such as missing/../file may exist only at its resolved destination. + } + } + return resolvePath(destination, PathUse.OTHER_ENTRY); } } diff --git a/src/site/markdown/extraction-paths.md b/src/site/markdown/extraction-paths.md new file mode 100644 index 00000000..5f251fb5 --- /dev/null +++ b/src/site/markdown/extraction-paths.md @@ -0,0 +1,40 @@ +# Extraction paths and symbolic links + +Extractors resolve existing path components before checking that output stays +inside the destination directory. Symbolic links are followed before processing +subsequent `..` components, including when the output file does not exist yet. +The same rules resolve the configured destination directory and classify it as +a file or directory. + +For an existing root or entry parent, the resolver checks whether its spelling +matches its current physical directory. A match lets it skip the component +walk for that directory. Otherwise it walks the components and reuses cached +directories only after a fresh check of their filesystem identity without +following symbolic links. The cache lasts for one extraction. Resolution +stops after 64 symbolic-link expansions, rejecting cyclic or excessively long +paths. + +## Archive formats and compatibility + +TAR, including its compressed variants, and ZIP-based formats such as JAR, +WAR, and EAR use the shared entry extractor. + +- Intermediate symbolic links are followed before + subsequent parent components are processed. Containment is checked even + when the destination leaf does not exist. The overwrite check and the write + both use the resolved destination. +- On Windows, a drive-relative mapper result such as `C:out\file` is relative + to the working directory of that drive. Its resolved destination must still + be inside the extraction directory. +- On Windows, an existing NTFS junction can serve as an extraction directory + when its resolved target is inside the extraction root. For example, if + `assets` is such a junction, both the directory entry `assets/` and the file + entry `assets/logo.png` are accepted. The file can also be extracted when + the archive omits the directory entry. A regular-file or symbolic-link entry + named `assets` cannot replace the junction. The same containment check + applies to the directory entry and to entries beneath it. + +Standalone GZIP, BZIP2, Snappy, XZ, and Zstandard extractors use the shared +destination validation and may report invalid destination paths during +validation. Each uses a format-specific stream copy to its configured output +file. The per-entry rules above apply to the archive readers. diff --git a/src/site/site.xml b/src/site/site.xml index dd5b761c..4e34d884 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -4,6 +4,7 @@ + diff --git a/src/test/java/org/codehaus/plexus/archiver/ExtractionPathCacheTest.java b/src/test/java/org/codehaus/plexus/archiver/ExtractionPathCacheTest.java new file mode 100644 index 00000000..70e88d3e --- /dev/null +++ b/src/test/java/org/codehaus/plexus/archiver/ExtractionPathCacheTest.java @@ -0,0 +1,251 @@ +/* + * Copyright 2026 The plexus developers. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.codehaus.plexus.archiver; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Date; + +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** Changes directories between entries to ensure cached spellings never replace filesystem validation. */ +class ExtractionPathCacheTest { + /** Temporary directory containing the extraction roots, link targets, and source fixture. */ + @TempDir + Path temp; + + /** A sequence of archive entries and filesystem changes to perform during one extraction. */ + @FunctionalInterface + private interface Entries { + /** + * Runs the sequence against the active extractor. + * + * @param extractor the extractor whose directory cache is active + * @throws IOException if an entry or fixture operation fails + */ + void extract(Extractor extractor) throws IOException; + } + + /** Exercises the shared extraction code with an in-memory entry stream. */ + private static class Extractor extends AbstractUnArchiver { + /** The entry sequence supplied by the current test. */ + Entries entries; + + /** Runs the configured sequence and reports I/O failures as extraction failures. */ + @Override + protected void execute() { + try { + entries.extract(this); + } catch (IOException e) { + throw new ArchiverException("Cannot extract fixture", e); + } + } + + /** + * Runs the same fixture sequence through the explicit-directory extraction entry point. + * + * @param path the archive prefix supplied by the test + * @param outputDirectory the destination supplied by the test + */ + @Override + protected void execute(String path, File outputDirectory) { + execute(); + } + + /** + * Extracts a one-byte regular file into the configured destination. + * + * @param name the entry name passed to the shared extractor + * @throws IOException if resolving or writing the file fails + */ + void write(String name) throws IOException { + extractFile( + getSourceFile(), + getDestDirectory(), + new ByteArrayInputStream(new byte[] {1}), + name, + new Date(), + false, + null, + null, + null); + } + + /** + * Starts an extraction through the selected public entry point. + * + * @param explicitDirectory whether to pass the configured destination to the extraction call + */ + void run(boolean explicitDirectory) { + if (explicitDirectory) { + extract("", getDestDirectory()); + } else { + extract(); + } + } + } + + /** + * Configures a fixture extractor with a temporary source file. + * + * @param root the destination directory + * @return the extractor to which the test can assign an entry sequence + * @throws IOException if the temporary source file cannot be created + */ + private Extractor extractor(Path root) throws IOException { + Extractor extractor = new Extractor(); + extractor.setDestDirectory(root.toFile()); + extractor.setSourceFile(Files.createTempFile(temp, "source", ".archive").toFile()); + return extractor; + } + + /** + * Creates a symbolic link for the fixture, skipping the test if link creation is unavailable. + * + * @param link the path at which to create the link + * @param target the target stored in the link + * @throws IOException handled as a skipped test if link creation fails + */ + private void symlink(Path link, Path target) throws IOException { + try { + Files.createSymbolicLink(link, target); + } catch (IOException | UnsupportedOperationException e) { + assumeTrue(false, "Symbolic links unavailable: " + e); + } + } + + /** + * Checks that replacing a previously used directory with a link cannot redirect the next write outside the root. + * + * @param explicitDirectory whether to pass the destination explicitly to the extraction call + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void observesDirectoryReplacedBySymlinkWithinExtraction(boolean explicitDirectory) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path outside = Files.createDirectory(temp.resolve("outside")); + Extractor extractor = extractor(root); + extractor.entries = current -> { + current.write("parent/first"); + Files.move(root.resolve("parent"), root.resolve("saved")); + symlink(root.resolve("parent"), outside); + assertThrows(ArchiverException.class, () -> current.write("parent/new/file")); + assertArrayEquals(new byte[] {1}, Files.readAllBytes(root.resolve("saved/first"))); + }; + extractor.run(explicitDirectory); + try (var files = Files.list(outside)) { + assertEquals(0, files.count()); + } + } + + /** + * Checks that the next sibling resolves to the moved directory when its old name becomes a link. + * + * @param explicitDirectory whether to pass the destination explicitly to the extraction call + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void resolvesExistingParentAgainAfterAncestorMoves(boolean explicitDirectory) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path parent = Files.createDirectory(root.resolve("parent")); + Files.createDirectory(parent.resolve("nested")); + Extractor extractor = extractor(root); + extractor.entries = current -> { + current.write("parent/nested/first"); + Path moved = Files.move(parent, root.resolve("moved")); + symlink(parent, moved); + + Path sibling = current.resolveExtractionPath(root.toFile(), "parent/nested/second"); + assertEquals(moved.resolve("nested").toRealPath().resolve("second"), sibling); + }; + extractor.run(explicitDirectory); + } + + /** + * Checks a formerly missing parent again when it appears as a symbolic link between entries. + * + * @param explicitDirectory whether to pass the destination explicitly to the extraction call + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void observesPreviouslyMissingParent(boolean explicitDirectory) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path outside = Files.createDirectory(temp.resolve("outside")); + Extractor extractor = extractor(root); + extractor.entries = current -> { + current.write("missing/../first"); + symlink(root.resolve("missing"), outside); + assertThrows(ArchiverException.class, () -> current.write("missing/new/file")); + }; + extractor.run(explicitDirectory); + try (var files = Files.list(outside)) { + assertEquals(0, files.count()); + } + } + + /** + * Verifies that a reused extractor observes the current link target after both failed and successful runs. + * + * @param explicitDirectory whether to pass the destination explicitly to the extraction call + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void canReuseExtractorAfterFailureAndSuccess(boolean explicitDirectory) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path first = Files.createDirectory(root.resolve("first")); + Path second = Files.createDirectory(root.resolve("second")); + Path outside = Files.createDirectory(temp.resolve("outside")); + Path link = root.resolve("link"); + symlink(link, first); + Extractor extractor = extractor(root); + extractor.entries = current -> { + current.write("link/before"); + Files.delete(link); + symlink(link, outside); + current.write("link/rejected"); + }; + assertThrows(ArchiverException.class, () -> extractor.run(explicitDirectory)); + assertTrue(Files.exists(first.resolve("before"))); + + Files.delete(link); + symlink(link, second); + extractor.entries = current -> current.write("link/after"); + extractor.run(explicitDirectory); + assertTrue(Files.exists(second.resolve("after"))); + + Files.delete(link); + symlink(link, first); + extractor.entries = current -> current.write("link/reused"); + extractor.run(explicitDirectory); + assertTrue(Files.exists(first.resolve("reused"))); + assertFalse(Files.exists(second.resolve("reused"))); + try (var files = Files.list(outside)) { + assertEquals(0, files.count()); + } + } +} diff --git a/src/test/java/org/codehaus/plexus/archiver/ExtractionPathTest.java b/src/test/java/org/codehaus/plexus/archiver/ExtractionPathTest.java new file mode 100644 index 00000000..27ebde9e --- /dev/null +++ b/src/test/java/org/codehaus/plexus/archiver/ExtractionPathTest.java @@ -0,0 +1,726 @@ +/* + * Copyright 2026 The plexus developers. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.codehaus.plexus.archiver; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystemLoopException; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.NotDirectoryException; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Date; +import java.util.stream.Stream; +import java.util.zip.GZIPOutputStream; + +import org.apache.commons.compress.archivers.ArchiveEntry; +import org.apache.commons.compress.archivers.ArchiveOutputStream; +import org.apache.commons.compress.archivers.ArchiveStreamFactory; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; +import org.codehaus.plexus.archiver.gzip.GZipUnArchiver; +import org.codehaus.plexus.archiver.jar.JarUnArchiver; +import org.codehaus.plexus.archiver.tar.TarUnArchiver; +import org.codehaus.plexus.archiver.zip.ZipUnArchiver; +import org.codehaus.plexus.components.io.filemappers.FileMapper; +import org.codehaus.plexus.util.Os; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** Exercises the shared path policy through both archive readers and the protected extraction hook. */ +class ExtractionPathTest { + /** The modification time assigned to fixture entries, in milliseconds since the epoch. */ + private static final long ENTRY_TIME_MILLIS = 1234567000000L; + + /** The extraction entry point exercised by a fixture. */ + enum Format { + /** The protected extraction hook, supplied with an in-memory member. */ + SHARED, + /** The TAR reader. */ + TAR, + /** The ZIP reader. */ + ZIP, + /** The JAR reader, using a ZIP-format fixture. */ + JAR + } + + /** The archive member type written by the fixture. */ + enum Kind { + /** A regular file with UTF-8 content. */ + FILE, + /** A directory entry. */ + DIRECTORY, + /** A symbolic link whose value specifies its target. */ + SYMLINK + } + + /** Temporary directory for archives, extraction roots, and link targets. */ + @TempDir + Path temp; + + /** + * Supplies ordinary entry types for each extraction entry point. + * + * @return the combinations of format and regular-file or directory entry + */ + private static Stream ordinaryEntries() { + return Arrays.stream(Format.values()) + .flatMap(format -> Stream.of(Kind.FILE, Kind.DIRECTORY).map(kind -> Arguments.of(format, kind))); + } + + /** + * Supplies Windows paths rooted on the current drive with each supported slash spelling. + * + * @return the format, slash spelling, and whether the mapped path is inside the root + */ + private static Stream windowsRootedMappings() { + return Arrays.stream(Format.values()) + .flatMap(format -> Stream.of("rooted", "rooted-forward").flatMap(spelling -> Stream.of(false, true) + .map(contained -> Arguments.of(format, spelling, contained)))); + } + + /** + * Creates a symbolic link for the fixture, skipping the test if link creation is unavailable. + * + * @param link the path at which to create the link + * @param target the target stored in the link + * @throws IOException handled as a skipped test if link creation fails + */ + private void symlink(Path link, Path target) throws IOException { + try { + Files.createSymbolicLink(link, target); + } catch (IOException | UnsupportedOperationException e) { + assumeTrue(false, "Symbolic links unavailable: " + e); + } + } + + /** + * Creates an NTFS directory junction named {@code assets} using the native Windows command. + * + * @param directory the directory in which to create the junction + * @param target the directory to which the junction will point + * @return the junction path + * @throws IOException if the file store cannot be inspected or the command cannot be started or read + * @throws InterruptedException if interrupted while waiting for the command + */ + private Path assetsJunction(Path directory, Path target) throws IOException, InterruptedException { + assumeTrue("NTFS".equalsIgnoreCase(Files.getFileStore(directory).type()), "Requires an NTFS volume"); + Process mklink = new ProcessBuilder( + "cmd.exe", + "/d", + "/c", + "mklink", + "/j", + "assets", + directory.relativize(target).toString()) + .directory(directory.toFile()) + .redirectErrorStream(true) + .start(); + String output = new String(mklink.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + assertEquals(0, mklink.waitFor(), output); + return directory.resolve("assets"); + } + + /** + * Maps a neutral member name to the requested destination so the archive writer cannot rewrite it. + * + * @param format the extraction entry point to exercise + * @param root the extraction directory + * @param name the destination name returned by the fixture's mapper + * @param kind the archive member type + * @param value the file contents or symbolic-link target, ignored for directories + * @throws IOException if the archive fixture cannot be created or written + */ + private void extract(Format format, Path root, String name, Kind kind, String value) throws IOException { + String member = kind == Kind.DIRECTORY ? "member/" : "member"; + extractMember(format, root, member, kind, value, ignored -> name); + } + + /** + * Builds a single-member fixture and extracts it through the selected reader or shared extraction hook. + * + * @param format the extraction entry point to exercise + * @param root the extraction directory + * @param member the literal name passed to the archive writer or shared extraction hook + * @param kind the archive member type + * @param value the file contents or symbolic-link target, ignored for directories + * @param mappers the file mappers in application order + * @throws IOException if the archive fixture cannot be created or written + */ + private void extractMember(Format format, Path root, String member, Kind kind, String value, FileMapper... mappers) + throws IOException { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + Path archive = Files.createTempFile(temp, "path", ".archive"); + AbstractUnArchiver extractor; + if (format == Format.TAR) { + try (TarArchiveOutputStream out = new TarArchiveOutputStream(Files.newOutputStream(archive))) { + byte type = (byte) (kind == Kind.FILE ? '0' : kind == Kind.DIRECTORY ? '5' : '2'); + TarArchiveEntry entry = new TarArchiveEntry(member, type); + entry.setModTime(ENTRY_TIME_MILLIS); + entry.setMode(0755); + if (kind == Kind.FILE) { + entry.setSize(bytes.length); + } else if (kind == Kind.SYMLINK) { + entry.setLinkName(value); + } + out.putArchiveEntry(entry); + if (kind == Kind.FILE) { + out.write(bytes); + } + out.closeArchiveEntry(); + } + extractor = new TarUnArchiver(); + } else if (format == Format.ZIP || format == Format.JAR) { + try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(Files.newOutputStream(archive))) { + ZipArchiveEntry entry = new ZipArchiveEntry(member); + entry.setUnixMode((kind == Kind.SYMLINK ? 0120000 : kind == Kind.DIRECTORY ? 0040000 : 0100000) | 0755); + entry.setTime(ENTRY_TIME_MILLIS); + out.putArchiveEntry(entry); + if (kind != Kind.DIRECTORY) { + out.write(bytes); + } + out.closeArchiveEntry(); + } + extractor = format == Format.JAR ? new JarUnArchiver() : new ZipUnArchiver(); + } else { + extractor = new AbstractUnArchiver() { + /** Passes the synthetic member and its metadata directly to the shared extraction hook. */ + @Override + protected void execute() { + try { + extractFile( + getSourceFile(), + getDestDirectory(), + new ByteArrayInputStream(bytes), + member, + new Date(ENTRY_TIME_MILLIS), + kind == Kind.DIRECTORY, + 0755, + kind == Kind.SYMLINK ? value : null, + getFileMappers()); + } catch (IOException e) { + throw new ArchiverException("Cannot extract fixture", e); + } + } + + /** + * Rejects partial extraction for this single-member fixture. + * + * @param path the requested archive prefix + * @param outputDirectory the requested destination directory + * @throws UnsupportedOperationException whenever partial extraction is requested + */ + @Override + protected void execute(String path, File outputDirectory) { + throw new UnsupportedOperationException(); + } + }; + } + extractor.setSourceFile(archive.toFile()); + extractor.setDestDirectory(root.toFile()); + extractor.setFileMappers(mappers); + extractor.extract(); + } + + /** + * Checks that an invalid mapped name is reported with its original spelling and parsing cause. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource( + value = Format.class, + names = {"TAR", "ZIP"}) + void reportsInvalidMappedEntryName(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + String name = "dir/bad\0name"; + ArchiverException failure = + assertThrows(ArchiverException.class, () -> extract(format, root, name, Kind.FILE, "content")); + assertTrue(failure.getMessage().contains(name), failure::getMessage); + assertInstanceOf(InvalidPathException.class, failure.getCause()); + assertFalse(Files.exists(root.resolve("dir"))); + } + + /** + * Checks that a literal question mark is reported as invalid on Windows and preserved on Unix. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource( + value = Format.class, + names = {"TAR", "ZIP"}) + void handlesQuestionMarkInArchiveEntryName(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + String name = "dir/what?.txt"; + if (Os.isFamily(Os.FAMILY_WINDOWS)) { + ArchiverException failure = assertThrows( + ArchiverException.class, () -> extractMember(format, root, name, Kind.FILE, "content")); + assertTrue(failure.getMessage().contains(name), failure::getMessage); + assertInstanceOf(InvalidPathException.class, failure.getCause()); + assertFalse(Files.exists(root.resolve("dir"))); + } else { + extractMember(format, root, name, Kind.FILE, "content"); + assertEquals("content", Files.readString(root.resolve(name))); + } + } + + /** + * A missing leaf must not hide the physical location of an existing symlinked parent on Windows. + * + * @param format the extraction entry point to exercise + * @param kind the archive member type + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @MethodSource("ordinaryEntries") + void rejectsOutsideParentBeforeCreatingDirectories(Format format, Kind kind) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path outside = Files.createDirectory(temp.resolve("outside")); + symlink(root.resolve("redirect"), outside); + assertThrows(ArchiverException.class, () -> extract(format, root, "redirect/new/entry", kind, "replacement")); + try (var files = Files.list(outside)) { + assertEquals(0, files.count()); + } + assertTrue(Files.isSymbolicLink(root.resolve("redirect"))); + } + + /** + * Checks that a link to an outside parent leaves its existing file intact. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void rejectsOutsideParentWithoutChangingExistingFile(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path outside = Files.createDirectory(temp.resolve("outside")); + Path file = Files.writeString(outside.resolve("file"), "original"); + symlink(root.resolve("redirect"), outside); + assertThrows(ArchiverException.class, () -> extract(format, root, "redirect/file", Kind.FILE, "replacement")); + assertEquals("original", Files.readString(file)); + } + + /** + * Checks that a regular file used as a parent produces a directory error and retains its contents. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void rejectsRegularFileAsParent(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path parent = Files.writeString(root.resolve("parent"), "original"); + + ArchiverException failure = + assertThrows(ArchiverException.class, () -> extract(format, root, "parent/file", Kind.FILE, "content")); + assertInstanceOf(NotDirectoryException.class, failure.getCause()); + assertEquals("original", Files.readString(parent)); + } + + /** + * Checks that GZIP reports a non-directory parent while validating the destination. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @Test + void gzipRejectsInvalidDestinationDuringSharedValidation() throws Exception { + Path source = temp.resolve("source.gz"); + try (GZIPOutputStream gzip = new GZIPOutputStream(Files.newOutputStream(source))) { + gzip.write("content".getBytes(StandardCharsets.UTF_8)); + } + Path parent = Files.writeString(temp.resolve("parent"), "original"); + GZipUnArchiver extractor = new GZipUnArchiver(source.toFile()); + extractor.setDestFile(parent.resolve("file").toFile()); + + ArchiverException failure = assertThrows(ArchiverException.class, extractor::extract); + assertEquals("Cannot resolve extraction destination", failure.getMessage()); + assertInstanceOf(NotDirectoryException.class, failure.getCause()); + assertEquals("original", Files.readString(parent)); + } + + /** + * Windows rooted paths can be non-absolute and must retain Path.resolve semantics through mappers. + * + * @param format the extraction entry point to exercise + * @param spelling the backslash or forward-slash spelling of the rooted path + * @param contained whether the mapped destination lies inside the extraction directory + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @MethodSource("windowsRootedMappings") + void preservesWindowsRootedMappings(Format format, String spelling, boolean contained) throws Exception { + assumeTrue(Os.isFamily(Os.FAMILY_WINDOWS), "Requires Windows path syntax"); + Path root = Files.createDirectory(temp.resolve("root")).toAbsolutePath(); + Path outside = Files.createDirectory(temp.resolve("outside")).toAbsolutePath(); + Path expected = (contained ? root : outside).resolve("file.txt"); + String rooted = "\\" + root.getRoot().relativize(expected); + String name = spelling.equals("rooted-forward") ? rooted.replace('\\', '/') : rooted; + Path path = Path.of(name); + assertFalse(path.isAbsolute()); + assertNotNull(path.getRoot()); + if (contained) { + extract(format, root, name, Kind.FILE, "content"); + assertEquals("content", Files.readString(expected)); + try (var files = Files.list(root)) { + assertEquals(1, files.count()); + } + } else { + assertThrows(ArchiverException.class, () -> extract(format, root, name, Kind.FILE, "content")); + assertFalse(Files.exists(expected)); + try (var files = Files.list(root)) { + assertEquals(0, files.count()); + } + } + try (var files = Files.list(outside)) { + assertEquals(0, files.count()); + } + } + + /** + * Checks contained and outside mappings when the drive's working directory differs from the extraction root. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnabledOnOs(OS.WINDOWS) + @EnumSource(Format.class) + void resolvesDriveRelativeMappingsFromDriveWorkingDirectory(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("out")).toAbsolutePath(); + String volume = root.getRoot().toString(); + assumeTrue(volume.length() == 3 && volume.charAt(1) == ':', "Requires a drive-letter destination"); + String drive = volume.substring(0, 2); + Path driveDirectory = Path.of(drive).toAbsolutePath(); + assertNotEquals(driveDirectory, root); + + Path expected = root.resolve("file.txt"); + String contained = drive + driveDirectory.relativize(expected); + extract(format, root, contained, Kind.FILE, "content"); + assertEquals("content", Files.readString(expected)); + + // A bare filename on the same drive is relative to the drive directory, outside the extraction root. + String bareName = temp.getFileName() + "-outside.txt"; + assertThrows(ArchiverException.class, () -> extract(format, root, drive + bareName, Kind.FILE, "content")); + assertFalse(Files.exists(root.resolve(bareName))); + } + + /** + * Both a safe root alias and a contained directory link must work with nonexistent descendants. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void acceptsAliasesWithMissingDescendants(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path real = Files.createDirectory(root.resolve("real")); + symlink(root.resolve("redirect"), Path.of("real")); + Path alias = temp.resolve("alias"); + symlink(alias, root); + extract(format, alias, "redirect/new/file", Kind.FILE, "relative"); + extract(format, alias, alias.resolve("redirect/other/file").toString(), Kind.FILE, "absolute"); + assertEquals("relative", Files.readString(real.resolve("new/file"))); + assertEquals("absolute", Files.readString(real.resolve("other/file"))); + } + + /** + * Checks that a file is written to the approved destination after its directory alias disappears. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @Test + void writesToDestinationApprovedByOverwriteCheck() throws Exception { + Path target = Files.createDirectory(temp.resolve("target")).toRealPath(); + Path alias = temp.resolve("assets"); + symlink(alias, target); + Path expected = target.resolve("new/logo.png"); + AbstractUnArchiver extractor = new ZipUnArchiver() { + /** + * Removes the directory alias after the overwrite check to verify which destination the writer uses. + * + * @param dir the configured extraction directory + * @param file the resolved destination supplied to the overwrite check + * @param entryName the mapped archive name + * @param entryDate the timestamp of the archive entry + * @return the overwrite decision for the resolved destination + * @throws IOException if the overwrite check or removal of the alias fails + */ + @Override + protected boolean shouldExtractEntry(File dir, File file, String entryName, Date entryDate) + throws IOException { + assertEquals(expected, file.toPath()); + boolean approved = super.shouldExtractEntry(dir, file, entryName, entryDate); + Files.delete(alias); + return approved; + } + }; + extractor.setOverwrite(false); + byte[] content = "logo".getBytes(StandardCharsets.UTF_8); + extractor.extractFile( + null, + temp.toFile(), + new ByteArrayInputStream(content), + "assets/new/logo.png", + new Date(ENTRY_TIME_MILLIS), + false, + null, + null, + null); + assertArrayEquals(content, Files.readAllBytes(expected)); + } + + /** + * Extracts a TAR or ZIP fixture containing {@code assets/logo.png}. + * + * @param format the TAR or ZIP reader to exercise + * @param root the extraction directory + * @param logo the source file to store as the logo + * @param explicitDirectory whether the archive includes an {@code assets/} directory entry + * @return the extractor so its case-mismatch warning count can be inspected + * @throws IOException if the archive fixture cannot be created or written + */ + private AbstractUnArchiver extractAssets(Format format, Path root, Path logo, boolean explicitDirectory) + throws IOException { + Path archive = Files.createTempFile(temp, "assets", ".archive"); + try (var bytes = Files.newOutputStream(archive); + ArchiveOutputStream out = + ArchiveStreamFactory.DEFAULT.createArchiveOutputStream(format.name(), bytes)) { + if (explicitDirectory) { + out.putArchiveEntry(out.createArchiveEntry(logo.getParent(), "assets/")); + out.closeArchiveEntry(); + } + out.putArchiveEntry(out.createArchiveEntry(logo, "assets/logo.png")); + Files.copy(logo, out); + out.closeArchiveEntry(); + } + AbstractUnArchiver extractor = format == Format.TAR ? new TarUnArchiver() : new ZipUnArchiver(); + extractor.setSourceFile(archive.toFile()); + extractor.setDestDirectory(root.toFile()); + extractor.extract(); + return extractor; + } + + /** + * Checks extraction and case warnings for a nested file with and without an explicit parent entry. + * + * @param format the extraction entry point to exercise + * @param useJunction whether the existing parent is an NTFS junction + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @CsvSource({"TAR, false", "ZIP, false", "TAR, true", "ZIP, true"}) + void extractsAssetsWithAndWithoutDirectoryEntry(Format format, boolean useJunction) throws Exception { + assumeTrue(!useJunction || Os.isFamily(Os.FAMILY_WINDOWS), "Requires Windows for the junction case"); + Path root = Files.createDirectory(temp.resolve("root")); + Path target = Files.createDirectory(root.resolve(useJunction ? "target" : "assets")); + Path assets = useJunction ? assetsJunction(root, target) : target; + try { + for (boolean explicitDirectory : new boolean[] {false, true}) { + Path logo = Files.writeString(temp.resolve("logo.png"), explicitDirectory ? "explicit" : "implicit"); + AbstractUnArchiver extractor = extractAssets(format, root, logo, explicitDirectory); + assertEquals(0, extractor.casingMessageEmitted.get()); + assertTrue(Files.isSameFile(assets, target)); + assertEquals(Files.readString(logo), Files.readString(target.resolve("logo.png"))); + } + } finally { + if (useJunction) { + Files.delete(assets); + } + } + } + + /** + * Checks that an exactly spelled file reached through a directory symlink produces no case warning. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @Test + void doesNotWarnAboutCasingThroughDirectorySymlink() throws Exception { + Path target = Files.createDirectory(temp.resolve("target")); + symlink(temp.resolve("assets"), target); + Path logo = Files.writeString(target.resolve("logo.png"), "existing"); + AbstractUnArchiver extractor = extractAssets(Format.ZIP, temp, logo, false); + assertEquals(0, extractor.casingMessageEmitted.get()); + } + + /** + * Checks that a filename case difference beneath an NTFS junction produces one warning. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @Test + @EnabledOnOs(OS.WINDOWS) + void warnsForDifferentFileCasingUnderJunction() throws Exception { + Path target = Files.createDirectory(temp.resolve("target")); + Path logo = Files.writeString(target.resolve("LOGO.PNG"), "existing"); + assumeTrue(Files.exists(target.resolve("logo.png")), "Requires a case-insensitive directory"); + Path assets = assetsJunction(temp, target); + try { + AbstractUnArchiver extractor = extractAssets(Format.ZIP, temp, logo, false); + assertEquals(1, extractor.casingMessageEmitted.get()); + } finally { + Files.delete(assets); + } + } + + /** + * Checks the resolver's treatment of a junction as a root, parent, or final component. + * + * @throws Exception if the fixture cannot be prepared or inspected + */ + @EnabledOnOs(OS.WINDOWS) + @Test + void checksJunctionPositionBeforeWriting() throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path target = Files.createDirectory(temp.resolve("target")); + Path link = assetsJunction(root, target); + try { + AbstractUnArchiver resolver = new TarUnArchiver(); + assertEquals(target.toRealPath(), resolver.resolveExtractionRoot(link.toFile())); + assertThrows(ArchiverException.class, () -> resolver.resolveExtractionPath(root.toFile(), "assets/file")); + for (String entry : new String[] {"root/assets", "root/assets/."}) { + ArchiverException failure = assertThrows( + ArchiverException.class, () -> resolver.resolveExtractionPath(temp.toFile(), entry)); + assertTrue(failure.getMessage().contains("redirected Windows reparse point"), failure::getMessage); + } + assertTrue(Files.isSameFile(link, target)); + } finally { + Files.delete(link); + } + } + + /** + * Checks that file and link entries preserve a junction and that directory entries respect containment. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @EnabledOnOs(OS.WINDOWS) + @ParameterizedTest + @EnumSource( + value = Format.class, + names = {"TAR", "ZIP"}) + void protectsExistingJunctionDuringExtraction(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path target = Files.createDirectory(temp.resolve("target")); + Path marker = Files.writeString(target.resolve("keep"), "original"); + Path assets = assetsJunction(root, target); + try { + // The target is contained when extracting into temp, but outside the narrower root. + for (Kind kind : new Kind[] {Kind.FILE, Kind.SYMLINK}) { + ArchiverException failure = + assertThrows(ArchiverException.class, () -> extract(format, temp, "root/assets", kind, "keep")); + assertTrue(failure.getMessage().contains("redirected Windows reparse point"), failure::getMessage); + } + ArchiverException outside = + assertThrows(ArchiverException.class, () -> extract(format, root, "assets/", Kind.DIRECTORY, "")); + assertTrue(outside.getMessage().contains("outside of the target directory"), outside::getMessage); + assertTrue(Files.isSameFile(assets, target)); + assertEquals("original", Files.readString(marker)); + } finally { + Files.delete(assets); + } + } + + /** + * Validation and writes must agree on link/.. even when the lexical destination does not exist. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void resolvesRootLinkBeforeParentComponent(Format format) throws Exception { + Path lexical = Files.createDirectory(temp.resolve("lexical")); + Path actual = Files.createDirectory(temp.resolve("actual")); + Path sub = Files.createDirectory(actual.resolve("sub")); + Path destination = Files.createDirectory(actual.resolve("only")); + symlink(lexical.resolve("hop"), sub); + Path root = lexical.resolve("hop/../only"); + extract(format, root, "file", Kind.FILE, "content"); + extract(format, root, root.resolve("absolute").toString(), Kind.FILE, "mapped"); + assertEquals("content", Files.readString(destination.resolve("file"))); + assertEquals("mapped", Files.readString(destination.resolve("absolute"))); + assertFalse(Files.exists(lexical.resolve("only"))); + } + + /** + * Checks that a cycle is reported as a filesystem loop within the test timeout. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + @Timeout(5) + void rejectsSymlinkCycles(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + symlink(root.resolve("loop"), Path.of("loop")); + Throwable error = + assertThrows(ArchiverException.class, () -> extract(format, root, "loop/file", Kind.FILE, "content")); + while (error.getCause() != null) { + error = error.getCause(); + } + assertInstanceOf(FileSystemLoopException.class, error); + } + + /** + * Resolve long chains ourselves instead of depending on an operating system's whole-path link limit. + * + * @param format the extraction entry point to exercise + * @throws Exception if the fixture cannot be prepared or inspected + */ + @ParameterizedTest + @EnumSource(Format.class) + void boundsSymlinkExpansions(Format format) throws Exception { + Path root = Files.createDirectory(temp.resolve("root")); + Path real = Files.createDirectory(root.resolve("real")); + for (int i = 64; i >= 0; i--) { + symlink(root.resolve("link" + i), Path.of(i == 64 ? "real" : "link" + (i + 1))); + } + extract(format, root, "link1/accepted", Kind.FILE, "content"); + assertEquals("content", Files.readString(real.resolve("accepted"))); + Throwable error = assertThrows( + ArchiverException.class, () -> extract(format, root, "link0/rejected", Kind.FILE, "content")); + while (error.getCause() != null) { + error = error.getCause(); + } + assertInstanceOf(FileSystemLoopException.class, error); + assertFalse(Files.exists(real.resolve("rejected"))); + } +}