# AI Security Policies and Cedar Authorization\n\n**Status**: ✅ Production-Ready (Cedar integration, policy enforcement)\n\nComprehensive documentation of security controls, authorization policies, and data protection mechanisms for the AI system. All AI operations are\ncontrolled through Cedar policies and include strict secret isolation.\n\n## Security Model Overview\n\n### Defense in Depth\n\n```\n┌─────────────────────────────────────────┐\n│ User Request to AI                      │\n└──────────────┬──────────────────────────┘\n               ↓\n┌─────────────────────────────────────────┐\n│ Layer 1: Authentication                 │\n│ - Verify user identity                  │\n│ - Validate API token/credentials        │\n└──────────────┬──────────────────────────┘\n               ↓\n┌─────────────────────────────────────────┐\n│ Layer 2: Authorization (Cedar)          │\n│ - Check if user can access AI features  │\n│ - Verify workspace permissions          │\n│ - Check role-based access               │\n└──────────────┬──────────────────────────┘\n               ↓\n┌─────────────────────────────────────────┐\n│ Layer 3: Data Sanitization              │\n│ - Remove secrets from data              │\n│ - Redact PII                            │\n│ - Filter sensitive information          │\n└──────────────┬──────────────────────────┘\n               ↓\n┌─────────────────────────────────────────┐\n│ Layer 4: Request Validation             │\n│ - Check request parameters              │\n│ - Verify resource constraints           │\n│ - Apply rate limits                     │\n└──────────────┬──────────────────────────┘\n               ↓\n┌─────────────────────────────────────────┐\n│ Layer 5: External API Call              │\n│ - Only if all previous checks pass      │\n│ - Encrypted TLS connection              │\n│ - No secrets in request                 │\n└──────────────┬──────────────────────────┘\n               ↓\n┌─────────────────────────────────────────┐\n│ Layer 6: Audit Logging                  │\n│ - Log all AI operations                 │\n│ - Capture user, time, action            │\n│ - Store in tamper-proof log             │\n└─────────────────────────────────────────┘\n```\n\n## Cedar Policies\n\n### Policy Engine Setup\n\n```\n// File: provisioning/policies/ai-policies.cedar\n\n// Core principle: Least privilege\n// All actions denied by default unless explicitly allowed\n\n// Admin users can access all AI features\npermit(\n  principal == ?principal,\n  action == Action::"ai_generate_config",\n  resource == ?resource\n)\nwhen {\n  principal.role == "admin"\n};\n\n// Developers can use AI within their workspace\npermit(\n  principal == ?principal,\n  action in [\n    Action::"ai_query",\n    Action::"ai_generate_config",\n    Action::"ai_troubleshoot"\n  ],\n  resource == ?resource\n)\nwhen {\n  principal.role in ["developer", "senior_engineer"]\n  && principal.workspace == resource.workspace\n};\n\n// Operators can access troubleshooting and queries\npermit(\n  principal == ?principal,\n  action in [\n    Action::"ai_query",\n    Action::"ai_troubleshoot"\n  ],\n  resource == ?resource\n)\nwhen {\n  principal.role in ["operator", "devops"]\n};\n\n// Form assistance enabled for all authenticated users\npermit(\n  principal == ?principal,\n  action == Action::"ai_form_assistance",\n  resource == ?resource\n)\nwhen {\n  principal.authenticated == true\n};\n\n// Agents (when available) require explicit approval\npermit(\n  principal == ?principal,\n  action == Action::"ai_agent_execute",\n  resource == ?resource\n)\nwhen {\n  principal.role == "automation_admin"\n  && resource.requires_approval == true\n};\n\n// MCP tool access - restrictive by default\npermit(\n  principal == ?principal,\n  action == Action::"mcp_tool_call",\n  resource == ?resource\n)\nwhen {\n  principal.role == "admin"\n|  |  | (principal.role == "developer" && resource.tool in ["generate_config", "validate_config"]) |\n};\n\n// Cost control policies\npermit(\n  principal == ?principal,\n  action == Action::"ai_generate_config",\n  resource == ?resource\n)\nwhen {\n  // User must have remaining budget\n  principal.ai_budget_remaining_usd > resource.estimated_cost_usd\n  // Workspace must be under budget\n  && resource.workspace.ai_budget_remaining_usd > resource.estimated_cost_usd\n};\n```\n\n### Policy Best Practices\n\n1. **Explicit Allow**: Only allow specific actions, deny by default\n2. **Workspace Isolation**: Users can't access AI in other workspaces\n3. **Role-Based**: Use consistent role definitions\n4. **Cost-Aware**: Check budgets before operations\n5. **Audit Trail**: Log all policy decisions\n\n## Data Sanitization\n\n### Automatic PII Removal\n\nBefore sending data to external LLMs, the system removes:\n\n```\nPatterns Removed:\n├─ Passwords: password="...", pwd=..., etc.\n├─ API Keys: api_key=..., api-key=..., etc.\n├─ Tokens: token=..., bearer=..., etc.\n├─ Email addresses: user@example.com (unless necessary for context)\n├─ Phone numbers: +1-555-0123 patterns\n├─ Credit cards: 4111-1111-1111-1111 patterns\n├─ SSH keys: -----BEGIN RSA PRIVATE KEY-----...\n└─ AWS/GCP/Azure: AKIA2..., AIza..., etc.\n```\n\n### Configuration\n\n```\n[ai.security]\nsanitize_pii = true\nsanitize_secrets = true\n\n# Custom redaction patterns\nredact_patterns = [\n  # Database passwords\n  "(?i)db[_-]?password\\s*[:=]\\s*'?[^'\\n]+'?",\n  # Generic secrets\n  "(?i)secret\\s*[:=]\\s*'?[^'\\n]+'?",\n  # API endpoints that shouldn't be logged\n  "https?://api[.-]secret\\..+",\n]\n\n# Exceptions (patterns NOT to redact)\npreserve_patterns = [\n  # Preserve example.com domain for docs\n  "example\\.com",\n  # Preserve placeholder emails\n  "user@example\\.com",\n]\n```\n\n### Example Sanitization\n\n**Before**:\n```\nError configuring database:\nconnection_string: postgresql://dbadmin:MySecurePassword123@prod-db.us-east-1.rds.amazonaws.com:5432/app\napi_key: sk-ant-abc123def456\nvault_token: hvs.CAESIyg7...\n```\n\n**After Sanitization**:\n```\nError configuring database:\nconnection_string: postgresql://dbadmin:[REDACTED]@prod-db.us-east-1.rds.amazonaws.com:5432/app\napi_key: [REDACTED]\nvault_token: [REDACTED]\n```\n\n## Secret Isolation\n\n### Never Access Secrets Directly\n\nAI cannot directly access secrets. Instead:\n\n```\nUser wants: "Configure PostgreSQL with encrypted backups"\n  ↓\nAI generates: Configuration schema with placeholders\n  ↓\nUser inserts: Actual secret values (connection strings, passwords)\n  ↓\nSystem encrypts: Secrets remain encrypted at rest\n  ↓\nDeployment: Uses secrets from secure store (Vault, AWS Secrets Manager)\n```\n\n### Secret Protection Rules\n\n1. **No Direct Access**: AI never reads from Vault/Secrets Manager\n2. **Never in Logs**: Secrets never logged or stored in cache\n3. **Sanitization**: All secrets redacted before sending to LLM\n4. **Encryption**: Secrets encrypted at rest and in transit\n5. **Audit Trail**: All access to secrets logged\n6. **TTL**: Temporary secrets auto-expire\n\n## Local Models Support\n\n### Air-Gapped Deployments\n\nFor environments requiring zero external API calls:\n\n```\n# Deploy local Ollama with provisioning support\ndocker run -d \\n  --name provisioning-ai \\n  -p 11434:11434 \\n  -v ollama:/root/.ollama \\n  -e OLLAMA_HOST=0.0.0.0:11434 \\n  ollama/ollama\n\n# Pull model\nollama pull mistral\nollama pull llama2-70b\n\n# Configure provisioning to use local model\nprovisioning config edit ai\n\n[ai]\nprovider = "local"\nmodel = "mistral"\napi_base = "[http://localhost:11434"](http://localhost:11434")\n```\n\n### Benefits\n\n- ✅ Zero external API calls\n- ✅ Full data privacy (no LLM vendor access)\n- ✅ Compliance with classified/regulated data\n- ✅ No API key exposure\n- ✅ Deterministic (same results each run)\n\n### Performance Trade-offs\n\n|  | Factor | Local | Cloud |  |\n|  | -------- | ------- | ------- |  |\n|  | Privacy | Excellent | Requires trust |  |\n|  | Cost | Free (hardware) | Per token |  |\n|  | Speed | 5-30s/response | 2-5s/response |  |\n|  | Quality | Good (70B models) | Excellent (Opus) |  |\n|  | Hardware | Requires GPU | None |  |\n\n## HSM Integration\n\n### Hardware Security Module Support\n\nFor highly sensitive environments:\n\n```\n[ai.security.hsm]\nenabled = true\nprovider = "aws-cloudhsm"  # or "thales", "yubihsm"\n\n[ai.security.hsm.aws]\ncluster_id = "cluster-123"\ncustomer_ca_cert = "/etc/provisioning/certs/customerCA.crt"\nserver_cert = "/etc/provisioning/certs/server.crt"\nserver_key = "/etc/provisioning/certs/server.key"\n```\n\n## Encryption\n\n### Data at Rest\n\n```\n[ai.security.encryption]\nenabled = true\nalgorithm = "aes-256-gcm"\nkey_derivation = "argon2id"\n\n# Key rotation\nkey_rotation_enabled = true\nkey_rotation_days = 90\nrotation_alert_days = 7\n\n# Encrypted storage\ncache_encryption = true\nlog_encryption = true\n```\n\n### Data in Transit\n\n```\nAll external LLM API calls:\n├─ TLS 1.3 (minimum)\n├─ Certificate pinning (optional)\n├─ Mutual TLS (with cloud providers)\n└─ No plaintext transmission\n```\n\n## Audit Logging\n\n### What Gets Logged\n\n```\n{\n  "timestamp": "2025-01-13T10:30:45Z",\n  "event_type": "ai_action",\n  "action": "generate_config",\n  "principal": {\n    "user_id": "user-123",\n    "role": "developer",\n    "workspace": "prod"\n  },\n  "resource": {\n    "type": "database",\n    "name": "prod-postgres"\n  },\n  "authorization": {\n    "decision": "permit",\n    "policy": "ai-policies.cedar",\n    "reason": "developer role in workspace"\n  },\n  "cost": {\n    "tokens_used": 1250,\n    "estimated_cost_usd": 0.037\n  },\n  "sanitization": {\n    "items_redacted": 3,\n    "patterns_matched": ["db_password", "api_key", "token"]\n  },\n  "status": "success"\n}\n```\n\n### Audit Trail Access\n\n```\n# View recent AI actions\nprovisioning audit log ai --tail 100\n\n# Filter by user\nprovisioning audit log ai --user alice@company.com\n\n# Filter by action\nprovisioning audit log ai --action generate_config\n\n# Filter by time range\nprovisioning audit log ai --from "2025-01-01" --to "2025-01-13"\n\n# Export for analysis\nprovisioning audit export ai --format csv --output audit.csv\n\n# Full-text search\nprovisioning audit search ai "error in database configuration"\n```\n\n## Compliance Frameworks\n\n### Built-in Compliance Checks\n\n```\n[ai.compliance]\nframeworks = ["pci-dss", "hipaa", "sox", "gdpr"]\n\n[ai.compliance.pci-dss]\nenabled = true\n# Requires encryption, audit logs, access controls\n\n[ai.compliance.hipaa]\nenabled = true\n# Requires local models, encrypted storage, audit logs\n\n[ai.compliance.gdpr]\nenabled = true\n# Requires data deletion, consent tracking, privacy by design\n```\n\n### Compliance Reports\n\n```\n# Generate compliance report\nprovisioning audit compliance-report \\n  --framework pci-dss \\n  --period month \\n  --output report.pdf\n\n# Verify compliance\nprovisioning audit verify-compliance \\n  --framework hipaa \\n  --verbose\n```\n\n## Security Best Practices\n\n### For Administrators\n\n1. **Rotate API Keys**: Every 90 days minimum\n2. **Monitor Budget**: Set up alerts at 80% and 90%\n3. **Review Policies**: Quarterly policy audit\n4. **Audit Logs**: Weekly review of AI operations\n5. **Update Models**: Use latest stable models\n6. **Test Recovery**: Monthly rollback drills\n\n### For Developers\n\n1. **Use Workspace Isolation**: Never share workspace access\n2. **Don't Log Secrets**: Use sanitization, never bypass it\n3. **Validate Outputs**: Always review AI-generated configs\n4. **Report Issues**: Security issues to `security-ai@company.com`\n5. **Stay Updated**: Follow security bulletins\n\n### For Operators\n\n1. **Monitor Costs**: Alert if exceeding 110% of budget\n2. **Watch Errors**: Unusual error patterns may indicate attacks\n3. **Check Audit Logs**: Unauthorized access attempts\n4. **Test Policies**: Periodically verify Cedar policies work\n5. **Backup Configs**: Secure backup of policy files\n\n## Incident Response\n\n### Compromised API Key\n\n```\n# 1. Immediately revoke key\nprovisioning admin revoke-key ai-api-key-123\n\n# 2. Rotate key\nprovisioning admin rotate-key ai \\n  --notify ops-team@company.com\n\n# 3. Audit usage since compromise\nprovisioning audit log ai \\n  --since "2025-01-13T09:00:00Z" \\n  --api-key-id ai-api-key-123\n\n# 4. Review any generated configs from this period\n# Configs generated while key was compromised may need review\n```\n\n### Unauthorized Access\n\n```\n# Review Cedar policy logs\nprovisioning audit log ai \\n  --decision deny \\n  --last-hour\n\n# Check for pattern\nprovisioning audit search ai "authorization.*deny" \\n  --trend-analysis\n\n# Update policies if needed\nprovisioning policy update ai-policies.cedar\n```\n\n## Security Checklist\n\n### Pre-Production\n\n- ✅ Cedar policies reviewed and tested\n- ✅ API keys rotated and secured\n- ✅ Data sanitization tested with real secrets\n- ✅ Encryption enabled for cache\n- ✅ Audit logging configured\n- ✅ Cost limits set appropriately\n- ✅ Local-only mode tested (if needed)\n- ✅ HSM configured (if required)\n\n### Ongoing\n\n- ✅ Monthly policy review\n- ✅ Weekly audit log review\n- ✅ Quarterly key rotation\n- ✅ Annual compliance assessment\n- ✅ Continuous budget monitoring\n- ✅ Error pattern analysis\n\n## Related Documentation\n\n- [Architecture](architecture.md) - System overview\n- [Configuration](configuration.md) - Security settings\n- [Cost Management](cost-management.md) - Budget controls\n- [ADR-015](../architecture/adr/adr-015-ai-integration-architecture.md) - Design decisions\n\n---\n\n**Last Updated**: 2025-01-13\n**Status**: ✅ Production-Ready\n**Compliance**: PCI-DSS, HIPAA, SOX, GDPR\n**Cedar Version**: 3.0+
