# Security Best Practices

Comprehensive security guidelines for protecting your Twig AI deployment and data.

## Account Security

### Password Requirements

**Twig enforces**:

* Min 12 characters
* ≥1 uppercase letter
* ≥1 lowercase letter
* ≥1 number
* ≥1 special character (!@#$%^&\*)

**Password rejection examples**:

* `password123` → Too common
* `Company2024` → Dictionary word + year
* `Abc123!` → Too short (7 chars)

**Recommended**: Use password manager (1Password, Bitwarden) to generate 16+ char random passwords

### Multi-Factor Authentication (MFA)

✅ **Enable MFA:**

* Required for admin roles
* Strongly recommended for all users
* Use authenticator app (not SMS)
* Backup codes stored securely

✅ **Supported Methods:**

* TOTP authenticator apps (Google, Authy)
* Hardware keys (YubiKey, Security Key)
* SMS (less secure, backup only)

### Account Monitoring

✅ **Monitor for:**

* Unusual login locations
* Failed login attempts
* New device logins
* Permission changes
* Suspicious activity

## API Security

### API Key Management

✅ **Best Practices:**

```bash
# Store in environment variables
export TWIG_API_KEY="sk_live_..."

# Never in code
❌ const key = "sk_live_abc123..."

# Use secret managers
✅ AWS Secrets Manager, Vault
```

✅ **Key Rotation:**

* Rotate every 90 days
* Different keys per environment
* Revoke immediately if compromised
* Monitor key usage

✅ **Scoped Keys:**

```json
{
  "scope": ["chat", "agents:read"],
  "notScope": ["agents:delete", "admin"]
}
```

### Network Security

✅ **HTTPS Only:**

* All API calls over HTTPS
* Certificate pinning (mobile apps)
* TLS 1.3 preferred

✅ **IP Whitelisting:**

```typescript
{
  "allowedIPs": [
    "203.0.113.0/24",
    "198.51.100.0/24"
  ]
}
```

✅ **Rate Limiting:**

* Implement client-side rate limiting
* Respect 429 responses
* Use exponential backoff

### Request Security

✅ **Input Validation:**

```typescript
// Validate inputs
function sanitizePrompt(prompt) {
  // Remove potential injection attempts
  // Limit length
  // Sanitize special characters
  return prompt.trim().slice(0, 4000);
}
```

✅ **Output Encoding:**

* Escape HTML in responses
* Sanitize URLs
* Validate JSON

## Data Security

### Data Classification

| Level            | Examples            | Controls                 |
| ---------------- | ------------------- | ------------------------ |
| **Public**       | Marketing materials | Standard                 |
| **Internal**     | Company docs        | Auth required            |
| **Confidential** | Customer data       | Encryption + RBAC        |
| **Restricted**   | Financial, PII      | Encryption + MFA + Audit |

### Encryption

✅ **At Rest:**

* AES-256 for databases
* Encrypted file storage
* Encrypted backups
* Key management (AWS KMS)

✅ **In Transit:**

* TLS 1.3
* Perfect forward secrecy
* Strong cipher suites
* Certificate validation

### Data Access

✅ **Principle of Least Privilege:**

* Grant minimum necessary access
* Time-limited access for contractors
* Regular access reviews
* Remove unused permissions

✅ **Data Segregation:**

* Organization data isolation
* No cross-org data access
* Separate environments (dev/staging/prod)

## Application Security

### Secure Configuration

✅ **Agent Settings:**

```typescript
{
  "configAIUseOnlyPrivateData": true,  // No external data
  "requireCitation": true,             // Always cite sources
  "piiDetection": true,                // Detect sensitive data
  "contentFiltering": true             // Block inappropriate
}
```

✅ **Deployment:**

* Staging environment for testing
* Gradual rollout
* Rollback procedures
* Health checks

### Secure Integrations

✅ **OAuth Security:**

* Use state parameter (CSRF protection)
* Validate redirect URIs
* Short-lived authorization codes
* Secure token storage

✅ **Webhook Security:**

* Verify signatures
* HTTPS endpoints only
* Rate limit webhook handlers
* Validate payloads

## Operational Security

### Access Control

✅ **User Management:**

* Regular access reviews
* Remove inactive users (90 days)
* Verify role assignments
* Audit group memberships

✅ **Privileged Access:**

* Limit Super Admin role (2-3 users)
* Require MFA for admin accounts
* Monitor admin activity
* Regular recertification

### Logging & Monitoring

✅ **Comprehensive Logs:**

* Authentication events
* Authorization failures
* Data access
* Configuration changes
* API calls
* Errors and exceptions

✅ **Monitoring:**

* Failed login attempts
* Unusual access patterns
* Performance anomalies
* Security events

✅ **Alerting:**

```typescript
{
  "securityAlerts": {
    "failedLogins": {
      "threshold": 5,
      "window": 300,  // 5 minutes
      "action": "LOCK_ACCOUNT"
    },
    "suspiciousActivity": {
      "enabled": true,
      "notify": "security@company.com"
    }
  }
}
```

### Incident Response

✅ **Preparation:**

* Incident response plan documented
* Team roles defined
* Escalation procedures
* Contact list maintained

✅ **Response Process:**

1. Detection and analysis
2. Containment
3. Eradication
4. Recovery
5. Post-incident review

✅ **Communication:**

* Internal notification channels
* Customer notification templates
* Regulatory reporting procedures

## Vulnerability Management

### Patch Management

✅ **Regular Updates:**

* Security patches applied within 48 hours
* Platform updates monthly
* Dependency updates weekly
* Zero-day vulnerabilities: Immediate

### Vulnerability Scanning

✅ **Continuous Scanning:**

* Automated daily scans
* Dependency vulnerability checks
* Container image scanning
* Code analysis (SAST)

### Penetration Testing

✅ **Annual Testing:**

* External penetration test
* Internal vulnerability assessment
* Social engineering tests
* Report and remediation

## Third-Party Security

### Vendor Assessment

✅ **Sub-Processor Review:**

* Security questionnaires
* Compliance verification
* Contract terms
* Regular reassessment

✅ **Current Sub-Processors:**

* AWS (SOC 2, ISO 27001)
* OpenAI (SOC 2, enterprise agreement)
* Pinecone (SOC 2)
* Stripe (PCI Level 1)

### Integration Security

✅ **OAuth Integrations:**

* Minimum required scopes
* Token encryption
* Regular token rotation
* Revocation procedures

## Developer Security

### Secure Coding

✅ **Practices:**

* Input validation
* Output encoding
* Parameterized queries
* Error handling (don't leak info)
* Secure dependencies

✅ **Code Review:**

* Peer review required
* Security review for sensitive changes
* Automated security scanning

### API Security

✅ **Implementation:**

```typescript
// Validate inputs
if (!isValidAgentId(agentId)) {
  throw new Error('Invalid agent ID');
}

// Rate limiting
const rateLimit = checkRateLimit(userId);
if (rateLimit.exceeded) {
  throw new RateLimitError();
}

// Authorization
if (!canAccessAgent(userId, agentId)) {
  throw new ForbiddenError();
}
```

## Security Checklist

### Initial Setup

* [ ] Enable MFA for all admins
* [ ] Configure SSO (if available)
* [ ] Set strong password policy
* [ ] Review default permissions
* [ ] Enable audit logging
* [ ] Configure security alerts
* [ ] Review sub-processors
* [ ] Sign DPA
* [ ] Configure data residency
* [ ] Set up backup contacts

### Ongoing (Monthly)

* [ ] Review access logs
* [ ] Check for failed logins
* [ ] Audit API key usage
* [ ] Remove inactive users
* [ ] Review group memberships
* [ ] Check security alerts
* [ ] Update contact information

### Ongoing (Quarterly)

* [ ] Full access review
* [ ] Recertify privileged access
* [ ] Review and update security policies
* [ ] Test incident response plan
* [ ] Rotate API keys
* [ ] Review compliance status
* [ ] Update security training

### Annual

* [ ] Comprehensive security audit
* [ ] Review all users and permissions
* [ ] Update security documentation
* [ ] Review vendor security
* [ ] Penetration testing
* [ ] Compliance recertification
* [ ] Update business continuity plan

## Reporting Security Issues

### Responsible Disclosure

Found a security vulnerability?

**Email:** <security@twig.so>

**Include:**

* Description of vulnerability
* Steps to reproduce
* Impact assessment
* Suggested fix (if known)

**We commit to:**

* Acknowledge within 24 hours
* Provide updates every 3-5 days
* Fix critical issues within 48 hours
* Credit researchers (with permission)

### Bug Bounty Program

**Status:** Enterprise customers only

Contact <security@twig.so> for details.

## Resources

* **Security Portal:** [security.twig.so](https://security.twig.so)
* **Trust Center:** [trust.twig.so](https://trust.twig.so)
* **Status Page:** [status.twig.so](https://status.twig.so)
* **Security Email:** <security@twig.so>

## Next Steps

* [Authentication & Authorization](/product/security/authentication-authorization.md) - Access control
* [Data Privacy](/product/security/data-privacy.md) - Privacy protection
* [Compliance](/product/security/compliance.md) - Regulatory requirements
* [User Permissions](/product/administration/user-permissions.md) - Manage access


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.twig.so/product/security/best-practices.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
