Overview
IP addresses in audit logs are encrypted using AES-256-GCM encryption with user-specific keys. This ensures that IP addresses are stored securely and can only be decrypted by the user who owns the log entry.Security Features
- User-specific encryption: Each user’s IP addresses are encrypted with a key derived from their user ID
- AES-256-GCM: Industry-standard authenticated encryption
- PBKDF2 key derivation: 100,000 iterations with SHA-256
- Automatic decryption: IP addresses are automatically decrypted when retrieved via the audit logs API
Implementation
Code Reference
Functions
encryptIp(ip: string, userId: string): string
Encrypts an IP address using a user-specific key.
Parameters:
ip: The IP address to encrypt (or'unknown')userId: The user ID used for key derivation
iv:tag:encrypted or 'unknown'
Example:
decryptIp(encryptedIp: string, userId: string): string
Decrypts an encrypted IP address using a user-specific key.
Parameters:
encryptedIp: The encrypted IP string (formativ:tag:encrypted)userId: The user ID used for key derivation
'unknown' if decryption fails
Example:
getClientIp(request: NextRequest): string
Extracts the client IP address from request headers.
Priority order:
x-client-ipheader- First IPv4 address from
x-forwarded-forheader - First address from
x-forwarded-forheader x-real-ipheader'unknown'if no IP found
getClientIpForStorage(request: NextRequest, userId: string): string
Extracts and encrypts the client IP address for database storage.
Example:
Encryption Format
Encrypted IP addresses are stored in the format:iv: Initialization vector (hex, 16 bytes)tag: Authentication tag (hex, 16 bytes)encrypted: Encrypted IP address (hex)
Key Derivation
Keys are derived using PBKDF2:- Algorithm: SHA-256
- Iterations: 100,000
- Key length: 32 bytes (256 bits)
- Salt:
'ip-encryption-salt' - Key material:
{userId}:{IP_ENCRYPTION_SECRET}
Environment Variables
string
required
Secret key used for IP encryption key derivation. Must be set in production and kept secure.
Usage in Audit Logs
IP addresses are automatically encrypted when stored in audit logs:Security Considerations
- User isolation: Each user’s IP addresses are encrypted with a unique key derived from their user ID
- Forward secrecy: If
IP_ENCRYPTION_SECRETis compromised, existing encrypted IPs cannot be decrypted without the user ID - Authentication: GCM mode provides authentication, ensuring encrypted IPs cannot be tampered with
- Fallback: Invalid or corrupted encrypted IPs return
'unknown'instead of throwing errors