package v1 import ( "context" "crypto/hmac" "errors" "fmt" "github.com/ogen-go/ogen/ogenerrors" "lincodex/backend/internal/adapter/primary/http/api" httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" "lincodex/backend/internal/usecase/identity" ) var errCsrfCheckFailed = errors.New("CSRF check failed") type SessionAuthenticator interface { Authenticate(ctx context.Context, rawToken string) (identity.AuthenticatedSession, error) } // 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 } var _ api.SecurityHandler = (*SessionSecurity)(nil) func NewSessionSecurity(authenticator SessionAuthenticator, publicOrigin string) *SessionSecurity { return &SessionSecurity{authenticator: authenticator, publicOrigin: publicOrigin} } func (handler *IdentityHandler) SessionSecurity() *SessionSecurity { if handler == nil || handler.sessions == nil { return NewSessionSecurity(nil, "") } return NewSessionSecurity(handler.sessions, handler.publicOrigin) } func (security *SessionSecurity) HandleSessionCookie( ctx context.Context, _ api.OperationName, cookie api.SessionCookie, ) (context.Context, error) { if security == nil || security.authenticator == nil || !httpmiddleware.SessionCookieMatches(ctx, cookie.APIKey) { return ctx, ogenerrors.ErrSkipServerSecurity } authenticated, err := security.authenticator.Authenticate(ctx, cookie.APIKey) if errors.Is(err, identity.ErrUnauthenticated) { return ctx, ogenerrors.ErrSkipServerSecurity } if err != nil { return ctx, fmt.Errorf("SessionSecurity.HandleSessionCookie - authenticate session: %w", err) } ctx, ok := withAuthenticatedSession(ctx, authenticated) if !ok { return ctx, ogenerrors.ErrSkipServerSecurity } return ctx, nil } func (security *SessionSecurity) HandleSessionCsrf( ctx context.Context, _ api.OperationName, csrf api.SessionCsrf, ) (context.Context, error) { authenticated, ok := sessionFromContext(ctx) if !ok { return ctx, ogenerrors.ErrSkipServerSecurity } origin, hasOrigin := httpmiddleware.RequestOrigin(ctx) if security == nil || security.publicOrigin == "" || !hasOrigin || origin != security.publicOrigin || !hmac.Equal([]byte(authenticated.CSRFToken), []byte(csrf.APIKey)) { return ctx, errCsrfCheckFailed } return ctx, nil }