Every OpenClaw deployment that handles user interactions is an application that processes, stores, and transmits user data. Whether you are running a customer support bot, an internal knowledge assistant, or a public-facing AI agent, application security is not optional — it is the foundation of user trust.
This guide covers the essential application-level security configurations for OpenClaw, from authentication and authorization to data protection and compliance.
OpenClaw applications face a unique combination of traditional web security risks and AI-specific threats:
# OpenClaw auth configuration
authentication:
admin_panel:
method: "password+2fa"
password_policy:
min_length: 12
require_uppercase: true
require_number: true
require_special: true
max_age_days: 90
two_factor:
enabled: true
method: "totp" # Google Authenticator compatible
session:
timeout_minutes: 30
max_concurrent: 3
api:
method: "api_key"
key_rotation_days: 90
rate_limit:
requests_per_minute: 60
burst: 10
# auth_middleware.py
import jwt
from datetime import datetime, timedelta
SECRET_KEY = os.environ['JWT_SECRET']
def create_token(user_id, role):
payload = {
'sub': user_id,
'role': role,
'iat': datetime.utcnow(),
'exp': datetime.utcnow() + timedelta(minutes=30),
'jti': str(uuid.uuid4()) # Unique token ID for revocation
}
return jwt.encode(payload, SECRET_KEY, algorithm='HS256')
def verify_token(token):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
if is_token_revoked(payload['jti']):
raise jwt.InvalidTokenError("Token revoked")
return payload
except jwt.ExpiredSignatureError:
raise AuthError("Token expired")
except jwt.InvalidTokenError as e:
raise AuthError(f"Invalid token: {e}")
Implement Role-Based Access Control (RBAC):
# rbac.py
PERMISSIONS = {
'admin': [
'manage_users', 'manage_config', 'view_logs',
'manage_channels', 'view_analytics', 'manage_models'
],
'operator': [
'view_logs', 'view_analytics', 'manage_channels'
],
'user': [
'chat', 'view_own_history'
],
'viewer': [
'view_analytics'
]
}
def check_permission(user_role, required_permission):
"""Check if user role has the required permission"""
if user_role not in PERMISSIONS:
return False
return required_permission in PERMISSIONS[user_role]
Deploy on Tencent Cloud Lighthouse — simple, high-performance, cost-effective — and use the built-in firewall to restrict admin access by IP.
# Enable disk encryption on Lighthouse
# Use LUKS for the data partition
sudo cryptsetup luksFormat /dev/vdb
sudo cryptsetup luksOpen /dev/vdb openclaw_data
sudo mkfs.ext4 /dev/mapper/openclaw_data
sudo mount /dev/mapper/openclaw_data /opt/openclaw/data
# data_encryption.py
from cryptography.fernet import Fernet
ENCRYPTION_KEY = os.environ['DATA_ENCRYPTION_KEY']
cipher = Fernet(ENCRYPTION_KEY)
def encrypt_field(plaintext):
"""Encrypt sensitive user data before storage"""
return cipher.encrypt(plaintext.encode()).decode()
def decrypt_field(ciphertext):
"""Decrypt user data for authorized access"""
return cipher.decrypt(ciphertext.encode()).decode()
# Usage: encrypt conversation content, user emails, etc.
encrypted_message = encrypt_field("User's sensitive message")
# Only collect what you need
data_collection:
store_conversations: true
store_user_ip: false # Not needed
store_user_agent: false # Not needed
store_full_request: false # Only store relevant fields
anonymize_after_days: 30
delete_after_days: 90
# input_validator.py
import re
MAX_INPUT_LENGTH = 4000
BLOCKED_PATTERNS = [
r'ignore\s+(all\s+)?previous\s+instructions',
r'system\s+prompt',
r'reveal\s+(your|the)\s+(instructions|prompt|rules)',
r'pretend\s+you\s+are',
r'jailbreak',
r'DAN\s+mode',
]
def validate_user_input(text):
"""Validate and sanitize user input before AI processing"""
if len(text) > MAX_INPUT_LENGTH:
return None, "Input too long"
if not text.strip():
return None, "Empty input"
# Check for prompt injection patterns
for pattern in BLOCKED_PATTERNS:
if re.search(pattern, text, re.IGNORECASE):
return None, "Blocked input pattern detected"
# Sanitize HTML/script content
sanitized = re.sub(r'<[^>]+>', '', text)
return sanitized, None
Log security events without exposing sensitive data:
# secure_logger.py
import logging
import re
class SanitizingFormatter(logging.Formatter):
"""Remove sensitive data from log output"""
SENSITIVE_PATTERNS = [
(r'password["\s:=]+\S+', 'password=***'),
(r'api[_-]?key["\s:=]+\S+', 'api_key=***'),
(r'token["\s:=]+[A-Za-z0-9._-]+', 'token=***'),
(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', '***@***.***'),
]
def format(self, record):
message = super().format(record)
for pattern, replacement in self.SENSITIVE_PATTERNS:
message = re.sub(pattern, replacement, message, flags=re.IGNORECASE)
return message
Set up automated security monitoring:
# security_monitoring.yml
alerts:
- name: "Failed Login Attempts"
condition: "failed_logins > 5 in 10m"
action: "block_ip + notify_admin"
- name: "Unusual API Usage"
condition: "api_calls > 1000 in 5m"
action: "rate_limit + notify_admin"
- name: "Data Export Spike"
condition: "data_export_size > 100MB in 1h"
action: "block_export + notify_admin"
- name: "New Admin Created"
condition: "user_role_changed to admin"
action: "notify_all_admins"
Application security for OpenClaw requires a defense-in-depth approach: strong authentication, granular authorization, encrypted data storage, input validation, secure logging, and continuous monitoring. Each layer protects against different attack vectors, and together they create a robust security posture.
Secure your OpenClaw deployment on Tencent Cloud Lighthouse — simple, high-performance, cost-effective — with predictable pricing and built-in network security features.
For detailed OpenClaw setup, refer to the configuration guide.