feat: Add webhook user authentication under WEBHOOK_AUTH_ENABLE variable#9139
Conversation
…r authentication 🔧 (endpoints.py): Update webhook_run_flow endpoint to use get_webhook_user for authentication 🔧 (utils.py): Add get_webhook_user function to handle webhook user authentication in services.auth ✅ (test_webhook.py): Add tests for webhook endpoint authentication and authorization
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughThe webhook authentication logic was refactored to centralize user retrieval into a new asynchronous function, Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant FastAPI
participant AuthUtils
participant FlowRunner
Client->>FastAPI: POST /webhook/{flow_id_or_name}
FastAPI->>AuthUtils: get_webhook_user(flow_id_or_name, request)
AuthUtils-->>FastAPI: UserRead (if authorized) or HTTP 403
FastAPI->>FlowRunner: simple_run_flow_task(..., api_key_user=UserRead)
FlowRunner-->>FastAPI: Flow execution result
FastAPI-->>Client: Response
Estimated code review effort2 (~15 minutes) Suggested labels
Suggested reviewers
✨ Finishing Touches🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/backend/base/langflow/api/v1/endpoints.py(4 hunks)src/backend/base/langflow/services/auth/utils.py(2 hunks)src/backend/tests/unit/test_webhook.py(2 hunks)
📓 Path-based instructions (3)
{src/backend/**/*.py,tests/**/*.py,Makefile}
📄 CodeRabbit Inference Engine (.cursor/rules/backend_development.mdc)
{src/backend/**/*.py,tests/**/*.py,Makefile}: Run make format_backend to format Python code before linting or committing changes
Run make lint to perform linting checks on backend Python code
Files:
src/backend/base/langflow/services/auth/utils.pysrc/backend/base/langflow/api/v1/endpoints.pysrc/backend/tests/unit/test_webhook.py
src/backend/tests/unit/**/*.py
📄 CodeRabbit Inference Engine (.cursor/rules/backend_development.mdc)
Test component integration within flows using create_flow, build_flow, and get_build_events utilities
Files:
src/backend/tests/unit/test_webhook.py
src/backend/tests/**/*.py
📄 CodeRabbit Inference Engine (.cursor/rules/testing.mdc)
src/backend/tests/**/*.py: Unit tests for backend code must be located in the 'src/backend/tests/' directory, with component tests organized by component subdirectory under 'src/backend/tests/unit/components/'.
Test files should use the same filename as the component under test, with an appropriate test prefix or suffix (e.g., 'my_component.py' → 'test_my_component.py').
Use the 'client' fixture (an async httpx.AsyncClient) for API tests in backend Python tests, as defined in 'src/backend/tests/conftest.py'.
When writing component tests, inherit from the appropriate base class in 'src/backend/tests/base.py' (ComponentTestBase, ComponentTestBaseWithClient, or ComponentTestBaseWithoutClient) and provide the required fixtures: 'component_class', 'default_kwargs', and 'file_names_mapping'.
Each test in backend Python test files should have a clear docstring explaining its purpose, and complex setups or mocks should be well-commented.
Test both sync and async code paths in backend Python tests, using '@pytest.mark.asyncio' for async tests.
Mock external dependencies appropriately in backend Python tests to isolate unit tests from external services.
Test error handling and edge cases in backend Python tests, including using 'pytest.raises' and asserting error messages.
Validate input/output behavior and test component initialization and configuration in backend Python tests.
Use the 'no_blockbuster' pytest marker to skip the blockbuster plugin in tests when necessary.
Be aware of ContextVar propagation in async tests; test both direct event loop execution and 'asyncio.to_thread' scenarios to ensure proper context isolation.
Test error handling by mocking internal functions using monkeypatch in backend Python tests.
Test resource cleanup in backend Python tests by using fixtures that ensure proper initialization and cleanup of resources.
Test timeout and performance constraints in backend Python tests using 'asyncio.wait_for' and timing assertions.
Test Langflow's Messag...
Files:
src/backend/tests/unit/test_webhook.py
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test webhook endpoints in backend Python tests by posting payloads and asserting correct processing and response codes.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test Langflow's REST API endpoints in backend Python tests using the async client fixture and asserting response codes and payloads.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.474Z
Learning: Applies to tests/**/*.py : Test authenticated API endpoints using logged_in_headers
src/backend/tests/unit/test_webhook.py (12)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test webhook endpoints in backend Python tests by posting payloads and asserting correct processing and response codes.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.091Z
Learning: Applies to src/backend/tests/**/*.py : Use the 'client' fixture (an async httpx.AsyncClient) for API tests in backend Python tests, as defined in 'src/backend/tests/conftest.py'.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test components that require external APIs using appropriate pytest markers (e.g., 'api_key_required', 'no_blockbuster') and environment variables for API keys.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Mock external dependencies appropriately in backend Python tests to isolate unit tests from external services.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test Langflow's REST API endpoints in backend Python tests using the async client fixture and asserting response codes and payloads.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.474Z
Learning: Applies to tests/**/*.py : Mark tests that require real API keys with @pytest.mark.api_key_required and @pytest.mark.no_blockbuster
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Be aware of ContextVar propagation in async tests; test both direct event loop execution and 'asyncio.to_thread' scenarios to ensure proper context isolation.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.474Z
Learning: Applies to tests/**/*.py : Test authenticated API endpoints using logged_in_headers
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test real-time event streaming endpoints in backend Python tests by consuming and validating NDJSON event streams.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test both sync and async code paths in backend Python tests, using '@pytest.mark.asyncio' for async tests.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test flows using predefined JSON data and utility functions such as 'create_flow', 'build_flow', 'get_build_events', and 'consume_and_assert_stream' in backend Python tests.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.474Z
Learning: Applies to src/backend/tests/unit/**/*.py : Test component integration within flows using create_flow, build_flow, and get_build_events utilities
🧰 Additional context used
📓 Path-based instructions (3)
{src/backend/**/*.py,tests/**/*.py,Makefile}
📄 CodeRabbit Inference Engine (.cursor/rules/backend_development.mdc)
{src/backend/**/*.py,tests/**/*.py,Makefile}: Run make format_backend to format Python code before linting or committing changes
Run make lint to perform linting checks on backend Python code
Files:
src/backend/base/langflow/services/auth/utils.pysrc/backend/base/langflow/api/v1/endpoints.pysrc/backend/tests/unit/test_webhook.py
src/backend/tests/unit/**/*.py
📄 CodeRabbit Inference Engine (.cursor/rules/backend_development.mdc)
Test component integration within flows using create_flow, build_flow, and get_build_events utilities
Files:
src/backend/tests/unit/test_webhook.py
src/backend/tests/**/*.py
📄 CodeRabbit Inference Engine (.cursor/rules/testing.mdc)
src/backend/tests/**/*.py: Unit tests for backend code must be located in the 'src/backend/tests/' directory, with component tests organized by component subdirectory under 'src/backend/tests/unit/components/'.
Test files should use the same filename as the component under test, with an appropriate test prefix or suffix (e.g., 'my_component.py' → 'test_my_component.py').
Use the 'client' fixture (an async httpx.AsyncClient) for API tests in backend Python tests, as defined in 'src/backend/tests/conftest.py'.
When writing component tests, inherit from the appropriate base class in 'src/backend/tests/base.py' (ComponentTestBase, ComponentTestBaseWithClient, or ComponentTestBaseWithoutClient) and provide the required fixtures: 'component_class', 'default_kwargs', and 'file_names_mapping'.
Each test in backend Python test files should have a clear docstring explaining its purpose, and complex setups or mocks should be well-commented.
Test both sync and async code paths in backend Python tests, using '@pytest.mark.asyncio' for async tests.
Mock external dependencies appropriately in backend Python tests to isolate unit tests from external services.
Test error handling and edge cases in backend Python tests, including using 'pytest.raises' and asserting error messages.
Validate input/output behavior and test component initialization and configuration in backend Python tests.
Use the 'no_blockbuster' pytest marker to skip the blockbuster plugin in tests when necessary.
Be aware of ContextVar propagation in async tests; test both direct event loop execution and 'asyncio.to_thread' scenarios to ensure proper context isolation.
Test error handling by mocking internal functions using monkeypatch in backend Python tests.
Test resource cleanup in backend Python tests by using fixtures that ensure proper initialization and cleanup of resources.
Test timeout and performance constraints in backend Python tests using 'asyncio.wait_for' and timing assertions.
Test Langflow's Messag...
Files:
src/backend/tests/unit/test_webhook.py
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test webhook endpoints in backend Python tests by posting payloads and asserting correct processing and response codes.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test Langflow's REST API endpoints in backend Python tests using the async client fixture and asserting response codes and payloads.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.474Z
Learning: Applies to tests/**/*.py : Test authenticated API endpoints using logged_in_headers
src/backend/tests/unit/test_webhook.py (12)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test webhook endpoints in backend Python tests by posting payloads and asserting correct processing and response codes.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.091Z
Learning: Applies to src/backend/tests/**/*.py : Use the 'client' fixture (an async httpx.AsyncClient) for API tests in backend Python tests, as defined in 'src/backend/tests/conftest.py'.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test components that require external APIs using appropriate pytest markers (e.g., 'api_key_required', 'no_blockbuster') and environment variables for API keys.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Mock external dependencies appropriately in backend Python tests to isolate unit tests from external services.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test Langflow's REST API endpoints in backend Python tests using the async client fixture and asserting response codes and payloads.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.474Z
Learning: Applies to tests/**/*.py : Mark tests that require real API keys with @pytest.mark.api_key_required and @pytest.mark.no_blockbuster
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Be aware of ContextVar propagation in async tests; test both direct event loop execution and 'asyncio.to_thread' scenarios to ensure proper context isolation.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.474Z
Learning: Applies to tests/**/*.py : Test authenticated API endpoints using logged_in_headers
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test real-time event streaming endpoints in backend Python tests by consuming and validating NDJSON event streams.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test both sync and async code paths in backend Python tests, using '@pytest.mark.asyncio' for async tests.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.092Z
Learning: Applies to src/backend/tests/**/*.py : Test flows using predefined JSON data and utility functions such as 'create_flow', 'build_flow', 'get_build_events', and 'consume_and_assert_stream' in backend Python tests.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.474Z
Learning: Applies to src/backend/tests/unit/**/*.py : Test component integration within flows using create_flow, build_flow, and get_build_events utilities
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Optimize new Python code in this PR
🔇 Additional comments (10)
src/backend/base/langflow/services/auth/utils.py (1)
10-10: LGTM: Import addition for new functionalityThe
Requestimport is correctly added to support the newget_webhook_userfunction parameter.src/backend/base/langflow/api/v1/endpoints.py (4)
45-45: LGTM: Import addition for webhook authenticationThe
get_webhook_userimport is correctly added to support the new webhook authentication logic.
394-399: LGTM: Function signature updated for centralized authenticationThe addition of the
flow_id_or_nameparameter and removal of the user dependency injection aligns well with the new centralized webhook authentication approach. This provides more control over the authentication flow.
418-421: LGTM: Centralized webhook authentication implementationThe call to
get_webhook_useris correctly implemented with proper async/await usage and clear variable naming. This centralizes the webhook authentication logic as intended.
453-453: LGTM: Consistent user parameter usageThe
webhook_useris correctly passed as theapi_key_userparameter to maintain consistency with the background task function signature.src/backend/tests/unit/test_webhook.py (5)
11-22: LGTM: Well-structured test for API key requirementThe test properly validates the default authentication behavior with clear assertions and appropriate error message checking. The docstring clearly explains the test purpose.
24-41: LGTM: Comprehensive test with proper resource managementThe test effectively validates webhook functionality with valid API key authentication. The use of temporary files with proper cleanup and validation of both HTTP response and file creation demonstrates good testing practices.
43-56: LGTM: Authorization failure test with clear validationThe test properly simulates and validates authorization failure scenarios with appropriate HTTP status checking and error message validation.
70-88: LGTM: Proper mocking for AUTO_LOGIN scenario testingThe test correctly uses mocking to simulate the AUTO_LOGIN=true scenario and validates that webhook execution works without an API key. The mocking approach is appropriate and the test is well-structured.
90-106: LGTM: Comprehensive authentication testing with different payloadsThe test effectively validates authentication requirements regardless of payload content, testing both failure and success scenarios with appropriate assertions and clear documentation.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
ogabrielluiz
left a comment
There was a problem hiding this comment.
I don't understand why this is needed.
Co-authored-by: Gabriel Luiz Freitas Almeida <gabriel@langflow.org>
Our webhook has no security in place. |
…ecurity function for better code reuse and readability
…ble (#9139) * 📝 (endpoints.py): Add get_webhook_user function to handle webhook user authentication 🔧 (endpoints.py): Update webhook_run_flow endpoint to use get_webhook_user for authentication 🔧 (utils.py): Add get_webhook_user function to handle webhook user authentication in services.auth ✅ (test_webhook.py): Add tests for webhook endpoint authentication and authorization * Update src/backend/base/langflow/services/auth/utils.py Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * [autofix.ci] apply automated fixes * Update src/backend/base/langflow/services/auth/utils.py Co-authored-by: Gabriel Luiz Freitas Almeida <gabriel@langflow.org> * 🔧 (utils.py): refactor authentication logic to use existing api_key_security function for better code reuse and readability * [autofix.ci] apply automated fixes * 📝 (endpoints.py): Update ConfigResponse class to include webhook_auth_enable field and modify from_settings method to accept auth_settings parameter 📝 (endpoints.py): Update get_config function to pass auth_settings to ConfigResponse.from_settings method 📝 (utils.py): Update get_webhook_user function to use WEBHOOK_AUTH_ENABLE setting for authentication logic 📝 (auth.py): Add WEBHOOK_AUTH_ENABLE setting to AuthSettings class 📝 (index.tsx): Add webhookAuthEnable state and setWebhookAuthEnable function to utilityStore 📝 (use-get-config.ts): Update useGetConfig hook to set webhook_auth_enable value from API response 📝 (get-curl-code.tsx): Update getCurlWebhookCode function to use webhookAuthEnable instead of isAuth parameter 📝 (utilityStore.ts): Add webhookAuthEnable state and setWebhookAuthEnable function to utilityStore 📝 (index.ts): Update GetCodeType type to use webhookAuthEnable instead of isAuth parameter * refactor: Simplify error messages in get_webhook_user function - Updated HTTPException messages for flow not found and access denied scenarios to be more concise and user-friendly. - Improved logging for invalid API key validation to enhance clarity. --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Gabriel Luiz Freitas Almeida <gabriel@langflow.org>
Codecov Report❌ Patch coverage is ❌ Your project status has failed because the head coverage (5.81%) is below the target coverage (10.00%). You can increase the head coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## main #9139 +/- ##
==========================================
- Coverage 34.69% 34.62% -0.07%
==========================================
Files 1209 1209
Lines 57115 57159 +44
Branches 5419 5418 -1
==========================================
- Hits 19818 19794 -24
- Misses 37153 37221 +68
Partials 144 144
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…conditions being tested 📝 (test_webhook.py): update test descriptions to improve clarity and consistency with actual test conditions
…o cz/webhook-auth
…when flow owner is not found in get_webhook_user function. Added explicit check and raise HTTPException with appropriate status code and detail message.
…ver is rate limiting requests
…o cz/webhook-auth
|



This pull request introduces webhook authentication enhancements, backend and frontend updates to support these changes, and improvements to testing and error handling. The key changes include implementing a new
WEBHOOK_AUTH_ENABLEsetting, modifying webhook execution logic to respect this setting, and updating the frontend to reflect the new authentication behavior.Webhook Authentication Enhancements:
WEBHOOK_AUTH_ENABLEsetting inAuthSettingsto toggle webhook authentication. When enabled, API key authentication is mandatory for webhook execution; otherwise, webhooks execute as the flow owner without authentication (src/backend/base/langflow/services/settings/auth.py).get_webhook_userfunction to handle user authentication for webhooks based on theWEBHOOK_AUTH_ENABLEsetting (src/backend/base/langflow/services/auth/utils.py).webhook_run_flowendpoint to useget_webhook_userfor determining the executing user (src/backend/base/langflow/api/v1/endpoints.py) [1] [2] [3].Backend Updates:
ConfigResponseschema and itsfrom_settingsmethod to include theWEBHOOK_AUTH_ENABLEflag, ensuring the frontend is aware of the setting (src/backend/base/langflow/api/v1/schemas.py) [1] [2].WEBHOOK_AUTH_ENABLEsetting (src/backend/tests/unit/test_webhook.py) [1] [2].Frontend Updates:
TextAreaComponentto use thewebhookAuthEnablestate from theutilityStore, ensuring the frontend reflects the authentication requirements for webhooks (src/frontend/src/components/core/parameterRenderComponent/components/textAreaComponent/index.tsx) [1] [2] [3] [4] [5].Testing and Error Handling Improvements:
BLE001) from exception handling in tests for better readability and compliance (src/backend/tests/conftest.py,src/backend/tests/integration/components/astra/test_astra_component.py,src/backend/tests/locust/locustfile.py,src/backend/tests/unit/components/agents/test_agent_component.py) [1] [2] [3] [4] [5].These changes collectively enhance the security and configurability of webhook execution while improving the maintainability of the codebase.