Skip to main content

FastAPI Middleware for IP Address Safelisting

Project description

ip-safelist-middleware

FastAPI Middleware for IP Address Safelisting. This middleware allows you to restrict access to your FastAPI application based on client IP addresses.

Features

  • IP address filtering based on exact match or network ranges (CIDR notation)
  • Support for AWS IP ranges from specified regions
  • Path-based access control using regex patterns
  • Environment variable configuration with pydantic-settings
  • Customizable HTTP status code and message for blocked requests

Installation

pip install ip-safelist-middleware

Usage

Basic Usage with Environment Variables

from fastapi import FastAPI
from ip_safelist_middleware import IPSafeListMiddleware, ListItem, ListType

app = FastAPI()

# Configure the middleware to use environment-based IP safe list
app.add_middleware(
    IPSafeListMiddleware,
    list_items=[
        ListItem(path=r'^/api/.*$', type=ListType.env),
    ]
)

Set the environment variable to specify allowed IPs:

export IP_SAFELIST_NETWORKS="127.0.0.1,192.168.0.0/24,10.0.0.0/8"

Using AWS IP Ranges

from fastapi import FastAPI
from ip_safelist_middleware import IPSafeListMiddleware, ListItem, ListType

app = FastAPI()

# Configure the middleware to use AWS IP ranges for specific paths
app.add_middleware(
    IPSafeListMiddleware,
    list_items=[
        ListItem(path=r'^/admin/.*$', type=ListType.aws),
    ]
)

Configure AWS regions through environment variables:

export IP_SAFELIST_AWS_REGIONS="us-east-1,us-west-2"

Combined Configuration

You can combine different allowlist types for different paths:

from fastapi import FastAPI
from ip_safelist_middleware import IPSafeListMiddleware, ListItem, ListType

app = FastAPI()

app.add_middleware(
    IPSafeListMiddleware,
    list_items=[
        ListItem(path=r'^/admin/.*$', type=ListType.aws),  # AWS IPs for admin
        ListItem(path=r'^/api/internal/.*$', type=ListType.env),  # Environment IPs for internal API
        ListItem(path=r'^/(?!health).*$', type=ListType.env),  # Environment IPs for everything except health
    ]
)

Excluding Paths

To exclude paths (e.g., health checks), use negative lookahead in your regex pattern:

ListItem(path=r'^/(?!health).*$', type=ListType.env)  # All paths except /health

Custom Error Response

You can customize the HTTP status code and message returned to blocked requests:

app.add_middleware(
    IPSafeListMiddleware,
    list_items=[
        ListItem(path=r'^/api/.*$', type=ListType.env),
    ],
    status_code=401,
    status_message="Unauthorized access"
)

Default Behavior

When added to your FastAPI application without any parameters:

  • The middleware blocks all paths by default (matches pattern ^/.*$)
  • It uses the environment-based allowlist type
  • If no IP addresses are specified in the IP_SAFELIST_NETWORKS environment variable, all requests will be blocked
  • Blocked requests receive a 403 Forbidden response
  • AWS IP ranges are disabled by default

Example of default behavior:

app.add_middleware(IPSafeListMiddleware)  # No parameters - blocks all requests by default

To allow any traffic, you must explicitly define allowed IP addresses through environment variables or custom configurations.

Custom Rules

If you do not use the default path of ^/.*$ and add your own path rules, requests to a path without a defined rule will be refused.

Configuration

The middleware can be configured using environment variables:

Environment Variable Description Default
IP_SAFELIST_NETWORKS Comma-separated list of IP addresses or CIDR blocks None
IP_SAFELIST_AWS_ENABLED Enable/disable AWS IP ranges False
IP_SAFELIST_AWS_REGIONS Comma-separated list of AWS regions us-east-1,us-east-2
IP_SAFELIST_STATUS_CODE HTTP status code for blocked requests 403
IP_SAFELIST_STATUS_MESSAGE Message returned for blocked requests Forbidden

License

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

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

ip_safelist_middleware-1.1.0.tar.gz (100.8 kB view details)

Uploaded Source

Built Distribution

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

ip_safelist_middleware-1.1.0-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

Details for the file ip_safelist_middleware-1.1.0.tar.gz.

File metadata

  • Download URL: ip_safelist_middleware-1.1.0.tar.gz
  • Upload date:
  • Size: 100.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for ip_safelist_middleware-1.1.0.tar.gz
Algorithm Hash digest
SHA256 d11ac210f9c8195671edaec3a844d4b1bf54e5fcee7df0a617ef45c528d6eda7
MD5 e995f693d034c916f3b1c6c4bd8ba883
BLAKE2b-256 7d457a7208e0a13983168d7e619f586c5090e65f0e004c19a2dfb0fa5c322805

See more details on using hashes here.

File details

Details for the file ip_safelist_middleware-1.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for ip_safelist_middleware-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 21ef38bb5e0d4a6cfd90da12b713dac5e466afccbcd34ab12bb9555f163cb686
MD5 b6b0590df48924a253ef9aa1793450a0
BLAKE2b-256 125e0279c47b7cea3f9f361a340d3e8ecbd43592cfabc71464d7d47e1d12297d

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