Spring Boot 中使用的 System.getenv() 在 sonarQube 中显示为安全漏洞

Shi*_*N.R 5 java environment-variables spring-boot

我的 spring boot 应用程序中有方法从系统环境变量中获取数据,该方法按预期工作,但 sonarQube 说“确保此处安全使用环境变量”,我试图找到解决此问题的替代方法,但我是找不到解决办法,方法如下:

我该如何处理这个安全问题,除了从环境变量中获取值之外,我不能使用任何其他方法。

public Map<String, Object> getConfigurations() {
    Map<String, Object> result = new HashMap<>();
    HttpResponse response = null;
    try {
         String xVaultToken = System.getenv("XVaultToken");
         String cityAppConfig = System.getenv("CityApp_Config");

        @SuppressWarnings("deprecation")
        HttpClient client = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
                .setSslcontext(
                        new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build())
                .build();
        Map<String, Object> headerDatas = new HashMap<>();
        headerDatas.put("Content-Type", "application/json");
        headerDatas.put("X-Vault-Token", xVaultToken);
        HttpGet get = new HttpGet(cityAppConfig);
        Set<String> keys = headerDatas.keySet();
        for (String key : keys) {
            get.setHeader(key, headerDatas.get(key).toString());
        }
        response = client.execute(get);
        try(BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))){
            String responseData = rd.readLine();
            result.put(Constants.RESPONSE, responseData);
        }
        int statusCode = response.getStatusLine().getStatusCode();
        result.put(Constants.STATUS, statusCode);

    } catch (Exception e) {
        logger.info("error is local settings getConfigurations" + e);
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

}

cod*_*dev 5

免责声明!!!

首先,正如我在评论中提到的,如果有人要求您阅读 ENV 变量,但还说您不能将 SonarQube 警告标记为误报:(礼貌地)告诉他们他们将不得不生活带有 SonarQube 警告。

但是,如果出于任何原因这不是一个选项,我将向您展示两种可能不会在 SonarQube 中触发警告的方法,它们仍然比cmd.exe为此目的调用要简洁得多。

示例 1

通过调用函数 java.util.function.Function

private static String getenv(String variable) {
    return ((Function<String, String>) System::getenv).apply(variable);
}
Run Code Online (Sandbox Code Playgroud)

示例 2

通过反射调用函数

    private static String getenv(String variable) {
        try {
            return (String) System.class.getMethod("getenv", String.class).invoke(null, variable);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }
Run Code Online (Sandbox Code Playgroud)