feat(identity): enforce shared session and browser request security
This commit is contained in:
1 parent
7df521bd89
commit
86f562f5b6
23 files changed
+430
-121
No files matched your search
@@ -14,11 +14,11 @@ From the repository root, `make -C backend check` runs the main checks and `make
|
||||
|
||||
## Server sessions
|
||||
|
||||
The implemented operations are email-and-password login, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current`, and `DELETE /api/v1/identity/sessions/current`. Other operations that require a session remain unavailable. Only accounts with a verified email can sign in. An unknown email and an incorrect password return the same `401 invalid_credentials`; correct credentials for an unverified account return `403 email_not_verified`.
|
||||
Registration, email confirmation, login, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current`, and `DELETE /api/v1/identity/sessions/current` are implemented. The session boundary authenticates every operation protected by the OpenAPI contract; handwritten handlers can read a principal containing the user ID and verified-email state resolved from the PostgreSQL session. Unknown, expired, revoked, or unverified sessions answer `401 unauthenticated`. Other protected business operations currently answer 501 after the security boundary and request validation succeed. An unknown email and an incorrect password return the same `401 invalid_credentials`; correct credentials for an unverified account return `403 email_not_verified` at login.
|
||||
|
||||
Sessions are stored in PostgreSQL. The browser receives a `__Host-lincodex_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/`, and no `Domain`; the database stores only the token hash. The default idle timeout is 24 hours and the absolute lifetime is 168 hours. Configure them with `IDENTITY_SESSION_IDLE_TIMEOUT` and `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; the idle timeout cannot exceed the absolute lifetime.
|
||||
|
||||
Login and logout require exactly one `Origin` header whose value exactly matches the configured `APP_PUBLIC_URL`; forwarded headers are not used for this check. Logout also requires the session-bound HMAC token in `X-CSRF-Token`. All API instances must use the same `IDENTITY_KEY_SECRET` for this check. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour.
|
||||
Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires exactly one `Origin` header matching `APP_PUBLIC_URL`. Unsafe session operations also require the session-bound HMAC token in `X-CSRF-Token`; all API instances must use the same `IDENTITY_KEY_SECRET`. Origin checks do not trust `Host` or forwarded headers. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour.
|
||||
|
||||
HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int`; compile the integration suite without starting containers with `make -C backend test-int-compile`.
|
||||
|
||||
|
||||
+2
-2
@@ -14,11 +14,11 @@
|
||||
|
||||
## Серверные сессии
|
||||
|
||||
Реализованы вход по email и паролю, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current` и `DELETE /api/v1/identity/sessions/current`. Остальные операции, требующие сессию, пока остаются закрытыми. Войти может только пользователь с подтвержденным email. Неизвестный email и неверный пароль возвращают одинаковый `401 invalid_credentials`; для правильного пароля неподтвержденной учетной записи возвращается `403 email_not_verified`.
|
||||
Реализованы регистрация, подтверждение email, вход, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current` и `DELETE /api/v1/identity/sessions/current`. Session boundary аутентифицирует каждую операцию, для которой OpenAPI требует сессию; principal для handwritten handlers содержит ID и подтвержденный email из PostgreSQL-сессии. Неизвестная, истекшая, отозванная сессия и аккаунт без подтвержденного email получают `401 unauthenticated`. Остальные защищенные бизнес-операции пока отвечают 501 после успешной проверки security и запроса. Неизвестный email и неверный пароль возвращают одинаковый `401 invalid_credentials`; правильный пароль неподтвержденной учетной записи при входе дает `403 email_not_verified`.
|
||||
|
||||
Сессия хранится в PostgreSQL. Браузер получает cookie `__Host-lincodex_session` с атрибутами `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/` и без `Domain`; в базе хранится только хеш токена. Время бездействия по умолчанию - 24 часа, абсолютный срок - 168 часов. Эти значения задаются через `IDENTITY_SESSION_IDLE_TIMEOUT` и `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; время бездействия не может превышать абсолютный срок.
|
||||
|
||||
Вход и выход требуют единственного заголовка `Origin`, в точности совпадающего с настроенным `APP_PUBLIC_URL`; адреса из forwarded-заголовков для этого не используются. Выход дополнительно требует `X-CSRF-Token`, HMAC-токен для текущей сессии. Для него все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверки с неверным Origin или CSRF отвечают `403` и сохраняют действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час.
|
||||
Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`) требует ровно один заголовок `Origin`, в точности совпадающий с `APP_PUBLIC_URL`. Небезопасные операции сессии также требуют `X-CSRF-Token`, HMAC-токен, связанный с текущей сессией; все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверка Origin не доверяет `Host` или forwarded-заголовкам. Неверный Origin или CSRF отвечает `403` и сохраняет действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час.
|
||||
|
||||
Проверки HTTP-сценариев с PostgreSQL и Redis входят в `make -C backend test-int`; компиляция integration suite без запуска контейнеров выполняется через `make -C backend test-int-compile`.
|
||||
|
||||
|
||||
@@ -493,6 +493,9 @@ func (harness *registrationHarness) confirm(t *testing.T, token, password string
|
||||
if err != nil {
|
||||
t.Fatalf("encode confirmation request: %v", err)
|
||||
}
|
||||
if origin == nil {
|
||||
return harness.postWithoutDefaultOrigin(t, emailVerificationPath, string(body), headers)
|
||||
}
|
||||
return harness.post(t, emailVerificationPath, string(body), headers)
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ type registrationHarness struct {
|
||||
clock *testClock
|
||||
logs *syncBuffer
|
||||
identity *postgresadapter.IdentityStore
|
||||
origin string
|
||||
// registration is the usecase behind the router.
|
||||
registration *identity.Registration
|
||||
// nextKey makes every request carry a new Idempotency-Key.
|
||||
@@ -170,7 +171,9 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler(
|
||||
registration, v1.WithEmailConfirmation(confirmation, env.Config.AppPublicURL),
|
||||
registration,
|
||||
v1.WithEmailConfirmation(confirmation),
|
||||
v1.WithPublicOrigin(env.Config.AppPublicURL),
|
||||
)))
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, metrics, logger, nil)
|
||||
if err != nil {
|
||||
@@ -196,6 +199,7 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
|
||||
}
|
||||
return ®istrationHarness{
|
||||
start: start, pool: pool, router: router, sender: sender, fixture: fixture, clock: clock, logs: logs, identity: identityStore,
|
||||
origin: env.Config.AppPublicURL,
|
||||
registration: registration,
|
||||
}
|
||||
}
|
||||
@@ -210,9 +214,20 @@ type registrationResponse struct {
|
||||
}
|
||||
|
||||
func (harness *registrationHarness) post(t *testing.T, path, body string, headers map[string]string) registrationResponse {
|
||||
return harness.postWithOriginDefault(t, path, body, headers, true)
|
||||
}
|
||||
|
||||
func (harness *registrationHarness) postWithoutDefaultOrigin(t *testing.T, path, body string, headers map[string]string) registrationResponse {
|
||||
return harness.postWithOriginDefault(t, path, body, headers, false)
|
||||
}
|
||||
|
||||
func (harness *registrationHarness) postWithOriginDefault(t *testing.T, path, body string, headers map[string]string, setDefaultOrigin bool) registrationResponse {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if setDefaultOrigin {
|
||||
request.Header.Set("Origin", harness.origin)
|
||||
}
|
||||
for name, value := range headers {
|
||||
request.Header.Set(name, value)
|
||||
}
|
||||
@@ -678,6 +693,72 @@ func TestRegistrationOverHTTP(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestPublicIdentityOriginRefusalDoesNotMutateAccountsOrMailState(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout)
|
||||
defer cancel()
|
||||
harness := newRegistrationHarness(ctx, t, env, 1000)
|
||||
harness.truncate(ctx, t)
|
||||
harness.clock.Set(harness.start)
|
||||
|
||||
const verifiedFlowEmail = "origin-check@example.test"
|
||||
token := harness.registerAndSendVerification(ctx, t, verifiedFlowEmail, "candidate", registrationPassword)
|
||||
stateCounts := func() map[string]int {
|
||||
t.Helper()
|
||||
counts := make(map[string]int)
|
||||
for _, table := range []string{"users", "consent_records", "email_tokens", "idempotency_records", "outbox_events", "deliveries"} {
|
||||
counts[table] = harness.count(ctx, t, "SELECT count(*) FROM "+table)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
assertCountsUnchanged := func(want map[string]int) {
|
||||
t.Helper()
|
||||
for table, expected := range want {
|
||||
if got := harness.count(ctx, t, "SELECT count(*) FROM "+table); got != expected {
|
||||
t.Errorf("%s count = %d after Origin refusal, want unchanged at %d", table, got, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
before := stateCounts()
|
||||
register := harness.post(t, registrationPath,
|
||||
registrationBody("rejected@example.test", "candidate", registrationPassword, registrationC1),
|
||||
map[string]string{"Idempotency-Key": "origin-refused-registration", "Origin": "https://attacker.example"},
|
||||
)
|
||||
requireProblemStatus(t, register, http.StatusForbidden, "csrf_check_failed")
|
||||
assertCountsUnchanged(before)
|
||||
|
||||
resend := harness.post(t, resendPath, `{"email":"`+verifiedFlowEmail+`"}`, map[string]string{"Origin": "https://attacker.example"})
|
||||
requireProblemStatus(t, resend, http.StatusForbidden, "csrf_check_failed")
|
||||
assertCountsUnchanged(before)
|
||||
|
||||
confirmation := harness.post(t, emailVerificationPath,
|
||||
`{"token":"`+token+`","password":"`+registrationPassword+`"}`,
|
||||
map[string]string{"Origin": "https://attacker.example"},
|
||||
)
|
||||
requireProblemStatus(t, confirmation, http.StatusForbidden, "csrf_check_failed")
|
||||
assertCountsUnchanged(before)
|
||||
|
||||
var verifiedAt *time.Time
|
||||
var registrationVersion int64
|
||||
if err := harness.pool.QueryRow(ctx,
|
||||
`SELECT email_verified_at, registration_version FROM users WHERE email_normalized = $1`, verifiedFlowEmail,
|
||||
).Scan(&verifiedAt, ®istrationVersion); err != nil {
|
||||
t.Fatalf("read account after Origin refusals: %v", err)
|
||||
}
|
||||
if verifiedAt != nil || registrationVersion != 1 {
|
||||
t.Fatalf("account state after refused operations: verified=%v registration version=%d", verifiedAt, registrationVersion)
|
||||
}
|
||||
var consumedAt, invalidatedAt *time.Time
|
||||
if err := harness.pool.QueryRow(ctx,
|
||||
`SELECT consumed_at, invalidated_at FROM email_tokens WHERE user_id = (SELECT id FROM users WHERE email_normalized = $1)`, verifiedFlowEmail,
|
||||
).Scan(&consumedAt, &invalidatedAt); err != nil {
|
||||
t.Fatalf("read verification token state after Origin refusals: %v", err)
|
||||
}
|
||||
if consumedAt != nil || invalidatedAt != nil {
|
||||
t.Fatalf("verification token changed after Origin refusals: consumed=%v invalidated=%v", consumedAt, invalidatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationClientLimit(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout)
|
||||
|
||||
@@ -86,12 +86,15 @@ func newSessionHTTPHarnessWithSettings(
|
||||
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))
|
||||
identityHandler := v1.NewIdentityHandler(nil,
|
||||
v1.WithSessionService(service),
|
||||
v1.WithPublicOrigin(env.Config.AppPublicURL),
|
||||
)
|
||||
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler))
|
||||
router, err := httpadapter.NewRouter(
|
||||
healthHandler,
|
||||
handler,
|
||||
v1.NewSessionSecurity(service, env.Config.AppPublicURL),
|
||||
identityHandler.SessionSecurity(),
|
||||
responder,
|
||||
prometheus.New(),
|
||||
logger,
|
||||
@@ -323,12 +326,55 @@ func TestIdentitySessionsOverHTTP(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
var userVersionBefore int64
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1`, verifiedUser.ID).Scan(&userVersionBefore); err != nil {
|
||||
t.Fatalf("read current account version before protected reads: %v", err)
|
||||
}
|
||||
var outboxBefore, idempotencyBefore int64
|
||||
if err := harness.pool.QueryRow(ctx,
|
||||
`SELECT (SELECT count(*) FROM outbox_events), (SELECT count(*) FROM idempotency_records)`,
|
||||
).Scan(&outboxBefore, &idempotencyBefore); err != nil {
|
||||
t.Fatalf("read business side-effect counts before protected reads: %v", err)
|
||||
}
|
||||
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")
|
||||
var accountBody struct {
|
||||
ID string `json:"id"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
}
|
||||
if err := json.Unmarshal(currentAccount.Body.Bytes(), &accountBody); err != nil {
|
||||
t.Fatalf("decode current account response: %v", err)
|
||||
}
|
||||
if accountBody.ID != verifiedUser.ID.String() || !accountBody.EmailVerified {
|
||||
t.Fatalf("current account = %+v, want verified account resolved from PostgreSQL session", accountBody)
|
||||
}
|
||||
guestProfile := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", "", "", "192.0.2.8:1234")
|
||||
requireSessionProblem(t, guestProfile, http.StatusUnauthorized, "unauthenticated")
|
||||
guestWrite := harness.request(t, http.MethodPut, "/api/v1/me/privacy/search-status", `{"expected_version":0,"value":"looking"}`, "", "", "", "192.0.2.9:1234")
|
||||
requireSessionProblem(t, guestWrite, http.StatusUnauthorized, "unauthenticated")
|
||||
unsupported := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", firstCookie.Value, "", "192.0.2.18:1234")
|
||||
requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented")
|
||||
unsupportedWrite := harness.request(
|
||||
t, http.MethodPut, "/api/v1/me/privacy/search-status", `{"expected_version":0,"value":"looking"}`,
|
||||
sessionHTTPTestOrigin, firstCookie.Value, firstBody.CSRFToken, "192.0.2.19:1234",
|
||||
)
|
||||
requireSessionProblem(t, unsupportedWrite, http.StatusNotImplemented, "not_implemented")
|
||||
var userVersionAfter int64
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1`, verifiedUser.ID).Scan(&userVersionAfter); err != nil {
|
||||
t.Fatalf("read current account version after protected reads: %v", err)
|
||||
}
|
||||
var outboxAfter, idempotencyAfter int64
|
||||
if err := harness.pool.QueryRow(ctx,
|
||||
`SELECT (SELECT count(*) FROM outbox_events), (SELECT count(*) FROM idempotency_records)`,
|
||||
).Scan(&outboxAfter, &idempotencyAfter); err != nil {
|
||||
t.Fatalf("read business side-effect counts after protected reads: %v", err)
|
||||
}
|
||||
if userVersionAfter != userVersionBefore || outboxAfter != outboxBefore || idempotencyAfter != idempotencyBefore {
|
||||
t.Fatalf("protected reads changed account or business side effects: user version %d -> %d, outbox %d -> %d, idempotency %d -> %d",
|
||||
userVersionBefore, userVersionAfter, outboxBefore, outboxAfter, idempotencyBefore, idempotencyAfter)
|
||||
}
|
||||
|
||||
wrongPasswordWithSession := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.9:1234")
|
||||
requireSessionProblem(t, wrongPasswordWithSession, http.StatusUnauthorized, "invalid_credentials")
|
||||
|
||||
@@ -36,7 +36,10 @@ func newConfirmationRouter(t *testing.T, confirmation v1.EmailConfirmation) http
|
||||
t.Helper()
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
identityHandler := v1.NewIdentityHandler(nil, v1.WithEmailConfirmation(confirmation, "https://app.example"))
|
||||
identityHandler := v1.NewIdentityHandler(nil,
|
||||
v1.WithEmailConfirmation(confirmation),
|
||||
v1.WithPublicOrigin("https://app.example"),
|
||||
)
|
||||
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(identityHandler))
|
||||
return newTestRouterWithAPI(t, healthHandler, handler, logger)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -22,32 +24,41 @@ type scriptedRegistration struct {
|
||||
err error
|
||||
register identity.RegisterCommand
|
||||
resend identity.ResendCommand
|
||||
calls int
|
||||
}
|
||||
|
||||
func (registration *scriptedRegistration) Register(_ context.Context, command identity.RegisterCommand) error {
|
||||
registration.calls++
|
||||
registration.register = command
|
||||
return registration.err
|
||||
}
|
||||
|
||||
func (registration *scriptedRegistration) ResendVerification(_ context.Context, command identity.ResendCommand) error {
|
||||
registration.calls++
|
||||
registration.resend = command
|
||||
return registration.err
|
||||
}
|
||||
|
||||
const identityTestOrigin = "https://app.example"
|
||||
|
||||
func newIdentityRouter(t *testing.T, registration v1.AccountRegistration) http.Handler {
|
||||
t.Helper()
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(v1.NewIdentityHandler(registration)))
|
||||
identityHandler := v1.NewIdentityHandler(registration, v1.WithPublicOrigin(identityTestOrigin))
|
||||
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(identityHandler))
|
||||
return newTestRouterWithAPI(t, healthHandler, handler, logger)
|
||||
}
|
||||
|
||||
func TestRegistrationOperationsMapUsecaseOutcomes(t *testing.T) {
|
||||
registerRequest := identityRequest{
|
||||
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
|
||||
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
|
||||
headers: map[string]string{"Idempotency-Key": testIdempotencyKey, "Origin": identityTestOrigin},
|
||||
}
|
||||
resendRequest := identityRequest{
|
||||
method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`,
|
||||
headers: map[string]string{"Origin": identityTestOrigin},
|
||||
}
|
||||
resendRequest := identityRequest{method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`}
|
||||
staleConsent := &identity.InvalidFieldError{Pointer: "/consent_c1/text_version", Err: errors.New("stale")}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
@@ -105,7 +116,7 @@ func TestRegistrationPassesTheRequestToTheUsecase(t *testing.T) {
|
||||
router := newIdentityRouter(t, registration)
|
||||
response := serveIdentityRequest(t, router, identityRequest{
|
||||
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
|
||||
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
|
||||
headers: map[string]string{"Idempotency-Key": testIdempotencyKey, "Origin": identityTestOrigin},
|
||||
})
|
||||
if response.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d: %s", response.Code, response.Body.String())
|
||||
@@ -118,3 +129,78 @@ func TestRegistrationPassesTheRequestToTheUsecase(t *testing.T) {
|
||||
t.Fatalf("command = %+v, want %+v", registration.register, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationAndResendRejectOriginBeforeUsecase(t *testing.T) {
|
||||
for _, operation := range []struct {
|
||||
name string
|
||||
request identityRequest
|
||||
}{
|
||||
{
|
||||
name: "register",
|
||||
request: identityRequest{
|
||||
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
|
||||
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "resend",
|
||||
request: identityRequest{method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`},
|
||||
},
|
||||
} {
|
||||
for _, originCase := range []struct {
|
||||
name string
|
||||
origins []string
|
||||
headers map[string]string
|
||||
}{
|
||||
{name: "missing"},
|
||||
{name: "null origin", origins: []string{"null"}},
|
||||
{name: "foreign origin", origins: []string{"https://attacker.example"}},
|
||||
{name: "duplicate origin", origins: []string{identityTestOrigin, "https://attacker.example"}},
|
||||
{name: "forwarded host only", headers: map[string]string{"X-Forwarded-Host": "app.example"}},
|
||||
} {
|
||||
t.Run(operation.name+"/"+originCase.name, func(t *testing.T) {
|
||||
registration := &scriptedRegistration{}
|
||||
request := operation.request
|
||||
request.headers = cloneHeaders(request.headers)
|
||||
for name, value := range originCase.headers {
|
||||
request.headers[name] = value
|
||||
}
|
||||
response := serveIdentityRequestWithOrigins(t, newIdentityRouter(t, registration), request, originCase.origins)
|
||||
requireProblem(t, response, http.StatusForbidden, api.ProblemCodeCsrfCheckFailed)
|
||||
if registration.calls != 0 {
|
||||
t.Fatalf("identity usecase calls = %d, want zero before origin check", registration.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func serveIdentityRequestWithOrigins(
|
||||
t *testing.T,
|
||||
router http.Handler,
|
||||
identityRequest identityRequest,
|
||||
origins []string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(identityRequest.method, identityRequest.path, strings.NewReader(identityRequest.body))
|
||||
if identityRequest.body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for name, value := range identityRequest.headers {
|
||||
request.Header.Set(name, value)
|
||||
}
|
||||
for _, origin := range origins {
|
||||
request.Header.Add("Origin", origin)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
return response
|
||||
}
|
||||
|
||||
func cloneHeaders(headers map[string]string) map[string]string {
|
||||
cloned := make(map[string]string, len(headers))
|
||||
for name, value := range headers {
|
||||
cloned[name] = value
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
@@ -61,8 +61,9 @@ func NewRouter(
|
||||
// The client address is resolved once, through the trusted proxies only,
|
||||
// for the per-client rate limits of the handlers.
|
||||
router.Use(httpmiddleware.ClientIP(trustedProxies))
|
||||
// Login and logout compare one Origin header value exactly with the
|
||||
// configured public origin. Session metadata never trusts forwarded headers.
|
||||
// Unsafe public identity operations and session CSRF checks compare one
|
||||
// Origin header value exactly with the configured public origin. Session
|
||||
// metadata never trusts forwarded headers.
|
||||
router.Use(httpmiddleware.SessionRequestMetadata())
|
||||
router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath))
|
||||
router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute))
|
||||
|
||||
@@ -18,6 +18,39 @@ const (
|
||||
sessionCSRFScheme = "sessionCsrf"
|
||||
)
|
||||
|
||||
func TestProtectedContractOperationsRequireSessionCookie(t *testing.T) {
|
||||
data, err := os.ReadFile(publicContractBundle)
|
||||
if err != nil {
|
||||
t.Fatalf("read the public contract bundle: %v", err)
|
||||
}
|
||||
spec, err := ogen.Parse(data)
|
||||
if err != nil {
|
||||
t.Fatalf("parse the public contract bundle: %v", err)
|
||||
}
|
||||
|
||||
checked := 0
|
||||
for path, item := range spec.Paths {
|
||||
for method, operation := range contractOperations(item) {
|
||||
requirements := operation.Security
|
||||
if requirements == nil {
|
||||
requirements = spec.Security
|
||||
}
|
||||
if len(requirements) == 0 {
|
||||
continue
|
||||
}
|
||||
checked++
|
||||
for _, requirement := range requirements {
|
||||
if _, usesSession := requirement[sessionCookieScheme]; !usesSession {
|
||||
t.Errorf("%s %s (%s) is protected without %s", method, path, operation.OperationID, sessionCookieScheme)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if checked == 0 {
|
||||
t.Fatal("found no protected operation; the check would pass vacuously")
|
||||
}
|
||||
}
|
||||
|
||||
// A browser sends the session cookie with every same-site request, so an
|
||||
// unsafe operation that accepts the session must also demand the
|
||||
// session-bound CSRF token. A new operation that forgets sessionCsrf would
|
||||
@@ -78,3 +111,25 @@ func unsafeOperations(item *ogen.PathItem) map[string]*ogen.Operation {
|
||||
}
|
||||
return operations
|
||||
}
|
||||
|
||||
func contractOperations(item *ogen.PathItem) map[string]*ogen.Operation {
|
||||
operations := map[string]*ogen.Operation{
|
||||
http.MethodGet: item.Get,
|
||||
http.MethodHead: item.Head,
|
||||
http.MethodPost: item.Post,
|
||||
http.MethodPut: item.Put,
|
||||
http.MethodPatch: item.Patch,
|
||||
http.MethodDelete: item.Delete,
|
||||
http.MethodOptions: item.Options,
|
||||
http.MethodTrace: item.Trace,
|
||||
}
|
||||
for method, operation := range item.AdditionalOperations {
|
||||
operations[method] = operation
|
||||
}
|
||||
for method, operation := range operations {
|
||||
if operation == nil {
|
||||
delete(operations, method)
|
||||
}
|
||||
}
|
||||
return operations
|
||||
}
|
||||
File renamed without changes.
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
@@ -73,6 +72,9 @@ func (handler *IdentityHandler) RegisterAccount(
|
||||
request *api.RegistrationRequest,
|
||||
params api.RegisterAccountParams,
|
||||
) (api.RegisterAccountRes, error) {
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.RegisterAccountForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
err := handler.registration.Register(ctx, identity.RegisterCommand{
|
||||
IdempotencyKey: params.IdempotencyKey,
|
||||
Email: string(request.Email),
|
||||
@@ -99,6 +101,9 @@ func (handler *IdentityHandler) ResendEmailVerification(
|
||||
ctx context.Context,
|
||||
request *api.EmailVerificationResendRequest,
|
||||
) (api.ResendEmailVerificationRes, error) {
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.ResendEmailVerificationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
if handler.registration == nil {
|
||||
return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured")
|
||||
}
|
||||
@@ -121,13 +126,12 @@ func (handler *IdentityHandler) ResendEmailVerification(
|
||||
func (handler *IdentityHandler) ConfirmEmail(
|
||||
ctx context.Context,
|
||||
request *api.EmailVerificationRequest,
|
||||
params api.ConfirmEmailParams,
|
||||
_ api.ConfirmEmailParams,
|
||||
) (api.ConfirmEmailRes, error) {
|
||||
if handler.confirmation == nil {
|
||||
return nil, errors.New("IdentityHandler.ConfirmEmail - confirmation is not configured")
|
||||
}
|
||||
origin, ok := params.Origin.Get()
|
||||
if !ok || strings.TrimSpace(origin) == "" || origin != handler.confirmationOrigin {
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
|
||||
@@ -155,7 +159,7 @@ func (handler *IdentityHandler) ConfirmEmail(
|
||||
}
|
||||
|
||||
func (handler *IdentityHandler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) {
|
||||
if !originAllowed(ctx, handler.sessionOrigin) {
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
result, err := handler.sessions.Login(ctx, identity.LoginCommand{
|
||||
@@ -254,8 +258,11 @@ func wholeSeconds(wait time.Duration) int32 {
|
||||
}
|
||||
|
||||
func originAllowed(ctx context.Context, expected string) bool {
|
||||
if expected == "" {
|
||||
return false
|
||||
}
|
||||
origin, ok := httpmiddleware.RequestOrigin(ctx)
|
||||
return ok && origin == expected
|
||||
return ok && origin != "" && origin == expected
|
||||
}
|
||||
|
||||
func unauthenticatedProblemResponse(ctx context.Context) *api.Problem {
|
||||
|
||||
@@ -23,11 +23,10 @@ type IdentityHandlerOption func(*IdentityHandler)
|
||||
|
||||
// IdentityHandler serves authentication and account identity operations.
|
||||
type IdentityHandler struct {
|
||||
registration AccountRegistration
|
||||
confirmation EmailConfirmation
|
||||
confirmationOrigin string
|
||||
sessions *identity.SessionService
|
||||
sessionOrigin string
|
||||
registration AccountRegistration
|
||||
confirmation EmailConfirmation
|
||||
sessions *identity.SessionService
|
||||
publicOrigin string
|
||||
}
|
||||
|
||||
func NewIdentityHandler(registration AccountRegistration, options ...IdentityHandlerOption) *IdentityHandler {
|
||||
@@ -38,21 +37,26 @@ func NewIdentityHandler(registration AccountRegistration, options ...IdentityHan
|
||||
return handler
|
||||
}
|
||||
|
||||
// WithEmailConfirmation serves ConfirmEmail and compares Origin with the
|
||||
// configured public application origin. The request Host is never trusted.
|
||||
func WithEmailConfirmation(confirmation EmailConfirmation, publicOrigin string) IdentityHandlerOption {
|
||||
// WithEmailConfirmation serves ConfirmEmail. The configured public origin is
|
||||
// supplied once with WithPublicOrigin; the request Host is never trusted.
|
||||
func WithEmailConfirmation(confirmation EmailConfirmation) IdentityHandlerOption {
|
||||
return func(handler *IdentityHandler) {
|
||||
handler.confirmation = confirmation
|
||||
handler.confirmationOrigin = publicOrigin
|
||||
}
|
||||
}
|
||||
|
||||
// WithSessionService serves login, current account, current session, and
|
||||
// logout against PostgreSQL-backed sessions. Unsafe browser operations compare
|
||||
// Origin exactly with the configured public origin.
|
||||
func WithSessionService(sessions *identity.SessionService, publicOrigin string) IdentityHandlerOption {
|
||||
// logout against PostgreSQL-backed sessions.
|
||||
func WithSessionService(sessions *identity.SessionService) IdentityHandlerOption {
|
||||
return func(handler *IdentityHandler) {
|
||||
handler.sessions = sessions
|
||||
handler.sessionOrigin = publicOrigin
|
||||
}
|
||||
}
|
||||
|
||||
// WithPublicOrigin configures the exact browser Origin accepted by unsafe
|
||||
// public identity operations and session CSRF checks.
|
||||
func WithPublicOrigin(publicOrigin string) IdentityHandlerOption {
|
||||
return func(handler *IdentityHandler) {
|
||||
handler.publicOrigin = publicOrigin
|
||||
}
|
||||
}
|
||||
@@ -36,18 +36,23 @@ func PrincipalFromContext(ctx context.Context) (Principal, bool) {
|
||||
return Principal{}, false
|
||||
}
|
||||
principal, ok := ctx.Value(principalContextKey{}).(Principal)
|
||||
return principal, ok && principal.UserID != uuid.Nil
|
||||
return principal, ok && principal.UserID != uuid.Nil && principal.EmailVerified
|
||||
}
|
||||
|
||||
func withAuthenticatedSession(ctx context.Context, session identity.AuthenticatedSession) context.Context {
|
||||
func withAuthenticatedSession(ctx context.Context, session identity.AuthenticatedSession) (context.Context, bool) {
|
||||
if ctx == nil || session.User.ID == uuid.Nil || session.SessionID == uuid.Nil ||
|
||||
!session.User.EmailVerified() || session.CSRFToken == "" {
|
||||
return ctx, false
|
||||
}
|
||||
principal := Principal{UserID: session.User.ID, EmailVerified: session.User.EmailVerified()}
|
||||
ctx = context.WithValue(ctx, principalContextKey{}, principal)
|
||||
return context.WithValue(ctx, sessionContextKey{}, authenticatedSession{
|
||||
ctx = context.WithValue(ctx, sessionContextKey{}, authenticatedSession{
|
||||
Principal: principal,
|
||||
User: session.User,
|
||||
SessionID: session.SessionID,
|
||||
CSRFToken: session.CSRFToken,
|
||||
})
|
||||
return ctx, true
|
||||
}
|
||||
|
||||
func sessionFromContext(ctx context.Context) (authenticatedSession, bool) {
|
||||
@@ -55,5 +60,6 @@ func sessionFromContext(ctx context.Context) (authenticatedSession, bool) {
|
||||
return authenticatedSession{}, false
|
||||
}
|
||||
session, ok := ctx.Value(sessionContextKey{}).(authenticatedSession)
|
||||
return session, ok && session.UserID != uuid.Nil && session.SessionID != uuid.Nil
|
||||
return session, ok && session.UserID != uuid.Nil && session.SessionID != uuid.Nil &&
|
||||
session.EmailVerified && session.CSRFToken != ""
|
||||
}
|
||||
@@ -7,21 +7,15 @@ import (
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
)
|
||||
|
||||
// errSessionsNotImplemented rejects every session-protected request until the
|
||||
// session boundary exists. Its text stays in the server: the generated server
|
||||
// wraps it in *ogenerrors.SecurityError, which the problem responder answers
|
||||
// with a fixed 401 unauthenticated problem.
|
||||
// errSessionsNotImplemented is used by DenyAllSecurity, a test helper. Its text
|
||||
// stays in the server and maps to a fixed 401 unauthenticated problem.
|
||||
var errSessionsNotImplemented = errors.New("v1.DenyAllSecurity - sessions are not implemented")
|
||||
|
||||
// DenyAllSecurity implements api.SecurityHandler by rejecting every session
|
||||
// cookie and CSRF token, so no operation that requires a session is reachable
|
||||
// before server sessions exist. Operations that declare `security: []` do not
|
||||
// call it and keep their own behavior, which is 501 not_implemented until
|
||||
// their business logic exists.
|
||||
//
|
||||
// Session authentication will replace it. The generated server (ogen v1.24.0) evaluates the
|
||||
// schemes of an operation as follows; TestGeneratedServerSecurityOrder pins
|
||||
// the order and the context propagation:
|
||||
// cookie and CSRF token. Production bootstrap uses SessionSecurity instead;
|
||||
// tests use this helper when they need to verify a denied session. The
|
||||
// generated server evaluates schemes in type-name order. The contract test
|
||||
// pins the order and context propagation:
|
||||
//
|
||||
// - It evaluates sessionCookie before sessionCsrf, in the order of the
|
||||
// generated type names, and each step receives the context returned by
|
||||
@@ -41,7 +35,7 @@ var errSessionsNotImplemented = errors.New("v1.DenyAllSecurity - sessions are no
|
||||
// ogenerrors.ErrSecurityRequirementIsNotSatisfied}, without a Security
|
||||
// field, to Handler.NewError with the context of the last successful step.
|
||||
//
|
||||
// The intended mapping on top of that behavior:
|
||||
// SessionSecurity and Handler.NewError implement this mapping on top of that behavior:
|
||||
//
|
||||
// - HandleSessionCookie returns a context with the principal for a valid
|
||||
// session and ogenerrors.ErrSkipServerSecurity for a missing, unknown,
|
||||
|
||||
@@ -19,9 +19,8 @@ type SessionAuthenticator interface {
|
||||
Authenticate(ctx context.Context, rawToken string) (identity.AuthenticatedSession, error)
|
||||
}
|
||||
|
||||
// SessionSecurity authenticates only the three session operations enabled in
|
||||
// this implementation. All other protected operations remain unavailable until their
|
||||
// handlers are implemented.
|
||||
// SessionSecurity authenticates every operation protected by the public
|
||||
// contract's session schemes. Business handlers may still be unimplemented.
|
||||
type SessionSecurity struct {
|
||||
authenticator SessionAuthenticator
|
||||
publicOrigin string
|
||||
@@ -37,15 +36,15 @@ func (handler *IdentityHandler) SessionSecurity() *SessionSecurity {
|
||||
if handler == nil || handler.sessions == nil {
|
||||
return NewSessionSecurity(nil, "")
|
||||
}
|
||||
return NewSessionSecurity(handler.sessions, handler.sessionOrigin)
|
||||
return NewSessionSecurity(handler.sessions, handler.publicOrigin)
|
||||
}
|
||||
|
||||
func (security *SessionSecurity) HandleSessionCookie(
|
||||
ctx context.Context,
|
||||
operation api.OperationName,
|
||||
_ api.OperationName,
|
||||
cookie api.SessionCookie,
|
||||
) (context.Context, error) {
|
||||
if !sessionOperationAllowed(operation) || security == nil || security.authenticator == nil ||
|
||||
if security == nil || security.authenticator == nil ||
|
||||
!httpmiddleware.SessionCookieMatches(ctx, cookie.APIKey) {
|
||||
return ctx, ogenerrors.ErrSkipServerSecurity
|
||||
}
|
||||
@@ -56,34 +55,26 @@ func (security *SessionSecurity) HandleSessionCookie(
|
||||
if err != nil {
|
||||
return ctx, fmt.Errorf("SessionSecurity.HandleSessionCookie - authenticate session: %w", err)
|
||||
}
|
||||
return withAuthenticatedSession(ctx, authenticated), nil
|
||||
ctx, ok := withAuthenticatedSession(ctx, authenticated)
|
||||
if !ok {
|
||||
return ctx, ogenerrors.ErrSkipServerSecurity
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (security *SessionSecurity) HandleSessionCsrf(
|
||||
ctx context.Context,
|
||||
operation api.OperationName,
|
||||
_ api.OperationName,
|
||||
csrf api.SessionCsrf,
|
||||
) (context.Context, error) {
|
||||
if operation != api.LogoutOperation {
|
||||
return ctx, ogenerrors.ErrSkipServerSecurity
|
||||
}
|
||||
authenticated, ok := sessionFromContext(ctx)
|
||||
if !ok {
|
||||
return ctx, ogenerrors.ErrSkipServerSecurity
|
||||
}
|
||||
origin, hasOrigin := httpmiddleware.RequestOrigin(ctx)
|
||||
if security == nil || !hasOrigin || origin != security.publicOrigin || authenticated.CSRFToken == "" ||
|
||||
if security == nil || security.publicOrigin == "" || !hasOrigin || origin != security.publicOrigin ||
|
||||
!hmac.Equal([]byte(authenticated.CSRFToken), []byte(csrf.APIKey)) {
|
||||
return ctx, errCsrfCheckFailed
|
||||
}
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func sessionOperationAllowed(operation api.OperationName) bool {
|
||||
switch operation {
|
||||
case api.GetCurrentSessionOperation, api.GetCurrentAccountOperation, api.LogoutOperation:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func (authenticator *sessionAuthenticatorStub) Authenticate(_ context.Context, _
|
||||
return authenticator.result, authenticator.err
|
||||
}
|
||||
|
||||
func TestSessionSecurityAddsPrincipalOnlyForTheThreeEnabledOperations(t *testing.T) {
|
||||
func TestSessionSecurityAddsVerifiedPrincipalForEveryProtectedOperationClass(t *testing.T) {
|
||||
token, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -48,6 +48,8 @@ func TestSessionSecurityAddsPrincipalOnlyForTheThreeEnabledOperations(t *testing
|
||||
for _, operation := range []api.OperationName{
|
||||
api.GetCurrentAccountOperation,
|
||||
api.GetCurrentSessionOperation,
|
||||
api.GetMyProfileOperation,
|
||||
api.CreateOrganizationOperation,
|
||||
api.LogoutOperation,
|
||||
} {
|
||||
ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com")
|
||||
@@ -60,18 +62,12 @@ func TestSessionSecurityAddsPrincipalOnlyForTheThreeEnabledOperations(t *testing
|
||||
t.Fatalf("PrincipalFromContext(%s) = %+v, %v", operation, principal, ok)
|
||||
}
|
||||
}
|
||||
if authenticator.calls != 3 {
|
||||
t.Fatalf("authentication calls = %d, want one for each allowed operation", authenticator.calls)
|
||||
}
|
||||
|
||||
ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com")
|
||||
_, err = security.HandleSessionCookie(ctx, api.GetMyProfileOperation, api.SessionCookie{APIKey: token.Reveal()})
|
||||
if !errors.Is(err, ogenerrors.ErrSkipServerSecurity) || authenticator.calls != 3 {
|
||||
t.Fatalf("disallowed operation error=%v authentication calls=%d", err, authenticator.calls)
|
||||
if authenticator.calls != 5 {
|
||||
t.Fatalf("authentication calls = %d, want one for each protected operation class", authenticator.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutRequiresExactOriginAndSessionBoundCSRF(t *testing.T) {
|
||||
func TestSessionCsrfRequiresExactOriginForAnyContractOperation(t *testing.T) {
|
||||
token, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -97,11 +93,11 @@ func TestLogoutRequiresExactOriginAndSessionBoundCSRF(t *testing.T) {
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := sessionRequestContext(t, token.Reveal(), test.origin)
|
||||
ctx, err := security.HandleSessionCookie(ctx, api.LogoutOperation, api.SessionCookie{APIKey: token.Reveal()})
|
||||
ctx, err := security.HandleSessionCookie(ctx, api.CreateOrganizationOperation, api.SessionCookie{APIKey: token.Reveal()})
|
||||
if err != nil {
|
||||
t.Fatalf("HandleSessionCookie() error = %v", err)
|
||||
}
|
||||
_, err = security.HandleSessionCsrf(ctx, api.LogoutOperation, api.SessionCsrf{APIKey: test.csrf})
|
||||
_, err = security.HandleSessionCsrf(ctx, api.CreateOrganizationOperation, api.SessionCsrf{APIKey: test.csrf})
|
||||
if !errors.Is(err, test.wantErr) {
|
||||
t.Fatalf("HandleSessionCsrf() error = %v, want %v", err, test.wantErr)
|
||||
}
|
||||
@@ -109,6 +105,41 @@ func TestLogoutRequiresExactOriginAndSessionBoundCSRF(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionSecurityRejectsInvalidAuthenticatedSession(t *testing.T) {
|
||||
token, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verifiedAt := time.Now()
|
||||
valid := identity.AuthenticatedSession{
|
||||
User: domain.User{ID: uuid.New(), EmailVerifiedAt: &verifiedAt},
|
||||
SessionID: uuid.New(),
|
||||
CSRFToken: "csrf-for-this-session",
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
result identity.AuthenticatedSession
|
||||
}{
|
||||
{name: "unverified account", result: identity.AuthenticatedSession{User: domain.User{ID: valid.User.ID}, SessionID: valid.SessionID, CSRFToken: valid.CSRFToken}},
|
||||
{name: "missing user ID", result: identity.AuthenticatedSession{User: domain.User{EmailVerifiedAt: &verifiedAt}, SessionID: valid.SessionID, CSRFToken: valid.CSRFToken}},
|
||||
{name: "missing session ID", result: identity.AuthenticatedSession{User: valid.User, CSRFToken: valid.CSRFToken}},
|
||||
{name: "missing CSRF token", result: identity.AuthenticatedSession{User: valid.User, SessionID: valid.SessionID}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
authenticator := &sessionAuthenticatorStub{result: test.result}
|
||||
security := NewSessionSecurity(authenticator, "https://app.example.com")
|
||||
ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com")
|
||||
authenticated, err := security.HandleSessionCookie(ctx, api.GetMyProfileOperation, api.SessionCookie{APIKey: token.Reveal()})
|
||||
if !errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
|
||||
t.Fatalf("HandleSessionCookie() error = %v, want skipped authentication", err)
|
||||
}
|
||||
if _, ok := PrincipalFromContext(authenticated); ok {
|
||||
t.Fatal("invalid authenticated session installed a principal")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityErrorsMapToUnauthenticatedOrCSRFProblem(t *testing.T) {
|
||||
logger := slog.New(slog.NewTextHandler(&strings.Builder{}, nil))
|
||||
handler := NewHandler(nil, problem.NewResponder(logger))
|
||||
|
||||
@@ -133,8 +133,9 @@ func newIdentityHandler(
|
||||
// The HTTP server stops before this cleanup runs, so no request uses the
|
||||
// pool while it closes.
|
||||
return v1.NewIdentityHandler(registration,
|
||||
v1.WithEmailConfirmation(confirmation, settings.AppPublicURL),
|
||||
v1.WithSessionService(sessions, settings.AppPublicURL),
|
||||
v1.WithEmailConfirmation(confirmation),
|
||||
v1.WithSessionService(sessions),
|
||||
v1.WithPublicOrigin(settings.AppPublicURL),
|
||||
), pool.Close, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user