diff --git a/AGENTS.md b/AGENTS.md index 6bfcaf28..4a352ce9 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` 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 class HelmFeatureTest { diff --git a/helm-java/pom.xml b/helm-java/pom.xml index 17129c3a..2a3501c9 100644 --- a/helm-java/pom.xml +++ b/helm-java/pom.xml @@ -17,6 +17,8 @@ requireFilesExist + + ${project.build.directory}/helm-home @@ -27,7 +29,40 @@ /dev/null + + ${helm.test.home}/cache + ${project.build.testOutputDirectory}/helm-home/config + ${helm.test.home}/data + ${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 + 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/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/helm-java/src/test/resources/helm-home/config/registry/config.json b/helm-java/src/test/resources/helm-home/config/registry/config.json new file mode 100644 index 00000000..99a7a28b --- /dev/null +++ b/helm-java/src/test/resources/helm-home/config/registry/config.json @@ -0,0 +1,5 @@ +{ + "auths": { + "helm-java.invalid": {} + } +} diff --git a/helm-java/src/test/resources/helm-home/docker/config.json b/helm-java/src/test/resources/helm-home/docker/config.json new file mode 100644 index 00000000..99a7a28b --- /dev/null +++ b/helm-java/src/test/resources/helm-home/docker/config.json @@ -0,0 +1,5 @@ +{ + "auths": { + "helm-java.invalid": {} + } +} 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 513ecaf0..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 @@ -29,13 +29,19 @@ 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; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; /** * @author Marc Nuri @@ -50,11 +56,20 @@ 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() { } - 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; @@ -62,63 +77,136 @@ 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 = factory.newDocumentBuilder().parse(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"; + 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 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); + } } - 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. 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; + } + 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..34c4535f --- /dev/null +++ b/lib/api/src/test/java/com/marcnuri/helm/jni/RemoteJarLoaderTest.java @@ -0,0 +1,356 @@ +/* + * 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 org.xml.sax.SAXException; + +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +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.net.URLClassLoader; +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; + +/** + * @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 { + + 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; + + @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); + 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); + } + }); + 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("/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"); + 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(); + } + + @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 + 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 { + + // 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 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); + } + + 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..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", @@ -85,14 +99,27 @@ 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) + // 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 { @@ -105,7 +132,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",