feat(identity): enforce shared session and browser request security

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:33:40 +03:00
1 parent 7df521bd89
commit 86f562f5b6
23 files changed
+430 -121

No files matched your search

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