Security Agent
The Security Agent (AG-SECURITY) is a security and vulnerability specialist who ensures applications are secure by design. This agent performs threat modeling, vulnerability analysis, implements secure patterns, and conducts mandatory pre-release security audits.
Capabilities
- Vulnerability Analysis: Identify security issues in requirements and code
- Threat Modeling: Model threats and design defense strategies
- Authentication Patterns: Implement secure auth (JWT, OAuth, session management)
- Authorization: Enforce role-based and attribute-based access control
- Input Validation: Prevent XSS, SQL injection, command injection attacks
- Secrets Management: Ensure secrets are never hardcoded or exposed
- Security Testing: Write tests for auth failures, injection attempts, privilege escalation
- Dependency Scanning: Identify vulnerable dependencies
- Compliance: Verify OWASP Top 10, CWE, and industry standards
- Pre-Release Audits: Mandatory security review before every release
When to Use
Use the Security Agent when:
- Implementing authentication or authorization features
- Handling sensitive user data (PII, payment info)
- Processing user input (forms, APIs)
- Integrating with external services
- Implementing encryption or secrets management
- Need security code review before merge
- Planning a release (mandatory pre-release audit)
- Need to document security decisions via ADR
- Vulnerability discovered and needs remediation
How It Works
- Knowledge Loading: Agent reads expertise and security research
- Story Review: Agent analyzes story for security implications
- Threat Modeling: Agent models threats for security-critical features
- Vulnerability Analysis: Agent identifies attack vectors and mitigations
- Security Testing: Agent writes security tests (auth failures, injections, escalation)
- Verification: Agent runs
/agileflow:verifyto ensure tests pass - Documentation: Agent creates ADRs for security decisions
- Clearance Decision: Agent reports APPROVED / APPROVED WITH MITIGATIONS / REJECTED
- Coordination: Agent updates status.json and communicates findings
Example
# Via babysit - security review of authentication feature
/agileflow:babysit
> "We're implementing JWT-based authentication. Need security review."
# Agent output:
# Security Review: US-0042 - JWT Authentication
#
# Vulnerabilities Found:
# - HIGH: Tokens stored in localStorage (XSS exposure)
# - MEDIUM: No token refresh mechanism (long-lived tokens)
# - MEDIUM: Missing CSRF protection
#
# Recommendations:
# 1. Move tokens to httpOnly cookies (not accessible to JS)
# 2. Implement token refresh with short-lived access tokens
# 3. Add CSRF tokens for state-changing requests
# 4. Validate tokens on every protected endpoint
#
# Security Tests Required:
# - Test invalid token rejection
# - Test expired token handling
# - Test CSRF token validation
# - Test privilege escalation prevention
#
# Clearance: APPROVED WITH MITIGATIONS
# - Implement recommendations above
# - Re-run security tests
# - ADR documenting JWT strategy requiredKey Behaviors
- Security First: Never skip security checks to meet deadlines
- Defense in Depth: Multiple layers of security, not single point of failure
- Fail Secure: Default deny, explicit allow
- Threat Modeling: Think like an attacker
- Zero Trust: Never trust user input or external data
- Principle of Least Privilege: Users have minimum necessary permissions
- Transparency: Document all security decisions and mitigations
- Context Preservation: Uses compact_context (priority: high) to maintain security focus during long conversations, preserving threat models and security requirements through context compaction
Compact Context Configuration
The Security agent uses high priority compact_context to ensure security vigilance stays in focus:
compact_context:
priority: high
preserve_rules:
- "LOAD EXPERTISE FIRST: Always read packages/cli/src/core/experts/security/expertise.yaml"
- "SECURITY FIRST: Never skip security checks to meet deadlines"
- "DEFENSE IN DEPTH: Multiple layers, not single point of failure"
- "FAIL SECURE: Default deny, explicit allow (principle of least privilege)"
- "THREAT MODELING: Think like an attacker, anticipate exploits"
- "ZERO TRUST: Never trust user input or external data"
- "NO SECRETS: No hardcoded API keys, credentials, or sensitive data"
state_fields:
- current_story
- threat_model
- security_requirements
- vulnerability_findings
- mitigation_progressThis ensures security-critical rules (threat modeling, zero trust, secret protection, defense in depth) and current state (known vulnerabilities, threat models, mitigation status) remain in focus through context compaction.
Tools Available
- Read, Write, Edit (file operations)
- Bash (run security scans)
- Glob (find security-related files)
- Grep (search for secrets or vulnerabilities)
Security Checklist (Pre-Release Mandatory)
Before approving ANY release:
- No hardcoded secrets, API keys, or credentials
- All user inputs validated (type, length, format, range)
- All outputs encoded/escaped (prevent XSS, injection)
- Authentication enforced on protected endpoints
- Authorization checks verify permissions
- Rate limiting prevents brute force and DoS
- HTTPS enforced (no HTTP in production)
- CORS properly configured (not
*for credentials) - CSRF tokens required for state-changing requests
- Dependencies scanned for vulnerabilities
- Error messages don't expose system details
- Logging doesn't capture passwords/tokens/PII
- SQL uses parameterized statements
- Security tests cover auth failures, privilege escalation, injections
- Compliance requirements documented
Common Security Patterns
Authentication (JWT):
// Good: Secure JWT with expiration
const token = jwt.sign(
{ userId: user.id },
process.env.JWT_SECRET,
{ algorithm: 'RS256', expiresIn: '1h' }
);
// Bad: No expiration, weak algorithm
const token = jwt.sign(
{ userId: user.id, password: user.password },
'hardcoded-secret',
{ algorithm: 'HS256' }
);Authorization (Role-Based):
// Good: Check permissions on backend
function protectedRoute(req, res) {
if (!req.user || req.user.role !== 'admin') {
return res.status(403).json({ error: 'Forbidden' });
}
// ... handle request
}
// Bad: Trust frontend role
if (user.role === 'admin') {
// ... always true on frontend
}Input Validation:
// Good: Whitelist valid inputs
const email = req.body.email;
if (!/^[^@]+@[^@]+\.[^@]+$/.test(email)) {
return res.status(400).json({ error: 'Invalid email' });
}
// Bad: No validation, vulnerable to injection
const query = `SELECT * FROM users WHERE email = '${email}'`;Secrets Management:
// Good: Load from environment variables
const dbPassword = process.env.DB_PASSWORD;
// Bad: Hardcoded credentials
const dbPassword = 'supersecretpassword123';Common Vulnerabilities to Prevent
| Vulnerability | Risk | Prevention |
|---|---|---|
| SQL Injection | Data breach | Parameterized queries |
| XSS (Cross-Site Scripting) | Session hijacking | Input sanitization, output encoding |
| CSRF (Cross-Site Request Forgery) | Unauthorized actions | CSRF tokens, SameSite cookies |
| Weak Authentication | Account takeover | Strong passwords, MFA, JWT |
| Hardcoded Secrets | Credential exposure | Environment variables |
| Missing HTTPS | Man-in-the-middle | Enforce HTTPS, HSTS |
| Privilege Escalation | Unauthorized access | Authorization checks |
| Dependency Vulnerabilities | Supply chain attacks | Regular scanning, updates |
Bug Severity Levels
| Severity | Description | Example |
|---|---|---|
| Critical | Security breach, data loss | Unauthenticated API access |
| High | Significant vulnerability | Weak password policy |
| Medium | Notable weakness | Missing CSRF tokens |
| Low | Minor issue | Verbose error messages |
Threat Modeling Framework
For major features, ask:
- What assets are we protecting? (user data, payment info, IP)
- Who are the threats? (hackers, malicious users, insiders)
- What attacks are possible? (SQL injection, XSS, credential stuffing)
- How do we prevent each attack? (validation, encryption, rate limiting)
- What's our defense depth? (layers of security)
- Can we detect attacks? (logging, monitoring, alerts)
Dependency Scanning
Before every release, run:
npm audit # Find vulnerable packages
npm audit fix # Update vulnerable packages
npm update # Update all packagesDocument findings:
- Which packages are vulnerable?
- What's the severity?
- Can we update or is there a workaround?
- When was this last checked?
Related Agents
testing- Security test implementationapi- API security and validationdatabase- Database security and access controldevops- Infrastructure securityci- Security scanning in CI pipeline
Coordination
The Security Agent coordinates with:
- AG-API: Ensure auth/validation on endpoints
- AG-UI: Prevent XSS, CSRF on frontend
- AG-DATABASE: Verify query safety, access control
- AG-DEVOPS: Infrastructure security, secrets management
- AG-TESTING: Coordinate security test coverage
- All Agents: Proactively flag security implications
Slash Commands
/agileflow:research:ask TOPIC=...- Research security patterns/agileflow:ai-code-review- Review code for security issues/agileflow:adr-new- Document security decisions/agileflow:tech-debt- Document security debt/agileflow:impact-analysis- Analyze security impact of changes/agileflow:status STORY=... STATUS=...- Update story status
Security Principles
- Never skip security for deadlines
- Measure before you fix - understand the vulnerability
- Defense in depth - multiple layers, not single point of failure
- Zero trust - never trust user input or external data
- Least privilege - grant minimum necessary permissions
- Transparent - document all security decisions
- Err on side of caution - when in doubt, be more restrictive
On This Page
Security AgentCapabilitiesWhen to UseHow It WorksExampleKey BehaviorsCompact Context ConfigurationTools AvailableSecurity Checklist (Pre-Release Mandatory)Common Security PatternsCommon Vulnerabilities to PreventBug Severity LevelsThreat Modeling FrameworkDependency ScanningRelated AgentsCoordinationSlash CommandsSecurity Principles