corentin-soriano commented on code in PR #1143:
URL: https://github.com/apache/guacamole-client/pull/1143#discussion_r2912430299


##########
extensions/guacamole-vault/modules/guacamole-vault-openbao/src/main/java/org/apache/guacamole/vault/openbao/secret/OpenBaoClient.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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.guacamole.vault.openbao.secret;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import org.apache.guacamole.GuacamoleException;
+import org.apache.guacamole.GuacamoleServerException;
+import org.apache.guacamole.vault.openbao.conf.OpenBaoConfigurationService;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
+import org.apache.hc.core5.util.Timeout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * Client for communicating with OpenBao REST API.
+ */
+public class OpenBaoClient {
+
+    /**
+     * Logger for this class.
+     */
+    private static final Logger logger = 
LoggerFactory.getLogger(OpenBaoClient.class);
+
+    /**
+     * Service for retrieving OpenBao configuration.
+     */
+    @Inject
+    private OpenBaoConfigurationService configService;
+
+    /**
+     * Gson instance for JSON parsing.
+     */
+    private final Gson gson = new Gson();
+
+    /**
+     * Retrieves a secret from OpenBao by username.
+     *
+     * @param username
+     *     The Guacamole username to look up in OpenBao.
+     *
+     * @return
+     *     The JSON response from OpenBao.
+     *
+     * @throws GuacamoleException
+     *     If the secret cannot be retrieved from OpenBao.
+     */
+    public JsonObject getSecret(String username) throws GuacamoleException {
+
+        String serverUrl = configService.getServerUrl();
+        String token = configService.getToken();
+        String mountPath = configService.getMountPath();
+        String kvVersion = configService.getKvVersion();
+
+        // Build the API path based on KV version
+        // KV v2: /v1/{mount-path}/data/{username}
+        // KV v1: /v1/{mount-path}/{username}
+        String apiPath;
+        if ("2".equals(kvVersion)) {
+            apiPath = String.format("/v1/%s/data/%s", mountPath, username);
+        } else {
+            apiPath = String.format("/v1/%s/%s", mountPath, username);
+        }
+
+        String fullUrl = serverUrl + apiPath;
+
+        logger.info("Fetching secret from OpenBao: {}", fullUrl);
+
+        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
+
+            HttpGet httpGet = new HttpGet(fullUrl);
+            httpGet.setHeader("X-Vault-Token", token);
+            httpGet.setHeader("Accept", "application/json");
+
+            // Set timeouts
+            
httpGet.setConfig(org.apache.hc.client5.http.config.RequestConfig.custom()
+                    
.setConnectionRequestTimeout(Timeout.ofMilliseconds(configService.getConnectionTimeout()))
+                    
.setResponseTimeout(Timeout.ofMilliseconds(configService.getRequestTimeout()))
+                    .build());
+
+            org.apache.hc.core5.http.ClassicHttpResponse response = 
httpClient.executeOpen(null, httpGet, null);
+            try {
+                int statusCode = response.getCode();
+                String responseBody = 
EntityUtils.toString(response.getEntity());
+
+                if (statusCode == 200) {
+                    logger.info("OpenBao response status: {} - successfully 
retrieved password for {}", statusCode, username);
+                    JsonObject jsonResponse = gson.fromJson(responseBody, 
JsonObject.class);
+                    return jsonResponse;
+                } else if (statusCode == 404) {
+                    logger.warn("Secret not found in OpenBao for username: 
{}", username);
+                    throw new GuacamoleServerException("Secret not found in 
OpenBao for username: " + username);
+                } else if (statusCode == 403) {
+                    logger.error("Permission denied accessing OpenBao. Check 
token permissions.");
+                    throw new GuacamoleServerException("Permission denied 
accessing OpenBao. Check token permissions.");
+                } else {
+                    logger.error("OpenBao returned error status {}: {}", 
statusCode, responseBody);
+                    throw new GuacamoleServerException("OpenBao error (HTTP " 
+ statusCode + "): " + responseBody);
+                }
+            } finally {
+                response.close();
+            }
+
+        } catch (IOException | org.apache.hc.core5.http.ParseException e) {
+            logger.error("Failed to communicate with OpenBao at {}: {}", 
fullUrl, e.getMessage());
+            throw new GuacamoleServerException("Failed to communicate with 
OpenBao", e);
+        }
+    }
+
+    /**
+     * Extracts the password field from an OpenBao KV v2 response.
+     *
+     * @param response
+     *     The JSON response from OpenBao.
+     *
+     * @return
+     *     The password string, or null if not found.
+     */
+    public String extractPassword(JsonObject response) {
+        try {
+            // For KV v2: response.data.data.password
+            if (response.has("data")) {
+                JsonObject data = response.getAsJsonObject("data");
+                if (data.has("data")) {
+                    JsonObject innerData = data.getAsJsonObject("data");
+                    if (innerData.has("password")) {
+                        return innerData.get("password").getAsString();
+                    }
+                }
+            }
+
+            logger.warn("Password field not found in OpenBao response");
+            return null;
+
+        } catch (Exception e) {

Review Comment:
   Could we catch a more specific exception?



##########
extensions/guacamole-vault/modules/guacamole-vault-openbao/src/main/java/org/apache/guacamole/vault/openbao/secret/OpenBaoClient.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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.guacamole.vault.openbao.secret;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import org.apache.guacamole.GuacamoleException;
+import org.apache.guacamole.GuacamoleServerException;
+import org.apache.guacamole.vault.openbao.conf.OpenBaoConfigurationService;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
+import org.apache.hc.core5.util.Timeout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * Client for communicating with OpenBao REST API.
+ */
+public class OpenBaoClient {
+
+    /**
+     * Logger for this class.
+     */
+    private static final Logger logger = 
LoggerFactory.getLogger(OpenBaoClient.class);
+
+    /**
+     * Service for retrieving OpenBao configuration.
+     */
+    @Inject
+    private OpenBaoConfigurationService configService;
+
+    /**
+     * Gson instance for JSON parsing.
+     */
+    private final Gson gson = new Gson();
+
+    /**
+     * Retrieves a secret from OpenBao by username.
+     *
+     * @param username
+     *     The Guacamole username to look up in OpenBao.
+     *
+     * @return
+     *     The JSON response from OpenBao.
+     *
+     * @throws GuacamoleException
+     *     If the secret cannot be retrieved from OpenBao.
+     */
+    public JsonObject getSecret(String username) throws GuacamoleException {
+
+        String serverUrl = configService.getServerUrl();
+        String token = configService.getToken();
+        String mountPath = configService.getMountPath();
+        String kvVersion = configService.getKvVersion();
+
+        // Build the API path based on KV version
+        // KV v2: /v1/{mount-path}/data/{username}
+        // KV v1: /v1/{mount-path}/{username}
+        String apiPath;
+        if ("2".equals(kvVersion)) {
+            apiPath = String.format("/v1/%s/data/%s", mountPath, username);
+        } else {
+            apiPath = String.format("/v1/%s/%s", mountPath, username);
+        }
+
+        String fullUrl = serverUrl + apiPath;
+
+        logger.info("Fetching secret from OpenBao: {}", fullUrl);
+
+        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

Review Comment:
   Is there a specific reason to re-instantiate an HTTP client for each request?



##########
extensions/guacamole-vault/modules/guacamole-vault-openbao/src/main/java/org/apache/guacamole/vault/openbao/secret/OpenBaoClient.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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.guacamole.vault.openbao.secret;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import org.apache.guacamole.GuacamoleException;
+import org.apache.guacamole.GuacamoleServerException;
+import org.apache.guacamole.vault.openbao.conf.OpenBaoConfigurationService;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
+import org.apache.hc.core5.util.Timeout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+/**
+ * Client for communicating with OpenBao REST API.
+ */
+public class OpenBaoClient {
+
+    /**
+     * Logger for this class.
+     */
+    private static final Logger logger = 
LoggerFactory.getLogger(OpenBaoClient.class);
+
+    /**
+     * Service for retrieving OpenBao configuration.
+     */
+    @Inject
+    private OpenBaoConfigurationService configService;
+
+    /**
+     * Gson instance for JSON parsing.
+     */
+    private final Gson gson = new Gson();
+
+    /**
+     * Retrieves a secret from OpenBao by username.
+     *
+     * @param username
+     *     The Guacamole username to look up in OpenBao.
+     *
+     * @return
+     *     The JSON response from OpenBao.
+     *
+     * @throws GuacamoleException
+     *     If the secret cannot be retrieved from OpenBao.
+     */
+    public JsonObject getSecret(String username) throws GuacamoleException {
+
+        String serverUrl = configService.getServerUrl();
+        String token = configService.getToken();
+        String mountPath = configService.getMountPath();
+        String kvVersion = configService.getKvVersion();

Review Comment:
   What will happen if the URL, path, or token is not defined or is empty?



##########
extensions/guacamole-vault/modules/guacamole-vault-openbao/src/main/java/org/apache/guacamole/vault/openbao/secret/OpenBaoSecretService.java:
##########
@@ -0,0 +1,172 @@
+/*
+ * 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.guacamole.vault.openbao.secret;
+
+import com.google.gson.JsonObject;
+import com.google.inject.Inject;
+import org.apache.guacamole.GuacamoleException;
+import org.apache.guacamole.net.auth.Connectable;
+import org.apache.guacamole.net.auth.UserContext;
+import org.apache.guacamole.protocol.GuacamoleConfiguration;
+import org.apache.guacamole.token.TokenFilter;
+import org.apache.guacamole.vault.secret.VaultSecretService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Future;
+
+/**
+ * OpenBao implementation of VaultSecretService.
+ * Retrieves RDP passwords from OpenBao based on the logged-in Guacamole 
username.
+ */
+public class OpenBaoSecretService implements VaultSecretService {
+
+    /**
+     * Logger for this class.
+     */
+    private static final Logger logger = 
LoggerFactory.getLogger(OpenBaoSecretService.class);
+
+    /**
+     * Client for communicating with OpenBao.
+     */
+    @Inject
+    private OpenBaoClient openBaoClient;
+
+    /**
+     * Constructor that logs when the service is created.
+     */
+    public OpenBaoSecretService() {
+        logger.info("OpenBaoSecretService initialized");
+    }
+
+    /**
+     * The token pattern for OpenBao secrets: ${OPENBAO_SECRET}
+     */
+    public static final String OPENBAO_SECRET_TOKEN = "${OPENBAO_SECRET}";
+
+    /**
+     * The token pattern for Guacamole username: ${GUAC_USERNAME}
+     */
+    public static final String GUAC_USERNAME_TOKEN = "${GUAC_USERNAME}";
+
+    @Override
+    public String canonicalize(String token) {
+        // Return the canonical form for tokens we recognize
+        if (token == null)
+            return null;
+
+        // Remove ${} wrapper and return just the token name
+        if (OPENBAO_SECRET_TOKEN.equals(token)) {
+            return "OPENBAO_SECRET";
+        }
+
+        if (GUAC_USERNAME_TOKEN.equals(token)) {
+            return "GUAC_USERNAME";
+        }
+
+        // Not our token
+        return null;
+    }
+
+    @Override
+    public Future<String> getValue(String token) throws GuacamoleException {
+        // This method is called for simple token lookups without user context
+        logger.warn("getValue(String) called without user context - cannot 
determine username");
+        return CompletableFuture.completedFuture(null);
+    }
+
+    @Override
+    public Future<String> getValue(UserContext userContext, Connectable 
connectable, String token)
+            throws GuacamoleException {
+
+        logger.info("getValue() called with token: {}", token);
+
+        // Get the logged-in Guacamole username
+        String username = userContext.self().getIdentifier();
+
+        // Handle GUAC_USERNAME token - return the Guacamole username
+        if ("GUAC_USERNAME".equals(token)) {
+            logger.info("getValue() returning username: '{}'", username);
+            return CompletableFuture.completedFuture(username);
+        }
+
+        // Handle OPENBAO_SECRET token - fetch password from OpenBao
+        if ("OPENBAO_SECRET".equals(token)) {
+            logger.info("Retrieving OpenBao secret for username: {}", 
username);
+
+            try {
+                // Fetch the secret from OpenBao using the username
+                JsonObject response = openBaoClient.getSecret(username);
+
+                // Extract the password field
+                String password = openBaoClient.extractPassword(response);
+
+                if (password != null) {
+                    logger.info("Successfully retrieved password from OpenBao 
for user: {} (length: {})", username, password.length());
+                    return CompletableFuture.completedFuture(password);
+                } else {
+                    logger.warn("Password field not found in OpenBao for user: 
{}", username);
+                    return CompletableFuture.completedFuture(null);
+                }
+
+            } catch (GuacamoleException e) {
+                logger.error("Failed to retrieve secret from OpenBao for user: 
{}", username, e);
+                // Return null instead of throwing to allow connection attempt 
with empty password
+                return CompletableFuture.completedFuture(null);
+            }
+        }
+
+        // Not a recognized token
+        logger.warn("Token '{}' not recognized, returning null", token);
+        return CompletableFuture.completedFuture(null);
+    }
+
+    @Override
+    public Map<String, Future<String>> getTokens(UserContext userContext,
+            Connectable connectable,
+            GuacamoleConfiguration config,
+            TokenFilter tokenFilter) throws GuacamoleException {
+
+        Map<String, Future<String>> tokens = new java.util.HashMap<>();
+        String username = userContext.self().getIdentifier();
+
+        // Add GUAC_USERNAME token (always available)
+        tokens.put("GUAC_USERNAME", 
CompletableFuture.completedFuture(username));
+
+        // Add OPENBAO_SECRET token (fetch from OpenBao)
+        try {
+            JsonObject response = openBaoClient.getSecret(username);
+            String password = openBaoClient.extractPassword(response);
+            if (password != null) {
+                tokens.put("OPENBAO_SECRET", 
CompletableFuture.completedFuture(password));
+                logger.info("Added token OPENBAO_SECRET with password from 
OpenBao (length: {})", password.length());
+            } else {
+                logger.warn("Password not found in OpenBao for user: {}", 
username);
+            }
+        } catch (Exception e) {

Review Comment:
   Could we catch a more specific exception?



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