我遇到了 SonarQube 错误,但无法找出问题所在。 SonnarQube 的问题是,更改此代码以不从用户控制的数据构造 URL。
@Value("${...}")
String apiKey;
@Value("${...}")
String apiUrl;
public Response apiResponse(String location) {
HttpHeaders headers = new HttpHeaders();
headers.add("x-apikey", apiKey);
HttpEntity<Object> entity = new HttpEntity<>(headers);
String url = apiUrl + location; // SonarQube issue: tainted value is propagated
Response response = null;
try {
ResponseEntity<Response> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Response.class); // SonarQube issue: Tainted value is used to perform a security- sensitive operation.
response = responseEntity.getBody();
} catch(Exception){
// doesn't throw anything
}
return response;
}
@Cacheable(...)
Response cacheResponse(String location, String tokenKey) {
return apiResponse(location); // SonarQube issue: tainted value is propagated
}
这解决了问题,但为什么会这样呢?我如何在上面的代码中应用它?
String url = apiUrl + location; // SonarQube issue: tainted
相反,我只是尝试对位置值进行硬编码并解决了问题。
String url = apiUrl + "location";
好奇怪...
我添加了对位置变量的验证,这解决了问题
if(!location.matches(...)) {
throw error.....
}
String url = apiUrl + location;
SonarQube 试图告诉您的是,您正在将逻辑暴露给客户端的输入。更好的解决方案是重构代码,使其不依赖于客户端的特定标头来执行某些操作。如果不了解更多代码库,很难建议示例代码。
您正在使用来自客户端/用户的输入(即在变量位置中)来构造 URL。因此,如果客户端/用户向位置提供恶意值,他可能会形成无效的 URL。
在第二个示例中
String url = apiUrl + "location";
您没有使用用户输入,因为“位置”是一个硬编码的字符串。
我不知道你想用代码实现什么目的。但也许最好保存可能的 URL 列表以及用户提供的映射到 URL 的枚举值。
String url = "https://someurl/%s";
url = String.format(url,location);
sendRequest(url);
也许这种方法不会出错。
确保此 Azure 存储帐户密钥未被泄露。此消息显示在项目中的 sonarqube 中。如何解决这个问题。