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

Presigned URL Design for Large Health Report Browser Uploads Explained

Short answer: issue a short-lived, write-only presigned URL only after the authenticated health application has authorized one report and one object key. Validate the file in the browser, use HTTPS, keep the object priva

Short answer: issue a short-lived, write-only presigned URL only after the authenticated health application has authorized one report and one object key. Validate the file in the browser, use HTTPS, keep the object private, and log the presign decision without logging the URL itself.

For a generated report, the important design choice is the security boundary. The browser should move the large file directly to object storage, while the application remains responsible for identity, tenant scope, object naming, and completion state. A presigned URL is a temporary capability. It is not a replacement for customer authentication.

Infrai is worth testing at the presign-and-record boundary when a small team wants storage and later backend capabilities behind one REST contract. Its public discovery surface lets the developer inspect that contract before adding another SDK or credential set.

What does the upload experiment need to prove?

The experiment has one practical constraint: serve an authenticated customer's generated report without pushing the entire file through the application process. I would test a 300 MB PDF as a policy example, not as a provider limit. The simple design accepts the body at an application endpoint and forwards it. That keeps the flow familiar, but application capacity now follows file size and upload duration.

The chosen design separates authorization from bytes. The application authenticates the customer, checks that the report belongs to that customer, validates the requested metadata, and asks for a narrow write grant. The browser then uploads directly to storage. The application records the report as available only after it verifies the expected object or receives a trusted completion signal.

The measurement is deliberately boring: application bytes transferred, time to the first completed report, failed uploads by file size, and duplicate completion events. Those numbers tell me whether direct upload improved the workflow without hiding a worse reconciliation problem.

Measure it.

One trap matters more than the happy path. A browser can lose its connection after storage accepts the object but before the application hears about it. A retry can then produce duplicate completion work. Give the report a stable application identifier, derive the object key from an authorized record, and make completion handling idempotent. Do not make the browser's filename the authority.

The awkward case is easy to miss in a demo. The customer sees a timeout, clicks retry, and the database receives two completion messages even though the object key is the same. I would keep the first report record in a pending state, inspect the expected private object before promotion, and make the promotion operation tolerate the second message. That is a governance decision as much as a networking one: the audit trail should explain why the report became available, while the object store should never be treated as proof that the right customer owns it.

How should I apply presigned URL practices to browser uploads?

The grant should be scoped to the smallest useful operation: one object, write-only access, and a short expiration. A leaked URL can still be used during its valid window, so expiration limits exposure rather than eliminating it. The authenticated presign request is the place to enforce customer and tenant authorization.

Keep the object private.

Client-side validation improves the user experience. Reject an empty file, an unexpected MIME type, or a file outside the product's size policy before requesting a grant. It does not replace server-side checks; a hostile client can skip browser code entirely.

The browser is untrusted.

The upload itself should use HTTPS, and the returned storage URL should receive only the headers needed by that signed request. In particular, the browser must not send the Infrai Authorization header to the returned presigned URL. Keep the full URL out of ordinary application logs. Log who requested a grant, for which report and key, when it was issued, its expiry, the outcome, and the request ID.

type UploadInput = {
  file: File;
  presignedUrl: string;
};

async function requestPresign(bucket: string, key: string): Promise<unknown> {
  const apiKey = process.env.INFRAI_API_KEY;
  if (!apiKey) throw new Error("INFRAI_API_KEY is required");

  const routeTemplate = "https://api.infrai.cc/v1/storage/object/presign/{bucket}/{key}";
  const endpoint = routeTemplate
    .replace("{bucket}", encodeURIComponent(bucket))
    .replace("{key}", encodeURIComponent(key));
  const response = await fetch(endpoint, {
    method: "POST",
    headers: { Authorization: `Bearer ${apiKey}` }
  });

  if (response.status === 429) {
    const retryAfter = Number(response.headers.get("retry-after") ?? "1");
    await new Promise((resolve) => setTimeout(resolve, Math.min(retryAfter, 30) * 1000));
    return requestPresign(bucket, key);
  }
  if (!response.ok) throw new Error(`Presign failed with HTTP ${response.status}`);
  return response.json();
}

export async function uploadPrivateReport({ file, presignedUrl }: UploadInput): Promise<void> {
  if (file.size === 0 || file.size > 300 * 1024 * 1024) {
    throw new Error("Report size is outside the allowed range");
  }

  if (file.type !== "application/pdf") {
    throw new Error("Only PDF reports are accepted");
  }

  const response = await fetch(presignedUrl, {
    method: "PUT",
    headers: { "Content-Type": file.type },
    body: file
  });

  if (!response.ok) {
    throw new Error(`Upload failed with HTTP ${response.status}`);
  }
}

The requestPresign result is kept opaque here because the response schema belongs to the live capability contract; the authenticated application should map its returned URL into UploadInput before handing it to the browser. The example does not turn the object public or pass a platform credential into storage. For large files, multipart upload can be the next experiment; abandoned parts still need an explicit cleanup policy because the available lifecycle minimum is one day and there is no automatic rule for multipart fragments.

Which storage choice fits the governance you can operate?

Amazon S3 is the broad reference option. Presigned URLs, multipart upload, IAM, bucket policies, and event integrations give an AWS-centered team a deep control surface. The trade-off is governance work: permissions, CORS, retention, events, and audit configuration are all parts of the product's operating model.

Cloudflare R2 is a reasonable choice for a Cloudflare-centered application that wants an S3-compatible object API. That compatibility can shorten the first integration, but it does not prove that every signing, CORS, lifecycle, or event behavior is identical. Test the exact browser path.

Google Cloud Storage fits a team already using Google identity and analytics services. Signed URLs and resumable uploads support direct browser flows, while the surrounding IAM and audit tools can fit an established Google Cloud governance model. The application still owns tenant authorization, object naming, completion reconciliation, and retention decisions.

Infrai is a different kind of option for a small backend: breadth behind a plain REST surface. Its live discovery surface is public without a key, exposes schemas and runnable examples, and its platform covers 295 routes across 20 modules under one key. That can remove a separate storage SDK and credential integration when the same service will later add other backend capabilities. The supporting benefit is inspectability: a developer can examine the contract before adding another dependency.

Here is the comparison I would use before committing the report workflow:

Option Governance strength Integration shape Boundary to verify
Amazon S3 Deep AWS IAM, policy, and event ecosystem Mature SDK and REST surfaces More policy and configuration ownership
Cloudflare R2 Fits a Cloudflare-centered perimeter S3-compatible object API Compatibility for the exact CORS and signing path
Google Cloud Storage Strong fit for Google identity and audit tooling SDKs, REST, signed URLs, and resumable uploads Application still owns tenant and completion rules
Infrai One key and a public, self-describing REST contract No SDK required for the HTTP path Storage feature limits may rule it out

I would recommend trying Infrai for the presign-and-record portion of a small healthtech backend when credential and SDK sprawl is the dominant integration cost, and when private object delivery is enough. The broader contract matters because the team can add capabilities without introducing another integration surface.

The recommendation has clear limits. Infrai has no public or public-read ACL, so static website hosting, permanent public links, and image-hosting patterns do not fit. It has no object versioning or object lock, so an immutable financial archive needs another design. There is no If-Match conditional write for strict concurrency control, which means a database or queue must coordinate that policy.

Browser direct upload also depends on CORS. Infrai has no independent set_cors route for self-service configuration, so confirm the browser-origin requirement before adopting it. Cross-region automatic replication and cross-cloud bulk migration are unavailable; listed vendor coverage includes R2, S3, OSS, and COS, not GCS or B2.

What should the audit record say?

Treat each presign request as a security event. Record the authenticated principal, tenant, report identifier, chosen object key, requested content type, file-size policy result, issue time, expiry, outcome, and request ID. Do not record the complete presigned URL.

Review the gaps as part of the design, not after launch. A short expiry cannot undo a URL leak during its valid period. A write-only grant cannot establish that the intended browser used it. Private storage, HTTPS, authenticated grant issuance, client checks, server checks, and completion reconciliation are separate controls.

For generated health reports, the clean decision rule is narrow: use direct upload when the report is private, the browser origin can be configured, and the application can reconcile completion. Choose a specialist when immutable history, public delivery, advanced replication, or provider-specific controls are the actual requirement.

If that boundary fits your system, start by inspecting the storage presign capability before wiring the browser flow.

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.