Skip to content

Compliance & Audit

Compliance considerations and audit capabilities for the authentication system.


Compliance Overview

SOC 2 Type II

Control Implementation Evidence
Access Control RBAC with least privilege Role assignments, permission checks
Change Management Git history, migrations Commit logs, Alembic versions
Incident Response Alerting, documented procedures Runbooks, escalation paths
Data Encryption TLS 1.3, Fernet at rest TLS config, encryption code
Monitoring Structured logging, abuse detection Log aggregation, alerts
Penetration Testing Scheduled tests Test reports, remediation

GDPR Compliance

Requirement Implementation
Right to Access /api/v1/auth/me endpoint
Right to Deletion User deletion cascade (planned)
Right to Portability Data export endpoint (planned)
Right to be Forgotten Account deletion with data wipe
Consent Management Email verification, privacy acceptance
Data Breach Notification Logging + alerting + incident response
Data Minimization Only collect required fields
Data Retention Configurable retention policies

PCI DSS (if applicable)

Requirement Status Notes
Secure Authentication Bcrypt, multi-factor available
Secure Password Storage Bcrypt with salt
Protect Cardholder Data N/A No card data stored
Encryption in Transit TLS 1.3
Encryption at Rest Fernet for sensitive data
Access Control RBAC
Logging & Monitoring Comprehensive audit trail
Penetration Testing ⚠️ Scheduled

Audit Trail

Logged Events

All authentication events are logged with:

Field Description Example
event_type Type of event login, logout, refresh
user_id User identifier 123
team_id Team context 456
ip Client IP 1.2.3.4
user_agent Client UA Mozilla/5.0...
device_fingerprint Device identifier sha256-hash
geo Geographic location {"city": "SF", "country": "US"}
created_at Timestamp 2025-01-22T10:30:00Z
correlation_id Request ID uuid-v4

Event Types

Event Type Description Logged By
login Successful login AuthService
logout User logout AuthService
refresh Token refresh AuthService
session_expired Idle timeout AuthService
session_revoked Manual revocation AuthService
password_reset Password reset AuthService
email_verified Email verification AuthService
device_approved Device approved AuthService
suspicious_login Flagged login AuthService
concurrent_login Concurrent login attempt AuthService
permission_denied Authorization failure Dependencies
csrf_mismatch CSRF failure Dependencies

Log Query Examples

-- User login history (last 30 days)
SELECT
    user_id,
    event_type,
    ip,
    geo->>'city' as city,
    geo->>'country' as country,
    created_at
FROM login_activity
WHERE user_id = 123
  AND created_at > NOW() - INTERVAL '30 days'
ORDER BY created_at DESC;

-- Failed login attempts by IP (24h)
SELECT
    ip,
    COUNT(*) as failed_attempts
FROM auth_violation_log
WHERE violation_type = 'not_authenticated'
  AND created_at > NOW() - INTERVAL '24 hours'
GROUP BY ip
HAVING COUNT(*) > 10
ORDER BY failed_attempts DESC;

-- Permission denials by user (7 days)
SELECT
    user_id,
    jsonb_extract_path_text(extra, 'permission') as permission,
    COUNT(*) as denials
FROM auth_violation_log
WHERE violation_type = 'missing_permission'
  AND created_at > NOW() - INTERVAL '7 days'
GROUP BY user_id, permission
ORDER BY denials DESC;

-- Suspicious logins (24h)
SELECT
    user_id,
    ip,
    geo->>'city' as city,
    geo->>'country' as country,
    created_at
FROM login_activity
WHERE suspicious = true
  AND created_at > NOW() - INTERVAL '24 hours'
ORDER BY created_at DESC;

Data Retention

Current Policies

Data Type Retention Period Justification
Login Activity 1 year Security investigation
Active Sessions Until revoked/timeout Operational need
Trusted Devices Until revoked User convenience
Invite Tokens 30 days after expiry Audit trail
Email Verification Tokens 30 days after expiry Audit trail
Password Reset Tokens 30 days after expiry Audit trail
Auth Violation Logs 1 year Security analysis
Application Logs 90 days Troubleshooting

GDPR Data Deletion

When a user is deleted:

  1. Cascade Deletion:
  2. User record
  3. TeamMember associations
  4. ActiveSession records
  5. LoginActivity records
  6. TrustedDevice records

  7. Anonymization:

  8. Replace user_id with deleted_<timestamp> in audit logs
  9. Replace email with deleted@domain.local

  10. Verification:

  11. Confirm no PII remains
  12. Generate deletion certificate

Security Audits

Self-Assessment Checklist

Control Status Notes
Password Policy Bcrypt, min 8 chars
Multi-Factor Auth TOTP implemented (disabled)
Session Timeout Idle + absolute
Concurrent Login Single-session enforced
Rate Limiting Login endpoint
Account Lockout ⚠️ Not implemented
Password History Not implemented
Password Expiry Not enforced
Security Logging Comprehensive
Incident Response Documented

Penetration Testing

Scope: - Authentication endpoints - Session management - Permission enforcement - Token handling - CSRF protection

Findings (Last Assessment): | Finding | Severity | Status | Remediation | |---------|----------|--------|-------------| | JWT secret in config | Medium | ✅ Fixed | Use env vars | | Missing rate limit on some endpoints | Low | ✅ Fixed | Added rate limiting | | CSRF missing on some endpoints | High | ✅ Fixed | Applied CSRF middleware |


Incident Response

Security Incident Types

Incident Detection Response Time Escalation
Brute Force Rate limit alert < 5 min → Security Team
Token Leak Abuse signals < 15 min → Security Team → Executive
Data Breach Monitoring < 1 hour → Executive -> Legal
DDoS Traffic spike < 5 min → Infrastructure Team
Compromised Account User report < 30 min → Security Team

Response Playbook

Token Compromise

  1. Detection: Abnormal access patterns, multiple failed logins
  2. Containment: Blacklist all user JTIs, revoke sessions
  3. Investigation: Audit LoginActivity for unauthorized access
  4. Remediation: Force password reset, notify user
  5. Recovery: Monitor for re-compromise

Brute Force Attack

  1. Detection: Rate limit alerts (> 10/min per IP)
  2. Containment: Block IP via firewall
  3. Investigation: Check source (VPN, botnet, etc.)
  4. Remediation: Adjust rate limits, implement CAPTCHA
  5. Recovery: Monitor for continued attacks

Privacy Controls

PII Handling

PII Type Storage Access Logging
Email Database (users table) Authenticated users Redacted (j***@domain.com)
Password Bcrypt hash only None Never logged
IP Address LoginActivity Admin users Redacted (...)
User Agent LoginActivity Admin users Full
Geo Location LoginActivity Admin users City/Country only

PII Redaction

# Redaction rules
EMAIL_REDACTION = lambda e: f"{e[0]}***@{e.split('@')[1]}"
IP_REDACTION = lambda ip: '.'.join(ip.split('.')[:2]) + '.***.***'
TOKEN_REDACTION = lambda t: t[:8] if t else '***'

Compliance Reports

SOC 2 Report Sections

  1. System Description: Architecture, boundaries, data flow
  2. Control Design: How controls are implemented
  3. Control Testing: Evidence of control effectiveness
  4. Exception Management: Documented exceptions and remediation

GDPR Documentation

  1. Record of Processing Activities: What data is collected and why
  2. Data Protection Impact Assessment: Risk assessment for processing
  3. Breach Response Plan: Steps for handling data breaches
  4. User Rights Procedures: How to handle DSARs (Data Subject Access Requests)