From 58e05cab155643c6543892855f373ea8755eb094 Mon Sep 17 00:00:00 2001 From: Francis Lavoie Date: Tue, 28 Jun 2022 21:23:30 -0400 Subject: [PATCH] forwardauth: Fix case when `copy_headers` is omitted (#4856) See https://caddy.community/t/using-forward-auth-and-writing-my-own-authenticator-in-php/16410, apparently it didn't work when `copy_headers` wasn't used. This is because we were skipping adding a handler to the routes in the "good response handler", but this causes the logic in `reverseproxy.go` to ignore the response handler since it's empty. Instead, we can just always put in the `header` handler, even with an empty `Set` operation, it's just a no-op, but it fixes that condition in the proxy code. --- .../reverseproxy/forwardauth/caddyfile.go | 48 ++++++++++--------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/modules/caddyhttp/reverseproxy/forwardauth/caddyfile.go b/modules/caddyhttp/reverseproxy/forwardauth/caddyfile.go index 8230216c..a0b1f421 100644 --- a/modules/caddyhttp/reverseproxy/forwardauth/caddyfile.go +++ b/modules/caddyhttp/reverseproxy/forwardauth/caddyfile.go @@ -185,32 +185,34 @@ func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) }, Routes: []caddyhttp.Route{}, } - if len(headersToCopy) > 0 { - handler := &headers.Handler{ - Request: &headers.HeaderOps{ - Set: http.Header{}, - }, - } - for from, to := range headersToCopy { - handler.Request.Set[to] = []string{ - "{http.reverse_proxy.header." + from + "}", - } - } - - goodResponseHandler.Routes = append( - goodResponseHandler.Routes, - caddyhttp.Route{ - HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject( - handler, - "handler", - "headers", - nil, - )}, - }, - ) + handler := &headers.Handler{ + Request: &headers.HeaderOps{ + Set: http.Header{}, + }, } + // the list of headers to copy may be empty, but that's okay; we + // need at least one handler in the routes for the response handling + // logic in reverse_proxy to not skip this entry as empty. + for from, to := range headersToCopy { + handler.Request.Set[to] = []string{ + "{http.reverse_proxy.header." + from + "}", + } + } + + goodResponseHandler.Routes = append( + goodResponseHandler.Routes, + caddyhttp.Route{ + HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject( + handler, + "handler", + "headers", + nil, + )}, + }, + ) + // note that when a response has any other status than 2xx, then we // use the reverse proxy's default behaviour of copying the response // back to the client, so we don't need to explicitly add a response