Serving Static Files from the Cloudflare Edge
Three years ago, I wrote about a way to purge only changed static files when deploying a static site. It is very useful and I still use it for this website to this day. Its main advantage is that it only needs to be run on deploys. However, its main disadvantage is that it must be run on every deployment. Sometimes, this is not feasible.
For example, I run a bunch of APT repositories on apt.quantum2.xyz. These
repositories are constantly being updated by Jenkins and me personally, and
using purge-static
would require adding a purge-static
command to
every script that updates the repositories, which is clearly infeasible.
Wouldn’t it be nice to just have a background daemon that purged the CDN cache
automatically?
As it turns out, I already wrote it back in 2015 before starting this blog. It was massively out-of-date (until very recently) and required you to use your all-powerful Cloudflare API key, providing a massive attack surface. However, I recently updated it, and hopefully, it will prove useful for you.
Here’s a quick introduction to using it:
Installing cfwatch
This is trivial. Simply run pip install cfwatch
.
API tokens
First, you want to create a Cloudflare API token, scoped to allow purging caches only. This way, even if the token leaked, all an attacker could do is constantly purge your cache and slow down your load times.
To create the API token, follow the following steps:
- Go to My Profile on the Cloudflare dashboard, and navigate to the API Tokens tab, then press Create Token.
- Select Create Custom Token, and press Get started.
- Give the token a suitable name.
- For permissions, select Zone, Cache purge, and Purge.
- For Zone Resources, make sure your zone is allowed. I would recommend for security reasons that you select Specific zone and allow only the zones you want to allow it to access. Don’t worry about being too restrictive here, as you can change the scopes later without rerolling the token.
- You may enable client IP address filtering if you want, but I don’t use it
- Press Continue to summary, confirm that the token is configured the way you wanted, then press Create token.
- Cloudflare will show you your API token, but only once.
Once you have your token, copy it and hold onto it for later.
Setting up cfwatch
Using cfwatch
is very simple. For this example, we will assume that your
static files are in /srv/static
and these files will be served from
https://www.example.com/static/
. In this case, invoke cfwatch
as follows:
$ CFWATCH_TOKEN="<cloudflare API token>" cfwatch example.com https://www.example.com/static/ /srv/static
Note that for the first argument, you should use the Cloudflare zone name, i.e. the domain that is added to Cloudflare, not a subdomain.
While this is good for testing, you should probably run cfwatch
as a daemon
instead. This can be done with systemd
or your favourite daemon manager.
This will be left as an exercise for the reader.