DEV Community

KnutBerg8412
KnutBerg8412

Posted on

How to Specify Password Reset Email Content Before Sending Marketplace Reports

Combining account recovery with report delivery saves a message but couples an expiring security action to an unrelated attachment; keep the two jobs separate. TL;DR: a password reset email needs a secure, unique, time-bound reset link, an explicit expiration time, clear instructions, and a support contact. Never include a current password. For a marketplace sending a generated report as an email attachment, the first delivery gate should establish which message is being sent before any transport gets involved.

Consider a design review: a seller requests a password reset while a generated settlement report is ready for delivery. Both messages have the same destination, and a shared worker makes combining their payloads tempting. This is a hypothetical production scenario, not a reported incident. Its useful lesson is nevertheless concrete: delivering bytes successfully does not establish that those bytes belong in the recovery message, and a transport retry should never turn an account-recovery job into a report-delivery job.

Keep recovery small.

The engineering angle here is content validation before dispatch. A marketplace can buy mail delivery, but it still owns the decision about which content is authorized for which purpose. That decision should survive a busy queue, a delayed worker, and a template edit.

What fields are required in a password reset email for security?

Start with the message contract, rather than a vendor's request object. The required content is a secure reset link that is unique and time-bound, a clearly stated expiration time, instructions explaining how to use the link, and a way to contact support if recovery fails. These are semantic requirements; there is no claim here that every provider uses the same JSON field names or supplies the account-recovery logic.

Message element Content acceptance rule Application responsibility
Reset link Use a secure, unique, time-bound link Issue and validate the recovery authorization
Expiration time Say exactly when the link expires Reject expired authorization at redemption
Instructions Explain the reset action clearly Render the intended recovery flow
Support contact Give usable contact instructions Maintain the support destination
Sensitive content Exclude current passwords Keep secrets outside the email payload

IP logging or device-location notifications can provide additional security context. They do not replace an expiring reset link. Include a location notification only when the application actually has that information; a template should not manufacture reassurance.

The reset timer is more than copy. If the message says a link expires at a particular time but the server accepts it later, the security boundary lives in the wrong place. Conversely, a message arriving after its expiration can be perfectly well formed and still useless to the seller. Content validation and delivery timeliness need separate acceptance criteria.

Step 1 fixes the content boundary before rendering

The following standalone Go program renders a recovery message from a deliberately narrow application structure. Save it as main.go and run it with go run main.go. It uses an illustrative HTTPS address under example.com, generates a fresh token for the demonstration, and prints the result locally. It sends no email and implements no recovery endpoint. The field names belong to this example, not to any provider API.

The chosen 15-minute lifetime is an example policy, not a universal security requirement. In a deployed application, issue the token through the recovery service, persist its expiration and redemption state, and ensure the service enforces them. A renderer cannot establish those properties from a URL.

package main

import (
    "crypto/rand"
    "encoding/base64"
    "errors"
    "fmt"
    "net/mail"
    "net/url"
    "os"
    "strings"
    "time"
)

type ResetNotice struct {
    Link      string
    ExpiresAt time.Time
    Support   string
}

func render(n ResetNotice, now time.Time) (string, error) {
    u, err := url.Parse(n.Link)
    if err != nil || u.Scheme != "https" ||
        u.Host != "accounts.example.com" || u.User != nil ||
        u.Path != "/reset" || u.Fragment != "" {
        return "", errors.New("invalid recovery destination")
    }
    query, err := url.ParseQuery(u.RawQuery)
    if err != nil || len(query) != 1 || len(query["token"]) != 1 {
        return "", errors.New("invalid recovery query")
    }
    token, err := base64.RawURLEncoding.DecodeString(query.Get("token"))
    if err != nil || len(token) != 32 {
        return "", errors.New("invalid token representation")
    }
    if !n.ExpiresAt.After(now) {
        return "", errors.New("recovery link has expired")
    }
    contact, err := mail.ParseAddress(n.Support)
    if err != nil || contact.Address != n.Support ||
        strings.ContainsAny(n.Support, "\r\n") {
        return "", errors.New("invalid support address")
    }
    return fmt.Sprintf(
        "Subject: Reset your marketplace password\n\n"+
            "Use this link to choose a new password:\n%s\n\n"+
            "This link expires at %s.\n"+
            "If you did not request a reset, do not use this link.\n"+
            "For help, contact %s.\n",
        n.Link, n.ExpiresAt.UTC().Format(time.RFC3339), n.Support,
    ), nil
}

func main() {
    token := make([]byte, 32)
    if _, err := rand.Read(token); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    now := time.Now().UTC()
    link := url.URL{
        Scheme: "https",
        Host:   "accounts.example.com",
        Path:   "/reset",
    }
    query := url.Values{}
    query.Set("token", base64.RawURLEncoding.EncodeToString(token))
    link.RawQuery = query.Encode()
    notice := ResetNotice{
        Link:      link.String(),
        ExpiresAt: now.Add(15 * time.Minute),
        Support:   "support@example.com",
    }
    body, err := render(notice, now)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Print(body)
}
Enter fullscreen mode Exit fullscreen mode

The acceptance rule is visible: invalid destinations, malformed tokens, elapsed expiration times, and unusable support addresses stop rendering. The narrow structure has no attachment field and no current-password field. That reduces accidental coupling, although it cannot prevent a caller from misusing an unrelated mail builder elsewhere. Keep the report attachment builder outside this recovery path and bind each report-delivery job to its own authorized recipient.

Do not log the output in production. It contains a recovery token.

Step 2 budgets the time remaining when a worker sends

Once content passes validation, decide whether delivery can still be useful. An illustrative SLO could require 99.9% of eligible recovery jobs to reach a defined transport checkpoint within 2 minutes; this is a proposed operating target, not a measured result or a vendor guarantee. Record what the checkpoint means. Provider acceptance and inbox arrival are different events.

Suppose a link has a 15-minute lifetime and spends 12 minutes waiting behind report attachments. Only 3 minutes remain. A retry policy built around the original lifetime would overstate the useful delivery budget, so evaluate remaining validity when dispatching and stop sending an expired recovery notice. Issuing a replacement requires the recovery service's policy; changing the timestamp in the email does not extend authorization.

Queue age matters.

A planning workload of 120 reports per minute at 2 MiB each represents 240 MiB per minute of raw attachment data, before encoding and transport overhead. Those numbers are sizing assumptions. They are enough to show why report traffic deserves a bounded worker pool and why recovery traffic needs reserved capacity, even before a team has chosen a provider. If recovery traffic shares every worker with attachment delivery, a correctly rendered reset email can still miss its useful window.

At the dispatch boundary, preserve the logical job identity through retries and distinguish an uncertain send outcome from a confirmed rejection. Retry only within the message's remaining validity and the provider's documented behavior. A successful HTTP response should advance a transport state, not silently become a claim that the seller received the email.

Step 3 compares buying transport with building recovery

The buy-versus-build table should expose operational ownership. The three established mail products below are genuine alternatives to evaluate, but this article does not rank their inbox placement, quote unverified quotas, or imply that choosing a mail provider supplies password-reset authorization.

Option Where it belongs in the decision Boundary to review before buying
Amazon SES A mail-delivery candidate for a team evaluating the AWS service boundary Review its sending contract against attachment volume and the chosen delivery checkpoint; keep recovery authorization in the application
Twilio SendGrid A mail-delivery candidate when evaluating its Mail Send integration Review the request contract and operational workflow separately from reset-token enforcement
Postmark A candidate when comparing its email and template interfaces Review template ownership and attachment requirements against the marketplace's distinct message types
Infrai Its public, self-describing discovery surface supplies schemas and runnable examples, so an integration starts by reading a capability contract rather than learning a new SDK One key spans 295 routes across 20 modules, reducing credential administration for a platform with multiple backend jobs; that shared credential also deserves careful access handling
Build the application boundary Own token issuance, expiration enforcement, content validation, and authorized report-recipient binding Buying transport does not remove this work; building transport as well adds a separate operational responsibility

The useful differentiator is the integration boundary each team is willing to operate. A team already committed to one provider should demand a concrete reason to introduce another, while a platform consolidating backend integrations may value public discovery and fewer credentials to rotate. The trade-off is credential concentration. This approach is not suitable for a team whose policy requires separate provider credentials for each workload; retain its existing SES, SendGrid, or Postmark integration instead. Neither preference establishes a delivery SLO. Validate the exact request schema and delivery-observation model during selection rather than extrapolating from a polished API example.

For this workflow, discovery plus runnable examples reduces contract-reading friction, and a shared credential reduces the number of separate integration secrets the platform must administer. Those are integration advantages. They are not evidence of measured latency or guaranteed inbox arrival.

Make that contract review executable. The following independent Go program reads the email batch capability's discovery document and prints its request and response schemas. Save it separately as inspect.go and run it with go run inspect.go. Set INFRAI_BASE_URL to the platform's documented HTTPS versioned API base and INFRAI_API_KEY to your integration credential; discovery is public, so authentication is not required by discovery itself. The example includes the credential-handling pattern for an integration, refuses redirects, and never prints the key. Only use the trusted platform base as this environment variable's value.

This is a read-only inspection, not a send. It therefore needs no write-idempotency key. Use the returned contract to evaluate recipient and attachment representations before implementing dispatch; this example deliberately does not guess those fields.

package main

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

func inspect() error {
    base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
    key := os.Getenv("INFRAI_API_KEY")
    u, err := url.Parse(base)
    if err != nil || u.Scheme != "https" || u.Host == "" ||
        u.User != nil || u.RawQuery != "" || u.Fragment != "" ||
        u.Path != "/v1" || key == "" {
        return fmt.Errorf("set a trusted HTTPS versioned base and API key")
    }
    client := &http.Client{
        Timeout: 20 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    deadline := time.Now().Add(time.Minute)
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet,
            base+"/discovery/email.batch.send", 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, (4<<20)+1))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if len(body) > 4<<20 {
            return fmt.Errorf("discovery response exceeds inspection limit")
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.ParseInt(retry, 10, 64); err == nil && seconds >= 0 {
                if seconds > 60 {
                    return fmt.Errorf("retry exceeds inspection budget")
                }
                if candidate := time.Duration(seconds) * time.Second; candidate > delay {
                    delay = candidate
                }
            } else if at, err := http.ParseTime(retry); err == nil {
                if candidate := time.Until(at); candidate > delay {
                    delay = candidate
                }
            }
            if time.Now().Add(delay).After(deadline) {
                return fmt.Errorf("retry exceeds inspection budget")
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("HTTP %d: %s", resp.StatusCode, body)
        }
        var document map[string]json.RawMessage
        if err := json.Unmarshal(body, &document); err != nil {
            return err
        }
        if len(document["params"]) == 0 {
            return fmt.Errorf("discovery document has no params schema")
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("inspection retry budget exhausted")
}

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

The advice has limits. If the product cannot deliver an authorized report attachment through the selected transport contract, a good reset template does not solve that requirement. If recovery uses a different mechanism, do not force a reset-link template onto it. And if the user only requested a report, do not generate a recovery action as a side effect. The invariant remains useful across those cases: dispatch the content authorized for the job, with a deadline meaningful to that content.

References

The provider documentation below is a starting point for comparing actual sending interfaces, not evidence of a benchmark. RFC 6376 describes DKIM; authenticating a message's domain does not establish that its reset link expires correctly. Review sender authentication and application recovery controls separately.

Sources

Top comments (0)