This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 60f5651b1f0a CAMEL-26914: camel-jbang - fix GitHub error swallowing, 
add timeouts, bound body reads and self-update process (#29804)
60f5651b1f0a is described below

commit 60f5651b1f0a04bf5aeff4549f50d0d7a618bcb5
Author: Guillaume Nodet <[email protected]>
AuthorDate: Sat Nov 14 07:46:16 2026 +0100

    CAMEL-26914: camel-jbang - fix GitHub error swallowing, add timeouts, bound 
body reads and self-update process (#29804)
    
    Fixes four outbound network bugs in camel-jbang; CAMEL-26914 stays open for 
the remaining sites.
    
    - GitHubHelper and GistHelper no longer swallow non-200 responses: a 404 
fails with FileNotFoundException (exit 66), and a 403/429 hints GITHUB_TOKEN 
only when the rate limit is confirmed. GITHUB_TOKEN is sent as a Bearer token 
to api.github.com only.
    - GitHubResource and GistResource exists() use HttpURLConnection with 
connect and read timeouts instead of URL.openStream().
    - The helpers use sendAsync().get(timeout), so a stalled response body is 
bounded too, not only the headers.
    - SelfUpdateCommand waits at most 5 minutes for the installer, drains 
stdout on a daemon thread, kills the descendants on timeout and returns exit 
code 124.
    - CliExecutionExceptionHandler maps a TimeoutException or 
HttpTimeoutException in the cause chain to exit code 124.
    - camel-jbang-tips.adoc documents the GITHUB_TOKEN forwarding.
    
    _This PR was opened by a coding agent on behalf of gnodet._
    
    Co-authored-by: Claude <[email protected]>
---
 .../java/org/apache/camel/github/GistResource.java |   8 +-
 .../org/apache/camel/github/GitHubResource.java    |   8 +-
 .../modules/ROOT/pages/camel-jbang-tips.adoc       |  10 ++
 .../CliExecutionExceptionHandler.java              |  12 +-
 .../CliExecutionExceptionHandlerTest.java          |  64 +++++++++++
 .../camel/dsl/jbang/run/common/GistHelper.java     |  47 +++++++-
 .../camel/dsl/jbang/run/common/GitHubHelper.java   |  47 +++++++-
 .../dsl/jbang/run/common/GitHubHttpHelper.java     |  51 +++++++++
 .../jbang/run/common/GitHubApiResponseTest.java    | 125 ++++++++++++++++++++-
 .../launcher/selfupdate/InstallScriptFetcher.java  |   2 +-
 .../launcher/selfupdate/SelfUpdateCommand.java     |  48 +++++++-
 .../jbang/launcher/SelfUpdateIntegrationTest.java  |  42 +++++++
 12 files changed, 446 insertions(+), 18 deletions(-)

diff --git 
a/components/camel-resourceresolver-github/src/main/java/org/apache/camel/github/GistResource.java
 
b/components/camel-resourceresolver-github/src/main/java/org/apache/camel/github/GistResource.java
index d5b358a2d2db..2d7416956a4b 100644
--- 
a/components/camel-resourceresolver-github/src/main/java/org/apache/camel/github/GistResource.java
+++ 
b/components/camel-resourceresolver-github/src/main/java/org/apache/camel/github/GistResource.java
@@ -19,6 +19,7 @@ package org.apache.camel.github;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.net.HttpURLConnection;
 import java.net.URI;
 import java.net.URL;
 
@@ -41,8 +42,13 @@ public final class GistResource extends ResourceSupport {
         if (!init) {
             try {
                 URL u = URI.create(getLocation()).toURL();
-                try (InputStream is = u.openStream()) {
+                HttpURLConnection conn = (HttpURLConnection) 
u.openConnection();
+                conn.setConnectTimeout(10_000);
+                conn.setReadTimeout(20_000);
+                try (InputStream is = conn.getInputStream()) {
                     cache = 
camelContext.getTypeConverter().tryConvertTo(byte[].class, is);
+                } finally {
+                    conn.disconnect();
                 }
             } catch (Exception e) {
                 // ignore
diff --git 
a/components/camel-resourceresolver-github/src/main/java/org/apache/camel/github/GitHubResource.java
 
b/components/camel-resourceresolver-github/src/main/java/org/apache/camel/github/GitHubResource.java
index b5f4239ba9dc..b9212a9af5e2 100644
--- 
a/components/camel-resourceresolver-github/src/main/java/org/apache/camel/github/GitHubResource.java
+++ 
b/components/camel-resourceresolver-github/src/main/java/org/apache/camel/github/GitHubResource.java
@@ -19,6 +19,7 @@ package org.apache.camel.github;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.net.HttpURLConnection;
 import java.net.URI;
 import java.net.URL;
 
@@ -41,8 +42,13 @@ public final class GitHubResource extends ResourceSupport {
         if (!init) {
             try {
                 URL u = URI.create(getLocation()).toURL();
-                try (InputStream is = u.openStream()) {
+                HttpURLConnection conn = (HttpURLConnection) 
u.openConnection();
+                conn.setConnectTimeout(10_000);
+                conn.setReadTimeout(20_000);
+                try (InputStream is = conn.getInputStream()) {
                     cache = 
camelContext.getTypeConverter().tryConvertTo(byte[].class, is);
+                } finally {
+                    conn.disconnect();
                 }
             } catch (Exception e) {
                 // ignore
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-tips.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-jbang-tips.adoc
index 963c2a27423b..32294448ebe6 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-tips.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-tips.adoc
@@ -126,6 +126,16 @@ Wildcards work too:
 camel run 
https://github.com/apache/camel-kamelets-examples/tree/main/jbang/languages/rou*
 ----
 
+If you hit a GitHub rate limit on directory or wildcard URLs, set a 
`GITHUB_TOKEN` environment variable
+before running the command.
+The token is forwarded as an `Authorization: Bearer` header only to 
`api.github.com` (the directory-listing API) — it is never sent to other hosts:
+
+[source,bash]
+----
+export GITHUB_TOKEN=ghp_...
+camel run https://github.com/myorg/my-org-examples/tree/main/jbang/hello-java
+----
+
 === Run from GitHub gists
 
 Gists are a quick way to share small Camel routes:
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/exceptionhandler/CliExecutionExceptionHandler.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/exceptionhandler/CliExecutionExceptionHandler.java
index 13cfffad2c59..d454bca17592 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/exceptionhandler/CliExecutionExceptionHandler.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/exceptionhandler/CliExecutionExceptionHandler.java
@@ -19,7 +19,9 @@ package 
org.apache.camel.dsl.jbang.core.commands.exceptionhandler;
 import java.io.FileNotFoundException;
 import java.io.PrintWriter;
 import java.io.StringWriter;
+import java.net.http.HttpTimeoutException;
 import java.nio.file.NoSuchFileException;
+import java.util.concurrent.TimeoutException;
 
 import org.aesh.command.parser.CommandLineParserException;
 import org.aesh.command.validator.OptionValidatorException;
@@ -39,9 +41,10 @@ import org.apache.camel.main.download.DownloadException;
  * A {@link CliException} prints its message as one {@code ERROR:} line, and 
exits with its code. A file that does not
  * exist exits with {@link CliExitCode#FILE_NOT_FOUND}. A dependency that 
cannot be downloaded (a
  * {@link DownloadException}) prints its message as one {@code ERROR:} line, 
and exits with {@link CliExitCode#FAILURE}.
- * Any other exception is unexpected: it prints the error with the stack 
trace, and exits with
- * {@link CliExitCode#INTERNAL}. With {@code --verbose} or the environment 
variable {@code CAMEL_CLI_DEBUG=true}, every
- * error prints its stack trace.
+ * A network timeout ({@link TimeoutException} or {@link HttpTimeoutException} 
anywhere in the cause chain) exits with
+ * {@link CliExitCode#TIMEOUT}. Any other exception is unexpected: it prints 
the error with the stack trace, and exits
+ * with {@link CliExitCode#INTERNAL}. With {@code --verbose} or the 
environment variable {@code CAMEL_CLI_DEBUG=true},
+ * every error prints its stack trace.
  * <p/>
  * A command in JSON mode ({@code --json}) also prints the error as a JSON 
document on stdout, see {@link JsonOutput}.
  */
@@ -95,6 +98,9 @@ public class CliExecutionExceptionHandler {
             // such as a dependency that does not exist, or a Maven repository 
that cannot be reached
             return CliExitCode.FAILURE;
         }
+        if (find(ex, TimeoutException.class) != null || find(ex, 
HttpTimeoutException.class) != null) {
+            return CliExitCode.TIMEOUT;
+        }
         return CliExitCode.INTERNAL;
     }
 
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/exceptionhandler/CliExecutionExceptionHandlerTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/exceptionhandler/CliExecutionExceptionHandlerTest.java
new file mode 100644
index 000000000000..cb0e71eec6e0
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/exceptionhandler/CliExecutionExceptionHandlerTest.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.core.commands.exceptionhandler;
+
+import java.io.IOException;
+import java.net.http.HttpTimeoutException;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class CliExecutionExceptionHandlerTest {
+
+    private final CliExecutionExceptionHandler handler = new 
CliExecutionExceptionHandler(new CamelJBangMain());
+
+    @Test
+    void timeoutExceptionIsExit124() {
+        assertThat(handler.getExitCode(new TimeoutException("timed out")))
+                .isEqualTo(CliExitCode.TIMEOUT);
+    }
+
+    @Test
+    void timeoutExceptionWrappedInIoExceptionIsExit124() {
+        IOException wrapped = new IOException("GitHub API request timed out", 
new TimeoutException("timed out"));
+        assertThat(handler.getExitCode(wrapped))
+                .isEqualTo(CliExitCode.TIMEOUT);
+    }
+
+    @Test
+    void httpTimeoutExceptionIsExit124() {
+        assertThat(handler.getExitCode(new HttpTimeoutException("connect timed 
out")))
+                .isEqualTo(CliExitCode.TIMEOUT);
+    }
+
+    @Test
+    void httpTimeoutExceptionWrappedInIoExceptionIsExit124() {
+        IOException wrapped = new IOException("request failed", new 
HttpTimeoutException("read timed out"));
+        assertThat(handler.getExitCode(wrapped))
+                .isEqualTo(CliExitCode.TIMEOUT);
+    }
+
+    @Test
+    void genericIoExceptionIsInternal() {
+        assertThat(handler.getExitCode(new IOException("unexpected error")))
+                .isEqualTo(CliExitCode.INTERNAL);
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GistHelper.java
 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GistHelper.java
index d320f657cbb3..040422ce036c 100644
--- 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GistHelper.java
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GistHelper.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.dsl.jbang.run.common;
 
+import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.net.ProxySelector;
 import java.net.URI;
 import java.net.http.HttpClient;
@@ -23,6 +25,9 @@ import java.net.http.HttpRequest;
 import java.net.http.HttpResponse;
 import java.time.Duration;
 import java.util.StringJoiner;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 
 import org.apache.camel.util.FileUtil;
 import tools.jackson.databind.JsonNode;
@@ -83,11 +88,43 @@ public final class GistHelper {
     static void resolveGistAsRawFiles(
             String url, StringJoiner routes, StringJoiner kamelets, 
StringJoiner properties, StringJoiner all)
             throws Exception {
+        resolveGistAsRawFiles(url, routes, kamelets, properties, all, 
Duration.ofSeconds(20));
+    }
+
+    /**
+     * Package-private overload accepting a custom timeout for testing.
+     */
+    static void resolveGistAsRawFiles(
+            String url, StringJoiner routes, StringJoiner kamelets, 
StringJoiner properties, StringJoiner all,
+            Duration timeout)
+            throws Exception {
 
         // use JDK http client to call github api
         HttpClient hc = 
HttpClient.newBuilder().proxy(ProxySelector.getDefault()).build();
-        HttpResponse<String> res = hc.send(HttpRequest.newBuilder(new 
URI(url)).timeout(Duration.ofSeconds(20)).build(),
-                HttpResponse.BodyHandlers.ofString());
+        URI uri = new URI(url);
+        HttpRequest.Builder reqBuilder = 
HttpRequest.newBuilder(uri).timeout(timeout);
+        // Send GITHUB_TOKEN as Authorization header when set, but only to 
api.github.com (never leak to other hosts)
+        String token = System.getenv("GITHUB_TOKEN");
+        if (token != null && !token.isBlank() && 
"api.github.com".equals(uri.getHost())) {
+            reqBuilder.header("Authorization", "Bearer " + token);
+        }
+        HttpRequest req = reqBuilder.build();
+        // sendAsync + get(timeout) bounds both headers and body reads; 
HttpRequest.timeout() only covers headers
+        var future = hc.sendAsync(req, HttpResponse.BodyHandlers.ofString());
+        HttpResponse<String> res;
+        try {
+            res = future.get(timeout.toSeconds(), TimeUnit.SECONDS);
+        } catch (TimeoutException e) {
+            future.cancel(true);
+            throw new IOException(
+                    "GitHub Gist API request timed out after " + 
timeout.toSeconds() + " seconds for URL: " + url, e);
+        } catch (ExecutionException e) {
+            Throwable cause = e.getCause();
+            if (cause instanceof IOException ioe) {
+                throw ioe;
+            }
+            throw new IOException("GitHub Gist API request failed for URL: " + 
url, cause);
+        }
 
         if (res.statusCode() == 200) {
             ObjectMapper mapper = 
JsonMapper.builderWithJackson2Defaults().build();
@@ -115,6 +152,12 @@ public final class GistHelper {
                     all.add(u);
                 }
             }
+        } else if (res.statusCode() == 404) {
+            throw new FileNotFoundException("GitHub Gist API request failed 
with HTTP 404 for URL: " + url);
+        } else {
+            String hint = GitHubHttpHelper.rateLimitHint(res, token);
+            throw new IOException(
+                    "GitHub Gist API request failed with HTTP " + 
res.statusCode() + hint + " for URL: " + url);
         }
     }
 
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GitHubHelper.java
 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GitHubHelper.java
index 8969a3ed3333..4824ef539a28 100644
--- 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GitHubHelper.java
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GitHubHelper.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.dsl.jbang.run.common;
 
+import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.net.ProxySelector;
 import java.net.URI;
 import java.net.http.HttpClient;
@@ -24,6 +26,9 @@ import java.net.http.HttpResponse;
 import java.time.Duration;
 import java.util.Locale;
 import java.util.StringJoiner;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 
 import org.apache.camel.util.AntPathMatcher;
 import org.apache.camel.util.FileUtil;
@@ -152,11 +157,43 @@ public final class GitHubHelper {
     static void resolveGithubAsRawFiles(
             String url, String wildcard, StringJoiner routes, StringJoiner 
kamelets, StringJoiner properties, StringJoiner all)
             throws Exception {
+        resolveGithubAsRawFiles(url, wildcard, routes, kamelets, properties, 
all, Duration.ofSeconds(20));
+    }
+
+    /**
+     * Package-private overload accepting a custom timeout for testing.
+     */
+    static void resolveGithubAsRawFiles(
+            String url, String wildcard, StringJoiner routes, StringJoiner 
kamelets, StringJoiner properties, StringJoiner all,
+            Duration timeout)
+            throws Exception {
 
         // use JDK http client to call github api
         HttpClient hc = 
HttpClient.newBuilder().proxy(ProxySelector.getDefault()).build();
-        HttpResponse<String> res = hc.send(HttpRequest.newBuilder(new 
URI(url)).timeout(Duration.ofSeconds(20)).build(),
-                HttpResponse.BodyHandlers.ofString());
+        URI uri = new URI(url);
+        HttpRequest.Builder reqBuilder = 
HttpRequest.newBuilder(uri).timeout(timeout);
+        // Send GITHUB_TOKEN as Authorization header when set, but only to 
api.github.com (never leak to other hosts)
+        String token = System.getenv("GITHUB_TOKEN");
+        if (token != null && !token.isBlank() && 
"api.github.com".equals(uri.getHost())) {
+            reqBuilder.header("Authorization", "Bearer " + token);
+        }
+        HttpRequest req = reqBuilder.build();
+        // sendAsync + get(timeout) bounds both headers and body reads; 
HttpRequest.timeout() only covers headers
+        var future = hc.sendAsync(req, HttpResponse.BodyHandlers.ofString());
+        HttpResponse<String> res;
+        try {
+            res = future.get(timeout.toSeconds(), TimeUnit.SECONDS);
+        } catch (TimeoutException e) {
+            future.cancel(true);
+            throw new IOException(
+                    "GitHub API request timed out after " + 
timeout.toSeconds() + " seconds for URL: " + url, e);
+        } catch (ExecutionException e) {
+            Throwable cause = e.getCause();
+            if (cause instanceof IOException ioe) {
+                throw ioe;
+            }
+            throw new IOException("GitHub API request failed for URL: " + url, 
cause);
+        }
 
         if (res.statusCode() == 200) {
             ObjectMapper mapper = 
JsonMapper.builderWithJackson2Defaults().build();
@@ -187,6 +224,12 @@ public final class GitHubHelper {
                     }
                 }
             }
+        } else if (res.statusCode() == 404) {
+            throw new FileNotFoundException("GitHub API request failed with 
HTTP 404 for URL: " + url);
+        } else {
+            String hint = GitHubHttpHelper.rateLimitHint(res, token);
+            throw new IOException(
+                    "GitHub API request failed with HTTP " + res.statusCode() 
+ hint + " for URL: " + url);
         }
     }
 
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GitHubHttpHelper.java
 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GitHubHttpHelper.java
new file mode 100644
index 000000000000..6681eebedf9d
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/GitHubHttpHelper.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.dsl.jbang.run.common;
+
+import java.net.http.HttpResponse;
+
+/**
+ * Shared HTTP utility methods for GitHub API responses.
+ */
+final class GitHubHttpHelper {
+
+    private GitHubHttpHelper() {
+    }
+
+    /**
+     * Returns a hint string for rate-limit or access-denied errors (403/429).
+     */
+    static String rateLimitHint(HttpResponse<?> res, String token) {
+        int status = res.statusCode();
+        if (status == 429) {
+            // Always a rate-limit response
+            return token != null && !token.isBlank()
+                    ? " (rate limit exceeded)"
+                    : " (rate limit exceeded - set GITHUB_TOKEN to increase 
the limit)";
+        }
+        if (status == 403) {
+            String remaining = 
res.headers().firstValue("x-ratelimit-remaining").orElse(null);
+            if ("0".equals(remaining)) {
+                return token != null && !token.isBlank()
+                        ? " (rate limit exceeded)"
+                        : " (rate limit exceeded - set GITHUB_TOKEN to 
increase the limit)";
+            }
+            return " (access denied - the repository may be private or 
blocked)";
+        }
+        return "";
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/GitHubApiResponseTest.java
 
b/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/GitHubApiResponseTest.java
index 1a1f4b6876d1..4d85c6c9e5e0 100644
--- 
a/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/GitHubApiResponseTest.java
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/GitHubApiResponseTest.java
@@ -16,10 +16,15 @@
  */
 package org.apache.camel.dsl.jbang.run.common;
 
+import java.io.FileNotFoundException;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.net.InetSocketAddress;
 import java.nio.charset.StandardCharsets;
+import java.time.Duration;
 import java.util.StringJoiner;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 import com.sun.net.httpserver.HttpServer;
 import org.junit.jupiter.api.AfterEach;
@@ -40,15 +45,25 @@ class GitHubApiResponseTest {
     private HttpServer server;
     private String url;
     private volatile String response;
+    private volatile int statusCode = 200;
+    private volatile String rateLimitRemaining = null;
 
     @BeforeEach
     void startServer() throws IOException {
         server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
         server.createContext("/", exchange -> {
-            byte[] body = response.getBytes(StandardCharsets.UTF_8);
-            exchange.sendResponseHeaders(200, body.length);
-            exchange.getResponseBody().write(body);
-            exchange.close();
+            if (statusCode != 200) {
+                if (rateLimitRemaining != null) {
+                    exchange.getResponseHeaders().set("x-ratelimit-remaining", 
rateLimitRemaining);
+                }
+                exchange.sendResponseHeaders(statusCode, -1);
+                exchange.close();
+            } else {
+                byte[] body = response.getBytes(StandardCharsets.UTF_8);
+                exchange.sendResponseHeaders(200, body.length);
+                exchange.getResponseBody().write(body);
+                exchange.close();
+            }
         });
         server.start();
         url = "http://localhost:"; + server.getAddress().getPort() + "/";
@@ -94,4 +109,106 @@ class GitHubApiResponseTest {
 
         
assertThat(all).hasToString(GitHubHelper.asGithubSingleUrl("https://github.com/me/repo/blob/main/route.java";));
     }
+
+    @Test
+    void nonOkGithubResponseThrows() {
+        statusCode = 404;
+
+        assertThatThrownBy(() -> GitHubHelper.resolveGithubAsRawFiles(url, 
null, null, null, null, new StringJoiner(",")))
+                .isInstanceOf(FileNotFoundException.class)
+                .hasMessageContaining("404");
+    }
+
+    @Test
+    void accessDeniedGithubResponseThrowsWithHint() {
+        statusCode = 403;
+
+        assertThatThrownBy(() -> GitHubHelper.resolveGithubAsRawFiles(url, 
null, null, null, null, new StringJoiner(",")))
+                .isInstanceOf(IOException.class)
+                .hasMessageContaining("403")
+                .hasMessageContaining("access denied");
+    }
+
+    @Test
+    void rateLimitExhaustedGithubResponseThrowsWithHint() {
+        statusCode = 403;
+        rateLimitRemaining = "0";
+
+        assertThatThrownBy(() -> GitHubHelper.resolveGithubAsRawFiles(url, 
null, null, null, null, new StringJoiner(",")))
+                .isInstanceOf(IOException.class)
+                .hasMessageContaining("403")
+                .hasMessageContaining("rate limit exceeded");
+    }
+
+    @Test
+    void nonOkGistResponseThrows() {
+        statusCode = 404;
+
+        assertThatThrownBy(() -> GistHelper.resolveGistAsRawFiles(url, null, 
null, null, new StringJoiner(",")))
+                .isInstanceOf(FileNotFoundException.class)
+                .hasMessageContaining("404");
+    }
+
+    @Test
+    void stalledBodyGithubResponseTimesOut() throws Exception {
+        CountDownLatch stallLatch = new CountDownLatch(1);
+        HttpServer stallServer = HttpServer.create(new 
InetSocketAddress("localhost", 0), 0);
+        stallServer.createContext("/", exchange -> {
+            // send 200 headers with a declared body length, but never write 
the body
+            exchange.sendResponseHeaders(200, 1024);
+            OutputStream os = exchange.getResponseBody();
+            try {
+                // block until the test releases the latch (or until 
interrupted)
+                stallLatch.await(30, TimeUnit.SECONDS);
+            } catch (InterruptedException ignored) {
+                Thread.currentThread().interrupt();
+            } finally {
+                os.close();
+                exchange.close();
+            }
+        });
+        stallServer.start();
+        String stallUrl = "http://localhost:"; + 
stallServer.getAddress().getPort() + "/";
+        try {
+            Duration shortTimeout = Duration.ofSeconds(2);
+            assertThatThrownBy(() -> GitHubHelper.resolveGithubAsRawFiles(
+                    stallUrl, null, null, null, null, new StringJoiner(","), 
shortTimeout))
+                    .isInstanceOf(IOException.class)
+                    .hasMessageContaining("timed out");
+        } finally {
+            stallLatch.countDown();
+            stallServer.stop(0);
+        }
+    }
+
+    @Test
+    void stalledBodyGistResponseTimesOut() throws Exception {
+        CountDownLatch stallLatch = new CountDownLatch(1);
+        HttpServer stallServer = HttpServer.create(new 
InetSocketAddress("localhost", 0), 0);
+        stallServer.createContext("/", exchange -> {
+            // send 200 headers with a declared body length, but never write 
the body
+            exchange.sendResponseHeaders(200, 1024);
+            OutputStream os = exchange.getResponseBody();
+            try {
+                stallLatch.await(30, TimeUnit.SECONDS);
+            } catch (InterruptedException ignored) {
+                Thread.currentThread().interrupt();
+            } finally {
+                os.close();
+                exchange.close();
+            }
+        });
+        stallServer.start();
+        String stallUrl = "http://localhost:"; + 
stallServer.getAddress().getPort() + "/";
+        try {
+            Duration shortTimeout = Duration.ofSeconds(2);
+            assertThatThrownBy(() -> GistHelper.resolveGistAsRawFiles(
+                    stallUrl, null, null, null, new StringJoiner(","), 
shortTimeout))
+                    .isInstanceOf(IOException.class)
+                    .hasMessageContaining("timed out");
+        } finally {
+            stallLatch.countDown();
+            stallServer.stop(0);
+        }
+    }
 }
diff --git 
a/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/selfupdate/InstallScriptFetcher.java
 
b/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/selfupdate/InstallScriptFetcher.java
index 2e1e66c1bc45..d3fc396bcf0c 100644
--- 
a/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/selfupdate/InstallScriptFetcher.java
+++ 
b/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/selfupdate/InstallScriptFetcher.java
@@ -41,7 +41,7 @@ import org.apache.camel.util.FileUtil;
  * - not part of the existing {@code latest.properties}/{@code 
X.Y.Z.properties} manifest format, which neither script's
  * own strict parser could tolerate being extended with new keys.
  */
-public final class InstallScriptFetcher {
+public class InstallScriptFetcher {
 
     private static final String DEFAULT_INSTALL_BASE_URL = 
"https://camel.apache.org";;
     private static final Duration TIMEOUT = Duration.ofSeconds(30);
diff --git 
a/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/selfupdate/SelfUpdateCommand.java
 
b/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/selfupdate/SelfUpdateCommand.java
index d5abe19e9c3a..71e1cf3b13fc 100644
--- 
a/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/selfupdate/SelfUpdateCommand.java
+++ 
b/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/selfupdate/SelfUpdateCommand.java
@@ -26,6 +26,12 @@ import java.nio.file.attribute.BasicFileAttributes;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 
 import org.aesh.command.CommandDefinition;
 import org.aesh.command.option.Option;
@@ -33,6 +39,7 @@ import org.apache.camel.catalog.CamelCatalog;
 import org.apache.camel.catalog.DefaultCamelCatalog;
 import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
 import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
 import org.apache.camel.dsl.jbang.core.common.InstallDetector;
 import org.apache.camel.dsl.jbang.run.common.VersionHelper;
 import org.apache.camel.util.FileUtil;
@@ -73,6 +80,8 @@ public class SelfUpdateCommand extends CamelCommand {
     private final ManifestFetcher fetcherOverride;
     private final InstallScriptFetcher scriptFetcherOverride;
     private final Map<String, String> installerEnvironmentOverride;
+    // Visible for testing: set to a short duration to avoid a 5-minute wait 
in tests
+    public long processWaitTimeoutSeconds = 5 * 60;
 
     public SelfUpdateCommand(CamelJBangMain main) {
         this(main, null, null, null);
@@ -371,10 +380,41 @@ public class SelfUpdateCommand extends CamelCommand {
             // pin-state file for this run. Set last so it can never be 
dropped by the override block above.
             pb.environment().put("CAMEL_INSTALL_SELF_UPDATE", "true");
             Process process = pb.start();
-            String output = new 
String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
-            int exit = process.waitFor();
-            printer().print(output);
-            return exit;
+            // Drain stdout in a separate thread to prevent the subprocess 
from blocking on a full pipe buffer in
+            // the gap before waitFor() returns. Then wait with a timeout to 
prevent an indefinitely stalled
+            // installer from hanging the CLI.
+            ExecutorService drainer = Executors.newSingleThreadExecutor(r -> {
+                Thread t = new Thread(r, "camel-self-update-drainer");
+                t.setDaemon(true);
+                return t;
+            });
+            Future<String> outputFuture = drainer
+                    .submit(() -> new 
String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8));
+            try {
+                boolean finished = process.waitFor(processWaitTimeoutSeconds, 
TimeUnit.SECONDS);
+                if (!finished) {
+                    // Kill grandchildren first (curl/wget etc.) before the 
shell, so they release the pipe
+                    
process.descendants().forEach(ProcessHandle::destroyForcibly);
+                    process.destroyForcibly();
+                    printer().printErr("installer timed out after " + 
processWaitTimeoutSeconds + " seconds");
+                    return CliExitCode.TIMEOUT;
+                }
+                int exit = process.exitValue();
+                // outputFuture.get() can time out when a grandchild 
(curl/wget) keeps the pipe open after the
+                // shell exits, or fail with an I/O error in the drainer 
thread. Either case is best-effort:
+                // the install already finished (process.exitValue() was 
called above), so treat the drain
+                // failure as non-fatal and print what we have.
+                try {
+                    String output = outputFuture.get(10, TimeUnit.SECONDS);
+                    printer().print(output);
+                } catch (TimeoutException | ExecutionException e) {
+                    // stdout drain timed out or failed — the installer 
already returned exit, so continue
+                    printer().print("installer finished, but its output could 
not be read: " + e.getMessage());
+                }
+                return exit;
+            } finally {
+                drainer.shutdownNow();
+            }
         } catch (SelfUpdateException e) {
             printer().printErr(e.getMessage());
             return 1;
diff --git 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/SelfUpdateIntegrationTest.java
 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/SelfUpdateIntegrationTest.java
index 5b5c7f7f6342..9ae3a33abfeb 100644
--- 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/SelfUpdateIntegrationTest.java
+++ 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/SelfUpdateIntegrationTest.java
@@ -34,6 +34,7 @@ import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManagerFactory;
 
 import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
 import org.apache.camel.dsl.jbang.core.common.CommandTree;
 import org.apache.camel.dsl.jbang.launcher.selfupdate.InstallScriptFetcher;
 import org.apache.camel.dsl.jbang.launcher.selfupdate.ManifestFetcher;
@@ -135,6 +136,47 @@ class SelfUpdateIntegrationTest {
         }
     }
 
+    @Test
+    void installerTimeoutReturnsExit124(@TempDir Path temp) throws Exception {
+        try (WebsiteInstallerFixture fixture = 
WebsiteInstallerFixture.start(temp.resolve("fixture"))) {
+            Path home = Files.createDirectories(temp.resolve("home"));
+            Path xdgDataHome = home.resolve(".local/share");
+            markRunningAsWebInstaller(home, xdgDataHome, "1.0.0");
+            WebsiteInstallTest.publishLatest(fixture, NEWER_VERSION);
+            WebsiteInstallTest.publishVersion(fixture, NEWER_VERSION);
+
+            // A fake InstallScriptFetcher that returns a never-finishing 
`sleep 300` shell script
+            Path sleepScript = Files.createTempFile(temp, "fake-install", 
".sh");
+            Files.writeString(sleepScript, "#!/bin/sh\nsleep 300\n");
+            sleepScript.toFile().setExecutable(true);
+            InstallScriptFetcher hangingFetcher = new 
InstallScriptFetcher("unused") {
+                @Override
+                public Path fetch(Path stagingDir) {
+                    return sleepScript;
+                }
+            };
+
+            HttpClient httpClient = trustingHttpClient(fixture);
+            ManifestFetcher fetcher = new ManifestFetcher(
+                    fixture.baseUrl() + "/camel-cli/releases", 
fixture.mavenUrl(), fixture.snapshotUrl(), httpClient);
+            Map<String, String> installerEnv = fixture.environment(home);
+            SelfUpdateCommand cmd
+                    = new SelfUpdateCommand(new 
CamelJBangMain().withPrinter(printer), fetcher, hangingFetcher, installerEnv);
+            // Shorten the 5-minute process wait to 2 seconds so the test 
completes quickly
+            cmd.processWaitTimeoutSeconds = 2;
+
+            int exit;
+            try {
+                exit = new CommandTree(cmd).execute().getResultValue();
+            } catch (Exception e) {
+                throw new IllegalStateException(e);
+            }
+
+            assertThat(exit).isEqualTo(CliExitCode.TIMEOUT);
+            assertThat(printer.getOutput()).contains("timed out");
+        }
+    }
+
     @Test
     void installsLatestVersionByDelegatingToRealInstallSh(@TempDir Path temp) 
throws Exception {
         try (WebsiteInstallerFixture fixture = 
WebsiteInstallerFixture.start(temp.resolve("fixture"))) {

Reply via email to