security-testing
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSecurity Testing
安全测试
<default_to_action>
When testing security or conducting audits:
- TEST OWASP Top 10 vulnerabilities systematically
- VALIDATE authentication and authorization on every endpoint
- SCAN dependencies for known vulnerabilities (npm audit)
- CHECK for injection attacks (SQL, XSS, command)
- VERIFY secrets aren't exposed in code/logs
Quick Security Checks:
- Access control → Test horizontal/vertical privilege escalation
- Crypto → Verify password hashing, HTTPS, no sensitive data exposed
- Injection → Test SQL injection, XSS, command injection
- Auth → Test weak passwords, session fixation, MFA enforcement
- Config → Check error messages don't leak info
Critical Success Factors:
- Think like an attacker, build like a defender
- Security is built in, not added at the end
- Test continuously in CI/CD, not just before release </default_to_action>
<default_to_action>
在测试安全性或执行审计时:
- 系统性测试OWASP Top 10漏洞
- 验证每个端点的身份验证与授权机制
- 扫描依赖项以发现已知漏洞(npm audit)
- 检查注入攻击(SQL、XSS、命令注入)
- 验证密钥未在代码/日志中暴露
快速安全检查:
- 访问控制 → 测试水平/垂直权限提升
- 加密 → 验证密码哈希、HTTPS配置,确保敏感数据未暴露
- 注入 → 测试SQL注入、XSS、命令注入
- 身份验证 → 测试弱密码、会话固定、MFA强制验证
- 配置 → 检查错误信息未泄露敏感数据
关键成功因素:
- 像攻击者一样思考,像防御者一样构建
- 安全是内置的,而非后期添加
- 在CI/CD中持续测试,而非仅在发布前测试 </default_to_action>
Quick Reference Card
快速参考卡片
When to Use
适用场景
- Security audits and penetration testing
- Testing authentication/authorization
- Validating input sanitization
- Reviewing security configuration
- 安全审计与渗透测试
- 测试身份验证/授权机制
- 验证输入清理逻辑
- 审核安全配置
OWASP Top 10 (2021)
OWASP Top 10(2021)
| # | Vulnerability | Key Test |
|---|---|---|
| 1 | Broken Access Control | User A accessing User B's data |
| 2 | Cryptographic Failures | Plaintext passwords, HTTP |
| 3 | Injection | SQL/XSS/command injection |
| 4 | Insecure Design | Rate limiting, session timeout |
| 5 | Security Misconfiguration | Verbose errors, exposed /admin |
| 6 | Vulnerable Components | npm audit, outdated packages |
| 7 | Auth Failures | Weak passwords, no MFA |
| 8 | Integrity Failures | Unsigned updates, malware |
| 9 | Logging Failures | No audit trail for breaches |
| 10 | SSRF | Server fetching internal URLs |
| 序号 | 漏洞类型 | 核心测试点 |
|---|---|---|
| 1 | Broken Access Control | 普通用户访问其他用户的数据 |
| 2 | Cryptographic Failures | 明文密码、HTTP传输 |
| 3 | Injection | SQL/XSS/命令注入 |
| 4 | Insecure Design | 速率限制、会话超时 |
| 5 | Security Misconfiguration | 详细错误信息、暴露的/admin端点 |
| 6 | Vulnerable Components | npm audit检测、过时依赖包 |
| 7 | Auth Failures | 弱密码、未启用MFA |
| 8 | Integrity Failures | 未签名的更新、恶意软件 |
| 9 | Logging Failures | 无 breach审计追踪 |
| 10 | SSRF | 服务器获取内部URL |
Tools
工具
| Type | Tool | Purpose |
|---|---|---|
| SAST | SonarQube, Semgrep | Static code analysis |
| DAST | OWASP ZAP, Burp | Dynamic scanning |
| Deps | npm audit, Snyk | Dependency vulnerabilities |
| Secrets | git-secrets, TruffleHog | Secret scanning |
| 类型 | 工具 | 用途 |
|---|---|---|
| SAST | SonarQube, Semgrep | 静态代码分析 |
| DAST | OWASP ZAP, Burp | 动态扫描 |
| 依赖检测 | npm audit, Snyk | 依赖项漏洞检测 |
| 密钥扫描 | git-secrets, TruffleHog | 密钥泄露扫描 |
Agent Coordination
Agent协同
- : Multi-layer SAST/DAST scanning
qe-security-scanner - : API security testing
qe-api-contract-validator - : Security code review
qe-quality-analyzer
- : 多层SAST/DAST扫描
qe-security-scanner - : API安全测试
qe-api-contract-validator - : 安全代码评审
qe-quality-analyzer
Key Vulnerability Tests
核心漏洞测试
1. Broken Access Control
1. 访问控制失效
javascript
// Horizontal escalation - User A accessing User B's data
test('user cannot access another user\'s order', async () => {
const userAToken = await login('userA');
const userBOrder = await createOrder('userB');
const response = await api.get(`/orders/${userBOrder.id}`, {
headers: { Authorization: `Bearer ${userAToken}` }
});
expect(response.status).toBe(403);
});
// Vertical escalation - Regular user accessing admin
test('regular user cannot access admin', async () => {
const userToken = await login('regularUser');
expect((await api.get('/admin/users', {
headers: { Authorization: `Bearer ${userToken}` }
})).status).toBe(403);
});javascript
// Horizontal escalation - User A accessing User B's data
test('user cannot access another user\'s order', async () => {
const userAToken = await login('userA');
const userBOrder = await createOrder('userB');
const response = await api.get(`/orders/${userBOrder.id}`, {
headers: { Authorization: `Bearer ${userAToken}` }
});
expect(response.status).toBe(403);
});
// Vertical escalation - Regular user accessing admin
test('regular user cannot access admin', async () => {
const userToken = await login('regularUser');
expect((await api.get('/admin/users', {
headers: { Authorization: `Bearer ${userToken}` }
})).status).toBe(403);
});2. Injection Attacks
2. 注入攻击
javascript
// SQL Injection
test('prevents SQL injection', async () => {
const malicious = "' OR '1'='1";
const response = await api.get(`/products?search=${malicious}`);
expect(response.body.length).toBeLessThan(100); // Not all products
});
// XSS
test('sanitizes HTML output', async () => {
const xss = '<script>alert("XSS")</script>';
await api.post('/comments', { text: xss });
const html = (await api.get('/comments')).body;
expect(html).toContain('<script>');
expect(html).not.toContain('<script>');
});javascript
// SQL Injection
test('prevents SQL injection', async () => {
const malicious = "' OR '1'='1";
const response = await api.get(`/products?search=${malicious}`);
expect(response.body.length).toBeLessThan(100); // Not all products
});
// XSS
test('sanitizes HTML output', async () => {
const xss = '<script>alert("XSS")</script>';
await api.post('/comments', { text: xss });
const html = (await api.get('/comments')).body;
expect(html).toContain('<script>');
expect(html).not.toContain('<script>');
});3. Cryptographic Failures
3. 加密机制失效
javascript
test('passwords are hashed', async () => {
await db.users.create({ email: 'test@example.com', password: 'MyPassword123' });
const user = await db.users.findByEmail('test@example.com');
expect(user.password).not.toBe('MyPassword123');
expect(user.password).toMatch(/^\$2[aby]\$\d{2}\$/); // bcrypt
});
test('no sensitive data in API response', async () => {
const response = await api.get('/users/me');
expect(response.body).not.toHaveProperty('password');
expect(response.body).not.toHaveProperty('ssn');
});javascript
test('passwords are hashed', async () => {
await db.users.create({ email: 'test@example.com', password: 'MyPassword123' });
const user = await db.users.findByEmail('test@example.com');
expect(user.password).not.toBe('MyPassword123');
expect(user.password).toMatch(/^\$2[aby]\$\d{2}\$/); // bcrypt
});
test('no sensitive data in API response', async () => {
const response = await api.get('/users/me');
expect(response.body).not.toHaveProperty('password');
expect(response.body).not.toHaveProperty('ssn');
});4. Security Misconfiguration
4. 安全配置错误
javascript
test('errors don\'t leak sensitive info', async () => {
const response = await api.post('/login', { email: 'nonexistent@test.com', password: 'wrong' });
expect(response.body.error).toBe('Invalid credentials'); // Generic message
});
test('sensitive endpoints not exposed', async () => {
const endpoints = ['/debug', '/.env', '/.git', '/admin'];
for (let ep of endpoints) {
expect((await fetch(`https://example.com${ep}`)).status).not.toBe(200);
}
});javascript
test('errors don\'t leak sensitive info', async () => {
const response = await api.post('/login', { email: 'nonexistent@test.com', password: 'wrong' });
expect(response.body.error).toBe('Invalid credentials'); // Generic message
});
test('sensitive endpoints not exposed', async () => {
const endpoints = ['/debug', '/.env', '/.git', '/admin'];
for (let ep of endpoints) {
expect((await fetch(`https://example.com${ep}`)).status).not.toBe(200);
}
});5. Rate Limiting
5. 速率限制
javascript
test('rate limiting prevents brute force', async () => {
const responses = [];
for (let i = 0; i < 20; i++) {
responses.push(await api.post('/login', { email: 'test@example.com', password: 'wrong' }));
}
expect(responses.filter(r => r.status === 429).length).toBeGreaterThan(0);
});javascript
test('rate limiting prevents brute force', async () => {
const responses = [];
for (let i = 0; i < 20; i++) {
responses.push(await api.post('/login', { email: 'test@example.com', password: 'wrong' }));
}
expect(responses.filter(r => r.status === 429).length).toBeGreaterThan(0);
});Security Checklist
安全检查清单
Authentication
身份验证
- Strong password requirements (12+ chars)
- Password hashing (bcrypt, scrypt, Argon2)
- MFA for sensitive operations
- Account lockout after failed attempts
- Session ID changes after login
- Session timeout
- 强密码要求(12位以上)
- 密码哈希(bcrypt, scrypt, Argon2)
- 敏感操作启用MFA
- 多次失败尝试后锁定账户
- 登录后会话ID更新
- 会话超时设置
Authorization
授权
- Check authorization on every request
- Least privilege principle
- No horizontal escalation
- No vertical escalation
- 每个请求都检查授权
- 最小权限原则
- 无水平权限提升
- 无垂直权限提升
Data Protection
数据保护
- HTTPS everywhere
- Encrypted at rest
- Secrets not in code/logs
- PII compliance (GDPR)
- 全链路HTTPS
- 静态数据加密
- 密钥不存储在代码/日志中
- PII合规(GDPR)
Input Validation
输入验证
- Server-side validation
- Parameterized queries (no SQL injection)
- Output encoding (no XSS)
- Rate limiting
- 服务端验证
- 参数化查询(防止SQL注入)
- 输出编码(防止XSS)
- 速率限制
CI/CD Integration
CI/CD集成
yaml
undefinedyaml
undefinedGitHub Actions
GitHub Actions
security-checks:
steps:
- name: Dependency audit
run: npm audit --audit-level=high
- name: SAST scan
run: npm run sast
- name: Secret scan
uses: trufflesecurity/trufflehog@main
- name: DAST scan
if: github.ref == 'refs/heads/main'
run: docker run owasp/zap2docker-stable zap-baseline.py -t https://staging.example.com
**Pre-commit hooks:**
```bash
#!/bin/sh
git-secrets --scan
npm run lint:securitysecurity-checks:
steps:
- name: Dependency audit
run: npm audit --audit-level=high
- name: SAST scan
run: npm run sast
- name: Secret scan
uses: trufflesecurity/trufflehog@main
- name: DAST scan
if: github.ref == 'refs/heads/main'
run: docker run owasp/zap2docker-stable zap-baseline.py -t https://staging.example.com
**预提交钩子:**
```bash
#!/bin/sh
git-secrets --scan
npm run lint:securityAgent-Assisted Security Testing
Agent辅助安全测试
typescript
// Comprehensive multi-layer scan
await Task("Security Scan", {
target: 'src/',
layers: { sast: true, dast: true, dependencies: true, secrets: true },
severity: ['critical', 'high', 'medium']
}, "qe-security-scanner");
// OWASP Top 10 testing
await Task("OWASP Scan", {
categories: ['broken-access-control', 'injection', 'cryptographic-failures'],
depth: 'comprehensive'
}, "qe-security-scanner");
// Validate fix
await Task("Validate Fix", {
vulnerability: 'CVE-2024-12345',
expectedResolution: 'upgrade package to v2.0.0',
retestAfterFix: true
}, "qe-security-scanner");typescript
// Comprehensive multi-layer scan
await Task("Security Scan", {
target: 'src/',
layers: { sast: true, dast: true, dependencies: true, secrets: true },
severity: ['critical', 'high', 'medium']
}, "qe-security-scanner");
// OWASP Top 10 testing
await Task("OWASP Scan", {
categories: ['broken-access-control', 'injection', 'cryptographic-failures'],
depth: 'comprehensive'
}, "qe-security-scanner");
// Validate fix
await Task("Validate Fix", {
vulnerability: 'CVE-2024-12345',
expectedResolution: 'upgrade package to v2.0.0',
retestAfterFix: true
}, "qe-security-scanner");Agent Coordination Hints
Agent协同提示
Memory Namespace
内存命名空间
aqe/security/
├── scans/* - Scan results
├── vulnerabilities/* - Found vulnerabilities
├── fixes/* - Remediation tracking
└── compliance/* - Compliance statusaqe/security/
├── scans/* - 扫描结果
├── vulnerabilities/* - 发现的漏洞
├── fixes/* - 修复追踪
└── compliance/* - 合规状态Fleet Coordination
集群协同
typescript
const securityFleet = await FleetManager.coordinate({
strategy: 'security-testing',
agents: [
'qe-security-scanner',
'qe-api-contract-validator',
'qe-quality-analyzer',
'qe-deployment-readiness'
],
topology: 'parallel'
});typescript
const securityFleet = await FleetManager.coordinate({
strategy: 'security-testing',
agents: [
'qe-security-scanner',
'qe-api-contract-validator',
'qe-quality-analyzer',
'qe-deployment-readiness'
],
topology: 'parallel'
});Common Mistakes
常见错误
❌ Security by Obscurity
❌ 通过隐蔽性实现安全
Hiding admin at → Use proper auth
/super-secret-admin将管理页面隐藏在 → 使用正规身份验证
/super-secret-admin❌ Client-Side Validation Only
❌ 仅依赖客户端验证
JavaScript validation can be bypassed → Always validate server-side
JavaScript验证可被绕过 → 始终在服务端验证
❌ Trusting User Input
❌ 信任用户输入
Assuming input is safe → Sanitize, validate, escape all input
假设输入是安全的 → 对所有输入进行清理、验证、转义
❌ Hardcoded Secrets
❌ 硬编码密钥
API keys in code → Environment variables, secret management
代码中包含API密钥 → 使用环境变量、密钥管理工具
Related Skills
相关技能
- agentic-quality-engineering - Security with agents
- api-testing-patterns - API security testing
- compliance-testing - GDPR, HIPAA, SOC2
- agentic-quality-engineering - 基于Agent的安全测试
- api-testing-patterns - API安全测试
- compliance-testing - GDPR, HIPAA, SOC2合规测试
Remember
谨记
Think like an attacker: What would you try to break? Test that.
Build like a defender: Assume input is malicious until proven otherwise.
Test continuously: Security testing is ongoing, not one-time.
With Agents: Agents automate vulnerability scanning, track remediation, and validate fixes. Use agents to maintain security posture at scale.
像攻击者一样思考: 你会尝试攻破什么?就测试什么。
像防御者一样构建: 假设输入是恶意的,直到被证明是安全的。
持续测试: 安全测试是持续性工作,而非一次性任务。
使用Agent: Agent可自动完成漏洞扫描、追踪修复并验证修复效果。使用Agent可大规模维护安全态势。