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


##########
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Harden.java:
##########
@@ -193,6 +194,9 @@ String call(Harden harden, String endpoint, String 
sysPrompt, String userPrompt,
             defaultValue = "true", arity = "0..1", fallbackValue = "true")
     boolean stream = true;
 
+    // whether the answer was printed as it came
+    private boolean streamed;

Review Comment:
   Done in d87666ac9788: `streamed` is reset at the start of each file (in 
`hardenRoute`). Today the files of one run all take the same path, so it could 
not misfire yet, but the reset keeps it right per file.
   
   _Claude Code on behalf of davsclaus_



##########
dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/HardenTest.java:
##########
@@ -0,0 +1,126 @@
+/*
+ * 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;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.stream.Stream;
+
+import org.apache.camel.dsl.jbang.core.common.CliException;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
+import org.apache.camel.util.json.JsonObject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import picocli.CommandLine;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * camel harden: security suggestions for a route by an LLM (a local server 
plays Ollama, or an OpenAI-compatible
+ * service). Only the suggestions are on stdout.
+ */
+class HardenTest extends CamelCommandBaseTestSupport {
+
+    private static final String ROUTE = """
+            - route:
+                id: upload
+                from:
+                  uri: platform-http:/upload
+                  steps:
+                    - to: ftp:files.example.com/in?username=bob&password=secret
+            """;
+
+    private static final String SUGGESTIONS = "Use SFTP instead of FTP, and 
keep the password in a vault.";
+
+    @TempDir
+    Path dir;
+
+    private Path route;
+    private FakeLlmServer llm;
+
+    @BeforeEach
+    void start() throws Exception {
+        route = Files.writeString(dir.resolve("upload.camel.yaml"), ROUTE);
+        llm = new FakeLlmServer(SUGGESTIONS);
+    }
+
+    @AfterEach
+    void stop() {
+        llm.close();
+    }
+
+    @Test
+    void suggestionsFromOllama() throws Exception {
+        assertThat(command(route.toString()).doCall()).isZero();
+
+        assertThat(printer.getStdout()).contains("Security Hardening Analysis: 
" + route, SUGGESTIONS)
+                .doesNotContain("LLM Configuration");
+        assertThat(printer.getStderr()).contains("LLM Configuration:", 
"Performing security analysis with test (Ollama)");
+        
assertThat(llm.lastRequest().getString("prompt")).contains("ftp:files.example.com");
+    }
+
+    @Test
+    void suggestionsFromAnOpenAiCompatibleService() throws Exception {
+        assertThat(command(route.toString(), "--api-type=openai", 
"--api-key=sk-1234567890abcd").doCall()).isZero();
+
+        assertThat(printer.getStdout()).contains(SUGGESTIONS);
+        assertThat(printer.getStderr()).contains("(OpenAI-compatible)", "  API 
Key: ****abcd");
+        JsonObject request = llm.lastRequest();
+        assertThat(request.getString("model")).isEqualTo("test");
+        assertThat(request.toJson()).contains("ftp:files.example.com");
+    }
+
+    @Test
+    void thePromptsAreOnStderr() throws Exception {
+        assertThat(command(route.toString(), "--show-prompt", 
"--stream=false").doCall()).isZero();
+
+        assertThat(printer.getStderr()).contains("--- SYSTEM PROMPT ---", "--- 
USER PROMPT ---");
+        
assertThat(printer.getStdout()).contains(SUGGESTIONS).doesNotContain("--- 
SYSTEM PROMPT ---");
+    }
+
+    @Test
+    void anUnreachableUrlIsNotReplacedByAnotherLlm() throws Exception {
+        Harden command = new Harden(new CamelJBangMain().withPrinter(printer));
+        CommandLine.populateCommand(command, route.toString(), 
"--url=http://127.0.0.1:1";, "--model=test");
+
+        // the route is not sent to the Ollama of the host
+        assertThat(command.doCall()).isEqualTo(CliExitCode.FAILURE);
+        assertThat(printer.getStderr()).contains("Cannot connect to LLM 
service at: http://127.0.0.1:1";);
+    }
+
+    @Test
+    void unknownFormatIsAUsageError() {
+        Harden command = command(route.toString(), "--format=json");
+
+        assertThatThrownBy(command::doCall)
+                .isInstanceOfSatisfying(CliException.class,
+                        e -> 
assertThat(e.getExitCode()).isEqualTo(CliExitCode.USAGE))
+                .hasMessage("--format must be text or markdown, was: json");
+    }
+
+    private Harden command(String... args) {
+        Harden command = new Harden(new CamelJBangMain().withPrinter(printer));
+        CommandLine.populateCommand(command,
+                Stream.concat(Arrays.stream(args), Stream.of("--url=" + 
llm.url(), "--model=test"))
+                        .toArray(String[]::new));
+        return command;
+    }

Review Comment:
   Added in d87666ac9788: `suggestionsForEachFile` (OpenAI-compatible, not 
streamed) and `streamedSuggestionsForEachFile` (Ollama, streamed) run two files 
and check that the answer of each is printed.
   
   _Claude Code on behalf of davsclaus_



##########
dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/FakeLlmServer.java:
##########
@@ -0,0 +1,106 @@
+/*
+ * 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;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+
+/**
+ * A local server that plays an LLM for the tests of the AI commands: Ollama 
(its models, and the answer of the model,
+ * whole or streamed in two parts) and an OpenAI-compatible chat completion. 
It keeps the last question it answered.
+ */
+final class FakeLlmServer implements AutoCloseable {
+
+    private final HttpServer server;
+    private volatile String answer;
+    private volatile JsonObject lastRequest;
+
+    FakeLlmServer(String answer) throws IOException {
+        this.answer = answer;
+        server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+        server.createContext("/api/tags", ex -> reply(ex, 
"{\"models\":[{\"name\":\"test\",\"size\":1000}]}"));
+        server.createContext("/api/ps", ex -> reply(ex, "{\"models\":[]}"));
+        server.createContext("/api/show", ex -> reply(ex, 
"{\"model_info\":{}}"));
+        server.createContext("/api/generate", this::generate);
+        server.createContext("/v1/models", ex -> reply(ex, 
"{\"data\":[{\"id\":\"test\"}]}"));
+        server.createContext("/v1/chat/completions", this::chat);
+        server.start();
+    }
+
+    String url() {
+        return "http://127.0.0.1:"; + server.getAddress().getPort();
+    }
+
+    /**
+     * The last question the server answered, as the client sent it.
+     */
+    JsonObject lastRequest() {
+        return lastRequest;
+    }
+
+    @Override
+    public void close() {
+        server.stop(0);
+    }
+
+    private void generate(HttpExchange exchange) throws IOException {
+        JsonObject request = read(exchange);
+        if (request.getBooleanOrDefault("stream", false)) {
+            // the answer in two parts, a JSON document per line
+            int half = answer.length() / 2;
+            String first = new JsonObject(Map.of("response", 
answer.substring(0, half), "done", false)).toJson();
+            String last = new JsonObject(Map.of("response", 
answer.substring(half), "done", true)).toJson();
+            reply(exchange, first + "\n" + last + "\n");
+        } else {
+            reply(exchange, new JsonObject(Map.of("response", answer, "done", 
true)).toJson());
+        }
+    }
+
+    private void chat(HttpExchange exchange) throws IOException {
+        read(exchange);
+        JsonObject message = new JsonObject(Map.of("role", "assistant", 
"content", answer));
+        JsonObject choice = new JsonObject(Map.of("index", 0, "message", 
message));
+        reply(exchange, new JsonObject(Map.of("choices", new 
JsonArray(List.of(choice)))).toJson());
+    }
+
+    private JsonObject read(HttpExchange exchange) throws IOException {
+        String body = new String(exchange.getRequestBody().readAllBytes(), 
StandardCharsets.UTF_8);
+        JsonObject request = Jsoner.deserialize(body, new JsonObject());
+        lastRequest = request;
+        return request;
+    }
+
+    private static void reply(HttpExchange exchange, String body) throws 
IOException {
+        exchange.getRequestBody().readAllBytes();

Review Comment:
   Removed in d87666ac9788: `reply` no longer reads the request body; `read` 
drains it for the two endpoints that take a question.
   
   _Claude Code on behalf of davsclaus_



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