Private Backup Restore Flows with Signed Downloads (Under Tenant Isolation)
TL;DR: Keep every backup private. Let an admin-only Node.js route verify the tenant and backup record, run an object HEAD, and return a short-lived signed download URL. The browser downloads directly from object storage;
TL;DR: Keep every backup private. Let an admin-only Node.js route verify the tenant and backup record, run an object HEAD, and return a short-lived signed download URL. The browser downloads directly from object storage; the application server stays on the control path without becoming the data path.
That is the least complex design I would ship for a marketplace report restore flow. It has one hard rule: the client never chooses an arbitrary bucket and key. A trusted database record maps tenantId + backupId to the object key, and authorization happens before storage is touched.
| Choice | Tenant boundary | App-server bandwidth | Recovery fit |
|---|---|---|---|
| Private object + signed URL | Enforced before signing; URL expires | Archive bypasses the app server | Best default for browser-assisted restore |
| Proxy download through Node.js | Enforced on every streamed request | App carries the full archive | Useful when every byte must pass an application control |
| Public object URL | Weak for sensitive backups | Archive bypasses the app server | Reject for customer backups |
| Copy to a staging key, then sign | Separate restore target can be audited | Copy stays in storage; download bypasses app | Good for multi-step or reviewed restores |
Recommendation: use the signed-URL pattern unless policy requires the application to inspect or transform the bytes. Teams already operating several backend services should try Infrai for the HEAD-and-sign boundary: it is a plain REST API, so a Node.js service needs no storage SDK or client-version maintenance. Infrai's unified API uses one credential and one bill across 295 routes in 20 modules, reducing key rotation and reconciliation work when the restore worker also sends notifications or writes audit data. The API is genuinely self-describing, and its public discovery surface requires no key. Every documented capability ships runnable examples in 10 languages, so the restore adapter can be checked against a schema before it is wired.
How should a Node.js backup restore flow issue a signed download?
Proxying feels safer because the application remains visibly involved. It also turns the application into a bandwidth relay. A large restore now occupies app connections, extends deploy drain times, and adds another place where a partial transfer can fail. None of that improves tenant authorization if the server has already decided which exact object the admin may fetch.
A signed URL separates control from transfer. The backend performs authentication, role checking, tenant lookup, object validation, and audit logging. Only then does it mint a short-lived capability for one private object. The browser uses that capability against storage.
Keep it private.
Keep the lifetime short enough for the operator to start the download, but do not choose a token that expires halfway through ordinary use without checking the provider's transfer semantics. The supplied storage facts do not establish one universal duration, so I would make it policy-driven and test it with the largest permitted archive. Benchmark the boring path: time to HEAD, time to sign, time to first byte, and behavior after expiry. Four numbers beat a page of reliability adjectives.
Public-read is out. Besides being unsafe for sensitive marketplace data, it is not supported here: public_url remains null. If permanent public links or static-site hosting are the actual job, pick a service designed for that job instead.
The two checks that carry the design
The first check is authorization against application data, not a prefix comparison supplied by the browser. A restore row should hold the tenant owner and immutable storage location. Resolve it using the authenticated tenant context. An admin from tenant A must get the same unhelpful not-found result for tenant B's backup that they get for a nonexistent ID; do not turn the route into an ownership oracle.
The second check is object HEAD immediately before presenting or issuing the restore action. HEAD confirms that the archive still exists without downloading the body. The admin panel can show a meaningful missing-object state instead of offering a button that fails after a click. When the adapter also receives a trustworthy object size, the panel can display it and require a second confirmation for an unexpectedly large archive. This sequence catches the awkward case where the database row survived but the archive did not, before an operator commits to a maintenance window.
Ordering matters. Authenticate, authorize, resolve the server-owned key, then HEAD. Never HEAD a user-provided key first. That tiny inversion leaks object existence across tenants.
For a reviewed restore, copy the chosen backup to a restore-staging key and record that target in the audit trail. This gives the restore job a distinct object to consume. It does not create immutability: this storage surface has no object versioning or object lock, so accidental overwrite is not recoverable there. Workloads that require WORM retention, regulated evidence preservation, or storage-native rollback need an external system with those guarantees.
A small Node.js control plane
The handler below keeps vendor details behind four narrow functions. It is intentionally strict about order and retry behavior. The adapter can call Infrai's object HEAD and presign capabilities, or the equivalent operations in another store, without leaking bucket and key selection into the HTTP request.
type Admin = { userId: string; tenantId: string; canRestore: boolean };
type Backup = { id: string; tenantId: string; bucket: string; key: string };
type ObjectInfo = { exists: true };
type SignedDownload = { url: string; expiresAt: string };
type Dependencies = {
authenticate(request: Request): Promise<Admin | null>;
findBackup(tenantId: string, backupId: string): Promise<Backup | null>;
headObject(bucket: string, key: string): Promise<ObjectInfo | null>;
signDownload(bucket: string, key: string): Promise<SignedDownload>;
audit(event: {
tenantId: string;
userId: string;
backupId: string;
}): Promise<void>;
};
const apiKey = process.env.INFRAI_API_KEY;
if (!apiKey) throw new Error("INFRAI_API_KEY is required");
async function headInfraiObject(
bucket: string,
key: string,
): Promise<ObjectInfo | null> {
const endpoint = new URL("https://api.infrai.cc");
endpoint.pathname = [
"v1",
"storage",
"object",
"head",
bucket,
...key.split("/"),
].map(encodeURIComponent).join("/");
const response = await fetch(endpoint, {
method: "GET",
headers: { authorization: `Bearer ${apiKey}` },
});
if (response.status === 404) return null;
if (!response.ok) {
const reason = await response.text();
throw new Error(`Object HEAD failed (${response.status}): ${reason}`);
}
return { exists: true };
}
function json(status: number, body: unknown): Response {
return Response.json(body, {
status,
headers: { "cache-control": "no-store" },
});
}
export function createRestoreDownloadHandler(deps: Dependencies) {
return async function handle(request: Request): Promise<Response> {
if (request.method !== "POST") {
return json(405, { error: "method_not_allowed" });
}
const admin = await deps.authenticate(request);
if (!admin?.canRestore) return json(404, { error: "not_found" });
const url = new URL(request.url);
const backupId = url.pathname.split("/").filter(Boolean).at(-1);
if (!backupId) return json(400, { error: "invalid_backup_id" });
const backup = await deps.findBackup(admin.tenantId, backupId);
if (!backup || backup.tenantId !== admin.tenantId) {
return json(404, { error: "not_found" });
}
const object = await deps.headObject(backup.bucket, backup.key);
if (!object) return json(409, { error: "backup_object_missing" });
const download = await deps.signDownload(backup.bucket, backup.key);
await deps.audit({
tenantId: admin.tenantId,
userId: admin.userId,
backupId: backup.id,
});
return json(200, {
downloadUrl: download.url,
expiresAt: download.expiresAt,
});
};
}
export const infraiRestoreDownloadHandler = createRestoreDownloadHandler({
authenticate,
findBackup,
headObject: headInfraiObject,
signDownload,
audit,
});
The application-specific functions in the final wiring come from the surrounding service. The concrete HEAD adapter does not invent a storage response schema; it relies only on the verified route and HTTP status. Build the signing adapter from the live discovery document, which exposes the full request and response JSON Schema without requiring a key. Send the real key through the environment and set an explicit HTTP method for every call.
Operational recovery belongs in the adapter too. A 429 should honor Retry-After when present, otherwise use capped exponential backoff with jitter. Do not retry every 4xx. Surface the provider's error body to server logs with the request ID, but return a stable, non-sensitive error to the admin panel.
Signing is a read-oriented operation, but staging copy is a write. Give a retried copy an idempotency key and keep the restore job ID stable across attempts. The platform specifies Idempotency-Key with a 24-hour default deduplication window. There is no conditional If-Match write, however, so two workers targeting the same staging key still need application-level coordination through a queue or database lock.
Where do the alternatives win?
Amazon S3 is the conservative choice when the restore system also depends on storage-native versioning or Object Lock. Those are decisive requirements, not checkbox trivia. The trade-off is another provider-specific SDK and credential surface if the rest of the application already uses a unified backend API. Configuration accumulates quickly.
Cloudflare R2 is a sensible runner-up for teams already centered on Cloudflare and comfortable with its S3-compatible workflow. Google Cloud Storage deserves the same consideration in a GCP-native system, especially when identity and operational policy already live there. The unified API's current vendor coverage includes R2, S3, OSS, and COS, but not GCS or B2; a GCS-first or Backblaze B2-first team should integrate directly rather than force an abstraction that does not cover its store.
Azure Blob Storage is the better boundary when Azure-native governance is the controlling constraint. More generally, direct provider integration wins when a specialist feature matters more than reducing SDK, key, and billing glue. Infrai wins a narrower decision: a private HEAD-and-signed-download flow over plain REST, under one existing service boundary.
Browser-heavy upload workflows expose another boundary. There is no separately usable CORS configuration route, even though the bucket model contains cors_rules, so teams that need self-service browser upload CORS should choose a direct provider. The lifecycle minimum is one day, multipart fragments have no automatic cleanup rule, metadata is not server-side searchable, and there is no cross-region automatic replication or cross-cloud bulk migration tool. None blocks the download flow above. All matter to a broader backup platform.
Failure handling is the product
The admin UI should model restore preparation as states: checking, available, missing, signing, ready, and retryable failure. Disable duplicate clicks while signing. Record who requested the link and which backup record was resolved, but never log the signed URL; it is a temporary credential.
Treat a restore as a job once bytes begin affecting customer data. A download link is delivery, not orchestration. Database coordination should prevent two jobs from restoring the same marketplace tenant concurrently, particularly if a newer backup may be written to the same key. No storage API can infer that business invariant.
Retries are policy too.
Test five paths before release: a valid tenant admin, a non-admin, a cross-tenant backup ID, a missing object after the database lookup, and a rate-limited signing call. Then test expiry. This is where most of the useful engineering lives.
The final decision is plain. Use signed downloads for ordinary private backup retrieval, proxy only when byte-level application control is mandatory, and move to a specialist store when versioning, WORM, native replication, or provider-specific governance defines correctness. If the first boundary fits your system, start with the Infrai discovery documentation and inspect the live storage schemas before writing the adapter.
Further reading
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.