From dd5edbcc991dfa71876024bf6fff9c58c130e53c Mon Sep 17 00:00:00 2001 From: Marc Nuri Date: Sun, 22 Nov 2026 17:23:00 +0100 Subject: [PATCH] fix(jni): verify the remote native library JAR and cache it per user The JAR downloaded when no platform artifact is on the classpath holds native code, yet it was cached at a predictable path in the shared temporary directory and loaded from there without any check, so another local user could plant one first. - the download is verified against the repository's .sha1 (fail closed), and cached in a per-user directory (~/.cache/helm-java, %LOCALAPPDATA%\helm-java\cache, or the new com.marcnuri.jkube-helm.cacheDir system property) that is created owner-only and refused if unsafe; the files are owner-only too - a cache hit is a private file of the size recorded when verified - an unusable default directory falls back to a private temporary one, with a warning - stale .part files are cleaned up, snapshot metadata is validated, and invalid metadata no longer prints to stderr - NativeLibrary.getInstance() reporting the cause is tested, and the remote tests use their own cache directory - maven-jar-plugin is pinned, so builds no longer resolve its version from Maven Central Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Nuri --- AGENTS.md | 3 +- README.md | 6 + .../com/marcnuri/helm/NativeLibraryTest.java | 69 ++- .../com/marcnuri/helm/jni/CacheDirectory.java | 322 ++++++++++++ .../marcnuri/helm/jni/RemoteJarLoader.java | 322 ++++++++++-- .../marcnuri/helm/jni/CacheDirectoryTest.java | 434 ++++++++++++++++ .../helm/jni/RemoteJarLoaderTest.java | 474 +++++++++++++----- .../java/com/marcnuri/helm/jni/TestFiles.java | 84 ++++ pom.xml | 3 + 9 files changed, 1545 insertions(+), 172 deletions(-) create mode 100644 lib/api/src/main/java/com/marcnuri/helm/jni/CacheDirectory.java create mode 100644 lib/api/src/test/java/com/marcnuri/helm/jni/CacheDirectoryTest.java create mode 100644 lib/api/src/test/java/com/marcnuri/helm/jni/TestFiles.java diff --git a/AGENTS.md b/AGENTS.md index 4a352ce..453664e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,7 +94,7 @@ Java caller → returns C.Result (out/err/stdOut/stdErr) → JNA → Result → parsed into Release ``` -Native library loading: `Helm` class holds `HelmLibHolder.INSTANCE`, initialized lazily by `NativeLibrary.getInstance().load()`. `getInstance()` uses Java `ServiceLoader` to discover the platform module on the classpath (each platform JAR has `META-INF/services/com.marcnuri.helm.jni.NativeLibrary`) and `NativeLibrarySelector` picks the first one whose `getOs()`/`getArch()` match the running JVM, else the first that declares neither (detection in `Platform`; providers declaring another platform are never picked; the `com.marcnuri.jkube-helm.nativeLibrary` system property forces one by class name, `com.marcnuri.jkube-helm.tempDir` sets the extraction dir); if none are registered, falls back to `RemoteJarLoader` (downloads the correct platform JAR at runtime — works for Gradle, fails when air-gapped). `helm-java/pom.xml` has OS-activated profiles that pull in the right platform module automatically; both `amd64`/`x86_64` and `arm64`/`aarch64` aliases are handled. +Native library loading: `Helm` class holds `HelmLibHolder.INSTANCE`, initialized lazily by `NativeLibrary.getInstance().load()`. `getInstance()` uses Java `ServiceLoader` to discover the platform module on the classpath (each platform JAR has `META-INF/services/com.marcnuri.helm.jni.NativeLibrary`) and `NativeLibrarySelector` picks the first one whose `getOs()`/`getArch()` match the running JVM, else the first that declares neither (detection in `Platform`; providers declaring another platform are never picked; the `com.marcnuri.jkube-helm.nativeLibrary` system property forces one by class name, `com.marcnuri.jkube-helm.tempDir` sets the extraction dir); if none are registered, falls back to `RemoteJarLoader` (downloads the correct platform JAR at runtime — works for Gradle, fails when air-gapped). The download is verified against the repository's `.sha1` and cached in the per-user `CacheDirectory` (`~/.cache/helm-java`, `$XDG_CACHE_HOME/helm-java`, `%LOCALAPPDATA%\helm-java\cache`, or the `com.marcnuri.jkube-helm.cacheDir` system property; on POSIX the directory and files are owner-only, and the directory is refused if a symlink, another user's, or group/world-writable; an unusable default falls back to a per-JVM temp directory); a cache hit isn't re-hashed: the JAR and its `.verified` record must be private files and the JAR must have the recorded size, so a same-size replacement by the same user isn't detected. Failures surface as the cause of `getInstance()`'s `IllegalStateException`. `helm-java/pom.xml` has OS-activated profiles that pull in the right platform module automatically; both `amd64`/`x86_64` and `arm64`/`aarch64` aliases are handled. ## Public API shape (Helm.java) @@ -151,6 +151,7 @@ Verbs with both forms: `install`, `template`, `show`, `upgrade`. Most others are - The registry configs come from the test resources (`helm-java/src/test/resources/helm-home/`, copied by Maven and IDEs alike) and hold a placeholder entry, so registry logins go to that file and not to an OS credential store (Keychain, Credential Manager, `pass`, Secret Service). - Trade-off: Testcontainers reads `DOCKER_CONFIG` too, so the KinD and Ryuk image pulls in `HelmKubernetesTest` are anonymous (Docker Hub rate limits apply; an authenticated mirror won't be used). - Don't make a test depend on the working directory (e.g. packaging `Paths.get("")`): `target/helm-home` lives in it and holds large repository indexes. +- Tests that reach the remote native JAR download (`NativeLibraryTest`) set the `com.marcnuri.jkube-helm.cacheDir` system property to their own `@TempDir` (and restore it), so they never write the user's `~/.cache/helm-java`. ```java class HelmFeatureTest { diff --git a/README.md b/README.md index 478e8b8..e053953 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,11 @@ Helm runs in-process from a native library built for each platform, shipped in i An application built on Linux x86_64 gets `linux-amd64`, whatever host it runs on later. - **Without a platform artifact** (e.g. Gradle, which doesn't activate Maven profiles): the matching artifact is downloaded from Maven Central the first time it's needed. This doesn't work in air-gapped environments. + The download is verified against the repository's SHA-1 checksum (`.sha1`) and cached in a per-user directory: `~/.cache/helm-java` (or `$XDG_CACHE_HOME/helm-java`) on Linux and macOS, `%LOCALAPPDATA%\helm-java\cache` on Windows. + On Linux and macOS the directory and its files are created owner-only, and the directory is refused if it's a symbolic link, belongs to another user, or is group- or world-writable. + If the default directory can't be created or written (no home directory, a read-only file system), a new private temporary directory is used, so each JVM downloads the JAR again (a `java.util.logging` warning says why). + A cached JAR is used if it's still a file of the size recorded when it was verified that other users can't write; otherwise it's downloaded and verified again. + It isn't hashed again on each use, so a replacement of the same size by the same user isn't detected. **Building for another platform.** When the build host and the target host differ (e.g. a container image for `linux/arm64` built on an x86_64 machine), exclude the platform artifacts and add the one for the target explicitly: @@ -79,6 +84,7 @@ Libraries declaring another platform are never used. If libraries are on the cla |-----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `com.marcnuri.jkube-helm.tempDir` | Base directory where the native library is extracted before loading it (defaults to `java.io.tmpdir`). It's created if missing, and each JVM extracts into its own `helm-java*` subdirectory inside it. Set it to an executable location if `/tmp` is mounted with `noexec`. | | `com.marcnuri.jkube-helm.nativeLibrary` | Fully qualified class name of the `com.marcnuri.helm.jni.NativeLibrary` implementation to use, regardless of the detected platform. The class must be registered in a `META-INF/services/com.marcnuri.helm.jni.NativeLibrary` file on the classpath, like the ones in the platform artifacts. | +| `com.marcnuri.jkube-helm.cacheDir` | Directory where the native library JAR downloaded from Maven Central is cached (see above for the default). It must not be writable by other users: on Linux and macOS it's created owner-only if missing, and refused if it's a symbolic link, belongs to another user, or is group- or world-writable. Unlike the default directory, a directory set here that can't be created or written is an error, not a reason to fall back to a temporary one. | ## Features diff --git a/helm-java/src/test/java/com/marcnuri/helm/NativeLibraryTest.java b/helm-java/src/test/java/com/marcnuri/helm/NativeLibraryTest.java index e77e01d..0e7180f 100644 --- a/helm-java/src/test/java/com/marcnuri/helm/NativeLibraryTest.java +++ b/helm-java/src/test/java/com/marcnuri/helm/NativeLibraryTest.java @@ -18,8 +18,15 @@ import com.marcnuri.helm.jni.NativeLibrary; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.IOException; +import java.net.URL; import java.net.URLClassLoader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -29,6 +36,8 @@ */ class NativeLibraryTest { + private static final String CACHE_DIR = "com.marcnuri.jkube-helm.cacheDir"; + @Test void getInstanceFromClassPath() { System.setProperty("com.marcnuri.jkube-helm.skipRemoteJar", "true"); @@ -41,11 +50,15 @@ void getInstanceFromClassPath() { } @Test - void getSnapshotInstanceFromRemoteJar() { + void getSnapshotInstanceFromRemoteJar() throws IOException { final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); + // An empty cache directory of its own: always downloads, and leaves nothing in the user's cache. Not a @TempDir: + // the downloaded JAR stays open (its class loader is never closed), so on Windows it can't be deleted, and a + // @TempDir that can't be deleted fails the test + final Path cacheDir = Files.createTempDirectory("helm-java-test-cache"); + final String previousCacheDir = System.setProperty(CACHE_DIR, cacheDir.toString()); // Use a PUBLISHED snapshot version System.setProperty("com.marcnuri.jkube-helm.version", "0.0-SNAPSHOT"); - System.setProperty("com.marcnuri.jkube-helm.forceUpdate", "true"); try { Thread.currentThread().setContextClassLoader(new URLClassLoader(new java.net.URL[0], null)); assertThat(NativeLibrary.serviceProviderLibrary(null)).isNull(); @@ -54,16 +67,21 @@ void getSnapshotInstanceFromRemoteJar() { } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); System.clearProperty("com.marcnuri.jkube-helm.version"); - System.clearProperty("com.marcnuri.jkube-helm.forceUpdate"); + restoreCacheDir(previousCacheDir); + deleteQuietly(cacheDir); } } @Test - void getReleaseInstanceFromRemoteJar() { + void getReleaseInstanceFromRemoteJar() throws IOException { final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); + // An empty cache directory of its own: always downloads, and leaves nothing in the user's cache. Not a @TempDir: + // the downloaded JAR stays open (its class loader is never closed), so on Windows it can't be deleted, and a + // @TempDir that can't be deleted fails the test + final Path cacheDir = Files.createTempDirectory("helm-java-test-cache"); + final String previousCacheDir = System.setProperty(CACHE_DIR, cacheDir.toString()); // Use a PUBLISHED release version System.setProperty("com.marcnuri.jkube-helm.version", "0.0.1"); - System.setProperty("com.marcnuri.jkube-helm.forceUpdate", "true"); try { Thread.currentThread().setContextClassLoader(new URLClassLoader(new java.net.URL[0], null)); assertThat(NativeLibrary.serviceProviderLibrary(null)).isNull(); @@ -72,7 +90,27 @@ void getReleaseInstanceFromRemoteJar() { } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); System.clearProperty("com.marcnuri.jkube-helm.version"); - System.clearProperty("com.marcnuri.jkube-helm.forceUpdate"); + restoreCacheDir(previousCacheDir); + deleteQuietly(cacheDir); + } + } + + @Test + void getInstanceNotAvailableReportsRemoteJarFailureAsCause(@TempDir Path tempDir) { + final ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); + final String previousCacheDir = System.setProperty(CACHE_DIR, tempDir.toString()); + // An UNPUBLISHED version: a 404 from Maven Central, or a connection error when offline + System.setProperty("com.marcnuri.jkube-helm.version", "0.0.0-unpublished"); + try { + Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[0], null)); + assertThatThrownBy(NativeLibrary::getInstance) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No NativeLibrary implementation found, please add one of the supported dependencies to your project") + .cause().isInstanceOf(IOException.class); + } finally { + Thread.currentThread().setContextClassLoader(currentClassLoader); + System.clearProperty("com.marcnuri.jkube-helm.version"); + restoreCacheDir(previousCacheDir); } } @@ -91,4 +129,23 @@ void getInstanceNotAvailable() { Thread.currentThread().setContextClassLoader(currentClassLoader); } } + + private static void restoreCacheDir(String previousCacheDir) { + if (previousCacheDir == null) { + System.clearProperty(CACHE_DIR); + } else { + System.setProperty(CACHE_DIR, previousCacheDir); + } + } + + /** + * Deletes what can be deleted (on Windows, not the JAR a class loader still holds open). + */ + private static void deleteQuietly(Path directory) { + try (Stream files = Files.walk(directory)) { + files.sorted(Comparator.reverseOrder()).forEach(file -> file.toFile().delete()); + } catch (IOException exception) { + // Best effort + } + } } diff --git a/lib/api/src/main/java/com/marcnuri/helm/jni/CacheDirectory.java b/lib/api/src/main/java/com/marcnuri/helm/jni/CacheDirectory.java new file mode 100644 index 0000000..641a37b --- /dev/null +++ b/lib/api/src/main/java/com/marcnuri/helm/jni/CacheDirectory.java @@ -0,0 +1,322 @@ +/* + * Copyright 2024 Marc Nuri + * + * 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 com.marcnuri.helm.jni; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.nio.file.attribute.UserPrincipal; +import java.util.Set; +import java.util.function.Function; +import java.util.logging.Logger; + +/** + * The per-user directory where {@link RemoteJarLoader} caches the downloaded native library JARs. + * + *

The cached JARs contain native code that is loaded into the JVM, so other users must not be able to write the + * directory or its files. On POSIX file systems the directory is created owner-only ({@code rwx------}), and an + * existing one is refused if it's a symbolic link, belongs to another user, or is group- or world-writable. On other + * file systems (Windows), the default location is in the user's profile, which other users can't write. + * + *

If the default location can't be used (no home directory, a read-only file system, a parent owned by someone + * else, a directory owned by root), a new private temporary directory is used instead, so the JAR is downloaded + * again by each JVM. A directory set with the {@code com.marcnuri.jkube-helm.cacheDir} system property, and any + * unsafe directory, fail instead. + * + * @author Marc Nuri + */ +final class CacheDirectory { + + /** + * System property to set the directory where the downloaded native library JARs are cached. + */ + static final String CACHE_DIR = "com.marcnuri.jkube-helm.cacheDir"; + + private static final String PROBE_PREFIX = "helm-java-owner"; + private static final String PROBE_SUFFIX = ".probe"; + private static final Logger LOGGER = Logger.getLogger(CacheDirectory.class.getName()); + + private static final Set OWNER_ONLY_DIRECTORY = PosixFilePermissions.fromString("rwx------"); + private static final Set OWNER_ONLY_FILE = PosixFilePermissions.fromString("rw-------"); + + private final Path directory; + private final boolean temporary; + + private CacheDirectory(Path directory, boolean temporary) { + this.directory = directory; + this.temporary = temporary; + } + + Path getDirectory() { + return directory; + } + + /** + * Whether this is a per-JVM temporary directory (the default location couldn't be used). + */ + boolean isTemporary() { + return temporary; + } + + /** + * The cache directory set with the {@code com.marcnuri.jkube-helm.cacheDir} system property, or the default one. + */ + static CacheDirectory select() throws IOException { + return select(System.getProperty(CACHE_DIR), Platform.osName(), System::getenv, System.getProperty("user.home")); + } + + static CacheDirectory select(String configured, String osName, Function getenv, String userHome) + throws IOException { + if (configured != null && !configured.trim().isEmpty()) { + final Path directory; + try { + directory = Paths.get(configured); + } catch (InvalidPathException exception) { + throw new IOException("Invalid native library cache directory (set with the " + CACHE_DIR + + " system property): " + configured, exception); + } + return new CacheDirectory(ensurePrivate(directory), false); + } + Path defaultDirectory; + try { + defaultDirectory = defaultDirectory(osName, getenv, userHome); + } catch (InvalidPathException exception) { + defaultDirectory = null; + } + final String reason; + // e.g. containers running with an arbitrary user id that has no home directory (user.home=?) + if (defaultDirectory != null && defaultDirectory.isAbsolute()) { + try { + return new CacheDirectory(ensurePrivate(defaultDirectory), false); + } catch (UnsafeDirectoryException exception) { + throw exception; + } catch (IOException exception) { + // Unusable (not unsafe): use a private directory for this JVM only + reason = exception.getMessage(); + } + } else { + reason = "no per-user directory for user.home=" + userHome; + } + final Path temporary; + try { + temporary = Files.createTempDirectory("helm-java-cache"); + } catch (IOException exception) { + throw new IOException("Unable to use the default native library cache directory (" + reason + + "), nor a temporary directory in java.io.tmpdir (" + exception + "); set one with the " + CACHE_DIR + + " system property", exception); + } + temporary.toFile().deleteOnExit(); + LOGGER.warning(() -> "Downloading the native library to the temporary directory " + temporary + + ", downloaded again by each JVM, because the default cache directory can't be used: " + reason); + return new CacheDirectory(temporary, true); + } + + /** + * The default cache directory for the given platform. + * + *

    + *
  • Windows: {@code %LOCALAPPDATA%\helm-java\cache}, or {@code \AppData\Local\helm-java\cache}.
  • + *
  • Others: {@code $XDG_CACHE_HOME/helm-java} if set to an absolute path, or {@code /.cache/helm-java}.
  • + *
+ */ + static Path defaultDirectory(String osName, Function getenv, String userHome) { + if (userHome == null) { + // Relative, so not used by select() + userHome = ""; + } + if ("windows".equals(osName)) { + final String localAppData = getenv.apply("LOCALAPPDATA"); + final Path base = isAbsolute(localAppData) ? Paths.get(localAppData) : Paths.get(userHome, "AppData", "Local"); + return base.resolve("helm-java").resolve("cache"); + } + final String xdgCacheHome = getenv.apply("XDG_CACHE_HOME"); + final Path base = isAbsolute(xdgCacheHome) ? Paths.get(xdgCacheHome) : Paths.get(userHome, ".cache"); + return base.resolve("helm-java"); + } + + /** + * Creates the directory if missing (owner-only on POSIX file systems) and checks that it's usable and that other + * users can't write it. + * + * @return the directory. + * @throws UnsafeDirectoryException if it can't be trusted (a symbolic link, another user's, writable by others). + * @throws IOException if it can't be used (it can't be created, isn't a directory, isn't writable). + */ + static Path ensurePrivate(Path directory) throws IOException { + if (Files.isSymbolicLink(directory)) { + throw new UnsafeDirectoryException(directory, "it's a symbolic link"); + } + if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { + try { + if (isPosix()) { + Files.createDirectories(directory, PosixFilePermissions.asFileAttribute(OWNER_ONLY_DIRECTORY)); + } else { + Files.createDirectories(directory); + } + } catch (IOException exception) { + throw unusable(directory, "it can't be created (" + exception + ")", exception); + } + } + if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) { + throw unusable(directory, "it's not a directory", null); + } + if (isPosix()) { + final PosixFileAttributes attributes = + Files.readAttributes(directory, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + // Checked first: it doesn't need the current user + if (isWritableByOthers(attributes)) { + throw new UnsafeDirectoryException(directory, "it's group- or world-writable (" + + PosixFilePermissions.toString(attributes.permissions()) + "), restrict it with chmod 700"); + } + final UserPrincipal currentUser; + try { + currentUser = currentUser(); + } catch (IOException exception) { + throw unusable(directory, "the user this JVM runs as can't be determined (" + exception + ")", exception); + } + if (!attributes.owner().equals(currentUser)) { + if (isOwnedByRoot(directory, attributes)) { + // Other users can't write it, but neither can this one (e.g. created while building a container image) + throw unusable(directory, "it's owned by root", null); + } + throw new UnsafeDirectoryException(directory, "it's owned by " + attributes.owner().getName()); + } + } + if (!Files.isWritable(directory)) { + throw unusable(directory, "it's not writable", null); + } + return directory; + } + + /** + * Whether the file is a regular file (not a symbolic link) that, on POSIX file systems, belongs to the current + * user and isn't writable by others. + */ + static boolean isPrivateFile(Path file) throws IOException { + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + return false; + } + if (isPosix()) { + final PosixFileAttributes attributes = + Files.readAttributes(file, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + return !isWritableByOthers(attributes) && attributes.owner().equals(currentUser()); + } + return true; + } + + /** + * The attributes to create a file only its owner can read or write ({@code rw-------}) with, whatever the umask. + */ + static FileAttribute[] ownerOnlyFile() { + if (isPosix()) { + return new FileAttribute[]{PosixFilePermissions.asFileAttribute(OWNER_ONLY_FILE)}; + } + return new FileAttribute[0]; + } + + private static boolean isPosix() { + return FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + } + + private static boolean isWritableByOthers(PosixFileAttributes attributes) { + return attributes.permissions().contains(PosixFilePermission.GROUP_WRITE) || + attributes.permissions().contains(PosixFilePermission.OTHERS_WRITE); + } + + /** + * The user this JVM runs as (its effective user): more reliable than looking up {@code user.name}, which doesn't + * always match it (e.g. containers running with an arbitrary user id). + * + *

Never determined with a file in the directory being checked: before that directory is trusted, another user + * who can rename files in it could swap such a file between its creation and the owner lookup. Instead: + *

    + *
  1. Where available (Linux), the owner of {@code /proc/self}: the process' effective user, which no other user + * can change. Nothing is written.
  2. + *
  3. Otherwise, the owner of a probe file created (and deleted right away) in {@code java.io.tmpdir}, which is + * sticky, or private to the user (as on macOS), so other users can't rename or replace it. A + * {@code java.io.tmpdir} deliberately set to a non-sticky directory other users can write isn't protected.
  4. + *
+ */ + private static UserPrincipal currentUser() throws IOException { + final Path self = Paths.get("/proc/self"); + try { + if (Files.isDirectory(self)) { + return Files.getOwner(self); + } + } catch (IOException | SecurityException exception) { + // No usable /proc: probe + } + final Path probe = Files.createTempFile(PROBE_PREFIX, PROBE_SUFFIX); + try { + return Files.getOwner(probe, LinkOption.NOFOLLOW_LINKS); + } finally { + Files.deleteIfExists(probe); + } + } + + /** + * Whether the file is owned by root: by user id where the {@code unix} attribute view is available (e.g. when root + * has no name because {@code /etc/passwd} is missing), otherwise by name. Under user namespaces or NFS root squash + * the user id itself is a different one (e.g. 65534), so root-owned files aren't recognised there; they're then + * refused as another user's, which fails safe. + */ + private static boolean isOwnedByRoot(Path file, PosixFileAttributes attributes) { + try { + final Object uid = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (uid instanceof Integer) { + return (Integer) uid == 0; + } + } catch (IOException | UnsupportedOperationException | IllegalArgumentException exception) { + // No unix attribute view: by name + } + return "root".equals(attributes.owner().getName()); + } + + private static boolean isAbsolute(String path) { + try { + return path != null && !path.trim().isEmpty() && Paths.get(path).isAbsolute(); + } catch (InvalidPathException exception) { + return false; + } + } + + private static IOException unusable(Path directory, String reason, IOException cause) { + return new IOException(message(directory, reason), cause); + } + + private static String message(Path directory, String reason) { + return "Unable to use " + directory + " as the native library cache directory: " + reason + + " (another directory can be set with the " + CACHE_DIR + " system property)"; + } + + /** + * The directory can't be trusted: other users may be able to write it. + */ + static final class UnsafeDirectoryException extends IOException { + UnsafeDirectoryException(Path directory, String reason) { + super(message(directory, reason)); + } + } +} diff --git a/lib/api/src/main/java/com/marcnuri/helm/jni/RemoteJarLoader.java b/lib/api/src/main/java/com/marcnuri/helm/jni/RemoteJarLoader.java index 61975b7..b257026 100644 --- a/lib/api/src/main/java/com/marcnuri/helm/jni/RemoteJarLoader.java +++ b/lib/api/src/main/java/com/marcnuri/helm/jni/RemoteJarLoader.java @@ -17,38 +17,57 @@ package com.marcnuri.helm.jni; import org.w3c.dom.Document; +import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; -import java.io.FileOutputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; +import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; +import java.nio.charset.StandardCharsets; import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.DirectoryStream; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.EnumSet; +import java.util.Locale; import java.util.Properties; import java.util.UUID; -import java.util.zip.ZipException; -import java.util.zip.ZipFile; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; /** + * Downloads the native library JAR for the current platform from the Maven repository, verifies it against the + * repository's SHA-1 checksum, and caches it in the per-user {@link CacheDirectory}. + * + *

When a JAR is verified and cached, its checksum and size are recorded next to it ({@code .verified}). A + * cached JAR is used without hashing it again if it's still a private file (a regular file that, on POSIX file + * systems, belongs to the current user and isn't writable by others) of the recorded size; otherwise it's downloaded + * and verified again. + * * @author Marc Nuri */ class RemoteJarLoader { - private static final String TEMP_DIR = "java.io.tmpdir"; private static final String VERSION = "com.marcnuri.jkube-helm.version"; private static final String GROUP_ID = "com.marcnuri.jkube-helm.groupId"; private static final String SNAPSHOTS = "com.marcnuri.jkube-helm.repository.snapshots"; @@ -59,6 +78,18 @@ class RemoteJarLoader { // Without them, an unresponsive repository blocks the native library lookup forever static final int CONNECT_TIMEOUT_MILLIS = 10_000; static final int READ_TIMEOUT_MILLIS = 30_000; + private static final String CHECKSUM_EXTENSION = ".sha1"; + private static final String RECORD_EXTENSION = ".verified"; + private static final Pattern SHA1 = Pattern.compile("[0-9a-f]{40}"); + private static final Pattern SNAPSHOT_TIMESTAMP = Pattern.compile("\\d{8}\\.\\d{6}"); + private static final Pattern SNAPSHOT_BUILD_NUMBER = Pattern.compile("\\d+"); + // Downloads still in progress keep writing (or time out after READ_TIMEOUT_MILLIS), so a .part file not modified + // for this long was left behind by a JVM that stopped mid-download + static final long STALE_PART_FILE_MILLIS = TimeUnit.HOURS.toMillis(1); + private static final String PART_EXTENSION = ".part"; + // The names partFile() generates for a JAR or its record: ..part + private static final Pattern PART_FILE = Pattern.compile( + ".+\\.jar(\\" + RECORD_EXTENSION + ")?\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\" + PART_EXTENSION); private RemoteJarLoader() { } @@ -67,7 +98,8 @@ private RemoteJarLoader() { * Downloads (or reuses the cached) native library JAR for the current platform. * * @return a class loader for the JAR, or {@code null} if the remote JAR is disabled or the platform is unknown. - * @throws IOException if the JAR (or the snapshot metadata) can't be downloaded or read. + * @throws IOException if the JAR (or the snapshot metadata) can't be downloaded or verified, or if the cache + * directory can't be used. */ static ClassLoader remoteJar() throws IOException { // For testing @@ -93,8 +125,31 @@ static ClassLoader remoteJar() throws IOException { if (osName == null || archName == null) { return null; } - return remoteJar(repository, nativeLibraries.getProperty(GROUP_ID), version, osName, archName, - Paths.get(System.getProperty(TEMP_DIR))); + final CacheDirectory cacheDirectory = CacheDirectory.select(); + try { + return remoteJar(repository, nativeLibraries.getProperty(GROUP_ID), version, osName, archName, + cacheDirectory.getDirectory()); + } finally { + if (cacheDirectory.isTemporary()) { + deleteOnExit(cacheDirectory.getDirectory()); + } + } + } + + /** + * Registers the files in the (temporary) directory to be deleted when the JVM exits, whether the download + * succeeded or not. They're registered after the directory, so they're deleted before it (in reverse order). On + * Windows, the loaded JAR is still open then (its class loader is never closed), so it and the directory are left + * behind in the temporary directory. + */ + private static void deleteOnExit(Path temporaryDirectory) { + try (DirectoryStream files = Files.newDirectoryStream(temporaryDirectory)) { + for (Path file : files) { + file.toFile().deleteOnExit(); + } + } catch (IOException exception) { + // Best effort + } } static ClassLoader remoteJar(String repository, String groupId, String version, String osName, String archName, @@ -113,69 +168,218 @@ static ClassLoader remoteJar(String repository, String groupId, String version, private static String latestSnapshot(String version, String osName, String archName, String groupUrl) throws IOException { final String metadataXml = groupUrl + "/maven-metadata.xml"; + final String timestamp; + final String buildNumber; try (InputStream stream = openStream(new URL(metadataXml), CONNECT_TIMEOUT_MILLIS, READ_TIMEOUT_MILLIS)) { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - final Document xml = factory.newDocumentBuilder().parse(stream, metadataXml); + final DocumentBuilder documentBuilder = factory.newDocumentBuilder(); + // The default handler also prints parse errors to stderr; they're already reported with the exception + documentBuilder.setErrorHandler(new ThrowingErrorHandler()); + final Document xml = documentBuilder.parse(stream, metadataXml); final XPath xPath = XPathFactory.newInstance().newXPath(); - final String versionFragment = version.replace("-SNAPSHOT", ""); - final String timestamp = xPath.evaluate("//metadata/versioning/snapshot/timestamp", xml); - final String buildNumber = xPath.evaluate("//metadata/versioning/snapshot/buildNumber", xml); - return osName + "-" + archName + "-" + versionFragment + "-" + timestamp + "-" + buildNumber + ".jar"; + timestamp = xPath.evaluate("//metadata/versioning/snapshot/timestamp", xml).trim(); + buildNumber = xPath.evaluate("//metadata/versioning/snapshot/buildNumber", xml).trim(); } catch (ParserConfigurationException | SAXException | XPathExpressionException exception) { throw new IOException("Unable to read " + metadataXml, exception); } + if (timestamp.isEmpty() || buildNumber.isEmpty()) { + throw new IOException("No snapshot version in " + metadataXml); + } + // They become part of a file name in the cache directory + if (!SNAPSHOT_TIMESTAMP.matcher(timestamp).matches() || !SNAPSHOT_BUILD_NUMBER.matcher(buildNumber).matches()) { + throw new IOException("Invalid snapshot version in " + metadataXml + ": " + timestamp + "-" + buildNumber); + } + final String versionFragment = version.replace("-SNAPSHOT", ""); + return osName + "-" + archName + "-" + versionFragment + "-" + timestamp + "-" + buildNumber + ".jar"; } static URL cache(URL jarUrl, Path jarFile) throws IOException { return cache(jarUrl, jarFile, CONNECT_TIMEOUT_MILLIS, READ_TIMEOUT_MILLIS); } + /** + * Returns the cached JAR if it's still a private file of the size recorded when it was verified, otherwise + * downloads it, verifies it against the repository's {@code .sha1} checksum, and caches it. + * + *

The directory of {@code jarFile} must be private to the current user (see {@link CacheDirectory}). + */ static URL cache(URL jarUrl, Path jarFile, int connectTimeoutMillis, int readTimeoutMillis) throws IOException { - if (System.getProperty(FORCE_UPDATE) != null || !jarFile.toFile().exists() || !jarFile.toFile().isFile()) { - // Download next to the target and move it into place, so that neither this JVM on a later run nor a - // concurrent JVM ever sees (or deletes) a partial JAR - final Path partFile = jarFile.resolveSibling(jarFile.getFileName() + "." + UUID.randomUUID() + ".part"); + final Path recordFile = jarFile.resolveSibling(jarFile.getFileName() + RECORD_EXTENSION); + if (System.getProperty(FORCE_UPDATE) == null && isCached(jarFile, recordFile)) { + return jarFile.toUri().toURL(); + } + deleteStalePartFiles(jarFile.getParent()); + final String expectedChecksum = readChecksum( + new URL(jarUrl + CHECKSUM_EXTENSION), connectTimeoutMillis, readTimeoutMillis); + // Download next to the target and move it into place, so that neither this JVM on a later run nor a + // concurrent JVM ever sees (or deletes) a partial JAR + final Path partFile = partFile(jarFile); + try { + final URLConnection connection = openConnection(jarUrl, connectTimeoutMillis, readTimeoutMillis); + final MessageDigest digest = sha1(); final long downloaded; - try { - final URLConnection connection = openConnection(jarUrl, connectTimeoutMillis, readTimeoutMillis); - try ( - ReadableByteChannel inChannel = Channels.newChannel(connection.getInputStream()); - FileOutputStream fos = new FileOutputStream(partFile.toFile()); - FileChannel outChannel = fos.getChannel() - ) { - downloaded = outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE); - // A connection dropped mid-body reads as a normal end of stream. This cheap first check only covers - // responses with a Content-Length (not chunked or close-delimited ones): the ZIP check below covers all - final long expected = connection.getContentLengthLong(); - if (expected >= 0 && downloaded != expected) { - throw new IOException("Incomplete download of " + jarUrl + ": got " + downloaded + " of " + expected + " bytes"); - } + try ( + ReadableByteChannel inChannel = Channels.newChannel(new DigestInputStream(connection.getInputStream(), digest)); + FileChannel outChannel = createOwnerOnly(partFile) + ) { + downloaded = outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE); + // A connection dropped mid-body reads as a normal end of stream. This first check gives a clearer error for + // responses with a Content-Length; the checksum also covers chunked and close-delimited ones + final long expected = connection.getContentLengthLong(); + if (expected >= 0 && downloaded != expected) { + throw new IOException("Incomplete download of " + jarUrl + ": got " + downloaded + " of " + expected + " bytes"); } - // The ZIP central directory is at the end of the file, so a truncated download fails to open - try (ZipFile ignored = new ZipFile(partFile.toFile())) { - // Valid - } catch (ZipException exception) { - throw new IOException("Invalid download of " + jarUrl + ": truncated or not a valid ZIP", exception); - } - } catch (IOException | RuntimeException exception) { - deletePartFile(partFile, exception); + } + final String actualChecksum = hex(digest.digest()); + if (!actualChecksum.equals(expectedChecksum)) { + throw new IOException("Checksum mismatch for " + jarUrl + ": expected SHA-1 " + expectedChecksum + + ", got " + actualChecksum); + } + // The record first: a JAR without (a matching) one is never used from the cache + writeRecord(recordFile, actualChecksum, downloaded); + } catch (IOException | RuntimeException exception) { + deletePartFile(partFile, exception); + throw exception; + } + try { + move(partFile, jarFile); + } catch (IOException exception) { + deletePartFile(partFile, exception); + // A concurrent JVM may have moved its (identical) JAR into place first and still hold it open, which + // prevents replacing it on Windows: use that one, if it matches the checksum just fetched + if (!CacheDirectory.isPrivateFile(jarFile) || !expectedChecksum.equals(sha1(jarFile))) { throw exception; } - try { - move(partFile, jarFile); - } catch (IOException exception) { - deletePartFile(partFile, exception); - // A concurrent JVM may have moved its (complete) JAR into place first and still hold it open, which - // prevents replacing it on Windows: use that one, if it is the same size as the one just downloaded - // (a partial JAR left by a version without the .part download is not) - if (!jarFile.toFile().isFile() || jarFile.toFile().length() != downloaded) { - throw exception; + } + return jarFile.toUri().toURL(); + } + + /** + * Whether the JAR and its record are private files (see {@link CacheDirectory#isPrivateFile(Path)}) and the JAR + * still has the size recorded when it was verified. + * + *

The JAR isn't hashed again: other users can't write it, and this catches an incomplete or corrupt replacement + * by its size (a same-user process that replaces it with another file of the same size isn't detected). + */ + private static boolean isCached(Path jarFile, Path recordFile) throws IOException { + if (!CacheDirectory.isPrivateFile(jarFile) || !CacheDirectory.isPrivateFile(recordFile)) { + return false; + } + final Properties record = new Properties(); + try (InputStream stream = Files.newInputStream(recordFile, LinkOption.NOFOLLOW_LINKS)) { + record.load(stream); + } catch (IllegalArgumentException exception) { + // A corrupt record (e.g. a malformed Unicode escape): download again, which replaces it + return false; + } + final String size = record.getProperty("size"); + return parseChecksum(record.getProperty("sha1", "")) != null && size != null && + size.equals(Long.toString(Files.size(jarFile))); + } + + private static String readChecksum(URL checksumUrl, int connectTimeoutMillis, int readTimeoutMillis) + throws IOException { + final ByteArrayOutputStream content = new ByteArrayOutputStream(); + try (InputStream stream = openStream(checksumUrl, connectTimeoutMillis, readTimeoutMillis)) { + final byte[] buffer = new byte[256]; + int read; + // A checksum file is a few dozen bytes: don't read an unexpected large response into memory + while ((read = stream.read(buffer)) != -1 && content.size() < 4096) { + content.write(buffer, 0, read); + } + } + final String checksum = parseChecksum(new String(content.toByteArray(), StandardCharsets.US_ASCII)); + if (checksum == null) { + throw new IOException("Invalid SHA-1 checksum file " + checksumUrl); + } + return checksum; + } + + /** + * Parses a {@code .sha1} file: the hex digest, optionally followed by whitespace and the file name. + * + * @return the lower-case digest, or {@code null} if the content isn't a SHA-1 checksum. + */ + private static String parseChecksum(String content) { + final String[] tokens = content.trim().split("\\s+", 2); + final String checksum = tokens[0].toLowerCase(Locale.ROOT); + return SHA1.matcher(checksum).matches() ? checksum : null; + } + + private static void writeRecord(Path recordFile, String checksum, long size) throws IOException { + final Path partFile = partFile(recordFile); + try { + try (FileChannel channel = createOwnerOnly(partFile)) { + channel.write(ByteBuffer.wrap(("sha1=" + checksum + "\nsize=" + size + "\n").getBytes(StandardCharsets.US_ASCII))); + } + move(partFile, recordFile); + } catch (IOException exception) { + deletePartFile(partFile, exception); + throw exception; + } + } + + /** + * Creates a new file ({@code O_EXCL}) only its owner can read or write, whatever the umask. + */ + private static FileChannel createOwnerOnly(Path file) throws IOException { + return FileChannel.open(file, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), + CacheDirectory.ownerOnlyFile()); + } + + private static String sha1(Path file) throws IOException { + final MessageDigest digest = sha1(); + try (InputStream stream = new DigestInputStream(Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS), digest)) { + final byte[] buffer = new byte[64 * 1024]; + while (stream.read(buffer) != -1) { + // Digest + } + } + return hex(digest.digest()); + } + + private static MessageDigest sha1() { + try { + return MessageDigest.getInstance("SHA-1"); + } catch (NoSuchAlgorithmException exception) { + // Every Java platform implementation is required to support SHA-1 + throw new IllegalStateException(exception); + } + } + + private static String hex(byte[] bytes) { + final StringBuilder hex = new StringBuilder(bytes.length * 2); + for (byte b : bytes) { + hex.append(Character.forDigit((b >> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16)); + } + return hex.toString(); + } + + private static Path partFile(Path file) { + return file.resolveSibling(file.getFileName() + "." + UUID.randomUUID() + PART_EXTENSION); + } + + /** + * Deletes the {@code .part} files this class creates in the (private) cache directory that haven't been modified + * for {@link #STALE_PART_FILE_MILLIS}: a JVM killed mid-download leaves them behind, and their names are never + * reused. + */ + private static void deleteStalePartFiles(Path cacheDirectory) { + final long staleBefore = System.currentTimeMillis() - STALE_PART_FILE_MILLIS; + try (DirectoryStream files = Files.newDirectoryStream(cacheDirectory)) { + for (Path file : files) { + final String name = file.getFileName().toString(); + if (PART_FILE.matcher(name).matches() && + Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS) && + Files.getLastModifiedTime(file, LinkOption.NOFOLLOW_LINKS).toMillis() < staleBefore) { + Files.deleteIfExists(file); } } + } catch (IOException exception) { + // Best effort: a leftover file wastes space but is never used } - return jarFile.toUri().toURL(); } private static void deletePartFile(Path partFile, Exception exception) { @@ -209,4 +413,24 @@ private static URLConnection openConnection(URL url, int connectTimeoutMillis, i connection.setReadTimeout(readTimeoutMillis); return connection; } + + /** + * Fails on any parse error without printing it (the default handler prints errors to stderr). + */ + private static final class ThrowingErrorHandler implements ErrorHandler { + @Override + public void warning(SAXParseException exception) { + // Not an error + } + + @Override + public void error(SAXParseException exception) throws SAXException { + throw exception; + } + + @Override + public void fatalError(SAXParseException exception) throws SAXException { + throw exception; + } + } } diff --git a/lib/api/src/test/java/com/marcnuri/helm/jni/CacheDirectoryTest.java b/lib/api/src/test/java/com/marcnuri/helm/jni/CacheDirectoryTest.java new file mode 100644 index 0000000..b218030 --- /dev/null +++ b/lib/api/src/test/java/com/marcnuri/helm/jni/CacheDirectoryTest.java @@ -0,0 +1,434 @@ +/* + * Copyright 2024 Marc Nuri + * + * 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 com.marcnuri.helm.jni; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import static com.marcnuri.helm.jni.TestFiles.assumePosix; +import static com.marcnuri.helm.jni.TestFiles.permissions; +import static com.marcnuri.helm.jni.TestFiles.setPermissions; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * @author Marc Nuri + */ +class CacheDirectoryTest { + + @TempDir + private Path tempDir; + + // A controlled environment: no test depends on the real one (e.g. LOCALAPPDATA on Windows, XDG_CACHE_HOME) + private final Map env = new HashMap<>(); + + @Nested + class DefaultDirectory { + + @Test + void linuxUsesXdgCacheHome() { + env.put("XDG_CACHE_HOME", tempDir.toString()); + assertThat(CacheDirectory.defaultDirectory("linux", env::get, "/home/user")) + .isEqualTo(tempDir.resolve("helm-java")); + } + + @Test + void linuxIgnoresRelativeXdgCacheHome() { + env.put("XDG_CACHE_HOME", "relative/cache"); + assertThat(CacheDirectory.defaultDirectory("linux", env::get, tempDir.toString())) + .isEqualTo(tempDir.resolve(".cache").resolve("helm-java")); + } + + @Test + void linuxDefaultsToUserHomeCache() { + assertThat(CacheDirectory.defaultDirectory("linux", env::get, tempDir.toString())) + .isEqualTo(tempDir.resolve(".cache").resolve("helm-java")); + } + + @Test + void macOsDefaultsToUserHomeCache() { + assertThat(CacheDirectory.defaultDirectory("darwin", env::get, tempDir.toString())) + .isEqualTo(tempDir.resolve(".cache").resolve("helm-java")); + } + + @Test + void windowsUsesLocalAppData() { + env.put("LOCALAPPDATA", tempDir.toString()); + assertThat(CacheDirectory.defaultDirectory("windows", env::get, "/home/user")) + .isEqualTo(tempDir.resolve("helm-java").resolve("cache")); + } + + @Test + void windowsDefaultsToUserProfile() { + assertThat(CacheDirectory.defaultDirectory("windows", env::get, tempDir.toString())) + .isEqualTo(tempDir.resolve("AppData").resolve("Local").resolve("helm-java").resolve("cache")); + } + } + + @Nested + class Select { + + private CacheDirectory selected; + + @AfterEach + void deleteTemporaryDirectory() throws IOException { + if (selected != null && selected.isTemporary()) { + Files.deleteIfExists(selected.getDirectory()); + } + } + + @Test + void usesDirectorySetWithSystemProperty() throws IOException { + selected = CacheDirectory.select(tempDir.resolve("custom").toString(), "linux", env::get, tempDir.toString()); + assertThat(selected.getDirectory()).isEqualTo(tempDir.resolve("custom")).isDirectory(); + assertThat(selected.isTemporary()).isFalse(); + } + + @Test + void failsWhenDirectorySetWithSystemPropertyCantBeCreated() throws IOException { + assumePosix(); + final Path readOnly = Files.createDirectory(tempDir.resolve("read-only")); + setPermissions(readOnly, "r-x------"); + assumeTrue(!Files.isWritable(readOnly), "Running as a user that can write any directory (root)"); + final String configured = readOnly.resolve("cache").toString(); + assertThatThrownBy(() -> CacheDirectory.select(configured, "linux", env::get, tempDir.toString())) + .isInstanceOf(IOException.class) + .hasMessageStartingWith("Unable to use " + configured + " as the native library cache directory: it can't be created") + .hasMessageEndingWith("(another directory can be set with the com.marcnuri.jkube-helm.cacheDir system property)"); + } + + @Test + void failsWhenDirectorySetWithSystemPropertyIsUnsafe() throws IOException { + assumePosix(); + final Path unsafe = Files.createDirectory(tempDir.resolve("unsafe")); + setPermissions(unsafe, "rwxrwxrwx"); + assertThatThrownBy(() -> CacheDirectory.select(unsafe.toString(), "linux", env::get, tempDir.toString())) + .isInstanceOf(CacheDirectory.UnsafeDirectoryException.class); + } + + @Test + void ignoresBlankSystemProperty() throws IOException { + selected = CacheDirectory.select(" ", "linux", env::get, tempDir.toString()); + assertThat(selected.getDirectory()).isEqualTo(tempDir.resolve(".cache").resolve("helm-java")); + } + + @Test + void createsDefaultDirectory() throws IOException { + selected = CacheDirectory.select(null, "linux", env::get, tempDir.toString()); + assertThat(selected.getDirectory()).isEqualTo(tempDir.resolve(".cache").resolve("helm-java")).isDirectory(); + assertThat(selected.isTemporary()).isFalse(); + } + + @Test + void usesTemporaryDirectoryWithoutAbsoluteUserHome() throws IOException { + selected = CacheDirectory.select(null, "linux", env::get, "?"); + assertTemporary(selected); + } + + @Test + void warnsWhenUsingTemporaryDirectory() throws IOException { + final Logger logger = Logger.getLogger(CacheDirectory.class.getName()); + final List records = new ArrayList<>(); + final Handler handler = new Handler() { + @Override + public void publish(LogRecord logRecord) { + records.add(logRecord); + } + + @Override + public void flush() { + // NO-OP + } + + @Override + public void close() { + // NO-OP + } + }; + logger.addHandler(handler); + try { + selected = CacheDirectory.select(null, "linux", env::get, "?"); + } finally { + logger.removeHandler(handler); + } + assertThat(records).singleElement() + .returns(Level.WARNING, LogRecord::getLevel) + .extracting(LogRecord::getMessage).asString() + .contains(selected.getDirectory().toString(), "no per-user directory for user.home=?"); + } + + @Test + void usesTemporaryDirectoryWithoutUserHome() throws IOException { + selected = CacheDirectory.select(null, "linux", env::get, null); + assertTemporary(selected); + } + + @Test + void usesTemporaryDirectoryWithNonexistentUserHome() throws IOException { + // e.g. HOME=/nonexistent for system users + final Path root = tempDir.getRoot(); + assumeTrue(!Files.isWritable(root), "Running as a user that can write the file system root"); + selected = CacheDirectory.select(null, "linux", env::get, root.resolve("nonexistent-helm-java-home").toString()); + assertTemporary(selected); + } + + @Test + void treatsRootOwnedDirectoryAsUnusableNotUnsafe() throws IOException { + assumePosix(); + // e.g. a directory created while building a container image: safe, but not writable by this user + final Path rootOwned = Paths.get("/usr"); + // By user id (under user namespaces root-owned files show as another user, e.g. nobody, uid 65534) + assumeTrue(Files.isDirectory(rootOwned) && + Integer.valueOf(0).equals(Files.getAttribute(rootOwned, "unix:uid", LinkOption.NOFOLLOW_LINKS)) && + !Files.isWritable(rootOwned), "Needs a root-owned directory this user can't write"); + // So that as the default directory it's replaced by a temporary one instead of failing + assertThatThrownBy(() -> CacheDirectory.ensurePrivate(rootOwned)) + .isInstanceOf(IOException.class) + .isNotInstanceOf(CacheDirectory.UnsafeDirectoryException.class) + .hasMessageContaining("it's owned by root"); + } + + @Test + void usesTemporaryDirectoryWhenDefaultCantBeCreated() throws IOException { + assumePosix(); + // e.g. a read-only home, or a ~/.cache created by root + setPermissions(tempDir, "r-x------"); + try { + assumeTrue(!Files.isWritable(tempDir), "Running as a user that can write any directory (root)"); + selected = CacheDirectory.select(null, "linux", env::get, tempDir.toString()); + assertTemporary(selected); + } finally { + setPermissions(tempDir, "rwx------"); + } + } + + @Test + void usesTemporaryDirectoryWhenDefaultIsNotWritable() throws IOException { + assumePosix(); + final Path defaultDirectory = Files.createDirectories(tempDir.resolve(".cache").resolve("helm-java")); + setPermissions(defaultDirectory, "r-x------"); + try { + assumeTrue(!Files.isWritable(defaultDirectory), "Running as a user that can write any directory (root)"); + selected = CacheDirectory.select(null, "linux", env::get, tempDir.toString()); + assertTemporary(selected); + } finally { + setPermissions(defaultDirectory, "rwx------"); + } + } + + @Test + void failsWhenDefaultIsUnsafe() throws IOException { + assumePosix(); + final Path defaultDirectory = Files.createDirectories(tempDir.resolve(".cache").resolve("helm-java")); + setPermissions(defaultDirectory, "rwxrwx---"); + assertThatThrownBy(() -> CacheDirectory.select(null, "linux", env::get, tempDir.toString())) + .isInstanceOf(CacheDirectory.UnsafeDirectoryException.class) + .hasMessageContaining("it's group- or world-writable (rwxrwx---)"); + } + + private void assertTemporary(CacheDirectory cacheDirectory) throws IOException { + assertThat(cacheDirectory.isTemporary()).isTrue(); + assertThat(cacheDirectory.getDirectory()).isDirectory(); + assertThat(cacheDirectory.getDirectory().toRealPath().getParent()) + .isEqualTo(Paths.get(System.getProperty("java.io.tmpdir")).toRealPath()); + if (TestFiles.isPosix()) { + assertThat(permissions(cacheDirectory.getDirectory())).isEqualTo("rwx------"); + } + } + } + + @Nested + class EnsurePrivate { + + @BeforeEach + void posixOnly() { + assumePosix(); + } + + @Test + void createsMissingDirectoriesOwnerOnly() throws IOException { + final Path directory = tempDir.resolve("parent").resolve("cache"); + assertThat(CacheDirectory.ensurePrivate(directory)).isEqualTo(directory); + assertThat(permissions(directory)).isEqualTo("rwx------"); + assertThat(permissions(directory.getParent())).isEqualTo("rwx------"); + } + + @Test + void acceptsExistingPrivateDirectoryWithoutWritingToIt() throws IOException { + final Path directory = Files.createDirectory(tempDir.resolve("cache")); + setPermissions(directory, "rwx------"); + // Creating (even deleting right away) a file in it would change its modification time + // Whole seconds: some file systems (HFS+, FAT) don't store finer timestamps + final FileTime modified = FileTime.from(System.currentTimeMillis() / 1000 - 3_600, TimeUnit.SECONDS); + Files.setLastModifiedTime(directory, modified); + assertThat(CacheDirectory.ensurePrivate(directory)).isEqualTo(directory); + assertThat(Files.getLastModifiedTime(directory)).isEqualTo(modified); + } + + @Test + void acceptsReadableByOthers() throws IOException { + final Path directory = Files.createDirectory(tempDir.resolve("cache")); + setPermissions(directory, "rwxr-xr-x"); + assertThat(CacheDirectory.ensurePrivate(directory)).isEqualTo(directory); + } + + @Test + void refusesGroupWritableWithoutWritingToIt() throws IOException { + final Path directory = Files.createDirectory(tempDir.resolve("cache")); + setPermissions(directory, "rwxrwx---"); + // Before a directory is trusted, another user able to rename files in it could swap a file created there (e.g. + // one to look up the current user): creating, even deleting right away, a file would change its modification time + // Whole seconds: some file systems (HFS+, FAT) don't store finer timestamps + final FileTime modified = FileTime.from(System.currentTimeMillis() / 1000 - 3_600, TimeUnit.SECONDS); + Files.setLastModifiedTime(directory, modified); + assertThatThrownBy(() -> CacheDirectory.ensurePrivate(directory)) + .isInstanceOf(CacheDirectory.UnsafeDirectoryException.class) + .hasMessageStartingWith("Unable to use " + directory + " as the native library cache directory: " + + "it's group- or world-writable (rwxrwx---)"); + assertThat(Files.getLastModifiedTime(directory)).isEqualTo(modified); + } + + @Test + void refusesGroupWritableBeforeLookingUpTheOwner() throws IOException { + // Not writable by its owner: looking up the current user with a file in it would fail first + final Path directory = Files.createDirectory(tempDir.resolve("cache")); + setPermissions(directory, "r-xrwx---"); + try { + assertThatThrownBy(() -> CacheDirectory.ensurePrivate(directory)) + .isInstanceOf(CacheDirectory.UnsafeDirectoryException.class) + .hasMessageContaining("it's group- or world-writable (r-xrwx---)"); + } finally { + setPermissions(directory, "rwx------"); + } + } + + @Test + void looksUpTheOwnerWithoutWritingToTheDirectory() throws IOException { + // Before a directory is trusted, another user able to rename files in it could swap a file created there + final Path directory = Files.createDirectory(tempDir.resolve("cache")); + setPermissions(directory, "r-x------"); + try { + assumeTrue(!Files.isWritable(directory), "Running as a user that can write any directory (root)"); + assertThatThrownBy(() -> CacheDirectory.ensurePrivate(directory)) + .isInstanceOf(IOException.class) + .hasMessageContaining("it's not writable"); + } finally { + setPermissions(directory, "rwx------"); + } + } + + @Test + void refusesWorldWritable() throws IOException { + final Path directory = Files.createDirectory(tempDir.resolve("cache")); + setPermissions(directory, "rwx---rwx"); + assertThatThrownBy(() -> CacheDirectory.ensurePrivate(directory)) + .isInstanceOf(CacheDirectory.UnsafeDirectoryException.class) + .hasMessageContaining("it's group- or world-writable (rwx---rwx)"); + } + + @Test + void refusesSymbolicLink() throws IOException { + final Path target = Files.createDirectory(tempDir.resolve("target")); + setPermissions(target, "rwx------"); + final Path link = tempDir.resolve("link"); + TestFiles.createSymbolicLink(link, target); + assertThatThrownBy(() -> CacheDirectory.ensurePrivate(link)) + .isInstanceOf(CacheDirectory.UnsafeDirectoryException.class) + .hasMessageContaining("it's a symbolic link"); + } + + @Test + void refusesFileAsUnusable() throws IOException { + final Path file = Files.createFile(tempDir.resolve("a-file")); + assertThatThrownBy(() -> CacheDirectory.ensurePrivate(file)) + .isInstanceOf(IOException.class) + .isNotInstanceOf(CacheDirectory.UnsafeDirectoryException.class) + .hasMessageContaining("it's not a directory"); + } + + @Test + void refusesNotWritableAsUnusable() throws IOException { + final Path directory = Files.createDirectory(tempDir.resolve("cache")); + setPermissions(directory, "r-x------"); + try { + assumeTrue(!Files.isWritable(directory), "Running as a user that can write any directory (root)"); + assertThatThrownBy(() -> CacheDirectory.ensurePrivate(directory)) + .isInstanceOf(IOException.class) + .isNotInstanceOf(CacheDirectory.UnsafeDirectoryException.class) + .hasMessageContaining("it's not writable"); + } finally { + setPermissions(directory, "rwx------"); + } + } + } + + @Nested + class IsPrivateFile { + + @Test + void acceptsOwnRegularFile() throws IOException { + final Path file = TestFiles.writePrivate(tempDir.resolve("a-file"), new byte[]{1}); + assertThat(CacheDirectory.isPrivateFile(file)).isTrue(); + } + + @Test + void rejectsGroupWritableFile() throws IOException { + assumePosix(); + final Path file = Files.createFile(tempDir.resolve("a-file")); + setPermissions(file, "rw-rw-r--"); + assertThat(CacheDirectory.isPrivateFile(file)).isFalse(); + } + + @Test + void rejectsSymbolicLink() throws IOException { + final Path target = Files.createFile(tempDir.resolve("target")); + final Path link = tempDir.resolve("link"); + TestFiles.createSymbolicLink(link, target); + assertThat(CacheDirectory.isPrivateFile(link)).isFalse(); + } + + @Test + void rejectsDirectory() throws IOException { + assertThat(CacheDirectory.isPrivateFile(Files.createDirectory(tempDir.resolve("a-directory")))).isFalse(); + } + + @Test + void rejectsMissingFile() throws IOException { + assertThat(CacheDirectory.isPrivateFile(tempDir.resolve("missing"))).isFalse(); + } + } +} diff --git a/lib/api/src/test/java/com/marcnuri/helm/jni/RemoteJarLoaderTest.java b/lib/api/src/test/java/com/marcnuri/helm/jni/RemoteJarLoaderTest.java index 34c4535..4adb5a7 100644 --- a/lib/api/src/test/java/com/marcnuri/helm/jni/RemoteJarLoaderTest.java +++ b/lib/api/src/test/java/com/marcnuri/helm/jni/RemoteJarLoaderTest.java @@ -16,6 +16,7 @@ package com.marcnuri.helm.jni; +import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -30,6 +31,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.PrintStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; @@ -38,6 +40,12 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.FileTime; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -45,6 +53,10 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import static com.marcnuri.helm.jni.TestFiles.assumePosix; +import static com.marcnuri.helm.jni.TestFiles.permissions; +import static com.marcnuri.helm.jni.TestFiles.setPermissions; +import static com.marcnuri.helm.jni.TestFiles.writePrivate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -61,75 +73,39 @@ class RemoteJarLoaderTest { private Path tempDir; private byte[] jar; + private String jarSha1; + private Path jarFile; + private Path recordFile; private CountDownLatch release; private ExecutorService executor; private HttpServer server; + private final Map responses = new ConcurrentHashMap<>(); @BeforeEach void setUp() throws IOException { - release = new CountDownLatch(1); jar = jar(); + jarSha1 = sha1(jar); + jarFile = tempDir.resolve("the.jar"); + recordFile = tempDir.resolve("the.jar.verified"); + release = new CountDownLatch(1); executor = Executors.newCachedThreadPool(); server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); server.setExecutor(executor); - server.createContext("/responds", exchange -> { - final byte[] body = "the-content".getBytes(StandardCharsets.UTF_8); - exchange.sendResponseHeaders(200, body.length); - try (OutputStream os = exchange.getResponseBody()) { - os.write(body); - } - }); - server.createContext("/jar", exchange -> { - exchange.sendResponseHeaders(200, jar.length); - try (OutputStream os = exchange.getResponseBody()) { - os.write(jar); - } - }); - server.createContext("/jar-truncated-chunked", exchange -> { - // A chunked response (no Content-Length) with only part of the JAR: what the client gets when such a - // response is cut off, since it reads a dropped chunked or close-delimited body as a normal end of stream - exchange.sendResponseHeaders(200, 0); - try (OutputStream os = exchange.getResponseBody()) { - os.write(jar, 0, jar.length / 2); - } - }); - server.createContext("/repo/com/example/linux-amd64/1.0.0/linux-amd64-1.0.0.jar", exchange -> { - exchange.sendResponseHeaders(200, jar.length); - try (OutputStream os = exchange.getResponseBody()) { - os.write(jar); - } - }); - server.createContext("/repo/com/example/linux-amd64/1.1-SNAPSHOT/maven-metadata.xml", exchange -> { - final byte[] body = ("" + - "20261121.103929401" + - "").getBytes(StandardCharsets.UTF_8); - exchange.sendResponseHeaders(200, body.length); - try (OutputStream os = exchange.getResponseBody()) { - os.write(body); - } - }); - server.createContext("/repo/com/example/linux-amd64/1.1-SNAPSHOT/linux-amd64-1.1-20261121.103929-401.jar", exchange -> { - exchange.sendResponseHeaders(200, jar.length); - try (OutputStream os = exchange.getResponseBody()) { - os.write(jar); - } - }); - server.createContext("/repo/com/example/linux-amd64/1.2-SNAPSHOT/maven-metadata.xml", exchange -> { - final byte[] body = "not xml".getBytes(StandardCharsets.UTF_8); - exchange.sendResponseHeaders(200, body.length); - try (OutputStream os = exchange.getResponseBody()) { - os.write(body); + // Every path not registered in responses gets a 404 + server.createContext("/", exchange -> { + final Responder responder = responses.get(exchange.getRequestURI().getPath()); + if (responder == null) { + exchange.sendResponseHeaders(404, -1); + exchange.close(); + } else { + responder.respond(exchange); } }); - server.createContext("/truncated", exchange -> { - // Declares more bytes than it sends, then drops the connection - exchange.sendResponseHeaders(200, 1024); - exchange.getResponseBody().write("partial".getBytes(StandardCharsets.UTF_8)); - exchange.getResponseBody().flush(); - exchange.close(); - }); - server.createContext("/never-responds", exchange -> { + server.start(); + responses.put("/responds", body("the-content".getBytes(StandardCharsets.UTF_8))); + servesJar("/jar"); + final Responder neverResponds = exchange -> { try { release.await(); } catch (InterruptedException e) { @@ -137,8 +113,9 @@ void setUp() throws IOException { } finally { exchange.close(); } - }); - server.start(); + }; + responses.put("/never-responds", neverResponds); + responses.put("/never-responds.sha1", neverResponds); } @AfterEach @@ -169,48 +146,102 @@ void failsWhenServerStopsResponding() throws IOException { } @Nested - class Cache { + class Download { @Test - void downloadsToTarget() throws IOException { - final Path jarFile = tempDir.resolve("the.jar"); + void cachesJarWithMatchingChecksum() throws IOException { assertThat(RemoteJarLoader.cache(url("/jar"), jarFile)).isEqualTo(jarFile.toUri().toURL()); assertThat(jarFile).hasBinaryContent(jar); + assertThat(recordFile).hasContent("sha1=" + jarSha1 + "\nsize=" + jar.length); assertThat(tempDir).isDirectoryNotContaining("glob:**.part"); } @Test - void notAJarLeavesNoFile() throws IOException { - final Path jarFile = tempDir.resolve("the.jar"); - final URL url = url("/responds"); + void cachedFilesAreOwnerOnly() throws IOException { + assumePosix(); + RemoteJarLoader.cache(url("/jar"), jarFile); + // Whatever the umask (e.g. 002 on hosts where users share a group) + assertThat(permissions(jarFile)).isEqualTo("rw-------"); + assertThat(permissions(recordFile)).isEqualTo("rw-------"); + } + + @Test + void acceptsChecksumFileWithFileName() throws IOException { + responses.put("/named.jar", body(jar)); + responses.put("/named.jar.sha1", body((jarSha1.toUpperCase() + " named.jar\n").getBytes(StandardCharsets.UTF_8))); + RemoteJarLoader.cache(url("/named.jar"), jarFile); + assertThat(jarFile).hasBinaryContent(jar); + } + + @Test + void checksumMismatchLeavesNoFile() throws IOException { + responses.put("/tampered.jar", body("not-the-jar".getBytes(StandardCharsets.UTF_8))); + responses.put("/tampered.jar.sha1", body(jarSha1.getBytes(StandardCharsets.UTF_8))); + final URL url = url("/tampered.jar"); assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) .isInstanceOf(IOException.class) - .hasMessageEndingWith(": truncated or not a valid ZIP"); + .hasMessageStartingWith("Checksum mismatch for " + url + ": expected SHA-1 " + jarSha1); assertThat(tempDir).isEmptyDirectory(); } @Test - void truncatedChunkedDownloadLeavesNoFile() throws IOException { - final Path jarFile = tempDir.resolve("the.jar"); - final URL url = url("/jar-truncated-chunked"); + void missingChecksumLeavesNoFile() throws IOException { + responses.put("/unchecked.jar", body(jar)); + final URL url = url("/unchecked.jar"); + assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) + .isInstanceOf(FileNotFoundException.class) + .hasMessageEndingWith("/unchecked.jar.sha1"); + assertThat(tempDir).isEmptyDirectory(); + } + + @Test + void invalidChecksumLeavesNoFile() throws IOException { + responses.put("/invalid.jar", body(jar)); + responses.put("/invalid.jar.sha1", body("Not found".getBytes(StandardCharsets.UTF_8))); + final URL url = url("/invalid.jar"); assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) .isInstanceOf(IOException.class) - .hasMessageEndingWith(": truncated or not a valid ZIP"); + .hasMessage("Invalid SHA-1 checksum file " + url + ".sha1"); assertThat(tempDir).isEmptyDirectory(); } @Test void truncatedDownloadLeavesNoFile() throws IOException { - final Path jarFile = tempDir.resolve("the.jar"); - final URL url = url("/truncated"); + responses.put("/truncated.jar", exchange -> { + // Declares more bytes than it sends, then drops the connection + exchange.sendResponseHeaders(200, jar.length); + exchange.getResponseBody().write(jar, 0, jar.length / 2); + exchange.getResponseBody().flush(); + exchange.close(); + }); + responses.put("/truncated.jar.sha1", body(jarSha1.getBytes(StandardCharsets.UTF_8))); + final URL url = url("/truncated.jar"); assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) - .isInstanceOf(IOException.class); + .isInstanceOf(IOException.class) + .hasMessageStartingWith("Incomplete download of " + url); + assertThat(tempDir).isEmptyDirectory(); + } + + @Test + void truncatedChunkedDownloadLeavesNoFile() throws IOException { + responses.put("/chunked.jar", exchange -> { + // A chunked response (no Content-Length) with only part of the JAR: what the client gets when such a + // response is cut off, since it reads a dropped chunked or close-delimited body as a normal end of stream + exchange.sendResponseHeaders(200, 0); + try (OutputStream os = exchange.getResponseBody()) { + os.write(jar, 0, jar.length / 2); + } + }); + responses.put("/chunked.jar.sha1", body(jarSha1.getBytes(StandardCharsets.UTF_8))); + final URL url = url("/chunked.jar"); + assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) + .isInstanceOf(IOException.class) + .hasMessageStartingWith("Checksum mismatch for " + url); assertThat(tempDir).isEmptyDirectory(); } @Test void unresponsiveServerTimesOutAndLeavesNoFile() throws IOException { - final Path jarFile = tempDir.resolve("the.jar"); final URL url = url("/never-responds"); assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile, 5_000, 200)) .isInstanceOf(SocketTimeoutException.class); @@ -218,63 +249,201 @@ void unresponsiveServerTimesOutAndLeavesNoFile() throws IOException { } @Test - void usesCachedJarWithoutContactingServer() throws IOException { - final Path jarFile = Files.write(tempDir.resolve("the.jar"), "cached".getBytes(StandardCharsets.UTF_8)); + void failsWhenJarCantBeMovedIntoPlace() throws IOException { + // The fallback for a JAR another JVM holds open on Windows only applies to a private file matching the checksum + Files.write(Files.createDirectory(jarFile).resolve("not-empty"), new byte[]{1}); + final URL url = url("/jar"); + assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) + .isInstanceOf(IOException.class); + assertThat(tempDir).isDirectoryNotContaining("glob:**.part"); + } + + @Test + void deletesStalePartFiles() throws IOException { + final long staleTime = System.currentTimeMillis() - RemoteJarLoader.STALE_PART_FILE_MILLIS - 60_000; + final Path staleJar = Files.write(tempDir.resolve("other.jar." + UUID.randomUUID() + ".part"), new byte[]{1}); + final Path staleRecord = Files.write(tempDir.resolve("other.jar.verified." + UUID.randomUUID() + ".part"), new byte[]{1}); + // Not created by helm-java (e.g. with a cacheDir shared with other tools) + final Path foreign = Files.write(tempDir.resolve("download.part"), new byte[]{1}); + for (Path file : new Path[]{staleJar, staleRecord, foreign}) { + Files.setLastModifiedTime(file, FileTime.fromMillis(staleTime)); + } + // A download in progress (another JVM) keeps its file recently modified + final Path inProgress = Files.write(tempDir.resolve("the.jar." + UUID.randomUUID() + ".part"), new byte[]{1}); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(staleJar).doesNotExist(); + assertThat(staleRecord).doesNotExist(); + assertThat(foreign).exists(); + assertThat(inProgress).exists(); + } + } + + @Nested + class CacheHit { + + @Test + void usesRecordedJarWithoutContactingServer() throws IOException { + writePrivate(jarFile, jar); + writeRecord(jarSha1, jar.length); final long start = System.nanoTime(); assertThat(RemoteJarLoader.cache(url("/never-responds"), jarFile, 5_000, 5_000)) .isEqualTo(jarFile.toUri().toURL()); assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)).isLessThan(2_000L); - assertThat(jarFile).hasContent("cached"); + assertThat(jarFile).hasBinaryContent(jar); } - @Nested - class ForceUpdate { + @Test + void usesSameSizeReplacementWithoutHashingIt() throws IOException { + // Not hashed on every use: a same-user process can replace the JAR with another of the same size (out of + // scope: it can already run any code as that user). Other users can't write it. + final byte[] replacement = new byte[jar.length]; + writePrivate(jarFile, replacement); + writeRecord(jarSha1, jar.length); + RemoteJarLoader.cache(url("/never-responds"), jarFile, 5_000, 200); + assertThat(jarFile).hasBinaryContent(replacement); + } - private String previousForceUpdate; + @Test + void replacesJarOfAnotherSize() throws IOException { + // e.g. incomplete or corrupt + writePrivate(jarFile, "corrupt".getBytes(StandardCharsets.UTF_8)); + writeRecord(jarSha1, jar.length); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(jarFile).hasBinaryContent(jar); + } - @BeforeEach - void setForceUpdate() { - previousForceUpdate = System.setProperty(FORCE_UPDATE, "true"); - } + @Test + void doesNotUseJarOfAnotherSizeWhenServerIsUnreachable() throws IOException { + writePrivate(jarFile, "corrupt".getBytes(StandardCharsets.UTF_8)); + writeRecord(jarSha1, jar.length); + final URL url = url("/never-responds"); + assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile, 5_000, 200)) + .isInstanceOf(SocketTimeoutException.class); + } - @AfterEach - void restoreForceUpdate() { - if (previousForceUpdate == null) { - System.clearProperty(FORCE_UPDATE); - } else { - System.setProperty(FORCE_UPDATE, previousForceUpdate); - } - } + @Test + void replacesJarWithoutRecord() throws IOException { + // e.g. a JAR not downloaded (and verified) by this version + writePrivate(jarFile, "planted".getBytes(StandardCharsets.UTF_8)); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(jarFile).hasBinaryContent(jar); + assertThat(recordFile).hasContent("sha1=" + jarSha1 + "\nsize=" + jar.length); + } - @Test - void replacesCachedJar() throws IOException { - final Path jarFile = Files.write(tempDir.resolve("the.jar"), "cached".getBytes(StandardCharsets.UTF_8)); - RemoteJarLoader.cache(url("/jar"), jarFile); - assertThat(jarFile).hasBinaryContent(jar); - } + @Test + void replacesJarWithInvalidRecord() throws IOException { + writePrivate(jarFile, jar); + writePrivate(recordFile, ("size=" + jar.length).getBytes(StandardCharsets.UTF_8)); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(recordFile).hasContent("sha1=" + jarSha1 + "\nsize=" + jar.length); + } + + @Test + void replacesJarWithMalformedRecord() throws IOException { + writePrivate(jarFile, jar); + // Properties.load rejects a malformed Unicode escape with an IllegalArgumentException + writePrivate(recordFile, ("sha1=\\u12zz\nsize=" + jar.length).getBytes(StandardCharsets.ISO_8859_1)); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(recordFile).hasContent("sha1=" + jarSha1 + "\nsize=" + jar.length); + } - @Test - void keepsCachedJarWhenDownloadFails() throws IOException { - final Path jarFile = Files.write(tempDir.resolve("the.jar"), "cached".getBytes(StandardCharsets.UTF_8)); - final URL url = url("/truncated"); - assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) - .isInstanceOf(IOException.class); - assertThat(jarFile).hasContent("cached"); - assertThat(tempDir).isDirectoryNotContaining("glob:**.part"); + @Test + void replacesJarWritableByOthers() throws IOException { + assumePosix(); + writePrivate(jarFile, jar); + writeRecord(jarSha1, jar.length); + setPermissions(jarFile, "rw-rw-r--"); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(permissions(jarFile)).isEqualTo("rw-------"); + } + + @Test + void replacesJarWithRecordWritableByOthers() throws IOException { + assumePosix(); + writePrivate(jarFile, jar); + writeRecord(jarSha1, jar.length); + setPermissions(recordFile, "rw-rw-rw-"); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(permissions(recordFile)).isEqualTo("rw-------"); + } + + @Test + void replacesSymbolicLinkedJar() throws IOException { + final Path elsewhere = writePrivate(tempDir.resolve("elsewhere.jar"), jar); + writeRecord(jarSha1, jar.length); + TestFiles.createSymbolicLink(jarFile, elsewhere); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(Files.isSymbolicLink(jarFile)).isFalse(); + assertThat(jarFile).hasBinaryContent(jar); + } + } + + @Nested + class ForceUpdate { + + private String previousForceUpdate; + + @BeforeEach + void setForceUpdate() { + previousForceUpdate = System.setProperty(FORCE_UPDATE, "true"); + } + + @AfterEach + void restoreForceUpdate() { + if (previousForceUpdate == null) { + System.clearProperty(FORCE_UPDATE); + } else { + System.setProperty(FORCE_UPDATE, previousForceUpdate); } } + + @Test + void replacesRecordedJar() throws IOException { + final byte[] cached = "cached".getBytes(StandardCharsets.UTF_8); + writePrivate(jarFile, cached); + writeRecord(sha1(cached), cached.length); + RemoteJarLoader.cache(url("/jar"), jarFile); + assertThat(jarFile).hasBinaryContent(jar); + assertThat(recordFile).hasContent("sha1=" + jarSha1 + "\nsize=" + jar.length); + } + + @Test + void keepsCachedJarWhenDownloadFails() throws IOException { + writePrivate(jarFile, "cached".getBytes(StandardCharsets.UTF_8)); + responses.put("/broken.jar", body("not-the-jar".getBytes(StandardCharsets.UTF_8))); + responses.put("/broken.jar.sha1", body(jarSha1.getBytes(StandardCharsets.UTF_8))); + final URL url = url("/broken.jar"); + assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) + .isInstanceOf(IOException.class); + assertThat(jarFile).hasContent("cached"); + assertThat(tempDir).isDirectoryNotContaining("glob:**.part"); + } } @Nested class RemoteJar { + @BeforeEach + void setUp() throws IOException { + servesJar("/repo/com/example/linux-amd64/1.0.0/linux-amd64-1.0.0.jar"); + responses.put("/repo/com/example/linux-amd64/1.1-SNAPSHOT/maven-metadata.xml", body(("" + + "20261121.103929401" + + "").getBytes(StandardCharsets.UTF_8))); + servesJar("/repo/com/example/linux-amd64/1.1-SNAPSHOT/linux-amd64-1.1-20261121.103929-401.jar"); + responses.put("/repo/com/example/linux-amd64/1.2-SNAPSHOT/maven-metadata.xml", + body("not xml".getBytes(StandardCharsets.UTF_8))); + responses.put("/repo/com/example/linux-amd64/1.3-SNAPSHOT/maven-metadata.xml", body( + "20261121103929" + .getBytes(StandardCharsets.UTF_8))); + } + @Test void downloadsReleaseJarIntoCacheDirectory() throws IOException { try (URLClassLoader classLoader = (URLClassLoader) RemoteJarLoader.remoteJar( url("/repo").toString(), "com.example", "1.0.0", "linux", "amd64", tempDir)) { - final Path jarFile = tempDir.resolve("linux-amd64-1.0.0.jar"); - assertThat(classLoader.getURLs()).containsExactly(jarFile.toUri().toURL()); - assertThat(jarFile).hasBinaryContent(jar); + final Path downloaded = tempDir.resolve("linux-amd64-1.0.0.jar"); + assertThat(classLoader.getURLs()).containsExactly(downloaded.toUri().toURL()); + assertThat(downloaded).hasBinaryContent(jar); } } @@ -282,9 +451,9 @@ void downloadsReleaseJarIntoCacheDirectory() throws IOException { void downloadsLatestSnapshotJarFromMetadata() throws IOException { try (URLClassLoader classLoader = (URLClassLoader) RemoteJarLoader.remoteJar( url("/repo").toString(), "com.example", "1.1-SNAPSHOT", "linux", "amd64", tempDir)) { - final Path jarFile = tempDir.resolve("linux-amd64-1.1-20261121.103929-401.jar"); - assertThat(classLoader.getURLs()).containsExactly(jarFile.toUri().toURL()); - assertThat(jarFile).hasBinaryContent(jar); + final Path downloaded = tempDir.resolve("linux-amd64-1.1-20261121.103929-401.jar"); + assertThat(classLoader.getURLs()).containsExactly(downloaded.toUri().toURL()); + assertThat(downloaded).hasBinaryContent(jar); } } @@ -293,7 +462,7 @@ void missingReleaseJarThrowsWithUrl() { assertThatThrownBy(() -> RemoteJarLoader.remoteJar( url("/repo").toString(), "com.example", "2.0.0", "linux", "amd64", tempDir)) .isInstanceOf(FileNotFoundException.class) - .hasMessageEndingWith("/repo/com/example/linux-amd64/2.0.0/linux-amd64-2.0.0.jar"); + .hasMessageEndingWith("/repo/com/example/linux-amd64/2.0.0/linux-amd64-2.0.0.jar.sha1"); assertThat(tempDir).isEmptyDirectory(); } @@ -306,12 +475,50 @@ void missingSnapshotMetadataThrowsWithUrl() { } @Test - void invalidSnapshotMetadataThrowsWithUrl() { + void invalidSnapshotMetadataThrowsWithUrlWithoutPrintingIt() throws IOException { + final PrintStream previousErr = System.err; + final ByteArrayOutputStream err = new ByteArrayOutputStream(); + System.setErr(new PrintStream(err)); + try { + assertThatThrownBy(() -> RemoteJarLoader.remoteJar( + url("/repo").toString(), "com.example", "1.2-SNAPSHOT", "linux", "amd64", tempDir)) + .isInstanceOf(IOException.class) + .hasMessageEndingWith("/repo/com/example/linux-amd64/1.2-SNAPSHOT/maven-metadata.xml") + .hasCauseInstanceOf(SAXException.class); + } finally { + System.setErr(previousErr); + } + assertThat(err.toString()).isEmpty(); + } + + @Test + void snapshotMetadataWithoutSnapshotVersionThrowsWithUrl() throws IOException { assertThatThrownBy(() -> RemoteJarLoader.remoteJar( - url("/repo").toString(), "com.example", "1.2-SNAPSHOT", "linux", "amd64", tempDir)) + url("/repo").toString(), "com.example", "1.3-SNAPSHOT", "linux", "amd64", tempDir)) .isInstanceOf(IOException.class) - .hasMessageEndingWith("/repo/com/example/linux-amd64/1.2-SNAPSHOT/maven-metadata.xml") - .hasCauseInstanceOf(SAXException.class); + .hasMessage("No snapshot version in " + url("/repo") + "/com/example/linux-amd64/1.3-SNAPSHOT/maven-metadata.xml"); + } + } + + @Nested + class SnapshotVersion { + + @BeforeEach + void setUp() { + responses.put("/repo/com/example/linux-amd64/1.4-SNAPSHOT/maven-metadata.xml", body(("" + + "../../../escape1" + + "").getBytes(StandardCharsets.UTF_8))); + } + + @Test + void invalidSnapshotVersionThrowsWithUrl() throws IOException { + // It becomes part of a file name in the cache directory + assertThatThrownBy(() -> RemoteJarLoader.remoteJar( + url("/repo").toString(), "com.example", "1.4-SNAPSHOT", "linux", "amd64", tempDir)) + .isInstanceOf(IOException.class) + .hasMessage("Invalid snapshot version in " + url("/repo") + + "/com/example/linux-amd64/1.4-SNAPSHOT/maven-metadata.xml: ../../../escape-1"); + assertThat(tempDir).isEmptyDirectory(); } } @@ -330,6 +537,24 @@ void readTimeoutIsBounded() { } } + private void writeRecord(String sha1, long size) throws IOException { + writePrivate(recordFile, ("sha1=" + sha1 + "\nsize=" + size + "\n").getBytes(StandardCharsets.UTF_8)); + } + + private void servesJar(String path) { + responses.put(path, body(jar)); + responses.put(path + ".sha1", body(jarSha1.getBytes(StandardCharsets.UTF_8))); + } + + private static Responder body(byte[] body) { + return exchange -> { + exchange.sendResponseHeaders(200, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }; + } + private static byte[] jar() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); try (ZipOutputStream zip = new ZipOutputStream(out)) { @@ -340,6 +565,18 @@ private static byte[] jar() throws IOException { return out.toByteArray(); } + private static String sha1(byte[] bytes) { + try { + final StringBuilder hex = new StringBuilder(); + for (byte b : MessageDigest.getInstance("SHA-1").digest(bytes)) { + hex.append(String.format("%02x", b)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + private URL url(String path) throws IOException { return new URL("http", server.getAddress().getHostString(), server.getAddress().getPort(), path); } @@ -353,4 +590,9 @@ private static String read(InputStream stream) throws IOException { } return new String(out.toByteArray(), StandardCharsets.UTF_8); } + + @FunctionalInterface + private interface Responder { + void respond(HttpExchange exchange) throws IOException; + } } diff --git a/lib/api/src/test/java/com/marcnuri/helm/jni/TestFiles.java b/lib/api/src/test/java/com/marcnuri/helm/jni/TestFiles.java new file mode 100644 index 0000000..57dd9c8 --- /dev/null +++ b/lib/api/src/test/java/com/marcnuri/helm/jni/TestFiles.java @@ -0,0 +1,84 @@ +/* + * Copyright 2024 Marc Nuri + * + * 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 com.marcnuri.helm.jni; + +import java.io.IOException; +import java.nio.file.FileSystemException; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; + +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * File helpers shared by the {@code lib/api} tests. + * + * @author Marc Nuri + */ +final class TestFiles { + + private TestFiles() { + } + + static boolean isPosix() { + return FileSystems.getDefault().supportedFileAttributeViews().contains("posix"); + } + + /** + * Skips the test unless the default file system supports POSIX permissions. + */ + static void assumePosix() { + assumeTrue(isPosix(), "POSIX file permissions not supported"); + } + + static String permissions(Path path) throws IOException { + return PosixFilePermissions.toString(Files.getPosixFilePermissions(path)); + } + + static void setPermissions(Path path, String permissions) throws IOException { + Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(permissions)); + } + + /** + * Writes the file and, on POSIX file systems, makes it owner-only ({@code rw-------}) whatever the umask, like the + * files the cache creates. + */ + static Path writePrivate(Path file, byte[] content) throws IOException { + Files.write(file, content); + if (isPosix()) { + setPermissions(file, "rw-------"); + } + return file; + } + + /** + * Creates a symbolic link, or skips the test where they can't be created. + */ + static void createSymbolicLink(Path link, Path target) throws IOException { + try { + Files.createSymbolicLink(link, target); + } catch (UnsupportedOperationException exception) { + assumeTrue(false, "Symbolic links not supported: " + exception); + } catch (FileSystemException exception) { + // Windows without the privilege to create symbolic links; a failure anywhere else fails the test + assumeFalse(System.getProperty("os.name").startsWith("Windows"), "Symbolic links not allowed: " + exception); + throw exception; + } + } +} diff --git a/pom.xml b/pom.xml index 83d4bfa..d42c44a 100644 --- a/pom.xml +++ b/pom.xml @@ -61,6 +61,7 @@ 3.7.0 3.2.8 3.6.0 + 3.5.1 3.12.0 3.3.1 @@ -221,7 +222,9 @@ + org.apache.maven.plugins maven-jar-plugin + ${version.maven-jar-plugin}