Files
lincodex/backend/integration_test/session_http_test.go
T

496 lines
21 KiB
Go

//go:build integration
package integration_test
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
httpadapter "lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
)
const (
sessionHTTPTestTimeout = 5 * time.Minute
sessionHTTPTestOrigin = "http://localhost:8080"
sessionHTTPTestPass = "correct horse battery staple"
)
type sessionHTTPHarness struct {
pool *pgxpool.Pool
store *postgresadapter.IdentityStore
router http.Handler
credentials *identity.Credentials
clock *testClock
logs *strings.Builder
}
func newSessionHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness {
t.Helper()
return newSessionHTTPHarnessWithSettings(ctx, t, env, identity.SessionSettings{
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit),
EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
IdleTimeout: env.Config.IdentitySessionIdleTimeout,
AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime,
})
}
func newSessionHTTPHarnessWithSettings(
ctx context.Context,
t *testing.T,
env *testEnvironment,
settings identity.SessionSettings,
) *sessionHTTPHarness {
t.Helper()
pool := env.newPool(ctx, t)
store := postgresadapter.NewIdentityStore(pool)
hasher, err := argon2id.NewHasher(1)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
credentials := identity.NewCredentials(hasher)
keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)}
service, err := identity.NewSessionService(identity.SessionDependencies{
Transactor: postgresadapter.NewTransactor(pool),
Users: store.Users(),
Sessions: store.Sessions(),
Credentials: credentials,
Limiter: env.Redis,
Keyring: keyring,
Clock: clock.Now,
}, settings)
if err != nil {
t.Fatalf("NewSessionService() error = %v", err)
}
logs := &strings.Builder{}
logger := slog.New(slog.NewJSONHandler(logs, nil))
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(service, env.Config.AppPublicURL))
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler))
router, err := httpadapter.NewRouter(
healthHandler,
handler,
v1.NewSessionSecurity(service, env.Config.AppPublicURL),
responder,
prometheus.New(),
logger,
nil,
)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}
}
func createSessionHTTPUser(
ctx context.Context,
t *testing.T,
harness *sessionHTTPHarness,
email string,
passwordHash domain.PasswordHash,
verified bool,
) domain.User {
t.Helper()
address, err := domain.NewEmailAddress(email)
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
now := harness.clock.Now().Truncate(time.Microsecond)
user, err := domain.NewUser(domain.Registration{
Email: address,
PasswordHash: passwordHash,
Scenario: domain.ScenarioCandidate,
RegisteredAt: now,
})
if err != nil {
t.Fatalf("NewUser() error = %v", err)
}
if err := harness.store.Users().Create(ctx, user); err != nil {
t.Fatalf("Create(%s) error = %v", email, err)
}
if !verified {
return user
}
user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond))
if err != nil {
t.Fatalf("MarkEmailVerified() error = %v", err)
}
return user
}
func (harness *sessionHTTPHarness) request(
t *testing.T,
method string,
path string,
body string,
origin string,
cookie string,
csrf string,
remoteAddr string,
) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
if origin != "" {
request.Header.Set("Origin", origin)
}
if cookie != "" {
request.Header.Set("Cookie", "__Host-lincodex_session="+cookie)
}
if csrf != "" {
request.Header.Set("X-CSRF-Token", csrf)
}
request.RemoteAddr = remoteAddr
recorder := httptest.NewRecorder()
harness.router.ServeHTTP(recorder, request)
return recorder
}
func loginSessionHTTP(t *testing.T, harness *sessionHTTPHarness, email, password string, origin, cookie, remoteAddr string) *httptest.ResponseRecorder {
t.Helper()
body, err := json.Marshal(struct {
Email string `json:"email"`
Password string `json:"password"`
}{Email: email, Password: password})
if err != nil {
t.Fatalf("marshal login request: %v", err)
}
return harness.request(t, http.MethodPost, "/api/v1/identity/sessions", string(body), origin, cookie, "", remoteAddr)
}
func requireSessionProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code string) {
t.Helper()
var body struct {
Code string `json:"code"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode problem response %d %s: %v", response.Code, response.Body.String(), err)
}
if response.Code != status || body.Code != code {
t.Fatalf("response = %d code=%q body=%s, want %d code=%q", response.Code, body.Code, response.Body.String(), status, code)
}
}
func requireSessionCookie(t *testing.T, response *httptest.ResponseRecorder) *http.Cookie {
t.Helper()
cookies := response.Result().Cookies()
if len(cookies) != 1 {
t.Fatalf("Set-Cookie values = %v, want exactly one session cookie", response.Header().Values("Set-Cookie"))
}
cookie := cookies[0]
if cookie.Name != "__Host-lincodex_session" || cookie.Value == "" || cookie.Path != "/" || cookie.Domain != "" ||
!cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge <= 0 || cookie.Expires.IsZero() {
t.Fatalf("session cookie attributes = %+v", cookie)
}
return cookie
}
func requireExpiredSessionCookie(t *testing.T, response *httptest.ResponseRecorder) {
t.Helper()
cookies := response.Result().Cookies()
if len(cookies) != 1 {
t.Fatalf("Set-Cookie values = %v, want one cleared session cookie", response.Header().Values("Set-Cookie"))
}
cookie := cookies[0]
if cookie.Name != "__Host-lincodex_session" || cookie.Value != "" || cookie.Path != "/" || cookie.Domain != "" ||
!cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge >= 0 {
t.Fatalf("cleared session cookie attributes = %+v", cookie)
}
}
func TestIdentitySessionsOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout)
defer cancel()
harness := newSessionHTTPHarness(ctx, t, env)
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
verifiedEmail := "verified@example.test"
unverifiedEmail := "unverified@example.test"
verifiedUser := createSessionHTTPUser(ctx, t, harness, verifiedEmail, passwordHash, true)
createSessionHTTPUser(ctx, t, harness, unverifiedEmail, passwordHash, false)
unknown := loginSessionHTTP(t, harness, "unknown@example.test", sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.1:1234")
wrongPassword := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, "", "192.0.2.2:1234")
requireSessionProblem(t, unknown, http.StatusUnauthorized, "invalid_credentials")
requireSessionProblem(t, wrongPassword, http.StatusUnauthorized, "invalid_credentials")
if unknown.Header().Get("Content-Type") != wrongPassword.Header().Get("Content-Type") ||
!strings.Contains(unknown.Header().Get("Content-Type"), "application/problem+json") {
t.Fatalf("unknown and wrong-password response media types differ: %q and %q", unknown.Header().Get("Content-Type"), wrongPassword.Header().Get("Content-Type"))
}
if len(unknown.Header().Values("Set-Cookie")) != 0 || len(wrongPassword.Header().Values("Set-Cookie")) != 0 {
t.Fatal("a rejected login set a session cookie")
}
unverified := loginSessionHTTP(t, harness, unverifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.3:1234")
requireSessionProblem(t, unverified, http.StatusForbidden, "email_not_verified")
if len(unverified.Header().Values("Set-Cookie")) != 0 {
t.Fatal("unverified login set a session cookie")
}
badOriginBody, err := json.Marshal(struct {
Email string `json:"email"`
Password string `json:"password"`
}{Email: verifiedEmail, Password: sessionHTTPTestPass})
if err != nil {
t.Fatalf("marshal bad-origin login request: %v", err)
}
badOriginRequest := httptest.NewRequest(http.MethodPost, "/api/v1/identity/sessions", strings.NewReader(string(badOriginBody)))
badOriginRequest.Header.Set("Content-Type", "application/json")
badOriginRequest.Header.Set("Origin", "http://attacker.example")
badOriginRequest.Header.Set("X-Forwarded-Host", "localhost:8080")
badOriginRequest.RemoteAddr = "192.0.2.4:1234"
badOrigin := httptest.NewRecorder()
harness.router.ServeHTTP(badOrigin, badOriginRequest)
requireSessionProblem(t, badOrigin, http.StatusForbidden, "csrf_check_failed")
if len(badOrigin.Header().Values("Set-Cookie")) != 0 {
t.Fatal("a login with a disallowed Origin set a session cookie")
}
limitedEmail := "limit@example.test"
for attempt := 1; attempt <= 10; attempt++ {
response := loginSessionHTTP(t, harness, limitedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", fmt.Sprintf("198.51.100.%d:1234", attempt))
requireSessionProblem(t, response, http.StatusUnauthorized, "invalid_credentials")
}
limited := loginSessionHTTP(t, harness, limitedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "198.51.100.11:1234")
requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited")
if limited.Header().Get("Retry-After") == "" {
t.Fatal("email login limit response has no Retry-After")
}
malformedCookieLogin := loginSessionHTTP(t, harness, verifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "not-a-session-token", "192.0.2.5:1234")
if malformedCookieLogin.Code != http.StatusCreated {
t.Fatalf("login with a malformed incoming cookie status = %d, body=%s", malformedCookieLogin.Code, malformedCookieLogin.Body.String())
}
firstCookie := requireSessionCookie(t, malformedCookieLogin)
if malformedCookieLogin.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("login Cache-Control = %q, want no-store", malformedCookieLogin.Header().Get("Cache-Control"))
}
var firstBody struct {
Account struct {
ID string `json:"id"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
} `json:"account"`
CSRFToken string `json:"csrf_token"`
}
if err := json.Unmarshal(malformedCookieLogin.Body.Bytes(), &firstBody); err != nil {
t.Fatalf("decode login response: %v", err)
}
if firstBody.Account.ID != verifiedUser.ID.String() || firstBody.Account.Email != verifiedEmail || !firstBody.Account.EmailVerified || firstBody.CSRFToken == "" {
t.Fatalf("login account or CSRF token = %+v", firstBody)
}
currentSession := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.6:1234")
if currentSession.Code != http.StatusOK || currentSession.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("current session response = %d %s, Cache-Control=%q", currentSession.Code, currentSession.Body.String(), currentSession.Header().Get("Cache-Control"))
}
var sessionBody struct {
Account struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
} `json:"account"`
CSRFToken string `json:"csrf_token"`
}
if err := json.Unmarshal(currentSession.Body.Bytes(), &sessionBody); err != nil {
t.Fatalf("decode current session response: %v", err)
}
if sessionBody.Account.Email != verifiedEmail || !sessionBody.Account.EmailVerified || sessionBody.CSRFToken != firstBody.CSRFToken {
t.Fatalf("current session response = %+v, want the authenticated account and CSRF token", sessionBody)
}
currentAccount := harness.request(t, http.MethodGet, "/api/v1/identity/me", "", "", firstCookie.Value, "", "192.0.2.7:1234")
if currentAccount.Code != http.StatusOK || currentAccount.Header().Get("Cache-Control") != "no-store" || !strings.Contains(currentAccount.Body.String(), verifiedEmail) {
t.Fatalf("current account response = %d %s, Cache-Control=%q", currentAccount.Code, currentAccount.Body.String(), currentAccount.Header().Get("Cache-Control"))
}
unsupported := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", firstCookie.Value, "", "192.0.2.8:1234")
requireSessionProblem(t, unsupported, http.StatusUnauthorized, "unauthenticated")
wrongPasswordWithSession := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.9:1234")
requireSessionProblem(t, wrongPasswordWithSession, http.StatusUnauthorized, "invalid_credentials")
stillActive := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.10:1234")
if stillActive.Code != http.StatusOK {
t.Fatalf("failed login revoked its incoming session: status=%d body=%s", stillActive.Code, stillActive.Body.String())
}
rotated := loginSessionHTTP(t, harness, verifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.11:1234")
if rotated.Code != http.StatusCreated {
t.Fatalf("rotating login status = %d, body=%s", rotated.Code, rotated.Body.String())
}
secondCookie := requireSessionCookie(t, rotated)
if secondCookie.Value == firstCookie.Value {
t.Fatal("rotating login reused the session token")
}
var secondBody struct {
CSRFToken string `json:"csrf_token"`
}
if err := json.Unmarshal(rotated.Body.Bytes(), &secondBody); err != nil {
t.Fatalf("decode rotated login response: %v", err)
}
if secondBody.CSRFToken == "" || secondBody.CSRFToken == firstBody.CSRFToken {
t.Fatal("rotated login did not issue a new session-bound CSRF token")
}
replayed := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.12:1234")
requireSessionProblem(t, replayed, http.StatusUnauthorized, "unauthenticated")
for _, test := range []struct {
name string
origin string
csrf string
}{
{name: "wrong origin", origin: "http://attacker.example", csrf: secondBody.CSRFToken},
{name: "wrong CSRF token", origin: sessionHTTPTestOrigin, csrf: firstBody.CSRFToken},
{name: "missing CSRF token", origin: sessionHTTPTestOrigin},
} {
t.Run(test.name, func(t *testing.T) {
response := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", test.origin, secondCookie.Value, test.csrf, "192.0.2.13:1234")
requireSessionProblem(t, response, http.StatusForbidden, "csrf_check_failed")
if len(response.Header().Values("Set-Cookie")) != 0 {
t.Fatalf("rejected logout cleared the session cookie: %v", response.Header().Values("Set-Cookie"))
}
active := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", secondCookie.Value, "", "192.0.2.14:1234")
if active.Code != http.StatusOK {
t.Fatalf("rejected logout revoked the session: %d %s", active.Code, active.Body.String())
}
})
}
logout := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", sessionHTTPTestOrigin, secondCookie.Value, secondBody.CSRFToken, "192.0.2.15:1234")
if logout.Code != http.StatusNoContent || logout.Body.Len() != 0 {
t.Fatalf("logout response = %d %q, want 204 with no body", logout.Code, logout.Body.String())
}
requireExpiredSessionCookie(t, logout)
replayAfterLogout := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", secondCookie.Value, "", "192.0.2.16:1234")
requireSessionProblem(t, replayAfterLogout, http.StatusUnauthorized, "unauthenticated")
staleLogout := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", sessionHTTPTestOrigin, secondCookie.Value, secondBody.CSRFToken, "192.0.2.17:1234")
requireSessionProblem(t, staleLogout, http.StatusUnauthorized, "unauthenticated")
requireExpiredSessionCookie(t, staleLogout)
for _, secret := range []string{firstCookie.Value, secondCookie.Value, sessionHTTPTestPass, "incorrect horse battery staple"} {
if secret != "" && strings.Contains(harness.logs.String(), secret) {
t.Fatalf("a session token or password reached request logs")
}
}
}
func TestSessionExpiryAcrossAPIRestart(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout)
defer cancel()
first := newSessionHTTPHarness(ctx, t, env)
passwordHash, err := first.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
absoluteEmail := "absolute@example.test"
idleEmail := "idle@example.test"
createSessionHTTPUser(ctx, t, first, absoluteEmail, passwordHash, true)
createSessionHTTPUser(ctx, t, first, idleEmail, passwordHash, true)
absoluteLogin := loginSessionHTTP(t, first, absoluteEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.20:1234")
if absoluteLogin.Code != http.StatusCreated {
t.Fatalf("absolute-expiry login status = %d, body=%s", absoluteLogin.Code, absoluteLogin.Body.String())
}
absoluteCookie := requireSessionCookie(t, absoluteLogin)
idleLogin := loginSessionHTTP(t, first, idleEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.21:1234")
if idleLogin.Code != http.StatusCreated {
t.Fatalf("idle-expiry login status = %d, body=%s", idleLogin.Code, idleLogin.Body.String())
}
idleCookie := requireSessionCookie(t, idleLogin)
second := newSessionHTTPHarness(ctx, t, env)
for _, cookie := range []*http.Cookie{absoluteCookie, idleCookie} {
response := second.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.22:1234")
if response.Code != http.StatusOK {
t.Fatalf("session did not survive an API handler restart: %d %s", response.Code, response.Body.String())
}
}
absoluteToken, err := domain.ParseSecretToken(absoluteCookie.Value)
if err != nil {
t.Fatalf("ParseSecretToken(absolute cookie) error = %v", err)
}
idleToken, err := domain.ParseSecretToken(idleCookie.Value)
if err != nil {
t.Fatalf("ParseSecretToken(idle cookie) error = %v", err)
}
now := second.clock.Now()
absoluteHash := absoluteToken.Hash()
idleHash := idleToken.Hash()
if _, err := second.pool.Exec(ctx,
`UPDATE sessions SET created_at = $1, last_seen_at = $1, expires_at = $2 WHERE token_hash = $3`,
now.Add(-2*time.Second), now.Add(-time.Second), absoluteHash[:],
); err != nil {
t.Fatalf("expire absolute session: %v", err)
}
idleCreatedAt := now.Add(-env.Config.IdentitySessionIdleTimeout - 2*time.Second)
if _, err := second.pool.Exec(ctx,
`UPDATE sessions SET created_at = $1, last_seen_at = $2 WHERE token_hash = $3`,
idleCreatedAt, now.Add(-env.Config.IdentitySessionIdleTimeout-time.Second), idleHash[:],
); err != nil {
t.Fatalf("age idle session: %v", err)
}
for _, cookie := range []*http.Cookie{absoluteCookie, idleCookie} {
response := second.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.23:1234")
requireSessionProblem(t, response, http.StatusUnauthorized, "unauthenticated")
}
}
func TestShortIdleSessionRefreshesWhileActive(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout)
defer cancel()
harness := newSessionHTTPHarnessWithSettings(ctx, t, env, identity.SessionSettings{
ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit),
EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit),
IdleTimeout: time.Minute,
AbsoluteLifetime: 2 * time.Minute,
})
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
if err != nil {
t.Fatalf("HashNewPassword() error = %v", err)
}
user := createSessionHTTPUser(ctx, t, harness, "short-idle@example.test", passwordHash, true)
login := loginSessionHTTP(t, harness, user.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.30:1234")
if login.Code != http.StatusCreated {
t.Fatalf("login status = %d, body=%s", login.Code, login.Body.String())
}
cookie := requireSessionCookie(t, login)
harness.clock.Advance(40 * time.Second)
firstActivity := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.31:1234")
if firstActivity.Code != http.StatusOK {
t.Fatalf("session expired before first activity: %d %s", firstActivity.Code, firstActivity.Body.String())
}
harness.clock.Advance(40 * time.Second)
secondActivity := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.32:1234")
if secondActivity.Code != http.StatusOK {
t.Fatalf("session was not refreshed by activity: %d %s", secondActivity.Code, secondActivity.Body.String())
}
}