Skip to content

Commit 4862874

Browse files
authored
SONARPY-2143 add check if spread args are present in torch.load (#1980)
1 parent c7097e5 commit 4862874

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

python-checks/src/main/java/org/sonar/python/checks/TorchLoadLeadsToUntrustedCodeExecutionCheck.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import org.sonar.plugins.python.api.tree.RegularArgument;
3232
import org.sonar.plugins.python.api.tree.Tree;
3333
import org.sonar.python.cfg.fixpoint.ReachingDefinitionsAnalysis;
34+
import org.sonar.python.checks.utils.Expressions;
3435
import org.sonar.python.tree.TreeUtils;
3536

3637
@Rule(key = "S6985")
@@ -51,15 +52,17 @@ public void initialize(Context context) {
5152
context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, ctx -> {
5253
CallExpression callExpression = (CallExpression) ctx.syntaxNode();
5354
Symbol calleeSymbol = callExpression.calleeSymbol();
54-
if (calleeSymbol != null && TORCH_LOAD.equals(calleeSymbol.fullyQualifiedName()) && isWeightsOnlyNotFoundOrSetToFalse(callExpression.arguments())) {
55+
if (calleeSymbol != null && TORCH_LOAD.equals(calleeSymbol.fullyQualifiedName())
56+
&& isWeightsOnlyNotFoundOrSetToFalse(callExpression.arguments())) {
57+
5558
ctx.addIssue(callExpression.callee(), MESSAGE);
5659
}
5760
});
5861
}
5962

6063
private boolean isWeightsOnlyNotFoundOrSetToFalse(List<Argument> arguments) {
6164
RegularArgument weightsOnlyArg = TreeUtils.argumentByKeyword(WEIGHTS_ONLY, arguments);
62-
if (weightsOnlyArg == null) return true;
65+
if (weightsOnlyArg == null) return !Expressions.containsSpreadOperator(arguments);
6366
if (weightsOnlyArg.expression() instanceof Name name) {
6467
return PYTHON_FALSE.equals(name.name()) || isNameSetToFalse(name);
6568
}

python-checks/src/test/resources/checks/torchLoadLeadsToUntrustedCodeExecution.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,5 +33,11 @@ def only_one_definition():
3333
weights_only = False
3434
torch.load(model2, 'model.pth', weights_only=weights_only) #Noncompliant
3535

36+
def spread_operator(some_dict, some_list):
37+
torch.load(model2, 'model.pth', **some_dict)
38+
torch.load(model2, 'model.pth', *some_list)
39+
torch.load(model2, 'model.pth', weights_only=False, *some_list) #Noncompliant
40+
torch.load(model2, 'model.pth', weights_only=True, *some_list)
41+
3642
# test if no issue is raised if there is no symbol for the callee
3743
something[42]()

0 commit comments

Comments
 (0)