Bootcamp week 4: Add SecureCode AI - an AI-powered code security and performance analyzer
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"""Sample functions for testing the unit test generator."""
|
||||
|
||||
|
||||
def calculate_average(numbers):
|
||||
"""Calculate the average of a list of numbers."""
|
||||
if not numbers:
|
||||
return 0
|
||||
return sum(numbers) / len(numbers)
|
||||
|
||||
|
||||
def is_palindrome(text):
|
||||
"""Check if a string is a palindrome."""
|
||||
cleaned = "".join(c.lower() for c in text if c.isalnum())
|
||||
return cleaned == cleaned[::-1]
|
||||
|
||||
|
||||
def factorial(n):
|
||||
"""Calculate factorial of a number."""
|
||||
if n < 0:
|
||||
raise ValueError("Factorial is not defined for negative numbers")
|
||||
if n == 0 or n == 1:
|
||||
return 1
|
||||
return n * factorial(n - 1)
|
||||
|
||||
|
||||
def find_max(numbers):
|
||||
"""Find the maximum number in a list."""
|
||||
if not numbers:
|
||||
raise ValueError("Cannot find max of empty list")
|
||||
max_num = numbers[0]
|
||||
for num in numbers:
|
||||
if num > max_num:
|
||||
max_num = num
|
||||
return max_num
|
||||
|
||||
|
||||
class ShoppingCart:
|
||||
"""A simple shopping cart."""
|
||||
|
||||
def __init__(self):
|
||||
self.items = []
|
||||
|
||||
def add_item(self, name, price, quantity=1):
|
||||
"""Add an item to the cart."""
|
||||
if price < 0:
|
||||
raise ValueError("Price cannot be negative")
|
||||
if quantity < 1:
|
||||
raise ValueError("Quantity must be at least 1")
|
||||
|
||||
self.items.append({"name": name, "price": price, "quantity": quantity})
|
||||
|
||||
def get_total(self):
|
||||
"""Calculate the total price of all items."""
|
||||
total = 0
|
||||
for item in self.items:
|
||||
total += item["price"] * item["quantity"]
|
||||
return total
|
||||
|
||||
def apply_discount(self, percentage):
|
||||
"""Apply a discount percentage to the total."""
|
||||
if not 0 <= percentage <= 100:
|
||||
raise ValueError("Discount percentage must be between 0 and 100")
|
||||
|
||||
total = self.get_total()
|
||||
discount = total * (percentage / 100)
|
||||
return total - discount
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Example inefficient code for testing performance analysis."""
|
||||
|
||||
# Example 1: O(n²) complexity - inefficient duplicate finder
|
||||
def find_duplicates(items):
|
||||
duplicates = []
|
||||
for i in range(len(items)):
|
||||
for j in range(i + 1, len(items)):
|
||||
if items[i] == items[j] and items[i] not in duplicates:
|
||||
duplicates.append(items[i])
|
||||
return duplicates
|
||||
|
||||
|
||||
# Example 2: Inefficient string concatenation
|
||||
def build_large_string(items):
|
||||
result = ""
|
||||
for item in items:
|
||||
result += str(item) + ","
|
||||
return result
|
||||
|
||||
|
||||
# Example 3: Unnecessary repeated calculations
|
||||
def calculate_totals(orders):
|
||||
totals = []
|
||||
for order in orders:
|
||||
total = 0
|
||||
for item in order["items"]:
|
||||
# Recalculating tax each time
|
||||
tax_rate = 0.08
|
||||
total += item["price"] * (1 + tax_rate)
|
||||
totals.append(total)
|
||||
return totals
|
||||
|
||||
|
||||
# Example 4: Loading all data into memory
|
||||
def process_large_file(filename):
|
||||
with open(filename, "r") as f:
|
||||
all_lines = f.readlines() # Loads entire file into memory
|
||||
|
||||
processed = []
|
||||
for line in all_lines:
|
||||
if "ERROR" in line:
|
||||
processed.append(line.strip())
|
||||
return processed
|
||||
|
||||
|
||||
# Example 5: N+1 query problem simulation
|
||||
def get_user_posts(user_ids):
|
||||
posts = []
|
||||
for user_id in user_ids:
|
||||
# Simulates making a separate database query for each user
|
||||
user_posts = fetch_posts_for_user(user_id) # N queries
|
||||
posts.extend(user_posts)
|
||||
return posts
|
||||
|
||||
|
||||
def fetch_posts_for_user(user_id):
|
||||
# Simulate database query
|
||||
return [f"Post from user {user_id}"]
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Example vulnerable code for testing security analysis."""
|
||||
|
||||
# Example 1: SQL Injection vulnerability
|
||||
def get_user_by_id(user_id):
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("users.db")
|
||||
query = f"SELECT * FROM users WHERE id = {user_id}"
|
||||
result = conn.execute(query).fetchone()
|
||||
return result
|
||||
|
||||
|
||||
# Example 2: Command Injection
|
||||
def ping_host(hostname):
|
||||
import os
|
||||
|
||||
command = f"ping -c 1 {hostname}"
|
||||
os.system(command)
|
||||
|
||||
|
||||
# Example 3: Path Traversal
|
||||
def read_file(filename):
|
||||
file_path = f"/var/data/{filename}"
|
||||
with open(file_path, "r") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
# Example 4: Hardcoded credentials
|
||||
def connect_to_database():
|
||||
import psycopg2
|
||||
|
||||
connection = psycopg2.connect(
|
||||
host="localhost", database="mydb", user="admin", password="admin123"
|
||||
)
|
||||
return connection
|
||||
|
||||
|
||||
# Example 5: Insecure random number generation
|
||||
def generate_token():
|
||||
import random
|
||||
|
||||
return "".join([str(random.randint(0, 9)) for _ in range(32)])
|
||||
Reference in New Issue
Block a user