First step of the go-chi -> go-pkgz/routegroup migration. The HTTP->HTTPS redirect and ACME http-01 challenge routers are small, self-contained http.Handlers separate from the main API router, so they move cleanly: - chi.NewRouter() -> routegroup.New(http.NewServeMux()) - middleware.Throttle -> rest.Throttle (same concurrency-limit semantics) - middleware.Timeout -> local timeout helper (context deadline, mirrors chi) - drop middleware.RealIP: these routers do redirect/challenge only, with no per-IP logic, so the spoofable header trust is simply removed here - return http.Handler instead of chi.Router (callers already take http.Handler) chi stays a dependency (still used by the main API router); this only removes its use from ssl.go. go test -race, vet, golangci-lint and govulncheck clean.
128 lines
3.8 KiB
Go
128 lines
3.8 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestTimeout(t *testing.T) {
|
|
t.Run("fast handler passes through and gets a deadline", func(t *testing.T) {
|
|
var gotDeadline bool
|
|
h := timeout(time.Second)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_, gotDeadline = r.Context().Deadline()
|
|
w.WriteHeader(http.StatusCreated)
|
|
_, _ = w.Write([]byte("ok"))
|
|
}))
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", http.NoBody))
|
|
assert.True(t, gotDeadline, "request context should carry a deadline")
|
|
assert.Equal(t, http.StatusCreated, rec.Code)
|
|
assert.Equal(t, "ok", rec.Body.String())
|
|
})
|
|
|
|
t.Run("deadline exceeded writes 504", func(t *testing.T) {
|
|
h := timeout(10*time.Millisecond)(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
|
<-r.Context().Done() // honor the context: return only once the deadline fires
|
|
}))
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", http.NoBody))
|
|
assert.Equal(t, http.StatusGatewayTimeout, rec.Code)
|
|
})
|
|
}
|
|
|
|
func TestSSL_Redirect(t *testing.T) {
|
|
rest := Rest{RemarkURL: "https://localhost:443"}
|
|
|
|
ts := httptest.NewServer(rest.httpToHTTPSRouter())
|
|
defer ts.Close()
|
|
|
|
client := http.Client{
|
|
// prevent http redirect
|
|
CheckRedirect: func(*http.Request, []*http.Request) error {
|
|
return http.ErrUseLastResponse
|
|
},
|
|
|
|
// allow self-signed certificate
|
|
Transport: &http.Transport{
|
|
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
|
},
|
|
}
|
|
defer client.CloseIdleConnections()
|
|
|
|
// check http to https redirect response
|
|
resp, err := client.Get(ts.URL + "/blah?param=1")
|
|
require.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
assert.Equal(t, http.StatusTemporaryRedirect, resp.StatusCode)
|
|
assert.Equal(t, "https://localhost:443/blah?param=1", resp.Header.Get("Location"))
|
|
}
|
|
|
|
func TestSSL_RedirectURLKeepsConfiguredHost(t *testing.T) {
|
|
rest := Rest{RemarkURL: "https://localhost:443/base"}
|
|
req, err := http.NewRequest("GET", "http://example.com//evil.test/path?next=//evil.test", http.NoBody)
|
|
require.NoError(t, err)
|
|
|
|
redirectURL, err := rest.redirectURL(req)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, "https://localhost:443/base/evil.test/path?next=//evil.test", redirectURL)
|
|
}
|
|
|
|
func TestSSL_ACME_HTTPChallengeRouter(t *testing.T) {
|
|
rest := Rest{
|
|
RemarkURL: "https://localhost:443",
|
|
SSLConfig: SSLConfig{
|
|
ACMELocation: "acme",
|
|
},
|
|
}
|
|
|
|
m := rest.makeAutocertManager()
|
|
defer os.RemoveAll(rest.SSLConfig.ACMELocation)
|
|
|
|
ts := httptest.NewServer(rest.httpChallengeRouter(m))
|
|
defer ts.Close()
|
|
|
|
client := http.Client{
|
|
// prevent http redirect
|
|
CheckRedirect: func(*http.Request, []*http.Request) error {
|
|
return http.ErrUseLastResponse
|
|
},
|
|
}
|
|
defer client.CloseIdleConnections()
|
|
|
|
// check http to https redirect response
|
|
resp, err := client.Get(ts.URL + "/blah?param=1")
|
|
require.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
assert.Equal(t, http.StatusTemporaryRedirect, resp.StatusCode)
|
|
assert.Equal(t, "https://localhost:443/blah?param=1", resp.Header.Get("Location"))
|
|
|
|
// check acme http challenge
|
|
req, err := http.NewRequest("GET", ts.URL+"/.well-known/acme-challenge/token123", http.NoBody)
|
|
require.NoError(t, err)
|
|
req.Host = "localhost" // for passing hostPolicy check
|
|
resp, err = client.Do(req)
|
|
require.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
|
|
|
|
err = m.Cache.Put(context.Background(), "token123+http-01", []byte("token"))
|
|
assert.NoError(t, err)
|
|
|
|
resp, err = client.Do(req)
|
|
require.NoError(t, err)
|
|
defer resp.Body.Close()
|
|
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
|
body, err := io.ReadAll(resp.Body)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, "token", string(body))
|
|
}
|