Keep max-age within an expiring image URL's lifetime (closes #63)

Both image routes sent Cache-Control: public, max-age=31536000,
immutable, so a browser or proxy could keep serving an image for a year
after its signed or encrypted URL had expired. The header is now built
from the request's Expires: max-age is the whole seconds left until the
URL expires, never negative, or one year for a URL with no expiry.
ToImageRequest now carries an encrypted URL's expiry onto the request,
as the image route already does with exp. immutable stays: it only stops
revalidation while a copy is fresh, and freshness now ends at the
expiry. README.md documents the header.

Model: opus-5-5
This commit is contained in:
2026-09-29 01:25:25 +00:00
parent ac95c33cdb
commit 0a0142d1af
6 changed files with 44 additions and 5 deletions
+19 -1
View File
@@ -220,6 +220,24 @@ func (s *Handlers) respondImageError(
s.respondError(w, "internal error", http.StatusInternalServerError)
}
// cacheControl returns the Cache-Control header for an image served through a
// URL that expires at expires, or never when expires is the zero time. A cache
// may keep the image for a year, but not past the URL's expiry, after which
// pixa refuses the URL. The seconds left are rounded down and never negative.
// immutable only stops revalidation while the image is fresh, so it also ends
// at the expiry.
func cacheControl(expires time.Time) string {
const oneYear = 365 * 24 * time.Hour
maxAge := oneYear
if !expires.IsZero() {
maxAge = min(maxAge, max(time.Until(expires), 0))
}
return fmt.Sprintf("public, max-age=%d, immutable", int64(maxAge/time.Second))
}
// writeImageResponse writes headers and streams the image content,
// handling conditional and HEAD requests.
func (s *Handlers) writeImageResponse(
@@ -235,7 +253,7 @@ func (s *Handlers) writeImageResponse(
}
// Cache control headers
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
w.Header().Set("Cache-Control", cacheControl(req.Expires))
w.Header().Set("X-Pixa-Cache", string(resp.CacheStatus))
if resp.ETag != "" {