From b57b2af30b0f344b384ace1ce482999cfffeb694 Mon Sep 17 00:00:00 2001 From: phatlc Date: Fri, 25 Sep 2026 00:41:44 +0700 Subject: [PATCH] caddyhttp: Add status_code option to http_redirect listener wrapper The HTTP->HTTPS redirect written by the http_redirect listener wrapper was always a 308. Allow configuring it to 301, 302, 303, 307 or 308, defaulting to 308, and add Caddyfile support: http_redirect { status_code 307 } Closes #6499 --- ...server_options_http_redirect.caddyfiletest | 49 ++++++ modules/caddyhttp/httpredirectlistener.go | 87 +++++++++- .../caddyhttp/httpredirectlistener_test.go | 163 ++++++++++++++++++ 3 files changed, 290 insertions(+), 9 deletions(-) create mode 100644 caddytest/integration/caddyfile_adapt/global_server_options_http_redirect.caddyfiletest create mode 100644 modules/caddyhttp/httpredirectlistener_test.go diff --git a/caddytest/integration/caddyfile_adapt/global_server_options_http_redirect.caddyfiletest b/caddytest/integration/caddyfile_adapt/global_server_options_http_redirect.caddyfiletest new file mode 100644 index 000000000..efe18fe91 --- /dev/null +++ b/caddytest/integration/caddyfile_adapt/global_server_options_http_redirect.caddyfiletest @@ -0,0 +1,49 @@ +{ + servers { + listener_wrappers { + http_redirect { + status_code 307 + } + tls + } + } +} + +foo.com { +} + +---------- +{ + "apps": { + "http": { + "servers": { + "srv0": { + "listen": [ + ":443" + ], + "listener_wrappers": [ + { + "status_code": 307, + "wrapper": "http_redirect" + }, + { + "wrapper": "tls" + } + ], + "routes": [ + { + "match": [ + { + "host": [ + "foo.com" + ] + } + ], + "terminal": true + } + ] + } + } + } + } +} diff --git a/modules/caddyhttp/httpredirectlistener.go b/modules/caddyhttp/httpredirectlistener.go index 5d4ccb9ee..364f89aab 100644 --- a/modules/caddyhttp/httpredirectlistener.go +++ b/modules/caddyhttp/httpredirectlistener.go @@ -21,6 +21,7 @@ import ( "io" "net" "net/http" + "strconv" "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" @@ -47,6 +48,11 @@ type HTTPRedirectListenerWrapper struct { // MaxHeaderBytes is the maximum size to parse from a client's // HTTP request headers. Default: 1 MB MaxHeaderBytes int64 `json:"max_header_bytes,omitempty"` + + // StatusCode is the HTTP status code to use for the redirect + // response. It must be one of 301, 302, 303, 307 or 308. + // Default: 308 (Permanent Redirect) + StatusCode int `json:"status_code,omitempty"` } func (HTTPRedirectListenerWrapper) CaddyModule() caddy.ModuleInfo { @@ -56,12 +62,71 @@ func (HTTPRedirectListenerWrapper) CaddyModule() caddy.ModuleInfo { } } +// UnmarshalCaddyfile sets up the listener wrapper from Caddyfile tokens. Syntax: +// +// http_redirect { +// status_code +// } func (h *HTTPRedirectListenerWrapper) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { + d.Next() // consume wrapper name + + // No same-line options are supported + if d.NextArg() { + return d.ArgErr() + } + + for d.NextBlock(0) { + switch d.Val() { + case "status_code": + if !d.NextArg() { + return d.ArgErr() + } + code, err := strconv.Atoi(d.Val()) + if err != nil { + return d.Errf("parsing status code: %v", err) + } + if !validHTTPRedirectStatus(code) { + return d.Errf("invalid redirect status code: %d (must be one of 301, 302, 303, 307, 308)", code) + } + if d.NextArg() { + return d.ArgErr() + } + h.StatusCode = code + default: + return d.Errf("unrecognized subdirective '%s'", d.Val()) + } + } + return nil +} + +// Validate ensures the configured status code is a redirect status. +func (h *HTTPRedirectListenerWrapper) Validate() error { + if h.StatusCode != 0 && !validHTTPRedirectStatus(h.StatusCode) { + return fmt.Errorf("invalid redirect status code: %d (must be one of 301, 302, 303, 307, 308)", h.StatusCode) + } return nil } func (h *HTTPRedirectListenerWrapper) WrapListener(l net.Listener) net.Listener { - return &httpRedirectListener{l, h.MaxHeaderBytes} + statusCode := h.StatusCode + if statusCode == 0 { + statusCode = http.StatusPermanentRedirect + } + return &httpRedirectListener{l, h.MaxHeaderBytes, statusCode} +} + +// validHTTPRedirectStatus reports whether code is a status +// code that can be used for the HTTP->HTTPS redirect. +func validHTTPRedirectStatus(code int) bool { + switch code { + case http.StatusMovedPermanently, + http.StatusFound, + http.StatusSeeOther, + http.StatusTemporaryRedirect, + http.StatusPermanentRedirect: + return true + } + return false } // httpRedirectListener is listener that checks the first few bytes @@ -70,6 +135,7 @@ func (h *HTTPRedirectListenerWrapper) WrapListener(l net.Listener) net.Listener type httpRedirectListener struct { net.Listener maxHeaderBytes int64 + statusCode int } // Accept waits for and returns the next connection to the listener, @@ -86,17 +152,19 @@ func (l *httpRedirectListener) Accept() (net.Conn, error) { } return &httpRedirectConn{ - Conn: c, - limit: maxHeaderBytes, - r: bufio.NewReader(c), + Conn: c, + limit: maxHeaderBytes, + statusCode: l.statusCode, + r: bufio.NewReader(c), }, nil } type httpRedirectConn struct { net.Conn - once bool - limit int64 - r *bufio.Reader + once bool + limit int64 + statusCode int + r *bufio.Reader } // Read tries to peek at the first few bytes of the request, and if we get @@ -143,8 +211,8 @@ func (c *httpRedirectConn) Read(p []byte) (int, error) { headers.Add("Location", "https://"+req.Host+req.URL.String()) resp := &http.Response{ Proto: "HTTP/1.0", - Status: "308 Permanent Redirect", - StatusCode: 308, + Status: fmt.Sprintf("%d %s", c.statusCode, http.StatusText(c.statusCode)), + StatusCode: c.statusCode, ProtoMajor: 1, ProtoMinor: 0, Header: headers, @@ -170,5 +238,6 @@ func firstBytesLookLikeHTTP(hdr []byte) bool { var ( _ caddy.ListenerWrapper = (*HTTPRedirectListenerWrapper)(nil) + _ caddy.Validator = (*HTTPRedirectListenerWrapper)(nil) _ caddyfile.Unmarshaler = (*HTTPRedirectListenerWrapper)(nil) ) diff --git a/modules/caddyhttp/httpredirectlistener_test.go b/modules/caddyhttp/httpredirectlistener_test.go new file mode 100644 index 000000000..e618ad803 --- /dev/null +++ b/modules/caddyhttp/httpredirectlistener_test.go @@ -0,0 +1,163 @@ +// Copyright 2015 Matthew Holt and The Caddy Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package caddyhttp + +import ( + "bufio" + "net" + "net/http" + "testing" + + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" +) + +func TestHTTPRedirectListenerStatusCode(t *testing.T) { + for _, tc := range []struct { + name string + statusCode int + expected int + }{ + {name: "default", statusCode: 0, expected: http.StatusPermanentRedirect}, + {name: "301", statusCode: http.StatusMovedPermanently, expected: http.StatusMovedPermanently}, + {name: "302", statusCode: http.StatusFound, expected: http.StatusFound}, + {name: "303", statusCode: http.StatusSeeOther, expected: http.StatusSeeOther}, + {name: "307", statusCode: http.StatusTemporaryRedirect, expected: http.StatusTemporaryRedirect}, + {name: "308", statusCode: http.StatusPermanentRedirect, expected: http.StatusPermanentRedirect}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := doHTTPRedirectListenerRequest(t, &HTTPRedirectListenerWrapper{StatusCode: tc.statusCode}) + defer resp.Body.Close() + + if resp.StatusCode != tc.expected { + t.Errorf("expected status %d, got %d", tc.expected, resp.StatusCode) + } + if expected := http.StatusText(tc.expected); resp.Status[4:] != expected { + t.Errorf("expected status text %q, got %q", expected, resp.Status[4:]) + } + if loc, expected := resp.Header.Get("Location"), "https://example.com:8443/foo?bar=baz"; loc != expected { + t.Errorf("expected Location %q, got %q", expected, loc) + } + }) + } +} + +// doHTTPRedirectListenerRequest sends a plaintext HTTP request to a +// listener wrapped by h and returns the response it writes back. +func doHTTPRedirectListenerRequest(t *testing.T, h *HTTPRedirectListenerWrapper) *http.Response { + t.Helper() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("failed to listen: %v", err) + } + wrapped := h.WrapListener(ln) + t.Cleanup(func() { _ = wrapped.Close() }) + + serverErr := make(chan error, 1) + go func() { + conn, err := wrapped.Accept() + if err != nil { + serverErr <- err + return + } + defer conn.Close() + _, err = conn.Read(make([]byte, 1)) + serverErr <- err + }() + + client, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatalf("failed to dial: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + + _, err = client.Write([]byte("GET /foo?bar=baz HTTP/1.1\r\nHost: example.com:8443\r\n\r\n")) + if err != nil { + t.Fatalf("failed to write request: %v", err) + } + + resp, err := http.ReadResponse(bufio.NewReader(client), nil) + if err != nil { + t.Fatalf("failed to read response: %v", err) + } + + // the listener must report an error so the connection is closed + if err := <-serverErr; err == nil { + t.Error("expected an error from Read after redirecting, got nil") + } + + return resp +} + +func TestHTTPRedirectListenerWrapperValidate(t *testing.T) { + for _, code := range []int{0, 301, 302, 303, 307, 308} { + if err := (&HTTPRedirectListenerWrapper{StatusCode: code}).Validate(); err != nil { + t.Errorf("status code %d: unexpected error: %v", code, err) + } + } + for _, code := range []int{200, 300, 304, 305, 306, 309, 404} { + if err := (&HTTPRedirectListenerWrapper{StatusCode: code}).Validate(); err == nil { + t.Errorf("status code %d: expected an error, got nil", code) + } + } +} + +func TestHTTPRedirectListenerWrapperUnmarshalCaddyfile(t *testing.T) { + for i, tc := range []struct { + input string + shouldErr bool + statusCode int + }{ + {input: `http_redirect`, statusCode: 0}, + {input: `http_redirect { + status_code 307 + }`, statusCode: 307}, + {input: `http_redirect { + status_code 301 + }`, statusCode: 301}, + {input: `http_redirect 307`, shouldErr: true}, + {input: `http_redirect { + status_code + }`, shouldErr: true}, + {input: `http_redirect { + status_code 307 308 + }`, shouldErr: true}, + {input: `http_redirect { + status_code 200 + }`, shouldErr: true}, + {input: `http_redirect { + status_code temporary + }`, shouldErr: true}, + {input: `http_redirect { + foo bar + }`, shouldErr: true}, + } { + h := new(HTTPRedirectListenerWrapper) + err := h.UnmarshalCaddyfile(caddyfile.NewTestDispenser(tc.input)) + if tc.shouldErr { + if err == nil { + t.Errorf("test %d: expected an error, got nil", i) + } + continue + } + if err != nil { + t.Errorf("test %d: unexpected error: %v", i, err) + continue + } + if h.StatusCode != tc.statusCode { + t.Errorf("test %d: expected status code %d, got %d", i, tc.statusCode, h.StatusCode) + } + } +}