Security Review
SentryOfficialPublished by Sentry
- Skill
- Review and audit
- Security
- CC-BY-SA-4.0
- Medium risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The Security Review skill provides a structured approach to auditing code for security vulnerabilities. It emphasizes deep research into data flow and context to distinguish between theoretical risks and truly exploitable issues. By focusing on attacker-controlled inputs and framework-specific mitigations, it reduces false positives and ensures that reported findings are actionable and high-confidence.
What it does
- Performs systematic security audits on provided code snippets or files.
- Traces data flow to confirm if inputs are attacker-controlled or server-controlled.
- Evaluates code against common vulnerability patterns like injection, XSS, and authentication flaws.
- Filters out false positives by checking for framework-level protections and sanitization.
- Categorizes findings by severity and confidence levels.
- Provides a standardized reporting format for identified vulnerabilities.
When to use it
- When you need to audit code for potential security vulnerabilities.
- When performing an OWASP-based security review.
- When you need to verify if a specific code pattern is exploitable.
- When checking for common security issues like SQL injection, XSS, or insecure authentication.
Advantages
- Reduces noise by filtering out theoretical issues and server-controlled configurations.
- Ensures high-confidence reporting by requiring codebase research before flagging.
- Provides clear, actionable remediation advice for identified vulnerabilities.
- Standardizes the security review process across different codebases.
Usage examples
- “Perform a security review on this file: [code snippet]”
- The agent will analyze the code, trace the data flow of inputs, and provide a report of any high-confidence vulnerabilities found, or state that none were identified.
- “Check this API endpoint for potential injection vulnerabilities.”
- The agent will examine the endpoint's input handling and database queries to determine if user input is properly parameterized or sanitized.
- “Audit this authentication logic for security issues.”
- The agent will review the authentication implementation against best practices, such as password storage algorithms and brute-force protections.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/getsentry/security-review/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip security-review.zip -d .agents/skills
Documentation by Sentry
<!-- Reference material based on OWASP Cheat Sheet Series (CC BY-SA 4.0) https://cheatsheetseries.owasp.org/ -->
Security Review Skill
Identify exploitable security vulnerabilities in code. Report only HIGH CONFIDENCE findings—clear vulnerable patterns with attacker-controlled input.
Scope: Research vs. Reporting
CRITICAL DISTINCTION:
Report on: Only the specific file, diff, or code provided by the user
Research: The ENTIRE codebase to build confidence before reporting
Before flagging any issue, you MUST research the codebase to understand:
Where does this input actually come from? (Trace data flow)
Is there validation/sanitization elsewhere?
How is this configured? (Check settings, config files, middleware)
What framework protections exist?
Do NOT report issues based solely on pattern matching. Investigate first, then report only what you're confident is exploitable.
Confidence Levels
| Level | Criteria | Action |
|---|---|---|
| HIGH | Vulnerable pattern + attacker-controlled input confirmed | Report with severity |
| MEDIUM | Vulnerable pattern, input source unclear | Note as "Needs verification" |
| LOW | Theoretical, best practice, defense-in-depth | Do not report |
Do Not Flag
General Rules
Test files (unless explicitly reviewing test security)
Dead code, commented code, documentation strings
Patterns using constants or server-controlled configuration
Code paths that require prior authentication to reach (note the auth requirement instead)
Server-Controlled Values (NOT Attacker-Controlled)
These are configured by operators, not controlled by attackers:
| Source | Example | Why It's Safe |
|---|---|---|
| Django settings | settings.API_URL, settings.ALLOWED_HOSTS | Set via config/env at deployment |
| Environment variables | os.environ.get('DATABASE_URL') | Deployment configuration |
| Config files | config.yaml, app.config['KEY'] | Server-side files |
| Framework constants | django.conf.settings.* | Not user-modifiable |
| Hardcoded values | BASE_URL = "https://api.internal" | Compile-time constants |
SSRF Example - NOT a vulnerability:
# SAFE: URL comes from Django settings (server-controlled)
response = requests.get(f"{settings.SEER_AUTOFIX_URL}{path}")SSRF Example - IS a vulnerability:
# VULNERABLE: URL comes from request (attacker-controlled)
response = requests.get(request.GET.get('url'))Framework-Mitigated Patterns
Check language guides before flagging. Common false positives:
| Pattern | Why It's Usually Safe |
|---|---|
Django {{ variable }} | Auto-escaped by default |
React {variable} | Auto-escaped by default |
Vue {{ variable }} | Auto-escaped by default |
User.objects.filter(id=input) | ORM parameterizes queries |
cursor.execute("...%s", (input,)) | Parameterized query |
innerHTML = "<b>Loading...</b>" | Constant string, no user input |
Only flag these when:
Django:
{{ var|safe }},{% autoescape off %},mark_safe(user_input)React:
dangerouslySetInnerHTML={{__html: userInput}}Vue:
v-html="userInput"ORM:
.raw(),.extra(),RawSQL()with string interpolation
Review Process
1. Detect Context
What type of code am I reviewing?
| Code Type | Load These References |
|---|---|
| API endpoints, routes | authorization.md, authentication.md, injection.md |
| Django/DRF views, permission classes, object-level access | Use the django-access-review skill if available for access control; otherwise authorization.md |
| Frontend, templates | xss.md, csrf.md, modern-threats.md (DOM clobbering, prototype pollution) |
| File handling, uploads | file-security.md |
| Crypto, secrets, tokens | cryptography.md, data-protection.md |
| Data serialization | deserialization.md |
| External requests | ssrf.md |
| Business workflows | business-logic.md |
| GraphQL, REST design | api-security.md |
| Config, headers, CORS | misconfiguration.md |
| CI/CD, dependencies | supply-chain.md |
| Error handling | error-handling.md |
| Audit, logging | logging.md |
Object merging/cloning, __proto__, DOM id/name lookups, WebSocket handlers, LLM prompt construction | modern-threats.md |
2. Load Language Guide
Based on file extension or imports:
| Indicators | Guide |
|---|---|
.py, django, flask, fastapi | languages/python.md |
.js, .ts, express, react, vue, next | languages/javascript.md |
For other languages there is no dedicated guide; rely on the references/ files and verify framework protections directly in the codebase.
3. Load Infrastructure Guide (if applicable)
| File Type | Guide |
|---|---|
Dockerfile, .dockerignore | infrastructure/docker.md |
| GitHub Actions workflows | Use the gha-security-review skill if available; otherwise references/supply-chain.md |
| Other CI/CD pipelines, lockfiles, package manifests | references/supply-chain.md |
4. Research Before Flagging
For each potential issue, research the codebase to build confidence:
Where does this value actually come from? Trace the data flow.
Is it configured at deployment (settings, env vars) or from user input?
Is there validation, sanitization, or allowlisting elsewhere?
What framework protections apply?
Only report issues where you have HIGH confidence after understanding the broader context.
5. Verify Exploitability
For each potential finding, confirm:
Is the input attacker-controlled?
| Attacker-Controlled (Investigate) | Server-Controlled (Usually Safe) |
|---|---|
request.GET, request.POST, request.args | settings.X, app.config['X'] |
request.json, request.data, request.body | os.environ.get('X') |
request.headers (most headers) | Hardcoded constants |
request.cookies (unsigned) | Internal service URLs from config |
URL path segments: /users/<id>/ | Database content from admin/system |
| File uploads (content and names) | Signed session data |
| Database content from other users | Framework settings |
| WebSocket messages |
Does the framework mitigate this?
Check language guide for auto-escaping, parameterization
Check for middleware/decorators that sanitize
Is there validation upstream?
Input validation before this code
Sanitization libraries (DOMPurify, bleach, etc.)
6. Report HIGH Confidence Only
Skip theoretical issues. Report only what you've confirmed is exploitable after research.
Severity Classification
| Severity | Impact | Examples |
|---|---|---|
| Critical | Direct exploit, severe impact, no auth required | RCE, SQL injection to data, auth bypass, hardcoded secrets |
| High | Exploitable with conditions, significant impact | Stored XSS, SSRF to metadata, IDOR to sensitive data |
| Medium | Specific conditions required, moderate impact | Reflected XSS, CSRF on state-changing actions, path traversal |
| Low | Defense-in-depth, minimal direct impact | Missing headers, verbose errors, weak algorithms in non-critical context |
Quick Patterns Reference
Always Flag (Critical)
eval(user_input) # Any language
exec(user_input) # Any language
pickle.loads(user_data) # Python
yaml.load(user_data) # Python (not safe_load)
unserialize($user_data) # PHP
deserialize(user_data) # Java ObjectInputStream
shell=True + user_input # Python subprocess
child_process.exec(user) # Node.jsAlways Flag (High)
innerHTML = userInput # DOM XSS
dangerouslySetInnerHTML={user} # React XSS
v-html="userInput" # Vue XSS
f"SELECT * FROM x WHERE {user}" # SQL injection
`SELECT * FROM x WHERE ${user}` # SQL injection
os.system(f"cmd {user_input}") # Command injectionAlways Flag (Secrets)
password = "hardcoded"
api_key = "sk-..."
AWS_SECRET_ACCESS_KEY = "..."
private_key = "-----BEGIN"Check Context First (MUST Investigate Before Flagging)
# SSRF - ONLY if URL is from user input, NOT from settings/config
requests.get(request.GET['url']) # FLAG: User-controlled URL
requests.get(settings.API_URL) # SAFE: Server-controlled config
requests.get(f"{settings.BASE}/{x}") # CHECK: Is 'x' user input?
# Path traversal - ONLY if path is from user input
open(request.GET['file']) # FLAG: User-controlled path
open(settings.LOG_PATH) # SAFE: Server-controlled config
open(f"{BASE_DIR}/{filename}") # CHECK: Is 'filename' user input?
# Open redirect - ONLY if URL is from user input
redirect(request.GET['next']) # FLAG: User-controlled redirect
redirect(settings.LOGIN_URL) # SAFE: Server-controlled config
# Weak crypto - ONLY if used for security purposes
hashlib.md5(file_content) # SAFE: File checksums, caching
hashlib.md5(password) # FLAG: Password hashing
random.random() # SAFE: Non-security uses (UI, sampling)
random.random() for token # FLAG: Security tokens need secrets moduleOutput Format
## Security Review: [File/Component Name]
### Summary
- **Findings**: X (Y Critical, Z High, ...)
- **Risk Level**: Critical/High/Medium/Low
- **Confidence**: High/Mixed
### Findings
#### [VULN-001] [Vulnerability Type] (Severity)
- **Location**: `file.py:123`
- **Confidence**: High
- **Issue**: [What the vulnerability is]
- **Impact**: [What an attacker could do]
- **Evidence**:
```python
[Vulnerable code snippet]Fix: [How to remediate]
Needs Verification
[VERIFY-001] [Potential Issue]
Location:
file.py:456Question: [What needs to be verified]
If no vulnerabilities found, state: "No high-confidence vulnerabilities identified."
---
## Reference Files
### Core Vulnerabilities (`references/`)
| File | Covers |
|------|--------|
| `injection.md` | SQL, NoSQL, OS command, LDAP, template injection |
| `xss.md` | Reflected, stored, DOM-based XSS |
| `authorization.md` | Authorization, IDOR, privilege escalation |
| `authentication.md` | Sessions, credentials, password storage |
| `cryptography.md` | Algorithms, key management, randomness |
| `deserialization.md` | Pickle, YAML, Java, PHP deserialization |
| `file-security.md` | Path traversal, uploads, XXE |
| `ssrf.md` | Server-side request forgery |
| `csrf.md` | Cross-site request forgery |
| `data-protection.md` | Secrets exposure, PII, logging |
| `api-security.md` | REST, GraphQL, mass assignment |
| `business-logic.md` | Race conditions, workflow bypass |
| `modern-threats.md` | Prototype pollution, LLM injection, WebSocket |
| `misconfiguration.md` | Headers, CORS, debug mode, defaults |
| `error-handling.md` | Fail-open, information disclosure |
| `supply-chain.md` | Dependencies, build security |
| `logging.md` | Audit failures, log injection |
### Language Guides (`languages/`)
- `python.md` - Django, Flask, FastAPI patterns
- `javascript.md` - Node, Express, React, Vue, Next.js
### Infrastructure (`infrastructure/`)
- `docker.md` - Container securityFiles
- ATTRIBUTION.mdAdded by AutoGineer902 B
- LICENSE884 B
- SKILL.md11.5 KiB
- SPEC.md8.8 KiB
- infrastructure/docker.md9.2 KiB
- languages/javascript.md9.8 KiB
- languages/python.md9.3 KiB
- references/api-security.md12.4 KiB
- references/authentication.md8.9 KiB
- references/authorization.md9.8 KiB
- references/business-logic.md12.4 KiB
- references/cryptography.md8.5 KiB
- references/csrf.md9.7 KiB
- references/data-protection.md9.3 KiB
- references/deserialization.md10.0 KiB
- references/error-handling.md11.4 KiB
- references/file-security.md12.1 KiB
- references/injection.md6.7 KiB
- references/logging.md11.7 KiB
- references/misconfiguration.md10.1 KiB
- references/modern-threats.md13.0 KiB
- references/ssrf.md10.5 KiB
- references/supply-chain.md8.9 KiB
- references/xss.md7.4 KiB
references/business-logic.md
Business Logic Security Reference
Overview
Business logic vulnerabilities occur when the application's logic can be manipulated to achieve unintended outcomes. Unlike technical vulnerabilities, these flaws exploit legitimate functionality in unexpected ways.
Common Vulnerability Types
1. Race Conditions
Time-of-Check to Time-of-Use (TOCTOU)
# VULNERABLE: Race condition in balance check
def transfer(from_account, to_account, amount):
if from_account.balance >= amount: # Check
time.sleep(0.1) # Simulating processing delay
from_account.balance -= amount # Use
to_account.balance += amount
# Attack: Two concurrent transfers can overdraft
# SAFE: Atomic operation with locking
from threading import Lock
account_locks = {}
def transfer(from_account, to_account, amount):
# Acquire locks in consistent order to prevent deadlock
locks = sorted([from_account.id, to_account.id])
with account_locks[locks[0]], account_locks[locks[1]]:
if from_account.balance >= amount:
from_account.balance -= amount
to_account.balance += amount
return True
return FalseDatabase-Level Locking
# SAFE: Database transaction with SELECT FOR UPDATE
from django.db import transaction
@transaction.atomic
def transfer(from_account_id, to_account_id, amount):
from_account = Account.objects.select_for_update().get(id=from_account_id)
to_account = Account.objects.select_for_update().get(id=to_account_id)
if from_account.balance >= amount:
from_account.balance -= amount
to_account.balance += amount
from_account.save()
to_account.save()
return True
return False2. Workflow Bypass
# VULNERABLE: Multi-step process without server-side tracking
# Step 1: /verify-email
# Step 2: /set-password
# Step 3: /complete-registration
# Attacker skips to Step 3
# SAFE: Server-side state machine
class RegistrationFlow:
STATES = ['email_pending', 'email_verified', 'password_set', 'complete']
def __init__(self, user_id):
self.state = self.get_state(user_id)
def verify_email(self, token):
if self.state != 'email_pending':
raise InvalidStateError("Email verification not pending")
# Verify token...
self.set_state('email_verified')
def set_password(self, password):
if self.state != 'email_verified':
raise InvalidStateError("Email not verified")
# Set password...
self.set_state('password_set')
def complete(self):
if self.state != 'password_set':
raise InvalidStateError("Password not set")
# Complete registration...
self.set_state('complete')3. Numeric Manipulation
Integer Overflow
# VULNERABLE: Integer overflow in quantity
def calculate_total(quantity, price):
return quantity * price
# Attack: quantity = -1 results in negative price (refund)
# SAFE: Validate numeric ranges
def calculate_total(quantity, price):
if quantity <= 0 or quantity > MAX_QUANTITY:
raise ValueError("Invalid quantity")
if price <= 0:
raise ValueError("Invalid price")
return quantity * priceFloating Point Issues
# VULNERABLE: Floating point precision loss
total = 0.0
for item in items:
total += item.price * item.quantity
# 0.1 + 0.2 = 0.30000000000000004
# SAFE: Use Decimal for financial calculations
from decimal import Decimal, ROUND_HALF_UP
total = Decimal('0')
for item in items:
total += Decimal(str(item.price)) * item.quantity
# Round properly
total = total.quantize(Decimal('.01'), rounding=ROUND_HALF_UP)4. Price/Discount Manipulation
# VULNERABLE: Trust client-submitted price
@app.route('/checkout', methods=['POST'])
def checkout():
price = request.json['price'] # Client can set any price!
process_payment(price)
# SAFE: Calculate price server-side
@app.route('/checkout', methods=['POST'])
def checkout():
cart = get_cart(current_user.id)
price = calculate_total(cart) # Always server-calculated
process_payment(price)# VULNERABLE: Stackable discounts without limits
def apply_discounts(cart, discount_codes):
for code in discount_codes:
discount = get_discount(code)
cart.total -= discount.amount
# Attack: Apply same code multiple times, negative total
# SAFE: Limit discount application
def apply_discounts(cart, discount_codes):
# Remove duplicates
unique_codes = set(discount_codes)
total_discount = Decimal('0')
for code in unique_codes:
if is_code_used(cart.user_id, code):
continue # Code already used
discount = get_discount(code)
total_discount += discount.amount
mark_code_used(cart.user_id, code)
# Cap discount at total
max_discount = cart.subtotal * Decimal('0.5') # Max 50% off
final_discount = min(total_discount, max_discount)
cart.total -= final_discount5. Inventory/Resource Exhaustion
# VULNERABLE: No reservation during checkout
def checkout(cart):
for item in cart.items:
if get_stock(item.product_id) >= item.quantity:
# Stock available
pass
# Processing takes time...
process_payment()
for item in cart.items:
reduce_stock(item.product_id, item.quantity) # May oversell
# SAFE: Reserve inventory atomically
@transaction.atomic
def checkout(cart):
for item in cart.items:
product = Product.objects.select_for_update().get(id=item.product_id)
if product.stock < item.quantity:
raise InsufficientStock(product.name)
product.stock -= item.quantity # Reserve immediately
product.save()
# If payment fails, transaction rolls back
process_payment()6. Time-Based Attacks
# VULNERABLE: Expired coupon still usable with timing attack
def apply_coupon(code):
coupon = Coupon.objects.get(code=code)
if coupon.expiry > datetime.now():
return coupon.discount
raise CouponExpired()
# SAFE: Use database time, not application time
from django.db.models.functions import Now
def apply_coupon(code):
coupon = Coupon.objects.annotate(
is_valid=Q(expiry__gt=Now())
).get(code=code)
if not coupon.is_valid:
raise CouponExpired()
return coupon.discount7. Parameter Tampering
# VULNERABLE: Trust hidden form fields
# HTML: <input type="hidden" name="user_id" value="123">
@app.route('/update-profile', methods=['POST'])
def update_profile():
user_id = request.form['user_id'] # Attacker can change this!
User.query.get(user_id).update(...)
# SAFE: Use session-based user identification
@app.route('/update-profile', methods=['POST'])
def update_profile():
user_id = current_user.id # From authenticated session
User.query.get(user_id).update(...)Detection Patterns
State Machine Validation
class OrderStateMachine:
VALID_TRANSITIONS = {
'draft': ['submitted'],
'submitted': ['approved', 'rejected'],
'approved': ['shipped'],
'shipped': ['delivered', 'returned'],
'delivered': ['returned'],
'rejected': [],
'returned': ['refunded'],
'refunded': []
}
def transition(self, order, new_state):
current = order.state
if new_state not in self.VALID_TRANSITIONS.get(current, []):
raise InvalidTransition(f"Cannot go from {current} to {new_state}")
order.state = new_state
log_state_change(order, current, new_state)Idempotency
# SAFE: Idempotent operations with idempotency keys
import hashlib
def process_request(request_data, idempotency_key):
# Check if request was already processed
existing = ProcessedRequest.query.filter_by(key=idempotency_key).first()
if existing:
return existing.response # Return cached response
# Process request
result = do_processing(request_data)
# Store for future duplicate requests
ProcessedRequest.create(key=idempotency_key, response=result)
return resultRate Limiting Business Actions
# Limit business-critical actions
from functools import wraps
import time
def rate_limit_action(action_name, limit, window):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
user_id = current_user.id
key = f"action:{action_name}:{user_id}"
count = redis.incr(key)
if count == 1:
redis.expire(key, window)
if count > limit:
raise RateLimitExceeded(f"Too many {action_name} attempts")
return f(*args, **kwargs)
return wrapper
return decorator
@rate_limit_action('password_reset', limit=3, window=3600)
def request_password_reset(email):
pass
@rate_limit_action('transfer', limit=10, window=86400)
def transfer_funds(from_account, to_account, amount):
passValidation Patterns
Server-Side Calculation
# Always recalculate on server
def calculate_order_total(order):
subtotal = Decimal('0')
for item in order.items:
# Get current price from database, not from request
product = Product.query.get(item.product_id)
subtotal += product.price * item.quantity
# Apply tax
tax = subtotal * get_tax_rate(order.shipping_address)
# Apply discounts (validated server-side)
discount = calculate_discounts(order, order.discount_codes)
# Calculate total
total = subtotal + tax - discount
# Sanity checks
if total < Decimal('0'):
raise InvalidOrderError("Negative total")
if discount > subtotal:
raise InvalidOrderError("Discount exceeds subtotal")
return {
'subtotal': subtotal,
'tax': tax,
'discount': discount,
'total': total
}Business Rule Enforcement
class TransferValidator:
def validate(self, transfer):
errors = []
# Check transfer limits
if transfer.amount > MAX_SINGLE_TRANSFER:
errors.append("Exceeds single transfer limit")
# Check daily limits
daily_total = get_daily_transfer_total(transfer.from_account)
if daily_total + transfer.amount > DAILY_LIMIT:
errors.append("Exceeds daily transfer limit")
# Check velocity (unusual number of transfers)
recent_count = get_recent_transfer_count(transfer.from_account, hours=1)
if recent_count > MAX_TRANSFERS_PER_HOUR:
errors.append("Too many transfers in short period")
# Check for unusual patterns
if is_unusual_recipient(transfer.from_account, transfer.to_account):
errors.append("Unusual recipient - requires verification")
if errors:
raise ValidationError(errors)Grep Patterns for Detection
# Race condition indicators
grep -rn "sleep\|time\.sleep\|Thread\|async" --include="*.py"
grep -rn "balance\|inventory\|stock" --include="*.py" | grep -v "select_for_update\|lock"
# Price/amount from request
grep -rn "request\.\w*\[.*price\|request\.\w*\[.*amount\|request\.\w*\[.*total" --include="*.py"
# Missing validation
grep -rn "def checkout\|def purchase\|def transfer" --include="*.py"
# Floating point for money
grep -rn "float.*price\|float.*amount\|float.*balance" --include="*.py"Testing Checklist
[ ] Race conditions tested (concurrent requests)
[ ] Workflow steps enforced server-side
[ ] State transitions validated
[ ] Prices/totals calculated server-side
[ ] Discount limits enforced
[ ] Inventory checked and reserved atomically
[ ] Integer overflow/underflow prevented
[ ] Decimal used for financial calculations
[ ] Time-based logic uses server/database time
[ ] Hidden field values not trusted
[ ] Idempotency keys for critical operations
[ ] Rate limits on business-critical actions
[ ] Unusual patterns detected and flagged
References
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs an API key, Needs Python
Security
What our scanner noticed· Medium risk
- References to credential files
- Instructions that use the network
- Encoded commands that are executed
- Downloads piped into a shell
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Sentry
- Publisher
- Sentry (Official)
- Source
- getsentry/skills · skills/security-review · commit e94f222
- Licence
- Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Sentry.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download security-review.zip