### Install Dependencies Source: https://github.com/sonarsource/sonar-python/blob/master/python-frontend/typeshed_serializer/README.md Installs project dependencies using pip. This command should be run from the project root. ```bash pip install -r requirements.txt ``` -------------------------------- ### Compliant Pytorch Module Initialization Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6978.html This compliant example demonstrates the correct way to initialize a Pytorch module by calling super().__init__() at the beginning of the constructor. This ensures proper setup for AutoGrad and parameter tracking. ```python import torch.nn as nn class MyCustomModule(nn.Module): def __init__(self, input_size, output_size): super().__init__() self.fc = nn.Linear(input_size, output_size) ``` -------------------------------- ### Simple Output in Python Source: https://github.com/sonarsource/sonar-python/blob/master/python-frontend/src/test/resources/org/sonar/plugins/python/notebook.ipynb A basic example of printing 'hello world' to the console. ```python Output: hello world ``` -------------------------------- ### Simple Output String Source: https://github.com/sonarsource/sonar-python/blob/master/its/plugin/it-python-plugin-test/projects/ipynb_json_project/json_notebook.ipynb A basic output string example. ```text hello world ``` -------------------------------- ### Install and Test Argon2 CLI Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5344.html This command installs the argon2 library and demonstrates how to use its CLI to test and select safe custom parameters for Argon2 hashing. Adjust parameters like -t, -m, -p, and -l based on OWASP recommendations and your application's requirements. ```bash pip install argon2 python -m argon2 -t 1 -m 47104 -p 1 -l 32 ``` -------------------------------- ### Compliant: CORSMiddleware as Outermost Layer Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8414.html This example demonstrates the compliant setup where GZipMiddleware is added first, followed by CORSMiddleware. This ensures CORSMiddleware is the outermost layer, correctly handling CORS headers for all responses. ```python from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware app = FastAPI() app.add_middleware(GZipMiddleware) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) ``` -------------------------------- ### Compliant code example with consistent naming Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S117.html This example demonstrates compliant code where the function parameter and local variable follow a consistent naming convention. ```python def print_something(important_param): local_variable = "" print(important_param + local_variable) ``` -------------------------------- ### AnyIO Timeout With Checkpoint Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7490.html This compliant example adds a checkpoint using `anyio.lowlevel.checkpoint()` within an `anyio.move_on_after` scope. ```python import anyio async def process_data(data): async with anyio.move_on_after(1.0): # Compliant result = expensive_computation(data) await anyio.lowlevel.checkpoint() return result ``` -------------------------------- ### Compliant open() mode Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5828.html This example shows a valid mode "a" for the open() function, which will not raise an error. ```python with open("test.txt", "a") as f: pass ``` -------------------------------- ### Compliant Code Examples Without Redundant Parentheses Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1110.html These examples demonstrate correct usage where parentheses are either absent or used appropriately for clarity. ```python return 3 ``` ```python return (3) ``` ```python return x + 1 ``` ```python return (x + 1) ``` ```python x = y / 2 + 1 ``` ```python x = (y / 2) + 1 ``` -------------------------------- ### Compliant Python Code Example with Type Hint Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6540.html This example demonstrates how to fix the noncompliant code by adding a type hint for the 'name' parameter, improving clarity and enabling static analysis. ```python def hello(name: str) -> str: return 'Hello ' + name ``` -------------------------------- ### Compliant % Formatting Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S3457.html This is a compliant example of %-style string formatting where the number of arguments exactly matches the number of placeholders. ```python "Error %(message)s" % {"message": "something failed"} ``` -------------------------------- ### Compliant str.format() Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S3457.html This is a compliant example of str.format() usage, ensuring that the number of arguments matches the number of placeholders in the string. ```python "Error: User {} has not been able to access {}".format("Alice", "MyFile") ``` -------------------------------- ### Compliant Solution: Function with Docstring Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1720.html This example demonstrates a compliant Python function that includes a docstring to explain its purpose. ```python def my_function(a,b): """Do X""" ``` -------------------------------- ### Noncompliant Flask Route Handler for GET requests Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6965.html This noncompliant example omits the `methods` parameter for a route that is intended to handle GET requests. While GET is the default, explicitly stating it improves clarity and consistency. ```python @app.route('/dashboard') def dashboard(): # Noncompliant return render_template('dashboard.html') ``` -------------------------------- ### Compliant Solution: Reading IP from Configuration Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1313.html This example demonstrates a compliant solution where the IP address is retrieved from a configuration source. This approach allows for easier management and updates of network configurations without code changes. ```python ip = config.get(section, ipAddress) sock = socket.socket() sock.bind((ip, 9090)) ``` -------------------------------- ### Noncompliant GET Endpoint using @app.route() Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8412.html This example shows a noncompliant FastAPI endpoint using the generic @app.route() decorator with methods=["GET"]. Replace with @app.get() for compliance. ```python @app.route("/users", methods=["GET"]) # Noncompliant def get_users(): return {"users": []} ``` -------------------------------- ### Compliant APIRouter GET Endpoint Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8412.html This compliant example demonstrates defining a GET endpoint using APIRouter with the specific @router.get() decorator. This pattern is consistent with using the main FastAPI app instance. ```python router = APIRouter() @router.get("/items") def list_items(): return {"items": []} ``` -------------------------------- ### Correct defaultdict Initialization Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7507.html This example demonstrates the correct way to initialize `defaultdict` by providing the factory callable as the first positional argument. ```python from collections import defaultdict d1 = defaultdict(int) # Compliant ``` -------------------------------- ### Noncompliant APIRouter GET Endpoint Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8412.html This example shows a noncompliant endpoint defined using APIRouter, where the generic @router.route() decorator is used with methods=["GET"]. Use @router.get() for compliance. ```python router = APIRouter() @router.route("/items", methods=["GET"]) # Noncompliant def list_items(): return {"items": []} ``` -------------------------------- ### Compliant: Asynchronous file read with anyio.open_file Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7493.html This example demonstrates the compliant asynchronous file reading approach in AnyIO using 'anyio.open_file()'. ```python import anyio async def read_config(): async with await anyio.open_file("config.json", "r") as file: # Compliant data = await file.read() return data ``` -------------------------------- ### Noncompliant: Redundant response_model for GET endpoint Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8409.html This example demonstrates a FastAPI GET route with a noncompliant `response_model` parameter that duplicates the return type annotation. Remove the redundant parameter to improve code clarity. ```python @app.get("/users/{user_id}", response_model=User) # Noncompliant def get_user(user_id: int) -> User: return fetch_user(user_id) ``` -------------------------------- ### Sensitive Encryption Initialization with pynacl Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S4787.html These examples demonstrate sensitive calls to encryption initialization functions using the 'pynacl' library. Proper key management is crucial for security. ```python from nacl.public import Box def public_encrypt(secret_key, public_key): Box(secret_key, public_key) # Sensitive ``` ```python from nacl.secret import SecretBox def secret_encrypt(key): SecretBox(key) # Sensitive ``` -------------------------------- ### Noncompliant Test Method Naming Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5899.html Methods intended as tests must start with 'test' to be discovered by the test runner. This example shows a method 'something_test' that will not be executed. ```python import unittest class MyTest(unittest.TestCase): def setUp(self): ... # OK (unittest.TestCase method) def something_test(self): ... # Noncompliant ``` -------------------------------- ### Noncompliant Boto3 CloudWatch Metric Publishing Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7609.html This example demonstrates noncompliant metric publishing using Boto3 to a reserved 'AWS/' namespace. Ensure your custom namespaces do not start with 'AWS/'. ```python import boto3 cloudwatch = boto3.client('cloudwatch') # Publishing to AWS reserved namespace cloudwatch.put_metric_data( Namespace='AWS/MyCustomService', # Noncompliant MetricData=[ { 'MetricName': 'CustomMetric', 'Value': 123.0 } ] ) ``` -------------------------------- ### OWASP Recommended Argon2 Parameters Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5344.html This example shows how to define Argon2 parameters according to OWASP recommendations. These parameters balance security and resource usage for Argon2id. ```python import argon2 from argon2.low_level import ARGON2_VERSION, Type OWASP_1 = argon2.Parameters( type=Type.ID, version=ARGON2_VERSION, salt_len=16, hash_len=32, time_cost=1, memory_cost=47104, # 46 MiB parallelism=1) ``` -------------------------------- ### Detect Deeply Nested Control Flow Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S134.html This noncompliant example shows code with nesting levels exceeding the default limit of 4. Issues are reported starting from the 5th level of nesting. ```python if condition1: # ... if condition2: # ... for i in range(10): # ... if condition3: if condition4: if condition5: # ... ``` -------------------------------- ### Noncompliant: CORSMiddleware Not Outermost Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8414.html This example shows a noncompliant setup where CORSMiddleware is added before GZipMiddleware. This can cause CORS headers to be missed on responses modified by GZipMiddleware, leading to failed cross-origin requests. ```python from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.add_middleware(GZipMiddleware) # Noncompliant ``` -------------------------------- ### Compliant: Load Private Key from File in FastAPI Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6781.html This compliant example demonstrates loading the private key from a file ('resources/rs256.pem') instead of hard-coding it. This improves security by keeping the key out of the source code. ```python from typing import Dict from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm import jwt oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login") private_key = '' with open('resources/rs256.pem', 'r') as f: private_key = f.read() def create_access_token(data: dict): to_encode = data.copy() to_encode.update({"exp": datetime.now(timezone.utc) + timedelta(minutes=15)}) return jwt.encode(to_encode, private_key, algorithm="RS256") def validate_login(username: str, password: str) -> None: ... @app.post("/login") async def login( form_data: OAuth2PasswordRequestForm = Depends() ) -> Dict[str, str]: validate_login(form_data.username, form_data.password) return dict(access_token=create_access_token(data={"sub": form_data.username})) ``` -------------------------------- ### Compliant: 'async with' in async function Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7515.html This example demonstrates the compliant solution using the 'async with' statement within an async function. This correctly utilizes the asynchronous context manager protocol for setup and cleanup. ```python class Resource: def __enter__(self): return self def __exit__(self, exc_type, exc, tb): ... async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): ... async def main(): async with Resource() as resource: # Compliant: using 'async with' in async function ... ``` -------------------------------- ### Compliant AnyIO Function Using Timeout Context Manager Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7483.html This `anyio` example shows the compliant approach to handling timeouts using the `anyio.move_on_after()` context manager. ```python import anyio async def example_function(): await anyio.sleep(5) async def main(): with anyio.move_on_after(5): # Compliant await example_function() anyio.run(main) ``` -------------------------------- ### Noncompliant: Mutating Default List Parameter Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5717.html This example shows a function where the default parameter is a list that gets mutated within the function body. Subsequent calls reuse the mutated default, leading to unexpected results. ```python def myfunction(param=list()): # Noncompliant: param is a list that gets mutated param.append('a') # modification of the default value. return param print(myfunction()) # returns ['a'] print(myfunction()) # returns ['a', 'a'] print(myfunction()) # returns ['a', 'a', 'a'] ``` -------------------------------- ### Compliant Password Hashing with OWASP Recommended Parameters Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5344.html This example shows how to hash passwords using Argon2 with parameters recommended by OWASP for a good balance of security and performance. ```python from argon2 import Parameters from argon2.low_level import ARGON2_VERSION, Type OWASP_1 = Parameters( type=Type.ID, version=ARGON2_VERSION, salt_len=16, hash_len=32, time_cost=1, memory_cost=47104, # 46 MiB parallelism=1) def hash_password(password): ph = PasswordHasher.from_parameters(OWASP_1) return ph.hash(password) ``` -------------------------------- ### Compliant: Using tempfile.TemporaryFile with a Specific Directory Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5443.html This compliant example uses `tempfile.TemporaryFile` to create a temporary file. While a specific directory is provided, `tempfile` ensures secure handling. For maximum security, it's often best to let `tempfile` choose the directory. ```python import tempfile file = tempfile.TemporaryFile(dir="/tmp/my_subdirectory", mode="w+") # Compliant ``` -------------------------------- ### Compliant Flask Route Handler with GET and POST Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6965.html This compliant solution explicitly specifies 'GET' and 'POST' in the `methods` parameter of the route decorator. This ensures that both GET and POST requests are handled correctly by the route. ```python @app.route('/api/users', methods=['GET', 'POST']) def handle_users(): if request.method == 'POST': return create_user() return get_users() ``` -------------------------------- ### Hash Password with Scrypt Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5344.html Demonstrates how to hash a password using the Scrypt algorithm with recommended parameters for security. Ensure the salt is unique for each password. ```python from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.scrypt import Scrypt def hash_password(password, salt): scrypt = Scrypt( salt=salt, length=64, n=1 << 17, r=8, p=1) return scrypt.derive(password) ``` -------------------------------- ### Compliant Flask Route Handler for GET requests Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6965.html Even for routes that only handle GET requests, explicitly specifying `methods=['GET']` in the route decorator makes the intent clear and prevents potential issues if the default behavior is misunderstood. ```python @app.route('/dashboard', methods=['GET']) def dashboard(): return render_template('dashboard.html') ``` -------------------------------- ### Compliant AnyIO code using `anyio.lowlevel.checkpoint()` Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7491.html This example shows the compliant method for yielding control in AnyIO using `anyio.lowlevel.checkpoint()`. This function clearly indicates the intention to create a checkpoint for task switching. ```python import anyio async def main(): await anyio.lowlevel.checkpoint() # Compliant anyio.run(main) ``` -------------------------------- ### Compliant AnyIO code using Event Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7484.html This example demonstrates the compliant way to wait for a condition in AnyIO using `anyio.Event`. This allows tasks to pause efficiently and react immediately when the event is set. ```python import anyio SHARED_CONDITION = anyio.Event() async def worker(): await SHARED_CONDITION.wait() # Compliant print("Condition is now true") anyio.run(worker) ``` -------------------------------- ### Noncompliant Code Example: Missing Docstring Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1720.html This example shows a Python function without a docstring, which is considered noncompliant. ```python def my_function(a,b): ``` -------------------------------- ### Noncompliant Code Examples with Redundant Parentheses Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1110.html These examples show parentheses that do not change the code's behavior and should be removed. ```python return ((3)) ``` ```python return ((x + 1)) ``` ```python x = ((y / 2)) + 1 ``` -------------------------------- ### Compliant anyio cancellation handling Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7497.html This example demonstrates the compliant way to handle anyio cancellation exceptions by re-raising them after potential cleanup. ```python import anyio async def compute_result(data): ... async def process_data(data): try: result = await compute_result(data) return result except anyio.get_cancelled_exc_class(): # Compliant raise ``` -------------------------------- ### Compliant use of environment variables for credentials Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S2068.html This example demonstrates a compliant solution using environment variables to securely manage credentials. Ensure the environment variables are set before running the code. ```python import os username = os.getenv("username") # Compliant password = os.getenv("password") # Compliant usernamePassword = 'user=%s&password=%s' % (username, password) # Compliant ``` -------------------------------- ### Noncompliant code example using typing.List Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6545.html This example shows the noncompliant usage of `typing.List` for type hinting a list of integers. ```python import typing def print_numbers(numbers: typing.List[int]) -> None: for n in numbers: print(n) ``` -------------------------------- ### Noncompliant Code Example: Unused Parameter Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1172.html This is a noncompliant example where the second parameter 'b' is declared but not used within the function. ```python def do_something(a, b): # second parameter is unused return compute(a) ``` -------------------------------- ### Compliant Solution: Using Constants Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1192.html This example demonstrates the compliant solution by replacing duplicated string literals with a constant. This improves code maintainability as the string only needs to be updated in one place. ```python ACTION_1 = "action1" def run(): prepare(ACTION_1) execute(ACTION_1) release(ACTION_1) ``` -------------------------------- ### Compliant Loop Example Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1751.html This is a compliant example of a loop that might execute more than once. The 'break' statement is removed, allowing the loop to function as intended. ```python while node is not None: node = node.parent() print(node) ``` -------------------------------- ### Unofficial Flask-Argon2 Setup Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5344.html This snippet shows an unofficial way to set up Flask-Argon2, including parameter configuration. Ensure OWASP_1 is defined appropriately for your security needs. ```python from flask import Flask from flask_argon2 import Argon2 app = Flask(__name__) argon2 = Argon2(app) argon2.ph = OWASP_1 set_flask_argon2_parameters(app, OWASP_1) ``` -------------------------------- ### Noncompliant Code Example with NOSONAR Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/NoSonar.html This example shows how the NOSONAR marker is used in noncompliant Python code. It is intended to be flagged by the rule. ```python for d in lib_dirs: # NOSONAR: lib_dirs is undefined pass ``` -------------------------------- ### Compliant File Header Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1451.html This is an example of a compliant header that should be placed at the beginning of every source file. It includes copyright information and licensing details. ```text # # SonarQube, open source software quality management tool. # Copyright (C) 2008-2018 SonarSource # mailto:contact AT sonarsource DOT com # # SonarQube is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3 of the License, or (at your option) any later version. # # SonarQube is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # ``` -------------------------------- ### Compliant Flask Route Restricted to GET Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S3752.html This Flask route explicitly restricts allowed methods to GET. This is a secure practice for read-only operations. ```python @methods.route('/compliant2', methods=['GET']) def view(): return Response("...", 200) ``` -------------------------------- ### Compliant solution using built-in list Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6545.html This example demonstrates the compliant way to type hint a list of integers using the built-in `list` type. ```python def print_numbers(numbers: list[int]) -> None: for n in numbers: print(n) ``` -------------------------------- ### Fast/Minimal Maven Build Source: https://github.com/sonarsource/sonar-python/blob/master/README.md Use this command for a quick build that only compiles Java modules and runs tests. The Python interpreter is not required, and typeshed stub generation is skipped. ```bash mvn clean install -P-private ``` -------------------------------- ### Noncompliant Python Code Example Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6540.html This example shows a Python function without type hints for its parameters, which can lead to runtime type errors. ```python def hello(name) -> str: return 'Hello ' + name ``` -------------------------------- ### Noncompliant Code Example Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5864.html This example demonstrates a type annotation contradiction. The 'param' is annotated as 'str', but the code attempts to add an integer to it, which is incompatible. ```python def add_the_answer(param: str): return param + 42 # Noncompliant. Fix this "+" operation; Type annotation on "param" suggest that operands have incompatible types. # Note: In practice it is possible to create a class inheriting from both "str" and "int", but this would be a very confusing design. ``` -------------------------------- ### Compliant Flask Database Configuration using Environment Variable Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S2115.html This Flask example demonstrates a secure way to configure the database connection by retrieving the password from the DB_PASSWORD environment variable. Ensure this variable is set securely during deployment. ```python import os def configure_app(app): db_password = os.getenv('DB_PASSWORD') app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://user:{db_password}@domain.com" ``` -------------------------------- ### Incorrect defaultdict Initialization Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7507.html This example shows the incorrect way to initialize `defaultdict` using `default_factory` as a keyword argument. This will not set the default factory and will create a dictionary with a single key-value pair. ```python from collections import defaultdict d1 = defaultdict(default_factory=int) # Noncompliant: this creates a dictionary with a single key-value pair. ``` -------------------------------- ### Noncompliant Code Example: Suspicious Backslashes Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1717.html This example demonstrates strings with backslashes that do not form valid escape sequences. These can be misinterpreted by the Python interpreter. ```python s = "Hello \\world." t = "Nice to \\ meet you" u = "Let's have \\ lunch" ``` -------------------------------- ### Run Integration Tests Source: https://github.com/sonarsource/sonar-python/blob/master/its/Readme.txt Navigate to the plugin directory and run integration tests using Maven. Specify the SonarQube runtime version. ```bash cd its/plugin mvn test -Dsonar.runtimeVersion=LATEST_RELEASE ``` -------------------------------- ### Compliant GET Endpoint using @app.get() Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8412.html This is the compliant solution for a GET endpoint in FastAPI, using the specific @app.get() decorator. This is the idiomatic and recommended approach. ```python @app.get("/users") def get_users(): return {"users": []} ``` -------------------------------- ### Compliant: Asynchronous HTTP Call with httpx.AsyncClient Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7499.html This example demonstrates the recommended way to make HTTP requests in asynchronous code using `httpx.AsyncClient`. This approach allows other tasks to run while waiting for the response. ```python import httpx async def fetch_data(): async with httpx.AsyncClient() as client: response = await client.get("https://api.example.com/data") return response.json() ``` -------------------------------- ### Noncompliant Code Example: Unused Local Variable Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1854.html This example shows a local variable 'i' being assigned a value that is then overwritten before being used. This is flagged as a dead store. ```python def func(a, b, compute): i = a + b # Noncompliant; calculation result not used before value is overwritten i = compute() return i ``` -------------------------------- ### Compliant Instance, Class, and Static Methods Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5719.html This example demonstrates compliant instance, class, and static methods. Instance methods include 'self', class methods include 'cls', and static methods do not require a positional parameter. ```python class MyClass: def instance_method(self): print("instance_method") @classmethod def class_method(cls): print("class_method") @staticmethod def static_method(): print("static_method") ``` -------------------------------- ### Find minimum using min() (Compliant) Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8517.html This example shows the compliant way to find the smallest element using the `min()` function. This is more efficient than sorting. ```python numbers = [42, 17, 93, 8, 51] smallest = min(numbers) ``` -------------------------------- ### Compliant Django Password Hashers Configuration Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S5344.html This configuration uses stronger, modern hashing algorithms. Ensure 'argon2-cffi' is installed via 'pip install django[argon2]'. ```python # settings.py PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.ScryptPasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', ] ``` -------------------------------- ### Noncompliant code example with inconsistent naming Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S117.html This example shows noncompliant code where a function parameter and a local variable use inconsistent naming conventions, violating the rule. ```python def print_something(IMPORTANT_PARAM): # Noncompliant localVariable = "" # Noncompliant print(IMPORTANT_PARAM + localVariable) ``` -------------------------------- ### Noncompliant Code Example: Hard-coded API Key Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6418.html This example shows a hard-coded API key assigned to a variable, which is a security risk. Secrets should never be embedded directly in the code. ```python import requests API_KEY = "1234567890abcdef" # Hard-coded secret (bad practice) def send_api_request(data): headers = { "Authorization": f"Bearer {API_KEY}" } return requests.post("https://api.example.com", headers=headers, data=data) ``` -------------------------------- ### Compliant Methods Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1186.html These examples show compliant solutions for empty methods. This includes implementing the method, raising a `NotImplementedError`, or providing a comment or docstring to explain why the method is intentionally empty. ```python def shouldNotBeEmpty(): doSomething() ``` ```python def notImplemented(): raise NotImplementedError("notImplemented() cannot be performed because ...") ``` ```python def emptyOnPurpose(): pass # comment explaining why the method is empty ``` ```python def emptyOnPurposeBis(): """ Docstring explaining why this function is empty. """ ``` -------------------------------- ### Compliant Django Route Using GET Decorator Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S3752.html This Django view uses the `require_GET` decorator to explicitly allow only GET requests. This is a secure way to ensure a route is used only for read-only operations. ```python @require_GET def view(request): return HttpResponse("...") ``` -------------------------------- ### Compliant EFS File System Creation (AWS CDK) Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6332.html This example demonstrates the correct way to create an EFS file system with encryption enabled using AWS CDK. Setting 'encrypted' to True ensures data at rest is protected. ```python from aws_cdk import ( aws_efs as efs ) efs.FileSystem( self, "example", encrypted=True ) ``` -------------------------------- ### Noncompliant Code Example: Duplicated Strings Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1192.html This example shows duplicated string literals that violate the rule. The string "action1" is repeated three times, exceeding the default threshold. ```python def run(): prepare("action1") # Noncompliant - "action1" is duplicated 3 times execute("action1") release("action1") @app.route("/api/users/", methods=["GET", "POST", "PUT"]) ``` ```python def users(): pass @app.route("/api/projects/", methods=["GET", "POST", "PUT"]) # Compliant - strings inside decorators are ignored ``` ```python def projects(): pass ``` -------------------------------- ### Compliant: Using anyio.to_thread.run_sync Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S7489.html This example demonstrates running a blocking OS call like `os.waitpid` in a worker thread using `anyio.to_thread.run_sync`. ```python import anyio import os async def wait_for_child_process(pid): pid, status = await anyio.to_thread.run_sync( os.waitpid, pid, 0 ) return status ``` -------------------------------- ### Compliant: Rely on return type annotation for GET endpoint Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S8409.html This compliant solution for a FastAPI GET route omits the `response_model` parameter, allowing FastAPI to infer the response type directly from the return annotation. ```python @app.get("/users/{user_id}") def get_user(user_id: int) -> User: return fetch_user(user_id) ``` -------------------------------- ### Noncompliant EFS File System Creation (AWS CDK) Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S6332.html This example shows how to create an EFS file system with encryption disabled, which is a security risk. Ensure 'encrypted' is set to True for compliant configurations. ```python from aws_cdk import ( aws_efs as efs ) efs.FileSystem( self, "example", encrypted=False # Noncompliant ) ``` -------------------------------- ### Noncompliant Code Example: Hardcoded IP Address Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1313.html This example shows a hardcoded IP address being used directly in the code. This makes it difficult to change the IP address without modifying and redeploying the application. ```python ip = '192.168.12.42' # Noncompliant sock = socket.socket() sock.bind((ip, 9090)) ``` -------------------------------- ### Sensitive Encryption Initialization with cryptography Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S4787.html These examples show sensitive calls to encryption initialization functions within the 'cryptography' module. Ensure keys are strong and algorithms are secure. ```python from cryptography.fernet import Fernet from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305, AESGCM, AESCCM from cryptography.hazmat.primitives.ciphers import Cipher def encrypt(key): Fernet(key) # Sensitive ChaCha20Poly1305(key) # Sensitive AESGCM(key) # Sensitive AESCCM(key) # Sensitive ``` ```python from cryptography.hazmat.primitives.asymmetric import rsa private_key = rsa.generate_private_key() # Sensitive ``` ```python from cryptography.hazmat.primitives.ciphers import Cipher def encrypt2(algorithm, mode, backend): Cipher(algorithm, mode, backend) # Sensitive ``` -------------------------------- ### Noncompliant Code Example with Noqa Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1309.html This example demonstrates the use of a 'noqa' comment to suppress a specific linting issue (S100). Use this pattern when you intentionally need to ignore a particular rule for a specific line. ```python ... # noqa: S100 ``` -------------------------------- ### Compliant Solution: Unique Conditions Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S1862.html This compliant example demonstrates a correctly structured if/elif chain where each condition is unique and reachable. ```python if param == 1: openWindow() elif param == 2: closeWindow() elif param == 3: moveWindowToTheBackground() ``` -------------------------------- ### Sensitive Flask Route Allowing GET and POST Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S3752.html This Flask route allows both GET and POST methods. If the route performs state-changing operations with POST, it may be vulnerable to CSRF attacks if not adequately protected. Explicitly define only the required methods. ```python @methods.route('/sensitive', methods=['GET', 'POST']) def view(): return Response("...", 200) ``` -------------------------------- ### Sensitive Django Route Allowing GET and POST Source: https://github.com/sonarsource/sonar-python/blob/master/python-checks/src/main/resources/org/sonar/l10n/py/rules/python/S3752.html This Django view explicitly allows both GET and POST methods. If POST is used for state-changing operations without proper CSRF protection, it can be a security risk. Restrict methods to only those necessary for the operation. ```python @require_http_methods(["GET", "POST"]) def view(request): return HttpResponse("...") ```