|
| 1 | +/* |
| 2 | + * SonarQube Python Plugin |
| 3 | + * Copyright (C) 2011-2025 SonarSource Sàrl |
| 4 | + * mailto:info AT sonarsource DOT com |
| 5 | + * |
| 6 | + * This program is free software; you can redistribute it and/or |
| 7 | + * modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 | + * See the Sonar Source-Available License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the Sonar Source-Available License |
| 15 | + * along with this program; if not, see https://sonarsource.com/license/ssal/ |
| 16 | + */ |
| 17 | +package org.sonar.python.checks; |
| 18 | + |
| 19 | +import java.util.Optional; |
| 20 | +import javax.annotation.Nullable; |
| 21 | +import org.sonar.check.Rule; |
| 22 | +import org.sonar.plugins.python.api.PythonSubscriptionCheck; |
| 23 | +import org.sonar.plugins.python.api.SubscriptionContext; |
| 24 | +import org.sonar.plugins.python.api.symbols.v2.SymbolV2; |
| 25 | +import org.sonar.plugins.python.api.symbols.v2.UsageV2; |
| 26 | +import org.sonar.plugins.python.api.tree.CallExpression; |
| 27 | +import org.sonar.plugins.python.api.tree.Expression; |
| 28 | +import org.sonar.plugins.python.api.tree.Name; |
| 29 | +import org.sonar.plugins.python.api.tree.QualifiedExpression; |
| 30 | +import org.sonar.plugins.python.api.tree.RegularArgument; |
| 31 | +import org.sonar.plugins.python.api.tree.Tree; |
| 32 | +import org.sonar.plugins.python.api.types.v2.matchers.TypeMatcher; |
| 33 | +import org.sonar.plugins.python.api.types.v2.matchers.TypeMatchers; |
| 34 | +import org.sonar.python.checks.utils.Expressions; |
| 35 | +import org.sonar.python.tree.TreeUtils; |
| 36 | + |
| 37 | +@Rule(key = "S8414") |
| 38 | +public class CorsMiddlewareOrderingCheck extends PythonSubscriptionCheck { |
| 39 | + |
| 40 | + private static final String MESSAGE = "Add CORSMiddleware last in the middleware chain."; |
| 41 | + |
| 42 | + // Stubs are missing entirely for fastapi/starlette.middleware.cors so we match by FQN for add_middleware |
| 43 | + private static final TypeMatcher ADD_MIDDLEWARE_MATCHER = TypeMatchers.any( |
| 44 | + TypeMatchers.withFQN("fastapi.applications.FastAPI.add_middleware"), |
| 45 | + TypeMatchers.withFQN("starlette.applications.Starlette.add_middleware") |
| 46 | + ); |
| 47 | + |
| 48 | + private static final TypeMatcher CORS_MIDDLEWARE_MATCHER = TypeMatchers.any( |
| 49 | + TypeMatchers.withFQN("fastapi.middleware.cors.CORSMiddleware"), |
| 50 | + TypeMatchers.withFQN("starlette.middleware.cors.CORSMiddleware") |
| 51 | + ); |
| 52 | + |
| 53 | + @Override |
| 54 | + public void initialize(Context context) { |
| 55 | + context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, CorsMiddlewareOrderingCheck::checkAddMiddlewareCall); |
| 56 | + } |
| 57 | + |
| 58 | + private static void checkAddMiddlewareCall(SubscriptionContext ctx) { |
| 59 | + CallExpression callExpr = (CallExpression) ctx.syntaxNode(); |
| 60 | + |
| 61 | + if (!ADD_MIDDLEWARE_MATCHER.isTrueFor(callExpr.callee(), ctx)) { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + if (!isCorsMiddleware(ctx, callExpr)) { |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + SymbolV2 receiverSymbol = extractReceiverSymbol(callExpr).orElse(null); |
| 70 | + if (receiverSymbol == null) { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + Tree currentEnclosingScope = getScope(callExpr); |
| 75 | + if (currentEnclosingScope == null) { |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + int currentLine = callExpr.firstToken().line(); |
| 80 | + |
| 81 | + if (hasSubsequentMiddlewareAddition(ctx, receiverSymbol, currentLine, currentEnclosingScope)) { |
| 82 | + ctx.addIssue(callExpr.callee(), MESSAGE); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + private static boolean isCorsMiddleware(SubscriptionContext ctx, CallExpression callExpr) { |
| 87 | + return TreeUtils.nthArgumentOrKeywordOptional(0, "middleware_class", callExpr.arguments()) |
| 88 | + .map(RegularArgument::expression) |
| 89 | + .map(expr -> { |
| 90 | + if (CORS_MIDDLEWARE_MATCHER.isTrueFor(expr, ctx)) { |
| 91 | + return true; |
| 92 | + } |
| 93 | + if (expr instanceof Name name) { |
| 94 | + Expression assignedValue = Expressions.singleAssignedValue(name); |
| 95 | + return assignedValue != null && CORS_MIDDLEWARE_MATCHER.isTrueFor(assignedValue, ctx); |
| 96 | + } |
| 97 | + return false; |
| 98 | + }) |
| 99 | + .orElse(false); |
| 100 | + } |
| 101 | + |
| 102 | + private static boolean isNameContainingCors(@Nullable Expression expr){ |
| 103 | + if(expr == null){ |
| 104 | + return false; |
| 105 | + } |
| 106 | + if(!(expr instanceof Name name)) { |
| 107 | + return false; |
| 108 | + } |
| 109 | + String simpleName = name.name(); |
| 110 | + return simpleName != null && (simpleName.contains("CORS") || simpleName.contains("Cors")); |
| 111 | + } |
| 112 | + |
| 113 | + private static boolean hasSubsequentMiddlewareAddition( |
| 114 | + SubscriptionContext ctx, |
| 115 | + SymbolV2 receiverSymbol, |
| 116 | + int currentLine, |
| 117 | + Tree currentEnclosingScope) { |
| 118 | + |
| 119 | + return receiverSymbol.usages().stream() |
| 120 | + .filter(usage -> usage.kind() == UsageV2.Kind.OTHER) |
| 121 | + .filter(usage -> usage.tree().firstToken().line() > currentLine) |
| 122 | + .filter(usage -> isSameScope(usage.tree(), currentEnclosingScope)) |
| 123 | + .anyMatch(usage -> isReceiverOfAddMiddleware(usage, ctx)); |
| 124 | + } |
| 125 | + |
| 126 | + private static boolean isSameScope(Tree usageTree, Tree currentEnclosingScope) { |
| 127 | + Tree usageEnclosingScope = getScope(usageTree); |
| 128 | + return usageEnclosingScope == currentEnclosingScope; |
| 129 | + } |
| 130 | + |
| 131 | + private static Tree getScope(Tree tree) { |
| 132 | + return TreeUtils.firstAncestorOfKind(tree, Tree.Kind.FUNCDEF, Tree.Kind.LAMBDA, Tree.Kind.FILE_INPUT); |
| 133 | + } |
| 134 | + |
| 135 | + private static boolean isReceiverOfAddMiddleware(UsageV2 usage, SubscriptionContext ctx) { |
| 136 | + Tree tree = usage.tree(); |
| 137 | + |
| 138 | + Tree parent = tree.parent(); |
| 139 | + if (!(parent instanceof QualifiedExpression qualifiedExpr)) { |
| 140 | + return false; |
| 141 | + } |
| 142 | + |
| 143 | + Tree qualiifiedParent = qualifiedExpr.parent(); |
| 144 | + if (!(qualiifiedParent instanceof CallExpression parentCall)) { |
| 145 | + return false; |
| 146 | + } |
| 147 | + |
| 148 | + return ADD_MIDDLEWARE_MATCHER.isTrueFor(parentCall.callee(), ctx); |
| 149 | + } |
| 150 | + |
| 151 | + private static Optional<SymbolV2> extractReceiverSymbol(CallExpression callExpr) { |
| 152 | + return Optional.ofNullable(callExpr.callee()) |
| 153 | + .flatMap(TreeUtils.toOptionalInstanceOfMapper(QualifiedExpression.class)) |
| 154 | + .map(QualifiedExpression::qualifier) |
| 155 | + .flatMap(TreeUtils.toOptionalInstanceOfMapper(Name.class)) |
| 156 | + .map(Name::symbolV2); |
| 157 | + } |
| 158 | +} |
0 commit comments