From 7970ee644eb027d5c37c10013ef8f9c9bf8c4ee8 Mon Sep 17 00:00:00 2001 From: Marc Nuri Date: Sun, 22 Nov 2026 04:51:30 +0100 Subject: [PATCH 1/3] fix: isolate tests from the user's Helm config, harden JAR download The Java and Go tests wrote registry logins, repository indexes and lock files into the developer's own Helm config, cache and temp directory, and the remote native JAR download could hang forever or cache a truncated JAR. - Java tests: Surefire points the Helm and Docker homes at target/helm-home, drops the HELM_* overrides, and seeds the registry configs so logins never reach an OS credential store - Go tests: TestMain cleanup actually runs, repositories.yaml files live in t.TempDir() (test.RepositoryConfig), registry configs are seeded - RepoServerStop/StopAll now shut the test OCI servers down - RemoteJarLoader: connect/read timeouts, rejects downloads shorter than their Content-Length, downloads to a .part file and moves it into place - Go repo-server fixtures without goroutines or sleeps, bounded HTTP clients in the fixture tests Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Nuri --- AGENTS.md | 10 +- helm-java/pom.xml | 46 ++++ .../helm-home/config/registry/config.json | 5 + .../src/test/helm-home/docker/config.json | 5 + .../com/marcnuri/helm/HelmPackageTest.java | 5 +- .../com/marcnuri/helm/HelmRegistryTest.java | 6 + .../java/com/marcnuri/helm/HelmShowTest.java | 11 + .../com/marcnuri/helm/HelmTestServerTest.java | 16 +- .../marcnuri/helm/jni/RemoteJarLoader.java | 89 ++++++- .../helm/jni/RemoteJarLoaderTest.java | 176 +++++++++++++ native/internal/helm/helm_test.go | 7 +- native/internal/helm/install_test.go | 9 +- native/internal/helm/repotest.go | 9 +- native/internal/helm/template_test.go | 13 +- native/internal/helm/upgrade_test.go | 10 +- native/internal/test/env.go | 20 +- native/internal/test/repository.go | 37 +++ native/main_test.go | 247 +++++++++--------- pom.xml | 1 + 19 files changed, 556 insertions(+), 166 deletions(-) create mode 100644 helm-java/src/test/helm-home/config/registry/config.json create mode 100644 helm-java/src/test/helm-home/docker/config.json create mode 100644 lib/api/src/test/java/com/marcnuri/helm/jni/RemoteJarLoaderTest.java create mode 100644 native/internal/test/repository.go diff --git a/AGENTS.md b/AGENTS.md index 6bfcaf28..d4cb0f56 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,7 @@ Multi-module Maven build (parent `pom.xml`) + a sibling Go module under `native/ | `lib/wasi/` | Abandoned WebAssembly experiment (issue [#239](https://github.com/manusa/helm-java/issues/239), PR [#243](https://github.com/manusa/helm-java/pull/243)). Not in parent `pom.xml`. Don't touch; will be removed. | | `native/main.go` | **CGO bridge only**: C struct definitions + `//export` wrappers that delegate to `internal/helm`. No business logic. | | `native/internal/helm/` | **Real Go implementations** — one file per verb (`install.go`, `upgrade.go`, …) plus `_test.go` siblings. `helm.go` holds shared config (`NewCfg`), `debug.go` the stdout/stderr capture. | -| `native/internal/test/` | Go test helpers (envtest). | +| `native/internal/test/` | Go test helpers: `SetupIsolatedEnv` (isolated Helm/Docker homes and seeded registry configs, called from each package's `TestMain`) and `RepositoryConfig` (a `repositories.yaml` path in a test temp dir). The envtest (k8s) helper is `internal/helm/envtest_test.go`. | | `native/wasm/`, `native/out/` | TinyGo/WASI experiment entrypoint (see `lib/wasi/` note); build output for shared libraries. | | `docs/research/` | Audits and decision records (e.g. native-codebase audit). Snapshots — may be stale; check the date. | | `scripts/check-authors.sh` | Validates `@author` Javadoc tags (invoked via `make check-authors`). | @@ -125,7 +125,7 @@ Verbs with both forms: `install`, `template`, `show`, `upgrade`. Most others are ## Adding a new Helm command (end-to-end) 1. `native/internal/helm/.go` — write the real Go function (params struct + function returning `(string, error)`). -2. `native/internal/helm/_test.go` — Go test (use `internal/test/env.go` helpers if k8s needed). +2. `native/internal/helm/_test.go` — Go test (use the envtest helpers in `internal/helm/envtest_test.go` if k8s is needed, and `test.RepositoryConfig(t, content)` for any `repositories.yaml`, never `os.CreateTemp("", …)`: repo commands create a lock file next to it). 3. `native/main.go`: - Add `struct Options { ... }` in the CGO comment block. - Add `//export ` wrapper calling `helm.(...)` via `runCommand(...)`. @@ -145,6 +145,12 @@ Verbs with both forms: `install`, `template`, `show`, `upgrade`. Most others are - `@TempDir` as a field for shared dirs; as a parameter for per-test dirs (see `HelmInstallTest`). - k8s integration: `HelmKubernetesTest` spins up KinD via Testcontainers in `@BeforeAll`; clean releases in `@AfterEach`. - Surefire sets `KUBECONFIG=/dev/null` in `helm-java/pom.xml` so tests cannot accidentally hit your local cluster — pass `kubeConfigFile`/`kubeConfigContents` explicitly. +- Surefire also isolates the tests from your Helm and Docker config: + - `HELM_CACHE_HOME`, `HELM_CONFIG_HOME`, `HELM_DATA_HOME` and `DOCKER_CONFIG` point at `helm-java/target/helm-home/`. + - The other `HELM_*` variables from your environment that redirect Helm's files or change its behavior (`HELM_REPOSITORY_CACHE`, `HELM_REPOSITORY_CONFIG`, `HELM_NAMESPACE`, …) are not passed to the tests. `HELM_REGISTRY_CONFIG` is excluded too, defensively: the native registry client doesn't read it. + - Maven's `process-test-resources` phase seeds the registry configs there from `helm-java/src/test/helm-home/` with a placeholder entry, so registry logins go to that file and not to an OS credential store (Keychain, Credential Manager, `pass`, Secret Service). A test run from an IDE on a freshly cleaned `target/`, without that Maven phase, has no seed. + - Trade-off: Testcontainers reads `DOCKER_CONFIG` too, so the KinD 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. ```java class HelmFeatureTest { diff --git a/helm-java/pom.xml b/helm-java/pom.xml index 17129c3a..61b39ff4 100644 --- a/helm-java/pom.xml +++ b/helm-java/pom.xml @@ -17,6 +17,8 @@ requireFilesExist + + ${project.build.directory}/helm-home @@ -27,9 +29,53 @@ /dev/null + + ${helm.test.home}/cache + ${helm.test.home}/config + ${helm.test.home}/data + ${helm.test.home}/docker + + + HELM_DEBUG + HELM_DRIVER + HELM_KUBEAPISERVER + HELM_KUBECONTEXT + HELM_KUBETOKEN + HELM_NAMESPACE + HELM_PLUGINS + HELM_REGISTRY_CONFIG + HELM_REPOSITORY_CACHE + HELM_REPOSITORY_CONFIG + + + + org.apache.maven.plugins + maven-resources-plugin + ${version.maven-resources-plugin} + + + seed-helm-test-home + process-test-resources + + copy-resources + + + ${helm.test.home} + true + + + src/test/helm-home + + + + + + diff --git a/helm-java/src/test/helm-home/config/registry/config.json b/helm-java/src/test/helm-home/config/registry/config.json new file mode 100644 index 00000000..99a7a28b --- /dev/null +++ b/helm-java/src/test/helm-home/config/registry/config.json @@ -0,0 +1,5 @@ +{ + "auths": { + "helm-java.invalid": {} + } +} diff --git a/helm-java/src/test/helm-home/docker/config.json b/helm-java/src/test/helm-home/docker/config.json new file mode 100644 index 00000000..99a7a28b --- /dev/null +++ b/helm-java/src/test/helm-home/docker/config.json @@ -0,0 +1,5 @@ +{ + "auths": { + "helm-java.invalid": {} + } +} diff --git a/helm-java/src/test/java/com/marcnuri/helm/HelmPackageTest.java b/helm-java/src/test/java/com/marcnuri/helm/HelmPackageTest.java index 0538d6fe..aac96c06 100644 --- a/helm-java/src/test/java/com/marcnuri/helm/HelmPackageTest.java +++ b/helm-java/src/test/java/com/marcnuri/helm/HelmPackageTest.java @@ -25,7 +25,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Objects; @@ -66,8 +65,8 @@ void setUp() throws IOException { } @Test - void withoutChart() { - final PackageCommand packageCommand = new Helm(Paths.get("")).packageIt(); + void withoutChart() throws IOException { + final PackageCommand packageCommand = new Helm(Files.createDirectory(tempDir.resolve("no-chart"))).packageIt(); assertThatIllegalStateException() .isThrownBy(packageCommand::call) .withMessage("Chart.yaml file is missing"); diff --git a/helm-java/src/test/java/com/marcnuri/helm/HelmRegistryTest.java b/helm-java/src/test/java/com/marcnuri/helm/HelmRegistryTest.java index 9a439af2..21006430 100644 --- a/helm-java/src/test/java/com/marcnuri/helm/HelmRegistryTest.java +++ b/helm-java/src/test/java/com/marcnuri/helm/HelmRegistryTest.java @@ -17,6 +17,7 @@ package com.marcnuri.helm; import com.marcnuri.helm.jni.RepoServerOptions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -38,6 +39,11 @@ void setUp() { remoteServer = Helm.HelmLibHolder.INSTANCE.RepoOciServerStart(new RepoServerOptions()).out; } + @AfterEach + void tearDown() { + Helm.HelmLibHolder.INSTANCE.RepoServerStop(remoteServer); + } + @Nested class Login { @Test diff --git a/helm-java/src/test/java/com/marcnuri/helm/HelmShowTest.java b/helm-java/src/test/java/com/marcnuri/helm/HelmShowTest.java index 3d7afff1..351fea2d 100644 --- a/helm-java/src/test/java/com/marcnuri/helm/HelmShowTest.java +++ b/helm-java/src/test/java/com/marcnuri/helm/HelmShowTest.java @@ -17,6 +17,7 @@ package com.marcnuri.helm; import com.marcnuri.helm.jni.RepoServerOptions; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @@ -147,6 +148,11 @@ void setUp() { .call(); } + @AfterEach + void tearDown() { + Helm.HelmLibHolder.INSTANCE.RepoServerStop(remoteServer); + } + @Test void all() { final String result = Helm.show("oci://" + remoteServer + "/test") @@ -183,6 +189,11 @@ void setUp() { .call(); } + @AfterEach + void tearDown() { + Helm.HelmLibHolder.INSTANCE.RepoServerStop(remoteServer); + } + @Test void missingVersionThrowsException() { final ShowCommand.ShowSubcommand showAll = Helm.show("oci://" + remoteServer + "/test") diff --git a/helm-java/src/test/java/com/marcnuri/helm/HelmTestServerTest.java b/helm-java/src/test/java/com/marcnuri/helm/HelmTestServerTest.java index 3265f0e2..db77bfb6 100644 --- a/helm-java/src/test/java/com/marcnuri/helm/HelmTestServerTest.java +++ b/helm-java/src/test/java/com/marcnuri/helm/HelmTestServerTest.java @@ -41,8 +41,7 @@ void tearDown() { @Test void testRepoServerStart() throws Exception { final Result result = Helm.HelmLibHolder.INSTANCE.RepoServerStart(new RepoServerOptions()); - final HttpURLConnection uc = (HttpURLConnection) new URI(result.out).toURL().openConnection(); - uc.setRequestMethod("GET"); + final HttpURLConnection uc = get(result.out); uc.connect(); assertThat(uc.getResponseCode()).isEqualTo(200); } @@ -52,8 +51,7 @@ void testRepoServerStartMultipleTimesReturnsMultipleFunctionalUrls() throws Exce final Result result1 = Helm.HelmLibHolder.INSTANCE.RepoServerStart(new RepoServerOptions()); final Result result2 = Helm.HelmLibHolder.INSTANCE.RepoServerStart(new RepoServerOptions()); for (Result result : new Result[]{result1, result2}) { - final HttpURLConnection uc = (HttpURLConnection) new URI(result.out).toURL().openConnection(); - uc.setRequestMethod("GET"); + final HttpURLConnection uc = get(result.out); uc.connect(); assertThat(uc.getResponseCode()).isEqualTo(200); } @@ -65,10 +63,16 @@ void testRepoServerStopAllStopsAllInstances() throws Exception { final Result result2 = Helm.HelmLibHolder.INSTANCE.RepoServerStart(new RepoServerOptions()); Helm.HelmLibHolder.INSTANCE.RepoServerStopAll(); for (Result result : new Result[]{result1, result2}) { - final HttpURLConnection uc = (HttpURLConnection) new URI(result.out).toURL().openConnection(); - uc.setRequestMethod("GET"); + final HttpURLConnection uc = get(result.out); assertThatThrownBy(uc::connect).isInstanceOf(ConnectException.class); } } + private static HttpURLConnection get(String url) throws Exception { + final HttpURLConnection uc = (HttpURLConnection) new URI(url).toURL().openConnection(); + uc.setRequestMethod("GET"); + uc.setConnectTimeout(10_000); + uc.setReadTimeout(10_000); + return uc; + } } 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 513ecaf0..305cdf5a 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 @@ -29,13 +29,17 @@ import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; +import java.net.URLConnection; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; +import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.util.Properties; +import java.util.UUID; /** * @author Marc Nuri @@ -50,6 +54,9 @@ class RemoteJarLoader { // For testing private static final String FORCE_UPDATE = "com.marcnuri.jkube-helm.forceUpdate"; private static final String SKIP = "com.marcnuri.jkube-helm.skipRemoteJar"; + // 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 RemoteJarLoader() { } @@ -100,7 +107,10 @@ private static String latestSnapshot(String version, String osName, String archN 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(metadataXml); + final Document xml; + try (InputStream stream = openStream(new URL(metadataXml), CONNECT_TIMEOUT_MILLIS, READ_TIMEOUT_MILLIS)) { + xml = factory.newDocumentBuilder().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); @@ -108,17 +118,78 @@ private static String latestSnapshot(String version, String osName, String archN return osName + "-" + archName + "-" + versionFragment + "-" + timestamp + "-" + buildNumber + ".jar"; } - private static URL cache(URL jarUrl, Path jarFile) throws IOException { + static URL cache(URL jarUrl, Path jarFile) throws IOException { + return cache(jarUrl, jarFile, CONNECT_TIMEOUT_MILLIS, READ_TIMEOUT_MILLIS); + } + + 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()) { - Files.deleteIfExists(jarFile); - try ( - ReadableByteChannel inChannel = Channels.newChannel(jarUrl.openStream()); - FileOutputStream fos = new FileOutputStream(jarFile.toFile()); - FileChannel outChannel = fos.getChannel() - ) { - outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE); + // 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 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 + final long expected = connection.getContentLengthLong(); + if (expected >= 0 && downloaded != expected) { + throw new IOException("Incomplete download of " + jarUrl + ": got " + downloaded + " of " + expected + " bytes"); + } + } + } 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 (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(); } + + private static void deletePartFile(Path partFile, Exception exception) { + try { + Files.deleteIfExists(partFile); + } catch (IOException cleanupException) { + exception.addSuppressed(cleanupException); + } + } + + private static void move(Path source, Path target) throws IOException { + try { + Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); + } catch (AtomicMoveNotSupportedException exception) { + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); + } + } + + /** + * Same as {@link URL#openStream()}, but fails instead of blocking forever when the server doesn't + * accept the connection or stops sending data. + */ + static InputStream openStream(URL url, int connectTimeoutMillis, int readTimeoutMillis) throws IOException { + return openConnection(url, connectTimeoutMillis, readTimeoutMillis).getInputStream(); + } + + private static URLConnection openConnection(URL url, int connectTimeoutMillis, int readTimeoutMillis) + throws IOException { + final URLConnection connection = url.openConnection(); + connection.setConnectTimeout(connectTimeoutMillis); + connection.setReadTimeout(readTimeoutMillis); + return connection; + } } 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 new file mode 100644 index 00000000..61b40ad4 --- /dev/null +++ b/lib/api/src/test/java/com/marcnuri/helm/jni/RemoteJarLoaderTest.java @@ -0,0 +1,176 @@ +/* + * 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 com.sun.net.httpserver.HttpServer; +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.Timeout; +import org.junit.jupiter.api.io.TempDir; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * @author Marc Nuri + */ +// SEPARATE_THREAD: the timeout fails the test even if a socket read ignores the interrupt +@Timeout(value = 30, unit = TimeUnit.SECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) +class RemoteJarLoaderTest { + + @TempDir + private Path tempDir; + + private CountDownLatch release; + private ExecutorService executor; + private HttpServer server; + + @BeforeEach + void setUp() throws IOException { + 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("/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 -> { + try { + release.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + exchange.close(); + } + }); + server.start(); + } + + @AfterEach + void tearDown() { + release.countDown(); + server.stop(0); + executor.shutdownNow(); + } + + @Nested + class OpenStream { + + @Test + void readsResponse() throws IOException { + try (InputStream stream = RemoteJarLoader.openStream(url("/responds"), 5_000, 5_000)) { + assertThat(read(stream)).isEqualTo("the-content"); + } + } + + @Test + void failsWhenServerStopsResponding() throws IOException { + final URL url = url("/never-responds"); + final long start = System.nanoTime(); + assertThatThrownBy(() -> RemoteJarLoader.openStream(url, 5_000, 200)) + .isInstanceOf(SocketTimeoutException.class); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)).isLessThan(10_000L); + } + } + + @Nested + class Cache { + + @Test + void downloadsToTarget() throws IOException { + final Path jarFile = tempDir.resolve("the.jar"); + assertThat(RemoteJarLoader.cache(url("/responds"), jarFile)).isEqualTo(jarFile.toUri().toURL()); + assertThat(jarFile).hasContent("the-content"); + assertThat(tempDir).isDirectoryNotContaining("glob:**.part"); + } + + @Test + void truncatedDownloadLeavesNoFile() throws IOException { + final Path jarFile = tempDir.resolve("the.jar"); + final URL url = url("/truncated"); + assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) + .isInstanceOf(IOException.class); + 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); + assertThat(tempDir).isEmptyDirectory(); + } + } + + @Nested + class Timeouts { + + // The downloads use these; with 0 (no timeout), an unresponsive repository blocks the lookup forever + @Test + void connectTimeoutIsBounded() { + assertThat(RemoteJarLoader.CONNECT_TIMEOUT_MILLIS).isPositive(); + } + + @Test + void readTimeoutIsBounded() { + assertThat(RemoteJarLoader.READ_TIMEOUT_MILLIS).isPositive(); + } + } + + private URL url(String path) throws IOException { + return new URL("http", server.getAddress().getHostString(), server.getAddress().getPort(), path); + } + + private static String read(InputStream stream) throws IOException { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final byte[] buffer = new byte[1024]; + int read; + while ((read = stream.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return new String(out.toByteArray(), StandardCharsets.UTF_8); + } +} diff --git a/native/internal/helm/helm_test.go b/native/internal/helm/helm_test.go index 7ffe7b1c..6cb54b8d 100644 --- a/native/internal/helm/helm_test.go +++ b/native/internal/helm/helm_test.go @@ -30,9 +30,10 @@ func TestMain(m *testing.M) { if err != nil { panic(err) } - defer cleanup() - - os.Exit(m.Run()) + // Not deferred: os.Exit skips deferred calls, which left the isolated directories behind + code := m.Run() + cleanup() + os.Exit(code) } const kubeConfigContentsForTests = ` diff --git a/native/internal/helm/install_test.go b/native/internal/helm/install_test.go index 799f6fa0..15d7c317 100644 --- a/native/internal/helm/install_test.go +++ b/native/internal/helm/install_test.go @@ -21,6 +21,8 @@ import ( "path" "strings" "testing" + + "github.com/manusa/helm-java/native/internal/test" ) func TestInstallDry(t *testing.T) { @@ -66,13 +68,12 @@ func TestInstallDryUrl(t *testing.T) { func TestInstallFromRepoAndInvalidVersion(t *testing.T) { // Add a temp repository to retrieve the chart from (should include ingress-nginx) - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) + repositoryConfigFile := test.RepositoryConfig(t, "") err := RepoAdd(&RepoOptions{ Name: "helm", Url: "https://charts.helm.sh/stable", InsecureSkipTlsVerify: true, - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) if err != nil { t.Errorf("Expected repo add to succeed, got %s", err) @@ -84,7 +85,7 @@ func TestInstallFromRepoAndInvalidVersion(t *testing.T) { Name: "ingress-nginx", Version: "9999.9999.9999", ClientOnly: true, - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) // Then if err == nil { diff --git a/native/internal/helm/repotest.go b/native/internal/helm/repotest.go index df423a54..e2b58b98 100644 --- a/native/internal/helm/repotest.go +++ b/native/internal/helm/repotest.go @@ -32,10 +32,13 @@ import ( "os" "path/filepath" "testing" + "time" ) var servers = cmap.New[*ActiveServer]() +const ociServerShutdownTimeout = 5 * time.Second + type RepoServerOptions struct { Glob string Username string @@ -137,10 +140,12 @@ func serverStop(server *ActiveServer) { server.server.Stop() } if server.ociServer != nil { - // server.ociServer.Stop() //TODO can't be stopped for now ¯\_(ツ)_/¯ + // Closes the listener and lets ListenAndServe return; bounded in case a connection never goes idle + ctx, cancel := context.WithTimeout(context.Background(), ociServerShutdownTimeout) + _ = server.ociServer.Shutdown(ctx) + cancel() } _ = os.RemoveAll(server.dir) - _ = os.RemoveAll(server.id) } func RepoServerStop(url string) { diff --git a/native/internal/helm/template_test.go b/native/internal/helm/template_test.go index 6b275eee..a4995baa 100644 --- a/native/internal/helm/template_test.go +++ b/native/internal/helm/template_test.go @@ -21,6 +21,8 @@ import ( "os" "strings" "testing" + + "github.com/manusa/helm-java/native/internal/test" ) func TestTemplateFromLocal(t *testing.T) { @@ -90,13 +92,12 @@ func TestTemplateFromLocal(t *testing.T) { func TestTemplateFromReference(t *testing.T) { // Add a temp repository to retrieve the chart from (should include ingress-nginx) - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) + repositoryConfigFile := test.RepositoryConfig(t, "") err := RepoAdd(&RepoOptions{ Name: "ingress-nginx", Url: "https://kubernetes.github.io/ingress-nginx", InsecureSkipTlsVerify: true, - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) if err != nil { t.Errorf("Expected repo add to succeed, got %s", err) @@ -109,7 +110,7 @@ func TestTemplateFromReference(t *testing.T) { manifests, err := Template(&TemplateOptions{ Name: "the-name", Chart: "ingress-nginx/ingress-nginx", - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) if err != nil { t.Errorf("Expected template to succeed, got %s", err) @@ -127,7 +128,7 @@ func TestTemplateFromReference(t *testing.T) { t.Run("with values", func(t *testing.T) { manifests, err := Template(&TemplateOptions{ Chart: "ingress-nginx/ingress-nginx", - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, Values: "controller.image.registry=helm-java.registry.example.com", Debug: true, }) @@ -146,7 +147,7 @@ func TestTemplateFromReference(t *testing.T) { _, _ = valuesFile.WriteString("controller:\n image:\n registry: file.helm-java.registry.example.com\n") manifests, err := Template(&TemplateOptions{ Chart: "ingress-nginx/ingress-nginx", - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, ValuesFiles: valuesFile.Name(), Debug: true, }) diff --git a/native/internal/helm/upgrade_test.go b/native/internal/helm/upgrade_test.go index b74b058c..3a3126eb 100644 --- a/native/internal/helm/upgrade_test.go +++ b/native/internal/helm/upgrade_test.go @@ -17,20 +17,20 @@ package helm import ( - "os" "strings" "testing" + + "github.com/manusa/helm-java/native/internal/test" ) func TestUpgradeFromRepoAndInvalidVersion(t *testing.T) { // Add a temp repository to retrieve the chart from (should include ingress-nginx) - repositoryConfigFile, _ := os.CreateTemp(t.TempDir(), "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) + repositoryConfigFile := test.RepositoryConfig(t, "") err := RepoAdd(&RepoOptions{ Name: "helm", Url: "https://charts.helm.sh/stable", InsecureSkipTlsVerify: true, - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) if err != nil { t.Errorf("Expected repo add to succeed, got %s", err) @@ -42,7 +42,7 @@ func TestUpgradeFromRepoAndInvalidVersion(t *testing.T) { Name: "ingress-nginx", Version: "9999.9999.9999", ClientOnly: true, - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) // Then if err == nil { diff --git a/native/internal/test/env.go b/native/internal/test/env.go index a0193cf1..4073ec7a 100644 --- a/native/internal/test/env.go +++ b/native/internal/test/env.go @@ -85,14 +85,17 @@ func SetupIsolatedEnv() (EnvCleanup, error) { _ = os.MkdirAll(dockerConfigHome, 0755) _ = os.MkdirAll(gnupgHome, 0700) - // Create a minimal Docker config to avoid GPG credential helper - dockerConfigFile := filepath.Join(dockerConfigHome, "config.json") - dockerConfig := `{ - "auths": {}, - "credHelpers": {}, - "credsStore": "" + // Seed the Docker and Helm registry configs with a placeholder entry. With no entry (an empty "auths" or + // "credsStore" is not enough), Helm's registry client (oras-go DetectDefaultNativeStore) picks the platform's + // credential helper (osxkeychain, wincred, pass, secretservice) if found in PATH, and stores logins there. + registryConfig := `{ + "auths": { + "helm-java.invalid": {} + } }` - _ = os.WriteFile(dockerConfigFile, []byte(dockerConfig), 0644) + _ = os.WriteFile(filepath.Join(dockerConfigHome, "config.json"), []byte(registryConfig), 0644) + _ = os.MkdirAll(filepath.Join(helmConfigHome, "registry"), 0755) + _ = os.WriteFile(filepath.Join(helmConfigHome, "registry", "config.json"), []byte(registryConfig), 0644) // Clear all Helm-related environment variables for _, envVar := range helmEnvVars { @@ -105,7 +108,8 @@ func SetupIsolatedEnv() (EnvCleanup, error) { _ = os.Setenv("HELM_DATA_HOME", helmDataHome) _ = os.Setenv("DOCKER_CONFIG", dockerConfigHome) _ = os.Setenv("GNUPGHOME", gnupgHome) - // Set minimal PATH to avoid credential helper binaries + // Minimal PATH. It still includes /usr/local/bin (where e.g. docker-credential-osxkeychain lives), so it's the + // seeded registry configs above, not the PATH, that prevent the native credential store detection _ = os.Setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") // Note: We don't set HELM_DRIVER, leaving it to use the default driver diff --git a/native/internal/test/repository.go b/native/internal/test/repository.go new file mode 100644 index 00000000..c1511e1d --- /dev/null +++ b/native/internal/test/repository.go @@ -0,0 +1,37 @@ +/* + * 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 test + +import ( + "os" + "path/filepath" + "testing" +) + +// RepositoryConfig returns the path of a repositories.yaml file in a directory that is removed when the test +// ends, together with the lock file that repository commands create next to it. +// The file is created with the given content, or not at all if the content is empty (RepoAdd creates it). +func RepositoryConfig(t *testing.T, content string) string { + t.Helper() + repositoryConfig := filepath.Join(t.TempDir(), "repositories.yaml") + if content != "" { + if err := os.WriteFile(repositoryConfig, []byte(content), 0600); err != nil { + t.Fatalf("Error writing %s: %s", repositoryConfig, err) + } + } + return repositoryConfig +} diff --git a/native/main_test.go b/native/main_test.go index 8260e344..f138401e 100644 --- a/native/main_test.go +++ b/native/main_test.go @@ -20,14 +20,12 @@ import ( "net/http" "os" "path" - "path/filepath" "strings" "testing" "time" "github.com/manusa/helm-java/native/internal/helm" "github.com/manusa/helm-java/native/internal/test" - "helm.sh/helm/v3/pkg/repo/repotest" ) // TestMain sets up an isolated environment for tests by clearing Helm-related @@ -37,9 +35,10 @@ func TestMain(m *testing.M) { if err != nil { panic(err) } - defer cleanup() - - os.Exit(m.Run()) + // Not deferred: os.Exit skips deferred calls, which left the isolated directories behind + code := m.Run() + cleanup() + os.Exit(code) } func TestCreate(t *testing.T) { @@ -272,19 +271,18 @@ func TestRegistryLogout(t *testing.T) { } func TestRepoAdd(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) + repositoryConfigFile := test.RepositoryConfig(t, "") err := helm.RepoAdd(&helm.RepoOptions{ Name: "helm", Url: "https://charts.helm.sh/stable", InsecureSkipTlsVerify: true, - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) if err != nil { t.Errorf("Expected repo add to succeed, got %s", err) return } - fileContent, _ := os.ReadFile(repositoryConfigFile.Name()) + fileContent, _ := os.ReadFile(repositoryConfigFile) repositoryConfig := string(fileContent) if !strings.Contains(repositoryConfig, " name: helm\n") { t.Errorf("Expected file to contain 'helm' as name, got %s", repositoryConfig) @@ -295,12 +293,11 @@ func TestRepoAdd(t *testing.T) { } func TestRepoAddInvalidName(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) + repositoryConfigFile := test.RepositoryConfig(t, "") err := helm.RepoAdd(&helm.RepoOptions{ Name: "helm/invalid", Url: "https://charts.helm.sh/stable", - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) if err == nil { t.Error("Expected repo add to fail") @@ -324,12 +321,11 @@ func TestRepoAddInvalidPath(t *testing.T) { } func TestRepoAddInvalidRepo(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) + repositoryConfigFile := test.RepositoryConfig(t, "") err := helm.RepoAdd(&helm.RepoOptions{ Name: "helm", Url: "https://localhost/stable", - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) if err == nil { t.Error("Expected repo add to fail") @@ -341,15 +337,13 @@ func TestRepoAddInvalidRepo(t *testing.T) { } func TestRepoList(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) - _, _ = repositoryConfigFile.WriteString("apiVersion: \"\"\n" + - "repositories:\n" + - " - name: stable\n" + - " url: https://charts.helm.sh/stable\n" + - " - name: other\n" + + repositoryConfigFile := test.RepositoryConfig(t, "apiVersion: \"\"\n"+ + "repositories:\n"+ + " - name: stable\n"+ + " url: https://charts.helm.sh/stable\n"+ + " - name: other\n"+ " url: https://charts.example.com/other\n") - out, err := helm.RepoList(&helm.RepoOptions{RepositoryConfig: repositoryConfigFile.Name()}) + out, err := helm.RepoList(&helm.RepoOptions{RepositoryConfig: repositoryConfigFile}) if err != nil { t.Error("Expected repo list to succeed") } @@ -362,23 +356,21 @@ func TestRepoList(t *testing.T) { } func TestRepoRemove(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) - _, _ = repositoryConfigFile.WriteString("apiVersion: \"\"\n" + - "repositories:\n" + - " - name: stable\n" + - " url: https://charts.helm.sh/stable\n" + - " - name: other\n" + + repositoryConfigFile := test.RepositoryConfig(t, "apiVersion: \"\"\n"+ + "repositories:\n"+ + " - name: stable\n"+ + " url: https://charts.helm.sh/stable\n"+ + " - name: other\n"+ " url: https://charts.example.com/other\n") err := helm.RepoRemove(&helm.RepoOptions{ - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, Names: "stable", }) if err != nil { t.Error("Expected repo remove to succeed") return } - out, _ := helm.RepoList(&helm.RepoOptions{RepositoryConfig: repositoryConfigFile.Name()}) + out, _ := helm.RepoList(&helm.RepoOptions{RepositoryConfig: repositoryConfigFile}) if strings.Contains(out, "name=stable") { t.Errorf("Expected 'stable' repo to be removed, got %s", out) } @@ -388,16 +380,14 @@ func TestRepoRemove(t *testing.T) { } func TestRepoRemoveWithMissing(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) - _, _ = repositoryConfigFile.WriteString("apiVersion: \"\"\n" + - "repositories:\n" + - " - name: stable\n" + - " url: https://charts.helm.sh/stable\n" + - " - name: other\n" + + repositoryConfigFile := test.RepositoryConfig(t, "apiVersion: \"\"\n"+ + "repositories:\n"+ + " - name: stable\n"+ + " url: https://charts.helm.sh/stable\n"+ + " - name: other\n"+ " url: https://charts.example.com/other\n") err := helm.RepoRemove(&helm.RepoOptions{ - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, Names: "missing\nstable", }) if err == nil { @@ -410,14 +400,12 @@ func TestRepoRemoveWithMissing(t *testing.T) { } func TestRepoUpdateAll(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) - _, _ = repositoryConfigFile.WriteString("apiVersion: \"\"\n" + - "repositories:\n" + - " - name: stable\n" + + repositoryConfigFile := test.RepositoryConfig(t, "apiVersion: \"\"\n"+ + "repositories:\n"+ + " - name: stable\n"+ " url: https://charts.helm.sh/stable\n") updated, err := helm.RepoUpdate(&helm.RepoOptions{ - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, }) if err != nil { t.Error("Expected repo update to succeed") @@ -429,16 +417,14 @@ func TestRepoUpdateAll(t *testing.T) { } func TestRepoUpdateByName(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) - _, _ = repositoryConfigFile.WriteString("apiVersion: \"\"\n" + - "repositories:\n" + - " - name: stable\n" + - " url: https://charts.helm.sh/stable\n" + - " - name: other\n" + + repositoryConfigFile := test.RepositoryConfig(t, "apiVersion: \"\"\n"+ + "repositories:\n"+ + " - name: stable\n"+ + " url: https://charts.helm.sh/stable\n"+ + " - name: other\n"+ " url: https://charts.example.com/other\n") updated, err := helm.RepoUpdate(&helm.RepoOptions{ - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, Names: "stable\n", }) if err != nil { @@ -451,16 +437,14 @@ func TestRepoUpdateByName(t *testing.T) { } func TestRepoUpdateByNameWithInvalidRepo(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) - _, _ = repositoryConfigFile.WriteString("apiVersion: \"\"\n" + - "repositories:\n" + - " - name: stable\n" + - " url: https://charts.helm.sh/stable\n" + - " - name: other\n" + + repositoryConfigFile := test.RepositoryConfig(t, "apiVersion: \"\"\n"+ + "repositories:\n"+ + " - name: stable\n"+ + " url: https://charts.helm.sh/stable\n"+ + " - name: other\n"+ " url: https://charts.example.com/other\n") updated, err := helm.RepoUpdate(&helm.RepoOptions{ - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, Names: "other\n", }) if err == nil { @@ -478,16 +462,14 @@ func TestRepoUpdateByNameWithInvalidRepo(t *testing.T) { } func TestRepoUpdateByNameWithInvalidAndValidRepo(t *testing.T) { - repositoryConfigFile, _ := os.CreateTemp("", "repositories.yaml") - defer func(name string) { _ = os.Remove(name) }(repositoryConfigFile.Name()) - _, _ = repositoryConfigFile.WriteString("apiVersion: \"\"\n" + - "repositories:\n" + - " - name: stable\n" + - " url: https://charts.helm.sh/stable\n" + - " - name: other\n" + + repositoryConfigFile := test.RepositoryConfig(t, "apiVersion: \"\"\n"+ + "repositories:\n"+ + " - name: stable\n"+ + " url: https://charts.helm.sh/stable\n"+ + " - name: other\n"+ " url: https://charts.example.com/other\n") updated, err := helm.RepoUpdate(&helm.RepoOptions{ - RepositoryConfig: repositoryConfigFile.Name(), + RepositoryConfig: repositoryConfigFile, Names: "other\nstable\n", }) if err == nil { @@ -504,88 +486,117 @@ func TestRepoUpdateByNameWithInvalidAndValidRepo(t *testing.T) { } } -func repoServerStartAsync(t *testing.T, serverInfoChannel chan *repotest.Server, stopChannel chan bool) { - srv, err := helm.RepoServerStart(&helm.RepoServerOptions{}) +// testHttpClient bounds every request to the test servers; keep-alives are disabled so that a request +// after a server is stopped opens a new connection instead of reusing a pooled one +var testHttpClient = &http.Client{ + Timeout: 10 * time.Second, + Transport: &http.Transport{DisableKeepAlives: true}, +} + +// statusCode performs a GET request and returns the response status code +func statusCode(url string) (int, error) { + resp, err := testHttpClient.Get(url) if err != nil { - t.Errorf("Expected server to be started") + return 0, err } - serverInfoChannel <- srv + _ = resp.Body.Close() + return resp.StatusCode, nil +} + +// waitForOciServer waits (bounded) until the test OCI server, which starts serving in a goroutine, responds +func waitForOciServer(t *testing.T, registryURL string) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) for { - select { - case <-stopChannel: - helm.RepoServerStop(srv.URL()) + _, err := statusCode("http://" + registryURL + "/v2/") + if err == nil { return - default: - time.Sleep(10 * time.Millisecond) } + if time.Now().After(deadline) { + t.Fatalf("Expected OCI server to be started, got %s", err) + } + time.Sleep(50 * time.Millisecond) } } func TestRepoServerStart(t *testing.T) { defer helm.RepoServerStopAll() - serverInfoChannel := make(chan *repotest.Server) - stopChannel := make(chan bool) - defer func() { stopChannel <- true }() - go repoServerStartAsync(t, serverInfoChannel, stopChannel) - time.Sleep(100 * time.Millisecond) - serverInfo := <-serverInfoChannel - resp, err := http.Get(serverInfo.URL()) + srv, err := helm.RepoServerStart(&helm.RepoServerOptions{}) if err != nil { - t.Errorf("Expected server to be started") + t.Fatalf("Expected server to be started, got %s", err) + } + code, err := statusCode(srv.URL()) + if err != nil { + t.Fatalf("Expected server to be started, got %s", err) } - if resp.StatusCode != 200 { - t.Errorf("Expected server to return 200, got %d", resp.StatusCode) + if code != 200 { + t.Errorf("Expected server to return 200, got %d", code) } } func TestRepoServerStartMultipleInstances(t *testing.T) { defer helm.RepoServerStopAll() - serverInfoChannel := make(chan *repotest.Server) - stopChannel := make(chan bool) - defer func() { stopChannel <- true }() - defer helm.RepoServerStopAll() - go repoServerStartAsync(t, serverInfoChannel, stopChannel) - srv1 := <-serverInfoChannel - go repoServerStartAsync(t, serverInfoChannel, stopChannel) - time.Sleep(100 * time.Millisecond) // ensure servers are started and continue to run - srv2 := <-serverInfoChannel - resp1, err1 := http.Get(srv1.URL()) - resp2, err2 := http.Get(srv2.URL()) + srv1, err1 := helm.RepoServerStart(&helm.RepoServerOptions{}) + srv2, err2 := helm.RepoServerStart(&helm.RepoServerOptions{}) + if err1 != nil || err2 != nil { + t.Fatalf("Expected all servers to be started, got %v and %v", err1, err2) + } + code1, err1 := statusCode(srv1.URL()) + code2, err2 := statusCode(srv2.URL()) if err1 != nil || err2 != nil { - t.Errorf("Expected all servers to be started") + t.Fatalf("Expected all servers to be started, got %v and %v", err1, err2) } - if resp1.StatusCode != 200 || resp2.StatusCode != 200 { - t.Errorf("Expected all server to return 200, got %d and %d", resp1.StatusCode, resp2.StatusCode) + if code1 != 200 || code2 != 200 { + t.Errorf("Expected all server to return 200, got %d and %d", code1, code2) } } func TestRepoServerStop(t *testing.T) { - serverInfoChannel := make(chan *repotest.Server) - stopChannel := make(chan bool) - defer func() { stopChannel <- true }() - go repoServerStartAsync(t, serverInfoChannel, stopChannel) - time.Sleep(100 * time.Millisecond) - serverInfo := <-serverInfoChannel - helm.RepoServerStop(serverInfo.URL()) - _, err := http.Get(serverInfo.URL()) - if err == nil { + defer helm.RepoServerStopAll() + srv, err := helm.RepoServerStart(&helm.RepoServerOptions{}) + if err != nil { + t.Fatalf("Expected server to be started, got %s", err) + } + helm.RepoServerStop(srv.URL()) + if _, err := statusCode(srv.URL()); err == nil { t.Errorf("Expected server to be stopped") } } +func TestRepoServerStopWithOciServer(t *testing.T) { + defer helm.RepoServerStopAll() + srv, err := helm.RepoOciServerStart(&helm.RepoServerOptions{}) + if err != nil { + t.Fatalf("Expected OCI server to be started, got %s", err) + } + waitForOciServer(t, srv.RegistryURL) + helm.RepoServerStop(srv.RegistryURL) + if _, err := statusCode("http://" + srv.RegistryURL + "/v2/"); err == nil { + t.Errorf("Expected OCI server to be stopped") + } + if _, err := os.Stat(srv.Dir); !os.IsNotExist(err) { + t.Errorf("Expected OCI server directory %s to be removed, got %v", srv.Dir, err) + } +} + func TestRepoServerStopAll(t *testing.T) { - srv1, _ := helm.RepoServerStart(&helm.RepoServerOptions{}) - srv2, _ := helm.RepoServerStart(&helm.RepoServerOptions{}) + defer helm.RepoServerStopAll() // in case the test fails before stopping them + srv1, err1 := helm.RepoServerStart(&helm.RepoServerOptions{}) + srv2, err2 := helm.RepoOciServerStart(&helm.RepoServerOptions{}) + if err1 != nil || err2 != nil { + t.Fatalf("Expected all servers to be started, got %v and %v", err1, err2) + } + waitForOciServer(t, srv2.RegistryURL) helm.RepoServerStopAll() - _, err := http.Get(srv1.URL()) - _, err2 := http.Get(srv2.URL()) - if err == nil || err2 == nil { + _, err1 = statusCode(srv1.URL()) + _, err2 = statusCode("http://" + srv2.RegistryURL + "/v2/") + if err1 == nil || err2 == nil { t.Errorf("Expected all servers to be stopped") } } func TestSearchRepo(t *testing.T) { - repositoryConfig := filepath.Join(t.TempDir(), "repositories.yaml") + repositoryConfig := test.RepositoryConfig(t, "") err := helm.RepoAdd(&helm.RepoOptions{ Name: "helm", Url: "https://charts.helm.sh/stable", diff --git a/pom.xml b/pom.xml index 83d4bfab..adc3beef 100644 --- a/pom.xml +++ b/pom.xml @@ -63,6 +63,7 @@ 3.6.0 3.12.0 3.3.1 + 3.5.0 3.4.0 From c4c06dc20ed3c026ddde65b079c05aabad82c335 Mon Sep 17 00:00:00 2001 From: Marc Nuri Date: Sun, 22 Nov 2026 06:21:38 +0100 Subject: [PATCH 2/3] fix: reject truncated chunked JAR downloads, complete test isolation Follow-ups from the review of the test isolation change: - RemoteJarLoader opens the downloaded .part file as a ZIP before moving it into place, so a truncated chunked or close-delimited response (no Content-Length) is no longer cached as complete - RemoteJarLoaderTest covers that, the cache-hit path, and keeping the cached JAR with forceUpdate when the download fails - the excluded HELM_* variables (Surefire and the Go TestMain) are every one Helm reads that redirects files or changes behavior, and the two lists match - the registry config seeds are test resources, so IDE runs on a clean target/ get them too (no extra Maven execution) - SetupIsolatedEnv fails when it can't write the seeds Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Nuri --- AGENTS.md | 8 +- helm-java/pom.xml | 51 ++++----- .../helm-home/config/registry/config.json | 0 .../helm-home/docker/config.json | 0 .../marcnuri/helm/jni/RemoteJarLoader.java | 11 +- .../helm/jni/RemoteJarLoaderTest.java | 103 +++++++++++++++++- native/internal/test/env.go | 30 ++++- pom.xml | 1 - 8 files changed, 162 insertions(+), 42 deletions(-) rename helm-java/src/test/{ => resources}/helm-home/config/registry/config.json (100%) rename helm-java/src/test/{ => resources}/helm-home/docker/config.json (100%) diff --git a/AGENTS.md b/AGENTS.md index d4cb0f56..4a352ce9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -146,10 +146,10 @@ Verbs with both forms: `install`, `template`, `show`, `upgrade`. Most others are - k8s integration: `HelmKubernetesTest` spins up KinD via Testcontainers in `@BeforeAll`; clean releases in `@AfterEach`. - Surefire sets `KUBECONFIG=/dev/null` in `helm-java/pom.xml` so tests cannot accidentally hit your local cluster — pass `kubeConfigFile`/`kubeConfigContents` explicitly. - Surefire also isolates the tests from your Helm and Docker config: - - `HELM_CACHE_HOME`, `HELM_CONFIG_HOME`, `HELM_DATA_HOME` and `DOCKER_CONFIG` point at `helm-java/target/helm-home/`. - - The other `HELM_*` variables from your environment that redirect Helm's files or change its behavior (`HELM_REPOSITORY_CACHE`, `HELM_REPOSITORY_CONFIG`, `HELM_NAMESPACE`, …) are not passed to the tests. `HELM_REGISTRY_CONFIG` is excluded too, defensively: the native registry client doesn't read it. - - Maven's `process-test-resources` phase seeds the registry configs there from `helm-java/src/test/helm-home/` with a placeholder entry, so registry logins go to that file and not to an OS credential store (Keychain, Credential Manager, `pass`, Secret Service). A test run from an IDE on a freshly cleaned `target/`, without that Maven phase, has no seed. - - Trade-off: Testcontainers reads `DOCKER_CONFIG` too, so the KinD image pulls in `HelmKubernetesTest` are anonymous (Docker Hub rate limits apply; an authenticated mirror won't be used). + - `HELM_CACHE_HOME` and `HELM_DATA_HOME` point at `helm-java/target/helm-home/`; `HELM_CONFIG_HOME` and `DOCKER_CONFIG` at `helm-java/target/test-classes/helm-home/`. + - Every other `HELM_*` variable Helm reads that redirects its files or changes its behavior (`HELM_REPOSITORY_CACHE`, `HELM_NAMESPACE`, `HELM_KUBEASUSER`, …) is not passed to the tests. The list in `helm-java/pom.xml` matches the one in `native/internal/test/env.go`; keep both in sync with the variables Helm reads: those in its `pkg/cli/environment.go`, plus `HELM_DRIVER` (read by `native/internal/helm/helm.go`) and `HELM_DRIVER_SQL_CONNECTION_STRING` (Helm's `pkg/action/action.go`). `HELM_REGISTRY_CONFIG` is excluded defensively: the native registry client doesn't read it. + - 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. ```java diff --git a/helm-java/pom.xml b/helm-java/pom.xml index 61b39ff4..2a3501c9 100644 --- a/helm-java/pom.xml +++ b/helm-java/pom.xml @@ -17,7 +17,7 @@ requireFilesExist - + ${project.build.directory}/helm-home @@ -29,53 +29,42 @@ /dev/null - + ${helm.test.home}/cache - ${helm.test.home}/config + ${project.build.testOutputDirectory}/helm-home/config ${helm.test.home}/data - ${helm.test.home}/docker + ${project.build.testOutputDirectory}/helm-home/docker - + + HELM_BURST_LIMIT HELM_DEBUG HELM_DRIVER + HELM_DRIVER_SQL_CONNECTION_STRING HELM_KUBEAPISERVER + HELM_KUBEASGROUPS + HELM_KUBEASUSER + HELM_KUBECAFILE HELM_KUBECONTEXT + HELM_KUBEINSECURE_SKIP_TLS_VERIFY + HELM_KUBETLS_SERVER_NAME HELM_KUBETOKEN + HELM_MAX_HISTORY HELM_NAMESPACE HELM_PLUGINS + HELM_QPS HELM_REGISTRY_CONFIG HELM_REPOSITORY_CACHE HELM_REPOSITORY_CONFIG - - - org.apache.maven.plugins - maven-resources-plugin - ${version.maven-resources-plugin} - - - seed-helm-test-home - process-test-resources - - copy-resources - - - ${helm.test.home} - true - - - src/test/helm-home - - - - - - diff --git a/helm-java/src/test/helm-home/config/registry/config.json b/helm-java/src/test/resources/helm-home/config/registry/config.json similarity index 100% rename from helm-java/src/test/helm-home/config/registry/config.json rename to helm-java/src/test/resources/helm-home/config/registry/config.json diff --git a/helm-java/src/test/helm-home/docker/config.json b/helm-java/src/test/resources/helm-home/docker/config.json similarity index 100% rename from helm-java/src/test/helm-home/docker/config.json rename to helm-java/src/test/resources/helm-home/docker/config.json 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 305cdf5a..b571b360 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 @@ -40,6 +40,8 @@ import java.nio.file.StandardCopyOption; import java.util.Properties; import java.util.UUID; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; /** * @author Marc Nuri @@ -136,12 +138,19 @@ static URL cache(URL jarUrl, Path jarFile, int connectTimeoutMillis, int readTim FileChannel outChannel = fos.getChannel() ) { downloaded = outChannel.transferFrom(inChannel, 0, Long.MAX_VALUE); - // A connection dropped mid-body reads as a normal end of stream + // 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"); } } + // 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); throw exception; 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 61b40ad4..20c5269a 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 @@ -33,11 +33,14 @@ import java.net.SocketTimeoutException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -49,9 +52,13 @@ @Timeout(value = 30, unit = TimeUnit.SECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) class RemoteJarLoaderTest { + private static final String FORCE_UPDATE = "com.marcnuri.jkube-helm.forceUpdate"; + @TempDir private Path tempDir; + private byte[] jar; + private CountDownLatch release; private ExecutorService executor; private HttpServer server; @@ -59,6 +66,7 @@ class RemoteJarLoaderTest { @BeforeEach void setUp() throws IOException { release = new CountDownLatch(1); + jar = jar(); executor = Executors.newCachedThreadPool(); server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); server.setExecutor(executor); @@ -69,6 +77,20 @@ void setUp() throws IOException { 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("/truncated", exchange -> { // Declares more bytes than it sends, then drops the connection exchange.sendResponseHeaders(200, 1024); @@ -121,11 +143,31 @@ class Cache { @Test void downloadsToTarget() throws IOException { final Path jarFile = tempDir.resolve("the.jar"); - assertThat(RemoteJarLoader.cache(url("/responds"), jarFile)).isEqualTo(jarFile.toUri().toURL()); - assertThat(jarFile).hasContent("the-content"); + assertThat(RemoteJarLoader.cache(url("/jar"), jarFile)).isEqualTo(jarFile.toUri().toURL()); + assertThat(jarFile).hasBinaryContent(jar); assertThat(tempDir).isDirectoryNotContaining("glob:**.part"); } + @Test + void notAJarLeavesNoFile() throws IOException { + final Path jarFile = tempDir.resolve("the.jar"); + final URL url = url("/responds"); + assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) + .isInstanceOf(IOException.class) + .hasMessageEndingWith(": truncated or not a valid ZIP"); + assertThat(tempDir).isEmptyDirectory(); + } + + @Test + void truncatedChunkedDownloadLeavesNoFile() throws IOException { + final Path jarFile = tempDir.resolve("the.jar"); + final URL url = url("/jar-truncated-chunked"); + assertThatThrownBy(() -> RemoteJarLoader.cache(url, jarFile)) + .isInstanceOf(IOException.class) + .hasMessageEndingWith(": truncated or not a valid ZIP"); + assertThat(tempDir).isEmptyDirectory(); + } + @Test void truncatedDownloadLeavesNoFile() throws IOException { final Path jarFile = tempDir.resolve("the.jar"); @@ -143,6 +185,53 @@ void unresponsiveServerTimesOutAndLeavesNoFile() throws IOException { .isInstanceOf(SocketTimeoutException.class); assertThat(tempDir).isEmptyDirectory(); } + + @Test + void usesCachedJarWithoutContactingServer() throws IOException { + final Path jarFile = Files.write(tempDir.resolve("the.jar"), "cached".getBytes(StandardCharsets.UTF_8)); + 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"); + } + + @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 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 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"); + } + } } @Nested @@ -160,6 +249,16 @@ void readTimeoutIsBounded() { } } + private static byte[] jar() throws IOException { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(out)) { + zip.putNextEntry(new ZipEntry("META-INF/services/com.marcnuri.helm.jni.NativeLibrary")); + zip.write("com.example.NativeLibrary\n".getBytes(StandardCharsets.UTF_8)); + zip.closeEntry(); + } + return out.toByteArray(); + } + private URL url(String path) throws IOException { return new URL("http", server.getAddress().getHostString(), server.getAddress().getPort(), path); } diff --git a/native/internal/test/env.go b/native/internal/test/env.go index 4073ec7a..4220bfff 100644 --- a/native/internal/test/env.go +++ b/native/internal/test/env.go @@ -26,12 +26,26 @@ var helmEnvVars = []string{ "HELM_CACHE_HOME", "HELM_CONFIG_HOME", "HELM_DATA_HOME", + // Every other HELM_* variable Helm reads that would redirect its files or change its behavior: those in + // helm.sh/helm/v3 pkg/cli/environment.go, plus HELM_DRIVER (read by internal/helm/helm.go) and + // HELM_DRIVER_SQL_CONNECTION_STRING (pkg/action/action.go); same list as the excludedEnvironmentVariables in + // helm-java/pom.xml + "HELM_BURST_LIMIT", "HELM_DEBUG", "HELM_DRIVER", + "HELM_DRIVER_SQL_CONNECTION_STRING", "HELM_KUBEAPISERVER", + "HELM_KUBEASGROUPS", + "HELM_KUBEASUSER", + "HELM_KUBECAFILE", "HELM_KUBECONTEXT", + "HELM_KUBEINSECURE_SKIP_TLS_VERIFY", + "HELM_KUBETLS_SERVER_NAME", "HELM_KUBETOKEN", + "HELM_MAX_HISTORY", "HELM_NAMESPACE", + "HELM_PLUGINS", + "HELM_QPS", "HELM_REGISTRY_CONFIG", "HELM_REPOSITORY_CACHE", "HELM_REPOSITORY_CONFIG", @@ -93,9 +107,19 @@ func SetupIsolatedEnv() (EnvCleanup, error) { "helm-java.invalid": {} } }` - _ = os.WriteFile(filepath.Join(dockerConfigHome, "config.json"), []byte(registryConfig), 0644) - _ = os.MkdirAll(filepath.Join(helmConfigHome, "registry"), 0755) - _ = os.WriteFile(filepath.Join(helmConfigHome, "registry", "config.json"), []byte(registryConfig), 0644) + // A failed write must fail the tests: they would otherwise silently run with that detection back on + for _, seed := range []string{ + filepath.Join(dockerConfigHome, "config.json"), + filepath.Join(helmConfigHome, "registry", "config.json"), + } { + if err = os.MkdirAll(filepath.Dir(seed), 0755); err == nil { + err = os.WriteFile(seed, []byte(registryConfig), 0644) + } + if err != nil { + _ = os.RemoveAll(tempDir) + return nil, err + } + } // Clear all Helm-related environment variables for _, envVar := range helmEnvVars { diff --git a/pom.xml b/pom.xml index adc3beef..83d4bfab 100644 --- a/pom.xml +++ b/pom.xml @@ -63,7 +63,6 @@ 3.6.0 3.12.0 3.3.1 - 3.5.0 3.4.0 From 9fe35d113c33764dc7d67f8b0dcaab070245d4a1 Mon Sep 17 00:00:00 2001 From: Marc Nuri Date: Sun, 22 Nov 2026 06:37:48 +0100 Subject: [PATCH 3/3] fix(jni): report why the remote native library JAR failed to load RemoteJarLoader swallowed every download and metadata failure, so a timeout, an HTTP 404 or a truncated download all surfaced only as "No NativeLibrary implementation found, please add one of the supported dependencies to your project", with no hint of the cause. - remoteJar() now throws the IOException (XML errors in the snapshot metadata are wrapped with its URL); it still returns null when the remote JAR is disabled or the platform is unknown - NativeLibrary.getInstance() keeps its message and attaches that failure as the cause - RemoteJarLoaderTest covers the release and snapshot lookups and the failures through a package-private remoteJar(...) seam Co-Authored-By: Claude Opus 5.5 Signed-off-by: Marc Nuri --- .../com/marcnuri/helm/NativeLibraryTest.java | 3 +- .../com/marcnuri/helm/jni/NativeLibrary.java | 25 ++++-- .../marcnuri/helm/jni/RemoteJarLoader.java | 90 ++++++++++--------- .../helm/jni/RemoteJarLoaderTest.java | 81 +++++++++++++++++ 4 files changed, 148 insertions(+), 51 deletions(-) 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 7384756c..e77e01d9 100644 --- a/helm-java/src/test/java/com/marcnuri/helm/NativeLibraryTest.java +++ b/helm-java/src/test/java/com/marcnuri/helm/NativeLibraryTest.java @@ -84,7 +84,8 @@ void getInstanceNotAvailable() { Thread.currentThread().setContextClassLoader(new URLClassLoader(new java.net.URL[0], null)); assertThatThrownBy(NativeLibrary::getInstance) .isInstanceOf(IllegalStateException.class) - .hasMessage("No NativeLibrary implementation found, please add one of the supported dependencies to your project"); + .hasMessage("No NativeLibrary implementation found, please add one of the supported dependencies to your project") + .hasNoCause(); } finally { System.clearProperty("com.marcnuri.jkube-helm.skipRemoteJar"); Thread.currentThread().setContextClassLoader(currentClassLoader); diff --git a/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java b/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java index 18fa4ddf..420c2509 100644 --- a/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java +++ b/lib/api/src/main/java/com/marcnuri/helm/jni/NativeLibrary.java @@ -36,17 +36,24 @@ public interface NativeLibrary { static NativeLibrary getInstance() { - NativeLibrary nativeLibrary; - ClassLoader remoteJar; - if ( - // Load from ClassPath (should work on Maven) - (nativeLibrary = serviceProviderLibrary(null)) != null || - // Load from remote JAR (should work on Gradle if not air-gapped) - ((remoteJar = remoteJar()) != null && (nativeLibrary = serviceProviderLibrary(remoteJar)) != null) - ) { + // Load from ClassPath (should work on Maven) + NativeLibrary nativeLibrary = serviceProviderLibrary(null); + if (nativeLibrary != null) { return nativeLibrary; } - throw new IllegalStateException("No NativeLibrary implementation found, please add one of the supported dependencies to your project"); + // Load from remote JAR (should work on Gradle if not air-gapped) + IOException remoteJarFailure = null; + try { + final ClassLoader remoteJar = remoteJar(); + if (remoteJar != null && (nativeLibrary = serviceProviderLibrary(remoteJar)) != null) { + return nativeLibrary; + } + } catch (IOException exception) { + remoteJarFailure = exception; + } + throw new IllegalStateException( + "No NativeLibrary implementation found, please add one of the supported dependencies to your project", + remoteJarFailure); } /** 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 b571b360..61975b72 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 @@ -63,7 +63,13 @@ class RemoteJarLoader { private RemoteJarLoader() { } - static ClassLoader remoteJar() { + /** + * 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. + */ + static ClassLoader remoteJar() throws IOException { // For testing if (System.getProperty(SKIP) != null) { return null; @@ -71,53 +77,55 @@ static ClassLoader remoteJar() { final Properties nativeLibraries = new Properties(); try (final InputStream stream = NativeLibrary.class.getResourceAsStream("/META-INF/native-libraries.properties")) { nativeLibraries.load(stream); - final String version; - // Version can be overridden (for testing) using a system property - if (System.getProperty(VERSION) != null) { - version = System.getProperty(VERSION); - } else { - version = nativeLibraries.getProperty(VERSION); - } - final String groupId = nativeLibraries.getProperty(GROUP_ID); - final boolean isSnapshot = version.endsWith("-SNAPSHOT"); - final String repository = isSnapshot ? - nativeLibraries.getProperty(SNAPSHOTS) : - nativeLibraries.getProperty(RELEASES); - final String osName = Platform.osName(); - final String archName = Platform.archName(); - if (osName != null && archName != null) { - final String groupUrl = repository + "/" + groupId.replace('.', '/') + "/" + osName + "-" + archName + "/" + version; - final String jarName; - if (isSnapshot) { - jarName = latestSnapshot(version, osName, archName, groupUrl); - } else { - jarName = osName + "-" + archName + "-" + version + ".jar"; - } - final URL jarUrl = new URL(groupUrl + "/" + jarName); - final Path jarFile = Paths.get(System.getProperty(TEMP_DIR), jarName); - return new URLClassLoader(new URL[]{cache(jarUrl, jarFile)}, NativeLibrary.class.getClassLoader()); - } - } catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException exception) { - // NO OP } - return null; + final String version; + // Version can be overridden (for testing) using a system property + if (System.getProperty(VERSION) != null) { + version = System.getProperty(VERSION); + } else { + version = nativeLibraries.getProperty(VERSION); + } + final String repository = version.endsWith("-SNAPSHOT") ? + nativeLibraries.getProperty(SNAPSHOTS) : + nativeLibraries.getProperty(RELEASES); + final String osName = Platform.osName(); + final String archName = Platform.archName(); + if (osName == null || archName == null) { + return null; + } + return remoteJar(repository, nativeLibraries.getProperty(GROUP_ID), version, osName, archName, + Paths.get(System.getProperty(TEMP_DIR))); + } + + static ClassLoader remoteJar(String repository, String groupId, String version, String osName, String archName, + Path cacheDirectory) throws IOException { + final String groupUrl = repository + "/" + groupId.replace('.', '/') + "/" + osName + "-" + archName + "/" + version; + final String jarName; + if (version.endsWith("-SNAPSHOT")) { + jarName = latestSnapshot(version, osName, archName, groupUrl); + } else { + jarName = osName + "-" + archName + "-" + version + ".jar"; + } + final URL jarUrl = new URL(groupUrl + "/" + jarName); + return new URLClassLoader(new URL[]{cache(jarUrl, cacheDirectory.resolve(jarName))}, NativeLibrary.class.getClassLoader()); } private static String latestSnapshot(String version, String osName, String archName, String groupUrl) - throws IOException, ParserConfigurationException, SAXException, XPathExpressionException { + throws IOException { final String metadataXml = groupUrl + "/maven-metadata.xml"; - 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; try (InputStream stream = openStream(new URL(metadataXml), CONNECT_TIMEOUT_MILLIS, READ_TIMEOUT_MILLIS)) { - xml = factory.newDocumentBuilder().parse(stream, metadataXml); + 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 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"; + } catch (ParserConfigurationException | SAXException | XPathExpressionException exception) { + throw new IOException("Unable to read " + metadataXml, exception); } - 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"; } static URL cache(URL jarUrl, Path jarFile) throws IOException { 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 20c5269a..34c4535f 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 @@ -23,8 +23,10 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; +import org.xml.sax.SAXException; import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -32,6 +34,7 @@ import java.net.InetSocketAddress; import java.net.SocketTimeoutException; import java.net.URL; +import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -91,6 +94,34 @@ void setUp() throws IOException { 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); + } + }); server.createContext("/truncated", exchange -> { // Declares more bytes than it sends, then drops the connection exchange.sendResponseHeaders(200, 1024); @@ -234,6 +265,56 @@ void keepsCachedJarWhenDownloadFails() throws IOException { } } + @Nested + class RemoteJar { + + @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); + } + } + + @Test + 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); + } + } + + @Test + 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"); + assertThat(tempDir).isEmptyDirectory(); + } + + @Test + void missingSnapshotMetadataThrowsWithUrl() { + assertThatThrownBy(() -> RemoteJarLoader.remoteJar( + url("/repo").toString(), "com.example", "2.0-SNAPSHOT", "linux", "amd64", tempDir)) + .isInstanceOf(FileNotFoundException.class) + .hasMessageEndingWith("/repo/com/example/linux-amd64/2.0-SNAPSHOT/maven-metadata.xml"); + } + + @Test + void invalidSnapshotMetadataThrowsWithUrl() { + 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); + } + } + @Nested class Timeouts {