This commit is contained in:
Phat Le 2026-11-16 11:21:20 +03:00 • committed by GitHub
commit ca06c090b6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 290 additions and 9 deletions

View file

@ -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
}
]
}
}
}
}
}

View file

@ -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 <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)
)

View file

@ -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)
}
}
}