Dataset Viewer
Auto-converted to Parquet
name
stringlengths
0
69
severity
stringclasses
6 values
detector_id
stringlengths
0
61
category
stringclasses
3 values
cwe
listlengths
0
3
tags
listlengths
0
6
description
stringlengths
0
511
noncompliant_example
stringlengths
0
2.77k
compliant_example
stringlengths
0
1.73k
url
stringlengths
74
110
AWS api logging disabled cdk
High
security
[ "CWE-778" ]
[ "amazon-s3", "aws-cdk", "efficiency" ]
When an API does not have access logging enabled, it means that the system or organization responsible for the API is missing out on valuable information about how the API is being used, and it is failing to capture important data that can be essential for various purposes.
https://docs.aws.amazon.com/amazonq/detector-library/python/api-logging-disabled-cdk/
AWS AppConfig
Low
code-quality
[]
[ "maintainability" ]
To use the AppConfig correctly always first check if the new version is available and only then fetch the config.
https://docs.aws.amazon.com/amazonq/detector-library/python/aws-app-config/
AWS insecure transmission CDK
High
security
[ "CWE-319" ]
[ "amazon-s3", "aws-cdk", "efficiency" ]
Checks when user transmitting sensitive information, such as passwords, financial data, or personal information, over a network or storing it in a way that is not adequately protected with encryption.
https://docs.aws.amazon.com/amazonq/detector-library/python/aws-insecure-transmission-cdk/
Client-side KMS reencryption
High
security
[ "CWE-310", "CWE-311" ]
[ "aws-python-sdk", "aws-kms" ]
Client-side decryption followed by reencryption is inefficient and can lead to sensitive data leaks. The `reencrypt` APIs allow decryption followed by reencryption on the server side. This is more efficient and secure.
def kms_reencrypt_noncompliant(): import boto3 import base64 client = boto3.client('kms') plaintext = client.decrypt( CiphertextBlob=bytes(base64.b64decode("secret")) ) # Noncompliant: decrypt is immediately followed by encrypt. response = client.encrypt( KeyId='string', Plaintext=plaintext ) return response
def kms_reencrypt_compliant(): import boto3 import base64 client = boto3.client('kms') # Compliant: server-side reencryption. response = client.re_encrypt( CiphertextBlob=bytes(base64.b64decode("secret")), DestinationKeyId="string", ) return response
https://docs.aws.amazon.com/amazonq/detector-library/python/aws-kms-reencryption/
aws kmskey encryption cdk
High
security
[ "CWE-311" ]
[ "amazon-s3", "aws-cdk", "efficiency" ]
Using AWS KMS keys enables the organization to align with the standard security advice of granting least privilege. The data stored in the S3 bucket remains protected through encryption, and access to both the data and the encryption keys is restricted to authorized entities, reducing the potential security risks associated with data exposure and unauthorized access.
https://docs.aws.amazon.com/amazonq/detector-library/python/aws-kmskey-encryption-cdk/
AWS credentials logged
High
security
[ "CWE-255" ]
[ "access-control", "aws-python-sdk", "secrets", "owasp-top10" ]
Unencrypted AWS credentials are logged. This could expose those credentials to an attacker. Encrypt sensitive data, such as credentials, before they are logged to make the code more secure.
def log_credentials_noncompliant(): import boto3 import logging session = boto3.Session() credentials = session.get_credentials() credentials = credentials.get_frozen_credentials() access_key = credentials.access_key secret_key = credentials.secret_key # Noncompliant: credentials are written to the logger. logging.info('Access key: ', access_key) logging.info('secret access key: ', secret_key)
def log_credentials_compliant(): import boto3 session = boto3.Session() credentials = session.get_credentials() credentials = credentials.get_frozen_credentials() access_key = credentials.access_key secret_key = credentials.secret_key # Compliant: avoids writing credentials to the logger. session = boto3.Session( aws_access_key_id=access_key, aws_secret_access_key=secret_key )
https://docs.aws.amazon.com/amazonq/detector-library/python/aws-logged-credentials/
AWS missing encryption CDK
High
security
[ "CWE-311" ]
[ "aws-cdk" ]
Encryption ensure that the data is safe and is not sensitive to leakage. Ensure appropriate encryption strategies are used to prevent exposure of such sensitive data.
https://docs.aws.amazon.com/amazonq/detector-library/python/aws-missing-encryption-cdk/
Inefficient polling of AWS resource
Low
code-quality
[ "CWE-19" ]
[ "aws-python-sdk", "efficiency" ]
Custom polling can be inefficient and prone to error. Consider using AWS waiters instead. A waiter is an abstraction used to poll AWS resources, such as DynamoDB tables or Amazon S3 buckets, until a desired state is reached.
def polling_vs_waiters_noncompliant(response): import boto3 ec2_client = boto3.client('ec2', region_name='us-east-1') ec2_instance_id = response['Instances'][0]['InstanceId'] attempts = 0 while True: print("Waiting for EC2 instance to be up") # Noncompliant: uses custom polling instead of waiters feature. rsp = ec2_client.describe_instance_status( InstanceIds=[ str(ec2_instance_id) ], IncludeAllInstances=True ) instance_status = rsp['Statuses'][0]['InstanceStatus']['Status'] system_status = rsp['Statuses'][0]['SystemStatus']['Status'] if str(instance_status) == 'ok' and str(system_status) == 'ok': break if str(instance_status) == 'impaired' or \ str(instance_status) == 'insufficient-data' or \ str(system_status) == 'failed' or \ str(system_status) == 'insufficient-data': print('Instance status is ' + str(instance_status)) print('System status is ' + str(system_status)) tear_down() exit(1) attempts = attempts + 1 if attempts >= MAX_ATTEMPTS: print("MAX wait time for EC2 instance to be up reached.") print("Tearing down") tear_down() exit(1) time.sleep(10)
def polling_vs_waiters_compliant(): import boto3 client = boto3.client('kinesis', region_name='us-east-1') # Setup the Kinesis with 1 shard. stream_name = "tf_kinesis_test_1" client.create_stream(StreamName=stream_name, ShardCount=1) # Wait until stream exists, default is 10 * 18 seconds. # Compliant: uses waiters feature. client.get_waiter('stream_exists').wait(StreamName=stream_name) for i in range(10): data = "D" + str(i) client.put_record( StreamName=stream_name, Data=data, PartitionKey="TensorFlow" + str(i) )
https://docs.aws.amazon.com/amazonq/detector-library/python/aws-polling-instead-of-waiter/
Batch request with unchecked failures
Info
code-quality
[ "CWE-253" ]
[ "aws-python-sdk", "batch-operations", "data-integrity" ]
A batch request might return one or more failed items. To prevent data loss, make sure your code checks for failed items.
def write_itemsin_batch_noncompliant(self, request_items): import boto3 self.dynamodb = boto3.client('dynamodb') batch_list = self.dynamodb_conn.new_batch_write_list() batch_list.add_batch(dynamodb_table, puts=items) response = self.dynamodb_conn.batch_write_item(batch_list) # Noncompliant: unprocessed items not checked. return response
def write_itemsin_batch_compliant(self, request_items): import boto3 self.dynamodb = boto3.client('dynamodb') batch_list = self.dynamodb_conn.new_batch_write_list() batch_list.add_batch(dynamodb_table, puts=items) response = self.dynamodb_conn.batch_write_item(batch_list) # Compliant: has checks for unprocessed items. unprocessed = response.get('UnprocessedItems', None) return response, unprocessed
https://docs.aws.amazon.com/amazonq/detector-library/python/aws-unchecked-batch-failures/
Bad exception handling
Info
code-quality
[]
[]
Throwing a base or generic exception might cause important error information to be lost. This can make your code difficult to maintain. We recommend using built-in exceptions or creating a custom exception class that is derived from `Exception` or one of its subclasses.
def exception_handling_noncompliant(parameter): if not isinstance(parameter, int): # Noncompliant: a generic exception is thrown. raise Exception("param should be an integer")
def exception_handling_compliant(parameter): if not isinstance(parameter, int): # Compliant: specific exception is thrown. raise TypeError("param should be an integer")
https://docs.aws.amazon.com/amazonq/detector-library/python/bad-exception-handling-practices/
Catastrophic backtracking regex
Medium
code-quality
[]
[ "efficiency", "maintainability" ]
Inefficient regular expression patterns can lead to catastrophic backtracking. Follow ReDOS guidelines to make your regular expression more efficient, or use a different engine to evaluate the expressions.
https://docs.aws.amazon.com/amazonq/detector-library/python/catastrophic-backtracking-regex/
Catch and rethrow exception
Low
code-quality
[]
[ "efficiency", "maintainability" ]
Catching and re-throwing an exception without further actions is redundant and wasteful. Instead, it is recommended to re-throw custom exception type and/or log trace for debugging.
def nested_noncompliant(): try: try_something() except KeyError as e: try: catch_and_try_something() # Noncompliant: unnecessary `except` clause. except ValueError: raise raise e
def nested_compliant(): try: try_something() except KeyError as e: try: catch_and_try_something() except ValueError: # Compliant: operation in `except` clause. rethrow_exception_something() raise raise e
https://docs.aws.amazon.com/amazonq/detector-library/python/catch-and-rethrow-exception/
[]
[]
https://docs.aws.amazon.com/amazonq/detector-library/python/categories/security/
Clear text credentials
High
security
[ "CWE-916", "CWE-328" ]
[ "access-control", "information-leak", "secrets", "owasp-top10" ]
Credentials that are stored in clear text in memory or written to log files can be intercepted by a malicious actor.
PASSWORD_HASHERS = [ # Noncompliant: uses non-standard or insecure password hashers. "django.contrib.auth.hashers.MD5PasswordHasher", "django.contrib.auth.hashers.PBKDF2PasswordHasher" ]
PASSWORD_HASHERS = [ # Compliant: uses standard and secure hashers. 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher' ]
https://docs.aws.amazon.com/amazonq/detector-library/python/clear-text-credentials/
Unsanitized input is run as code
Critical
security
[ "CWE-94" ]
[ "injection", "owasp-top10", "top25-cwes" ]
Running scripts generated from unsanitized inputs (for example, evaluating expressions that include user-provided strings) can lead to malicious behavior and inadvertently running code remotely.
from flask import app @app.route('/') def execute_input_noncompliant(): from flask import request module_version = request.args.get("module_version") # Noncompliant: executes unsanitized inputs. exec("import urllib%s as urllib" % module_version)
from flask import app @app.route('/') def execute_input_compliant(): from flask import request module_version = request.args.get("module_version") # Compliant: executes sanitized inputs. exec("import urllib%d as urllib" % int(module_version))
https://docs.aws.amazon.com/amazonq/detector-library/python/code-injection/
Low maintainability with low class cohesion
Info
code-quality
[]
[ "maintainability" ]
Classes with low class cohesion contain unrelated operations which make them difficult to understand and less likely to be used. The class cohesion is computed as the number of clusters of instance methods that do not have any accessed class members in common. For example, a cluster might have two methods that access only the class fields `x` and `y`, and another cluster might have two other methods that access only the class fields `a` and `b`. A high number of these clusters indicates low class cohesion.
https://docs.aws.amazon.com/amazonq/detector-library/python/code-quality-metrics-class-cohesion/
Complex code hard to maintain
Low
code-quality
[]
[ "maintainability" ]
Complex code can be difficult to read and hard to maintain. For example, using three parameters in a single statement while slicing data, and comprehension with more than two subexpressions, can both be hard to understand.
def avoid_complex_comprehension_noncompliant(): text = [['bar', 'pie', 'line'], ['Rome', 'Madrid', 'Houston'], ['aa', 'bb', 'cc', 'dd']] # Noncompliant: list comprehensions with more than two control # sub expressions are hard to read and maintain. text_3 = [y.upper() for x in text if len(x) == 3 for y in x if y.startswith('f')]
def avoid_complex_comprehension_compliant(): text = [['bar', 'pie', 'line'], ['Rome', 'Madrid', 'Houston'], ['aa', 'bb', 'cc', 'dd']] text_1 = [] # Compliant: easy to read and maintain. for x in text: if len(x) > 3: for y in x: text_1.append(y)
https://docs.aws.amazon.com/amazonq/detector-library/python/code-readability/
Cross-site request forgery
High
security
[ "CWE-352" ]
[ "configuration", "injection", "owasp-top10", "top25-cwes" ]
Insecure configuration can lead to a cross-site request forgery (CRSF) vulnerability. This can enable an attacker to trick end users into performing unwanted actions while authenticated.
def csrf_protection_noncompliant(): from flask import Flask app = Flask(__name__) # Noncompliant: disables CSRF protection. app.config['WTF_CSRF_ENABLED'] = False
def csrf_protection_compliant(): from flask_wtf.csrf import CsrfProtect from flask import Flask csrf = CsrfProtect() app = Flask(__name__) # Compliant: enables CSRF protection. csrf.init_app(app)
https://docs.aws.amazon.com/amazonq/detector-library/python/cross-site-request-forgery/
Cross-site scripting
High
security
[ "CWE-20", "CWE-79", "CWE-80" ]
[ "injection", "owasp-top10", "top25-cwes" ]
User-controllable input must be sanitized before it's included in output used to dynamically generate a web page. Unsanitized user input can introduce cross-side scripting (XSS) vulnerabilities that can lead to inadvertedly running malicious code in a trusted context.
from flask import app @app.route('/redirect') def redirect_url_noncompliant(): from flask import request, redirect endpoint = request.args['url'] # Noncompliant: redirect to a user-supplied URL without sanitization. return redirect(endpoint)
from flask import app @app.route('/redirect') def redirect_url_compliant(): from flask import request, url_for, redirect endpoint = request.args['url'] # Compliant: user-supplied URL is sanitized before redirecting to it. return redirect(url_for(endpoint))
https://docs.aws.amazon.com/amazonq/detector-library/python/cross-site-scripting/
Dangerous global variables
Low
code-quality
[]
[ "maintainability" ]
Global variables can be dangerous and cause bugs because they can be simultaneously accessed from multiple sections of a program. Most global variable bugs are caused when one function reading and acting on the value of a global variable before another function has the chance to set it to an appropriate value. We recommend using a configuration module to mutate global state.
def dangerous_global_noncompliant(w): # Noncompliant: uses global variable, which can be accessed # from multiple sections. global width width = w
def dangerous_global_compliant(w): # Compliant: avoids using global variables, restricting # the scope to this method. width = w return width
https://docs.aws.amazon.com/amazonq/detector-library/python/dangerous-global-variables/
Mutable objects as default arguments of functions
Low
code-quality
[]
[ "maintainability" ]
Default values in Python are created exactly once, when the function is defined. If that object is changed, subsequent calls to the function will refer to the changed object, leading to confusion. We recommend that you set the default value to `None`, then check inside the function if the parameter is `None` before creating the desired mutable object.
# Noncompliant: default arguments have mutable objects. def with_complex_default_value_noncompliant(self, index=1, mydict={}, mylist=[]): mydict[index] = mylist[index] return mydict
# Compliant: default arguments are assigned to None or unmutable objects. def with_unmutable_objects_compliant(mydict=None, number=1, str="hi", mytuple=(1, 2)): print(mydict, number, str, mytuple)
https://docs.aws.amazon.com/amazonq/detector-library/python/default-argument-mutable-objects/
Use of a deprecated method
Low
code-quality
[ "CWE-477" ]
[ "availability", "maintainability" ]
This code uses deprecated methods, which suggests that it has not been recently reviewed or maintained. Using deprecated methods might lead to erroneous behavior.
def deprecated_method_noncompliant(url): import botocore.vendored.requests as requests # Noncompliant: uses the deprecated botocore vendored method. return requests.get(url)
def deprecated_method_compliant(url, sigv4auth): import requests # Compliant: avoids using the deprecated methods. return requests.get(url, auth=sigv4auth).text
https://docs.aws.amazon.com/amazonq/detector-library/python/deprecated-method/
Enabling and overriding debug feature
Medium
code-quality
[ "CWE-489" ]
[ "efficiency", "maintainability" ]
Don't enable or override an application's debug feature. Instead, use OS environment variables to set up the debug feature.
def detect_activated_debug_feature_noncompliant(): from django.conf import settings # Noncompliant: The debug feature is enabled. settings.configure(DEBUG=True)
def detect_activated_debug_feature_compliant(): from django.conf import settings import os # Compliant: The debug feature is set through the environment variable. settings.configure(DEBUG=os.environ['DEBUG'])
https://docs.aws.amazon.com/amazonq/detector-library/python/detect-activated-debug-feature/
Risky use of dict get method
Low
code-quality
[]
[ "availability", "maintainability" ]
Using the `get` method from the `dict` class without default values can cause undesirable results. Default parameter values can help prevent a `KeyError` exception.
def keyerror_noncompliant(): mydict = {1: 1, 2: 2, 3: 3} key = 5 try: # Noncompliant: uses [] which causes exception when key is not found. count = mydict[key] except KeyError: count = 0 return count
def keyerror_compliant(): mydict = {1: 1, 2: 2, 3: 3} key = 5 # Compliant: uses get() with a default value. return mydict.get(key, 0)
https://docs.aws.amazon.com/amazonq/detector-library/python/dict-get-method/
Using AutoAddPolicy or WarningPolicy
High
security
[ "CWE-322" ]
[ "owasp-top10" ]
We detected a Paramiko host key policy that implicitly trusts server's host key. Do not use `AutoAddPolicy` or `WarningPolicy` as a missing host key policy when creating `SSHClient`. Unverified host keys can allow a malicious server to take control of a trusted server by using the sensitive data (such as authentication information). Instead, use `RejectPolicy` or a custom subclass.
def do_not_auto_add_or_warning_missing_hostkey_policy_noncompliant(): from paramiko import AutoAddPolicy from paramiko.client import SSHClient ssh_client = SSHClient() # Noncompliant: Insecure `AutoAddPolicy` is used as missing hostkey policy. ssh_client.set_missing_host_key_policy(policy=AutoAddPolicy)
def do_not_auto_add_or_warning_missing_hostkey_policy_compliant(): from paramiko import RejectPolicy from paramiko.client import SSHClient ssh_client = SSHClient() # Compliant: Secure `RejectPolicy` is used as missing hostkey policy. ssh_client.set_missing_host_key_policy(RejectPolicy)
https://docs.aws.amazon.com/amazonq/detector-library/python/do-not-auto-add-or-warning-missing-hostkey-policy/
Do not pass generic exception rule
High
code-quality
[ "CWE-396", "CWE-397" ]
[ "consistency", "maintainability" ]
Do not pass generic exception.
https://docs.aws.amazon.com/amazonq/detector-library/python/do-not-pass-generic-exception-rule/
Docker arbitrary container run
Medium
security
[ "CWE-77" ]
[ "owasp-top10", "top25-cwes" ]
You are not sanitizing user input that is used as an argument for the Docker image. We recommend that you sanitize user input before passing it to a function call.
@app.route('/someUrl') def docker_arbitrary_container_run_noncompliant(): client = docker.from_env() img = request.args.get("image") # Noncompliant: Unsanitised user input is passed to `run`. client.containers.run(img, 'echo non compliant')
@app.route('/someUrl') def docker_arbitrary_container_run_compliant(): client = docker.from_env() img = os.environ["image"] # Compliant: Input from environment variable is passed to `run`. client.containers.run(img, 'echo hello world')
https://docs.aws.amazon.com/amazonq/detector-library/python/docker-arbitrary-container-run/
Confusion between equality and identity in conditional expression
Info
code-quality
[]
[]
Confusion between equality `==`, `!=` and identity `is` in conditional expressions can lead to unintended behavior.
def notequals_operator_noncompliant(): phrase = "Thisisstring" # Noncompliant: uses checks for equality instead of identity. if phrase != None: print(True)
def isnot_operator_compliant(): phrase = "Thisisstring" # Compliant: uses the correct mechanism for checking the identity. if phrase is not None: print(True)
https://docs.aws.amazon.com/amazonq/detector-library/python/equality-vs-identity/
Exposure of Sensitive Information CDK
High
code-quality
[ "CWE-668" ]
[ "aws-cdk", "efficiency" ]
Insecure permissions or program errors can unintentionally expose files and directories to the wrong people. For instance, private files may be accessible to unauthorized users, It's like a mix-up in who should access what, leading to resources in the wrong hands.
https://docs.aws.amazon.com/amazonq/detector-library/python/exposure-of-sensitive-information-cdk/
File injection
High
security
[ "CWE-93", "CWE-1236" ]
[ "injection", "owasp-top10" ]
Writing unsanitized user data to a file could allow injection or distributed denial of service (DDoS) attacks. Use appropriate sanitizers or validators on the user data before writing the data to a file.
https://docs.aws.amazon.com/amazonq/detector-library/python/file-injection/
Hardcoded interface binding
Medium
security
[ "CWE-605" ]
[ "availability", "networking" ]
Binding to all network interfaces can open a service up to traffic on interfaces that are not properly documented or secured. To ensure that connections from anywhere are not accepted, don't bind to '0.0.0.0' using a hardcoded reference.
https://docs.aws.amazon.com/amazonq/detector-library/python/hardcoded-bind-all-interfaces/
Hardcoded credentials
Critical
security
[ "CWE-798" ]
[ "secrets", "owasp-top10", "top25-cwes" ]
Access credentials, such as passwords and access keys, should not be hardcoded in source code. Hardcoding credentials may cause leaks even after removing them. This is because version control systems might retain older versions of the code. Credentials should be stored securely and obtained from the runtime environment.
def create_session_noncompliant(): import boto3 # Noncompliant: uses hardcoded secret access key. sample_key = "AjWnyxxxxx45xxxxZxxxX7ZQxxxxYxxx1xYxxxxx" boto3.session.Session(aws_secret_access_key=sample_key)
def create_session_compliant(): import boto3 import os # Compliant: uses environment variable for secret access key. sample_key = os.environ.get("AWS_SECRET_ACCESS_KEY") boto3.session.Session(aws_secret_access_key=sample_key)
https://docs.aws.amazon.com/amazonq/detector-library/python/hardcoded-credentials/
Hardcoded IP address
Medium
security
[]
[ "networking", "security-context" ]
We recommend that you do not hardcode IP addresses because they might change. A hardcoded IP address can make your code vulnerable to denial of service attacks and IP address spoofing to bypass security checks.
def hardcoded_ip_address_noncompliant(): sock = socket(AF_INET, SOCK_STREAM) # Noncompliant: IP address is hardcoded. sock.bind(('193.168.14.31', 80))
def hardcoded_ip_address_compliant(ip_add=None): sock = socket(AF_INET, SOCK_STREAM) # Compliant: IP address is not hardcoded. sock.bind((ip_add, 5080))
https://docs.aws.amazon.com/amazonq/detector-library/python/hardcoded-ip-address/
Inefficient new method from hashlib
High
code-quality
[]
[ "efficiency" ]
The constructors for the `hashlib` module are faster than `new()`. We recommend using `hashlib` constructors instead.
def constructor_noncompliant(): import hashlib text = "ExampleString" # Noncompliant: uses the new() constructor instead of the hashlib # constructor, which is slower. result = hashlib.new('sha256', text.encode()) print("The hexadecimal equivalent of SHA256 is : ") print(result.hexdigest())
def constructor_compliant(): import hashlib text = "ExampleString" # Compliant: uses the hashlib constructor over the new(), which is faster. result = hashlib.sha256(text.encode()) print("The hexadecimal equivalent of SHA256 is : ") print(result.hexdigest())
https://docs.aws.amazon.com/amazonq/detector-library/python/hashlib-constructor/
Improper Access Control CDK
High
code-quality
[ "CWE-284" ]
[ "aws-cdk", "efficiency" ]
Writing unsanitized user data into logs can allow malicious contents into it. Use appropriate sanitizers or validators on the user data before writing the data into logs.
https://docs.aws.amazon.com/amazonq/detector-library/python/improper-access-control-cdk/
Improper authentication
High
security
[ "CWE-287", "CWE-521", "CWE-502" ]
[ "access-control", "owasp-top10", "top25-cwes" ]
Failure to verify a user's identity results in improper authentication. This can allow an attacker to acquire privileges to access sensitive data in your application.
def improper_authentication_noncompliant(token): import jwt # Noncompliant: The verify flag is set to false. jwt.decode(token, verify=False)
def improper_authentication_compliant(token): import jwt # Compliant: The verify flag is set to true. jwt.decode(token, verify=True)
https://docs.aws.amazon.com/amazonq/detector-library/python/improper-authentication/
Improper certificate validation
High
security
[ "CWE-295" ]
[ "access-control", "cryptography", "owasp-top10" ]
Lack of validation or insufficient validation of a security certificate can lead to host impersonation and sensitive data leaks.
def create_connection_noncompliant(): import socket import ssl host, port = 'example.com', 443 with socket.socket(socket.AF_INET) as sock: context = ssl.SSLContext() # Noncompliant: security certificate validation disabled. context.verify_mode = ssl.CERT_NONE conn = context.wrap_socket(sock, server_hostname=host) try: conn.connect((host, port)) handle(conn) finally: conn.close()
def create_connection_compliant(): import socket import ssl host, port = 'example.com', 443 with socket.socket(socket.AF_INET) as sock: context = ssl.SSLContext() # Compliant: security certificate validation enabled. context.verify_mode = ssl.CERT_REQUIRED conn = context.wrap_socket(sock, server_hostname=host) try: conn.connect((host, port)) handle(conn) finally: conn.close()
https://docs.aws.amazon.com/amazonq/detector-library/python/improper-certificate-validation/
Improper error handling
Low
code-quality
[ "CWE-703" ]
[ "availability", "maintainability" ]
Improper error handling can enable attacks and lead to unwanted behavior. Parts of the system may receive unintended input, which may result in altered control flow, arbitrary control of a resource, or arbitrary code execution.
def error_handling_pass_noncompliant(): number = input("Enter number:\n") try: int(number) except Exception: # Noncompliant: has improper error handling. pass
def error_handling_compliant(): number = input("Enter number:\n") try: int(number) except ValueError: # Compliant: has proper error handling. print(number, "is not an integer.")
https://docs.aws.amazon.com/amazonq/detector-library/python/improper-error-handling/
Improper input validation
Medium
security
[ "CWE-20" ]
[ "injection", "owasp-top10", "top25-cwes" ]
Improper input validation can enable attacks and lead to unwanted behavior. Parts of the system may receive unintended input, which may result in altered control flow, arbitrary control of a resource, or arbitrary code execution.
def yaml_load_noncompliant(): import json import yaml response = yaml.dump({'a': 1, 'b': 2, 'c': 3}) # Noncompliant: uses unsafe yaml load. result = yaml.load(response) yaml.dump(result)
def yaml_load_compliant(): import json import yaml response = yaml.dump({'a': 1, 'b': 2, 'c': 3}) # Compliant: uses safe yaml load. result = yaml.load(response, Loader=yaml.CSafeLoader) yaml.dump(result)
https://docs.aws.amazon.com/amazonq/detector-library/python/improper-input-validation/
Improper privilege management
High
security
[ "CWE-269" ]
[ "access-control", "owasp-top10", "top25-cwes" ]
Privilege escalation occurs when a malicious user exploits a bug, design flaw, or configuration error in an application or operating system to gain elevated access to the system. Elevated privileges can be used to delete files, view private information, or install unwanted programs or backdoors.
def set_user_noncompliant(): import os root = 0 # Noncompliant: the process user is set to root. os.setuid(root)
def set_user_compliant(): import os root = 4 # Compliant: the process user is set to userid 4. os.setuid(root)
https://docs.aws.amazon.com/amazonq/detector-library/python/improper-privilege-management/
Improper sanitization of wildcards or matching symbols
High
security
[ "CWE-155" ]
[ "injection" ]
Unsanitized wildcards or special matching symbols in user-provided strings can enable attacks and lead to unwanted behavior, including unwanted filesystem access and denial of service.
https://docs.aws.amazon.com/amazonq/detector-library/python/improper-wildcard-sanitization/
Incorrect use of Process.terminate API
Low
code-quality
[]
[ "availability" ]
If a process that uses shared resources is terminated using `Process.terminate()`, then an exception might be thrown when another process attempts to use those shared resources.
def put_object_to_queue_noncompliant(queue): try: queue.put([42, None, 'hello']) finally: queue.task_done() def shared_queue_noncompliant(): from multiprocessing.context import Process from multiprocessing.queues import Queue queue = Queue() process = Process(target=put_object_to_queue_noncompliant, args=(queue,)) process.start() print(queue.get()) # prints "[42, None, 'hello']" # Noncompliant: uses 'Process.terminate' API on shared resources making # queue liable to become corrupted and may become unusable by other process process.terminate() # trying to access corrupt queue queue.put([50, None, 'hello'])
def put_object_to_queue_compliant(queue): try: queue.put([42, None, 'hello']) finally: queue.task_done() def shared_queue_compliant(): from multiprocessing.context import Process from multiprocessing.queues import Queue queue = Queue() process = Process(target=put_object_to_queue_compliant, args=(queue,)) process.start() print(queue.get()) # prints "[42, None, 'hello']" # Compliant: avoids using 'Process.terminate' API on shared resources # making the queue accessible. queue.join() # accessing safe queue object queue.put([50, None, 'hello'])
https://docs.aws.amazon.com/amazonq/detector-library/python/incorrect-usage-of-process-terminate-api/
Insecure connection using unencrypted protocol
High
security
[ "CWE-319" ]
[ "cryptography", "information-leak", "networking", "owasp-top10" ]
Connections that use insecure protocols transmit data in cleartext. This introduces a risk of exposing sensitive data to third parties.
def ftp_connection_noncompliant(): import ftplib # Noncompliant: insecure ftp used. cnx = ftplib.FTP("ftp://[email protected]")
def ftp_connection_compliant(): import ftplib # Compliant: secure ftp_tls used. cnx = ftplib.FTP_TLS("ftp.example.com")
https://docs.aws.amazon.com/amazonq/detector-library/python/insecure-connection/
Insecure cookie
High
security
[ "CWE-614", "CWE-311", "CWE-312" ]
[ "cookies", "cryptography", "owasp-top10" ]
Insecure cookie settings can lead to unencrypted cookie transmission. Even if a cookie doesn't contain sensitive data now, it could be added later. It's good practice to transmit all cookies only through secure channels.
def secure_cookie_noncompliant(): from http.cookies import SimpleCookie cookie = SimpleCookie() cookie['sample'] = "sample_value" # Noncompliant: the cookie is insecure. cookie['sample']['secure'] = 0 print(cookie)
def secure_cookie_compliant(): from http.cookies import SimpleCookie cookie = SimpleCookie() cookie['sample'] = "sample_value" # Compliant: the cookie is secure. cookie['sample']['secure'] = True # compliant print(cookie)
https://docs.aws.amazon.com/amazonq/detector-library/python/insecure-cookie/
Insecure CORS policy
Medium
security
[ "CWE-942" ]
[ "configuration", "owasp-top10" ]
The same-origin policy prevents Web application front-ends from loading resources that come from a different domain, protocol, or Cross-Origin Resource Sharing (CORS) policies can be used to relax this restriction. CORS policies that are too permissive may lead to loading content from untrusted or malicious sources.
from flask import app, request from flask import Flask from flask_cors import CORS app = Flask(__name__) # Noncompliant: the send_wildcard is set to allow any domain. CORS(app, send_wildcard=True)
from flask import app, request from flask import Flask from flask_cors import CORS app = Flask(__name__) # Compliant: the send_wildcard is set to allow only a specific list of # trusted domains. CORS(app, send_wildcard=False)
https://docs.aws.amazon.com/amazonq/detector-library/python/insecure-cors-policy/
Insecure cryptography
Critical
security
[ "CWE-327" ]
[ "cryptography", "owasp-top10" ]
Misuse of cryptography-related APIs can create security vulnerabilities. This includes algorithms with known weaknesses, certain padding modes, lack of integrity checks, insufficiently large key sizes, and insecure combinations of the aforementioned.
def cryptography_noncompliant(): from cryptography.hazmat.primitives import hashes, hmac import secrets # Noncompliant: keysize too small for this algorithm. key = secrets.token_bytes(12) hash_key = hmac.HMAC(key, algorithm=hashes.SHA512_224())
def cryptography_compliant(): from cryptography.hazmat.primitives import hashes, hmac import secrets # Compliant: keysize sufficient for this algorithm. key = secrets.token_bytes(48) hash_key = hmac.HMAC(key, algorithm=hashes.SHA512_224())
https://docs.aws.amazon.com/amazonq/detector-library/python/insecure-cryptography/
Weak algorithm used for Password Hashing
High
security
[ "CWE-327", "CWE-328" ]
[ "cryptography", "owasp-top10" ]
Weak algorithm used for Password Hashing. Consider using stronger algorithms, such as Argon2, PBKDF2, or scrypt.
https://docs.aws.amazon.com/amazonq/detector-library/python/insecure-hashing-hashlib/
Insecure hashing
Medium
security
[ "CWE-327", "CWE-328" ]
[ "cryptography", "owasp-top10" ]
A hashing algorithm is weak if it is easy to determine the original input from the hash or to find another input that yields the same hash. Weak hashing algorithms can lead to security vulnerabilities.
def hashing_noncompliant(): import hashlib from hashlib import pbkdf2_hmac # Noncompliant: insecure hashing algorithm used. derivedkey = hashlib.pbkdf2_hmac('sha224', password, salt, 100000) derivedkey.hex()
def hashing_compliant(): import hashlib from hashlib import pbkdf2_hmac # Compliant: secure hashing algorithm used. derivedkey = hashlib.pbkdf2_hmac('sha256', password, salt, 100000) derivedkey.hex()
https://docs.aws.amazon.com/amazonq/detector-library/python/insecure-hashing/
Insecure Socket Bind
Critical
security
[ "CWE-200" ]
[ "information-leak", "owasp-top10", "top25-cwes" ]
Binding the socket with an empty IP address will allow it to accept connections from any IPv4 address provided, thus can introduce security risks.
def insecure_socket_bind_noncompliant(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Noncompliant: Empty IP Address is passed when binding to a socket. s.bind(('', 0))
def insecure_socket_bind_compliant(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Compliant: Non-empty IP Address is passed when binding to a socket. s.bind(('192.168.1.1', 0))
https://docs.aws.amazon.com/amazonq/detector-library/python/insecure-socket-bind/
Insecure temporary file or directory
Medium
security
[ "CWE-377" ]
[ "availability", "race-condition", "owasp-top10" ]
Insecure ways of creating temporary files and directories can lead to race conditions (which can be exploited for denial of service attacks) and other security vulnerabilities such as privilege escalation.
def create_file_noncompliant(results): import tempfile # Noncompliant: uses a temporary file path to create a temporary file. filename = tempfile.mktemp() with open(filename, "w+") as f: f.write(results) print("Results written to", filename)
def create_temp_file_compliant(results): import tempfile # Compliant: uses the correct mechanism to create a temporary file. with tempfile.NamedTemporaryFile(mode="w+", delete=False) as f: f.write(results) print("Results written to", f.name)
https://docs.aws.amazon.com/amazonq/detector-library/python/insecure-temp-file/
Insufficient Logging CDK
High
code-quality
[ "CWE-778" ]
[ "aws-cdk", "efficiency" ]
Incomplete loggging of security events, like failed logins, hampers malicious behavior detection and post-attack analysis. Adopting cloud storage may need costly logging setup, causing potential gaps in crtitical audit logs, e.g., Azure defaults to logging disabled.
https://docs.aws.amazon.com/amazonq/detector-library/python/insufficient-logging-cdk/
Integer overflow
Medium
security
[ "CWE-190" ]
[ "security-context", "top25-cwes" ]
An integer overflow might occur when the input or resulting value is too large to store in associated representation. This can result in a critical security issue when it is used to make security decisions.
def integer_overflow_noncompliant(): # Noncompliant: Number larger than limit of the datatype is stored. arr = np.array([[100000000]], dtype=np.int8)
def integer_overflow_compliant(self, request_items): # Compliant: Number stored is within the limits of the specified datatype. arr = np.array([100000000], dtype=np.int32)
https://docs.aws.amazon.com/amazonq/detector-library/python/integer-overflow/
Error prone sequence modification
Medium
code-quality
[]
[ "availability", "data-integrity" ]
The iterable object for the loop expression is calculated once and remains unchanged despite any index changes caused by the sequence modification. This might lead to unexpected bugs. If you need to modify the sequence, we recommend that you first make a copy, such as by using slice notation.
def modifying_list_noncompliant(): words = ['cat', 'window', 'defenestrate'] # Noncompliant: modifies the same list while iterating over it. for word in words: if len(word) > 6: words.insert(0, word)
def modifying_list_splice_compliant(): words = ['cat', 'window', 'defenestrate'] # Compliant: creates new list using splicing, hence loops iterate on one # list, modifying a different list. for word in words[:]: if len(word) > 6: words.insert(0, word)
https://docs.aws.amazon.com/amazonq/detector-library/python/iterating-sequence-modification/
AWS client not reused in a Lambda function
Low
code-quality
[]
[ "availability", "aws-python-sdk", "aws-lambda", "efficiency" ]
Recreating AWS clients from scratch in each Lambda function invocation is expensive and can lead to availability risks. Clients should be cached across invocations.
def lambda_handler_noncompliant(event, context): import boto3 # Noncompliant: recreates AWS clients in each lambda invocation. client = boto3.client('s3') response = client.list_buckets()
import boto3 client = boto3.client('s3') def lambda_handler_compliant(event, context): # Compliant: uses the cached client. response = client.list_buckets()
https://docs.aws.amazon.com/amazonq/detector-library/python/lambda-client-reuse/
Override of reserved variable names in a Lambda function
High
security
[]
[ "availability", "aws-python-sdk", "aws-lambda", "data-integrity", "maintainability", "security-context" ]
Overriding environment variables that are reserved by AWS Lambda might lead to unexpected behavior or failure of the Lambda function.
def create_variable_noncompliant(): import os # Noncompliant: overrides reserved environment variable names # in a Lambda function. os.environ['_HANDLER'] = "value"
def create_variable_compliant(): import os # Compliant: prevents overriding reserved environment variable names # in a Lambda function. os.environ['SOME_ENV_VAR'] = "value"
https://docs.aws.amazon.com/amazonq/detector-library/python/lambda-override-reserved/
Unauthenticated LDAP requests
High
security
[ "CWE-521" ]
[ "access-control", "ldap", "owasp-top10" ]
Do not use anonymous or unauthenticated authentication mechanisms with a blind LDAP client request because they allow unauthorized access without passwords.
def authenticate_connection_noncompliant(): import ldap import os connect = ldap.initialize('ldap://127.0.0.1:1389') connect.set_option(ldap.OPT_REFERRALS, 0) # Noncompliant: authentication disabled. connect.simple_bind('cn=root')
def authenticate_connection_compliant(): import ldap import os connect = ldap.initialize('ldap://127.0.0.1:1389') connect.set_option(ldap.OPT_REFERRALS, 0) # Compliant: simple security authentication used. connect.simple_bind('cn=root', os.environ.get('LDAP_PASSWORD'))
https://docs.aws.amazon.com/amazonq/detector-library/python/ldap-authentication/
LDAP injection
High
security
[ "CWE-90" ]
[ "injection", "ldap", "owasp-top10" ]
An LDAP query that relies on potentially untrusted inputs might allow attackers to inject unwanted elements into the query. This can allow attackers to read or modify sensitive data, run code, and perform other unwanted actions.
from flask import app @app.route('/getUsers') def get_users_noncompliant(): import ldap from flask import request username = request.args['username'] filter_string = '(uid=' + username + ')' ldap_conn = ldap.initialize('ldaps://ldap.amazon.com:636') # Noncompliant: user-supplied filter is not sanitized. result = ldap_conn.search_s('o=amazon.com', ldap.SCOPE_SUBTREE, filter_string) return result
from flask import app @app.route('/getUsers') def get_users_compliant(request): import ldap import re from flask import request username = request.args['username'] # Compliant: user-supplied filter is checked for allowed characters. filter_string = "(uid=" + re.sub('[!@#$%^&*()_+-=]', '', username) + ")" ldap_conn = ldap.initialize('ldaps://ldap.amazon.com:636') result = ldap_conn.search('o=amazon.com', ldap.SCOPE_SUBTREE, filter_string) return result
https://docs.aws.amazon.com/amazonq/detector-library/python/ldap-injection/
Leaky subprocess timeout
Medium
code-quality
[]
[ "availability", "resource-leak" ]
If the process doesn't terminate after `timeout` seconds, a `TimeoutExpired` exception is raised. Because the child process does not end if the timeout expires, to properly clean up you must explicitly end the child process and finish communication.
def subprocess_timeout_noncompliant(): import subprocess process = subprocess.Popen("ls -al", bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: # Noncompliant: fails to terminate the child process before # the timeout expires. outs, errs = process.communicate(timeout=15) except subprocess.TimeoutExpired: print("Timed out")
def subprocess_timeout_compliant(): import subprocess process = subprocess.Popen("ls -al", bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: # Compliant: makes sure to terminate the child process when # the timeout expires. outs, errs = process.communicate(timeout=15) except subprocess.TimeoutExpired: process.kill() outs, errs = process.communicate()
https://docs.aws.amazon.com/amazonq/detector-library/python/leaky-subprocess-timeout/
Log injection
High
security
[ "CWE-117", "CWE-93" ]
[ "data-integrity", "injection", "owasp-top10" ]
User-provided inputs must be sanitized before they are logged. An attacker can use unsanitized input to break a log's integrity, forge log entries, or bypass log monitors.
def logging_noncompliant(): filename = input("Enter a filename: ") # Noncompliant: unsanitized input is logged. logger.info("Processing %s", filename)
def logging_compliant(): filename = input("Enter a filename: ") if filename.isalnum(): # Compliant: input is validated before logging. logger.info("Processing %s", filename)
https://docs.aws.amazon.com/amazonq/detector-library/python/log-injection/
Loose file permissions
High
security
[ "CWE-732", "CWE-266" ]
[ "access-control", "information-leak", "owasp-top10", "top25-cwes" ]
File and directory permissions should be granted to specific users and groups. Granting permissions to wildcards, such as everyone or others, can lead to privilege escalations, leakage of sensitive information, and inadvertently running malicious code.
def change_file_permissions_noncompliant(): import os import stat # Noncompliant: permissions assigned to all users. os.chmod("sample.txt", stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
def change_file_permissions_compliant(): import os import stat # Compliant: permissions assigned to owner and owner group. os.chmod("sample.txt", stat.S_IRWXU | stat.S_IRWXG)
https://docs.aws.amazon.com/amazonq/detector-library/python/loose-file-permissions/
Missing Authentication for Critical Function CDK
High
code-quality
[ "CWE-306" ]
[ "amazon-s3", "aws-cdk", "efficiency" ]
When authentication checks are not applied, users are able to access data or perform actions that they should not be allowed to access or perform. The lack of authentication checks can cause the exposure of information, denial of service, and arbitrary code execution. We recommend that you apply authentication checks to all access points.
https://docs.aws.amazon.com/amazonq/detector-library/python/missing-authentication-for-critical-function-cdk/
Missing Authorization CDK
High
security
[ "CWE-285" ]
[ "amazon-s3", "aws-cdk", "efficiency" ]
The endpoint is potentially accessible to not authorized users. If it contains sensitive information, like log files for example, it may lead to privilege escalation.
https://docs.aws.amazon.com/amazonq/detector-library/python/missing-authorization-cdk/
Missing authorization
High
security
[ "CWE-862" ]
[ "owasp-top10", "top25-cwes" ]
We recommend that you apply access control checks to all access points. When access control checks are not applied, users are able to access data or perform actions that they should not be allowed to access or perform. The lack of access control checks can cause the exposure of information, denial of service, and arbitrary code execution.
https://docs.aws.amazon.com/amazonq/detector-library/python/missing-authorization/
AWS missing encryption of sensitive data cdk
High
security
[ "CWE-311" ]
[ "amazon-s3", "aws-cdk", "efficiency" ]
Failing to implement robust data encryption undermines the security guarantees of confidentiality, integrity, and accountability provided by effective encryption practices.
https://docs.aws.amazon.com/amazonq/detector-library/python/missing-encryption-of-sensitive-data-cdk/
Missing none check on response metadata
Medium
code-quality
[]
[ "availability", "aws-python-sdk", "data-integrity", "maintainability" ]
Response metadata was not checked to verify that it is not `None`. This could be a bug.
def none_check_noncompliant(): import boto3 ddb_client = boto3.client('dynamodb') response = ddb_client.update_item() # Noncompliant: does not check to verify if the ResponseMetadata is None. return response.get("ResponseMetadata", {})
def none_check_compliant(self, record_dicts: List[Dict]) -> Dict: import boto3 kinesis_client = boto3.client('kinesis') response = kinesis_client.put_records(record_dicts) # Compliant: checks to verify if the response metadata is None. response_metadata = response.get('ResponseMetadata', {}) if response_metadata is not None: return response_metadata else: return response
https://docs.aws.amazon.com/amazonq/detector-library/python/missing-none-check/
Missing pagination
Medium
security
[ "CWE-19" ]
[ "aws-python-sdk", "data-integrity", "security-context" ]
Missing pagination on a paginated call can lead to inaccurate results. One must paginate to ensure additional results are not present, before returning the results.
def s3_loop_noncompliant(s3bucket_name, s3prefix_name): import boto3 s3_client = boto3.resource('s3').meta.client # Noncompliant: loops through the contents without checking whether # more requests are needed. list_object_response = s3_client.list_objects_v2(Bucket=s3bucket_name, Prefix=s3prefix_name) try: if 'Contents' in list_object_response: s3_deployment_folders = list_object_response['Contents'] return s3_deployment_folders except ListException: print("List objects in bucket {} with prefix {} " "failed with response {}".format(s3bucket_name, s3prefix_name, list_object_response))
def s3_recursion_compliant(self, s3bucket_name, s3prefix_name, token=None): import boto3 s3_client = boto3.client('s3') list_object_response = s3_client.list_objects_v2( Bucket=s3bucket_name, Prefix=s3prefix_name, ContinuationToken=token ) if token else s3_client.list_objects_v2(Bucket=s3bucket_name, Prefix=s3prefix_name) s3_deployment_folders = list_object_response['Contents'] # Compliant: keeps requesting until no more requests are needed. if not list_object_response['IsTruncated']: return s3_deployment_folders next_response = self.s3_recursion_compliant(s3bucket_name, s3prefix_name, list_object_response ['NextContinuationToken']) s3_deployment_folders += next_response return s3_deployment_folders
https://docs.aws.amazon.com/amazonq/detector-library/python/missing-pagination/
Module injection
High
security
[ "CWE-706" ]
[ "injection", "owasp-top10" ]
Untrusted user imports in Python allow an attacker to load arbitrary code. To prevent malicious code from running, only allow imports from trusted libraries or from libraries on allow lists.
def module_injection_noncompliant(): import importlib module_name = input('module name') # Noncompliant: Untrusted user input is being passed to `import_module`. importlib.import_module(module_name)
def module_injection_compliant(): import importlib allowed_module_names_list = ['example_module1', 'example_module2'] module_name = input('module name') if module_name in allowed_module_names_list: # Compliant: User input is validated before using in `import_module()`. importlib.import_module(module_name)
https://docs.aws.amazon.com/amazonq/detector-library/python/module-injection/
Multidimensional list initialization using replication is error prone
Low
code-quality
[]
[ "maintainability" ]
Replicating a `list` using replication operator creates references to the existing objects, not copies, which could introduce bugs. We recommend that you create a `list` of the desired length and then fill in each element with a newly created `list`, or use `list` comprehension.
def error_prone_multidimensional_list_noncompliant(): # Noncompliant: initialises a multidimensional list using replication. multi_dimension_list = [[1]]*3
def error_prone_multidimensional_list_compliant(): # Compliant: avoids initialising a multidimensional list using replication. multi_dimension_list = [[1 for x in range(2)] for y in range(3)]
https://docs.aws.amazon.com/amazonq/detector-library/python/multidimension-list-using-replication/
Multiple values in return statement is prone to error
Low
code-quality
[]
[ "maintainability" ]
Methods that return multiple values can be difficult to read and prone to error. Return a small class or `namedtuple` instance instead.
def unpack_multiple_values_noncompliant(): # Noncompliant: uses larger number of return values # making it prone to errors. return 'a', 'abc', 100, [0, 1, 2]
def unpack_multiple_values_compliant(): # Compliant: avoids using larger number of return values # making it less prone to errors. return 'abc', 100, [0, 1, 2]
https://docs.aws.amazon.com/amazonq/detector-library/python/multiple-values-in-return/
Deadlocks caused by improper multiprocessing API usage
Medium
code-quality
[]
[ "availability", "concurrency", "subprocess" ]
Invoking improper multiprocessing APIs with the wrong parameters might lead to a deadlock. The deadlock can result when the child process generates enough output to block the OS pipe buffer and waits for it to accept more data.
def deadlock_prevention_noncompliant(): from subprocess import Popen, PIPE process = Popen('sh ~/example.sh', stdout=PIPE) # Noncompliant: uses the 'Popen.wait' with 'stdout=PIPE' or 'stderr=PIPE', # resulting in a potential deadlock and busy loop. process.wait() print(process.returncode)
def deadlock_prevention_compliant(): from subprocess import Popen, PIPE process = Popen('sh ~/example.sh', stdout=PIPE) # Compliant: uses 'Popen.communicate' method, avoiding a # potential deadlock and busy loop. process.communicate()[0] print(process.returncode)
https://docs.aws.amazon.com/amazonq/detector-library/python/multiprocessing-deadlock-prevention/
Garbage collection prevention in multiprocessing
Medium
security
[]
[ "concurrency", "security-context", "subprocess" ]
If an object could be garbage collected in parent process and if you do not to pass it to a child process, there is a possibility of its garbage collection. This can happen even if the child process is alive.
def garbage_collect_noncompliant(self): from multiprocessing import Pipe pipe = Pipe() try: # Trigger a refresh. self.assertFalse( client._MongoReplicaSetClient__monitor.isAlive()) client.disconnect() self.assertSoon( lambda: client._MongoReplicaSetClient__monitor.isAlive()) client.db.collection.find_one() except Exception: traceback.print_exc() pipe.send(True) def multiprocessing_noncompliant(): from multiprocessing import Process, Pipe parent_connection, child_connection = Pipe() # Noncompliant: fails to pass the parent process object to child processes. process = Process(target=garbage_collect_noncompliant) process.start()
def garbage_collect_compliant(self, pipe): try: # Trigger a refresh. self.assertFalse( client._MongoReplicaSetClient__monitor.isAlive()) client.disconnect() self.assertSoon( lambda: client._MongoReplicaSetClient__monitor.isAlive()) client.db.collection.find_one() except Exception: traceback.print_exc() pipe.send(True) def multiprocessing_compliant(): from multiprocessing import Process, Pipe parent_connection, child_connection = Pipe() # Compliant: parent process object is passed to its child processes. process = Process(target=garbage_collect_compliant, args=(child_connection,)) process.start()
https://docs.aws.amazon.com/amazonq/detector-library/python/multiprocessing-garbage-collection-prevention/
Mutually exclusive call
High
security
[]
[ "security-context" ]
Calls to mutually exclusive methods were found in the code. This could indicate a bug or a deeper problem.
def get_metrics_noncompliant() -> None: import boto3 client = boto3.client('cloudwatch', region_name='eu-west-1') datapoints = client.get_metric_statistics( Namespace='CloudWatchSdkTest', MetricName='PythonBotoTestMetric', Dimensions=[ { 'Name': 'DimensionName', 'Value': 'DimensionValue' }, ], EndTime=datetime.datetime.now(datetime.timezone.utc), StartTime=EndTime - datetime.timedelta(days=1), Period=300, # Noncompliant: calls mutually exclusive methods. Statistics=[ 'SampleCount', 'Average', 'Sum', 'Minimum', 'Maximum' ], ExtendedStatistics=[ 'p70' ] )
def get_metrics_compliant() -> None: import boto3 client = boto3.client('cloudwatch', region_name='eu-west-1') datapoints = client.get_metric_statistics( Namespace='CloudWatchSdkTest', MetricName='PythonBotoTestMetric', Dimensions=[ { 'Name': 'DimensionName', 'Value': 'DimensionValue' }, ], EndTime=datetime.datetime.now(datetime.timezone.utc), StartTime=EndTime - datetime.timedelta(days=1), Period=300, # Compliant: avoid calling mutually exclusive methods. ExtendedStatistics=[ 'p99', 'p100' ] )
https://docs.aws.amazon.com/amazonq/detector-library/python/mutually-exclusive-calls-found/
Time zone aware datetimes
Low
code-quality
[]
[ "availability", "data-integrity" ]
Naive datetime objects are treated by many datetime methods as local times and might cause time zone related issues.
def datetime_noncompliant(): from datetime import datetime # Noncompliant: datetime method does not specify timezone, # resulting in time zone related issues. return datetime.now()
def datetime_compliant(): from datetime import datetime, timezone # Compliant: datetime method specifies the time zone, # avoiding the time zone related issues. return datetime.now(tz=timezone.utc)
https://docs.aws.amazon.com/amazonq/detector-library/python/naive-datatime-time-zone-issues/
Usage of an API that is not recommended - High Severity
High
security
[]
[ "security-context" ]
APIs that are not recommended were found. This could indicate a deeper problem in the code. High Severity
https://docs.aws.amazon.com/amazonq/detector-library/python/not-recommended-apis-high/
Usage of an API that is not recommended - Low Severity
Low
security
[]
[ "security-context" ]
APIs that are not recommended were found. This could indicate a deeper problem in the code - Low Severity.
https://docs.aws.amazon.com/amazonq/detector-library/python/not-recommended-apis-low/
Usage of an API that is not recommended - Medium Severity
Medium
security
[]
[ "security-context" ]
APIs that are not recommended were found. This could indicate a deeper problem in the code - Medium Severity.
https://docs.aws.amazon.com/amazonq/detector-library/python/not-recommended-apis-medium/
Usage of an API that is not recommended
High
security
[]
[ "security-context" ]
APIs that are not recommended were found. This could indicate a deeper problem in the code.
import xml.sax class ContentHandler(xml.sax.ContentHandler): def __init__(self): xml.sax.ContentHandler.__init__(self) def start_element(self, name, attributes): print('start:', name) def end_element(self, name): print('end:', name) def characters(self, characters): print('characters:', characters) def recommended_apis_noncompliant(): xml_string = "<body>XML_STRING</body>" # Noncompliant: uses xml.sax which is an unrecommended API. xml.sax.parseString(xml_string, ContentHandler()) if __name__ == "__main__": recommended_apis_noncompliant()
import xml import defusedxml.sax class ContentHandler(xml.sax.ContentHandler): def __init__(self): xml.sax.ContentHandler.__init__(self) def start_element(self, name, attributes): print('start:', name) def end_element(self, name): print('end:', name) def characters(self, characters): print('characters:', characters) def not_recommended_apis_compliant(): xml_string = "<body>XML_STRING</body>" # Compliant: avoids using unrecommended APIs. defusedxml.sax.parseString(xml_string, ContentHandler()) if __name__ == "__main__": not_recommended_apis_compliant()
https://docs.aws.amazon.com/amazonq/detector-library/python/not-recommended-apis/
Notebook best practice violation
Low
code-quality
[]
[ "maintainability", "machine-learning" ]
A set of best practices are recommended to keep notebooks clean and concise for better maintainability.
https://docs.aws.amazon.com/amazonq/detector-library/python/notebook-best-practice-violation/
Notebook invalid execution order
Medium
code-quality
[]
[ "machine-learning", "correctness" ]
Variable used prior to definition when the notebook is run in order of it's execution
https://docs.aws.amazon.com/amazonq/detector-library/python/notebook-invalid-execution-order/
Notebook variable redefinition
Medium
code-quality
[]
[ "machine-learning" ]
A variable is re-defined in multiple cells with different types. This can cause unexpected behaviours if the order of execution is changed.
https://docs.aws.amazon.com/amazonq/detector-library/python/notebook-variable-redefinition/
Direct dict object modification
Low
code-quality
[]
[ "maintainability" ]
Modifying `object.__dict__` directly or writing to an instance of a class `__dict__` attribute directly is not recommended. Inside every module is a `__dict__` attribute which contains its symbol table. If you modify `object.__dict__`, then the symbol table is changed. Also, direct assignment to the `__dict__` attribute is not possible.
def modify_dictionary_noncompliant(): import os # Noncompliant: modifies the __dict__ object directly. os.__dict__ = value
def modify_dictionary_compliant(test_args): from nettles_service.models.baseline import Baseline baseline = Baseline(**test_args) for arg, value in test_args.items(): # Compliant: avoids modifying the __dict__ object directly. assert baseline.__dict__[arg] == value
https://docs.aws.amazon.com/amazonq/detector-library/python/object-dict-modification/
URL redirection to untrusted site
High
security
[ "CWE-601" ]
[ "top25-cwes", "owasp-top10" ]
An HTTP parameter could contain a URL value and cause the web application to redirect the request to the specified URL. By modifying the URL value to a malicious site, an attacker could successfully launch a phishing attack and steal user credentials.
https://docs.aws.amazon.com/amazonq/detector-library/python/open-redirect/
OS command injection
High
security
[ "CWE-77", "CWE-78", "CWE-88" ]
[ "injection", "subprocess", "owasp-top10", "top25-cwes" ]
Constructing operating system or shell commands with unsanitized user input can lead to inadvertently running malicious code.
def exec_command_noncompliant(): from paramiko import client from flask import request address = request.args.get("address") cmd = "ping -c 1 %s" % address client = client.SSHClient() client.connect("ssh.samplehost.com") # Noncompliant: address argument is not sanitized. client.exec_command(cmd)
def exec_command_compliant(): from paramiko import client from flask import request address = request.args.get("address") # Compliant: address argument is sanitized (shell-escaped). address = shlex.quote(request.args.get("address")) cmd = "ping -c 1 %s" % address client = client.SSHClient() client.connect("ssh.samplehost.com") client.exec_command(cmd)
https://docs.aws.amazon.com/amazonq/detector-library/python/os-command-injection/
Sensitive data stored unencrypted due to partial encryption
Medium
security
[ "CWE-311" ]
[ "aws-python-sdk", "cryptography", "information-leak", "owasp-top10" ]
Encryption that is dependent on conditional logic, such as an `if...then` clause, might cause unencrypted sensitive data to be stored. If data is encrypted along some branch of a conditional statement, then encrypt data along all branches.
https://docs.aws.amazon.com/amazonq/detector-library/python/partial-encryption/
Path traversal
High
security
[ "CWE-22" ]
[ "injection", "owasp-top10", "top25-cwes" ]
Constructing path names with unsanitized user input can lead to path traversal attacks (for example, `../../..`) that allow an attacker access to file system resources.
def verify_file_path_noncompliant(): from flask import request file_path = request.args["file"] # Noncompliant: user input file path is not sanitized. file = open(file_path) file.close()
def verify_file_path_compliant(): from flask import request base_path = "/var/data/images/" file_path = request.args["file"] allowed_path = ["example_path1", "example_path2"] # Compliant: user input file path is sanitized. if file_path in allowed_path: file = open(base_path + file_path) file.close()
https://docs.aws.amazon.com/amazonq/detector-library/python/path-traversal/
Violation of PEP8 programming recommendations
Info
code-quality
[]
[ "consistency", "maintainability" ]
Following PEP8 makes your code clear and more readable. Often there are several ways to perform a similar action in Python. PEP 8 provides recommendations to remove that ambiguity and preserve consistency.
def readable_noncompliant(): # Noncompliant: violates PEP8 programming recommendations, # making it difficult to read. if not a is None: print(a)
def readable_compliant(): # Compliant: follows the PEP8 programming recommendations, # improving readability. if a is not None: print(a)
https://docs.aws.amazon.com/amazonq/detector-library/python/pep8-recommendations/
Spawning a process without main module
Medium
security
[]
[ "availability", "security-context", "subprocess" ]
Using the `spawn` or `forkserver` start method without importing the main module might lead to unexpected behavior (for example, it might cause a `RuntimeError`). Consider using if `__name__ == '__main__'` to safely import the main module and then run the function.
https://docs.aws.amazon.com/amazonq/detector-library/python/process-spawning-with-main-module/
Public method parameter validation
Medium
security
[ "CWE-20" ]
[ "null-check", "owasp-top10", "top25-cwes" ]
Public method parameters should be validated for nullness, unexpected values, and malicious values. Invalid or malicious input can compromise the system's safety.
https://docs.aws.amazon.com/amazonq/detector-library/python/public-method-parameter-validation/
Pytorch assign in place mod
Info
code-quality
[]
[ "machine-learning", "correctness" ]
A `torch.Tensor` object used with a modify in place function in an assignment statement might unintentionally overwrite the values of the calling variable.
def pytorch_assign_in_place_mod_noncompliant(): import torch x = torch.randn([2, 2]) y = torch.randn([2, 2]) # Noncompliant: in-place method is called as part of assignment statement. z = x.add_(y)
def pytorch_assign_in_place_mod_compliant(): import torch x = torch.randn([2, 2]) y = torch.randn([2, 2]) # Compliant: in-place method is not called as part of assignment statement. x.add_(y) z = x
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-assign-in-place-mod/
Pytorch avoid softmax with nllloss
Medium
code-quality
[]
[ "machine-learning", "correctness" ]
`NLLoss` requires as input log-probabilities and therefore it is not compatible with the outputs of a `Softmax` layer which produces probabilities. Consider using a `LogSoftmax`instead, or the `CrossEntropyLoss` with logits.
def pytorch_avoid_softmax_with_nllloss_rule_noncompliant(): import math import torch import torch.nn as nn # Noncompliant: `softmax` output is used directly with `NLLLoss`. m = nn.functional.softmax(dim=1) loss = nn.NLLLoss() input = torch.randn(3, 5, requires_grad=True) target = torch.tensor([1, 0, 4]) output = loss(m(input), target)
def pytorch_avoid_softmax_with_nllloss_rule_compliant(): import math import torch import torch.nn as nn # Compliant: `LogSoftmax` is used with `NLLLoss`. m = nn.LogSoftmax(dim=1) loss = nn.NLLLoss() input = torch.randn(3, 5, requires_grad=True) target = torch.tensor([1, 0, 4]) output = loss(m(input), target)
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-avoid-softmax-with-nllloss-rule/
Pytorch control sources of randomness
Medium
code-quality
[]
[ "machine-learning", "maintainability" ]
Not setting seeds for the random number generators in Pytorch can lead to reproducibility issues. Random numbers are used in the initialization of neural networks, in the shuffling of the training data, and, during training for layers such as Dropout. Not setting seeds causes the execution of the code to produce different results.
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-control-sources-of-randomness/
PyTorch create tensors directly on device
Medium
code-quality
[]
[ "machine-learning", "efficiency" ]
Creating PyTorch tensors on the CPU and then moving them to the device impacts the performance.
def pytorch_create_tensors_directly_on_device_noncompliant(): import torch t = torch.ones(list(range(1, 11)), dtype=torch.float64) # Noncompliant: tensor is created on cpu and then moved to device. t.cuda()
def pytorch_create_tensors_directly_on_device_compliant(): import torch # Compliant: tensor is directly created on device. t = torch.tensor([1, 2, 3, 4], device="cuda")
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-create-tensors-directly-on-device/
Pytorch data loader with multiple workers
Medium
code-quality
[]
[ "machine-learning", "efficiency" ]
Using DataLoader with `num_workers` greater than `0` can cause increased memory consumption over time when iterating over native Python objects such as `list` or `dict`. `Pytorch` uses multiprocessing in this scenario placing the data in shared memory. However, reference counting triggers copy-on-writes which over time increases the memory consumption. This behavior resembles a memory-leak. Using `pandas`, `numpy`, or `pyarrow` arrays solves this problem.
def pytorch_data_loader_with_multiple_workers_noncompliant(): import torch from torch.utils.data import DataLoader import numpy as np sampler = InfomaxNodeRecNeighborSampler(g, [fanout] * (n_layers), device=device, full_neighbor=True) pr_node_ids = list(sampler.hetero_map.keys()) pr_val_ind = list(np.random.choice(len(pr_node_ids), int(len(pr_node_ids) * val_pct), replace=False)) pr_train_ind = list(set(list(np.arange(len(pr_node_ids)))) .difference(set(pr_val_ind))) # Noncompliant: num_workers value is 8 and native python 'list' # is used here to store the dataset. loader = DataLoader(dataset=pr_train_ind, batch_size=batch_size, collate_fn=sampler.sample_blocks, shuffle=True, num_workers=8) optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2norm) # training loop print("start training...") for epoch in range(n_epochs): model.train()
def pytorch_data_loader_with_multiple_workers_compliant(args): import torch.optim import torchvision.datasets as datasets # Data loading code traindir = os.path.join(args.data, 'train') valdir = os.path.join(args.data, 'val') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_dataset = datasets.ImageFolder(traindir, imagenet_transforms) train_sampler = torch.utils.data.distributed\ .DistributedSampler(train_dataset) # Compliant: args.workers value is assigned to num_workers, # but native python 'list/dict' is not used here to store the dataset. train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), num_workers=args.workers, pin_memory=True, sampler=train_sampler)
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-data-loader-with-multiple-workers/
Pytorch disable gradient calculation
Medium
code-quality
[]
[ "machine-learning", "efficiency" ]
Checks if gradient calculation is disabled during evaluation.
def disable_gradient_calculation_noncompliant(): import torch # Noncompliant: disables gradient calculation using `torch.no_grad()`. with torch.no_grad(): model.eval()
def disable_gradient_calculation_compliant(): import torch # Compliant: disables gradient calculation using `torch.inference_mode()`. with torch.inference_mode(): model.eval()
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-disable-gradient-calculation/
Pytorch miss call to eval
Medium
code-quality
[]
[ "machine-learning", "correctness" ]
Checks if eval() is called before validating or testing a model. Some layers behave differently during training and evaluation.
def pytorch_miss_call_to_eval_noncompliant(model): import torch # Noncompliant: miss call to `eval()` after load. model.load_state_dict(torch.load("model.pth"))
def pytorch_miss_call_to_eval_compliant(model): model.load_state_dict(torch.load("model.pth")) # Compliant: `eval()` is called after load. model.eval()
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-miss-call-to-eval/
Pytorch miss call to zero grad
Medium
code-quality
[]
[ "machine-learning", "correctness" ]
Zero out the gradients before doing a backward pass or it would cause gradients to be accumulated instead of being replaced between mini-batches.
def pytorch_miss_call_to_zero_grad_noncompliant( model, dataloader, criterion, optimizer, i_epoch): model.train() avg_loss = 0 true_pos = 0 true_neg = 0 false_pos = 0 false_neg = 0 for i_batch, (data, offset, label) in enumerate(dataloader): output = model(data, offset) loss = criterion(output, label) # Noncompliant: gradients are not set to # zero before doing a backward pass. loss.backward() optimizer.step() avg_loss += loss.item() # train_error += torch.sum((output > 0) != label) true_pos += torch.sum((output >= 0).float() * label) false_pos += torch.sum((output >= 0).float() * (1.0 - label)) true_neg += torch.sum((output < 0).float() * (1.0 - label)) false_neg += torch.sum((output < 0).float() * label) print(f'\rEpoch {i_epoch},\ Training {i_batch+1:3d}/{len(dataloader):3d} batch, ' f'loss {loss.item():0.6f} ', end='') avg_loss /= len(dataloader) tpr = float(true_pos) / float(true_pos + false_neg) fpr = float(false_pos) / float(false_pos + true_neg) return avg_loss, tpr, fpr
def pytorch_miss_call_to_zero_grad_compliant( model, dataloader, criterion, optimizer, i_epoch): model.train() avg_loss = 0 true_pos = 0 true_neg = 0 false_pos = 0 false_neg = 0 for i_batch, (data, offset, label) in enumerate(dataloader): output = model(data, offset) loss = criterion(output, label) # Compliant: gradients are set to zero before doing a backward pass. optimizer.zero_grad() loss.backward() optimizer.step() avg_loss += loss.item() # train_error += torch.sum((output > 0) != label) true_pos += torch.sum((output >= 0).float() * label) false_pos += torch.sum((output >= 0).float() * (1.0 - label)) true_neg += torch.sum((output < 0).float() * (1.0 - label)) false_neg += torch.sum((output < 0).float() * label) print(f'\rEpoch {i_epoch},\ Training {i_batch+1:3d}/{len(dataloader):3d} batch, ' f'loss {loss.item():0.6f} ', end='') avg_loss /= len(dataloader) tpr = float(true_pos) / float(true_pos + false_neg) fpr = float(false_pos) / float(false_pos + true_neg) return avg_loss, tpr, fpr
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-miss-call-to-zero-grad/
Pytorch redundant softmax
Medium
code-quality
[]
[ "machine-learning", "correctness" ]
Detects if Softmax is used with CrossEntropyLoss. This is redundant as CrossEntropyLoss implicitly computes Softmax.
def pytorch_redundant_softmax_noncompliant(): import torch from torch import nn from torch.utils.data import DataLoader from torchvision import datasets from torchvision.transforms import ToTensor training_data = datasets.FashionMNIST( root="data", train=True, download=True, transform=ToTensor() ) test_data = datasets.FashionMNIST( root="data", train=False, download=True, transform=ToTensor() ) train_dataloader = DataLoader(training_data, batch_size=64) test_dataloader = DataLoader(test_data, batch_size=64) class NeuralNetwork(nn.Module): def __init__(self): super().__init__() self.flatten = nn.Flatten() self.linear_relu_stack = nn.Sequential( nn.Linear(28 * 28, 512), nn.ReLU(), nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 10) ) def forward(self, x): x = self.flatten(x) logits = self.linear_relu_stack(x) # Noncompliant: Softmax used with CrossEntropyLoss. logits = nn.functional.softmax(logits) return logits model = NeuralNetwork() def train_loop(dataloader, model, loss_fn, optimizer): size = len(dataloader.dataset) for batch, (x, y) in enumerate(dataloader): # Compute prediction and loss pred = model(x) loss = loss_fn(pred, y) # Backpropagation optimizer.zero_grad() loss.backward() optimizer.step() if batch % 100 == 0: loss, current = loss.item(), (batch + 1) * len(x) print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]") def test_loop(dataloader, model, loss_fn): size = len(dataloader.dataset) num_batches = len(dataloader) test_loss, correct = 0, 0 with torch.no_grad(): for x, y in dataloader: pred = model(x) test_loss += loss_fn(pred, y).item() correct += (pred.argmax(1) == y).type(torch.float).sum().item() test_loss /= num_batches correct /= size print(f"Test Error: \n Accuracy: {(100 * correct):>0.1f}%, " f"Avg loss: {test_loss:>8f} \n") loss_fn = nn.CrossEntropyLoss() learning_rate = 0.05 optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) epochs = 10 for t in range(epochs): print(f"Model - Epoch {t + 1}\n-------------------------------") train_loop(train_dataloader, model, loss_fn, optimizer) test_loop(test_dataloader, model, loss_fn) print("Done!")
def pytorch_redundant_softmax_compliant(): import torch import torch.nn as nn from transformers import BertModel, BertForSequenceClassification import default_constants class BERT(nn.Module): def __init__(self, tokenizer, bert_variant=default_constants.BERT): super(BERT, self).__init__() self.num_labels = default_constants.num_labels self.hidden_dim = default_constants.hidden_dim self.dropout_prob = default_constants.dropout_prob self.bert = BertModel.from_pretrained(bert_variant) self.bert.resize_token_embeddings(len(tokenizer)) self.dropout = nn.Dropout(self.dropout_prob).cuda() self.classifier = nn.Linear( self.hidden_dim, self.num_labels).cuda() torch.nn.init.xavier_uniform(self.classifier.weight) def forward( self, text, labels, attention_mask=None, token_type_ids=None ): outputs = self.bert( text, attention_mask=attention_mask, token_type_ids=token_type_ids ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) # Compliant: Softmax is not used with CrossEntropyLoss. loss_fct = nn.CrossEntropyLoss(weight=torch.Tensor( default_constants.class_weight)).cuda(default_constants.DEVICE) loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) return ( loss, logits, )
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-redundant-softmax/
Pytorch sigmoid before bceloss
Medium
code-quality
[]
[ "machine-learning", "correctness" ]
The computation of the bceloss using sigmoid values as inputs can be replaced by a single BCEWithLogitsLoss. By combining these two operations, Pytorch can take advantage of the log-sum-exp trick which offers better numerical stability.
def pytorch_sigmoid_before_bceloss_noncompliant(): import torch import torch.nn as nn # Noncompliant: `Sigmoid` layer followed by `BCELoss` # is not numerically robust. m = nn.Sigmoid() loss = nn.BCELoss() input = torch.randn(3, requires_grad=True) target = torch.empty(3).random_(2) output = loss(m(input), target) output.backward()
def pytorch_sigmoid_before_bceloss_compliant(): import torch import torch.nn as nn # Compliant: `BCEWithLogitsLoss` function integrates a `Sigmoid` # layer and the `BCELoss` into one class # and is numerically robust. loss = nn.BCEWithLogitsLoss() input = torch.randn(3, requires_grad=True) target = torch.empty(3).random_(2) output = loss(input, target) output.backward()
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-sigmoid-before-bceloss/
Pytorch use nondeterministic algoritm
Medium
code-quality
[]
[ "machine-learning" ]
This code uses APIs with nondeterministic operations by default which could affect reproducibility. Use torch.use_deterministic_algorithms(True) to ensure deterministic algorithms are used.
def pytorch_use_nondeterministic_algorithm_noncompliant(): import torch # Noncompliant: `torch.bmm` doesn't use deterministic algorithms # by default. torch.bmm(torch.randn(2, 2, 2).to_sparse().cuda(), torch.randn(2, 2, 2).cuda())
def pytorch_use_nondeterministic_algorithm_compliant(): import torch # Compliant: configure `torch.bmm` to use deterministic algorithms. torch.use_deterministic_algorithms(True) torch.bmm(torch.randn(2, 2, 2).to_sparse().cuda(), torch.randn(2, 2, 2).cuda())
https://docs.aws.amazon.com/amazonq/detector-library/python/pytorch-use-nondeterministic-algorithm/
Resource leak
Medium
security
[ "CWE-400", "CWE-664" ]
[ "availability", "resource-leak", "top25-cwes" ]
Allocated resources are not released properly. This can slow down or crash your system. They must be closed along all paths to prevent a resource leak.
def read_file_noncompliant(filename): file = open(filename, 'r') # Noncompliant: method returns without properly closing the file. return file.readlines()
def read_file_compliant(filename): # Compliant: file is declared using a `with` statement. with open(filename, 'r') as file: return file.readlines()
https://docs.aws.amazon.com/amazonq/detector-library/python/resource-leak/
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
69