I sell annotated EPUBs and audiobooks out of an object bucket. The first version leaked
the entire catalog's first chapters, and the fix was not a better password.
The failure I found first
The preview package — first chapter plus a short audio sample — was in the public bucket,
unsigned. /books/<slug>/preview/ch-001.json returned 200 to anyone. Twenty-three books
meant one for loop, twenty-three requests, and every free chapter in the catalog, fetched
in under a second.
The rate limiting I had written never ran, because the request never reached the app.
That is the trap with static hosting on object storage: an object marked public is public
for everyone, at machine speed, forever. Any protection you build above it is decoration.
The rule that came out of it: the public bucket holds only what you would put on a
billboard — covers, the catalog index. Anything a reader has to be inside the app to read
goes in a private bucket and is served through the app.
public/books/<slug>/cover.jpg
private/books/<slug>/preview/manifest.json
private/books/<slug>/preview/ch-001.json
private/books/<slug>/<edition>/chapters/ch-001.json …
private/books/<slug>/<edition>/download/<slug>.epub
Content-addressed editions, so paid links never 404
The paid download path contains an edition segment: YYYYMMDD-<hash6>. If you rebuild the
book, the hash changes and you get a new prefix — and the old prefix is not deleted.
def edition_hash(item):
digest = hashlib.sha256()
for name in ("book.json", "guide.json", "source.json"):
with open(os.path.join(item["_src"], name), "rb") as fh:
digest.update(fh.read())
with open(os.path.join(item["_src"], item["epub"]), "rb") as fh:
digest.update(fh.read(8 * 1024 * 1024))
for track in sorted(item["audio"]["tracks"].values(), key=lambda t: t["file"]):
digest.update(f"{track['file']}:{track['seconds']}".encode())
return digest.hexdigest()[:6]
Three decisions buried in those twelve lines:
- Hash file contents, not mtimes. A rebuild that reproduces identical bytes must not produce a new edition, or every deploy quietly forks the storage tree.
-
Only hash what changes what a reader sees. Not the build script, not the timestamp in
manifest.json. Otherwise the hash is a random number. - Never delete old prefixes. Storage is cheap; a 403 on a book someone paid for is not. The tradeoff is unbounded growth, which is fine at 23 books and a problem at 23,000 — at that point you need a retention job that only prunes prefixes with no live orders.
The 8 MB cap on the EPUB read is a sanity check, not the primary signal: the EPUB is
generated from the three JSON files, so if they are byte-identical the archive should be
too. Reading the whole 30 MB file on every build is just slower for no extra information.
Manifest plus one JSON per chapter
A 192-chapter book as a single payload is tens of megabytes on first paint, and most readers
stop at chapter three.
So the manifest carries metadata only — chapter titles, word counts, audio durations — and
each chapter body is its own object.
The cost is N+1 requests while reading. The benefit, on a phone with mediocre signal, is a
reader that opens in well under a second and a next-chapter prefetch that is one small
request instead of a re-download. For linear reading, that trade is clearly right: you are
exchanging a burst for a stream.
Signed URLs generated per request, never stored
DOWNLOAD_URL_TTL = 300. The download route verifies orderId + token, asks the storage
layer for a presigned URL, and 302s to it. Nothing about that URL goes into the database,
so there is no table of live URLs to leak or to expire incorrectly.
Two things worth knowing before you copy the number:
- Five minutes is short enough that a URL pasted into a group chat is usually dead on arrival, and long enough that a slow mobile connection still finishes. I tried 60 seconds; it produced retries on exactly the users you least want to annoy.
- Presigned URLs end up in proxy and access logs, with the signature attached. If that matters for your threat model, stream the bytes through the app instead of redirecting — same authorization, at the cost of bandwidth and a longer-lived worker.
The guard has three tiers, and only two of them are worth calling security
Tier 1 — HTML. Completely open, robots.txt allows everything, sitemap submitted. This
is the SEO surface. You want crawlers here, and the page renders its first-screen content
server-side so they never need the JSON.
Tier 2 — body JSON. Manifest and chapter endpoints require browser-like requests and hit
fixed-window limits: 30 preview chapters/hour, 60 preview manifests/hour, 200 catalog
reads/hour, 400 paid chapters/hour.
Tier 3 — paid content. orderId + token plus its own chapter budget, so one purchase
cannot be turned into a mirror crawler.
The UA list denies python-requests, curl/, httpx, scrapy, go-http-client,
node-fetch and friends — and deliberately does not contain bot or spider. Those
broad words catch Googlebot, which legitimately fetches your HTML, and they are bypassed by
editing one header. What actually carries signal is requiring positive browser behaviour.
And the honest part: this is a speed bump, not a wall. A headless browser with a real UA
and real headers walks straight through it. The defence that holds is per-order entitlement
plus noticing how fast chapters are consumed from a single order. UA filtering buys you two
things only: the laziest scraper goes away, and your logs tell you who is scraping.
Why fixed-window instead of a token bucket: the project already had a DB-backed
check_rate_limit used by other routes. It works across processes with no Redis. Preview
volume is tiny, so sub-second precision buys nothing. Reusing it beat adding an in-memory
limiter that silently resets whenever the worker restarts.
The 300-second cache that made "price changes are instant" a lie
Live price is computed per request: list price × discount rate. But the catalog is cached for
300 seconds. Change a discount in admin and the storefront serves the old price for up to five
minutes — including in the JSON the front-end reads.
That is a textbook read-through cache without an invalidation hook. It survived testing
because during the build phase I was the only writer and a full rebuild always ran alongside a
restart. The second writer is always the admin panel, and it arrived months later.
If I were starting again, the invalidation call would be written in the same commit as the
cache.
Six things I would tell someone starting today
- Put zero valuable objects in a public bucket. Not even chapter one.
- Content-address your editions and never delete an old prefix.
- One JSON object per chapter; metadata in the manifest.
- Signed URLs with a short TTL, generated per request, never persisted.
- Treat UA filtering as logging with a side effect, not as access control.
- Write the cache invalidation hook in the same commit as the cache.
The store this comes from is at books.hipangwork.online —
23 public-domain Chinese classics in English translation, annotated, a few with narration.
The build pipeline that turns JSON sources into EPUBs, audio manifests and a static catalog is
a separate set of mistakes, and I will write that one up if it is useful.
Top comments (1)
Nice write-up. One more place where per-request signing can quietly leak: a CDN in front of the bucket. If its cache key ignores the query string, the first signed download gets cached under the bare path, and later requests without any signature get the cached paid file. Worth checking that the cache key includes the signature parameters, or that signed paths bypass the cache entirely.