davsclaus commented on code in PR #30725:
URL: https://github.com/apache/camel/pull/30725#discussion_r4716630089


##########
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 {
+        try (FakeLlmServer server = new FakeLlmServer("unused")) {

Review Comment:
   `FakeLlmServer` answers `/api/tags` with 200, and `isEndpointReachable()` 
probes `base + "/api/tags"` first, so all three cases pass before the 
`/v1/models` probe runs. If `/api/tags` returns 404, only the `/v1/models` 
probe can make the test pass:
   
   ```suggestion
           try (FakeLlmServer server = new 
FakeLlmServer("unused").reply("/api/tags", 404, "")) {
   ```



##########
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:
   This method also runs for `--api-type=anthropic` (and `ollama`) with a 
`--url`. Then `resolveApiKey()` returns e.g. `ANTHROPIC_API_KEY`, which is sent 
here as `Authorization: Bearer`. It only goes to the user's URL, so this is not 
a leak, but Anthropic uses `x-api-key`, and the comment above says OpenAI only. 
Add the header only when `apiType == null || apiType == ApiType.openai`?



-- 
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