Short answer: make the export job tenant-owned before generating any CSV, write the completed bytes to a private S3-compatible object, and mint a short-lived signed download link only after the ownership check and upload both succeed.
The important design decision is not which SDK creates the link. It is where tenant identity remains attached to the work. In an edtech application, one instructor's class report must not become readable by another instructor because a job ID or object key was guessed. The browser should receive a temporary capability for one already-authorized object, never a storage credential and never a path that the browser can reinterpret.
This is a small pipeline. Treat it like a serious one.
The authorization failure happens before storage
Start with an application record such as export_jobs. It should contain the tenant ID, requesting user ID, export status, a stable job ID, and the object key once that key has been chosen. The request handler authenticates the user, checks that the user belongs to the tenant, and checks that the requested class or course also belongs to that tenant. Only then should it read rows.
The data flow is deliberately plain: create a pending job, derive a unique key from the tenant and job, generate CSV bytes, upload the private object, mark the job ready, and create a signed GET link when the client asks to download. A link generated before the write succeeds describes an object that may not exist. A link generated without the tenant check is an authorization bug in application design, even if the storage service signs it correctly.
The storage layer cannot repair a missing application decision.
No link yet.
Never put a user-controlled filename directly into an object key. A filename is presentation data. The key needs an opaque job component, for example tenant/t-17/exports/job-8f31/report.csv, with the tenant segment produced by the server. Keep the original display name in the database and sanitize it again when setting Content-Disposition; that HTTP header controls the suggested download name, not access control. I treat this as a four-part boundary: identity is checked in the database, bytes are owned by the job, the object remains private, and the link is a temporary capability. If one part is missing, the other three do not make the export safe.
A small reference implementation for the export contract
The following Python example isolates the part I want to test before wiring in Express or an object-storage client: tenant checks, deterministic CSV bytes, and a state transition that cannot expose a link while the job is pending. The same boundaries should exist in a Node.js handler, even if its CSV and HTTP libraries differ.
import csv
import io
import secrets
from dataclasses import dataclass
@dataclass(frozen=True)
class ExportJob:
job_id: str
tenant_id: str
object_key: str
status: str
def create_job(user_tenant_id: str, requested_tenant_id: str) -> ExportJob:
if user_tenant_id != requested_tenant_id:
raise PermissionError("tenant boundary rejected")
job_id = secrets.token_hex(16)
object_key = f"tenant/{requested_tenant_id}/exports/{job_id}/report.csv"
return ExportJob(job_id, requested_tenant_id, object_key, "pending")
def build_csv(rows: list[dict[str, object]]) -> bytes:
output = io.StringIO(newline="")
writer = csv.DictWriter(
output,
fieldnames=["student_id", "course_id", "score", "tokens_used"],
extrasaction="raise",
)
writer.writeheader()
writer.writerows(rows)
return output.getvalue().encode("utf-8")
def mark_ready(job: ExportJob, uploaded_key: str) -> ExportJob:
if uploaded_key != job.object_key:
raise ValueError("uploaded key does not belong to job")
return ExportJob(job.job_id, job.tenant_id, job.object_key, "ready")
job = create_job("tenant-17", "tenant-17")
payload = build_csv(
[
{"student_id": "s-204", "course_id": "python-101", "score": 0.92, "tokens_used": 611},
{"student_id": "s-205", "course_id": "python-101", "score": 0.81, "tokens_used": 744},
]
)
# The storage adapter uploads payload to job.object_key while it is still private.
ready_job = mark_ready(job, job.object_key)
assert ready_job.status == "ready"
The adapter should use the storage API's standard operations for a private object upload and a presigned GET, then return only the resulting URL and a server-chosen expiry to the authorized caller. Keep that adapter behind a small interface. The route should know about create_job, build_csv, and the job repository; it should not know how a provider signs bytes.
There are useful tests at each boundary. Give the serializer a value containing a comma, a quote, and a newline. Give the authorization test a valid user with the wrong tenant. Simulate a failed upload and verify the job stays pending with no URL in its response. Then retry the same job with the same object key. I've found this contract more valuable than a happy-path integration test alone because it catches accidental changes in the order of operations.
What should the Node.js upload and signed-link workflow record?
A synchronous Express request is acceptable for a small report, but large classroom or assessment exports belong in a worker. The HTTP request can create the job and return its ID; a worker can query rows in pages, serialize them, upload the object, and mark completion. The later download request rechecks the caller's tenant against the stored job before signing a GET request.
Keep these states explicit: pending, ready, and failed. A failed job is an application outcome with a retry policy, not permission to hand the client a partially written object. For retries, preserve the job ID and key. Otherwise one click can create several indistinguishable reports, which makes retention and incident review painful.
CSV has a security edge that is easy to miss. Spreadsheet programs may interpret a cell beginning with =, +, -, or @ as a formula. If teachers download and open the report in a spreadsheet, decide whether the product needs formula-injection protection, document the transformation, and test the resulting values. Do not quietly alter student-visible data without a policy; an escaped export and an exact machine-readable export may need different formats.
Set the object content type to text/csv; charset=utf-8 and use a controlled download name. Content-Disposition: attachment is a presentation choice that encourages download, while the signed URL's expiry and the object’s private policy are the access controls. These are separate responsibilities. Mixing them leads to confident-looking tests that verify the wrong thing.
Also record byte count, row count, generation duration, upload duration, and the storage request ID when one is available. Never log the signed URL: anyone with that string may be able to download the report until it expires. Log the job ID and tenant ID instead, with access restricted like any other student-data audit trail.
Choosing controls for a private school report
S3-compatible storage can be a practical abstraction for private artifacts because common operations map cleanly to upload, private read, delete, and signed GET. That does not make every implementation interchangeable. Check the exact signing behavior, maximum object size, multipart semantics, retention controls, and audit events of the service you select.
The catch is that an abstraction can hide provider-specific controls. It is not suitable when the school requires a provider-native retention lock, a specialized cross-region replication rule, or a compliance report that only one storage platform emits. In those cases, use that platform's native API behind the same application interface. Keep the domain contract stable and let the adapter carry the difference.
Cost also belongs in the decision, but it should not lead it. Large exports create storage, request, and data-transfer costs, and a signed link does not remove those costs. A retention policy that deletes temporary objects after the product's actual download window matters more than a tiny difference in request pricing. I am not sure which line item will dominate for your school; measure bytes generated, bytes downloaded, and object age from a representative week before setting policy.
Tenant isolation needs a second line of defense outside the key naming convention. On every status and download lookup, query by both tenant_id and job_id; do not fetch by job ID alone and check ownership later. A database row is the authorization source. The object prefix is an operational aid for cleanup, never the permission check.
The choice of storage controls should follow the report's governance requirement. A temporary classroom export may need private reads, signed GETs, deletion after a stated retention window, and an audit trail. A regulated assessment archive may also need immutable retention, provider-native legal holds, or a particular region. Those are different contracts. Keep the adapter narrow so the application can reject a storage choice that cannot express the required policy, instead of quietly pretending that a signed link is an archive system.
For a provider decision, I compare four questions: can it express the required private-read policy, can the team observe and delete objects, can the signing lifetime match the user workflow, and can it support the required retention controls? Price is a later input. A low request rate does not help if generated reports linger for months, while a cheap upload path can still become expensive when students repeatedly download large files. Your mileage may vary by retention period and geography, so measure bytes written and bytes served before tuning the policy.
An operational checklist that survives production
Before shipping, make one end-to-end test use two tenants and the same human-readable filename. The first tenant's job must be ready and downloadable; the second tenant must receive the same not-found or forbidden behavior whether it guesses the job ID, object key, or display name. Test expiry separately, because a link that works immediately proves little about its lifetime.
Then exercise the awkward paths: an export with zero rows, a quote-heavy name, a row that exceeds the expected size, a worker restart after upload but before the database update, and a repeated download request. The worker-restart case deserves more attention than it usually gets. Suppose the private upload succeeds, the process loses its connection, and the database still says pending. A blind retry can upload the same bytes again, which may be harmless, or it can generate a new key, which creates an orphan and loses the relationship between the report and its job. The recovery rule should therefore be explicit: retry the existing job and key, verify the object according to the storage contract, then make the database transition idempotently. If the object cannot be verified, leave the job pending or failed according to a bounded retry policy; do not mint a download link merely because an upload attempt was made. A reconciliation task can inspect pending jobs older than the expected generation window, while a cleanup task can delete objects whose job never reached ready. Both tasks need an audit record and a tenant-aware prefix. The database remains the source of authorization, and cleanup must never delete by a display filename. These decisions should be written down beside the job state model, because an on-call engineer should not have to infer retention or recovery policy from a half-finished HTTP handler.
The final rule is easy to review: authorization chooses the job, the job chooses the key, the worker owns the upload, and the download endpoint mints the capability. This keeps CSV generation testable from a notebook to production, keeps prompt and token metadata out of the access decision, and gives an AI-app builder enough observability to explain a slow report without guessing.
Top comments (1)
This is the part most export features get wrong: the authorization decision happening before storage, not at the download link. In security audits of multi-tenant platforms, the leak we kept finding was exactly the one you call out — a status/download endpoint that fetched by job ID alone and checked ownership after the fact, or not at all. Querying by (tenant_id, job_id) as the authorization source is the fix, and it's cheap.
Two additions from our side: first, the worker-restart case you describe is worth an explicit idempotency key on the upload as well — we had a retry re-upload under a new key and leave orphans the cleanup job couldn't attribute, because the object key was the only link back to the job. Second, on CSV formula injection: sanitizing cells that start with =, +, -, @ is worth doing by default in the serializer rather than leaving it as a per-export product decision — once teachers open these in Excel, the file itself is the attack surface.
Small note: the Python reference implementation reads a little odd in a Node/Express post, but the contract is language-agnostic, and that's what matters here.