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.0.0.tar.gz (100.6 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.0.0-py3-none-any.whl (7.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ip_safelist_middleware-1.0.0.tar.gz
  • Upload date:
  • Size: 100.6 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.0.0.tar.gz
Algorithm Hash digest
SHA256 b87906d1434e81e15eb77d7742625d5cb18fdb8f2e001caed3985db2a34c05d6
MD5 47eb8b2590429c96b0b4cf5475730f38
BLAKE2b-256 5bbaf8761144c2a88ac9612e22c64cf1ec8f33fa24b9b86c4dcd87a0a2110f07

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for ip_safelist_middleware-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 894be3972d5e45eef2ef5a1210b514bd5fdf355bd4ad4c6e8f8790152172c04d
MD5 98f652fd9d28aa2915735bea08234719
BLAKE2b-256 63b3949f0ae6cdbfaf7686fbd26fe757fcaadd32c80e663157eabe1c6053cf31

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