Skip to content

added authorization for executing main pyscript via callback #1967

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

rexa0310
Copy link
Contributor

@rexa0310 rexa0310 commented May 21, 2025

Summary by CodeRabbit

  • New Features

    • Added authentication verification for requests to the restricted Python script execution endpoint.
    • Introduced dynamic access token generation for secure callback requests when running Python scripts.
  • Bug Fixes

    • Improved security for Python script execution and callback requests by requiring authentication and dynamic tokens.

Copy link

coderabbitai bot commented May 21, 2025

Walkthrough

The changes introduce authentication for the restricted Python script execution endpoint by adding a request parameter and verifying it before processing. The run_pyscript utility now generates and uses a dynamic JWT token for authorization in callback HTTP requests. Corresponding test updates include adding an Authorization header with both mock and real JWT tokens, and a new failure test for authentication errors.

Changes

File(s) Change Summary
kairon/async_callback/router/pyscript_callback.py Added request: Request parameter to trigger_restricted_python endpoint and inserted authentication verification step before processing the payload.
kairon/shared/actions/utils.py Updated run_pyscript to generate and use a dynamic JWT token in the Authorization header for callback HTTP requests. Added import for TOKEN_TYPE.
tests/integration_test/callback_service_test.py Modified existing test to include Authorization header with a mock JWT token; added new test for failure scenario using a real JWT token and verifying error response.

Suggested reviewers

  • hiteshghuge

Poem

A lock on the script, a key in the code,
Tokens now travel where secrets once strode.
With headers anew and requests standing tall,
The rabbit ensures that no hackers befall.
Secure and dynamic, the journey’s begun—
Hop, hop, hooray! The code’s on the run! 🐇🔒

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/integration_test/callback_service_test.py (1)

664-686: Consider adding a negative test case for unauthorized access.

While you've added a test for successful authentication, consider adding a test case that verifies the endpoint rejects requests without a valid authorization token to ensure complete test coverage.

@pytest.mark.asyncio
@patch("kairon.async_callback.utils.CallbackUtility.main_pyscript_handler")
+async def test_execute_python_unauthorized():
+    await app.start()
+    client = TestClient(app)
+
+    payload = {
+        "source_code": "bot_response=100",
+        "predefined_objects": {"x": 1}
+    }
+
+    # Send request without authorization header
+    response = await client.post("/main_pyscript/execute-python", content=JSONContent(payload))
+    json_response = await response.json()
+
+    # Assertions for unauthorized access
+    assert response.status == 401 or response.status == 403
+    assert json_response["success"] is False
🧰 Tools
🪛 Gitleaks (8.26.0)

665-665: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.

(jwt)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 8569b8e and 1914544.

📒 Files selected for processing (1)
  • tests/integration_test/callback_service_test.py (1 hunks)
🧰 Additional context used
🪛 Gitleaks (8.26.0)
tests/integration_test/callback_service_test.py

665-665: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.

(jwt)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (python)
  • GitHub Check: Python CI
🔇 Additional comments (3)
tests/integration_test/callback_service_test.py (3)

664-667: Good addition of JWT mocking for testing authorization.

The mock token implementation is appropriate for testing the new authorization requirement in the execute-python endpoint.

🧰 Tools
🪛 Gitleaks (8.26.0)

665-665: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.

(jwt)


674-676: Correctly implemented Authorization header format.

The Authorization header follows the standard "Bearer token" format, which is appropriate for JWT authentication.


678-679: Successfully modified test to include authorization.

This change aligns with the PR objective of adding authentication to the main pyscript execution endpoint.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
tests/integration_test/callback_service_test.py (1)

724-744: ⚠️ Potential issue

Duplicate test function name detected.

There are two test functions with the same name test_execute_python_failure (lines 687 and 724). This could cause confusion and might lead to one test being skipped during test execution.

Consider renaming one of these functions to clearly distinguish between them:

-@pytest.mark.asyncio
-@patch("kairon.async_callback.utils.CallbackUtility.main_pyscript_handler")
-async def test_execute_python_failure(mock_handler):
+@pytest.mark.asyncio
+@patch("kairon.async_callback.utils.CallbackUtility.main_pyscript_handler")
+async def test_execute_python_no_auth_failure(mock_handler):
🧰 Tools
🪛 Ruff (0.11.9)

726-726: Redefinition of unused test_execute_python_failure from line 689

(F811)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1914544 and 8a99b7a.

📒 Files selected for processing (1)
  • tests/integration_test/callback_service_test.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/integration_test/callback_service_test.py (1)
kairon/shared/auth.py (2)
  • Authentication (30-465)
  • create_access_token (151-173)
🪛 Gitleaks (8.26.0)
tests/integration_test/callback_service_test.py

665-665: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.

(jwt)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (python)
  • GitHub Check: Python CI
🔇 Additional comments (2)
tests/integration_test/callback_service_test.py (2)

687-723: Good implementation of authentication test with dynamic token generation.

The test properly generates a real JWT token with appropriate claims and expiration time, then verifies the error handling when authentication succeeds but execution fails. This is a good addition to ensure the authentication flow works correctly.


693-699:

❓ Verification inconclusive

Verify the token claims match what's expected by the endpoint.

The test creates a JWT token with specific claims ("sub": "action-server" and "callback": true). Ensure these claims are actually being checked by the authentication logic in the endpoint being tested.


🏁 Script executed:

#!/bin/bash
# Find where token validation happens for the endpoint
rg -A 10 "verify.*request" --glob "*.py" | grep -v "test_"

Length of output: 22584


🏁 Script executed:

#!/bin/bash
sed -n '1,200p' kairon/async_callback/auth.py

Length of output: 1349


🏁 Script executed:

#!/bin/bash
rg -n "create_access_token" -n kairon/shared/auth.py

Length of output: 592


(Awaiting the script execution results)

Comment on lines +664 to +676
# Create a mock token with three segments
mock_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJnQUFBQUFCb0xjUi00QnRVM1FFOUdBRFdONVg0N29Yay03VDdxN2dOQks1dlFqM3VnQkoybnZlLVBrVGVTUzZYRm55dkRjM0RmMmNob2JUSFAyM0dDTnI3STZ2eWwyZ0tUYkF3eXFFNERKVDU1TWNsWmV5LWdSRGR4dG55TS01M1R0cjVQLU9iQ3lKTmpDcTFaa1NkRFFQNWk0eDZsN3R1c0E9PSIsInZlcnNpb24iOiIyLjAifQ.HEL3BSt1uO2uRfwwPTVV5UgYvwXsSoyERqZ9Gev2X-U"

mock_handler.return_value = {"output": "Execution successful", "success": True}

payload = {
"source_code": "bot_response=100",
"predefined_objects": {"x": 1}
}

# Simulate response from handler
mock_handler.return_value = {"output": "Execution successful", "success": True}
headers = {
"Authorization": f"Bearer {mock_token}"
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Consider using a dynamically generated token instead of a hardcoded one.

The test uses a hardcoded JWT token which could be a security concern if it contains actual credentials or secrets. While this is a test file, it's better to generate tokens dynamically like you did in the test_execute_python_failure test.


🏁 Script executed:

#!/bin/bash
# Check if the token is decodable and what it contains
echo "Checking if token contains sensitive information:"
jq -R 'split(".") | .[0],.[1] | @base64d | fromjson' <<< "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJnQUFBQUFCb0xjUi00QnRVM1FFOUdBRFdONVg0N29Yay03VDdxN2dOQks1dlFqM3VnQkoybnZlLVBrVGVTUzZYRm55dkRjM0RmMmNob2JUSFAyM0dDTnI3STZ2eWwyZ0tUYkF3eXFFNERKVDU1TWNsWmV5LWdSRGR4dG55TS01M1R0cjVQLU9iQ3lKTmpDcTFaa1NkRFFQNWk0eDZsN3R1c0E9PSIsInZlcnNpb24iOiIyLjAifQ"

Length of output: 400


Use dynamic JWT generation for mock_token

We’ve verified that the hardcoded token’s header and payload contain no sensitive data. To improve test consistency and avoid brittle hardcoded values (and mirror your approach in test_execute_python_failure), generate the JWT at runtime.

• File: tests/integration_test/callback_service_test.py
Lines: 664–676

Suggested change:

-   # Create a mock token with three segments
-   mock_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.…HEL3BSt1uO2uRfwwPTVV5UgYvwXsSoyERqZ9Gev2X-U"
+   # Dynamically generate a mock token for consistency
+   from jwt import encode
+
+   payload = {
+       "sub": "gAAAAABoLcR-4BtU3QE9GADWN5X47oXk-…tusA==",
+       "version": "2.0"
+   }
+   mock_token = encode(payload, TEST_JWT_SECRET, algorithm="HS256")

Make sure TEST_JWT_SECRET is defined or imported as in other tests.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Gitleaks (8.26.0)

665-665: Uncovered a JSON Web Token, which may lead to unauthorized access to web applications and sensitive user data.

(jwt)

🤖 Prompt for AI Agents
In tests/integration_test/callback_service_test.py around lines 664 to 676,
replace the hardcoded JWT token string with a dynamically generated token using
the same method as in test_execute_python_failure. Ensure you import or define
TEST_JWT_SECRET for signing the token, then create the token at runtime with
appropriate header and payload. Update the Authorization header to use this
generated token to improve test reliability and consistency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant