Skip to content

Commit

Permalink
SONARPY-2413 Clean-up the csrf_except decorator check
Browse files Browse the repository at this point in the history
  • Loading branch information
Seppli11 committed Dec 6, 2024
1 parent d06c65d commit b9c5f4d
Showing 1 changed file with 5 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,10 @@
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.sonar.check.Rule;
import org.sonar.plugins.python.api.PythonSubscriptionCheck;
import org.sonar.plugins.python.api.SubscriptionContext;
Expand Down Expand Up @@ -117,19 +114,14 @@ private static Predicate<Expression> isListAnyMatch(Predicate<Expression> pred)
"django.views.decorators.csrf.csrf_exempt",
"flask_wtf.csrf.CSRFProtect.exempt"));

private static boolean isDangerousDecorator(Decorator expression) {
return DANGEROUS_DECORATORS.stream().anyMatch(dangerousFqn -> TreeUtils.isDecoratorWithFQN(expression, dangerousFqn));
}

/** Raises issue whenever a decorator with something about "CSRF" and "exempt" in the combined name is found. */
private static void decoratorCsrfExemptCheck(SubscriptionContext subscriptionContext) {
Decorator decorator = (Decorator) subscriptionContext.syntaxNode();
List<String> names = Stream.of(TreeUtils.decoratorNameFromExpression(decorator.expression()))
.filter(Objects::nonNull)
.flatMap(s -> Arrays.stream(s.split("\\.")))
.toList();
// This is a temporary workaround until symbol resolution works for decorators.
// Use the actual functions with FQNs from DANGEROUS_DECORATORS once that's fixed.
// Related ticket: https://jira.sonarsource.com/browse/SONARPY-681
boolean isDangerous = names.stream().anyMatch(s -> s.toLowerCase(Locale.US).contains("csrf")) &&
names.stream().anyMatch(s -> s.toLowerCase(Locale.US).contains("exempt"));
if (isDangerous) {
if(isDangerousDecorator(decorator)) {
subscriptionContext.addIssue(decorator.lastToken(), MESSAGE);
}
}
Expand Down

0 comments on commit b9c5f4d

Please sign in to comment.