writer.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. // headerwriter is responsible for writing processing/stream response headers
  2. package headerwriter
  3. import (
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/imgproxy/imgproxy/v3/httpheaders"
  10. )
  11. // Writer is a struct that builds HTTP response headers.
  12. type Writer struct {
  13. config *Config
  14. originalResponseHeaders http.Header // Original response headers
  15. result http.Header // Headers to be written to the response
  16. maxAge int // Current max age for Cache-Control header
  17. url string // URL of the request, used for canonical header
  18. varyValue string // Vary header value
  19. }
  20. // New creates a new HeaderBuilder instance with the provided origin headers and URL
  21. func New(config *Config, originalResponseHeaders http.Header, url string) *Writer {
  22. vary := make([]string, 0)
  23. if config.SetVaryAccept {
  24. vary = append(vary, "Accept")
  25. }
  26. if config.EnableClientHints {
  27. vary = append(vary, "Sec-CH-DPR", "DPR", "Sec-CH-Width", "Width")
  28. }
  29. varyValue := strings.Join(vary, ", ")
  30. return &Writer{
  31. config: config,
  32. originalResponseHeaders: originalResponseHeaders,
  33. url: url,
  34. result: make(http.Header),
  35. maxAge: -1,
  36. varyValue: varyValue,
  37. }
  38. }
  39. // SetIsFallbackImage sets the Fallback-Image header to
  40. // indicate that the fallback image was used.
  41. func (w *Writer) SetIsFallbackImage() {
  42. // We set maxAge to FallbackImageTTL if it's explicitly passed
  43. if w.config.FallbackImageTTL < 0 {
  44. return
  45. }
  46. // However, we should not overwrite existing value if set (or greater than ours)
  47. if w.maxAge < 0 || w.maxAge > w.config.FallbackImageTTL {
  48. w.maxAge = w.config.FallbackImageTTL
  49. }
  50. }
  51. // SetExpires sets the TTL from time
  52. func (w *Writer) SetExpires(expires *time.Time) {
  53. if expires == nil {
  54. return
  55. }
  56. // Convert current maxAge to time
  57. currentMaxAgeTime := time.Now().Add(time.Duration(w.maxAge) * time.Second)
  58. // If maxAge outlives expires or was not set, we'll use expires as maxAge.
  59. if w.maxAge < 0 || expires.Before(currentMaxAgeTime) {
  60. w.maxAge = min(w.config.DefaultTTL, max(0, int(time.Until(*expires).Seconds())))
  61. }
  62. }
  63. // SetLastModified sets the Last-Modified header from request
  64. func (w *Writer) SetLastModified() {
  65. if !w.config.LastModifiedEnabled {
  66. return
  67. }
  68. val := w.originalResponseHeaders.Get(httpheaders.LastModified)
  69. if len(val) == 0 {
  70. return
  71. }
  72. w.result.Set(httpheaders.LastModified, val)
  73. }
  74. // SetVary sets the Vary header
  75. func (w *Writer) SetVary() {
  76. if len(w.varyValue) > 0 {
  77. w.result.Set(httpheaders.Vary, w.varyValue)
  78. }
  79. }
  80. // Passthrough copies specified headers from the original response headers to the response headers.
  81. func (w *Writer) Passthrough(only []string) {
  82. for _, key := range only {
  83. values := w.originalResponseHeaders.Values(key)
  84. for _, value := range values {
  85. w.result.Add(key, value)
  86. }
  87. }
  88. }
  89. // CopyFrom copies specified headers from the headers object. Please note that
  90. // all the past operations may overwrite those values.
  91. func (w *Writer) CopyFrom(headers http.Header, only []string) {
  92. for _, key := range only {
  93. values := headers.Values(key)
  94. for _, value := range values {
  95. w.result.Add(key, value)
  96. }
  97. }
  98. }
  99. // SetContentLength sets the Content-Length header
  100. func (w *Writer) SetContentLength(contentLength int) {
  101. if contentLength < 0 {
  102. return
  103. }
  104. w.result.Set(httpheaders.ContentLength, strconv.Itoa(contentLength))
  105. }
  106. // SetContentType sets the Content-Type header
  107. func (w *Writer) SetContentType(mime string) {
  108. w.result.Set(httpheaders.ContentType, mime)
  109. }
  110. // writeCanonical sets the Link header with the canonical URL.
  111. // It is mandatory for any response if enabled in the configuration.
  112. func (b *Writer) SetCanonical() {
  113. if !b.config.SetCanonicalHeader {
  114. return
  115. }
  116. if strings.HasPrefix(b.url, "https://") || strings.HasPrefix(b.url, "http://") {
  117. value := fmt.Sprintf(`<%s>; rel="canonical"`, b.url)
  118. b.result.Set(httpheaders.Link, value)
  119. }
  120. }
  121. // setCacheControl sets the Cache-Control header with the specified value.
  122. func (w *Writer) setCacheControl(value int) bool {
  123. if value <= 0 {
  124. return false
  125. }
  126. w.result.Set(httpheaders.CacheControl, fmt.Sprintf("max-age=%d, public", value))
  127. return true
  128. }
  129. // setCacheControlNoCache sets the Cache-Control header to no-cache (default).
  130. func (w *Writer) setCacheControlNoCache() {
  131. w.result.Set(httpheaders.CacheControl, "no-cache")
  132. }
  133. // setCacheControlPassthrough sets the Cache-Control header from the request
  134. // if passthrough is enabled in the configuration.
  135. func (w *Writer) setCacheControlPassthrough() bool {
  136. if !w.config.CacheControlPassthrough || w.maxAge > 0 {
  137. return false
  138. }
  139. if val := w.originalResponseHeaders.Get(httpheaders.CacheControl); val != "" {
  140. w.result.Set(httpheaders.CacheControl, val)
  141. return true
  142. }
  143. if val := w.originalResponseHeaders.Get(httpheaders.Expires); val != "" {
  144. if t, err := time.Parse(http.TimeFormat, val); err == nil {
  145. maxAge := max(0, int(time.Until(t).Seconds()))
  146. return w.setCacheControl(maxAge)
  147. }
  148. }
  149. return false
  150. }
  151. // setCSP sets the Content-Security-Policy header to prevent script execution.
  152. func (w *Writer) setCSP() {
  153. w.result.Set(httpheaders.ContentSecurityPolicy, "script-src 'none'")
  154. }
  155. // Write writes the headers to the response writer. It does not overwrite
  156. // target headers, which were set outside the header writer.
  157. func (w *Writer) Write(rw http.ResponseWriter) {
  158. // Then, let's try to set Cache-Control using priority order
  159. switch {
  160. case w.setCacheControl(w.maxAge): // First, try set explicit
  161. case w.setCacheControlPassthrough(): // Try to pick up from request headers
  162. case w.setCacheControl(w.config.DefaultTTL): // Fallback to default value
  163. default:
  164. w.setCacheControlNoCache() // By default we use no-cache
  165. }
  166. w.setCSP()
  167. for key, values := range w.result {
  168. // Do not overwrite existing headers which were set outside the header writer
  169. if len(rw.Header().Get(key)) > 0 {
  170. continue
  171. }
  172. for _, value := range values {
  173. rw.Header().Add(key, value)
  174. }
  175. }
  176. }