DEV Community

Keria
Keria

Posted on

A Node.js Backup Download and Restore Flow for Private Object Storage

Short answer: treat a receipt backup as an auditable retention record, then make the admin panel request a short-lived signed URL for download and a separately authorized restore job. The original object should remain private; the URL is a temporary capability, not a new permission model.

A fintech receipt flow has two different jobs hiding behind one button. Processing extracts the data the application needs. Retention preserves the original file so an auditor can inspect what was actually received. Restore is the controlled act of bringing that original back into application storage. Mixing those paths creates quiet failures: a worker can delete the source after processing succeeds, an admin can download a file without an audit event, or a restore can overwrite a current record with no review trail.

The useful shape is small: an application database stores the object key, digest, content type, retention deadline, and immutable event IDs; private object storage holds the bytes; a worker processes a copy; and an admin API mediates every download and restore request. The browser never receives storage credentials.

Implement a Node.js admin panel for backup download and file restore

Start with an application-owned endpoint. It checks the operator's role, records the request, and asks the storage adapter for a signed URL or a restore stream. The storage adapter is the only code that knows the provider-specific SDK or HTTP details. That boundary matters later: changing object storage should not change the admin panel or the retention policy.

Here is a compact TypeScript example for the application-facing half. The StorageAdapter is deliberately generic; its implementation must use the storage system's documented signing operation, while the application remains responsible for authorization and audit records.

type ReceiptBackup = {
  id: string;
  objectKey: string;
  sha256: string;
  contentType: string;
  retentionUntil: string;
};

type StorageAdapter = {
  createDownloadUrl(input: {
    objectKey: string;
    expiresInSeconds: number;
  }): Promise<string>;
  copyObject(input: {
    sourceKey: string;
    destinationKey: string;
  }): Promise<void>;
};

type AuditLog = {
  append(event: {
    action: "backup.download.requested" | "backup.restore.requested";
    backupId: string;
    operatorId: string;
    requestId: string;
  }): Promise<void>;
};

export async function getBackupDownload(
  backup: ReceiptBackup,
  operatorId: string,
  requestId: string,
  storage: StorageAdapter,
  audit: AuditLog,
): Promise<{ url: string; expiresInSeconds: number }> {
  await audit.append({
    action: "backup.download.requested",
    backupId: backup.id,
    operatorId,
    requestId,
  });

  const expiresInSeconds = 300;
  const url = await storage.createDownloadUrl({
    objectKey: backup.objectKey,
    expiresInSeconds,
  });

  return { url, expiresInSeconds };
}

export async function requestRestore(
  backup: ReceiptBackup,
  operatorId: string,
  requestId: string,
  storage: StorageAdapter,
  audit: AuditLog,
): Promise<{ destinationKey: string }> {
  const destinationKey = `receipts/${backup.id}/restored/${requestId}`;

  await storage.copyObject({
    sourceKey: backup.objectKey,
    destinationKey,
  });
  await audit.append({
    action: "backup.restore.requested",
    backupId: backup.id,
    operatorId,
    requestId,
  });

  return { destinationKey };
}
Enter fullscreen mode Exit fullscreen mode

This example leaves two production decisions visible instead of hiding them in a helper. The download route needs a real authorization check before getBackupDownload runs. The restore route should usually enqueue a job and return an operation ID, because copying bytes and validating them can outlive an HTTP request. The sample's direct copy is useful as a seam for that job; it is not a reason to make a large restore synchronous.

The original receipt's lifecycle

Retention is the primary decision axis. A successful processing result is not proof that the source can be deleted. For each receipt, record a policy version and an absolute retentionUntil timestamp. A deletion worker should select only records past that deadline, not records whose processing status happens to be complete.

The deletion operation also needs a state transition. Mark the record deletion_pending, issue the storage deletion through the adapter, verify the result according to that storage system's contract, and append a tamper-evident audit event. If a legal hold or investigation arrives, the policy check must stop the transition before bytes disappear. Keep the object key and digest in the audit record even after deletion; the record should say what was retained and when the retention decision was made.

A common mistake is to use one lifecycle rule for every object. Processed derivatives, temporary thumbnails, failed-upload fragments, and original receipts have different values and different deletion authority. Separate prefixes and policies make that visible in code review. The original receipt deserves the strictest path.

Object class Normal action Gate before deletion
Original receipt Keep private and versioned Retention deadline and legal-hold check
Processed derivative Rebuild when practical Product retention policy
Temporary upload fragment Remove after an expiry window Upload state is terminal

This table is a policy sketch, not a storage provider feature. The application still needs to record which policy version made the decision, because changing a lifecycle rule without preserving that context makes a later audit hard to explain.

Short URLs help. They don't solve retention.

What does a signed URL prove in this restore flow?

A signed URL proves that the signer authorized a particular storage request under a particular expiry and set of constraints. It does not prove that the person holding the URL is still an approved operator, that the download was reviewed, or that the bytes match the database record. Those are application responsibilities.

For a private object storage design, keep the URL lifetime narrow enough for the expected transfer, avoid putting it in application logs, and return it only after the audit event has been accepted. The admin API should identify the backup by an opaque application ID, resolve the object key server-side, and constrain the operation to a read. Never accept an arbitrary object key from a browser as an authorization decision.

The restore path is stricter than download. Restore to a new versioned destination first, verify the content type and SHA-256 digest, then make the application reference change in a transaction or an explicit state machine. A failed verification must leave the current receipt untouched. Idempotency keys prevent a double click from producing two competing restores; the request ID in the example is the natural place to carry one.

HTTP semantics are useful here. A download response should communicate its status and representation consistently, and a restore request that becomes asynchronous should expose an operation resource rather than pretending that the work finished. RFC 9110 is the right baseline for those semantics, while the storage provider's documentation defines the exact signing and copy behavior.

The cost of skipping restore verification

Test policy decisions without a cloud account first. Given a retention deadline in the future, deletion must be denied. Given a legal hold, it must be denied even after the ordinary deadline. Given a matching digest, restore may advance; given a mismatch, the active receipt reference must not change. Those tests protect the decision logic, which is more important than the adapter mock.

Then run an integration test against a private test bucket or equivalent isolated namespace. Assert that an unauthenticated browser cannot read the object, that an expired signed URL is rejected by the storage service, and that the audit event contains the operator, backup ID, request ID, and action. Test a canceled restore and a repeated idempotency key too.

The most valuable test is a deliberately interrupted restore. Start with an active receipt whose original object has a recorded digest, copy it to a versioned destination, and stop the workflow before the reference swap. The application should still point to the active receipt and the audit log should show an incomplete operation. Resume the job with the same idempotency key; it should verify the existing destination rather than create a second competing version. Then change one byte in an isolated test object and repeat the run. The digest check must reject the destination, leave the active reference untouched, and make the reason visible to an operator without exposing receipt contents in logs. This is a small state-machine test, but it covers the place where download, restore, audit, and deletion policies meet.

Do this once.

Observability should follow the object through upload, processing, download, restore, and deletion. Log IDs and state transitions, not signed URLs or receipt contents. Track restore duration, verification failures, deletion denials, and objects past their retention deadline. Your mileage may vary on the right expiry window: measure real file sizes and operator workflows, then choose a value that is short enough to limit leakage and long enough to avoid needless retries.

The catch is operational complexity. This pattern is not suitable when the team cannot maintain an audit store, key-digest metadata, and a tested deletion worker. A simpler managed backup workflow may be the better choice there, even if it gives up fine-grained restore controls. Stick with a basic provider console for a small internal system when the access review and retention policy are already enforced outside the application; build the application-owned flow when fintech auditability and repeatable restores are actual requirements.

Before shipping, walk through the checklist as prose: confirm that the bucket is private, the browser has no storage credential, every download and restore has an operator and request ID, deletion checks both retention and legal hold, restore writes beside rather than over the active object, digest verification gates reference changes, and logs exclude signed URLs. Finally, perform one documented restore from a real backup and inspect the resulting audit trail. That rehearsal finds gaps that unit tests cannot.

References

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The distinction that does the most work here is the one in your first paragraph: the signed URL is a temporary capability, not a new permission model. That framing is what keeps the admin panel from quietly becoming a second storage credential.

The test I would make concrete is the deliberately interrupted restore. The failure mode I would design it around is the copy that lands but dies before the digest check — the object is sitting in the new versioned destination, the record still says the restore never happened, and the operator retries. What does the retry do — reuse the same destination, or mint a new one and leave the first as an orphan? How does the operator tell which one is the good copy?