caddy: Invalid status codes returned from reverse_proxy when used with replace-response

I’ve been using the replace-response module alongside reverse_proxy recently and observed incorrect status codes being returned from the proxy, e.g., the origin responded with a 404 and the proxy responds with a 200.

flowchart
UA --> |Request| reverse_proxy --> |Request| Origin
Origin --> |404 Origin Response| reverse_proxy --> |200 Proxy Response| UA

After a bit of debugging, it looks like the call to copyResponse results in a flush action here, which causes a 200 status code to be written after http.ResponseController.Flush unwraps and writes to the replace-response’s replaceWriter caddyhttp.responseRecorder.

edit: I mistakenly thought I had streaming enabled, which is why I originally referenced replaceWriter.

A potential fix would be to check for an Unwrap method on the response writer alongside the base one in reverseproxy.go. I’ve tested this locally but I’m not sure if it’s the best solution. I’m also not entirely sure if this is even considered a bug. I know that flush_interval is available as a configuration and I haven’t tested if it solves the issue, but it definitely was not an obvious solution to the behavior if it is.

edit: Setting flush_interval does not seem to correct the issue.

type unwrapper interface {
  Unwrap() http.ResponseWriter
}

func (h *Handler) finalizeResponse {
  //...
  // Line 955
  rw.WriteHeader(res.StatusCode)
  
  // Unwrap and write non-200 status code
  if rw, ok := rw.(unwrapper); res.StatusCode != http.StatusOK && ok {
	rw.Unwrap().WriteHeader(res.StatusCode)
  }

  if h.VerboseLogs {
	logger.Debug("wrote header")
  }

  err := h.copyResponse(rw, res.Body, h.flushInterval(req, res), logger)
  //...
}

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 1
  • Comments: 15 (15 by maintainers)

Most upvoted comments

@ImpostorKeanu Can you try xcaddy buiild fix-6144 to see if it’s fixed.

I think it’s because we only called WriteHeader on the wrapped http.ResponseWriter, and that status is not written to the underlying response writer.

Thanks for the report and the possible solution(s).

My pleasure! Caddy is one of my favorite projects. It’s a minor contribution, but it’s honest work 😄

What about the flush interval tuning? Does that work?

Tried a few different values (1s, 5s) with no change @mholt …

Okay. So I think unwrapping is fine; see http.ResponseController in stdlib that does it as well via an anonymous interface assertion, could do it like that here.

But it feels weird that we’re calling WriteHeader twice. Is there any way we can avoid that? Maybe that needs an explanation for why that’s correct. I’m concerned it might break some edgecases, without having a full understanding of the consequences.