URL safety validation for redirect targets.
Prevents open redirect attacks by ensuring redirect URLs are relative paths on the same origin.
Usage::
from chirp.security.urls import is_safe_url
next_url = request.query.get("next", "/")
if is_safe_url(next_url):
return Redirect(next_url)
else:
return Redirect("/")
security.urls
| Name | Type | Default | Description |
|---|---|---|---|
type
|
|
— | |
qualified_name
|
|
— | |
element_type
|
|
— | |
description
|
|
— | |
source_file
|
|
— | |
line_number
|
|
— | |
is_autodoc
|
|
— | |
autodoc_element
|
|
— | |
_autodoc_template
|
|
— | |
_autodoc_url_path
|
|
— | |
_autodoc_page_type
|
|
— | |
title
|
|
— | |
doc_content_hash
|
|
— |
Symbols on this page
is_safe_url
function
def is_safe_url(url: str) -> bool
Check whether url is safe to redirect to.
A URL is considered safe only if it resolves to a relative path on the same origin. The decision is made against a browser-normalized view of the value, because browsers:
- ignore leading ASCII control characters and whitespace, and
- treat backslashes (
\) as forward slashes in the URL path.
So this function strips leading control/whitespace bytes, rejects any leading-backslash form, and normalizes embedded backslashes to forward slashes before checking that the value:
- is a non-empty string
- starts with
/ - does not start with
//(protocol-relative URL) - does not contain
://(absolute URL with scheme)
This closes the backslash open-redirect:"/\evil.com"normalizes to
"//evil.com" in the browser (a protocol-relative jump to evil.com)
and is correctly rejected, as is"\\evil.com". Legitimate relative
paths are unaffected.
Examples::
>>> is_safe_url("/dashboard")
True
>>> is_safe_url("/login?next=/home")
True
>>> is_safe_url("//evil.com")
False
>>> is_safe_url("https://evil.com")
False
>>> is_safe_url("/\\evil.com")
False
>>> is_safe_url("")
False
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
url
|
str
|
— |
View source · /home/runner/work/chirp/chirp/site/../src/chirp/security/urls.py:1