code-review-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Review Security

安全代码审查

When to Use

使用场景

Activate this skill when:
  • Reviewing pull requests for security vulnerabilities
  • Auditing authentication or authorization code changes
  • Reviewing code that handles user input, file uploads, or external data
  • Checking for OWASP Top 10 vulnerabilities in new features
  • Validating that secrets are not committed to the repository
  • Scanning dependencies for known vulnerabilities
  • Reviewing API endpoints that expose sensitive data
Output: Write findings to
security-review.md
with severity, file:line, description, and recommendations.
Do NOT use this skill for:
  • Deployment infrastructure security (use
    docker-best-practices
    )
  • Incident response procedures (use
    incident-response
    )
  • General code quality review without security focus (use
    pre-merge-checklist
    )
  • Writing implementation code (use
    python-backend-expert
    or
    react-frontend-expert
    )
在以下场景中启用本技能:
  • 审查拉取请求中的安全漏洞
  • 审计认证或授权代码变更
  • 审查处理用户输入、文件上传或外部数据的代码
  • 检查新功能中的OWASP Top 10漏洞
  • 验证密钥未提交至代码仓库
  • 扫描依赖项中的已知漏洞
  • 审查暴露敏感数据的API端点
输出: 将检查结果写入
security-review.md
,包含严重等级、文件:行号、问题描述及修复建议。
请勿在以下场景使用本技能:
  • 部署基础设施安全(请使用
    docker-best-practices
  • 事件响应流程(请使用
    incident-response
  • 无安全聚焦的通用代码质量审查(请使用
    pre-merge-checklist
  • 编写实现代码(请使用
    python-backend-expert
    react-frontend-expert

Instructions

操作指南

OWASP Top 10 Checklist

OWASP Top 10 检查清单

Review every PR against the OWASP Top 10 (2021 edition). Each category below includes specific checks for Python/FastAPI and React codebases.

针对每个PR,对照2021版OWASP Top 10进行审查。以下每个类别包含针对Python/FastAPI和React代码库的具体检查项。

A01: Broken Access Control

A01: 访问控制失效

What to look for:
  • Missing authorization checks on endpoints
  • Direct object reference without ownership verification
  • Endpoints that expose data without role-based filtering
  • Missing
    Depends()
    for auth on new routes
Python/FastAPI checks:
python
undefined
检查要点:
  • 端点缺失授权校验
  • 直接对象引用未验证所有权
  • 端点未基于角色过滤暴露的数据
  • 新路由缺失
    Depends()
    认证
Python/FastAPI 检查示例:
python
undefined

BAD: No authorization check -- any authenticated user can access any user

不安全:无授权校验——任何已认证用户均可访问任意用户数据

@router.get("/users/{user_id}") async def get_user(user_id: int, db: Session = Depends(get_db)): return await user_repo.get(user_id)
@router.get("/users/{user_id}") async def get_user(user_id: int, db: Session = Depends(get_db)): return await user_repo.get(user_id)

GOOD: Verify the requesting user owns the resource or is admin

安全:验证请求用户是否拥有资源或为管理员

@router.get("/users/{user_id}") async def get_user( user_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db), ): if current_user.id != user_id and current_user.role != "admin": raise HTTPException(status_code=403, detail="Forbidden") return await user_repo.get(user_id)

**Review checklist:**
- [ ] Every route has authentication (`Depends(get_current_user)`)
- [ ] Resource access is verified against the requesting user
- [ ] Admin-only endpoints check `role == "admin"`
- [ ] List endpoints filter by user ownership (unless admin)
- [ ] No IDOR (Insecure Direct Object Reference) vulnerabilities

---
@router.get("/users/{user_id}") async def get_user( user_id: int, current_user: User = Depends(get_current_user), db: Session = Depends(get_db), ): if current_user.id != user_id and current_user.role != "admin": raise HTTPException(status_code=403, detail="Forbidden") return await user_repo.get(user_id)

**审查清单:**
- [ ] 所有路由均配置认证(`Depends(get_current_user)`)
- [ ] 资源访问需验证请求用户的所有权
- [ ] 仅管理员可访问的端点需检查`role == "admin"`
- [ ] 列表端点需按用户所有权过滤(管理员除外)
- [ ] 不存在不安全直接对象引用(IDOR)漏洞

---

A02: Cryptographic Failures

A02: 加密机制失效

What to look for:
  • Passwords stored in plaintext or with weak hashing
  • Sensitive data in logs or error messages
  • Hardcoded secrets, API keys, or tokens
  • Weak JWT configuration
Python checks:
python
undefined
检查要点:
  • 密码以明文或弱哈希算法存储
  • 敏感数据出现在日志或错误信息中
  • 硬编码密钥、API密钥或令牌
  • JWT配置存在安全隐患
Python 检查示例:
python
undefined

BAD: Weak password hashing

不安全:弱密码哈希

import hashlib password_hash = hashlib.md5(password.encode()).hexdigest()
import hashlib password_hash = hashlib.md5(password.encode()).hexdigest()

GOOD: Use bcrypt via passlib

安全:通过passlib使用bcrypt

from passlib.context import CryptContext pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") password_hash = pwd_context.hash(password)
from passlib.context import CryptContext pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") password_hash = pwd_context.hash(password)

BAD: Secret in code

不安全:代码中硬编码密钥

SECRET_KEY = "my-super-secret-key-123"
SECRET_KEY = "my-super-secret-key-123"

GOOD: Secret from environment

安全:从环境变量读取密钥

SECRET_KEY = os.environ["SECRET_KEY"]

**Review checklist:**
- [ ] Passwords hashed with bcrypt (never MD5, SHA1, or plaintext)
- [ ] JWT secret loaded from environment, not hardcoded
- [ ] Sensitive data excluded from logs (passwords, tokens, PII)
- [ ] HTTPS enforced for all external communication
- [ ] No secrets in source code (check `.env.example` has placeholders only)

---
SECRET_KEY = os.environ["SECRET_KEY"]

**审查清单:**
- [ ] 密码使用bcrypt哈希(禁止使用MD5、SHA1或明文)
- [ ] JWT密钥从环境变量加载,而非硬编码
- [ ] 日志中排除敏感数据(密码、令牌、个人可识别信息PII)
- [ ] 所有外部通信强制使用HTTPS
- [ ] 源代码中无密钥(仅在`.env.example`中保留占位符)

---

A03: Injection

A03: 注入攻击

What to look for:
  • Raw SQL queries with string interpolation
  • eval()
    ,
    exec()
    ,
    compile()
    with user input
  • subprocess
    calls with
    shell=True
  • Template injection
Python checks:
python
undefined
检查要点:
  • 使用字符串拼接的原生SQL查询
  • 结合用户输入使用
    eval()
    exec()
    compile()
  • subprocess
    调用中使用
    shell=True
  • 模板注入
Python 检查示例:
python
undefined

BAD: SQL injection via string formatting

不安全:字符串格式化导致SQL注入

query = f"SELECT * FROM users WHERE email = '{email}'" db.execute(text(query))
query = f"SELECT * FROM users WHERE email = '{email}'" db.execute(text(query))

GOOD: Parameterized query

安全:参数化查询

db.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email})
db.execute(text("SELECT * FROM users WHERE email = :email"), {"email": email})

GOOD: SQLAlchemy ORM (always parameterized)

安全:SQLAlchemy ORM(自动参数化)

user = db.query(User).filter(User.email == email).first()
user = db.query(User).filter(User.email == email).first()

BAD: Command injection

不安全:命令注入

subprocess.run(f"convert {filename}", shell=True)
subprocess.run(f"convert {filename}", shell=True)

GOOD: Pass arguments as a list

安全:以列表形式传递参数

subprocess.run(["convert", filename], shell=False)
subprocess.run(["convert", filename], shell=False)

BAD: Code execution with user input

不安全:使用用户输入执行代码

result = eval(user_input)
result = eval(user_input)

GOOD: Never eval user input. Use ast.literal_eval for safe parsing.

安全:禁止使用eval处理用户输入。如需解析字面量结构,使用ast.literal_eval。

result = ast.literal_eval(user_input) # Only for literal structures

**Review checklist:**
- [ ] No raw SQL with string interpolation (use ORM or parameterized queries)
- [ ] No `eval()`, `exec()`, or `compile()` with external input
- [ ] No `subprocess.run(..., shell=True)` with dynamic arguments
- [ ] No `pickle.loads()` on untrusted data
- [ ] All user input validated by Pydantic schemas before use

---
result = ast.literal_eval(user_input) # 仅适用于字面量结构

**审查清单:**
- [ ] 无字符串拼接的原生SQL(使用ORM或参数化查询)
- [ ] 无结合外部输入使用`eval()`、`exec()`或`compile()`的情况
- [ ] 无结合动态参数使用`subprocess.run(..., shell=True)`的情况
- [ ] 无对不可信数据使用`pickle.loads()`的情况
- [ ] 所有用户输入在使用前均通过Pydantic模式验证

---

A04: Insecure Design

A04: 不安全设计

What to look for:
  • Missing rate limiting on authentication endpoints
  • No account lockout after failed login attempts
  • Missing CAPTCHA on public-facing forms
  • Business logic flaws (e.g., negative amounts, self-privilege-escalation)
Review checklist:
  • Rate limiting on login, registration, and password reset
  • Account lockout or exponential backoff after 5+ failed attempts
  • Business logic validates constraints (positive amounts, valid transitions)
  • Sensitive operations require re-authentication

检查要点:
  • 认证端点缺失速率限制
  • 登录失败后无账户锁定机制
  • 公共表单缺失CAPTCHA
  • 业务逻辑缺陷(如负金额、自我权限提升)
审查清单:
  • 登录、注册和密码重置端点配置速率限制
  • 5次以上失败尝试后触发账户锁定或指数退避
  • 业务逻辑验证约束条件(如金额为正、有效状态转换)
  • 敏感操作需重新认证

A05: Security Misconfiguration

A05: 安全配置错误

What to look for:
  • Debug mode enabled in production
  • CORS configured with wildcard
    *
    origins
  • Default credentials or admin accounts
  • Verbose error messages exposing stack traces
Python/FastAPI checks:
python
undefined
检查要点:
  • 生产环境启用调试模式
  • CORS配置使用通配符
    *
    来源
  • 默认凭据或管理员账户未修改
  • 详细错误信息暴露堆栈跟踪
Python/FastAPI 检查示例:
python
undefined

BAD: Wide-open CORS

不安全:CORS完全开放

app.add_middleware(CORSMiddleware, allow_origins=["*"])
app.add_middleware(CORSMiddleware, allow_origins=["*"])

GOOD: Explicit allowed origins

安全:明确允许的来源

app.add_middleware( CORSMiddleware, allow_origins=["https://app.example.com"], allow_methods=["GET", "POST", "PUT", "DELETE"], allow_headers=["Authorization", "Content-Type"], )
app.add_middleware( CORSMiddleware, allow_origins=["https://app.example.com"], allow_methods=["GET", "POST", "PUT", "DELETE"], allow_headers=["Authorization", "Content-Type"], )

BAD: Debug mode in production

不安全:生产环境启用调试模式

app = FastAPI(debug=True)
app = FastAPI(debug=True)

GOOD: Debug only in development

安全:仅在开发环境启用调试

app = FastAPI(debug=settings.DEBUG) # DEBUG=False in production

**Review checklist:**
- [ ] CORS origins are explicit (no wildcard in production)
- [ ] Debug mode disabled in production configuration
- [ ] Error responses do not expose stack traces or internal details
- [ ] Default admin credentials are changed or removed
- [ ] Security headers set (X-Content-Type-Options, X-Frame-Options, etc.)

---
app = FastAPI(debug=settings.DEBUG) # 生产环境DEBUG=False

**审查清单:**
- [ ] CORS来源明确(生产环境禁用通配符)
- [ ] 生产环境配置中禁用调试模式
- [ ] 错误响应不暴露堆栈跟踪或内部细节
- [ ] 默认管理员凭据已修改或移除
- [ ] 设置安全头(X-Content-Type-Options、X-Frame-Options等)

---

A06: Vulnerable and Outdated Components

A06: 易受攻击且过时的组件

Review checklist:
  • No known CVEs in Python dependencies (
    pip-audit
    or
    safety check
    )
  • No known CVEs in npm dependencies (
    npm audit
    )
  • Dependencies pinned to specific versions in lock files
  • No deprecated packages still in use

审查清单:
  • Python依赖项中无已知CVE漏洞(使用
    pip-audit
    safety check
  • npm依赖项中无已知CVE漏洞(使用
    npm audit
  • 依赖项在锁定文件中固定为特定版本
  • 无已弃用的包仍在使用

A07: Identification and Authentication Failures

A07: 身份识别与认证失败

What to look for:
  • Weak password policies
  • Session tokens that do not expire
  • Missing multi-factor authentication for admin actions
  • JWT tokens without expiration
Python checks:
python
undefined
检查要点:
  • 弱密码策略
  • 会话令牌永不过期
  • 管理员操作缺失多因素认证
  • JWT令牌无过期时间
Python 检查示例:
python
undefined

BAD: JWT without expiration

不安全:JWT无过期时间

token = jwt.encode({"sub": user_id}, SECRET_KEY, algorithm="HS256")
token = jwt.encode({"sub": user_id}, SECRET_KEY, algorithm="HS256")

GOOD: JWT with expiration

安全:JWT配置过期时间

token = jwt.encode( {"sub": user_id, "exp": datetime.utcnow() + timedelta(minutes=30)}, SECRET_KEY, algorithm="HS256", )

**Review checklist:**
- [ ] JWT tokens have expiration (`exp` claim)
- [ ] Refresh tokens are stored securely and can be revoked
- [ ] Password policy enforces minimum length (12+) and complexity
- [ ] Session invalidation on password change or logout
- [ ] No user enumeration via login error messages

---
token = jwt.encode( {"sub": user_id, "exp": datetime.utcnow() + timedelta(minutes=30)}, SECRET_KEY, algorithm="HS256", )

**审查清单:**
- [ ] JWT令牌包含过期声明(`exp`)
- [ ] 刷新令牌安全存储且可撤销
- [ ] 密码策略强制最小长度(12位以上)及复杂度要求
- [ ] 密码修改或登出时失效会话
- [ ] 无通过登录错误信息枚举用户的情况

---

A08: Software and Data Integrity Failures

A08: 软件与数据完整性失效

Review checklist:
  • CI/CD pipeline validates artifact integrity
  • No unsigned or unverified packages
  • Deserialization of untrusted data uses safe methods (no
    pickle.loads
    )
  • Database migrations are reviewed before execution

审查清单:
  • CI/CD流水线验证工件完整性
  • 无未签名或未验证的包
  • 反序列化不可信数据使用安全方法(禁止
    pickle.loads
  • 数据库迁移在执行前经过审查

A09: Security Logging and Monitoring Failures

A09: 安全日志与监控失效

Review checklist:
  • Authentication events are logged (login, logout, failed attempts)
  • Authorization failures are logged with context
  • Sensitive data is NOT included in logs (passwords, tokens, PII)
  • Log entries include timestamp, user ID, IP address, action
  • Alerting configured for suspicious patterns (brute force, unusual access)

审查清单:
  • 认证事件已记录(登录、登出、失败尝试)
  • 授权失败事件已记录上下文信息
  • 日志中不包含敏感数据(密码、令牌、PII)
  • 日志条目包含时间戳、用户ID、IP地址、操作内容
  • 针对可疑模式(暴力破解、异常访问)配置告警

A10: Server-Side Request Forgery (SSRF)

A10: 服务器端请求伪造(SSRF)

What to look for:
  • User-supplied URLs used in server-side requests
  • Redirect endpoints that accept arbitrary URLs
Python checks:
python
undefined
检查要点:
  • 服务器端请求使用用户提供的URL
  • 重定向端点接受任意URL
Python 检查示例:
python
undefined

BAD: Fetch arbitrary URL from user input

不安全:根据用户输入获取任意URL

url = request.query_params["url"] response = httpx.get(url) # SSRF: can access internal services
url = request.query_params["url"] response = httpx.get(url) # SSRF:可访问内部服务

GOOD: Validate URL against allowlist

安全:对照允许列表验证URL

ALLOWED_HOSTS = {"api.example.com", "cdn.example.com"} parsed = urlparse(url) if parsed.hostname not in ALLOWED_HOSTS: raise HTTPException(400, "URL not allowed") response = httpx.get(url)

**Review checklist:**
- [ ] No server-side requests to user-controlled URLs without validation
- [ ] URL allowlists used for external integrations
- [ ] Internal service URLs not exposed in error messages

---
ALLOWED_HOSTS = {"api.example.com", "cdn.example.com"} parsed = urlparse(url) if parsed.hostname not in ALLOWED_HOSTS: raise HTTPException(400, "URL not allowed") response = httpx.get(url)

**审查清单:**
- [ ] 无未验证的用户控制URL用于服务器端请求
- [ ] 外部集成使用URL允许列表
- [ ] 内部服务URL未在错误信息中暴露

---

Python-Specific Security Checks

Python专属安全检查

Beyond OWASP, review Python code for these patterns:
PatternRiskFix
eval(user_input)
Remote code executionRemove or use
ast.literal_eval
pickle.loads(data)
Arbitrary code executionUse JSON or
msgpack
subprocess.run(cmd, shell=True)
Command injectionPass args as list,
shell=False
yaml.load(data)
Code executionUse
yaml.safe_load(data)
os.system(cmd)
Command injectionUse
subprocess.run([...])
Raw SQL stringsSQL injectionUse ORM or parameterized queries
hashlib.md5(password)
Weak hashingUse
bcrypt
via
passlib
jwt.decode(token, options={"verify_signature": False})
Auth bypassAlways verify signature
open(user_path)
Path traversalValidate path, use
pathlib.resolve()
tempfile.mktemp()
Race conditionUse
tempfile.mkstemp()
除OWASP外,还需检查Python代码的以下模式:
模式风险修复方案
eval(user_input)
远程代码执行移除或使用
ast.literal_eval
pickle.loads(data)
任意代码执行使用JSON或
msgpack
subprocess.run(cmd, shell=True)
命令注入以列表形式传递参数,设置
shell=False
yaml.load(data)
代码执行使用
yaml.safe_load(data)
os.system(cmd)
命令注入使用
subprocess.run([...])
原生SQL字符串SQL注入使用ORM或参数化查询
hashlib.md5(password)
弱哈希通过
passlib
使用
bcrypt
jwt.decode(token, options={"verify_signature": False})
认证绕过始终验证签名
open(user_path)
路径遍历验证路径,使用
pathlib.resolve()
tempfile.mktemp()
竞争条件使用
tempfile.mkstemp()

React-Specific Security Checks

React专属安全检查

PatternRiskFix
dangerouslySetInnerHTML
XSSUse text content or sanitize with DOMPurify
javascript:
in href
XSSValidate URLs, allow only
https:
window.location = userInput
Open redirectValidate against allowlist
Storing tokens in localStorageToken theft via XSSUse httpOnly cookies
Inline event handlers from dataXSSUse React event handlers
eval()
or
Function()
Code executionRemove entirely
Rendering user HTMLXSSUse a sanitization library
React code review:
tsx
// BAD: XSS via dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{ __html: userBio }} />

// GOOD: Sanitize first, or use text content
import DOMPurify from "dompurify";
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userBio) }} />

// BETTER: Use text content when HTML is not needed
<p>{userBio}</p>

// BAD: javascript: URL
<a href={userLink}>Click</a>  // userLink could be "javascript:alert(1)"

// GOOD: Validate protocol
const safeHref = /^https?:\/\//.test(userLink) ? userLink : "#";
<a href={safeHref}>Click</a>
模式风险修复方案
dangerouslySetInnerHTML
XSS使用文本内容或通过DOMPurify清理
javascript:
在href中
XSS验证URL,仅允许
https:
window.location = userInput
开放重定向对照允许列表验证
在localStorage中存储令牌XSS导致令牌被盗使用httpOnly Cookie
从数据生成内联事件处理程序XSS使用React事件处理程序
eval()
Function()
代码执行完全移除
渲染用户提供的HTMLXSS使用清理库
React代码审查示例:
tsx
// 不安全:通过dangerouslySetInnerHTML导致XSS
<div dangerouslySetInnerHTML={{ __html: userBio }} />

// 安全:先清理,或使用文本内容
import DOMPurify from "dompurify";
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userBio) }} />

// 更优:无需HTML时使用文本内容
<p>{userBio}</p>

// 不安全:javascript: URL
<a href={userLink}>Click</a>  // userLink可能为"javascript:alert(1)"

// 安全:验证协议
const safeHref = /^https?:\/\//.test(userLink) ? userLink : "#";
<a href={safeHref}>Click</a>

Severity Classification

严重等级分类

Classify each finding by severity for prioritization:
SeverityDescriptionExamplesSLA
CriticalExploitable remotely, no auth needed, data breachSQL injection, RCE, auth bypassBlock merge, fix immediately
HighExploitable with auth, privilege escalationIDOR, broken access control, XSS (stored)Block merge, fix before release
MediumRequires specific conditions to exploitCSRF, XSS (reflected), open redirectFix within sprint
LowDefense-in-depth, informationalMissing headers, verbose errorsFix when convenient
InfoBest practice recommendationsDependency updates, code styleTrack in backlog
为每个检查结果分类严重等级以确定优先级:
严重等级描述示例服务级别协议(SLA)
Critical(严重)可远程利用,无需认证,可导致数据泄露SQL注入、远程代码执行(RCE)、认证绕过阻止合并,立即修复
High(高)需认证才能利用,可导致权限提升IDOR、访问控制失效、存储型XSS阻止合并,发布前修复
Medium(中)需特定条件才能利用CSRF、反射型XSS、开放重定向迭代内修复
Low(低)深度防御建议,信息性缺失安全头、详细错误信息方便时修复
Info(信息)最佳实践建议依赖项更新、代码风格积压任务中跟踪

Finding Report Format

检查结果报告格式

When reporting security findings, use this format for consistency:
markdown
undefined
报告安全问题时,使用以下统一格式:
markdown
undefined

Security Finding: [Title]

安全问题:[标题]

Severity: Critical | High | Medium | Low | Info Category: OWASP A01-A10 or custom category File: path/to/file.py:42 CWE: CWE-89 (if applicable)
严重等级: Critical | High | Medium | Low | Info 类别: OWASP A01-A10 或自定义类别 文件: path/to/file.py:42 CWE: CWE-89(如适用)

Description

描述

Brief description of the vulnerability and its impact.
漏洞的简要说明及其影响。

Vulnerable Code

问题代码

python
undefined
python
undefined

The problematic code

有问题的代码

vulnerable_function(user_input)
undefined
vulnerable_function(user_input)
undefined

Recommended Fix

推荐修复方案

python
undefined
python
undefined

The secure alternative

安全替代方案

safe_function(sanitize(user_input))
undefined
safe_function(sanitize(user_input))
undefined

Impact

影响

What an attacker could achieve by exploiting this vulnerability.
攻击者利用该漏洞可实现的操作。

References

参考链接

  • Link to relevant OWASP page
  • Link to relevant CWE entry
undefined
  • 相关OWASP页面链接
  • 相关CWE条目链接
undefined

Automated Scanning

自动化扫描

Use
scripts/security-scan.py
to perform AST-based scanning for common vulnerability patterns in Python code. The script scans for:
  • eval()
    /
    exec()
    /
    compile()
    calls
  • subprocess
    with
    shell=True
  • pickle.loads()
    on potentially untrusted data
  • Raw SQL string construction
  • yaml.load()
    without
    Loader=SafeLoader
  • Hardcoded secret patterns (API keys, passwords)
  • Weak hash functions (MD5, SHA1 for passwords)
Run:
python scripts/security-scan.py --path ./app --output-dir ./security-results
Dependency scanning (run separately):
bash
undefined
使用
scripts/security-scan.py
对Python代码进行基于AST的常见漏洞模式扫描。该脚本检查:
  • eval()
    /
    exec()
    /
    compile()
    调用
  • shell=True
    subprocess
    调用
  • 对潜在不可信数据使用
    pickle.loads()
  • 原生SQL字符串构造
  • 未指定
    Loader=SafeLoader
    yaml.load()
  • 硬编码密钥模式(API密钥、密码)
  • 弱哈希函数(用于密码的MD5、SHA1)
运行命令:
python scripts/security-scan.py --path ./app --output-dir ./security-results
依赖项扫描(单独运行):
bash
undefined

Python dependencies

Python依赖项

pip-audit --requirement requirements.txt --output json > dep-audit.json
pip-audit --requirement requirements.txt --output json > dep-audit.json

npm dependencies

npm依赖项

npm audit --json > npm-audit.json
undefined
npm audit --json > npm-audit.json
undefined

Examples

示例

Example Review Comment (Critical)

审查评论示例(严重)

SECURITY: SQL Injection (Critical, OWASP A03)
File:
app/repositories/user_repository.py:47
python
query = f"SELECT * FROM users WHERE name LIKE '%{search_term}%'"
This constructs a raw SQL query with string interpolation, allowing SQL injection. An attacker could input
'; DROP TABLE users; --
to destroy data.
Fix: Use SQLAlchemy ORM filtering:
python
users = db.query(User).filter(User.name.ilike(f"%{search_term}%")).all()
安全问题:SQL注入(严重,OWASP A03)
文件:
app/repositories/user_repository.py:47
python
query = f"SELECT * FROM users WHERE name LIKE '%{search_term}%'"
该代码通过字符串拼接构造原生SQL查询,存在SQL注入风险。 攻击者可输入
'; DROP TABLE users; --
来销毁数据。
修复方案: 使用SQLAlchemy ORM过滤:
python
users = db.query(User).filter(User.name.ilike(f"%{search_term}%")).all()

Example Review Comment (Medium)

审查评论示例(中)

SECURITY: Missing Rate Limiting (Medium, OWASP A04)
File:
app/routes/auth.py:12
The
/auth/login
endpoint has no rate limiting. An attacker could perform brute-force password attacks at unlimited speed.
Fix: Add rate limiting middleware:
python
from slowapi import Limiter
limiter = Limiter(key_func=get_remote_address)

@router.post("/login")
@limiter.limit("5/minute")
async def login(request: Request, ...):
安全问题:缺失速率限制(中,OWASP A04)
文件:
app/routes/auth.py:12
/auth/login
端点未配置速率限制。攻击者可无限制地执行暴力破解密码攻击。
修复方案: 添加速率限制中间件:
python
from slowapi import Limiter
limiter = Limiter(key_func=get_remote_address)

@router.post("/login")
@limiter.limit("5/minute")
async def login(request: Request, ...):

Output File

输出文件

Write security findings to
security-review.md
:
markdown
undefined
将安全检查结果写入
security-review.md
markdown
undefined

Security Review: [Feature/PR Name]

安全审查:[功能/PR名称]

Summary

摘要

  • Critical: 0 | High: 1 | Medium: 2 | Low: 1
  • 严重:0 | 高:1 | 中:2 | 低:1

Findings

检查结果

[CRITICAL] SQL Injection in user search

[严重] 用户搜索中的SQL注入

  • File: app/routes/users.py:45
  • OWASP: A03 Injection
  • Description: Raw SQL with string interpolation
  • Recommendation: Use SQLAlchemy ORM filtering
  • 文件: app/routes/users.py:45
  • OWASP类别: A03 注入
  • 描述: 字符串拼接构造原生SQL
  • 建议: 使用SQLAlchemy ORM过滤

[HIGH] Missing authorization check

[高] 缺失授权校验

...
...

Passed Checks

通过的检查项

  • No hardcoded secrets found
  • Dependencies up to date
undefined
  • 未发现硬编码密钥
  • 依赖项已更新至最新版本
undefined