Skip to main content

Midstar is a collection of middleware components for ASGI applications (like FastAPI and Starlette)

Project description

Midstar

Midstar is a collection of middleware components for ASGI applications (like FastAPI and Starlette) that provides essential security features, performance optimizations, and utility functions to enhance your web applications.

Installation

pip install midstar

Key Features

  • Security: CSRF protection, JWT authentication, and customizable security headers
  • Performance: HTTP caching with ETag support, rate limiting, and concurrent request limiting
  • Simple Configuration: Easy-to-use configuration objects for each middleware component

Middleware Components

Security Middleware

SecurityHeadersMiddleware

Adds essential security headers to HTTP responses to protect against common web vulnerabilities.

from starlette.applications import Starlette
from midstar.middleware import SecurityHeadersMiddleware, SecurityHeadersConfig

config = SecurityHeadersConfig(
    headers={
        "X-Content-Type-Options": "nosniff",
        "X-Frame-Options": "DENY",
        "Content-Security-Policy": "default-src 'self'"
    }
)
app = Starlette()
app.add_middleware(SecurityHeadersMiddleware, config=config)

CSRFProtectionMiddleware

Provides Cross-Site Request Forgery (CSRF) protection for your application.

from midstar.middleware import CSRFProtectionMiddleware, CSRFConfig

app.add_middleware(
    CSRFProtectionMiddleware, 
    config=CSRFConfig(
        secret_key=b"your-secret-key",
        token_lifetime=3600  # 1 hour
    )
)

JWTMiddleware

Handles JWT-based authentication for protected routes.

from midstar.middleware import JWTMiddleware

app.add_middleware(
    JWTMiddleware,
    jwt_secret="your-secret-key",
    jwt_algorithm="HS256",
    jwt_expires_in=3600
)

Performance Middleware

EdgeCacheMiddleware

Implements HTTP caching using ETags to reduce bandwidth and improve response times.

from midstar.middleware import EdgeCacheMiddleware, CacheConfig

cache_config = CacheConfig(
    max_age=300,  # 5 minutes
    s_maxage=600,  # 10 minutes for CDNs
    private_paths=["/user/", "/account/"],
    exclude_paths=["/admin/"],
    vary_by=["Accept", "Accept-Encoding"]
)

app.add_middleware(EdgeCacheMiddleware, config=cache_config)

RateLimitMiddleware

Protects your API from abuse by limiting the number of requests per client.

from midstar.core.backend import RedisBackend
from midstar.middleware import RateLimitMiddleware

redis_client = Redis(host="localhost", port=6379)
storage_backend = RedisBackend(redis_client)

app.add_middleware(
    RateLimitMiddleware,
    storage_backend=storage_backend,
    requests_per_minute=100,
    window_size=60
)

ConcurrentRequestMiddleware

Limits the number of concurrent requests to prevent server overload.

from midstar.middleware import ConcurrentRequestMiddleware

app.add_middleware(
    ConcurrentRequestMiddleware,
    max_concurrent_requests=100
)

Backend Storage Options

Midstar supports multiple backend storage options for rate limiting and other features:

RedisBackend

from redis.asyncio import Redis
from midstar.core.backend import RedisBackend

redis_client = Redis(host="localhost", port=6379)
backend = RedisBackend(redis_client)

InMemoryBackend

from midstar.core.backend import InMemoryBackend

backend = InMemoryBackend()

Example Application

Here's a complete example setting up multiple middleware components:

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from midstar.middleware import (
    RateLimitMiddleware,
    EdgeCacheMiddleware,
    ConcurrentRequestMiddleware,
    SecurityHeadersMiddleware,
    CacheConfig,
    SecurityHeadersConfig
)
from midstar.core.backend import InMemoryBackend

backend = InMemoryBackend()

app = Starlette(
    middleware=[
        Middleware(
            ConcurrentRequestMiddleware,
            max_concurrent_requests=100,
        ),
        Middleware(
            RateLimitMiddleware,
            storage_backend=backend,
            requests_per_minute=60,
            window_size=60
        ),
        Middleware(
            EdgeCacheMiddleware,
            config=CacheConfig(max_age=60)    
        ),
        Middleware(
            SecurityHeadersMiddleware,
            config=SecurityHeadersConfig(
                headers={
                    "X-Content-Type-Options": "nosniff",
                    "X-Frame-Options": "DENY",
                    "Content-Security-Policy": "default-src 'self'",
                }
            ),
        ),
    ]
)

@app.route("/")
def hello(request):
    return PlainTextResponse("Hello, world!")

License

This project is licensed under the MIT License - see the LICENSE file for details.

Download files

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

Source Distribution

midstar-0.1.0.tar.gz (12.6 kB view details)

Uploaded Source

Built Distribution

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

midstar-0.1.0-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file midstar-0.1.0.tar.gz.

File metadata

  • Download URL: midstar-0.1.0.tar.gz
  • Upload date:
  • Size: 12.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.2 CPython/3.12.10 Linux/6.8.0-1021-azure

File hashes

Hashes for midstar-0.1.0.tar.gz
Algorithm Hash digest
SHA256 3e301cb62215ae4cb9fe243d88e675148ca367df7932883b9f0d8b46dac83eb7
MD5 cc61f678bda6e1552995c57a681389ac
BLAKE2b-256 b07ba104ba596c6137465fc3762d5974ef66483d011cc933e7d1d49eb936018e

See more details on using hashes here.

File details

Details for the file midstar-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: midstar-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 16.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.2 CPython/3.12.10 Linux/6.8.0-1021-azure

File hashes

Hashes for midstar-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ecfe54259178d66787aaff94f9cc423592400bb078e7d1d59e811cec847534b1
MD5 439bd94d89d41d5e2d3ef90d399f4094
BLAKE2b-256 3189d75a91455303ea473f3c00002e64555523a831e56835077850c9a2f7c0e3

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