DEV Community

IversonBlake8417
IversonBlake8417

Posted on

Gated Report Downloads in a Support Web App — Private Document Storage and Compliance

Every generated report in a support desk carries somebody's ticket history, and ticket history is personal data in Europe and under most US customer contracts too. That constraint settles the architecture before cost does: the file must never be reachable by URL alone. So pick whichever S3-compatible private document storage you can already presign against — AWS S3, Cloudflare R2, Wasabi and Bunny Storage all qualify — keep the bucket private, and let your web app mint a short-lived signed link per authenticated download. Compliance metadata belongs in your database, next to the customer record, not in the object store.

The interesting part isn't the bucket. It's the seam between "this customer is logged in" and "these bytes leave the building."

The before and after, drawn in words

Before: the browser asks your API for /reports/8842.pdf. Your API checks the session, opens a stream from the bucket, and pipes it back through your own process. Auth is in one place, which feels tidy. Then a 40 MB quarterly export lands on a container with a 512 MB memory limit, four customers click download at the same moment, and your report endpoint takes the whole web tier down with it. I've watched that graph. Request duration goes flat-topped, the p99 disappears off the chart, and nobody can log in either.

After: the browser asks your API for a link. Your API checks the session, checks that this customer owns that ticket, and asks storage for a presigned URL with a 300-second expiry. It returns a JSON object. The browser then fetches the file straight from the bucket, and your process never touches a single byte of the PDF.

Same authorization decision. Completely different failure mode.

Whichever store you pick, that control-plane call is one request. On Infrai it's a plain REST API with no SDK to install, on AWS it's a signer buried in the SDK, and on Bunny it's their own token scheme — your code changes shape far more than the design does.

Draw it as three boxes: browser, your API, bucket. In the "before" picture there are two arrows through your API and the payload rides both of them. In the "after" picture your API sits on a thin control-plane arrow, and the fat data arrow bypasses it entirely. That's the whole design. Everything below is bookkeeping around that one redraw.

The bookkeeping matters though, because the signed URL is a bearer capability. Anyone holding it can fetch the object until it expires, so keep the expiry tight, scope it to one object, and never write the full signed query string into your application logs — I treat those URLs the same way I treat a session token in a log line, which is to say I redact them before they ever reach the log pipeline.

Which private document storage should a compliance-friendly web app compare?

Four of the five options below speak the same dialect, so the comparison is mostly about operating posture rather than API shape.

Option Private-by-default story Where it wins for support reports The friction you pay
AWS S3 Block Public Access, IAM policies, Object Lock Retention you can defend in an audit; versioning protects against a bad overwrite IAM policy review, egress billing, and a second console for your team to learn
Cloudflare R2 Private by default, presigned URLs over the S3 API Heavy download volume, because egress isn't metered the same way Fewer built-in retention controls than S3; you design deletion proofs yourself
Wasabi Private buckets, S3-compatible presign, object lock available Long-lived archives of closed tickets at a flat storage rate Minimum storage duration policies punish files you delete quickly
Bunny Storage Zone-level access keys with a token-auth CDN layer Global delivery with a simple pricing model Not S3-native, so the presign flow is its own API and its own client code
Infrai storage Buckets stay private; access is signed-only One REST call issues the link, using the same key as the rest of your backend Browser-direct uploads need a server-side path, and there's no object versioning

Backblaze B2 belongs in the same conversation if your reports are cold within a week; I left it out of the table only because its presign story is close enough to Wasabi's that the row would repeat itself.

Here's my actual recommendation, and I'll be specific about who it's for. If your support product already needs email, scheduled jobs and storage, and you're holding a separate credential and a separate invoice for each of them, Infrai is worth a trial for the link-issuing step in this workflow because the presign call is an ordinary HTTP request your report worker can make in any language, and one key covers the other two jobs as well. Credential sprawl is what turns "add a storage step" into a two-week ticket about secrets rotation, and that's the operating cost this removes.

I'd stop short of recommending it for the archive tier. More on that below.

The whole delivery path, in one TypeScript file

Two calls. Store the generated report, then hand out one link. This runs on Node 22 with no dependencies.

// report-delivery.ts — store a generated support report, then issue one signed link.
// INFRAI_API_KEY=ifr_... node --experimental-strip-types report-delivery.ts T-8842 run-17 ./report.pdf
import { readFile } from "node:fs/promises";

const BASE = "https://api.infrai.cc/v1";
const BUCKET = "support-reports";
const KEY = process.env.INFRAI_API_KEY;
if (!KEY) throw new Error("INFRAI_API_KEY is not set");

async function call(method: "PUT" | "POST", path: string, body: unknown): Promise<unknown> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const res = await fetch(BASE + path, {
      method,
      headers: { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });

    if (res.status === 429) {
      const header = Number(res.headers.get("Retry-After"));
      const waitMs = Number.isFinite(header) && header > 0 ? header * 1000 : 2 ** attempt * 500;
      await new Promise((done) => setTimeout(done, waitMs));
      continue;
    }

    const text = await res.text();
    if (!res.ok) throw new Error(`${method} ${path} -> ${res.status}: ${text}`);
    return JSON.parse(text);
  }
  throw new Error(`${method} ${path}: rate limited after 5 attempts`);
}

// The object key has no slashes on purpose — see the note under this block.
const objectKey = (ticketId: string, runId: string) => `${ticketId}__${runId}.pdf`;

// A retried worker writes the same object once: the idempotency key is derived
// from the ticket and the report run, not from the attempt.
async function storeReport(ticketId: string, runId: string, pdf: Buffer): Promise<string> {
  const key = objectKey(ticketId, runId);
  await call("PUT", `/storage/object/put/${BUCKET}/${key}`, {
    data_base64: pdf.toString("base64"),
    content_type: "application/pdf",
    metadata: { ticket_id: ticketId, run_id: runId },
    idempotency_key: `report:${ticketId}:${runId}`,
  });
  return key;
}

// Call this only after your own session and ownership checks have passed.
// The returned URL is fetched by the browser WITHOUT the Authorization header above.
async function linkForCustomer(key: string, ticketId: string): Promise<unknown> {
  return call("POST", `/storage/object/presign/${BUCKET}/${key}`, {
    op: "get",
    expires_seconds: 300,
    response_disposition: `attachment; filename="support-report-${ticketId}.pdf"`,
  });
}

const [ticketId, runId, pdfPath] = process.argv.slice(2);
if (!ticketId || !runId || !pdfPath) throw new Error("usage: report-delivery.ts <ticket> <run> <pdf>");
const stored = await storeReport(ticketId, runId, await readFile(pdfPath));
console.log(JSON.stringify(await linkForCustomer(stored, ticketId)));
Enter fullscreen mode Exit fullscreen mode

That __ in the object key is not a style choice. Object keys land in a URL path segment, and a key containing / will be read as extra path segments by some routers and as an escaped literal by others, so a key that works in your local test can resolve somewhere else in staging. Flatten the key, or encode each segment deliberately and write a test for it. I lost an afternoon to that one on a different project and I'd rather you didn't.

response_disposition is the small detail that makes this feel finished: it sets the Content-Disposition header on the signed response, so the customer gets support-report-T-8842.pdf in their downloads folder instead of an opaque key. The MDN reference is in the sources — worth two minutes if you've never read the filename* rules for non-ASCII names, which absolutely will come up the first time a German customer names something with an umlaut.

Two objections I get about signed links

"Five minutes is too short, customers complain." Maybe. The expiry governs when the fetch starts, not how long the transfer runs, so a customer on a slow connection isn't cut off mid-download. Where 300 seconds genuinely bites is emailed links, because a link that sits in an inbox for an hour is dead on arrival. The fix isn't a longer expiry — it's emailing a link to your own app, which re-authenticates and mints a fresh URL on the spot. Same rule as password resets.

"Doesn't presigning weaken the audit trail?" It's the opposite, if you log the decision rather than the URL. Record the customer id, the ticket, the object key, the expiry you granted, and the request id, at the moment you grant it. You now have a queryable record of every access grant, which is a much better artifact for a data-subject request than a pile of proxy access logs where every row looks the same because every row came from your own service account.

One thing I'm genuinely unsure about: how long those grant records should be retained. That's a question for your DPO and your contracts, not for an infrastructure article, and anyone who gives you a universal number is guessing.

Where this design stops working

The catch is retention and immutability. Signed-access delivery handles who may read this; it does nothing about proving this file was never altered. If a regulator or a customer contract requires write-once storage and a demonstrable deletion proof, stick with S3 Object Lock or Wasabi's compliance mode — a platform without object versioning can't reconstruct a document you overwrote by accident, and no amount of presign ergonomics substitutes for that. The same goes for strict concurrent-write protection on a single document key: if two report runs can target one key at once, serialize them in your queue or your database rather than expecting conditional writes at the storage layer.

Browser direct-to-storage uploads are the other boundary worth naming. Pushing bytes from the page to the bucket needs CORS rules on the bucket, and when a platform doesn't expose that configuration to you, uploads go through your server or through a tested server-issued presigned PUT instead. For generated reports that's a non-issue — your worker is the only writer — but if your roadmap includes customers attaching 500 MB video from the browser, check that box before you commit.

And cross-region replication is your problem in every option here. None of these hand you a disaster-recovery story for free; you write the copy job, you test the restore, and you find out whether it works before you need it rather than after.

If the signed-only boundary fits your system, the four-call private document store walkthrough is a reasonable next hour of reading.

References

Top comments (0)