For a large AI-generated image upload, make the Node.js control plane bind every multipart action to the authenticated marketplace tenant before revealing any object storage coordinate.
Short answer: let a Node.js control plane create the object key and multipart session, store both against a tenant-owned report, presign one numbered part at a time, and accept only part numbers plus ETags for completion; complete or abort by looking up the stored session again under the authenticated tenant. The generator moves image bytes, but it never chooses the bucket, object key, upload ID, or tenant.
That split matters more than chunk size. A presigned URL grants time-limited access to a specific storage operation, and AWS describes it as a bearer token. Anyone holding it may use its permissions until it expires. For generated marketplace reports, the database authorization check must therefore happen before signing, not after the image has reached object storage.
The flow is plain: an authenticated customer requests a report, a worker generates a large image, and the application opens an upload associated with that report. The worker asks for part URLs and sends bytes directly to S3-compatible object storage. It returns the ETags, while the application owns completion, cancellation, and the later customer download decision.
Security boundary keeps storage coordinates on the trusted side
The example below makes storage an adapter because S3-compatible services can sit behind different SDKs or HTTP clients. The application contract stays fixed. More important, the public inputs omit bucket, objectKey, and uploadId; accepting any of those from a browser or generation worker would let an untrusted caller steer a privileged operation.
import { randomUUID } from "node:crypto";
type Part = { partNumber: number; etag: string };
type Status = "open" | "completing" | "aborting" | "complete" | "aborted";
type Upload = {
tenantId: string;
reportId: string;
bucket: string;
objectKey: string;
uploadId: string;
status: Status;
createdAt: Date;
};
interface MultipartStorage {
create(input: {
bucket: string;
objectKey: string;
contentType: string;
}): Promise<{ uploadId: string }>;
presignPart(input: {
bucket: string;
objectKey: string;
uploadId: string;
partNumber: number;
expiresInSeconds: number;
}): Promise<string>;
complete(input: {
bucket: string;
objectKey: string;
uploadId: string;
parts: Part[];
}): Promise<void>;
abort(input: {
bucket: string;
objectKey: string;
uploadId: string;
}): Promise<void>;
}
interface Uploads {
insert(upload: Upload): Promise<void>;
findForTenant(tenantId: string, reportId: string): Promise<Upload | null>;
transition(input: {
tenantId: string;
reportId: string;
from: Status;
to: Status;
}): Promise<boolean>;
}
const REPORT_BUCKET = "marketplace-reports";
const PART_URL_TTL_SECONDS = 600;
const MAX_PARTS = 128;
function reportKey(tenantId: string, reportId: string): string {
return `tenants/${tenantId}/reports/${reportId}/${randomUUID()}.webp`;
}
Those constants are application policy, not universal S3 limits. Ten minutes is deliberately concrete so the example has testable behavior; production teams should choose an expiry from generation time, retry behavior, and the damage window of a leaked URL. I'm not sure there is one sensible value across interactive generation and overnight batch work. Measure both before freezing it.
Session creation derives every storage coordinate on the trusted side:
async function beginReportUpload(input: {
tenantId: string;
reportId: string;
storage: MultipartStorage;
uploads: Uploads;
}): Promise<{ partUrlExpiresInSeconds: number }> {
const objectKey = reportKey(input.tenantId, input.reportId);
const { uploadId } = await input.storage.create({
bucket: REPORT_BUCKET,
objectKey,
contentType: "image/webp",
});
await input.uploads.insert({
tenantId: input.tenantId,
reportId: input.reportId,
bucket: REPORT_BUCKET,
objectKey,
uploadId,
status: "open",
createdAt: new Date(),
});
return { partUrlExpiresInSeconds: PART_URL_TTL_SECONDS };
}
async function getPartUrl(input: {
tenantId: string;
reportId: string;
partNumber: number;
storage: MultipartStorage;
uploads: Uploads;
}): Promise<{ url: string }> {
if (
!Number.isInteger(input.partNumber) ||
input.partNumber < 1 ||
input.partNumber > MAX_PARTS
) {
throw new Error("invalid_part_number");
}
const upload = await input.uploads.findForTenant(
input.tenantId,
input.reportId,
);
if (!upload || upload.status !== "open") {
throw new Error("upload_not_open");
}
const url = await input.storage.presignPart({
bucket: upload.bucket,
objectKey: upload.objectKey,
uploadId: upload.uploadId,
partNumber: input.partNumber,
expiresInSeconds: PART_URL_TTL_SECONDS,
});
return { url };
}
Keep the tenant ID out of request bodies. It should come from verified authentication context, while reportId is merely a lookup key. The findForTenant name is intentionally loud: a repository method that fetches by report alone makes a cross-tenant authorization mistake much easier to ship.
What must Node.js authorize before presigning large multipart image parts?
Presign the narrowest useful operation only after selecting an open upload by authenticated tenant and report. Return the URL to the generator, let it upload that numbered part, and retain the returned ETag for the final manifest. Don't hand the worker long-lived storage credentials just because it needs to transfer a large buffer.
This is a capability design, not a URL convenience trick.
Presigned access has a real limitation: restricting who may ask your API for a URL doesn't control who can use that URL after it leaves the process. Logs, queue payloads, analytics events, and exception trackers are poor places for it. Short expiry reduces exposure, but an expiry cannot repair careless disclosure. The control plane should avoid logging query strings and should issue a fresh URL only after repeating the same tenant-scoped lookup.
There is also a portability catch. “S3-compatible” doesn't prove that every provider has identical signing controls, policy conditions, or retry semantics. Keep these details behind the adapter, run the same contract suite against the chosen service, and stick with a provider-specific integration when a compliance boundary or signing control cannot be expressed by the portable contract. For workloads requiring authorization accepted under the US federal cloud program, evaluate the actual service and deployment against FedRAMP requirements rather than treating API compatibility as compliance evidence.
How does one tenant-scoped state machine govern upload authority?
Completion is where a harmless-looking API shape can undo the tenant boundary. The caller should submit only the manifest it learned while uploading: numbered parts and their ETags. The server reloads the bucket, key, and upload ID from its own tenant-scoped row. It then claims one terminal direction with a conditional state transition.
function validateParts(parts: Part[]): Part[] {
if (parts.length === 0 || parts.length > MAX_PARTS) {
throw new Error("invalid_part_count");
}
const sorted = [...parts].sort((a, b) => a.partNumber - b.partNumber);
const seen = new Set<number>();
for (const part of sorted) {
if (
!Number.isInteger(part.partNumber) ||
part.partNumber < 1 ||
part.partNumber > MAX_PARTS ||
part.etag.trim() === "" ||
seen.has(part.partNumber)
) {
throw new Error("invalid_part_manifest");
}
seen.add(part.partNumber);
}
return sorted;
}
async function completeReportUpload(input: {
tenantId: string;
reportId: string;
parts: Part[];
storage: MultipartStorage;
uploads: Uploads;
}): Promise<void> {
const parts = validateParts(input.parts);
const upload = await input.uploads.findForTenant(
input.tenantId,
input.reportId,
);
if (!upload) throw new Error("upload_not_found");
const claimed = await input.uploads.transition({
tenantId: input.tenantId,
reportId: input.reportId,
from: "open",
to: "completing",
});
if (!claimed) throw new Error("upload_not_open");
await input.storage.complete({
bucket: upload.bucket,
objectKey: upload.objectKey,
uploadId: upload.uploadId,
parts,
});
await input.uploads.transition({
tenantId: input.tenantId,
reportId: input.reportId,
from: "completing",
to: "complete",
});
}
async function abortReportUpload(input: {
tenantId: string;
reportId: string;
storage: MultipartStorage;
uploads: Uploads;
}): Promise<void> {
const upload = await input.uploads.findForTenant(
input.tenantId,
input.reportId,
);
if (!upload) return;
const claimed = await input.uploads.transition({
tenantId: input.tenantId,
reportId: input.reportId,
from: "open",
to: "aborting",
});
if (!claimed) return;
await input.storage.abort({
bucket: upload.bucket,
objectKey: upload.objectKey,
uploadId: upload.uploadId,
});
await input.uploads.transition({
tenantId: input.tenantId,
reportId: input.reportId,
from: "aborting",
to: "aborted",
});
}
One conditional update decides the race. If cancellation claims open first, completion can't claim it; if completion wins, abort can't redirect that session. In a real deployment, persist the terminal intent and completion manifest transactionally, then let a worker perform the storage call. That keeps a process exit between the database update and remote call from erasing the operation. The queue message can be a wake-up signal; durable truth belongs in the database.
The authorization matrix is small enough to review as a whole:
| Action | Server-owned coordinates | Required stored state | Caller-supplied data |
|---|---|---|---|
| Presign part | Bucket, object key, upload ID | open |
Report ID, part number |
| Complete | Bucket, object key, upload ID |
open to completing
|
Report ID, parts and ETags |
| Abort | Bucket, object key, upload ID |
open to aborting
|
Report ID |
| Download | Bucket and object key | complete |
Report ID |
Every row begins with the authenticated tenant plus report lookup. The caller data can identify an intended action, but it can't redirect that action to another tenant's storage coordinates.
Suppose tenant A and tenant B each own a report called report-42, while tenant A's generator uploads part 7, loses the response, and retries. The retry can replace the attempted part and retain the ETag it actually receives. Before completion, test the hostile variation: the generator authenticated for A submits B's report ID alongside A's valid part manifest. A repository lookup scoped to both authenticated tenant and report finds no matching upload, so the application rejects the request before it sees B's bucket, key, or upload ID. Now let A's client send its legitimate completion twice because the first API response disappears. The first request claims open; the second receives an application-level 409 or the equivalent conflict result. It must not create another multipart session, and a simultaneous abort must not change the selected terminal direction. Finally, replay A's ETags against B's report and verify the same tenant-scoped rejection. This isn't a personal war story or a claim about a provider response code; 409 is the control plane behavior chosen here so callers have an explicit, testable result. The useful artifact is the test matrix: two tenants, the same public report identifier, one valid manifest, and every complete/abort ordering.
That's the boundary.
Abort needs the same durability. A cancelled generation, expired application session, or failed policy check should record abort intent, and a reconciler should revisit old nonterminal rows. Otherwise abandoned parts become invisible operational state. Set the retention threshold from your workload and policy rather than copying the 600-second URL expiry: URL validity and upload cleanup solve different problems.
Which reliability and cost checks reveal authorization gaps before launch?
Start testing with two tenants that each have a report named report-42. Tenant A must be unable to request a part URL, complete, abort, or download tenant B's asset even when A knows that report ID. Repeat the test for an open, completing, complete, and aborting row. Then submit duplicate part numbers, a blank ETag, part zero, part 129, an empty manifest, and simultaneous complete and abort requests. These are cheap tests. They catch authority leaks that a happy-path upload demo won't.
Observe metadata, not secrets. Record tenant and report identifiers in the application's normal privacy-safe form, state transitions, operation latency, part number, retry count, and age of the oldest nonterminal session. Never record presigned URLs or storage credentials. Alert on sessions stuck outside a terminal state and on repeated authorization failures, then inspect whether they indicate a broken client, an abusive caller, or an overly tight expiry.
Deployment deserves one awkward test: terminate the application after it records completing but before the storage adapter returns. Restart it and verify that durable intent is discovered and processed without taking instructions from the caller again. Do the corresponding abort test. Also exercise the adapter against the exact object store used in production; compatibility labels are less useful than an executable contract covering create, part signing, completion, abort, and repeated calls.
Finally, inspect cost through retained bytes and failed work, not just request counts. Direct-to-storage transfer keeps image bodies away from the Node.js control plane, while prompt cancellation and reconciliation prevent unfinished work from lingering unnoticed. The design is unsuitable when images are always small enough for one bounded request and multipart state would add more operational burden than value. Use the simpler upload path then, but keep the same tenant-derived key and authorization rule.
The launch rule is strict: no storage operation happens from caller-supplied coordinates, no presigned capability appears before authorization, and every multipart session reaches a discoverable terminal decision. Chunk sizing can change later. The tenant boundary cannot.
Top comments (0)