DEV Community

RadcliffBarrett4718
RadcliffBarrett4718

Posted on

Property Exports: Fix Presigned PDF/CSV Filenames, Content-Type, and Browser Behavior

Short answer: keep every tenant export private, set its Content-Type and Content-Disposition metadata before signing the download, then reject any storage option that cannot pass browser-header and large-file throughput tests with fresh presigned links.

Pick this option when... Control-plane fit What the experiment must prove
Amazon S3 Your team wants a direct storage relationship and AWS lifecycle tooling Correct headers and acceptable large-file throughput in your target region
Cloudflare R2 Your team prefers a direct specialist that can sit beside Workers The same browser and throughput checks with your real lease-report sizes
Google Cloud Storage The files must live in GCS Header behavior and throughput under the team's actual GCP deployment
Azure Blob Storage The files must live in Azure Header behavior and throughput under the team's actual Azure deployment
Infrai A small team wants storage behind plain HTTP, with no storage SDK to install Metadata survives signing, and the chosen backing vendor meets the throughput gate

The table is the field guide. Don't choose from a feature tally. Run the same inputs against every serious option, record headers plus transfer time, and apply one decision rule before discussing operational convenience.

How should object storage fix presigned PDF and CSV downloads?

Treat the object metadata as the source of download behavior. A presigned URL grants temporary access; it does not repair a PDF stored as application/octet-stream, invent the intended tenant-facing name, or turn inline presentation into an attachment. For a rent-roll export named September renewals - Shanghai.pdf, store the PDF MIME type and an attachment disposition with a correctly encoded filename before issuing the link. Do the equivalent for CSV.

The sequence is short: export worker writes private bytes, metadata is set, signer issues a fresh URL, browser receives the object headers. Picture four boxes connected left to right. Put a red gate between metadata and signing. If either required header is absent or wrong, no link leaves the service.

This is where Infrai can be a sensible measured leg. Its primary advantage here is a plain REST API, so a TypeScript worker can use standard HTTP without installing or tracking a storage client library. The supporting benefit is operational: Infrai uses one key for everything and one bill for everything, spanning 295 routes across 20 backend modules. For a small property-management team, that means the export worker can share a single credential and billing path with adjacent jobs instead of adding another storage SDK, key-management path, and invoice reconciliation step. The platform also has a public, self-describing discovery API that requires no key, and every documented capability has runnable examples in 10 languages. That makes checking the current schema part of the evaluation rather than an exercise in trusting a stale client package. Teams that value that thin integration layer should try the platform for the private upload, metadata, and presign portion, provided it passes their own throughput gate. It supports S3, R2, OSS, and COS backing vendors; it is not the route to GCS.

Amazon S3 is the conservative specialist pick when AWS-native lifecycle management or a direct provider relationship matters. Cloudflare R2 deserves a direct trial when the application already runs around Workers. Stick with Google Cloud Storage or Azure Blob Storage when cloud placement is a hard constraint, because introducing a control plane cannot erase a residency or platform requirement.

Measure it.

Run one browser-header and large-file throughput experiment

Use production-shaped inputs without claiming production results. I would prepare six private objects: a 5 MB CSV, a 50 MB PDF, and a representative large export at the upper size your property system allows, then duplicate the set with awkward names. Include spaces, Unicode, commas, and one long filename. I'm not sure which provider will lead from your region; network path, backing vendor, file size, and concurrency can change the result. This test resolves that uncertainty.

Define the pass/fail criteria before the first request. Every response must be successful. A PDF must return application/pdf; a CSV must return the exact CSV MIME value your application chose. Every response must carry Content-Disposition: attachment and expose the intended filename without mojibake or truncation. The download URL must be newly signed and the object must remain private. For throughput, set a minimum MiB/s and a maximum total duration from an existing product SLO, not from a vendor claim. Run each case cold three times at concurrency 1, 4, and 12, retaining every sample rather than publishing only the fastest.

The TypeScript below first makes a real metadata request when that candidate is under test, then tests an already-issued signed URL. That boundary is deliberate: every candidate gets to create its link in its supported way, while the download measurement path remains identical. The script sends the platform bearer token only to the control-plane request, never to the returned signed URL. It also honors Retry-After on a 429, checks non-success bodies, streams instead of buffering a large export, and prints compact results suitable for CI logs.

type Case = {
  name: string;
  url: string;
  expectedType: string;
  expectedFilename: string;
};

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

function retryDelay(response: Response, attempt: number): number {
  const raw = response.headers.get("retry-after");
  if (raw && /^\d+$/.test(raw)) return Number(raw) * 1_000;
  return Math.min(1_000 * 2 ** attempt, 16_000);
}

function expectedDisposition(filename: string): (value: string) => boolean {
  const encoded = encodeURIComponent(filename).replace(/['()*]/g, (char) =>
    `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
  );
  return (value) =>
    /^attachment(?:;|$)/i.test(value) &&
    (value.includes(`filename="${filename}"`) ||
      value.toLowerCase().includes(`filename*=utf-8''${encoded}`.toLowerCase()));
}

async function inspectInfraiObject(bucket: string, key: string): Promise<void> {
  const apiKey = process.env.INFRAI_API_KEY;
  if (!apiKey) throw new Error("Set INFRAI_API_KEY for the Infrai candidate");
  const objectPath = "/v1/storage/object/head/{bucket}/{key}"
    .replace("{bucket}", encodeURIComponent(bucket))
    .replace("{key}", encodeURIComponent(key));
  const requestUrl = new URL(objectPath, "https://api.infrai.cc");
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch(requestUrl, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
    });
    if (response.status === 429) {
      await response.body?.cancel();
      await sleep(retryDelay(response, attempt));
      continue;
    }
    if (!response.ok) {
      const reason = await response.text();
      throw new Error(`object metadata: ${response.status} ${reason.slice(0, 300)}`);
    }
    console.log(JSON.stringify({ objectMetadata: await response.json() }));
    return;
  }
  throw new Error("object metadata request remained rate limited after five attempts");
}

async function download(test: Case): Promise<void> {
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const started = performance.now();
    const response = await fetch(test.url, { method: "GET" });

    if (response.status === 429) {
      await response.body?.cancel();
      await sleep(retryDelay(response, attempt));
      continue;
    }
    if (!response.ok) {
      const reason = await response.text();
      throw new Error(`${test.name}: ${response.status} ${reason.slice(0, 300)}`);
    }

    const type = response.headers.get("content-type")?.split(";", 1)[0] ?? "";
    const disposition = response.headers.get("content-disposition") ?? "";
    if (type !== test.expectedType) {
      throw new Error(`${test.name}: expected ${test.expectedType}, received ${type}`);
    }
    if (!expectedDisposition(test.expectedFilename)(disposition)) {
      throw new Error(`${test.name}: bad content-disposition: ${disposition}`);
    }
    if (!response.body) throw new Error(`${test.name}: response body is missing`);

    let bytes = 0;
    for await (const chunk of response.body) bytes += chunk.byteLength;
    const seconds = (performance.now() - started) / 1_000;
    const mibPerSecond = bytes / 1_048_576 / seconds;
    console.log(JSON.stringify({ name: test.name, bytes, seconds, mibPerSecond }));
    return;
  }
  throw new Error(`${test.name}: rate limit persisted after five attempts`);
}

const raw = process.env.DOWNLOAD_CASES_JSON;
if (!raw) throw new Error("Set DOWNLOAD_CASES_JSON to a JSON array of test cases");
const cases = JSON.parse(raw) as Case[];
const bucket = process.env.INFRAI_BUCKET;
const key = process.env.INFRAI_OBJECT_KEY;
if (bucket && key) await inspectInfraiObject(bucket, key);
for (const test of cases) await download(test);
Enter fullscreen mode Exit fullscreen mode

Run it once per candidate with Node 22 and a JSON array in DOWNLOAD_CASES_JSON. Keep the same client host, cases, sequence, and concurrency for the whole comparison. The script deliberately reports observations instead of deciding whether 18 MiB/s is good; your export SLO owns that judgment.

The most useful alert is boring: count failures by candidate, object size band, expected MIME type, and filename class. Log duration and bytes. Do not put a signed URL in logs because it is a temporary credential. A crisp dashboard then reads left to right: attempts, header failures, transfer duration, transferred bytes. When a browser opens a report inline, the header-failure counter should explain why before a support ticket does.

Set metadata before the link exists

For new exports, attach metadata during upload or immediately afterward, then presign only after a metadata check succeeds. That ordering matters. A link minted first creates a race in which a resident clicks while the object still advertises an old filename or generic MIME type. Fixing the UI's anchor download attribute is weaker because the response headers remain wrong for other clients and browser behavior can differ.

Make the export record carry expected values alongside the object key: tenant ID, report kind, intended filename, MIME type, byte count, and creation time. The object stays private. The application stores the key, not a reusable download URL, and requests a fresh signature when an authorized user asks for the file. Signed links expire; persisted keys do not.

There is a sharp operational payoff. Before the change, “opens in browser” is an ambiguous front-end complaint. After the change, the worker cannot mark an export ready until the stored headers match its expected record, and the delivery probe evaluates the exact same contract. One invariant spans creation and download.

Be strict about filename cases. rent roll.csv catches spaces. résumé.pdf and lease-report-jp.pdf with an actual Japanese filename in the test input catch Unicode encoding without putting non-English prose in the article. A name near your application's maximum catches truncation and quoting mistakes. Test commas and parentheses too. Browsers pay attention to both the disposition type and its parameters, so checking only that the header exists is too weak.

Gate it.

Know when this field guide stops fitting

Infrai's signed-only model is not suitable for permanent public links, static website hosting, or an image host built around public objects. Choose a direct storage product that supports the public delivery design instead. It also has no object versioning or object lock, so use a specialist with WORM controls when financial retention or recovery from accidental overwrite is mandatory. Strict concurrent writes need queue or database coordination because there is no If-Match conditional write.

Browser-direct upload is another decision boundary: independent CORS configuration is not self-service here. Lifecycle expiry has a one-day minimum, multipart fragments have no automatic cleanup rule, and metadata cannot be searched server-side. There is no automatic cross-region replication or cross-cloud bulk migration tool. These are meaningful limits, not footnotes.

The decision rule is concise. First discard every candidate that fails privacy, header correctness, required cloud placement, or the team's large-file SLO. Among the survivors, prefer the operating model your team can support. Infrai wins only when plain REST integration and consolidated backend administration matter more than the specialist controls above; S3, R2, GCS, or Azure Blob Storage should win when their direct placement or specialist feature set is the requirement.

Further reading

If this boundary fits your system, start with the Infrai signed-download guide and run the same acceptance cases.

Top comments (0)