# 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. ```text 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.py` is a late hook for requests under `/API/v2` - `reports.hook.early.py` is 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](#hooks-and-http-methods). A `GET` request to `/API/v2/reports/company` runs: 1. `reports.hook.early.py` 2. `company.page.get.py` 3. `v2.hook.late.py` A `GET` request to `/API/v2/users` runs: 1. `users.page.get.py` 2. `v2.hook.late.py` A hook is a `main()` function like any other handler. It can ask for the same [parameters](handlers.md#handler-parameters) and it returns the response. Hooks also run around [static files](static-files.md), 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: ```python 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: ```text 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`: ```python 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()`](errors.md#abort) in an early hook stops the request before the page handler runs. A hook runs for [every HTTP method](#hooks-and-http-methods), so no request gets past this one by using another. `config` is an [extra parameter](composition.md#extra-parameters-on-main) 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: ```text 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: 1. `webapp1.hook.early.py` 2. `admin.hook.early.py` 3. `reports.hook.early.py` 4. `reports.page.get.py` 5. `admin.hook.late.py` 6. `webapp1.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 `/admin` runs after it, and cannot switch it off. When an early hook calls `abort()`, 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: ```python # 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: ```python # 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](routing.md#when-nothing-matches). 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: ```python # 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](#example-answering-a-preflight-request) 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: ```text my_webapps |-- webapp1.hook.early.py |-- webapp1.page.get.py |-- /webapp1 |-- /API |-- /v2 |-- reports.page.get.py ``` `webapp1.hook.early.py`: ```python 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](routing.md#one-spelling-for-each-url), 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`: ```python 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](security.md#redirect-only-where-you-mean-to) 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`: ```python 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)`](errors.md#ending-a-request-with-the-response-itself) 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](errors.md#what-survives-an-abort). - A file named `API.tree.options.py` would 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 a `GET` to it would get a `405` in place of a `404`. ## 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](handlers.md#only-a-page-handler-reads-the-request-body), 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](routing.md#when-nothing-matches) passes through the early hooks before it is answered with a `404`, a `405`, or a `501`, 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 that `404` too. - **A hook always covers the paths beneath it.** A page handler takes on the paths beneath it only as a [`.tree.` file](routing.md#handlers-for-a-whole-tree). 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.py` runs for `/users/123` and everything beneath it, and can ask for `user_id`. See [Placeholders](routing.md#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 [plain `500`](errors.md#cylinder-always-answers) that takes the place of a response that cannot be sent at all, such as one whose `Location` a handler set to a URL that Werkzeug cannot read. In a late hook, the `e` parameter is the exception, or `None` if the request succeeded. A header that only suits a successful response, such as a long `Cache-Control`, needs a check on `response.status_code` first. For static files, see [what a late hook sees](static-files.md#what-a-late-hook-sees-for-a-static-file). - **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 `response` is still there when the page handler runs. To pass other data from a hook to a handler, see [the `g` object](composition.md#the-g-object).