I'm working on a C# application using Npgsql to query a PostgreSQL database. I have the following method that constructs a query dynamically while using parameterized queries to prevent SQL injection:
public DataSummary GetSummaryData(List<long> recordIds = null)
{
var sqlParameters = new List<NpgsqlParameter>();
var conditions = new List<string>();
var userAccess = _accessProxy.GetUserAccess();
if (userAccess != null && !userAccess.HasFullAccess)
{
if (userAccess.FilteredRecords?.Any() == true)
{
AddSqlParam(sqlParameters, "filteredIds", userAccess.FilteredRecords, NpgsqlDbType.Array | NpgsqlDbType.Bigint);
conditions.Add("record_id = ANY(@filteredIds)");
}
if (userAccess.AccessibleCategoryIds?.Any() == true)
{
AddSqlParam(sqlParameters, "categoryIds", userAccess.AccessibleCategoryIds, NpgsqlDbType.Array | NpgsqlDbType.Bigint);
conditions.Add("category_id = ANY(@categoryIds)");
}
}
var query = new StringBuilder(@"
SELECT COUNT(DISTINCT item_id) AS TotalItems,
COUNT(DISTINCT CASE WHEN status = 'Active' THEN item_id END) AS ActiveItems
FROM data.items
WHERE created_date BETWEEN current_date AND current_date + 30");
if (recordIds?.Any() == true)
{
AddSqlParam(sqlParameters, "recordIds", recordIds, NpgsqlDbType.Array | NpgsqlDbType.Bigint);
conditions.Add("entity_id = ANY(@recordIds)");
}
if (conditions.Any())
{
query.Append(" AND " + string.Join(" AND ", conditions));
}
string finalQuery = query.ToString();
using (var conn = GetConnection())
{
using (var cmd = new NpgsqlCommand(finalQuery, conn))
{
cmd.Parameters.AddRange(sqlParameters.ToArray());
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
return new DataSummary
{
TotalItems = reader.GetInt32(0),
ActiveItems = reader.GetInt32(1)
};
}
}
}
}
return new DataSummary();
}
GitLab CI/CD flags this method as vulnerable to SQL injection, but I don’t see how it could be exploited. The code does not use direct string concatenation with user input and relies on parameterized queries using NpgsqlParameter. However, despite these precautions, the warning persists.
Is this method actually vulnerable to SQL injection? If not, why is GitLab flagging it? Lastly, how can I refactor this code to avoid the warning while maintaining its flexibility?
Would appreciate any insights on this! Thanks in advance.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745065828a4609250.html
评论列表(0条)