Skip to main content

Zero-config network request obfuscation middleware for FastAPI - protect your APIs from reverse engineering

Project description

rossetta-fastapi

Zero-config network request obfuscation middleware for FastAPI

Features

  • 🔒 Automatic endpoint obfuscation - API endpoints are hashed and unreadable
  • 🔐 Request/response encryption - AES-256-CBC encryption for all data
  • Session-based key management - No hardcoded secrets in frontend
  • 🛡️ Anti-replay protection - Timestamp validation prevents replay attacks
  • 📝 Request signatures - HMAC-SHA256 ensures request integrity

Installation

pip install rossetta-fastapi

Quick Start

from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware
from rossetta_fastapi import setup_rossetta

app = FastAPI()

# Setup Rossetta - this adds middleware AND creates /api/init-session endpoint
setup_rossetta(app)

# Add session middleware (required)
app.add_middleware(SessionMiddleware, secret_key="your-secret-key-here")

# Define your routes normally - responses are automatically encrypted!
@app.get("/api/users")
async def get_users():
    return {"users": []}  # Automatically encrypted

@app.post("/api/users")
async def create_user(request: Request):
    data = request.state.decrypted_data  # Incoming data is auto-decrypted
    return {"id": 1, "name": data["name"]}  # Response is auto-encrypted

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

That's it! All /api/* endpoints automatically get:

  • ✅ Request decryption (access via request.state.decrypted_data)
  • ✅ Response encryption (just return your data normally)
  • ✅ Session initialization endpoint at /api/init-session

Usage

Basic Setup

from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware
from rossetta_fastapi import setup_rossetta

app = FastAPI()

# Setup Rossetta - automatically creates /api/init-session and adds middleware
setup_rossetta(
    app,
    secret="your-rossetta-secret",  # Optional
    timestamp_window=300000  # 5 minutes (default)
)

# Add session middleware (required)
app.add_middleware(
    SessionMiddleware,
    secret_key="your-secret-key-here"
)

All /api/* endpoints now automatically encrypt responses and decrypt requests!

Reading Decrypted Requests

For POST/PUT/DELETE requests, access decrypted data via request.state.decrypted_data:

@app.post("/api/create")
async def create_item(request: Request):
    # Decrypted data is automatically available
    data = request.state.decrypted_data
    name = data.get('name')
    
    # Just return your response - encryption happens automatically
    return {"id": 1, "name": name}

Working with GET Requests

GET requests return encrypted responses automatically:

@app.get("/api/data")
async def get_data(request: Request):
    # Just return your data normally
    return {"message": "Hello, World!"}  # Automatically encrypted

Note:

  • All /api/* endpoints are automatically encrypted (except /api/init-session)
  • The /api/init-session endpoint is automatically created by setup_rossetta()
  • You don't need to manually encrypt/decrypt - it's all handled for you!

How It Works

  1. Session Initialization: Client requests session keys
  2. Key Generation: Server generates unique encryption keys per session
  3. Endpoint Obfuscation: All endpoints are hashed using SHA-256
  4. Request Encryption: Client encrypts requests with session key
  5. Server Decryption: Middleware automatically decrypts and validates
  6. Response Encryption: Responses are encrypted before sending

Security Features

  • No Hardcoded Secrets: Keys are generated per session
  • Perfect Forward Secrecy: Each session has unique keys
  • Replay Attack Prevention: Timestamp-based validation
  • Request Integrity: HMAC signatures prevent tampering
  • Endpoint Obfuscation: API structure hidden from inspection

⚠️ Production Deployment

IMPORTANT: This package provides obfuscation and encryption at the application layer. For production use, you MUST also implement:

Required for Production:

  1. HTTPS/TLS: Always use HTTPS in production

    • Obfuscation is NOT a replacement for TLS
    • Use valid SSL/TLS certificates
    • Configure HSTS headers
  2. Environment Variables: Never hardcode secrets

    ROSSETTA_SECRET_KEY=your-secure-random-key-here
    
  3. Rate Limiting: Add rate limiting middleware

    from slowapi import Limiter
    limiter = Limiter(key_func=get_remote_address)
    
  4. Authentication & Authorization: Add proper auth layer

    • This package only handles obfuscation
    • Implement JWT, OAuth, or session-based auth
  5. Database Security: Use parameterized queries/ORMs

  6. Input Validation: Validate all user inputs with Pydantic

  7. CORS Configuration: Restrict allowed origins

Recommended Security Stack:

[Client] → HTTPS/TLS → [Rate Limiter] → [Auth Middleware] → [Rossetta Middleware] → [Your API]

Environment Variables

ROSSETTA_SECRET_KEY=your-secret-key-here  # Optional

API Reference

setup_rossetta(app, secret=None, timestamp_window=300000)

Main setup function that configures Rossetta for your FastAPI app.

Parameters:

  • app (FastAPI): Your FastAPI application instance
  • secret (str): Secret key for encryption (auto-generated if not provided)
  • timestamp_window (int): Request validity window in milliseconds (default: 300000)

What it does:

  • Creates the /api/init-session endpoint automatically
  • Adds the RossettaMiddleware to your app

RossettaMiddleware

The underlying middleware class (automatically added by setup_rossetta).

Parameters:

  • secret (str): Secret key for encryption (auto-generated if not provided)
  • timestamp_window (int): Request validity window in milliseconds (default: 300000)

Request State

After middleware processing:

  • request.state.rossetta['session_key']: Current session encryption key
  • request.state.rossetta['endpoint_salt']: Salt for endpoint obfuscation
  • request.state.rossetta['obfuscate_endpoint']: Function to obfuscate endpoints
  • request.state.rossetta['encrypt']: Function to encrypt data
  • request.state.rossetta['decrypt']: Function to decrypt data
  • request.state.decrypted_data: Decrypted request payload

Helper Functions (Advanced Usage)

Most users won't need these - automatic encryption is enabled by default for all /api/* endpoints.

encrypt_response(data, session_key)

Manually encrypt response data (rarely needed).

Parameters:

  • data (dict): Data to encrypt
  • session_key (str): Session encryption key

Returns: Encrypted string

@protected_route

Decorator for manual control over response encryption (rarely needed).

Usage:

from rossetta_fastapi import protected_route

@app.get('/api/data')
@protected_route
async def get_data(request: Request):
    return {'message': 'Hello, World!'}

Note: This decorator is optional since automatic encryption is enabled for all /api/* endpoints.

Complete Example

from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware
from rossetta_fastapi import setup_rossetta

app = FastAPI()

# Setup Rossetta - this creates /api/init-session automatically
setup_rossetta(app)

# Add session middleware
app.add_middleware(SessionMiddleware, secret_key="super-secret")

# All your API routes work normally - encryption is automatic!
@app.get("/api/todos")
async def list_todos(request: Request):
    todos = [
        {"id": 1, "text": "Learn Rossetta API", "completed": False}
    ]
    return todos  # Automatically encrypted

@app.post("/api/todos")
async def create_todo(request: Request):
    # Access decrypted request data
    data = request.state.decrypted_data
    
    todo = {
        "id": 2,
        "text": data['text'],
        "completed": False
    }
    # Just return the data - encryption is automatic
    return todo

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

That's it! No manual encryption/decryption code needed. The middleware handles everything automatically for all /api/* endpoints.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rossetta_fastapi-0.1.3.tar.gz (9.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rossetta_fastapi-0.1.3-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

Details for the file rossetta_fastapi-0.1.3.tar.gz.

File metadata

  • Download URL: rossetta_fastapi-0.1.3.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for rossetta_fastapi-0.1.3.tar.gz
Algorithm Hash digest
SHA256 fda6beb7e3434c1f538ce8c3f42076a22903a93967b56bd7b21b22a22eeb7ef0
MD5 00d70a70e0a20e5ffad535801619ebeb
BLAKE2b-256 0f8091675ee385e3cbc956f90976be4c6e21ab90bf43ae8013077a387caec379

See more details on using hashes here.

File details

Details for the file rossetta_fastapi-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for rossetta_fastapi-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 0e880e0dec5a2eec7562513653876f8b754e8a7b6606d05da251563e840fb246
MD5 7b05d94823b9ede1157b55f1877f58b2
BLAKE2b-256 bc6e3d0ea4583a3c0da26c72c19d84fa8a4f114d4b595c27aef472b0cfb1a6b9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page