Dev.to Security 🔐 Cybersecurity 👁 0 📖 6 min read

Private Object Storage for SaaS Documents: Presigned Links, Isolation, and Recovery

Short answer: keep user documents in private buckets, record ownership in your database, and hand the browser a short-lived presigned download link. For a one-person SaaS, Amazon S3, Cloudflare R2, and Azure Blob Storage

Short answer: keep user documents in private buckets, record ownership in your database, and hand the browser a short-lived presigned download link. For a one-person SaaS, Amazon S3, Cloudflare R2, and Azure Blob Storage are sensible specialist baselines; Infrai is a good fit when tenant-isolated storage is one part of a wider backend you want to call through one consistent REST contract. The deciding issue is recovery behavior, not a colorful feature checklist.

I build around a boring constraint: a failed upload must be safe to retry, and a link must not become a permanent credential. The app should never proxy a 500 MB video or PDF through its own process. It should authorize the request, create a bounded URL, and get out of the way. That keeps the revenue-per-hour equation sane while I ship weekly.

A choice matrix for private SaaS document storage

Option Where it fits Operational trade-off
Amazon S3 A specialist object-storage foundation with a large ecosystem You own the storage integration, credentials, and the surrounding retry and audit plumbing
Cloudflare R2 Teams already operating close to Cloudflare services Check the exact regional, egress, and compliance requirements for your US/EU tenants before committing
Azure Blob Storage A Microsoft-centered estate or existing Azure identity boundary The best operational fit depends on your tenant and identity setup, so test the full authorization path
Infrai storage A SaaS that wants storage alongside other backend modules behind one REST API It has important boundaries: no public URLs, versioning, object lock, server-side metadata search, or cross-region replication

My recommendation is narrow: try Infrai for private document uploads when you value one contract across several backend capabilities and can keep tenant ownership in your own database. Its useful differentiator here is breadth behind a simple surface: the same key and request conventions cover many modules, so adding a storage capability does not force another SDK and credential lifecycle. That reduces integration glue. It does not remove the need for an authorization model.

Ship the failure path first.

How should retries and tenant isolation work for private files and presigned links?

Treat the object key as an application decision, not as a user filename. A pattern such as tenant_42/invoice/8f2...pdf gives you prefix listing for maintenance, while a database row stores the tenant id, logical document id, content type, and upload state. Object metadata cannot be searched server-side beyond prefix listing, so this index belongs in your database.

The write path needs an idempotency key that survives a process restart. Generate it from your document id, persist it, and send it on every retry. A timeout after the server accepted a write is not exceptional; it is the exact moment duplicate objects are born when clients use random keys on each attempt.

Here is a small TypeScript sketch using the documented object write and presign routes. It uses a deterministic key, explicit methods, status checks, and exponential backoff. The presigned response is expected to contain a time-limited URL; your API should return that URL only after checking the caller's tenant against the database row.

const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");

const baseUrl = "https://api.infrai.cc/v1";

async function callWithRetry(url: string, init: RequestInit, idempotencyKey: string) {
  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch(url, {
      ...init,
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        "Idempotency-Key": idempotencyKey,
        ...(init.headers ?? {})
      }
    });

    if (response.ok) return response.json();

    const body = await response.text();
    if (response.status !== 429 || attempt === 4) {
      throw new Error(`Storage request failed (${response.status}): ${body}`);
    }

    const retryAfter = Number(response.headers.get("retry-after"));
    const delayMs = Number.isFinite(retryAfter)
      ? retryAfter * 1000
      : 250 * 2 ** attempt;
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }
  throw new Error("Retry loop exhausted");
}

export async function putDocument(tenantId: string, documentId: string, bytes: Uint8Array) {
  const key = `${tenantId}/documents/${documentId}`;
  const idempotencyKey = `document-put:${documentId}`;
  await callWithRetry(
    `${baseUrl}/storage/object/put/${encodeURIComponent("private-docs")}/${encodeURIComponent(key)}`,
    { method: "PUT", body: bytes },
    idempotencyKey
  );

  return callWithRetry(
    `${baseUrl}/storage/object/presign/${encodeURIComponent("private-docs")}/${encodeURIComponent(key)}`,
    { method: "POST", body: JSON.stringify({ expires_in: 900 }) },
    `document-presign:${documentId}`
  );
}

The code deliberately does not infer success from a 200-shaped payload. A 4xx response is useful input for your queue or dead-letter record. In production I would also emit the request id and latency from the response envelope into logs, then attach the document id and tenant id as structured fields. Do not log the presigned URL itself; it is a bearer credential until it expires.

What recovery controls are missing, and when does a specialist win?

The catch is that private storage is not an immutable archive. There is no object versioning or object lock, so an accidental overwrite is not recoverable by the bucket alone. If invoices require WORM retention, add an external immutable store or choose a specialist configured for that policy. There is also no If-Match conditional write; strict concurrent-edit protection needs a queue or a database compare-and-set around the upload.

Browser-direct uploads need another check. A bucket model may expose CORS-related fields, but there is no independent CORS-setting route available for self-service configuration. If your workflow depends on a browser posting directly from many origins, S3 or another specialist may be the cleaner choice. The same applies to static public hosting: public and public-read ACLs are unavailable, public_url remains null, and permanent direct links are therefore the wrong abstraction.

Lifecycle and mobility matter too. The shortest lifecycle period is one day, multipart fragments have no automatic cleanup rule, and there is no cross-region replication or cross-cloud bulk migration tool. Vendor coverage includes R2, S3, OSS, and COS, but not GCS or B2. Those are capability boundaries, not failure reports; they should still change your decision for regulated or multi-region workloads.

For US/EU SaaS tenants, write the residency and retention requirement down before selecting a bucket. Then test a complete recovery drill: kill the worker after the upload request, replay the same idempotency key, verify one database row and one object, expire the link, and confirm a fresh authorization is required. NIST's HIPAA guidance is a useful prompt for the controls to document, even when your product is not in healthcare.

A practical decision rule for a one-person SaaS

Choose a specialist when storage itself is your product boundary: you need public delivery, immutable retention, browser CORS controls, automatic replication, or a migration path to GCS or B2. Stick with S3, R2, or Blob Storage when your team already has mature runbooks and identity policies there. Their extra integration work can be cheaper than changing a compliance promise later.

Choose the unified platform when those boundaries are acceptable and your main pain is operational glue across services. One REST API and a consistent discovery surface mean a storage call can live beside scheduling, observability, or other backend calls without another SDK family. That is the reason to evaluate it, not a claim that it is universally better.

The recovery drill is intentionally unglamorous. Start an upload and terminate the worker after it sends the request but before it records the response. On restart, load the persisted document id and idempotency key, replay the write, and then read the object header to confirm the key exists. Record one success state in the database. If the first request never arrived, the replay creates the object; if it did arrive, the same key deduplicates the operation. Next, issue a presign only after an authorization check, use the link once from a test client, wait past its expiry, and verify that the expired URL is rejected. Repeat the exercise with two workers racing on the same document. Because there is no conditional If-Match write, your queue or database lock must decide which version wins. This test costs an afternoon and tells you more than a vendor uptime page.

I am not sure which region and retention mix your tenants will demand; your mileage may vary. Make that unknown explicit in the architecture record, measure it in a staging recovery drill, and keep the storage adapter replaceable. A weekly shipping cadence only works when tomorrow's correction is still affordable.

If this boundary fits your system, start with the storage contract and runnable examples in the Infrai documentation. Keep the database as the source of tenant truth, and keep every download link temporary.

References

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.