Skip to main content
Framefox provides enterprise-grade security features to protect your web applications from common vulnerabilities and attacks. The security system is built with defense-in-depth principles and includes multiple layers of protection.

Core Security Features

Framefox’s security architecture includes:
  • Authentication & Authorization: Multiple authentication methods with role-based access control
  • CSRF Protection: Automatic token generation and validation for form submissions
  • XSS Prevention: Input validation and output encoding to prevent cross-site scripting
  • SQL Injection Protection: Context-aware input sanitization and validation
  • Rate Limiting: Protection against DDoS and brute force attacks
  • Security Headers: Automatic application of security headers based on environment
  • Session Management: Secure session handling with JWT tokens
  • Brute Force Protection: Progressive delays and blocking for suspicious login attempts

Security Architecture

The security system is orchestrated by the FirewallHandler which manages all incoming requests:
# Security is automatically applied through middleware
# Configure in config/security.yaml
security:
  firewalls:
    main:
      pattern: ^/
      authenticator: app.security.CustomAuthenticator
      login_path: /login
      logout_path: /logout
      provider: app_user_provider
Reference: /home/daytona/workspace/source/framefox/core/security/handlers/firewall_handler.py:50

CSRF Protection

Framefox automatically protects against Cross-Site Request Forgery attacks:

How It Works

  1. CSRF tokens are automatically generated for each session
  2. Tokens are validated on form submissions (POST, PUT, PATCH)
  3. Invalid tokens are rejected with a security error

In Templates

Use the csrf_token() function in your forms:
<form method="POST" action="/login">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <input type="email" name="_username" required>
    <input type="password" name="_password" required>
    <button type="submit">Login</button>
</form>

Token Validation

The CsrfTokenBadge class handles validation using constant-time comparison:
def validate_csrf_token(self, request: Request):
    stored_token = request.cookies.get("csrf_token", "")
    if not secrets.compare_digest(self.token, stored_token):
        raise InvalidCsrfTokenException()
    return True
Reference: /home/daytona/workspace/source/framefox/core/security/passport/csrf_token_badge.py:32

XSS Prevention

Framefox provides multiple layers of XSS protection:

Input Validation

The InputValidationProtector automatically sanitizes user input:
from framefox.core.security.protector.input_validation_protector import InputValidationProtector

protector = InputValidationProtector()
clean_data, threats = protector.validate_and_sanitize(
    user_input, 
    field_name="comment",
    context="form"
)

if threats:
    # Handle security threat
    logger.warning(f"Security threats detected: {threats}")
Reference: /home/daytona/workspace/source/framefox/core/security/protector/input_validation_protector.py:71

Context-Aware Validation

The protector uses different validation rules based on context:
  • form: Full XSS and SQL injection checks
  • json: Structured data validation
  • html_content: Allows safe HTML for rich text
  • search: Removes special characters
  • file: Path traversal protection

Security Headers

Framefox automatically applies security headers:
# Applied automatically in production
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Content-Security-Policy: default-src 'self'
Reference: /home/daytona/workspace/source/framefox/core/security/protector/security_headers_protector.py:33

Access Control

Framefox implements role-based access control (RBAC):

Configuring Access Rules

# config/security.yaml
security:
  access_control:
    - { path: ^/admin, roles: [ROLE_ADMIN] }
    - { path: ^/api, roles: [ROLE_USER] }
    - { path: ^/public, roles: IS_AUTHENTICATED_ANONYMOUSLY }
  
  default_access_policy: deny  # or 'allow'

How It Works

The AccessManager evaluates access rules:
def is_allowed(self, user_roles: List[str], required_roles: List[str]) -> bool:
    if "IS_AUTHENTICATED_ANONYMOUSLY" in required_roles:
        return True
    
    if not required_roles:
        return True
    
    if not user_roles:
        return False
    
    return any(role in user_roles for role in required_roles)
Reference: /home/daytona/workspace/source/framefox/core/security/access_manager.py:56

Rate Limiting & Protection

Framefox includes multiple protection mechanisms:

Rate Limiting

Protects against DDoS and excessive requests:
# Configurable thresholds
max_requests = 200  # per window
window_seconds = 60
burst_protection = True  # Block extreme bursts
Reference: /home/daytona/workspace/source/framefox/core/security/protector/rate_limiting_protector.py:35

Brute Force Protection

Protects login endpoints:
  • Progressive delays after failed attempts
  • IP-based blocking (25 attempts/hour)
  • Account locking (15 attempts/hour)
  • Automatic cleanup of old attempts
Reference: /home/daytona/workspace/source/framefox/core/security/protector/brute_force_protector.py:39

Security Best Practices

1. Always Use CSRF Protection

<!-- Never forget the CSRF token in forms -->
<form method="POST">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <!-- form fields -->
</form>

2. Validate and Sanitize Input

# Always validate user input
clean_data, threats = protector.validate_and_sanitize(
    request.form.get("content"),
    field_name="content",
    context="form"
)

3. Use Role-Based Access Control

# Protect sensitive routes
access_control:
  - { path: ^/admin, roles: [ROLE_ADMIN] }
  - { path: ^/api/users, roles: [ROLE_USER, ROLE_ADMIN] }

4. Enable Security Headers

# Automatically applied in production (APP_ENV=prod)
# Configure strict_mode for development if needed
from framefox.core.security.protector.security_headers_protector import SecurityHeadersProtector

headers_protector = SecurityHeadersProtector(strict_mode=True)

5. Use Strong Password Hashing

from framefox.core.security.password.password_hasher import PasswordHasher

hasher = PasswordHasher()
hashed = hasher.hash("user_password")  # Uses bcrypt
valid = hasher.verify("user_password", hashed)

6. Implement Proper Logout

# Framefox handles logout automatically
# Clears: session, tokens, cookies
logout_path: /logout

Environment-Based Security

Framefox adjusts security based on your environment:

Development (APP_ENV=dev)

  • Lenient CSP policies for hot-reload
  • Allows localhost connections
  • SAMEORIGIN frame policy
  • Cross-origin resource sharing enabled

Production (APP_ENV=prod)

  • Strict CSP policies
  • DENY frame policy
  • HTTPS enforcement with HSTS
  • Same-origin resource policy
  • No inline scripts or eval
Reference: /home/daytona/workspace/source/framefox/core/security/protector/security_headers_protector.py:27

Next Steps

Authentication

Learn about user authentication and session management

CSRF Protection

Detailed guide to CSRF token handling

User Management

User models, providers, and role management

Build docs developers (and LLMs) love