code stringlengths 14 2.05k | label int64 0 1 | programming_language stringclasses 7
values | cwe_id stringlengths 6 14 | cwe_name stringlengths 5 98 ⌀ | description stringlengths 36 379 ⌀ | url stringlengths 36 48 ⌀ | label_name stringclasses 2
values |
|---|---|---|---|---|---|---|---|
def testEmptyShapeWithEditDistanceRaisesError(self):
para = {
"hypothesis_indices": [[]],
"hypothesis_values": ["tmp/"],
"hypothesis_shape": [],
"truth_indices": [[]],
"truth_values": [""],
"truth_shape": [],
"normalize": False,
}
# Check edit dista... | 1 | Python | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
def TestFunction():
"""Wrapper function for edit distance call."""
array_ops.gen_array_ops.EditDistance(**para) | 1 | Python | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. | https://cwe.mitre.org/data/definitions/190.html | safe |
def testSnapshotRecoveryFailsWithBadSplitNames(self, bad_split_filename):
cluster, _ = self.setup()
write_file(os.path.join(self.source_dir(), bad_split_filename))
with self.assertRaisesRegex(
ValueError, "Expected split_<local_split_index>_<global_split_index>"):
cluster.restart_dispatcher(... | 1 | Python | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def testSnapshotRecoveryFailsWithOutOfOrderSplitName(self):
cluster, _ = self.setup()
write_file(os.path.join(self.source_dir(), "split_1_0"))
with self.assertRaisesRegex(
ValueError, "The local split index 1 exceeds the global split index 0"):
cluster.restart_dispatcher() | 1 | Python | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def testAvgPoolGradSamePaddingZeroStrideZeroSize(self):
output_gradient_vals = np.array([0.39117979], dtype=np.float32)
output_gradient_vals = output_gradient_vals.reshape([1, 1, 1, 1])
with self.session() as sess:
with self.test_scope():
output_gradients = array_ops.placeholder(
... | 1 | Python | CWE-697 | Incorrect Comparison | The product compares two entities in a security-relevant context, but the comparison is incorrect, which may lead to resultant weaknesses. | https://cwe.mitre.org/data/definitions/697.html | safe |
def testParallelConcatShapeZero(self):
if not tf2.enabled():
self.skipTest("only fails in TF2")
@def_function.function
def f():
y = gen_array_ops.parallel_concat(values=[["tf"]], shape=0)
return y
with self.assertRaisesRegex(
errors.InvalidArgumentError, r"0th dimension .* ... | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def func():
y = op(**para)
return y | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def testParallelConcatFailsWithRankZeroShape(self):
op = array_ops.ParallelConcat
para = {"shape": 0, "values": [1]}
def func():
y = op(**para)
return y
with self.assertRaisesRegex(
Exception, "(rank|dimension) of .* must be greater than .* 0"
):
func() | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def testImportShapeInference(self, is_anonymous):
v = variables.Variable(1)
@def_function.function(jit_compile=True)
def foo():
return gen_lookup_ops.lookup_table_import_v2(
table_handle=v.handle, keys=[1.1, 2.2], values=1
)
with self.assertRaisesRegex(
ValueError, r"Sh... | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def foo():
return gen_lookup_ops.lookup_table_import_v2(
table_handle=v.handle, keys=[1.1, 2.2], values=1
) | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def testOutOfBoundsIndexRaisesInvalidArgument(self):
with self.assertRaisesRegex(errors.InvalidArgumentError, "out of range"):
indices = [[-1000], [405], [519], [758], [1015]]
data = [
[110.27793884277344],
[120.29475402832031],
[157.2418212890625],
[157.2626953... | 1 | Python | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | https://cwe.mitre.org/data/definitions/125.html | safe |
def testInvalidSplitLength(self):
with self.session(), self.test_scope():
tensor_list_split = list_ops.tensor_list_split(
tensor=[1], element_shape=[-1], lengths=[0]
)
with self.assertRaisesRegex(
errors.UnimplementedError, "All lengths must be positive"
):
self... | 1 | Python | CWE-697 | Incorrect Comparison | The product compares two entities in a security-relevant context, but the comparison is incorrect, which may lead to resultant weaknesses. | https://cwe.mitre.org/data/definitions/697.html | safe |
def testInvalidSplitLength(self):
with self.session(), self.test_scope():
tensor_list_split = list_ops.tensor_list_split(
tensor=[1], element_shape=[-1], lengths=[0]
)
with self.assertRaisesRegex(
errors.UnimplementedError, "All lengths must be positive"
):
self... | 1 | Python | CWE-476 | NULL Pointer Dereference | A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. | https://cwe.mitre.org/data/definitions/476.html | safe |
def testInputRank0(self):
with self.session():
with self.test_scope():
bincount = gen_math_ops.bincount(arr=6, size=804, weights=[52, 351])
with self.assertRaisesRegex(
errors.InvalidArgumentError,
(
"`weights` must be the same shape as `arr` or a length-0"
... | 1 | Python | CWE-697 | Incorrect Comparison | The product compares two entities in a security-relevant context, but the comparison is incorrect, which may lead to resultant weaknesses. | https://cwe.mitre.org/data/definitions/697.html | safe |
def upload_ssh_key(name: str, user_group: str, key: str) -> bool:
if '..' in name:
print('error: nice try')
return False
try:
key = paramiko.pkey.load_private_key(key)
except Exception as e:
print(f'error: Cannot save SSH key file: {e}')
return False
lib_path = get_config.get_config_var('main', 'lib_pat... | 1 | Python | CWE-668 | Exposure of Resource to Wrong Sphere | The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource. | https://cwe.mitre.org/data/definitions/668.html | safe |
def create_ssh_cred() -> None:
from jinja2 import Environment, FileSystemLoader
name = common.checkAjaxInput(form.getvalue('new_ssh'))
enable = common.checkAjaxInput(form.getvalue('ssh_enable'))
group = common.checkAjaxInput(form.getvalue('new_group'))
group_name = sql.get_group_name_by_id(group)
username = comm... | 1 | Python | CWE-668 | Exposure of Resource to Wrong Sphere | The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource. | https://cwe.mitre.org/data/definitions/668.html | safe |
def test_proxy_url_forgery(self):
"""The GeoNode Proxy should preserve the original request headers."""
import geonode.proxy.views
from urllib.parse import urlsplit
class Response:
status_code = 200
content = "Hello World"
headers = {
... | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def extract_ip_or_domain(url):
ip_regex = re.compile("^(?:http\:\/\/|https\:\/\/)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
domain_regex = re.compile("^(?:http\:\/\/|https\:\/\/)([a-zA-Z0-9.-]+)")
match = ip_regex.findall(url)
if len(match):
ip_address = match[0]
try:
ipaddress.... | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def extract_ip_or_domain(url):
# Decode the URL to handle percent-encoded characters
_url = remove_credentials_from_url(unquote(url))
ip_regex = re.compile("^(?:http://|https://)(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})")
domain_regex = re.compile("^(?:http://|https://)([a-zA-Z0-9.-]+)")
match =... | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def remove_credentials_from_url(url):
# Parse the URL
parsed_url = urlparse(url)
# Remove the username and password from the parsed URL
parsed_url = parsed_url._replace(netloc=parsed_url.netloc.split("@")[-1])
# Reconstruct the URL without credentials
cleaned_url = urlunparse(parsed_url)
... | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def payment_gateway_notification_event(
*, order: Order, user: UserType, message: str, payment: Payment
) -> OrderEvent:
if not _user_is_valid(user):
user = None
parameters = {"message": message}
if payment:
parameters.update({"gateway": payment.gateway, "payment_id": payment.token})
... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def _update_config_items(
cls, configuration_to_update: List[dict], current_config: List[dict]
):
super()._update_config_items(configuration_to_update, current_config)
for item in current_config:
if item.get("name") == "Notification password":
item["value"] = ... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def webhook(self, request: WSGIRequest, path: str, previous_value) -> HttpResponse:
config = self._get_gateway_config()
return handle_webhook(request, config) | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
configuration = {item["name"]: item["value"] for item in self.configuration}
self.config = GatewayConfig(
gateway_name=GATEWAY_NAME,
auto_capture=configuration[
"Automatically mark ... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def convert_adyen_price_format(value: str, currency: str):
value = Decimal(value)
precision = get_currency_precision(currency)
number_places = Decimal(10) ** -precision
return value * number_places | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def create_payment_notification_for_order(
payment: Payment, success_msg: str, failed_msg: Optional[str], is_success: bool
):
if not payment.order:
# Order is not assigned
return
msg = success_msg if is_success else failed_msg
payment_gateway_notification_event(
order=payment.or... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_cancel_or_refund(
notification: Dict[str, Any], gateway_config: GatewayConfig
):
additional_data = notification.get("additionalData")
action = additional_data.get("modification.action")
if action == "refund":
handle_refund(notification, gateway_config)
elif action == "cancel":
... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_failed_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(
payment, transaction_id, Transact... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.REFUND)
... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_webhook(request: WSGIRequest, gateway_config: "GatewayConfig"):
json_data = json.loads(request.body)
# JSON and HTTP POST notifications always contain a single NotificationRequestItem
# object.
notification = json_data.get("notificationItems")[0].get(
"NotificationRequestItem", {}
... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def get_transaction(
payment: "Payment", transaction_id: str, kind: TransactionKind,
) -> Transaction:
transaction = payment.transactions.filter(kind=kind, token=transaction_id)
return transaction | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_reversed_refund(
notification: Dict[str, Any], _gateway_config: GatewayConfig
):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(
payment, transaction_id, Tr... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def webhook_not_implemented(
notification: Dict[str, Any], gateway_config: GatewayConfig
):
adyen_id = notification.get("pspReference")
success = notification.get("success", True)
event = notification.get("eventCode")
payment = get_payment(notification.get("merchantReference"))
if not payment:
... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def validate_auth_user(headers: HttpHeaders, gateway_config: "GatewayConfig") -> bool:
username = gateway_config.connection_params["webhook_user"]
password = gateway_config.connection_params["webhook_user_password"]
auth_header = headers.get("Authorization")
if not auth_header and not username:
... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_cancellation(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.CANC... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def get_payment(payment_id: str) -> Payment:
_type, payment_id = from_global_id(payment_id)
payment = Payment.objects.prefetch_related("order").filter(id=payment_id).first()
return payment | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def create_new_transaction(notification, payment, kind):
transaction_id = notification.get("pspReference")
currency = notification.get("amount", {}).get("currency")
amount = convert_adyen_price_format(
notification.get("amount", {}).get("value"), currency
)
is_success = True if notification.... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_refund_with_data(
notification: Dict[str, Any], _gateway_config: GatewayConfig
):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, Transacti... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def validate_hmac_signature(
notification: Dict[str, Any], gateway_config: "GatewayConfig"
) -> bool:
"""
pspReference 7914073381342284
originalReference
merchantAccountCode YOUR_MERCHANT_ACCOUNT
merchantReference TestPayment-1407325143704
value 1130
currency EUR
eventCode AUTHORISA... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayConfig):
mark_capture = gateway_config.auto_capture
if mark_capture:
# If we mark order as a capture by default we don't need to handle auth actions
return
payment = get_payment(notification.get("merchantReference"... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.CAPTURE)
... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_pending(notification: Dict[str, Any], gateway_config: GatewayConfig):
mark_capture = gateway_config.auto_capture
if mark_capture:
# If we mark order as a capture by default we don't need to handle this action
return
payment = get_payment(notification.get("merchantReference"))
... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def handle_failed_refund(notification: Dict[str, Any], _gateway_config: GatewayConfig):
payment = get_payment(notification.get("merchantReference"))
if not payment:
return
transaction_id = notification.get("pspReference")
transaction = get_transaction(payment, transaction_id, TransactionKind.REF... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def create_transaction(
payment: Payment,
kind: str,
payment_information: Optional[PaymentData],
action_required: bool = False,
gateway_response: GatewayResponse = None,
error_msg=None,
) -> Transaction:
"""Create a transaction based on transaction kind and gateway response."""
# Default... | 1 | Python | CWE-203 | Observable Discrepancy | The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. | https://cwe.mitre.org/data/definitions/203.html | safe |
def test_account_reset_password_user_is_inactive(
mocked_notify, user_api_client, customer_user, channel_USD
):
user = customer_user
user.is_active = False
user.save()
variables = {
"email": customer_user.email,
"redirectUrl": "https://www.example.com",
"channel": channel_US... | 1 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | safe |
def mutate(cls, root, info: ResolveInfo, **data):
disallow_replica_in_context(info.context)
try:
setup_context_user(info.context)
except jwt.InvalidTokenError:
return cls.handle_errors(
ValidationError(
"Invalid token", code=Account... | 1 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | safe |
def test_graphql_execution_exception(monkeypatch, api_client):
def mocked_execute(*args, **kwargs):
raise IOError("Spanish inquisition")
monkeypatch.setattr("graphql.backend.core.execute_and_validate", mocked_execute)
response = api_client.post_graphql("{ shop { name }}")
assert response.status... | 1 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | safe |
def test_format_error_prints_allowed_errors():
error_cls = ALLOWED_ERRORS[0]
error = error_cls("Example error")
result = format_error(error, ())
assert result["message"] == str(error) | 1 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | safe |
def test_format_error_hides_internal_error_msg_in_production_mode():
error = ValueError("Example error")
result = format_error(error, ())
assert result["message"] == INTERNAL_ERROR_MESSAGE | 1 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | safe |
def test_format_error_prints_internal_error_msg_in_debug_mode():
error = ValueError("Example error")
result = format_error(error, ())
assert result["message"] == str(error) | 1 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | safe |
def format_error(error, handled_exceptions):
result: Dict[str, Any]
if isinstance(error, GraphQLError):
result = format_graphql_error(error)
else:
result = {"message": str(error)}
if "extensions" not in result:
result["extensions"] = {}
exc = error
while isinstance(exc,... | 1 | Python | CWE-209 | Generation of Error Message Containing Sensitive Information | The product generates an error message that includes sensitive information about its environment, users, or associated data. | https://cwe.mitre.org/data/definitions/209.html | safe |
def _raise_if_restricted_key(key):
# Prevent access to dunder-methods since this could expose access to globals through leaky
# attributes such as obj.__init__.__globals__.
if len(key) > 4 and key.isascii() and key.startswith("__") and key.endswith("__"):
raise KeyError(f"access to restricted key {k... | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def _raise_if_restricted_key(key):
# Prevent access to dunder-methods since this could expose access to globals through leaky
# attributes such as obj.__init__.__globals__.
if len(key) > 4 and key.isascii() and key.startswith("__") and key.endswith("__"):
raise KeyError(f"access to restricted key {k... | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
def _base_get_object(obj, key, default=UNSET):
value = _base_get_item(obj, key, default=UNSET)
if value is UNSET:
_raise_if_restricted_key(key)
value = default
try:
value = getattr(obj, key)
except Exception:
pass
return value | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def _base_get_object(obj, key, default=UNSET):
value = _base_get_item(obj, key, default=UNSET)
if value is UNSET:
_raise_if_restricted_key(key)
value = default
try:
value = getattr(obj, key)
except Exception:
pass
return value | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
def base_set(obj, key, value, allow_override=True):
"""
Set an object's `key` to `value`. If `obj` is a ``list`` and the `key` is the next available
index position, append to list; otherwise, pad the list of ``None`` and then append to the list.
Args:
obj (list|dict): Object to assign value to.... | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def base_set(obj, key, value, allow_override=True):
"""
Set an object's `key` to `value`. If `obj` is a ``list`` and the `key` is the next available
index position, append to list; otherwise, pad the list of ``None`` and then append to the list.
Args:
obj (list|dict): Object to assign value to.... | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
def test_get__does_not_raise_for_dict_or_list_when_path_restricted(obj, path):
assert _.get(obj, path) is None | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def test_get__does_not_raise_for_dict_or_list_when_path_restricted(obj, path):
assert _.get(obj, path) is None | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
def test_get__raises_for_objects_when_path_restricted(obj, path):
with pytest.raises(KeyError, match="access to restricted key"):
_.get(obj, path) | 1 | Python | CWE-77 | Improper Neutralization of Special Elements used in a Command ('Command Injection') | The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/77.html | safe |
def test_get__raises_for_objects_when_path_restricted(obj, path):
with pytest.raises(KeyError, match="access to restricted key"):
_.get(obj, path) | 1 | Python | CWE-94 | Improper Control of Generation of Code ('Code Injection') | The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. | https://cwe.mitre.org/data/definitions/94.html | safe |
def is_activated(self) -> bool:
return self.state == SessionState.Activated | 1 | Python | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
async def test_secure_channel_key_expiration(srv_crypto_one_cert, mocker):
timeout = 1
_, cert = srv_crypto_one_cert
clt = Client(uri_crypto_cert)
clt.secure_channel_timeout = timeout * 1000
user_cert = uacrypto.CertProperties(peer_creds['certificate'], "DER")
user_key = uacrypto.CertProperties(... | 1 | Python | CWE-287 | Improper Authentication | When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. | https://cwe.mitre.org/data/definitions/287.html | safe |
def data_received(self, data):
self._buffer += data
# try to parse the incoming data
while self._buffer:
try:
buf = Buffer(self._buffer)
try:
header = header_from_binary(buf)
except NotEnoughData:
... | 1 | Python | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
async def test_dos_server(opc):
# See issue 1013 a crafted packet triggered dos
port = opc.server.endpoint.port
async with Client(f'opc.tcp://127.0.0.1:{port}') as c:
# craft invalid packet that trigger dos
message_type, chunk_type, packet_size = [ua.MessageType.SecureOpen, b'E', 0]
... | 1 | Python | CWE-835 | Loop with Unreachable Exit Condition ('Infinite Loop') | The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. | https://cwe.mitre.org/data/definitions/835.html | safe |
def render(
self, tokens: Sequence[Token], options: OptionsDict, env: MutableMapping
) -> str:
"""Takes token stream and generates HTML.
:param tokens: list on block tokens to render
:param options: params of parser instance
:param env: additional data from parsed input
... | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def renderInlineAsText(
self,
tokens: Sequence[Token] | None,
options: OptionsDict,
env: MutableMapping,
) -> str:
"""Special kludge for image `alt` attributes to conform CommonMark spec.
Don't try to use it! Spec requires to show `alt` content with stripped mark... | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def image(
self,
tokens: Sequence[Token],
idx: int,
options: OptionsDict,
env: MutableMapping,
) -> str:
token = tokens[idx]
# "alt" attr MUST be set, even if empty. Because it's mandatory and
# should be placed on proper position for tests.
... | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def replace(state: StateCore) -> None:
if not state.md.options.typographer:
return
for token in state.tokens:
if token.type != "inline":
continue
if token.children is None:
continue
if SCOPED_ABBR_RE.search(token.content):
replace_scoped(toke... | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def smartquotes(state: StateCore) -> None:
if not state.md.options.typographer:
return
for token in state.tokens:
if token.type != "inline" or not QUOTE_RE.search(token.content):
continue
if token.children is not None:
process_inlines(token.children, state) | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def test_issue_fixes(line, title, input, expected):
md = MarkdownIt()
text = md.render(input)
print(text)
assert text.rstrip() == expected.rstrip() | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def convert_file(filename: str) -> None:
"""
Parse a Markdown file and dump the output to stdout.
"""
try:
with open(filename, "r", encoding="utf8", errors="ignore") as fin:
rendered = MarkdownIt().render(fin.read())
print(rendered, end="")
except OSError:
sys... | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def test_non_utf8():
with tempfile.TemporaryDirectory() as tempdir:
path = pathlib.Path(tempdir).joinpath("test.md")
path.write_bytes(b"\x80abc")
assert parse.main([str(path)]) == 0 | 1 | Python | NVD-CWE-Other | Other | NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset. | https://nvd.nist.gov/vuln/categories | safe |
def get(self, path: str) -> None:
parts = path.split("/")
component_name = parts[0]
component_root = self._registry.get_component_path(component_name)
if component_root is None:
self.write("not found")
self.set_status(404)
return
filename ... | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def validate_absolute_path(self, root, absolute_path):
try:
media_file_manager.get(absolute_path)
except KeyError:
LOGGER.error("MediaFileManager: Missing file %s" % absolute_path)
raise tornado.web.HTTPError(404, "not found")
return absolute_path | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def test_invalid_content_request(self):
"""Test request failure when invalid content (file) is provided."""
with mock.patch("streamlit.components.v1.components.os.path.isdir"):
declare_component("test", path=PATH)
with mock.patch("streamlit.components.v1.components.open") as m:... | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def test_invalid_component_request(self):
"""Test request failure when invalid component name is provided."""
response = self._request_component("invalid_component")
self.assertEqual(404, response.code)
self.assertEqual(b"not found", response.body) | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def test_invalid_encoding_request(self):
"""Test request failure when invalid encoded file is provided."""
with mock.patch("streamlit.components.v1.components.os.path.isdir"):
declare_component("test", path=PATH)
with mock.patch("streamlit.components.v1.components.open") as m:
... | 1 | Python | CWE-79 | Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') | The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. | https://cwe.mitre.org/data/definitions/79.html | safe |
def convert(cls, bytestring=None, *, file_obj=None, url=None, dpi=96,
parent_width=None, parent_height=None, scale=1, unsafe=False,
background_color=None, negate_colors=False,
invert_images=False, write_to=None, output_width=None,
output_height=None, *... | 1 | Python | CWE-918 | Server-Side Request Forgery (SSRF) | The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. | https://cwe.mitre.org/data/definitions/918.html | safe |
def download_url(url, proxies=None):
"""
Downloads a given url in a temporary file. This function is not safe to use in multiple processes. Its only use is
for deprecated behavior allowing to download config/models with a single url instead of using the Hub.
Args:
url (`str`): The url of the fi... | 1 | Python | CWE-377 | Insecure Temporary File | Creating and using insecure temporary files can leave application and system data vulnerable to attack. | https://cwe.mitre.org/data/definitions/377.html | safe |
def get_lm_corpus(datadir, dataset):
fn = os.path.join(datadir, "cache.pt")
fn_pickle = os.path.join(datadir, "cache.pkl")
if os.path.exists(fn):
logger.info("Loading cached dataset...")
corpus = torch.load(fn_pickle)
elif os.path.exists(fn):
logger.info("Loading cached dataset f... | 1 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
def get_lm_corpus(datadir, dataset):
fn = os.path.join(datadir, "cache.pt")
fn_pickle = os.path.join(datadir, "cache.pkl")
if os.path.exists(fn):
logger.info("Loading cached dataset...")
corpus = torch.load(fn_pickle)
elif os.path.exists(fn):
logger.info("Loading cached dataset f... | 1 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
def _load_passages(self):
logger.info(f"Loading passages from {self.index_path}")
passages_path = self._resolve_path(self.index_path, self.PASSAGE_FILENAME)
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.l... | 1 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
def _load_passages(self):
logger.info(f"Loading passages from {self.index_path}")
passages_path = self._resolve_path(self.index_path, self.PASSAGE_FILENAME)
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.l... | 1 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
def _deserialize_index(self):
logger.info(f"Loading index from {self.index_path}")
resolved_index_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index.dpr")
self.index = faiss.read_index(resolved_index_path)
resolved_meta_path = self._resolve_path(self.index_path,... | 1 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
def _deserialize_index(self):
logger.info(f"Loading index from {self.index_path}")
resolved_index_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index.dpr")
self.index = faiss.read_index(resolved_index_path)
resolved_meta_path = self._resolve_path(self.index_path,... | 1 | Python | CWE-502 | Deserialization of Untrusted Data | The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. | https://cwe.mitre.org/data/definitions/502.html | safe |
def do_test(proto_ver):
rc = 1
connect_packet = mosq_test.gen_connect("03-pub-qos2-dup-test", proto_ver=proto_ver)
connack_packet = mosq_test.gen_connack(rc=0, proto_ver=proto_ver)
mid = 1
publish_packet = mosq_test.gen_publish("topic", qos=2, mid=mid, payload="message", proto_ver=proto_ver, dup=1)... | 1 | Python | CWE-401 | Missing Release of Memory after Effective Lifetime | The product does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory. | https://cwe.mitre.org/data/definitions/401.html | safe |
def all_tests():
rc = do_test(proto_ver=4)
if rc:
return rc;
rc = do_test(proto_ver=5)
if rc:
return rc;
return 0 | 1 | Python | CWE-401 | Missing Release of Memory after Effective Lifetime | The product does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory. | https://cwe.mitre.org/data/definitions/401.html | safe |
def get_mediastatic_content(url):
if url.startswith(settings.STATIC_URL):
local_path = settings.STATIC_ROOT / url[len(settings.STATIC_URL) :]
elif url.startswith(settings.MEDIA_URL):
local_path = settings.MEDIA_ROOT / url[len(settings.MEDIA_URL) :]
else:
raise FileNotFoundError()
... | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the... | https://cwe.mitre.org/data/definitions/22.html | safe |
def get_mediastatic_content(url):
if url.startswith(settings.STATIC_URL):
local_path = settings.STATIC_ROOT / url[len(settings.STATIC_URL) :]
elif url.startswith(settings.MEDIA_URL):
local_path = settings.MEDIA_ROOT / url[len(settings.MEDIA_URL) :]
else:
raise FileNotFoundError()
... | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the... | https://cwe.mitre.org/data/definitions/22.html | safe |
def dump_content(destination, path, getter):
logging.debug(path)
content = getter(path)
if path.endswith("/"):
path = path + "index.html"
path = (Path(destination) / path.lstrip("/")).resolve()
if not Path(destination) in path.parents:
raise CommandError("Path traversal detected, ab... | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the... | https://cwe.mitre.org/data/definitions/22.html | safe |
def dump_content(destination, path, getter):
logging.debug(path)
content = getter(path)
if path.endswith("/"):
path = path + "index.html"
path = (Path(destination) / path.lstrip("/")).resolve()
if not Path(destination) in path.parents:
raise CommandError("Path traversal detected, ab... | 1 | Python | CWE-22 | Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') | The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the... | https://cwe.mitre.org/data/definitions/22.html | safe |
def _find_working_git(self):
test_cmd = 'version'
main_git = app.GIT_PATH or 'git'
log.debug(u'Checking if we can use git commands: {0} {1}', main_git, test_cmd)
_, _, exit_status = self._run_git(main_git, test_cmd)
if exit_status == 0:
log.debug(u'Using: {0}', ... | 1 | Python | CWE-78 | Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') | The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. | https://cwe.mitre.org/data/definitions/78.html | safe |
def _set_document_file_metadata(self):
self.file.open()
# Set new document file size
self.file_size = self.file.size
# Set new document file hash
self._set_file_hash()
self.file.seek(0) | 1 | Python | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
def _set_document_file_metadata(self):
self.file.open()
# Set new document file size
self.file_size = self.file.size
# Set new document file hash
self._set_file_hash()
self.file.seek(0) | 1 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
def _set_file_hash(self):
with self.open_file() as f:
self.file_hash = hash_filelike(f) | 1 | Python | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
def _set_file_hash(self):
with self.open_file() as f:
self.file_hash = hash_filelike(f) | 1 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
def get_file_hash(self):
if self.file_hash == "":
self._set_file_hash()
self.save(update_fields=["file_hash"])
return self.file_hash | 1 | Python | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
def get_file_hash(self):
if self.file_hash == "":
self._set_file_hash()
self.save(update_fields=["file_hash"])
return self.file_hash | 1 | Python | CWE-770 | Allocation of Resources Without Limits or Throttling | The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. | https://cwe.mitre.org/data/definitions/770.html | safe |
def test_file_hash(self):
self.assertEqual(
self.document.get_file_hash(), "7d8c4778b182e4f3bd442408c64a6e22a4b0ed85"
)
self.assertEqual(
self.pdf_document.get_file_hash(),
"7d8c4778b182e4f3bd442408c64a6e22a4b0ed85",
)
self.assertEqual(
... | 1 | Python | CWE-400 | Uncontrolled Resource Consumption | The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. | https://cwe.mitre.org/data/definitions/400.html | safe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.