Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 7 min read

Implementing Tenant-Isolated Pre-Signed Download URLs for Object Storage (with Audit)

The decision rule is straightforward: create a short-lived download authorization only after the authenticated caller, export record, and object key have been checked against the same tenant. The storage service should r

The decision rule is straightforward: create a short-lived download authorization only after the authenticated caller, export record, and object key have been checked against the same tenant. The storage service should receive an opaque object key, never an arbitrary path supplied by the browser, and the authorization event should be durable enough to reconcile later. A pre-signed URL is a bearer credential with an expiration time; it is not an authorization system.

Short answer: put tenant identity and export ownership checks in your application, sign one server-selected object key, keep the expiry narrow, and record the issuance before returning the URL. The browser can then fetch the object directly, while the API retains the decision boundary and an audit trail.

This matters in fintech because a product-image export may look harmless while still crossing account boundaries. A tenant can have a merchant catalog, a generated archive, and several users with different permissions. The bytes are the last step. The dangerous decision is which bytes the link is allowed to name.

Keep it boring.

How do I generate pre-signed download URLs for tenant-owned files?

I treat the export path as a small architecture decision record. The invariants are more important than the storage SDK:

  1. The authenticated principal belongs to the tenant recorded on the export.
  2. The export is complete and has not been revoked or expired.
  3. The object key was created by the export job, not copied from request input.
  4. The signed request is bound to the intended method and response behavior.
  5. Issuance, download intent, and outcome can be correlated without logging the secret URL.

The failure boundary is deliberate. The API decides whether a download may happen; object storage decides whether the signature is valid; the browser follows a URL whose capability is intentionally narrow. If the storage layer is asked to discover tenant authorization from a user-provided key, the layers have been assigned the wrong job.

Option Tenant-isolation property Operational consequence Decision
Public object URL Anyone holding the URL can attempt access Revocation and attribution are weak Reject
API proxy for every byte Authorization stays in the API More bandwidth and connection handling Use when per-byte policy is required
Short-lived signed URL Storage serves bytes after an application check Bearer-token leakage must be controlled Use for bounded exports

The table leaves out an attractive but unsafe shortcut: accepting key from the query string and signing it after checking only the user's login. Authentication answers who is calling. It does not answer whether that caller owns the named object.

How should the critical path bind a tenant to an object?

The database lookup should return the export and its server-generated object key in one authorization-shaped operation. In a real service, the repository would use a transaction or a consistent read appropriate to its database; the important property is that the authorization decision is made from records owned by the service, not from a path reconstructed from request text.

The same boundary applies to a Node.js implementation: its storage client may generate the URL, but the application must resolve the tenant-owned export first. The language changes; the authorization order does not.

The following Go example keeps the signer generic. Signer represents the object-storage adapter, while the service owns the checks, expiry, and audit event. The example uses a 10-minute capability because the export endpoint is intended for an interactive download; a background integration would use a different policy, measured against its delivery window.

package export

import (
    "context"
    "errors"
    "fmt"
    "time"
)

type Export struct {
    ID string
    TenantID string
    ObjectKey string
    Status string
    ExpiresAt time.Time
}

type Signer interface {
    PresignGet(context.Context, string, time.Duration) (string, error)
}

type ExportStore interface {
    Find(context.Context, string, string) (Export, error)
    RecordIssued(context.Context, string, string, string, time.Time) error
}

var (
    ErrForbidden = errors.New("export is not available to this tenant")
    ErrNotReady = errors.New("export is not ready")
)

func IssueDownloadURL(ctx context.Context, store ExportStore, signer Signer,
    exportID, tenantID, requestID string, now time.Time) (string, error) {
    exp, err := store.Find(ctx, exportID, tenantID)
    if err != nil { return "", err }
    if exp.TenantID != tenantID || exp.ObjectKey == "" { return "", ErrForbidden }
    if exp.Status != "ready" || !now.Before(exp.ExpiresAt) { return "", ErrNotReady }

    const ttl = 10 * time.Minute
    url, err := signer.PresignGet(ctx, exp.ObjectKey, ttl)
    if err != nil { return "", fmt.Errorf("presign export %s: %w", exportID, err) }
    if err := store.RecordIssued(ctx, exportID, tenantID, requestID, now); err != nil {
        return "", fmt.Errorf("record export issuance: %w", err)
    }
    return url, nil
}

There is a consequential policy choice here: the issuance record is written after signing and before the URL is returned. A failure between those operations can leave an unused capability, but it does not create an unrecorded returned URL. If the audit system is unavailable, the service should fail closed for regulated workflows rather than quietly returning a capability it cannot account for. That is an exactly-once mindset applied to evidence, not a claim that distributed systems make every side effect exactly once.

What can go wrong after the check?

The URL is a bearer credential. Anyone who obtains it before expiry may present it, so the surrounding system must reduce accidental disclosure. Do not put it in application logs, analytics query captures, exception messages, or a support ticket. Store a hash or request identifier for correlation instead. Referrer policies and careful frontend navigation also matter because browsers can carry URL-derived information into other requests; MDN's CORS guidance is relevant to browser access, but CORS does not turn a bearer URL into a tenant-aware credential.

The browser download should use a dedicated response path. If the export is displayed inline, a content type from the stored object can create a different threat model than an attachment download. The application should choose a content-disposition policy, constrain the filename, and ensure that the signer binds any response headers it promises. A filename is presentation data, not an object key.

The URL lifetime, export lifetime, and clock-skew allowance are separate values. If an export expires in 90 seconds, issuing a 10-minute URL does not extend the business authorization unless that policy is explicit. Conversely, a 15-second URL can fail in a mobile browser before the download starts. Record the policy version with the issuance event so an investigation can distinguish a bad clock from a bad authorization decision.

Retry behavior matters too. A client may retry after a timeout even though the first request succeeded. Use an idempotency key for issuance records, keyed by tenant, export, and caller-defined request identity. Reusing an existing still-valid capability may be acceptable, but the decision must be explicit; silently minting five independent bearer credentials makes audit review harder and increases exposure.

Why is a direct browser download not the whole design?

Direct delivery reduces API byte handling, but it moves observability to a boundary where storage may not know the authenticated user. Emit an event such as export.download_url_issued with tenant ID, export ID, request ID, policy version, expiry timestamp, and a one-way URL fingerprint. A subsequent storage access record, where available, can be correlated by export ID encoded in metadata or by a server-side issuance token; never rely on parsing the secret URL in an observability pipeline.

The useful tests are mostly negative tests. A request from tenant A for tenant B's export must be denied. A not-ready export must never be signed. A key containing a path traversal sequence, an unexpected prefix, or a second tenant identifier must never reach the signer. A replay after expiry must fail at storage. A retry with the same idempotency key must not produce contradictory audit records.

One test deserves its own line: a valid URL for tenant A must never become a valid URL for tenant B after a database update.

I would also test the deployment boundary: a frontend origin allowed by the storage CORS configuration, a disallowed origin, a preflight request, and a response whose headers match the signed request. CORS is a browser enforcement mechanism, not a replacement for server-side authorization, and it is easy to mistake a successful preflight for a successful permission check.

For operations, alert on issuance-denial changes, exports issued far above the tenant's normal range, repeated requests for expired exports, and audit-write failures. Keep metrics low-cardinality. Tenant IDs belong in controlled logs or trace attributes, not in metric labels with an unbounded cardinality budget.

The rejected option and its valid use case

The rejected design is a single application endpoint that accepts an export ID, reads the object, and streams every byte through the API. It has one strong property: authorization remains visible for the whole transfer, and the service can enforce policy while bytes flow. It also inherits connection management, range requests, backpressure, partial responses, timeout handling, and API capacity planning. Those costs are justified when a download requires per-byte inspection, dynamic redaction, watermarking, or a policy that can be revoked during transfer.

For ordinary tenant-scoped product-image exports, a short-lived signed URL is a narrower mechanism with a clearer failure boundary. It does not solve authorization by itself. The reliable design is the sequence: resolve tenant-owned export, verify readiness, sign only the stored key, record issuance, and let storage enforce the resulting capability.

This approach is unsuitable when access must be revoked during an active transfer or when every byte needs inspection; that limitation is the trade-off for direct delivery. In those cases, choose an authenticated application proxy with explicit streaming controls, accepting its higher connection and capacity burden.

That sequence is worth preserving when the storage implementation changes. The adapter can evolve; the invariants should not.

References

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.