Hooks
A hook is a file that runs before or after the page handlers in its part of the tree. Hooks are how you
apply one piece of logic to a whole section of a site: an authentication check for everything under
/admin, a set of security headers for every page, a JSON content type for an API.
Because a hook is a file in the tree, you can see where it applies. There is no middleware stack to trace and no ordering to configure.
Early hooks and late hooks
There are two kinds, marked in the filename:
Early hooks (
.hook.early) run before the page handler.Late hooks (
.hook.late) run after it.
my_webapps
|-- webapp1.page.get.py
|-- /webapp1
|-- /API
|-- v2.hook.late.py
|-- /v2
|-- reports.hook.early.py
|-- reports.page.get.py
|-- users.page.get.py
|-- /reports
|-- company.page.get.py
In this layout:
v2.hook.late.pyis a late hook for requests under/API/v2reports.hook.early.pyis an early hook for requests under/API/v2/reports
A hook is placed like a page handler: reports.hook.early.py sits beside the reports directory and
covers /API/v2/reports and everything beneath it. Unlike a page handler, it is not named for an HTTP
method, and runs for every one.
A GET request to /API/v2/reports/company runs:
reports.hook.early.pycompany.page.get.pyv2.hook.late.py
A GET request to /API/v2/users runs:
users.page.get.pyv2.hook.late.py
A hook is a main() function like any other handler. It can ask for the same
parameters and it returns the response.
Hooks also run around static files, so a late hook can add headers to them.
What each kind is for
Early hooks are a good place to check something before the page runs, or to set a default the page may override. A late hook runs after the page handler and gets the last word, so it is the place to enforce something.
For example, if v2.hook.late.py contains:
def main(response):
response.headers["Content-Security-Policy"] = "default-src 'self';"
return response
then every response under /API/v2 carries that policy, even if a page handler set a different one.
Example: protecting a section of a site
To require a token for everything under /admin, add one early hook:
my_webapps
|-- webapp1.page.get.py
|-- /webapp1
|-- admin.hook.early.py
|-- admin.page.get.py
|-- /admin
|-- users.page.get.py
|-- users.page.post.py
admin.hook.early.py:
import hmac
def main(request, response, abort, config):
supplied = request.headers.get("X-Admin-Token", "")
if not hmac.compare_digest(supplied.encode(), config["admin_token"].encode()):
abort(401)
return response
Calling abort() in an early hook stops the request before the page handler runs. A
hook runs for every HTTP method, so no request gets past this one by using
another. config is an extra parameter supplied by the
application.
hmac.compare_digest() takes the same time whether the token is wrong in its first character or its last,
so the time a request takes tells a client nothing about the token. It is given bytes because it raises an
error for a str that is not ASCII, and a client is free to send one.
None of the handlers under /admin mention authentication. A page added to that directory next year is
protected without anyone remembering to protect it.
Every hook on the path runs
A request runs every hook between the site root and its URL, not only the closest one:
Early hooks run from the site root down. The hook at the root runs first, and the one closest to the URL runs last, just before the page handler.
Late hooks run from the URL back up. The hook closest to the URL runs first, and the hook at the root runs last.
Given these hooks:
my_webapps
|-- webapp1.hook.early.py
|-- webapp1.hook.late.py
|-- /webapp1
|-- admin.hook.early.py
|-- admin.hook.late.py
|-- /admin
|-- reports.hook.early.py
|-- reports.page.get.py
a GET request to /admin/reports runs:
webapp1.hook.early.pyadmin.hook.early.pyreports.hook.early.pyreports.page.get.pyadmin.hook.late.pywebapp1.hook.late.py
The order is what makes hooks safe to rely on:
A hook can only add to the ones above it. If authentication for the whole site lives in the early hook at the root, a hook added later for
/adminruns after it, and cannot switch it off. When an early hook callsabort(), the early hooks below it and the page handler do not run.The root has the last word on the response. A header set in the late hook at the root is set after every other hook and handler has run, so nothing deeper in the tree can change it.
A hook for a section therefore holds only what is particular to that section:
# admin/reports.hook.early.py
def main(response, abort, g):
# the hooks above this one have already checked that the visitor is signed in
if "reports" not in g.permissions:
abort(403)
return response
To see which hooks apply to a URL, list the directories above it. Every file there that is named for a part
of the URL, with .hook. after the name, runs.
A hook cannot opt out of the ones above it. When one part of a protected section has to be public, such as
/admin/login, make the exception in the hook that does the protecting, where it can be seen:
# admin.hook.early.py
def main(request, response, abort):
if request.path != "/admin/login" and not request.cookies.get("session_id"):
abort(302, "/admin/login")
return response
Hooks and HTTP methods
A page handler is named for an HTTP method, and a hook is not. A hook runs for every request beneath its
path, whatever the method is: GET, POST, a method of your own, and a method that
no page handler can be named for.
That is what makes a hook a safe place for a check. No method is left out of it, and no file can be put beside a hook to answer in its place for one method.
A hook that treats a method differently says so in its code. This one turns down a request that changes something unless its body is JSON:
# API.hook.early.py
def main(request, response, abort):
if request.method not in ("GET", "HEAD") and not request.is_json:
abort(415)
return response
The same goes for a method that a check should let through, such as the OPTIONS request that a browser
sends before a cross-origin one. The exception is a line in the hook that makes the check, as an exception
for a path is, and not a second file. An example below answers
that request in the hook.
Every page handler and hook ends in three parts, and the middle one says what the file is:
reports.page.get.py is a page handler, and reports.hook.early.py is a hook. An error handler ends in
its status, as reports.404.py does. So a filename can only be read one way, whatever a URL or a method is
called.
Example: a header on every response
To allow cross-origin requests across an entire site, put an early hook at the root:
my_webapps
|-- webapp1.hook.early.py
|-- webapp1.page.get.py
|-- /webapp1
|-- /API
|-- /v2
|-- reports.page.get.py
webapp1.hook.early.py:
def main(response):
response.access_control_allow_origin = "*"
return response
Because the hook is at the root, it runs for every request to the site, whatever other hooks a section adds.
Example: redirecting a stray slash
Cylinder serves a page at one URL only, so /about/ is a 404
when the page is /about. A site that would sooner send that visitor on to the page can do it in an early
hook at the root, because hooks run before a request is turned down:
webapp1.hook.early.py:
from urllib.parse import quote
def main(request, response, abort):
tidy = "/" + "/".join(part for part in request.path.split("/") if part)
if request.path != tidy:
query = request.query_string.decode()
abort(308, quote(tidy) + (f"?{query}" if query else ""))
return response
The hook takes out a slash at the end and a slash too many, and keeps the query string. It does not see a
slash too many at the very start, as in //about: Werkzeug has merged those into one in request.path,
and the URL stays a 404. A 308 redirect keeps the method and the body of the request as well. A URL
that the hook leaves as it is, such as one with a .. in it, is still a 404.
quote() is not optional. request.path is the path with the client’s percent-encoding undone, so it can
hold characters that mean something else in a Location. Sent back as it is, /%09/evil.example/ becomes
a redirect to //evil.example, which a browser reads as another site, and /a%3Fb/ becomes one to /a?b.
Encoded again, each stays a path on this site. Security has
the general rule.
Example: answering a preflight request
Before a page on another origin sends a request with an Authorization header, the browser asks permission
with an OPTIONS request, and sends it without the header. A hook that checks the header would turn it
away. This one answers it instead:
API.hook.early.py:
import hmac
def main(request, response, abort, config):
response.access_control_allow_origin = config["app_origin"]
if request.method == "OPTIONS":
response.status_code = 204
response.access_control_allow_methods = ["GET", "POST"]
response.access_control_allow_headers = ["Authorization", "Content-Type"]
abort(response)
supplied = request.headers.get("Authorization", "")
if not hmac.compare_digest(supplied.encode(), f"Bearer {config['api_token']}".encode()):
abort(401)
return response
abort(response) ends the request with the response
as the hook left it. No page handler runs, so the answer is the same for every URL under /API, and no URL
needs a file for OPTIONS.
The first line runs for every request, so the header is on the answer to the real request as well, and on the
401: headers survive an abort.A file named
API.tree.options.pywould answer the same requests, and change the answer to others. A.tree.handler serves every path beneath it, so a URL that nobody wrote a page for would have a page for one method, and aGETto it would get a405in place of a404.
What hooks can and cannot do
Hooks cannot read the request body unless they opt in. A request is let in or turned away on its headers, before anything is done with its body, and a late hook is held to the same rule as an early one. See the rules Cylinder enforces, which also shows a hook that needs the body, for a CSRF token in a form.
Hooks run whether or not a page is found. A request for a URL that no page handler serves passes through the early hooks before it is answered with a
404, a405, or a501, and through the late hooks afterwards. So a hook that checks authentication turns an anonymous visitor away without revealing which URLs exist, and a header set in a hook is on that404too.A hook always covers the paths beneath it. A page handler takes on the paths beneath it only as a
.tree.file. Hooks and error handlers have no such kind, because they always cover theirs.A hook can be named with a placeholder.
users/{user_id}.hook.early.pyruns for/users/123and everything beneath it, and can ask foruser_id. See Placeholders.Late hooks run after errors and redirects too. If a page handler calls
abort()or raises an exception, the late hook still runs on the error response, so a security header set there is not skipped. The one response that it does not reach is the plain500that takes the place of a response that cannot be sent at all, such as one whoseLocationa handler set to a URL that Werkzeug cannot read. In a late hook, theeparameter is the exception, orNoneif the request succeeded. A header that only suits a successful response, such as a longCache-Control, needs a check onresponse.status_codefirst. For static files, see what a late hook sees.A late hook that fails does not run twice. If a late hook raises, the error takes the place of the response, and that hook is not run again. The late hooks above it still run, on the error.
Hooks share the response with the page handler. Whatever an early hook sets on
responseis still there when the page handler runs. To pass other data from a hook to a handler, see thegobject.