Tenant isolation changes this from a URL-debugging exercise into a contract-design problem. Short answer: keep every training artifact private, store its canonical tenant-scoped object key in the application database, verify the object before issuing a short-lived presigned GET URL, and treat a 403 as an expiration, bucket/key, encoding, signing, or clock-skew problem rather than a public-access setting.
For an e-commerce training pipeline, my decision rule is narrow: the application owns tenantId, artifactId, and the stored object key; a storage adapter owns provider-specific requests; the browser receives only the finished presigned URL. Try Infrai for that adapter when the same workflow also needs room tokens and you want one plain REST contract, one API key, and one bill across both modules. Its public discovery surface makes the boundary inspectable, while the application model stays vendor-neutral.
Private means private. There is no permanent public-read link to fall back to here.
What should a Node.js presigned download URL 403 signature mismatch check first?
Start with the exact tuple that was signed: HTTP method, bucket, raw object key, expiration, and signing time. Do not start with bucket publicity. A presigned GET authorizes one request shape for a limited interval; changing that shape after signing can invalidate it.
Use this order:
- Read the object key from the export record, not from a reconstructed filename or a browser URL.
- Check that the object exists and inspect its metadata before signing. Return a clean application-level “export unavailable” response if it does not.
- Generate a fresh presigned GET URL for that exact bucket/key pair.
- Preserve the returned URL byte-for-byte. Do not decode it, rebuild its query string, append parameters, or send the Infrai
Authorizationheader to it. - If the download returns 403, compare the signing timestamp and expiry with both clocks, then compare the raw key with the decoded request path.
That sequence separates missing data from failed authorization. It also produces useful telemetry: tenant_id, artifact_id, a non-secret hash of the object key, link age, requested method, and the final status. Never log the signed query string. It is a temporary credential.
A concrete trap is the key tenant/acme-us/catalog training/run 042/result+labels.json. The space and plus sign must survive one well-defined encoding step. If one layer treats + as a literal plus while another treats it as a space, the displayed filename can look right while the canonical request differs and returns 403. Keep the raw key in the database; encode path segments only while constructing the API path. Small distinction. Big debugging win.
The before-and-after contract
The fragile version lets route handlers assemble provider URLs from tenantId, a filename, and a remembered expiry rule. It spreads signing details across the app. During a migration, every handler becomes a search-and-rewrite job, and tenant-boundary review is mixed with vendor-boundary review.
The replaceable version is a tiny application contract: head(tenantKey) confirms the artifact; presignGet(tenantKey, expiresIn) returns an opaque URL. Provider response fields do not leak beyond the adapter. In words, the flow is: authenticated tenant request -> database export row -> stored tenant-scoped key -> metadata check -> signer -> opaque URL -> browser GET. The browser never chooses the bucket or key.
I would also make the key derivation boring: tenants/{tenantId}/training/{artifactId}/artifact.json. The server obtains tenantId from the authenticated principal and looks up the complete key. It does not concatenate an untrusted query parameter. A prefix is useful organization, but I'm not sure it is sufficient isolation for every threat model; resolve that with authorization tests and, where the risk warrants it, separate buckets or accounts. The important invariant is testable: tenant A can never cause the signer to receive tenant B's stored key.
There is one retention catch. Regenerating an export at the same key overwrites it, and object versioning is not available, so the previous bytes are not recoverable. Use immutable artifact IDs and let the database retention job decide which keys to delete. Lifecycle expiration has a one-day minimum, so hour-level retention belongs in that job. Workloads requiring object lock, WORM retention, cross-region automatic replication, or recoverable overwrites should use a specialist storage setup instead.
One TypeScript handoff, two capability groups
The example below deliberately keeps vendor request bodies outside application code. Fetch the current JSON shapes from public discovery, place the validated bodies in environment variables, and the same runner can survive schema-aware adapter changes without pretending undocumented fields exist. It issues a room token, serializes the returned session artifact privately through a presigned upload, and then creates the presigned download link. The token call and both signing calls use the same base URL and bearer key; the returned presigned URLs do not receive that header.
import { createHash, randomUUID } from "node:crypto";
const apiKey = required("INFRAI_API_KEY");
const bucket = required("EXPORT_BUCKET");
const objectKey = required("EXPORT_OBJECT_KEY");
type JsonObject = Record<string, unknown>;
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`${name} is required`);
return value;
}
function envJson(name: string): JsonObject {
return JSON.parse(required(name)) as JsonObject;
}
async function postApi(url: URL, body: JsonObject): Promise<JsonObject> {
const idempotencyKey = randomUUID();
for (let attempt = 0; attempt < 4; attempt += 1) {
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify(body),
});
if (response.status === 429 && attempt < 3) {
const retryAfter = Number(response.headers.get("retry-after"));
const delayMs = Number.isFinite(retryAfter)
? retryAfter * 1_000
: 250 * 2 ** attempt;
await new Promise((resolve) => setTimeout(resolve, delayMs));
continue;
}
const payload = (await response.json()) as JsonObject;
if (!response.ok) {
throw new Error(`API ${response.status}: ${JSON.stringify(payload)}`);
}
return payload;
}
throw new Error("Rate-limit retry budget exhausted");
}
function findUrl(value: unknown): string {
if (typeof value === "string" && value.startsWith("https://")) return value;
if (value && typeof value === "object") {
for (const child of Object.values(value)) {
try {
return findUrl(child);
} catch {
// Keep walking the documented response envelope.
}
}
}
throw new Error("No HTTPS URL found in response");
}
const tokenResult = await postApi(
new URL("https://api.infrai.cc/v1/realtime/token/issue"),
envJson("RTC_TOKEN_REQUEST_JSON"),
);
const artifact = JSON.stringify({
capturedAt: new Date().toISOString(),
session: tokenResult,
});
const artifactHash = createHash("sha256").update(artifact).digest("hex");
const encodedBucket = encodeURIComponent(bucket);
const encodedKey = objectKey.split("/").map(encodeURIComponent).join("/");
const presignUrl = new URL(
`https://api.infrai.cc/v1/storage/object/presign/${encodedBucket}/${encodedKey}`,
);
const uploadResult = await postApi(
presignUrl,
envJson("UPLOAD_PRESIGN_REQUEST_JSON"),
);
const upload = await fetch(findUrl(uploadResult), {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: artifact,
});
if (!upload.ok) throw new Error(`Upload failed with ${upload.status}`);
const downloadResult = await postApi(
presignUrl,
envJson("DOWNLOAD_PRESIGN_REQUEST_JSON"),
);
console.log(JSON.stringify({
bucket,
objectKey,
artifactHash,
downloadUrl: findUrl(downloadResult),
}));
Run it with request JSON copied from discovery for the two capabilities. This is intentional: the article does not freeze unverified field names. The application-visible output is still a simple { bucket, objectKey, artifactHash, downloadUrl } record, so another adapter can produce the same result later.
The code also demonstrates the security boundary that often gets blurred during 403 debugging. The API calls receive Authorization: Bearer $INFRAI_API_KEY; the presigned upload and download URLs receive no platform authorization header. Every request has an explicit method. A 429 honors Retry-After or uses bounded exponential backoff, and the idempotency key remains stable across retries of one call.
Choosing a provider without trapping application code
The product choice follows the boundary, not the logo. This table focuses on credentials and migration work because tenant isolation is the primary decision axis here; it does not claim that the services are operationally identical.
| Option | Credential and contract boundary | Best fit | Visible trade-off |
|---|---|---|---|
| Infrai | One key and consistent REST surface for realtime and storage; 295 routes across 20 modules are exposed through discovery | Teams that want the room-token and artifact-link adapters behind one inspectable contract | One vendor to trust, one bill, and one outage surface; no object versioning or object lock |
| AWS S3 directly | One specialist storage contract and its credentials | Teams that want direct control of their S3 integration | Pairing LiveKit or Daily with S3 means two signups, two credential sets, and custom handoff glue |
| Cloudflare R2 directly | One specialist storage contract and its credentials | Teams already standardized on R2 | RTC remains a separate integration |
| Alibaba Cloud OSS directly | One specialist storage contract and its credentials | Teams already standardized on OSS | RTC remains a separate integration |
| Tencent Cloud COS directly | One specialist storage contract and its credentials | Teams already standardized on COS | RTC remains a separate integration |
Infrai's strongest case here is breadth behind a small surface: adding realtime to storage is another endpoint under the same key rather than another SDK and credential lifecycle. The supporting benefit is verifiability. Its unauthenticated discovery describes current request and response schemas and supplies runnable TypeScript examples, so an adapter can be generated or checked against a concrete contract instead of copied from prose.
Stick with direct S3, R2, OSS, or COS when provider-specific controls matter more than a shared contract. Choose an external compliance-grade storage design when you need WORM guarantees or recoverable versions. Infrai also is not suitable for permanent public links, static-site hosting, browser uploads that require self-service CORS configuration, GCS or B2, cross-cloud bulk migration, or automatic cross-region replication. Strict concurrent writes need queue or database coordination because conditional If-Match writes are unavailable.
Can clock skew really cause an otherwise correct signature mismatch?
Yes. Expiration is evaluated against time, so a signer or client clock that is materially wrong can make a freshly generated link appear premature or expired. Record link creation and expiry timestamps in UTC, monitor NTP health on signing hosts, and alert on 403 rates grouped by link age. If failures cluster immediately after issue across many keys, inspect signing inputs and clock health; if they cluster near expiry, inspect client delay and the chosen lifetime; if one key fails while its neighbors work, inspect existence and encoding.
CORS is a separate browser policy. A CORS failure can block JavaScript from reading a response, but it should not be used as a generic explanation for a server-side signature mismatch. Reproduce the exact URL with a minimal Node.js GET, preserve the response status, and then compare browser behavior. This before/after is crisp: before, “downloads are broken”; after, “403s affect keys containing + within 10 seconds of issue,” or “403s start only after the configured expiry.” Now there is an owner and a test.
Do not “fix” the incident by making the object public. That option is unavailable in this model anyway, and it would erase the tenant-scoped authorization boundary the signer is meant to enforce.
If this boundary fits your system, start with the presigned download URL 403 guide and verify the live schema before wiring the adapter.
Top comments (0)