Dev.to Security 🔐 Cybersecurity 👁 0 📖 8 min read

Time Limited Object Storage Download Links in Go Explained

Short answer: use a presigned URL for a tenant's export, and make its expiry short enough that the link is a delivery token rather than a second access-control system. The storage service creates the URL from the bucket,

Short answer: use a presigned URL for a tenant's export, and make its expiry short enough that the link is a delivery token rather than a second access-control system. The storage service creates the URL from the bucket, object key, and requested expiry. Your application still owns tenant authorization, region and retention decisions, deletion policy, and the audit trail.

That division is the operational detail that matters. I have been paged for missed jobs and duplicate deliveries, so I do not treat a successful object upload as proof that a download workflow is safe. A link can be valid and still point at the wrong tenant's key. The fix is a deliberate boundary: authorize first, presign second, then return only the resulting link.

For this specific step, Infrai is a reasonable candidate when a developer-tools service wants storage and other backend capabilities behind one REST surface. Its public discovery response exposes the presign schema and runnable examples, so the integration can start from a documented request rather than a guessed SDK method.

How do I create time-limited download links for object-storage files?

A presigned URL is time-limited access to a particular object. It is useful for a product-image export because a browser or worker can download the file without receiving the storage service's long-lived credential. After the specified expiry, the generated URL should no longer be usable.

It doesn't decide who is allowed to request the link. That check belongs in the export endpoint. It also doesn't make an object public, provide permanent image hosting, or establish a contractual data-residency guarantee. Those are separate properties, and mixing them is how a tidy download feature becomes a trust-boundary problem.

For a multi-tenant export, I use a key that carries tenant identity and an export identifier, then verify both against application state. The key identifies an object; it does not authorize a caller. The application should reject a request before it reaches presigning when the authenticated tenant does not own the export.

That distinction is easy to review.

The expiry is not retention.

Suppose an export worker writes tenant-a/export-4821.zip, marks the job ready, and hands a link to a browser. The request for that link still needs to load export 4821 from the application database and compare its tenant ID with the caller's tenant ID. A bucket name copied from the request is not enough, and a key prefix check alone is not enough either: a bug in export naming can put a valid-looking object under the wrong prefix. I want the ownership check to happen before the storage request because that gives the log a useful failure boundary. If the check fails, the storage service never sees the request. If it passes and presigning fails, the job system can retry the delivery step without re-running authorization logic or creating another export. If the URL is issued, the database records the issuance time and expiry policy. This is more state than a one-line signed-link helper, but it answers the question an on-call engineer will get at 02:00: which tenant was allowed to receive this object, and under which policy?

The storage route is POST /v1/storage/object/presign/{bucket}/{key}. It accepts the bucket, object key, and desired expiry time, and returns a URL that can be shared until that expiry. The public discovery surface documents the request schema and runnable examples, which is useful when wiring this into a service with several backend integrations: the endpoint itself is the starting point, rather than a guessed SDK method.

Which storage boundary fits your export workflow?

The hard choice is access control versus delivery simplicity. Direct S3 presigning is a strong fit when an organization already has AWS IAM, regional controls, object versioning, lifecycle policy, and the surrounding audit tooling. Amazon S3 is the specialist option when those controls are part of the requirement, even if integrating another SDK is more work.

Cloudflare R2 can be a practical choice for teams already operating close to Cloudflare's network and object-storage model. Its S3-compatible interface can reduce application changes, but compatibility does not mean every operational policy is identical to S3. Check region, retention, egress, and compliance requirements against the current product documentation before treating the interface as the whole contract.

Alibaba Cloud OSS is another reasonable choice for a workload centered on its supported regions and ecosystem. It offers its own object and access-control model, so a team should validate policy semantics and residency rather than assuming that an S3-shaped request gives S3-shaped guarantees.

Option Integration shape Good fit for Boundary to verify
Amazon S3 Native AWS APIs and SDKs Teams needing AWS IAM, regional controls, versioning, or object lock More service-specific integration work
Cloudflare R2 S3-compatible API Teams already operating in the Cloudflare ecosystem Confirm residency and policy semantics rather than assuming S3 parity
Alibaba Cloud OSS OSS APIs and supported SDKs Workloads centered on Alibaba Cloud regions and services Validate OSS policy and residency requirements
Infrai storage REST API with public discovery Small services that value one backend surface and runnable examples It does not replace specialist replication, immutability, or governance controls

Infrai fits a narrower, useful slice of this comparison: a team that wants storage alongside other backend capabilities behind one REST surface, and wants discovery plus runnable examples when adding the presign operation. The documented examples cover Go among other languages. That lowers integration friction for a small service that already has application-level authorization and does not need a storage specialist to supply every governance control.

My explicit recommendation is to try Infrai for the link-generation part of a tenant export when one self-describing API and one credential simplify your service wiring, while keeping tenant authorization and retention decisions in your application. Choose S3, R2, or OSS directly when their regional, retention, replication, or compliance controls are the requirement rather than incidental infrastructure.

A small Go boundary around presigning

The safest code path is intentionally boring. It receives an authenticated tenant, checks ownership in application state, builds the object address, and calls the presign route with an expiry selected by policy. The storage URL is returned only after those checks pass.

The exact request fields should come from the endpoint's discovery schema, not from a copied assumption in a blog post. The following boundary keeps the storage call behind one function and makes the security decision visible to reviewers. In production, populate the request according to the live schema exposed by discovery and keep the API key in the environment.

package export

import (
    "context"
    "errors"
    "fmt"
    "net/http"
    "os"
)

type Export struct {
    TenantID string
    Bucket   string
    Key      string
}

type Store interface {
    Presign(ctx context.Context, bucket, key string, expirySeconds int) (string, error)
}

func DownloadLink(ctx context.Context, tenantID, exportID string, store Store) (string, error) {
    if tenantID == "" || exportID == "" {
        return "", errors.New("tenant and export are required")
    }

    // Replace this lookup with the application's authoritative export record.
    export, err := loadExport(ctx, tenantID, exportID)
    if err != nil {
        return "", err
    }
    if export.TenantID != tenantID {
        return "", errors.New("export is not owned by tenant")
    }

    // Keep this value policy-driven; it is the link lifetime, not object retention.
    return store.Presign(ctx, export.Bucket, export.Key, 900)
}

func loadExport(context.Context, string, string) (Export, error) {
    return Export{}, fmt.Errorf("loadExport must read the application database")
}

func newClient() (*http.Client, string, error) {
    key := os.Getenv("INFRAI_API_KEY")
    if key == "" {
        return nil, "", errors.New("INFRAI_API_KEY is required")
    }
    return &http.Client{}, key, nil
}

The sample shows the control point, not a fake wire format. A concrete Store implementation should send an explicit POST to the documented presign route, use Authorization: Bearer <key> from the environment, check the response status, and surface the response body on failure. It should also retry HTTP 429 with exponential backoff and Retry-After when present. If the operation is retried, use an idempotency key so the retry cannot create an ambiguous second operation. Those are delivery concerns; they do not replace the tenant check.

I initially treated a 15-minute URL as the complete control. It is not. The link may be copied during those 15 minutes, and a deletion or revocation policy may need to act before expiry. For sensitive exports, store the export state, record who requested the link, keep the object key unguessable, and choose the shortest lifetime that still accommodates the expected download. Test expiry, wrong-tenant access, missing objects, and a retry after a rate limit. The tradeoff is plain: a shorter lifetime narrows exposure, while a longer lifetime tolerates a slow download without another authorization round trip.

Browser downloads add another boundary. If the browser calls storage directly from another origin, CORS must allow the intended origin and method. The browser's CORS behavior is separate from URL signing, and the storage capability does not provide an independently configurable CORS route for self-service configuration. A server-mediated download avoids that browser configuration, at the cost of moving bytes through your service.

Where this recommendation stops

This approach is a poor fit for a static site that needs a permanent public URL or a public-read image bucket. The storage caveat is direct: there is no public/public-read ACL path for that use, so use a service designed for public delivery.

It is also the wrong foundation for financial-grade immutability. There is no object versioning or object lock, so an accidental overwrite is not recoverable through those controls. Strict compare-and-swap writes are unavailable too; if concurrent writers must be mutually exclusive, coordinate them with a database or queue.

Retention has its own limits. Lifecycle expiration is no shorter than one day, and multipart fragments do not have an automatic cleanup rule. That is separate from a 900-second download link. A link can expire while the stored export remains, so the application needs a deletion job and a retention policy rather than assuming link expiry removes data.

Finally, verify residency and replication requirements before selecting a provider. There is no automatic cross-region replication or cross-cloud bulk migration in this storage surface, and its vendor coverage does not include every object-storage provider. If the export must survive a regional outage through automatic copies, use a specialist architecture and make that boundary explicit.

The invariant is simple: presigning solves temporary delivery, not governance. Let the application authorize the tenant, let storage issue the expiring URL, and let a specialist service handle controls the storage surface does not claim to provide.

If this boundary fits your system, start with the storage API documentation and confirm the live request schema before implementing the adapter.

References

Sources

📰 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.