DEV Community

PeregrineShaw9645
PeregrineShaw9645

Posted on

Node.js Generated Support Images: Temporary Download Links as Tenant Capability Leases

A customer-support image stops being private the moment one tenant can ask the application to sign another tenant's object key. Short answer: store originals and AI-generated derivatives in private object storage, look up each attachment by authenticated tenant and stable attachment ID, and issue a five-minute signed URL only after that lookup succeeds. Treat the URL as a temporary capability, not as proof that the caller was allowed to receive it.

The tempting implementation is a signing endpoint that accepts an object key. It is short, easy to demo, and wrong at the trust boundary: possession or discovery of tenants/acme/cases/42/image.png becomes enough to request a usable link. Making the bucket private doesn't repair that authorization gap. The application has to choose the object from tenant-scoped metadata; the browser should never choose it for the signer.

That is the experiment constraint for this design: tenant B must be unable to cause even one signing call for tenant A's attachment. Upload speed, SDK ergonomics, and storage cost matter after that invariant holds.

No lookup, no lease.

Model the URL as a capability lease

A signed URL is best understood as a bearer capability with an expiry. During its useful life, the holder can present it directly to object storage. That is why saving the URL beside a ticket, placing it in analytics, or printing its query string into a trace quietly expands the number of people and systems that can use it. Save the stable attachment ID instead. Mint another URL after the next authorization check.

The word lease is useful here because it separates four clocks that otherwise get mixed together: the support agent's session, the authorization decision, the link expiry, and the object's retention date. A five-minute download link doesn't delete the image after five minutes. A lifecycle rule that removes an object after a retention window doesn't revoke a leaked link immediately. And a long-lived browser session shouldn't authorize a link for a case the agent can no longer access. Each clock needs its own owner.

Keep the public response deliberately dull. A request from tenant B for tenant A's attachment ID should have the same 404 shape as a request for an ID that does not exist. That avoids turning the endpoint into an attachment-existence oracle. A known user who lacks an allowed role inside the correct tenant can receive 403; in both cases, the storage signer must not run.

Signed delivery is fast because Node.js stays out of the image byte stream. The catch is that this path is not suitable when every download must receive a fresh watermark, pass through an inline policy gateway, or undergo transformation at read time. Use an application proxy for those cases and accept its bandwidth and latency. A hybrid is often cleaner: validate and scan before marking an attachment ready, then deliver approved bytes directly with short-lived links.

How should Node.js store private AI images and create signed download URLs?

Start from a metadata row, not a storage URL. The row binds attachmentId, tenantId, caseId, objectKey, media type, byte size, and state. The object key can repeat the tenant and case boundary for easier policy review, but its prefix is defense in depth, not the primary access check. A UUID prevents accidental collisions; it doesn't grant or deny access.

The focused TypeScript example below keeps key construction and tenant lookup in the application service. The storage adapter receives only keys the service has selected. It uses the S3-compatible JavaScript client shown in the supplied implementation context, while the interface keeps ticket records independent of provider URLs.

import { randomUUID } from "node:crypto";
import {
  GetObjectCommand,
  PutObjectCommand,
  S3Client,
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

type ImageAttachment = {
  id: string;
  tenantId: string;
  caseId: string;
  objectKey: string;
  contentType: "image/png" | "image/jpeg" | "image/webp";
  size: number;
  state: "ready";
};

interface AttachmentRepository {
  insert(row: ImageAttachment): Promise<void>;
  findReadyForTenant(
    tenantId: string,
    attachmentId: string,
  ): Promise<ImageAttachment | null>;
}

interface PrivateObjectStore {
  put(key: string, body: Uint8Array, contentType: string): Promise<void>;
  signGet(key: string, expiresInSeconds: number): Promise<string>;
}

class S3ObjectStore implements PrivateObjectStore {
  constructor(
    private readonly client: S3Client,
    private readonly bucket: string,
  ) {}

  async put(key: string, body: Uint8Array, contentType: string): Promise<void> {
    await this.client.send(new PutObjectCommand({
      Bucket: this.bucket,
      Key: key,
      Body: body,
      ContentType: contentType,
    }));
  }

  signGet(key: string, expiresInSeconds: number): Promise<string> {
    return getSignedUrl(
      this.client,
      new GetObjectCommand({ Bucket: this.bucket, Key: key }),
      { expiresIn: expiresInSeconds },
    );
  }
}

class SupportImageService {
  constructor(
    private readonly repository: AttachmentRepository,
    private readonly objects: PrivateObjectStore,
  ) {}

  async storeGeneratedImage(input: {
    tenantId: string;
    caseId: string;
    bytes: Uint8Array;
    contentType: ImageAttachment["contentType"];
  }): Promise<string> {
    const attachmentId = randomUUID();
    const extension = extensionFor(input.contentType);
    const objectKey =
      `tenants/${input.tenantId}/cases/${input.caseId}/${attachmentId}.${extension}`;

    await this.objects.put(objectKey, input.bytes, input.contentType);
    await this.repository.insert({
      id: attachmentId,
      tenantId: input.tenantId,
      caseId: input.caseId,
      objectKey,
      contentType: input.contentType,
      size: input.bytes.byteLength,
      state: "ready",
    });

    return attachmentId;
  }

  async createDownloadUrl(
    authenticatedTenantId: string,
    attachmentId: string,
  ): Promise<{ url: string; expiresInSeconds: number }> {
    const attachment = await this.repository.findReadyForTenant(
      authenticatedTenantId,
      attachmentId,
    );
    if (!attachment) throw new Error("ATTACHMENT_NOT_FOUND");

    const expiresInSeconds = 300;
    return {
      url: await this.objects.signGet(attachment.objectKey, expiresInSeconds),
      expiresInSeconds,
    };
  }
}

function extensionFor(contentType: ImageAttachment["contentType"]): string {
  return {
    "image/png": "png",
    "image/jpeg": "jpg",
    "image/webp": "webp",
  }[contentType];
}
Enter fullscreen mode Exit fullscreen mode

Both tenantId and caseId must come from trusted application state. Don't accept either value from an unverified form field and then congratulate the prefix for providing isolation. The upload edge also needs a byte limit and decoded-image validation rather than blind trust in Content-Type. If generation or inspection is asynchronous, use explicit states such as pending, ready, and rejected, and let only a ready row reach the signer.

There is an uncomfortable write sequence hidden in the example. Object creation can complete before metadata insertion. Pretending those two systems share a transaction makes the cleanup story worse, not better. Make retries idempotent, keep enough state to reconcile the pair, and inspect objects that remain unreferenced after a conservative delay. A storage lifecycle policy can clean up abandoned data, but it should backstop reconciliation rather than replace it. Never mark metadata ready before the object write completes.

Prove isolation before testing successful downloads

The first integration test should be a denial test. Create tenant A and tenant B, attach an image to a case owned by A, authenticate as B, and request A's attachment ID. Assert the public 404 response and, more importantly, assert that the fake signGet dependency received zero calls. Repeat with a nonexistent ID. Those two requests should be indistinguishable outside the service. Next, keep the authenticated principal fixed while changing every tenant-looking field supplied by the request; the selected object must not change. Finally, authenticate as a real tenant A user whose role cannot read that case. The public response can now be 403, but the important internal assertion stays the same: storage receives no signing request. This sequence catches the dangerous case in which middleware establishes one tenant, the body supplies another, and a helper farther down chooses whichever value is convenient.

Then test the ordinary path: an authorized A user receives a URL for the intended key with an expiry contract of 300 seconds. Don't snapshot the complete URL. Signatures and timestamps make that assertion brittle, and a copied fixture trains people to treat credential-bearing query strings as harmless test data. Verify the adapter input, expiry value, hostname, and returned bytes without retaining the secret.

I can't tell from a generic architecture diagram whether prefix isolation is enough for a particular support contract. If customers require separate cloud accounts, tenant-controlled encryption administration, or independently auditable storage boundaries, use bucket- or account-level isolation and budget for more provisioning and policy work. Shared storage with tenant prefixes is the compact option for many small teams, but it is not a substitute for a contractual boundary.

Operate the metadata-object gap

Authorization logs should record the tenant ID, stable attachment ID, actor role, allow or deny decision, requested TTL, storage latency, and correlation ID. Exclude the signed query string. Also exclude the URL from support transcripts and error reports; those destinations tend to live much longer than a download interaction.

Track p50 and p95 authorization-plus-signing latency, denied cross-tenant attempts, validation rejection counts, unreferenced object age, and reconciliation lag. For cost, measure stored bytes, downloaded bytes per resolved case, request volume, retention, and duplicate derivatives. Storage capacity alone doesn't describe the bill, and optimizing it before measuring retrieval and egress is false precision.

Retention belongs beside case policy. I'm not sure whether 30 or 90 days fits your product; deletion promises, legal holds, and the actual case-reopen window decide it. Test lifecycle changes with representative object ages before rollout, and keep legal holds outside the routine expiry path. AWS documents lifecycle rules as the mechanism for managing objects over time, while S3-compatible services may expose their own operational boundaries, so portability needs testing rather than assumption.

Tiny rule: rotate runtime credentials without changing attachment records.

The application stores stable identifiers and object keys, not provider URLs, which makes that possible. Keep the runtime identity limited to the expected bucket and operations. Give a cleanup worker deletion rights only when deletion is its job.

Decide what to measure before copying this design

This design is a fit when the application can make authorization decisions from tenant-scoped metadata and approved images can be delivered unchanged. Before adopting it, measure the full path under representative image sizes: metadata lookup latency, signing latency, time to first byte, completed downloads, and the number of URL renewals caused by expiry. Also run a log scanner that fails the build or deployment test when credential-bearing query strings appear.

Stick with proxied downloads when per-request transformation or inspection is mandatory. Choose stronger bucket or account separation when policy demands an administrative boundary that a key prefix cannot provide. If direct delivery remains the choice, the decisive evidence is not a successful download; it is repeated proof that the wrong tenant cannot make the signer run, while reconciliation and retention continue to keep metadata and bytes aligned.

That is the result worth shipping.

References

Top comments (0)