Short answer: for Node.js image thumbnail resize and upload, resize with Sharp, write to a private compatible object-storage bucket, and issue a short-lived presigned download URL only after checking the tenant.
For a developer tool that stores product screenshots, that sequence separates access control from delivery: storage never becomes a public image server, while the browser still gets a normal URL.
The useful boundary is an object key such as tenant_42/products/p_891/thumb-320.webp. The tenant ID is part of the key and part of the authorization check; it is not a security control by itself. Your application must verify ownership before it signs anything. That's the boundary.
Start with the export contract, not the bucket
An upload request and a download request have different trust levels. The upload path receives an image, validates its type and size, asks Sharp to decode and resize it, then writes the derivative to private S3-compatible object storage. The export path reads a list of already-authorized keys and signs each read for a short lifetime.
I keep the original and derivative in separate prefixes. That makes retention rules, cache headers, and incident review easier. A 403 from the object store should mean “this signature or policy is not valid,” not “the tenant guessed a different key.” Log the tenant, object key, and decision, but never log the signed query string. It sounds tiny. It saves a nasty incident review later.
The first version can be small:
import sharp from "sharp";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
const storage = new S3Client({
region: process.env.S3_REGION,
endpoint: process.env.S3_ENDPOINT,
forcePathStyle: process.env.S3_PATH_STYLE === "true",
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY!,
secretAccessKey: process.env.S3_SECRET_KEY!,
},
});
export async function writeThumbnail(
tenantId: string,
productId: string,
input: Buffer,
): Promise<string> {
const body = await sharp(input)
.rotate()
.resize({ width: 320, height: 320, fit: "inside", withoutEnlargement: true })
.webp({ quality: 82 })
.toBuffer();
const key = `${tenantId}/products/${productId}/thumb-320.webp`;
await storage.send(new PutObjectCommand({
Bucket: process.env.S3_BUCKET!,
Key: key,
Body: body,
ContentType: "image/webp",
CacheControl: "private, max-age=300",
}));
return key;
}
This function does not accept a client-supplied key, ACL, or content type. Those are server decisions. I also cap the input bytes before Sharp sees them and put decoding behind a request timeout; image dimensions can be hostile even when the file is small.
How should private bucket uploads and presigned downloads enforce tenant access?
Treat the signed URL as a delivery token, not a database permission. The export handler loads product rows with tenant_id = session.tenantId, confirms each row is exportable, and signs only those keys. A signature lifetime of five minutes is long enough for a download and short enough to limit a leaked link. Your mileage may vary for a slow mobile client; choose the lifetime from observed transfer times, not a round number copied from a blog post. I don't promise that one expiry fits every customer.
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
export async function signedThumbnail(
tenantId: string,
productId: string,
): Promise<string> {
const key = `${tenantId}/products/${productId}/thumb-320.webp`;
// The database authorization check belongs immediately before this call.
return getSignedUrl(
storage,
new GetObjectCommand({ Bucket: process.env.S3_BUCKET!, Key: key }),
{ expiresIn: 300 },
);
}
For a tenant export, return a manifest of signed URLs rather than making the bucket readable. If the export is large, create a server-side archive in a separate private prefix and sign one archive object after the job completes. Do not put a long-lived URL in an email or permanent database row.
Which tenant checks belong in CI before a thumbnail ships?
The common failure is authorization performed once, followed by unconstrained object access. A route checks that a user belongs to a tenant, then accepts ?key=other-tenant/... and signs it. Test the key derivation, not only the role middleware. Include a cross-tenant fixture in CI and expect a 404 or 403 from the application before the object store is contacted.
The second failure is treating a derivative as disposable when it is the only copy used by an export. Keep an explicit state in the database: source_ready, thumbnail_ready, thumbnail_failed, and exported. Retries should be idempotent because the object name is deterministic. If a resize fails, record the failure and let a worker retry; do not quietly publish the original under the thumbnail key. A missing thumbnail is visible; a wrong-tenant thumbnail is a security incident.
Test the ugly path.
Watch three numbers: rejected input bytes, Sharp processing time, and signed URL downloads that return 403. A spike in the last metric usually points to clock skew, an expiry that is too short, or a cache replaying an old URL. I am not sure which threshold fits every workload, so start with dashboards and adjust after a week of normal traffic.
Retention and observability are part of the export contract
At small scale, synchronous resizing keeps the product flow understandable. At higher volume, enqueue a job keyed by (tenantId, productId, transformVersion), write derivatives with a versioned suffix, and let the API report readiness. A transform version prevents a new Sharp setting from colliding with old bytes.
Use lifecycle rules to remove abandoned originals or old derivative versions after a documented retention period. Lifecycle behavior is storage-specific, so verify it with a test bucket and keep the policy beside the deployment configuration. S3 lifecycle management is a useful standard reference, but compatible services can differ in timing and filters.
The catch is operational overhead. A queue, worker, manifest table, and cleanup policy are not suitable when the product has a few images a week. Keep a direct synchronous path until processing time or failure recovery starts eating revenue-per-hour. Choose a managed image pipeline when image transforms are your product; choose plain object storage when they are a supporting detail.
Top comments (0)