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
@@ -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))
|
||||
|
||||
Reference in new issue
Block a user