gnodet-bot commented on code in PR #30725:
URL: https://github.com/apache/camel/pull/30725#discussion_r4716779950


##########
dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/LlmClientExplicitUrlTest.java:
##########
@@ -95,4 +102,83 @@ void aUrlThatAnswersIsUsed() throws Exception {
             assertThat(client.apiType()).isEqualTo(ApiType.ollama);
         }
     }
+
+    /**
+     * CAMEL-27514: a URL ending with /v1 (the common OpenAI base path) must 
not produce a double /v1/v1/models probe.
+     * The server only knows /v1/models; /v1/v1/models returns 404 and would 
cause detection to fail.
+     */
+    @Test
+    void urlEndingWithV1IsDetectedAsOpenAi() throws Exception {
+        try (FakeLlmServer server = new FakeLlmServer("unused")) {
+            // The user passes the OpenAI-style base URL that includes the /v1 
segment.
+            LlmClient client = LlmClient.create().withUrl(server.url() + 
"/v1");
+
+            assertThat(client.detectEndpoint()).isTrue();
+            assertThat(client.apiType()).isEqualTo(ApiType.openai);
+        }
+    }
+
+    /**
+     * CAMEL-27514: an OpenAI-compatible server that requires auth (returns 
401 without a key) must be treated as
+     * reachable when the user has supplied an API key, because the health 
probe now forwards the Authorization header.
+     * <p>
+     * The negative assertion (no-key → detection fails) is skipped when 
{@code OPENAI_API_KEY} or {@code LLM_API_KEY}
+     * is set in the environment: {@code resolveApiKey()} falls back to those 
variables, so a developer machine with
+     * either variable set would send a Bearer header and make detection 
succeed even without an explicit key.
+     */
+    @Test
+    @DisabledIfEnvironmentVariables({
+            @DisabledIfEnvironmentVariable(named = "OPENAI_API_KEY", matches = 
".+"),
+            @DisabledIfEnvironmentVariable(named = "LLM_API_KEY", matches = 
".+")
+    })
+    void openAiCompatibleEndpointRequiringAuthIsDetectedWhenKeyIsConfigured() 
throws IOException {
+        // A server that replies 401 to /v1/models without an Authorization 
header, 200 with one.
+        HttpServer authServer = HttpServer.create(new 
InetSocketAddress("127.0.0.1", 0), 0);
+        authServer.createContext("/v1/models", exchange -> {
+            String auth = 
exchange.getRequestHeaders().getFirst("Authorization");
+            int status = (auth != null && auth.startsWith("Bearer ")) ? 200 : 
401;
+            String body = status == 200 ? "{\"data\":[{\"id\":\"test\"}]}" : 
"";
+            byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+            exchange.sendResponseHeaders(status, bytes.length == 0 ? -1 : 
bytes.length);
+            try (OutputStream os = exchange.getResponseBody()) {
+                os.write(bytes);
+            }
+        });
+        authServer.start();
+        String base = "http://127.0.0.1:"; + authServer.getAddress().getPort();
+        try {
+            // Without a key the server returns 401, endpoint detection must 
fail.
+            LlmClient noKey = LlmClient.create().withUrl(base);
+            assertThat(noKey.detectEndpoint()).isFalse();
+
+            // With a key the Authorization header is forwarded; detection 
succeeds.
+            LlmClient withKey = 
LlmClient.create().withUrl(base).withApiKey("sk-test");
+            assertThat(withKey.detectEndpoint()).isTrue();
+            assertThat(withKey.apiType()).isEqualTo(ApiType.openai);
+        } finally {
+            authServer.stop(0);
+        }
+    }
+
+    /**
+     * CAMEL-27514: when {@code --api-type=openai} is set explicitly, 
detection goes through
+     * {@code isEndpointReachable()} rather than {@code tryExplicitUrl()}. The 
same normalisation must apply: a URL
+     * ending with {@code /v1} or {@code /v1/} must not produce a double 
{@code /v1/v1/models} probe.
+     */
+    @Test
+    void withApiTypeOpenAiAndV1UrlVariants() throws Exception {

Review Comment:
   ⚠️ **Test does not cover the OpenAI probe path.** `FakeLlmServer` answers 
`/api/tags` with 200, so `isEndpointReachable()` short-circuits on the first 
(Ollama) probe and never reaches the `/v1/models` probe this test is named for. 
To actually verify the OpenAI normalization, let the Ollama probe fail: add 
`server.reply("/api/tags", 404, "")` before the assertions.



##########
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/LlmClient.java:
##########
@@ -2637,8 +2647,18 @@ boolean isEndpointReachable(String endpoint) {
             String base = normalizeGeminiBaseUrl(endpoint);
             return tryHealthCheck(base + "/models", buildGeminiHeaders(key));
         }
-        return tryHealthCheck(endpoint + "/api/tags", Map.of(), false)
-                || tryHealthCheck(endpoint + "/v1/models", Map.of(), false)
+        // normalizeOpenAiModelsUrl strips any trailing /v1, /v1/, or 
/v1/chat/completions suffix before
+        // appending /v1/models, preventing a double-prefix (/v1/v1/models) 
when the caller supplies a URL
+        // that already ends with /v1 or /v1/.
+        // The API key is forwarded only on the /v1/models probe 
(OpenAI-compatible) to avoid leaking credentials
+        // onto the Ollama /api/tags or root probes.
+        String openAiModelsUrl = normalizeOpenAiModelsUrl(endpoint);
+        // Derive the base URL for Ollama and root probes (strip /v1/models 
suffix added above).
+        String base = openAiModelsUrl.endsWith("/v1/models")
+                ? openAiModelsUrl.substring(0, openAiModelsUrl.length() - 
"/v1/models".length())
+                : endpoint;
+        return tryHealthCheck(base + "/api/tags", Map.of(), false)
+                || tryHealthCheck(openAiModelsUrl, 
buildOpenAiAuthHeaders(resolveApiKey()), false)

Review Comment:
   ⚠️ **Bearer header sent to non-OpenAI endpoints.** When 
`--api-type=anthropic` or `--api-type=vertex` triggers `isEndpointReachable()`, 
this fallback sends `resolveApiKey()` as `Authorization: Bearer` to 
`<endpoint>/v1/models`. Anthropic uses `x-api-key`, not Bearer. Guard this 
probe:
   
   ```suggestion
                   || (apiType == null || apiType == ApiType.openai)
                      && tryHealthCheck(openAiModelsUrl, 
buildOpenAiAuthHeaders(resolveApiKey()), false)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to