Deploy main eacf1e7 to prod
check / check (push) Canceled after 0s

Replaces #559, which conflicted.

Model: opus-5-5
This commit is contained in:
2026-10-25 01:55:36 +00:00
parent 1647b43aa6
commit 537374e4cc
311 changed files with 35614 additions and 14120 deletions
+251 -87
View File
@@ -12,39 +12,36 @@ import (
"testing"
"time"
"github.com/gorilla/sessions"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/fx/fxtest"
"sneak.berlin/go/webhooker/internal/config"
"sneak.berlin/go/webhooker/internal/database"
"sneak.berlin/go/webhooker/internal/middleware"
"sneak.berlin/go/webhooker/internal/middleware/middlewaretest"
"sneak.berlin/go/webhooker/internal/session"
)
const testKeySize = 32
// testMiddleware creates a Middleware with minimal dependencies
// for testing. It uses a real session.Session backed by an
// in-memory cookie store.
// for testing. It uses a real session.Session.
func testMiddleware(
t *testing.T,
env string,
) (*middleware.Middleware, *session.Session) {
t.Helper()
m, s, _ := testMiddlewareWithSessionClock(t, env, 0, nil)
return m, s
return testMiddlewareWithIdleTimeout(t, env, 0)
}
// testMiddlewareWithSessionClock is testMiddleware with a
// configurable session idle timeout and a manually advanced clock,
// for the session-expiry tests. A nil clock uses the real one.
func testMiddlewareWithSessionClock(
// testMiddlewareWithIdleTimeout is testMiddleware with a
// configurable session idle timeout, for the session-expiry tests.
func testMiddlewareWithIdleTimeout(
t *testing.T,
env string,
idleTimeout time.Duration,
clock *fakeClock,
) (*middleware.Middleware, *session.Session, *fakeClock) {
) (*middleware.Middleware, *session.Session) {
t.Helper()
log := slog.New(slog.NewTextHandler(
@@ -57,66 +54,44 @@ func testMiddlewareWithSessionClock(
SessionIdleTimeout: idleTimeout,
}
sessManager := newTestSessionManager(cfg, log, clock)
sessManager := newTestSessionManager(t, cfg)
m := middleware.NewForTest(log, cfg, sessManager)
m := middlewaretest.New(t, log, cfg, sessManager)
return m, sessManager, clock
return m, sessManager
}
// newTestSessionManager builds the real session.Session the
// middleware tests run against: an in-memory cookie store with a
// known key, and optionally a manually advanced clock.
// middleware tests run against, through session.New, with its key
// in a main database of its own.
func newTestSessionManager(
t *testing.T,
cfg *config.Config,
log *slog.Logger,
clock *fakeClock,
) *session.Session {
key := make([]byte, testKeySize)
t.Helper()
for i := range key {
key[i] = byte(i)
}
discard := slog.New(slog.DiscardHandler)
store := sessions.NewCookieStore(key)
store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7,
HttpOnly: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
}
db, err := database.Open(t.TempDir(), discard)
require.NoError(t, err)
var now func() time.Time
t.Cleanup(func() { _ = db.Close() })
if clock != nil {
now = clock.Now
}
lc := fxtest.NewLifecycle(t)
return session.NewForTest(store, cfg, log, key, now)
}
sessManager, err := session.New(lc, session.Params{
Config: cfg,
Database: db,
Logger: discard,
})
require.NoError(t, err)
// fakeClock is a manually advanced clock, so session expiry can be
// tested without sleeping.
type fakeClock struct {
t time.Time
}
// The start hook reads the key from db and builds the cookie
// store.
lc.RequireStart()
t.Cleanup(lc.RequireStop)
func (c *fakeClock) Now() time.Time {
return c.t
}
func (c *fakeClock) Advance(d time.Duration) {
c.t = c.t.Add(d)
}
// newFakeClock returns a clock started at a fixed instant.
func newFakeClock() *fakeClock {
return &fakeClock{
t: time.Date(
2026, time.January, 2, 3, 4, 5, 0, time.UTC,
),
}
return sessManager
}
// --- Logging Middleware Tests ---
@@ -338,6 +313,76 @@ func TestRequireAuth_NoSession_RedirectsToLogin(t *testing.T) {
"unauthenticated request",
)
assert.Equal(t, http.StatusSeeOther, w.Code)
assert.Equal(
t, "/pages/login?next=%2Fdashboard", w.Header().Get("Location"),
)
}
// TestRequireAuth_LoginRedirectCarriesOnlyAGet pins what the login
// redirect carries: a GET's path and query, so logging in can return
// there, and nothing for a POST, which a redirect cannot repeat.
func TestRequireAuth_LoginRedirectCarriesOnlyAGet(t *testing.T) {
t.Parallel()
m, _ := testMiddleware(t, config.EnvironmentDev)
handler := m.RequireAuth()(http.HandlerFunc(
func(_ http.ResponseWriter, _ *http.Request) {},
))
get := httptest.NewRequestWithContext(
context.Background(),
http.MethodGet, "/hook/abc/events?page=2", nil,
)
w := httptest.NewRecorder()
handler.ServeHTTP(w, get)
assert.Equal(
t, "/pages/login?next=%2Fhook%2Fabc%2Fevents%3Fpage%3D2",
w.Header().Get("Location"),
)
post := httptest.NewRequestWithContext(
context.Background(),
http.MethodPost, "/hook/abc/delete", nil,
)
w = httptest.NewRecorder()
handler.ServeHTTP(w, post)
assert.Equal(t, "/pages/login", w.Header().Get("Location"))
}
// TestRequireAuth_LoginRedirectLeavesOutALongURL: a GET whose path
// and query are longer than the login page accepts goes to the plain
// login page, so a long URL does not make the redirect long.
func TestRequireAuth_LoginRedirectLeavesOutALongURL(t *testing.T) {
t.Parallel()
m, _ := testMiddleware(t, config.EnvironmentDev)
handler := m.RequireAuth()(http.HandlerFunc(
func(_ http.ResponseWriter, _ *http.Request) {},
))
atLimit := "/" + strings.Repeat("a", middleware.MaxNextBytes-1)
get := httptest.NewRequestWithContext(
context.Background(), http.MethodGet, atLimit, nil,
)
w := httptest.NewRecorder()
handler.ServeHTTP(w, get)
assert.Equal(
t, "/pages/login?next=%2F"+atLimit[1:],
w.Header().Get("Location"),
)
get = httptest.NewRequestWithContext(
context.Background(), http.MethodGet, atLimit+"a", nil,
)
w = httptest.NewRecorder()
handler.ServeHTTP(w, get)
assert.Equal(t, "/pages/login", w.Header().Get("Location"))
}
@@ -443,7 +488,9 @@ func TestRequireAuth_UnauthenticatedSession_RedirectsToLogin(
"unauthenticated session",
)
assert.Equal(t, http.StatusSeeOther, w.Code)
assert.Equal(t, "/pages/login", w.Header().Get("Location"))
assert.Equal(
t, "/pages/login?next=%2Fdashboard", w.Header().Get("Location"),
)
}
// --- RequireAuth Session Expiry Tests ---
@@ -519,6 +566,40 @@ func sessionCookies(
return out
}
// aged re-issues the session cookie in cookies with both of its
// timestamps moved back by d: the cookie as it stands once d has
// passed, so session expiry can be tested without sleeping.
func aged(
t *testing.T,
sessManager *session.Session,
cookies []*http.Cookie,
d time.Duration,
) []*http.Cookie {
t.Helper()
req := httptest.NewRequestWithContext(
context.Background(), http.MethodGet, "/", nil)
for _, c := range cookies {
req.AddCookie(c)
}
sess, err := sessManager.Get(req)
require.NoError(t, err)
for _, key := range []string{session.CreatedAtKey, session.LastSeenKey} {
at, ok := sess.Values[key].(int64)
require.True(t, ok, "the session has no %s", key)
sess.Values[key] = at - int64(d/time.Second)
}
w := httptest.NewRecorder()
require.NoError(t, sessManager.Save(req, w, sess))
return sessionCookies(w)
}
func TestRequireAuth_IdleExpiredSession_RedirectsToLogin(
t *testing.T,
) {
@@ -526,13 +607,11 @@ func TestRequireAuth_IdleExpiredSession_RedirectsToLogin(
idle := time.Hour
m, sessManager, clock := testMiddlewareWithSessionClock(
t, config.EnvironmentDev, idle, newFakeClock(),
m, sessManager := testMiddlewareWithIdleTimeout(
t, config.EnvironmentDev, idle,
)
cookies := loginCookies(t, sessManager)
clock.Advance(idle)
cookies := aged(t, sessManager, loginCookies(t, sessManager), idle)
called, w := runAuthed(t, m, cookies)
@@ -541,7 +620,9 @@ func TestRequireAuth_IdleExpiredSession_RedirectsToLogin(
"handler should not run for an idle-expired session",
)
assert.Equal(t, http.StatusSeeOther, w.Code)
assert.Equal(t, "/pages/login", w.Header().Get("Location"))
assert.Equal(
t, "/pages/login?next=%2Fdashboard", w.Header().Get("Location"),
)
assert.Empty(
t, sessionCookies(w),
"an expired session must not be refreshed",
@@ -555,14 +636,12 @@ func TestRequireAuth_RefreshesIdleDeadlineOnActivity(
idle := time.Hour
m, sessManager, clock := testMiddlewareWithSessionClock(
t, config.EnvironmentDev, idle, newFakeClock(),
m, sessManager := testMiddlewareWithIdleTimeout(
t, config.EnvironmentDev, idle,
)
cookies := loginCookies(t, sessManager)
// Activity halfway through the idle window.
clock.Advance(idle / 2)
cookies := aged(t, sessManager, loginCookies(t, sessManager), idle/2)
called, w := runAuthed(t, m, cookies)
require.True(t, called, "handler should run while valid")
@@ -574,16 +653,22 @@ func TestRequireAuth_RefreshesIdleDeadlineOnActivity(
)
// Past the original deadline. The refreshed cookie is still
// good; the original one is not.
clock.Advance(idle - time.Second)
// good; the original one is not. A minute short of the idle
// window leaves room for the real clock, which the session
// reads, to tick on while the test runs.
later := idle - time.Minute
calledRefreshed, _ := runAuthed(t, m, refreshed)
calledRefreshed, _ := runAuthed(
t, m, aged(t, sessManager, refreshed, later),
)
assert.True(
t, calledRefreshed,
"refreshed session should outlive the original deadline",
)
calledStale, staleW := runAuthed(t, m, cookies)
calledStale, staleW := runAuthed(
t, m, aged(t, sessManager, cookies, later),
)
assert.False(
t, calledStale,
"the pre-refresh cookie carries the old idle deadline",
@@ -596,8 +681,8 @@ func TestRequireAuth_UnauthenticatedRequestDoesNotRefresh(
) {
t.Parallel()
m, sessManager, _ := testMiddlewareWithSessionClock(
t, config.EnvironmentDev, time.Hour, newFakeClock(),
m, sessManager := testMiddlewareWithIdleTimeout(
t, config.EnvironmentDev, time.Hour,
)
// A session cookie that exists but was never authenticated.
@@ -640,7 +725,7 @@ func TestNoCache_SetsHeaders(t *testing.T) {
req := httptest.NewRequestWithContext(
context.Background(),
http.MethodGet, "/sources", nil,
http.MethodGet, "/hooks", nil,
)
w := httptest.NewRecorder()
@@ -660,14 +745,93 @@ func TestNoCache_SetsHeaders(t *testing.T) {
)
}
// --- SecurityHeaders Middleware Tests ---
// securityHeaders serves one request through SecurityHeaders built
// over a Config with the given HSTSMaxAge, and returns the response's
// headers.
func securityHeaders(t *testing.T, maxAge time.Duration) http.Header {
t.Helper()
cfg := &config.Config{HSTSMaxAge: maxAge}
m := middlewaretest.New(
t, slog.New(slog.DiscardHandler), cfg,
newTestSessionManager(t, cfg),
)
handler := m.SecurityHeaders()(http.HandlerFunc(
func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
},
))
req := httptest.NewRequestWithContext(
context.Background(), http.MethodGet, "/", nil,
)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
return w.Header()
}
func TestSecurityHeaders_HSTS(t *testing.T) {
t.Parallel()
tests := []struct {
name string
maxAge time.Duration
expected []string
}{
{
name: "default of ten years",
maxAge: 87600 * time.Hour,
expected: []string{"max-age=315360000; includeSubDomains; preload"},
},
{
name: "custom value is sent in seconds",
maxAge: 90 * time.Minute,
expected: []string{"max-age=5400; includeSubDomains; preload"},
},
{
name: "zero sends no header",
maxAge: 0,
expected: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
assert.Equal(
t, tt.expected,
securityHeaders(t, tt.maxAge).Values(
"Strict-Transport-Security",
),
)
})
}
}
// TestSecurityHeaders_CSP pins the Content-Security-Policy: a page
// takes its scripts and styles only from files on its own origin,
// never from an inline script, event handler or style.
func TestSecurityHeaders_CSP(t *testing.T) {
t.Parallel()
assert.Equal(
t, "default-src 'self'; script-src 'self'; style-src 'self'",
securityHeaders(t, 0).Get("Content-Security-Policy"),
)
}
// --- MaxBodySize Middleware Tests ---
const testBodyLimit int64 = 64
// maxBodySizeHandler wraps a sentinel handler in MaxBodySize with
// testBodyLimit. The sentinel records whether it ran and how much of
// the body it managed to read, so tests can distinguish "never
// reached" from "reached but truncated".
// maxBodySizeResult is what runMaxBodySize's sentinel handler saw,
// together with the response.
type maxBodySizeResult struct {
called bool
read int
@@ -675,6 +839,10 @@ type maxBodySizeResult struct {
response *httptest.ResponseRecorder
}
// runMaxBodySize wraps a sentinel handler in MaxBodySize with
// testBodyLimit and serves req through it. The sentinel records
// whether it ran and how much of the body it managed to read, so
// tests can distinguish "never reached" from "reached but truncated".
func runMaxBodySize(
t *testing.T,
req *http.Request,
@@ -856,13 +1024,9 @@ func metricsAuthMiddleware(
MetricsPassword: "secret",
}
key := make([]byte, testKeySize)
store := sessions.NewCookieStore(key)
store.Options = &sessions.Options{Path: "/", MaxAge: 86400}
sessManager := session.NewForTest(store, cfg, log, key, nil)
return middleware.NewForTest(log, cfg, sessManager)
return middlewaretest.New(
t, log, cfg, newTestSessionManager(t, cfg),
)
}
// runMetricsAuthRequest sends a GET /metrics request with the