Content Security Policy (CSP) is a great way to protect your sites. You implement it by adding a header to your web server’s HTTP response. The hardest part, in my opinion, is finding out where you can report violations, without having to pay a penny.
Using Google’s Firebase Free plan you can create a Cloud Function to handle the reports sent by browsers when a rule has been violated. The Cloud Function can be triggered by an HTTP request. The URL to trigger the request is a bit long, but you can shorten that using a route in the hosting config.
Getting Firebase ready to to receive your Content Security Policy reports is what I’ll go over next. The first thing you must do is install the Firebase CLI tool. Then create a new project, and login using the CLI tool. This project requires three services.
- Cloud Firestore
- Cloud Functions
- Firebase Hosting (sorta optional, but suggested)
Cloud Function for Content Security Policy
In the above Gist we create a Firebase Cloud Function called cspReport. This function listens for any HTTP request, tries to parse the body as JSON, then writes it to our Cloud Firestore. If it is successful, it returns the ID. If it fails, it tells you the error message. You could add more functionality to this function, such as sending an email, or calling another API (if you’re on a Firebase paid plan).
Firebase Hosting for Content Security Policy
The default URL Firebase gives you for your cloud function is long, and isn’t easy to remember. For example, https://us-central1-project-name.cloudfunctions.net/cspReport, I probably won’t remember that. And perhaps you want your CSP URL branded with your domain, so we will need to use Firebase Hosting to accomplish this.
You should connect a custom domain to the Firebase project. This will allow you to brand your Content Security Policy Report URL. You will also need to configure your Firebase hosting to rewrite /csp to your Function named cspReport. You can do that in your firebase.json file; I’ve included mine below. Specifically lines 19-24.
Firebase is a handy service and the free tier will usually let you do what you need. If your service/app/site starts getting more traffic, it’s easy to upgrade to a paid plan. It can take a bit of getting used to if you aren’t used to deploying your code via the command line. But just think of it as you’re pushing the code to a Git repo. Check out the Firebase CSP repo if you want to see more.