Bird
Raised Fist0
FastAPIframework~10 mins

Trusted host middleware in FastAPI - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Trusted host middleware
Request Received
Check Host Header
Is Host in Trusted List?
NoReject Request (400)
Yes
Pass Request to App
Response Sent
The middleware checks the request's Host header against a trusted list. If trusted, it passes the request to the app; otherwise, it rejects it.
Execution Sample
FastAPI
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "localhost"])
This code adds TrustedHostMiddleware to allow requests only from example.com and localhost.
Execution Table
StepRequest Host HeaderCheck Host in Allowed ListActionResult
1"example.com"YesPass to appRequest processed
2"localhost"YesPass to appRequest processed
3"malicious.com"NoReject request400 Bad Request response
4""NoReject request400 Bad Request response
💡 Requests with hosts not in allowed_hosts are rejected with 400 Bad Request.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
request_hostNone"example.com""localhost""malicious.com"""
allowed_hosts["example.com", "localhost"]["example.com", "localhost"]["example.com", "localhost"]["example.com", "localhost"]["example.com", "localhost"]
host_allowedFalseTrueTrueFalseFalse
Key Moments - 3 Insights
Why does the middleware reject requests with empty Host headers?
Because the empty string is not in the allowed_hosts list, as shown in execution_table step 4, so the middleware rejects it for safety.
What happens if the Host header matches exactly one of the allowed hosts?
The middleware passes the request to the app, as seen in steps 1 and 2 of the execution_table where 'example.com' and 'localhost' are allowed.
Can the allowed_hosts list contain wildcards or patterns?
No, allowed_hosts must be exact hostnames or IPs; the middleware checks exact matches as shown in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the action taken when the Host header is "malicious.com"?
APass to app
BReject request
CRedirect request
DIgnore Host header
💡 Hint
Check execution_table row 3 under 'Action' column.
At which step does the Host header check result in 'True' for host_allowed?
AStep 4
BStep 3
CStep 1
DNone
💡 Hint
Look at variable_tracker row for 'host_allowed' at 'After Step 1' and 'After Step 2'.
If we add "malicious.com" to allowed_hosts, how would step 3 in the execution table change?
AAction would be 'Pass to app' and Result 'Request processed'
BAction would remain 'Reject request'
CResult would be '500 Internal Server Error'
DNo change
💡 Hint
Consider how allowed_hosts affects 'host_allowed' and action in execution_table step 3.
Concept Snapshot
TrustedHostMiddleware checks the Host header of incoming requests.
It compares the Host to a list of allowed hosts.
If the Host is allowed, the request proceeds.
If not, the middleware rejects with 400 Bad Request.
Use it to protect your app from Host header attacks.
Full Transcript
Trusted host middleware in FastAPI checks the Host header of each incoming request. It compares this Host value to a list of allowed hosts you provide. If the Host matches one in the list, the middleware lets the request continue to your app. If it does not match, the middleware rejects the request with a 400 Bad Request response. This protects your app from requests pretending to come from untrusted hosts. The middleware works by intercepting requests, checking the Host header, and deciding to pass or reject based on your allowed hosts list.

Practice

(1/5)
1. What is the main purpose of the TrustedHostMiddleware in FastAPI?
easy
A. To block requests from hosts not in the allowed list
B. To speed up the response time of the app
C. To handle database connections securely
D. To manage user authentication tokens

Solution

  1. Step 1: Understand middleware role

    The TrustedHostMiddleware is designed to filter incoming requests based on their host header.
  2. Step 2: Identify its security purpose

    It blocks requests from hosts not explicitly allowed to protect against host header attacks.
  3. Final Answer:

    To block requests from hosts not in the allowed list -> Option A
  4. Quick Check:

    TrustedHostMiddleware blocks unknown hosts = D [OK]
Hint: Remember: Trusted hosts means allowed hosts only [OK]
Common Mistakes:
  • Confusing it with authentication middleware
  • Thinking it speeds up app performance
  • Assuming it manages database connections
2. Which of the following is the correct way to add TrustedHostMiddleware to a FastAPI app?
easy
A. app.middleware(TrustedHostMiddleware, allowed=['example.com'])
B. app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com'])
C. app.use(TrustedHostMiddleware, hosts=['example.com'])
D. app.add_middleware(TrustedHostMiddleware, hosts=['example.com'])

Solution

  1. Step 1: Recall FastAPI middleware syntax

    FastAPI uses app.add_middleware() with the middleware class and keyword arguments.
  2. Step 2: Check correct argument name

    The correct argument for allowed hosts is allowed_hosts, not hosts or allowed.
  3. Final Answer:

    app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com']) -> Option B
  4. Quick Check:

    Use add_middleware with allowed_hosts = C [OK]
Hint: Use add_middleware and allowed_hosts keyword [OK]
Common Mistakes:
  • Using wrong method like app.use()
  • Passing 'hosts' instead of 'allowed_hosts'
  • Incorrect argument names like 'allowed'
3. Given this FastAPI app code snippet, what will happen if a request comes from host 'malicious.com'?
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', 'localhost'])

@app.get('/')
def read_root():
    return {'message': 'Hello World'}
medium
A. The request will be redirected to 'example.com'
B. The request will succeed and return 'Hello World'
C. The app will crash with an exception
D. The request will be blocked with a 400 Bad Request error

Solution

  1. Step 1: Check allowed hosts list

    The allowed hosts are 'example.com' and 'localhost'. 'malicious.com' is not in this list.
  2. Step 2: Understand middleware behavior on unknown hosts

    TrustedHostMiddleware blocks requests from hosts not in the allowed list by returning a 400 error.
  3. Final Answer:

    The request will be blocked with a 400 Bad Request error -> Option D
  4. Quick Check:

    Unknown host causes 400 error = A [OK]
Hint: Requests from hosts not allowed get 400 error [OK]
Common Mistakes:
  • Assuming the request passes through
  • Thinking the app crashes on unknown hosts
  • Believing the request is redirected automatically
4. Identify the error in this FastAPI app setup using TrustedHostMiddleware:
from fastapi import FastAPI
from starlette.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts='example.com')

@app.get('/')
def home():
    return {'msg': 'Welcome'}
medium
A. The route function must be async
B. TrustedHostMiddleware is not imported correctly
C. allowed_hosts should be a list, not a string
D. Missing middleware initialization parameters

Solution

  1. Step 1: Check allowed_hosts argument type

    The allowed_hosts parameter expects a list of strings, but a single string was given.
  2. Step 2: Understand impact of wrong type

    Passing a string instead of a list will cause the middleware to treat each character as a host, leading to incorrect behavior or errors.
  3. Final Answer:

    allowed_hosts should be a list, not a string -> Option C
  4. Quick Check:

    allowed_hosts must be list = A [OK]
Hint: allowed_hosts always needs a list, not a string [OK]
Common Mistakes:
  • Passing a single string instead of list
  • Thinking route functions must be async
  • Assuming import is incorrect without error
5. You want to allow requests from any subdomain of example.com and also from localhost. Which allowed_hosts list correctly configures TrustedHostMiddleware for this?
hard
A. ['*.example.com', 'localhost']
B. ['example.com', 'localhost']
C. ['example.com/*', 'localhost']
D. ['*example.com', 'localhost']

Solution

  1. Step 1: Understand wildcard usage in allowed_hosts

    TrustedHostMiddleware supports wildcards like *.example.com to allow all subdomains.
  2. Step 2: Check each option for correct wildcard syntax

    ['*.example.com', 'localhost'] uses '*.example.com' which correctly matches all subdomains; others use incorrect patterns.
  3. Final Answer:

    ['*.example.com', 'localhost'] -> Option A
  4. Quick Check:

    Use '*.example.com' for subdomains = B [OK]
Hint: Use '*.domain.com' to allow all subdomains [OK]
Common Mistakes:
  • Using 'example.com/*' which is invalid
  • Using '*example.com' missing dot after *
  • Not using wildcard for subdomains