Skip to content

Allow TestDriver to run on outside contributions #1622

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

Merged
merged 5 commits into from
Dec 25, 2024

Conversation

esimkowitz
Copy link
Member

@esimkowitz esimkowitz commented Dec 24, 2024

Discussed in #1621, the current setup for the TestDriver workflow doesn't allow it to run for PRs from outside contributors, since GitHub restricts secrets access for external PRs using the pull_request trigger.

This PR splits the TestDriver workflow into two separate workflows, a pull_request-triggered one which builds the artifact, and a workflow_run-triggered one which can access our secrets to upload the job to TestDriver.

resolves #1621

Copy link
Contributor

coderabbitai bot commented Dec 24, 2024

Walkthrough

The pull request introduces modifications to three GitHub Actions workflow configuration files. In .github/workflows/testdriver.yml, the workflow name has been changed to TestDriver.ai Run, and the event triggers have been updated to run after the completion of another workflow named TestDriver.ai Build. The job name has shifted from build_and_upload to run_testdriver, and several steps related to building and uploading artifacts have been removed. In .github/workflows/merge-gatekeeper.yml, the ignored parameter in the merge-gatekeeper job has been updated to replace "Test Onboarding" with "Build for TestDriver.ai." Additionally, a new workflow file named .github/workflows/testdriver-build.yml has been added, which includes triggers for pushes to the main branch, version tags, and pull requests, as well as a daily scheduled trigger and manual dispatch capability. This new workflow focuses on building and uploading a Windows executable.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1bdee09 and 3ca8c36.

📒 Files selected for processing (2)
  • .github/workflows/merge-gatekeeper.yml (1 hunks)
  • .github/workflows/testdriver-build.yml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • .github/workflows/merge-gatekeeper.yml
  • .github/workflows/testdriver-build.yml

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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
Contributor

@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: 2

🔭 Outside diff range comments (1)
.github/workflows/testdriver.yml (1)

Line range hint 82-157: Critical security concerns in artifact handling

The current artifact handling implementation has several security risks:

  1. Direct execution of downloaded artifacts without validation
  2. Potential path traversal vulnerabilities
  3. Insufficient error handling for network issues

Consider implementing these security improvements:

  1. Add checksum validation:
# After download, before execution
$expectedHash = "..." # Get from a secure source
$fileHash = Get-FileHash -Path $artifactFilePath -Algorithm SHA256
if ($fileHash.Hash -ne $expectedHash) {
    Write-Error "Artifact validation failed"
    exit 1
}
  1. Sanitize file paths:
# Before using any file paths
$downloadFolder = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName())
  1. Add timeout and retry logic:
$maxRetries = 3
$retryCount = 0
do {
    try {
        # Download logic here
        break
    } catch {
        $retryCount++
        if ($retryCount -eq $maxRetries) { throw }
        Start-Sleep -Seconds (2 * $retryCount)
    }
} while ($retryCount -lt $maxRetries)
🧹 Nitpick comments (1)
.github/workflows/testdriver.yml (1)

Line range hint 1-157: Architectural security review for external PR handling

While the approach to enabling external PR testing is fundamentally sound, consider implementing these additional security measures:

  1. Add explicit workflow concurrency limits to prevent resource exhaustion
  2. Implement artifact allow-listing to restrict what can be executed
  3. Consider adding a manual approval step for external PR testing

Add these configurations:

# Add at root level
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

# Add job-level condition for external PRs
jobs:
  build_and_upload:
    # Add this condition
    if: |
      github.event_name == 'pull_request_target' &&
      github.event.pull_request.head.repo.full_name != github.repository
    # ... rest of job config
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c1cf539 and 17cf7f7.

📒 Files selected for processing (1)
  • .github/workflows/testdriver.yml (3 hunks)

Comment on lines 55 to 56
env:
GITHUB_TOKEN: ""
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance GITHUB_TOKEN security handling

While unsetting GITHUB_TOKEN is a good security practice, consider these improvements:

  1. Use job-level environment variable control
  2. Add explicit environment variable blocking for all sensitive tokens

Apply this change at the job level:

 jobs:
   build_and_upload:
     name: Test Onboarding
     runs-on: windows-latest
+    env:
+      # Explicitly unset sensitive tokens for all steps
+      GITHUB_TOKEN: ""
+      # List other sensitive tokens that should be blocked
+      ACTIONS_RUNTIME_TOKEN: ""
+      ACTIONS_ID_TOKEN_REQUEST_TOKEN: ""

Then remove the individual GITHUB_TOKEN: "" settings from steps.

Also applies to: 68-68

@@ -6,7 +6,7 @@
- main
tags:
- "v[0-9]+.[0-9]+.[0-9]+*"
pull_request:
pull_request_target:
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Critical security vulnerability in pull_request_target workflow

The workflow configuration has a significant security risk. After reviewing the complete workflow file, I found that it checks out and executes code from external PRs without explicitly checking out the base ref, and more importantly, it builds and runs untrusted code from PRs with access to secrets:

  1. The workflow uses pull_request_target but doesn't specify the ref in the checkout action
  2. It proceeds to build and execute the code from the PR using task package
  3. It has access to sensitive secrets (secrets.DASHCAM_API and secrets.GITHUB_TOKEN)
  4. The code is not only built but also executed in the prerun script of testdriver action

This is a serious security concern as malicious code in external PRs could potentially exfiltrate secrets.

Required changes:

  • Add explicit base ref checkout:
- uses: actions/checkout@v4
  with:
    ref: ${{ github.event.pull_request.base.sha }}
  • Move the build and test steps to a separate workflow triggered by pull_request (without _target)
  • Keep only the comment/status operations in the pull_request_target workflow
🔗 Analysis chain

Security considerations for pull_request_target

The switch to pull_request_target allows external PR access while maintaining workflow security. However, this trigger requires additional safeguards:

  1. Ensure that no user-controlled code from the PR is checked out or executed before validation
  2. Consider adding explicit checkout of the base ref

Add this step immediately after the checkout:

 - uses: actions/checkout@v4
+  with:
+    ref: ${{ github.event.pull_request.base.sha }}

Let me verify the workflow configuration and security implications.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Check the complete workflow file content
cat .github/workflows/testdriver.yml

Length of output: 6853


Script:

#!/bin/bash
# Look for other workflow files that might be affected
fd -e yml -e yaml . .github/workflows/

Length of output: 286


Script:

#!/bin/bash
# Search for checkout actions usage across workflows
rg "actions/checkout" .github/workflows/

Length of output: 721

Copy link
Contributor

@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: 4

🔭 Outside diff range comments (1)
.github/workflows/testdriver.yml (1)

Line range hint 29-97: Enhance security for artifact handling and execution

The current implementation has several security concerns in artifact handling and execution:

  1. No validation of artifact integrity
  2. Direct execution of downloaded executables
  3. No sandboxing of executed applications

Implement these security measures:

  1. Add checksum validation for downloaded artifacts
  2. Implement signature verification for executables
  3. Add execution policy restrictions
  4. Run in isolated environment

Example implementation for checksum validation:

# Add after artifact download
$expectedHash = (Invoke-RestMethod -Uri "https://api.github.com/repos/${{ github.repository }}/actions/artifacts/$artifactId/hash" -Headers $headers).sha256
$actualHash = Get-FileHash -Path $artifactZipPath -Algorithm SHA256
if ($actualHash.Hash -ne $expectedHash) {
    Write-Error "Artifact integrity check failed"
    exit 1
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 17cf7f7 and b7deb9c.

📒 Files selected for processing (3)
  • .github/workflows/merge-gatekeeper.yml (1 hunks)
  • .github/workflows/testdriver-build.yml (1 hunks)
  • .github/workflows/testdriver.yml (3 hunks)
🔇 Additional comments (1)
.github/workflows/merge-gatekeeper.yml (1)

26-26: Verify workflow name in ignored list

The ignored workflow name "Run TestDriver.ai" should exactly match the name of the job in the TestDriver workflow.

✅ Verification successful

Workflow name in ignored list matches exactly

The workflow name "Run TestDriver.ai" in the ignored list matches exactly with the job name defined in .github/workflows/testdriver.yml.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the workflow name matches exactly
rg "name: Run TestDriver\.ai" .github/workflows/

Length of output: 115

Comment on lines +63 to +68
- name: Build
run: task package
env:
USE_SYSTEM_FPM: true # Ensure that the installed version of FPM is used rather than the bundled one.
CSC_IDENTITY_AUTO_DISCOVERY: false # disable codesign
shell: powershell # electron-builder's Windows code signing package has some compatibility issues with pwsh, so we need to use Windows Powershell
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Enhance security for package task execution

The task package step runs with write permissions and could potentially execute malicious code from external PRs.

  1. Add explicit base ref checkout before this step:
- uses: actions/checkout@v4
  with:
    ref: ${{ github.event.pull_request.base.sha }}
  1. Consider moving build steps to a separate job with minimal permissions
  2. Add input validation for external PR code before execution

workflow_dispatch: null

env:
GO_VERSION: "1.23"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Invalid Go version specified

The Go version "1.23" is incorrect as it doesn't exist. The latest stable version is 1.22.

-    GO_VERSION: "1.23"
+    GO_VERSION: "1.22"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
GO_VERSION: "1.23"
GO_VERSION: "1.22"


env:
GO_VERSION: "1.23"
NODE_VERSION: 22
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Node.js version 22 is not recommended for this project

The package.json files reveal that:

  • The main project has dependencies on packages like electron v33.2.1 and other modern packages
  • The docs project specifically requires Node.js >= 18.0
  • The project uses advanced development tools and frameworks that are better suited for LTS versions

Using Node.js 22 (which is currently in development) could lead to compatibility issues. Node.js 20 is the current LTS version and would be more appropriate for production use.

🔗 Analysis chain

Verify Node.js version compatibility

Node.js version 22 is currently in development. Consider using the latest LTS version 20.

-    NODE_VERSION: 22
+    NODE_VERSION: 20

Let me verify the Node.js version compatibility by checking the project's dependencies and requirements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Check for package.json files and their Node.js version requirements
fd package.json --exec cat {}

# Check for .nvmrc or .node-version files
fd -e nvmrc -e node-version --exec cat {}

# Look for any Node.js version specifications in workflow files
fd -e yml -e yaml -p '.github/workflows' --exec cat {}

Length of output: 8150

- uses: testdriverai/action@main
id: testdriver
env:
FORCE_COLOR: "3"
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consolidate and secure GITHUB_TOKEN usage

The GITHUB_TOKEN is exposed in multiple places and could be leaked during execution.

  1. Use a dedicated environment variable for the token
  2. Implement token rotation for artifact downloads
  3. Add token validation before usage
 env:
+  ARTIFACT_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Then update all token usages to reference ARTIFACT_TOKEN.

Also applies to: 50-50

@esimkowitz esimkowitz merged commit 0f1d138 into main Dec 25, 2024
8 checks passed
@esimkowitz esimkowitz deleted the evan/testdriver-target branch December 25, 2024 16:16
@chottuthejimmy
Copy link
Contributor

chottuthejimmy commented Dec 25, 2024

Hey @esimkowitz I think as Ian said, gh sometimes passes empty secrets.
Hope that doesn't happen here

@esimkowitz
Copy link
Member Author

esimkowitz commented Dec 25, 2024

It shouldn't, since I switched the trigger type. Though is that token really necessary? The artifacts should be public. If you have your own token on your end that would be better to use so we don't risk leaking secrets. Let's discuss later, we should really be using GitHub Apps to manage your workflow's access to our repo. Happy to show you how we do it for our own workflows.

@chottuthejimmy
Copy link
Contributor

Ofc, always open to learn.
Do you want to sync or just send it to me ?

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.

TestDriver pipeline fails for non-org members
2 participants