AgileFlow

Security

PreviousNext

Security specialist for vulnerability analysis, authentication patterns, authorization, compliance, and security reviews before release.

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

  1. Knowledge Loading: Agent reads expertise and security research
  2. Story Review: Agent analyzes story for security implications
  3. Threat Modeling: Agent models threats for security-critical features
  4. Vulnerability Analysis: Agent identifies attack vectors and mitigations
  5. Security Testing: Agent writes security tests (auth failures, injections, escalation)
  6. Verification: Agent runs /agileflow:verify to ensure tests pass
  7. Documentation: Agent creates ADRs for security decisions
  8. Clearance Decision: Agent reports APPROVED / APPROVED WITH MITIGATIONS / REJECTED
  9. 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 required

Key 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_progress

This 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

VulnerabilityRiskPrevention
SQL InjectionData breachParameterized queries
XSS (Cross-Site Scripting)Session hijackingInput sanitization, output encoding
CSRF (Cross-Site Request Forgery)Unauthorized actionsCSRF tokens, SameSite cookies
Weak AuthenticationAccount takeoverStrong passwords, MFA, JWT
Hardcoded SecretsCredential exposureEnvironment variables
Missing HTTPSMan-in-the-middleEnforce HTTPS, HSTS
Privilege EscalationUnauthorized accessAuthorization checks
Dependency VulnerabilitiesSupply chain attacksRegular scanning, updates

Bug Severity Levels

SeverityDescriptionExample
CriticalSecurity breach, data lossUnauthenticated API access
HighSignificant vulnerabilityWeak password policy
MediumNotable weaknessMissing CSRF tokens
LowMinor issueVerbose error messages

Threat Modeling Framework

For major features, ask:

  1. What assets are we protecting? (user data, payment info, IP)
  2. Who are the threats? (hackers, malicious users, insiders)
  3. What attacks are possible? (SQL injection, XSS, credential stuffing)
  4. How do we prevent each attack? (validation, encryption, rate limiting)
  5. What's our defense depth? (layers of security)
  6. 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 packages

Document findings:

  • Which packages are vulnerable?
  • What's the severity?
  • Can we update or is there a workaround?
  • When was this last checked?
  • testing - Security test implementation
  • api - API security and validation
  • database - Database security and access control
  • devops - Infrastructure security
  • ci - 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