CloudFlare R2 is a groundbreaking free service generously offered by the good folks at Cloudflare, providing users with 10GB of storage and unlimited bandwidth by default. However, this “unlimited” comes with some restrictions: no more than 1 million write operations and 10 million read operations per month, beyond which usage will be billed accordingly. Recently, I migrated over 110,000 images to R2 and became concerned about exceeding these limits, so I implemented strict security measures.
Protection Principles
The R2 bucket I needed to secure is part of the soomal.cc
website mentioned in the article Migrating Soomal.cc to Hugo.
The website is already hosted on Cloudflare Pages, which provides free hosting. The focus here is securing the images referenced in the HTML.
Restrict direct access to the R2 bucket. Prevent direct access to the R2 bucket via URLs, allowing access only through Cloudflare Workers.
Restrict direct access to image URLs. Block direct requests to image URLs like
https://images.soomal.cc/test.webp
, ensuring all image requests are made within the context of the original website.Implement appropriate security policies on the origin site. Since images themselves aren’t suitable for overly restrictive rules, the main approach is to increase the difficulty of directly requesting image links by enforcing security measures on the origin site.
Configuration Steps
Disable R2 Public Access
In the R2 settings, avoid configuring custom domain access and do not expose R2 publicly on the web.
For CORS policies, restrict access to the origin site only.
|
|
Add Workers Access Rules
- Create a Worker.
- Bind the R2 bucket.
- Add a custom domain and route.
- Add Worker script.
|
|
This script ensures that all requests to
images.soomal.cc
are routed through Workers.By leveraging Workers’ daily limit of 100,000 requests (3 million per month), it prevents excessive billing for R2 bucket access.
At this point, my goal is achieved. With 100,000 daily requests, this backup site has more than enough capacity. If the limit is exceeded, Workers will simply stop functioning, rendering the images inaccessible.
Add Additional Security Policies (Optional)
With the above settings, all requests to the R2 bucket must originate from soomal.cc
.
This allows further security enhancements on the origin site to indirectly protect the images.
- Enable Strict SSL Mode.
- Enable Caching. Cache as much as possible.
- Security Rules. Enable features like continuous script monitoring, browser integrity checks, rate limiting, and bot attack mitigation for added protection.