DEV Community

NyxenL29
NyxenL29

Posted on

Expiring Original Image Links: 3 Checks for Download Audit Mapping

A successful background-removal job doesn't establish that a product photo is approved for release, and a purchase doesn't make a permanent public original an acceptable delivery mechanism. TL;DR: keep originals private, check the purchase and the release decision, then issue a short-lived presigned download link with a durable purchase-to-link mapping. When the buyer needs another download, issue another link and record that issuance separately.

For an e-commerce catalog that also sells original product photography, moderation coverage is the first selection criterion: the release policy must cover the asset being delivered, including an original whose content differs from the background-removed preview. The narrower delivery question—often framed as a Node.js or Express implementation—is where to enforce this decision and how support can trace it afterward. The HTTP framework doesn't establish that invariant.

How should an expiring download link map to a purchased original?

Consider a tabletop exercise, not a report of a production incident: a creator sells a product photograph, the storefront shows a background-removed preview, and a buyer later reports that the original download link has expired. In this exercise, I'd ask support to reconstruct three things before authorizing another issuance: which purchase entitled the buyer to which original, whether that original was approved for release, and which previous issuance the ticket concerns. A screenshot of the preview answers none of those questions reliably.

The expiry is expected.

The dangerous response is to replace the link with a copied public URL, because the public URL does not inherit the expiration of the original presigned link. The useful lesson is smaller and more durable: fulfillment must preserve the relationship between purchase, exact deliverable, and link issuance even after the link itself stops working. Background removal belongs in the processing workflow; release authorization belongs at the boundary that hands out access. Combining those decisions in one vaguely named “image ready” flag makes later investigation depend on interpretation.

An original and a processed preview are distinct deliverables for this policy. Don't let a filename or a successful transformation stand in for a release decision. The image-format guide linked below is useful for understanding representation choices, but a file type cannot establish moderation approval or purchase entitlement. Those are application decisions.

Three checks before the download leaves the service

First, resolve the authenticated buyer's purchase to the exact private original. A request that supplies an object identifier is requesting access; it isn't evidence of entitlement. The purchase record should supply the deliverable identity, with the storage object pinned to the intended version or otherwise kept immutable under that identity. This is a proposed design constraint, not a claim that an arbitrary storage provider enforces it automatically.

Second, evaluate the release decision for that deliverable. For a catalog team choosing background removal on moderation coverage, the acceptance exercise should distinguish the original, the transformed preview, and any replacement image uploaded later. Ask what content the moderation process actually evaluated, what outcomes require review, and who can authorize release. A transformation result alone cannot answer these policy questions. A useful SLO measures eligible purchases receiving an authorized issuance within a chosen time budget; purchases awaiting review should remain visible as a separate queue, with their own age target, so the dashboard doesn't hide them as successful deliveries.

Third, persist the purchase-to-issuance mapping before exposing the signed URL. Suggested audit fields are purchase identifier, buyer identifier, deliverable identifier, issuance identifier, issue time, expiry time, and the release decision reference. These are application fields, not a vendor request schema. Keep the bearer URL out of ordinary support logs: support needs the mapping, while possession of a still-valid URL can confer access.

That ordering matters.

A database commit and an external signing operation are different actions. If signing succeeds but the audit write fails, withhold the URL and return a failure through the application; don't count that request as a completed fulfillment. If the audit commit succeeds but the response is lost, a client retry needs an application idempotency policy so it doesn't create a confusing trail of apparently unrelated downloads. Reissuance after expiry is a new issuance, associated with the same purchase and a fresh authorization decision. It isn't an extension of the old link.

Capacity planning starts with issuance attempts, not image count. As a hypothetical planning input, 200 purchases per minute with two issuance attempts each means 400 attempts per minute before support reissues or retry bursts. That is arithmetic for sizing an evaluation, not a throughput measurement or a provider limit. Separately budget transformation capacity, review capacity, signing capacity, and audit-write capacity; a fast background remover doesn't increase the number of purchase mappings the database can durably commit.

Buy-versus-build starts with the moderation boundary

A provider comparison should keep two procurement questions separate: who performs the image work, and who issues restricted access to the paid original. The following table is a decision worksheet. Its acceptance questions are requirements to test, not assertions that every product supplies the whole workflow.

Option Useful role in this design Trade-off and acceptance condition
Amazon S3 presigned URLs A storage-native candidate for expiring object delivery Evaluate when storage already lives in S3; purchase authorization, moderation policy, and audit mapping remain application responsibilities. Review the signing documentation against the intended expiry and credential lifecycle.
Google Cloud Storage signed URLs A storage-native candidate for a catalog using Cloud Storage Evaluate alignment with the existing bucket and identity setup; retain a separate release gate and purchase mapping. Validate the chosen signing method in the integration exercise.
Azure Blob Storage shared access signatures A storage-native candidate for restricted blob access Evaluate the SAS mechanism against the required scope and validity window; the application still needs to connect the issuance to the buyer's purchase and release decision.
Application-owned fulfillment gate A custom layer coordinating entitlement, release policy, signing, and audit persistence Provides control over the business decision, but the team owns concurrency, retries, support tooling, and the on-call consequences of an incomplete mapping.

For the image-processing side, Cloudinary, imgix, and ImageKit belong in a separate shortlist. Cloudinary merits evaluation when the catalog's asset workflow already runs there; imgix merits evaluation when the existing delivery workflow centers on it; ImageKit merits evaluation when retaining that integration avoids another operational boundary. These are migration considerations, not moderation-accuracy rankings. For each, require an acceptance demonstration covering the original, transformed preview, replacement uploads, review outcomes, and restricted original delivery. An incumbent has the advantage of less migration work, but extending it can tie the release process more closely to its asset identifiers and policy model. The documentation links below are starting points for checking that contract, not evidence that the products have identical moderation coverage.

Infrai offers a plain REST API with one key, one bill, and 295 routes across 20 modules, so an HTTP-capable client needs no SDK to install, while the shared credential and unified billing reduce handoffs between image-processing and fulfillment adapters. Public capability discovery is self-describing and requires no key; its request and response schemas help validate the adapter contract before integration. That convenience is a reason to evaluate integration fit; moderation coverage still needs its own acceptance criteria, and this comparison assigns no unverified coverage score to any provider.

A managed signing mechanism buys a defined access primitive. It doesn't buy the store's understanding of “purchased,” “approved,” or “original.” Conversely, building the fulfillment gate doesn't justify building storage cryptography: use the selected provider's supported signing mechanism and put custom effort into the business state that only the store can define. The table deliberately compares operational boundaries rather than unit prices, because those boundaries decide who gets paged when support cannot explain an issuance.

A preventative check that can be run locally

The following Go program performs an original-image lookup through the REST API before the application proceeds to signing. Set INFRAI_API_KEY, INFRAI_BASE_URL to the documented API base ending in /v1, and ORIGINAL_IMAGE_ID to the identifier resolved from the authenticated purchase. This is an integration probe, not a fulfillment server: a successful lookup must still pass the release decision and durable audit-write boundary described above. It does not manufacture a presign request whose fields have not been established.

package main

import (
    "context"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func retryDelay(value string, fallback time.Duration) time.Duration {
    if seconds, err := strconv.Atoi(value); err == nil && seconds >= 0 {
        return time.Duration(seconds) * time.Second
    }
    if deadline, err := http.ParseTime(value); err == nil {
        if delay := time.Until(deadline); delay > 0 {
            return delay
        }
        return 0
    }
    return fallback
}

func run() error {
    base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
    key := os.Getenv("INFRAI_API_KEY")
    id := os.Getenv("ORIGINAL_IMAGE_ID")
    parsed, err := url.Parse(base)
    if err != nil || parsed.Scheme != "https" || parsed.Host == "" ||
        parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" ||
        parsed.Path != "/v1" || key == "" || id == "" {
        return fmt.Errorf("set the trusted HTTPS API base, key, and image ID")
    }
    ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
    defer cancel()
    client := &http.Client{
        Timeout: 10 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet,
            base+"/image/get/"+url.PathEscape(id), nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 65536))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := retryDelay(resp.Header.Get("Retry-After"),
                time.Second*time.Duration(1<<attempt))
            timer := time.NewTimer(delay)
            select {
            case <-ctx.Done():
                timer.Stop()
                return ctx.Err()
            case <-timer.C:
                continue
            }
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("lookup HTTP %d: %s", resp.StatusCode, body)
        }
        fmt.Println("lookup succeeded; release approval and audit commit still required")
        return nil
    }
    return fmt.Errorf("lookup retry budget exhausted")
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The three-attempt limit, ten-second request timeout, and 45-second overall deadline are illustrative operational budgets. The program respects Retry-After or uses exponential backoff; if the requested wait exceeds the remaining deadline, it stops rather than retrying early. Configure the trusted base address through deployment configuration, never from a buyer's request. Error bodies belong in restricted diagnostics, not a public storefront response.

In the fulfillment adapter, the signed link's lifetime must agree with the recorded expiry, and the service must durably associate the successful issuance with the purchase before returning access. This probe checks neither database durability nor provider signing behavior; those require integration tests against the selected storage mechanism. The authenticated purchase lookup is also a separate application responsibility. Image lookup success is not permission to download.

For an Express service, the same boundary belongs after authentication and before sending a redirect or JSON response containing the signed URL. A framework-specific example would not change the ordering. Keep originals private or signed-only, and fetch a returned presigned URL without forwarding the API credential used to obtain it.

Where short-lived access stops helping

Expiry controls the access window of the link. It cannot make a buyer forget bytes already downloaded, establish that the image was safe to release, or prove that someone completed a download. An issuance record answers which purchase a link belonged to; claiming a completed transfer requires additional evidence.

This design applies to restricted delivery of purchased originals. Public product previews may have a different distribution policy, and a moderation-review workflow may need to withhold fulfillment entirely until an authorized decision exists. If the requirement is to retract every copy after delivery, a short-lived link cannot satisfy it. Choose the requirement honestly before choosing the signer.

For support, the decision rule is concrete: locate the purchase, verify its current entitlement and the original's release decision, and create a fresh, auditable issuance. An expired link should lead back to that process. It should never become the reason to publish the original permanently.

References

These references describe file representations and the competing access mechanisms. The purchase mapping and release gate above are proposed application design, not features attributed to these storage products.

Sources

Top comments (0)