This post is a quick introduction to creating a Cloudflare worker. The worker it's self is a way to feel out the platform and a stepping stone to a more thorough worker that I'll be putting together to protect staging environment without having to resort to IP Address whitelisting to stop unauthorized users from accessing it and search engines from indexing it.
Let's start at the start.
Workers are Cloudflare's edge computing platform. This allows us to run code within Cloudflare's data centres rather than having to do all processing at the origin server.
Cloudflare workers operate on the request at the edge of the Cloudflare network. Here they can intercept, reject, redirect. modify or respond to a request. This can have a range of benefits including:
- Faster response time when responding from the edge.
- Modify the request before it hits an origin server, injecting additional data that can be used by the origin server to validate requests or serve them from their correct location.
- Filter out requests that shouldn't be allowed through to the origin server.
The simplest place to get started creating your first Cloudflare worker is by using the Cloudflare console.
Once you've logged in open the workers page from the top menu.
Select Manage workers to view/add/edit/delete your Cloudflare workers.
In the manage workers page select create a worker to make a new worker
Now add the code. This sample code will check if there is a
__gateway_auth cookie present on the request. If it is there it will transparently pass the request through to the origin and return the value. The code in the screenshot below can be found in this gist.
Save the worker code and navigate back to the domain that you want to add the worker into. I'm going to use my
[saladsimulator.com](http://saladsimulator.com) joke website.
Select Add route to open the dialogue
Add the worker on a route on your domain so that it's executed when a request is made on that path. For this example I'm adding the worker to all calls to the
foo.saladsimulator.com subdomain which doesn't exist.
Now we can navigate to our domain and we'll see the message that we set up for when no cookie is present.
If you add the cookie you'll get a 404 response because there is nothing listening on that sub domain.
So this is a fairly contrived example. It doesn't add any real security to the route. It is however a step towards what I am to build. I'd like to have a set up that protects a staging domain using authentication provided by Auth0. Typically I've found that staging environments are protected using IP address allow listing and I just don't think that's good enough in 2021. I want everything to be zero trust.