Skip to content

Conversation

hi120ki
Copy link
Contributor

@hi120ki hi120ki commented Feb 13, 2025

User description

For GitHub Action's integration, we can setup pull_request and pull_request_target.

https://docs.github.com/en/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows#pull_request_target

pull_request_target event will fix the workflow context to default branch's ref (like refs/heads/main), and it will help us to not to allow editing the workflow file on PR for preventing unintended resource usage.

Even if we switch the workflow from pull_request to pull_request_target, we can continue to get event_payload.get("action") and event_payload.get("pull_request", {}), then we don't need to change the existing codes.

For testing, I tried to run the PR Agent with pull_request_target configuration and confirmed /describe , /review, /improve works. This shows we don't need to change the existing codes, and if my patch is applied, the automated describe and review will be executed on PR with pull_request_target.

Could you please take a look? Thank you for your great work on awesome tool!


PR Type

Enhancement, Bug fix


Description

  • Added support for pull_request_target event in GitHub Actions.

  • Ensured compatibility with existing pull_request event handling.

  • Prevented unintended workflow edits for resource usage control.


Changes walkthrough 📝

Relevant files
Enhancement
github_action_runner.py
Support `pull_request_target` event in GitHub Actions       

pr_agent/servers/github_action_runner.py

  • Added condition to handle pull_request_target event.
  • Ensured compatibility with existing pull_request event logic.
  • Improved workflow security by supporting fixed context.
  • +1/-1     

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Signed-off-by: Hi120ki <12624257+hi120ki@users.noreply.github.com>
    Copy link
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 1 🔵⚪⚪⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ No major issues detected

    Copy link
    Contributor

    qodo-merge-for-open-source bot commented Feb 13, 2025

    PR Code Suggestions ✨

    Latest suggestions up to c9500cf

    CategorySuggestion                                                                                                                                    Impact
    Security
    Add security check for untrusted sources

    Add validation to ensure the event payload is from a trusted source when
    handling 'pull_request_target' events, as they can expose sensitive workflow
    data to untrusted forks.

    pr_agent/servers/github_action_runner.py [84-85]

     if GITHUB_EVENT_NAME == "pull_request" or GITHUB_EVENT_NAME == "pull_request_target":
    +    if GITHUB_EVENT_NAME == "pull_request_target" and not is_trusted_source(event_payload):
    +        get_logger().warning("Skipping untrusted pull_request_target event")
    +        return
         action = event_payload.get("action")
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    __

    Why: The suggestion addresses a critical security vulnerability by adding validation for 'pull_request_target' events, which could potentially expose sensitive workflow data to untrusted forks. This is a significant security enhancement.

    High
    Learned
    best practice
    Add null safety checks and validation for event data to prevent potential runtime errors

    Add null safety check for GITHUB_EVENT_NAME and event_payload variables to
    handle cases where they might be None or undefined. Also validate that the
    action value exists in event_payload before using it.

    pr_agent/servers/github_action_runner.py [84-85]

    -if GITHUB_EVENT_NAME == "pull_request" or GITHUB_EVENT_NAME == "pull_request_target":
    +if GITHUB_EVENT_NAME and GITHUB_EVENT_NAME in ("pull_request", "pull_request_target"):
    +    if not event_payload:
    +        get_logger().error("Event payload is missing")
    +        return
         action = event_payload.get("action")
    +    if not action:
    +        get_logger().error("Action field is missing in event payload")
    +        return
    • Apply this suggestion
    Suggestion importance[1-10]: 6
    Low
    • Author self-review: I have reviewed the PR code suggestions, and addressed the relevant ones.

    Previous suggestions

    Suggestions up to commit c9500cf
    CategorySuggestion                                                                                                                                    Impact
    Security
    Add security check for events

    Verify the event payload's repository context when handling pull_request_target
    events to prevent potential security risks from malicious forks.

    pr_agent/servers/github_action_runner.py [84-85]

     if GITHUB_EVENT_NAME == "pull_request" or GITHUB_EVENT_NAME == "pull_request_target":
    +    if GITHUB_EVENT_NAME == "pull_request_target":
    +        # Verify repository context for security
    +        repo_context = event_payload.get("repository", {}).get("full_name")
    +        if not repo_context or repo_context != os.environ.get("GITHUB_REPOSITORY"):
    +            raise SecurityError("Invalid repository context in pull_request_target event")
         action = event_payload.get("action")
    Suggestion importance[1-10]: 9

    __

    Why: The suggestion addresses a critical security vulnerability by adding validation for pull_request_target events, which could be exploited by malicious forks if not properly verified against the repository context.

    High
    Learned
    best practice
    Add null safety checks when accessing dictionary values to prevent potential runtime errors

    Add null safety check when getting the "action" value from event_payload
    dictionary to handle cases where the key might not exist or the value might be
    None. Use the dict.get() method with a default value.

    pr_agent/servers/github_action_runner.py [85]

    -action = event_payload.get("action")
    +action = event_payload.get("action", "unknown")
    Suggestion importance[1-10]: 6
    Low

    @@ -81,7 +81,7 @@ async def run_action():
    get_logger().info(f"github action: failed to apply repo settings: {e}")

    # Handle pull request opened event
    if GITHUB_EVENT_NAME == "pull_request":
    if GITHUB_EVENT_NAME == "pull_request" or GITHUB_EVENT_NAME == "pull_request_target":
    Copy link
    Collaborator

    Choose a reason for hiding this comment

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

    /ask explain what will change when implementing this diff

    Copy link
    Contributor

    Choose a reason for hiding this comment

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

    This change expands the condition to handle GitHub Actions events from pull requests. Here's what changes:

    • Before: The code only processed events when GITHUB_EVENT_NAME was "pull_request"
    • After: The code will now process events when GITHUB_EVENT_NAME is either "pull_request" OR "pull_request_target"

    The main impact is that this adds support for the pull_request_target event, which is a more secure way to handle pull requests from forks. The pull_request_target event:

    • Runs in the context of the base repository
    • Has access to secrets
    • Can safely handle PRs from forks without exposing sensitive repository data

    This is particularly useful for automation workflows that need to interact with pull requests from external contributors while maintaining security.

    @mrT23
    Copy link
    Collaborator

    mrT23 commented Feb 14, 2025

    /improve

    @mrT23
    Copy link
    Collaborator

    mrT23 commented Feb 14, 2025

    @hi120ki
    looks good, but just to be sure:

    can you specify exactly when a pull_request_target event (and not a regular pull_request) is sent ?

    @hi120ki
    Copy link
    Contributor Author

    hi120ki commented Feb 15, 2025

    @mrT23 Thank you!
    Yes, pull_request_target can be specified in workflow file's trigger settings. The pull_request_target event must be explicitly specified when configuring a workflow, so it does not affect existing pull_request event processing.

    name: pr_agent_job
    
    on:
      pull_request_target:
        types: [opened, reopened, ready_for_review]
      issue_comment:
    jobs:
      pr_agent_job:
        if: ${{ github.event.sender.type != 'Bot' }}
        runs-on: ubuntu-latest
        permissions:
          issues: write
          pull-requests: write
          contents: write
        name: Run pr agent on every pull request, respond to user comments
        steps:
          - name: Check out repository
            uses: actions/checkout@v3
            with:
              ref: ${{ github.event.pull_request.head.ref }}
              repository: ${{ github.event.pull_request.head.repo.full_name }}
          - name: PR Agent action step
            id: pragent
            uses: qodo-ai/pr-agent@main
            env:
              OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
              GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

    @mrT23 mrT23 merged commit 359c963 into qodo-ai:main Feb 15, 2025
    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.

    2 participants