Offloading Zendesk Attachments to R2/S3 Without Leaking OAuth Tokens or Hitting the 1-Byte redacted.txt Quirk
Zendesk attachment storage overages add up fast, so moving old ticket attachments into a customer's own Cloudflare R2 or AWS S3 bucket sounds like a weekend pipeline: list tickets, stream bytes to S3, call the redaction endpoint.
Once you run that worker against a real Zendesk Agent Workspace account with private attachments enabled, the API surface bites back in several places that are easy to miss in docs. Here are six bugs and failure modes we ran into building a Go offload worker, along with the exact fixes that held up in production testing.
1. The 302 Redirect Trap: OAuth Token Leaks and S3 400s
With private attachments enabled, attachment.content_url requires Authorization: Bearer <token>. On GET content_url, Zendesk authenticates the caller and returns a 302 redirect to a short-lived CDN or S3 presigned URL.
Following that redirect with headers intact causes two problems:
- You leak the tenant's Zendesk OAuth bearer token (and
X-Zendesk-Marketplace-*headers) to an external storage host. - S3 returns HTTP
400 Bad Requestwhen a request carries both query-string presigned auth parameters and anAuthorizationheader.
Go's net/http strips Authorization across different domains by default, which hides the bug until a subdomain matches or a custom CheckRedirect copies headers. Automatic redirect following also skips per-hop SSRF validation on the Location header.
In internal/zendesk/client.go, DownloadAttachment2Step splits the download using a noRedirClient whose CheckRedirect returns http.ErrUseLastResponse:
func (c *Client) DownloadAttachment2Step(ctx context.Context, tenantID, contentURL string) (io.ReadCloser, error) { if _, err := ssrf.ValidateURL(contentURL, c.allowLocalHTTP); err != nil { return nil, fmt.Errorf("invalid content_url: %w", err) } token, _, err := c.GetValidAccessToken(ctx, tenantID) if err != nil { return nil, err } req1, _ := http.NewRequestWithContext(ctx, http.MethodGet, contentURL, nil) req1.Header.Set("Authorization", "Bearer "+token) c.attachMarketplaceHeaders(req1) resp1, err := c.noRedirClient.Do(req1) if err != nil { return nil, err } // handle 401/403/404/429 and direct 200 ... if resp1.StatusCode >= 300 && resp1.StatusCode < 400 { loc := resp1.Header.Get("Location") resp1.Body.Close() if _, err := ssrf.ValidateURL(loc, c.allowLocalHTTP); err != nil { return nil, fmt.Errorf("blocked redirect location: %w", err) } // Step 2: NO Authorization or marketplace headers sent to external CDN req2, _ := http.NewRequestWithContext(ctx, http.MethodGet, loc, nil) resp2, err := c.httpClient.Do(req2) if err != nil { return nil, err } if resp2.StatusCode != http.StatusOK { resp2.Body.Close() return nil, &APIError{StatusCode: resp2.StatusCode, Cause: ErrSourceGone} } return resp2.Body, nil } // ... } Private content_url values cached during discovery can also expire before a worker claims the row. When DownloadAttachment2Step returns ErrSourceGone, downloadWithStaleURLRefresh in internal/worker/engine.go re-fetches /api/v2/tickets/{id}/comments.json?include_inline_images=true, verifies the attachment is not already redacted, updates the stored URL, and retries once.
2. Rotating OAuth Refresh Tokens Under Concurrent Workers
Zendesk rotates refresh tokens on POST /oauth/tokens (grant_type=refresh_token). If two worker goroutines or replicas see an access token with under two minutes left and refresh concurrently, the first wins and invalidates the old refresh token. The second gets invalid_grant and flips the tenant to REAUTH_REQUIRED.
We serialize renewal per tenant with a PostgreSQL SELECT ... FOR UPDATE transaction (WithTenantOAuthLock in internal/db/postgres.go) and a double-check inside the lock:
err = c.store.WithTenantOAuthLock(ctx, tenantID, func(locked *db.Tenant) error { now2 := time.Now().UTC() if locked.OAuthStatus != "CONNECTED" { return ErrReauthRequired } if locked.OAuthExpiresAt != nil && locked.OAuthExpiresAt.After(now2.Add(2*time.Minute)) && len(locked.OAuthAccessEnc) > 0 { tokBytes, err := c.envelope.OpenForTenant(locked.ID, locked.DEKEnc, locked.OAuthAccessEnc) if err != nil { return err } freshToken = string(tokBytes) updatedTenant = locked return nil } // Decrypt refresh token, exchange at /oauth/tokens, re-seal access + refresh tokens }) Healthy tokens take the lock-free fast path. Near expiry, waiting workers block on the row lock and reuse the freshly sealed token once the winner commits.
3. Never Fetch the ZAF Public Key From iss
When a Zendesk sidebar app uses signedUrls, Zendesk sends an RS256 JWT with iss set to {subdomain}.zendesk.com. Fetching the public key PEM from the host named in iss lets an attacker point iss at their own key server and forge tokens.
VerifyZAFJWT pins the Marketplace app's RSA public key at startup, restricts algorithms to RS256, requires exp, and validates {subdomain}.zendesk.com only after the signature passes:
parser := jwt.NewParser( jwt.WithValidMethods([]string{jwt.SigningMethodRS256.Alg()}), jwt.WithTimeFunc(func() time.Time { return now }), jwt.WithExpirationRequired(), ) tok, err := parser.ParseWithClaims(strings.TrimSpace(tokenStr), claims, func(*jwt.Token) (any, error) { return pinnedPub, nil }) Only after tok.Valid succeeds do we check strings.HasSuffix(issLower, ".zendesk.com") and reject subdomains containing /:@..
4. The Iron Rule State Machine Before Permanent Redaction
PUT /api/v2/comment_redactions/{comment_id} permanently destroys the attachment in Zendesk. If a customer's S3 lifecycle rule or manual delete removed the uploaded object before redaction runs, you lose the file permanently.
We split offload into RunPhase1Upload and RunPhase2Redact, gated by CheckIronRule in internal/statemachine/statemachine.go. Before redacting, every row must satisfy:
- State is
VERIFIED_IN_BUCKET, with non-emptyStorageConfigIDandStorageKey. -
SHA256Hexmatches^[a-f0-9]{64}$andVerifiedSizeBytes > 0. - Tenant is
Enabled,Mode == "LIVE", and notBillingPaused. -
VerifiedAtis withinFreshHeadMaxAge(60s) or backed by a freshHeadObject.
RunPhase2Redact runs sc.HeadObject(ctx, att.StorageKey) immediately before calling Zendesk. On storage.ErrObjectNotFound or a ContentLength mismatch, the state machine executes a legal VERIFIED_IN_BUCKET -> DISCOVERED reset (ResetVerifiedToDiscovered), clearing hashes so Phase 1 re-uploads the object instead of deleting the Zendesk source.
5. The Live Agent Workspace 1-Byte redacted.txt Quirk
Older Zendesk docs describe a 0-byte redacted.txt placeholder after redaction. On a live Agent Workspace account, redacting an attachment actually leaves a 1-byte redacted.txt file.
Checking only size == 0 breaks two paths: incremental scans keep re-discovering Zendesk's own placeholder, and crash recovery (reconcileAlreadyRedacted, which inspects comments.json after a 5xx or timeout on comment_redactions) fails to detect that Zendesk already committed the redaction.
The fix in internal/statemachine/statemachine.go:
func IsRedactedPlaceholder(filename string, sizeBytes int64) bool { return strings.EqualFold(strings.TrimSpace(filename), "redacted.txt") && sizeBytes >= 0 && sizeBytes <= 1 } Any user-uploaded redacted.txt larger than 1 byte is left alone.
6. DNS-Rebinding, IMDS, and BiDi Filename Hardening
Customer-supplied S3/R2 endpoints and dynamic redirect targets make outbound HTTP an SSRF surface. Validating the URL string alone fails against DNS rebinding to 169.254.169.254.
SafeDialContext in internal/ssrf/guard.go resolves DNS at dial time, normalizes IPv4-mapped IPv6 via addr.Unmap(), blocks loopback, RFC1918, CGNAT (100.64.0.0/10), link-local/IMDS (169.254.0.0/16, fc00::/7 including fd00:ec2::254), and reserved CIDRs across all resolved IPs, then dials the verified literal IP directly:
for _, ipAddr := range ips { if IsBlockedIP(ipAddr.IP) { return nil, fmt.Errorf("%w: %s", ErrBlockedIP, ipAddr.IP.String()) } } return dialer.DialContext(ctx, network, net.JoinHostPort(ips[0].IP.String(), port)) For untrusted filenames, SanitizeFilename strips traversal segments, control characters, and Unicode BiDi/RTL override runes (U+202A to U+202E, U+2066 to U+2069, U+200E, U+200F), capping UTF-8 length at 180 bytes while keeping the extension. BuildContentDisposition emits RFC 5987 attachment headers, and SafeDownloadContentType forces application/octet-stream for .svg, .html, .js, and active MIME types to prevent stored XSS from a customer's bucket.
Author note: These patterns come out of building VaultOffload, a BYO Cloudflare R2 / AWS S3 attachment offloader for Zendesk. VaultOffload is currently completing Zendesk Marketplace review.
