Prompt Details
Model
Chat - (gpt-6-luna)
Token size
398
Example input
[Language and Framework]: Python 3.12 / FastAPI
[Module Purpose]: User login endpoint that verifies credentials and returns a session token
[Issue or Goal]: Audit for security vulnerabilities, timing attacks, and error handling flaws
[Runtime Constraints]: Docker container behind Nginx, 2,000 requests per minute
[Code Snippet]: @app.post("/login") def login(username: str, password: str, db=Depends(get_db)): query = f"SELECT id, password_hash FROM users WHERE username = '{username}'" user = db.execute(query).fetchone() if user and user.password_hash == hashlib.md5(password.encode()).hexdigest(): token = str(random.randint(100000, 999999)) return {"status": "ok", "token": token} return {"status": "error", "message": "Invalid username or password"}
Example output
1. Prioritized Issue & Risk Matrix
Overall Security Assessment: Critical Risk – Not Production Ready
The submitted login endpoint contains multiple security vulnerabilities. The most serious are SQL injection, insecure password hashing, predictable session tokens, and timing-related authentication weaknesses.
Severity Category Location/Pattern Impact Summary
Critical Security f"SELECT ... '{username}'" SQL injection allows attackers to manipulate database queries, potentially bypassing authentication or extracting user data.
Critical Security hashlib.md5(password.encode()) MD5 is unsuitable for password storage. Fast hashing makes offline password cracking significantly easier.
Critical Security random.randint(100000, 999999) Generates predictable, low-entropy session tokens. Attackers may guess valid tokens.
High Security user[1] == hashed_password Ordinary string comparison is not designed to prevent timing attacks.
High Security if user and ... Different authentication execution paths can reveal whether a username exists through timing analysis.
High Security No token expiration or session management Tokens have no expiration, revocation, or session lifecycle management.
High Bug username: str, password: str Missing explicit validation for empty values, excessive input lengths, and malformed credentials.
High Security Credentials passed as endpoint parameters FastAPI interprets these as query parameters by default, potentially exposing credentials through URLs and access logs.
Medium Bug db.execute(query).fetchone() Database exceptions are not handled, potentially producing unstructured HTTP 500 responses.
Medium Performance Synchronous def login() Database operations can consume thread-pool capacity under concurrent traffic.
Medium Security No rate limiting Attackers can perform brute-force and credential-stuffing attacks.
Medium Security Generic error without throttling Generic error messages are good, but they do not prevent repeated authentication attempts.
Low Bug No explicit response models API response structure is not formally validated or documented.
Low Performance No explicit query optimization Username lookup performance depends on database indexing, which is not established by the snippet.
Runtime consideration: At 2,000 requests per minute (approximately 33.3 requests per second), the endpoint needs efficient database access, bounded password-hashing concurrency, and protection against authentication abuse.
2. Root-Cause Breakdown
1. SQL Injection – Critical
Problematic code:
query = f"SELECT id, password_hash FROM users WHERE username = '{username}'"
Root cause:
- Username is inserted directly into the SQL statement.
- SQL syntax is not separated from user-provided data.
- An attacker can submit specially crafted input.
Example malicious username:
' OR '1'='1' --
This can alter the intended query and potentially return an unintended user record.
Correction: Use parameterized SQL queries.
query = "SELECT id, password_hash FROM users WHERE username = ?"user = db.execute(query, (username,)).fetchone()
The placeholder syntax depends on the database driver. For SQLAlchemy, use its parameter-binding API.
2. Weak Password Hashing – Critical
Problematic code:
hashlib.md5(password.encode()).hexdigest()
Root cause:
- MD5 is designed for fast hashing, not password storage.
- It has no built-in configurable work factor.
- Attackers can test enormous numbers of password combinations quickly.
Correction: Use Argon2id through pwdlib or another maintained password-hashing library.
Example:
from pwdlib import PasswordHashpassword_hash = PasswordHash.recommended()hashed = password_hash.hash("SecurePassword123")verified = password_hash.verify("SecurePassword123", hashed)
3. Predictable Session Token – Critical
Problematic code:
token = str(random.randint(100000, 999999))
Root cause:
- Only 900,000 possible six-digit values exist.
- Python's random module is not designed for cryptographic security.
- Tokens have insufficient entropy for authentication sessions.
Correction: Generate tokens using Python's cryptographically secure secrets module.
import secretstoken = secrets.token_urlsafe(32)
This generates a substantially stronger random token.
3. Step-by-Step Refactoring Plan
The following architecture is suitable for Python 3.12, FastAPI, Docker, and Nginx.
Step 1 – Separate authentication responsibilities
Separate the login process into logical responsibilities:
Component Responsibility
FastAPI Endpoint HTTP request and response handling
Input Validation Validate usernames and passwords
Authentication Service Verify credentials
Database Layer Retrieve user records
Password Handler Secure password hashing and verification
Token Handler Generate secure session tokens
Avoid placing all authentication logic inside the endpoint.
Step 2 – Implement secure request validation
Use Pydantic models.
Requirements:
- Username cannot be empty.
- Username maximum length should be restricted.
- Password cannot be empty.
- Password maximum length should prevent excessive resource consumption.
- Credentials must be submitted through a JSON POST body.
Step 3 – Replace SQL string interpolation
Use parameterized database queries.
Benefits:
- Prevents SQL injection.
- Separates SQL instructions from user input.
- Makes query behavior predictable.
Ensure that the database username column has an appropriate index.
Step 4 – Implement Argon2id password verification
Use:
pip install "pwdlib[argon2]"
Store password hashes generated by Argon2id.
Do not compare newly generated MD5 hashes against existing database hashes. Existing accounts require a controlled password migration or password-reset process.
Step 5 – Implement timing-resistant authentication
Use:
- Constant-time password verification through the password-hashing library.
- A dummy password hash when the username does not exist.
- Consistent authentication failure messages.
- Similar authentication processing paths.
This reduces username enumeration through timing differences, although it cannot guarantee perfectly identical response times.
Step 6 – Implement secure session tokens
Use:
secrets.token_urlsafe(32)
Production session management should additionally provide:
- Token expiration.
- Token revocation.
- Server-side session storage.
- Secure token transmission.
- HTTPS enforcement through Nginx.
Step 7 – Improve error handling
Use appropriate HTTP status codes.
Situation HTTP Status
Successful login 200
Invalid credentials 401
Invalid input 422
Database unavailable 503
Unexpected internal error 500
Never expose SQL statements, database credentials, password hashes, or internal exception details to clients.
Step 8 – Implement authentication rate limiting
Configure rate limiting at the application or reverse-proxy level.
Suggested starting policy:
- 5 failed login attempts per minute per account.
- Additional IP-based throttling.
- Temporary progressive delays.
- Monitoring for credential-stuffing patterns.
Use a shared rate-limit store such as Redis when running multiple Docker workers.
Step 9 – Optimize for 2,000 requests per minute
Recommended improvements:
- Use database connection pooling.
- Index the username lookup column.
- Keep database transactions short.
- Bound concurrent Argon2 verification operations.
- Monitor CPU usage and database latency.
- Use asynchronous database operations if the application uses an asynchronous database driver.
Do not blindly increase worker count: password hashing can become CPU-intensive.
Step 10 – Add automated security testing
Test:
- SQL injection attempts.
- Invalid credentials.
- Empty and oversized input.
- Password verification.
- Database failures.
- Token uniqueness and generation.
- Authentication timing behavior.
4. Refactored Code Implementation
The following implementation preserves the original business logic:
1. Accept username and password.
2. Retrieve the corresponding user.
3. Verify the password.
4. Generate a session token.
5. Return a generic error for invalid credentials.
It uses FastAPI, Pydantic, SQLAlchemy, Argon2id, and Python's secure random generator.
Installation
pip install fastapi uvicorn sqlalchemy "pwdlib[argon2]" pytest httpx
Complete implementation – main.py
import secretsfrom typing import Annotated, Generatorfrom fastapi import Depends, FastAPI, HTTPException, statusfrom pydantic import BaseModel, ConfigDict, Fieldfrom pwdlib import PasswordHashfrom sqlalchemy import create_engine, textfrom sqlalchemy.exc import SQLAlchemyErrorfrom sqlalchemy.orm import Session, sessionmaker# --------------------------------------------------# Application configuration# --------------------------------------------------DATABASE_URL = "sqlite:///./users.db"engine = create_engine( DATABASE_URL, connect_args={"check_same_thread": False}, pool_pre_ping=True,)SessionLocal = sessionmaker( bind=engine, autoflush=False, autocommit=False,)app = FastAPI(title="Secure Authentication API")password_hasher = PasswordHash.recommended()# Used to reduce username enumeration timing differences.DUMMY_PASSWORD_HASH = password_hasher.hash(
Important production considerations
The implementation above improves the original code, but it is not a complete production session-management system.
Area Required production improvement
Database Configure production database credentials through environment variables.
Password migration Migrate existing MD5 accounts through password reset or controlled rehashing.
Sessions Store tokens server-side with expiration and revocation.
Rate limiting Add Redis-backed authentication throttling.
Token storage Store only a cryptographic hash of opaque session tokens server-side.
Nginx Enable HTTPS, appropriate security headers, and request-size limits.
Logging Log authentication failures without recording passwords or tokens.
Password hashing Benchmark Argon2id parameters under actual container CPU limits.
Important: The generated token is currently returned but not persisted or associated with a server-side session. Therefore, it is a secure random token generator, not yet a fully implemented session-management system.
5. Targeted Unit Test Cases
Use pytest and FastAPI's TestClient.
The four tests below cover:
1. Successful authentication.
2. Boundary values.
3. Invalid credentials and injection attempts.
4. Database failure recovery.
Test implementation – test_main.py
import pytestfrom fastapi.testclient import TestClientfrom sqlalchemy.exc import OperationalErrorfrom main import ( app, get_db, password_hasher,)class FakeUser: def __init__(self, user_id, password_hash): self.id = user_id self.password_hash = password_hashclass FakeResult: def __init__(self, user): self.user = user def fetchone(self): return self.userclass FakeDatabase: def __init__(self, user=None, should_fail=False): self.user = user self.should_fail = should_fail self.last_params = None def execute(self, query, params): if self.should_fail: raise OperationalError(
Execute the tests
Run the following command from the project directory:
pytest -v test_main.py
Expected test results:
Test execution summary
4 test cases
Successful login
Valid credentials return a session token.
Boundary values
Maximum permitted username and password lengths.
Invalid inputs
Empty, oversized, and SQL injection inputs.
Database failure
Database exception returns HTTP 503.
Expected outcome
4 passed
Expected results when the implementation and dependencies are configured correctly.
Final Security Assessment
Security area Original code Refactored code
SQL injection Vulnerable Parameterized
Password hashing MD5 Argon2id
Token generation Predictable Cryptographically secure
Input validation Missing Pydantic
Error handling Unstructured Structured HTTP errors
Timing protection Missing Dummy hash + secure verification
Rate limiting Missing Not implemented
Session lifecycle Missing Not implemented
Final verdict: The refactored implementation addresses the most serious vulnerabilities in the original snippet. Before production deployment, prioritize server-side session persistence, token expiration and revocation, distributed rate limiting, and load testing with realistic Argon2id settings at the target 2,000 requests per minute.
By purchasing this prompt, you agree to our terms of service
GPT-6-LUNA
Analyze a pasted code snippet or module to uncover bugs, edge-case failures, security risks, and performance bottlenecks. Outputs a prioritized severity report, root-cause explanations, a step-by-step refactoring plan, cleaner rewritten starter code, and targeted unit test cases tailored to your language, framework, and runtime constraints. Built for software engineers, indie hackers, and students debugging or cleaning up legacy code.
...more
Added 58 minutes ago
