Skip to content

✨ feat: add Connect & Run Script functionality and update navigation - #20

Open
azigler wants to merge 1 commit into
base-pythonfrom
add-qa-testing-agent-support-qodo
Open

azigler wants to merge 1 commit into
base-pythonfrom
add-qa-testing-agent-support-qodo

Conversation

@azigler

@azigler azigler commented Jun 30, 2025

Copy link
Copy Markdown
Contributor

User description

This commit introduces a new view and template for connecting to a server and executing a script via SSH. It also updates the navigation bar to include links to the new functionality and enhances the base template with improved structure and Bootstrap integration.


PR Type

Enhancement


Description

  • Add SSH script execution functionality with form interface

  • Update navigation with new menu items

  • Improve base template formatting and structure

  • Implement Connect & Run Script view with POST handling


Changes diagram

flowchart LR
  A["User Form"] --> B["ConnectAndRunScriptView"]
  B --> C["SSH Command Execution"]
  C --> D["Script on Remote Server"]
  E["Navigation Update"] --> F["New Menu Items"]
Loading

Changes walkthrough 📝

Relevant files
Enhancement
urls.py
Add new URL routes for SSH functionality                                 

pages/urls.py

  • Add new URL patterns for syscall and connect_and_run views
  • Import new view classes and functions
  • +4/-1     
    views.py
    Implement SSH script execution view                                           

    pages/views.py

  • Add ConnectAndRunScriptView class with GET/POST methods
  • Implement SSH command execution using os.system()
  • Add form handling for server, username, and script parameters
  • Import required Django modules for HTTP handling
  • +17/-0   
    _base.html
    Update navigation and improve template formatting               

    templates/_base.html

  • Add new navigation items for "Unsafe Example" and "Connect & Run"
  • Improve HTML formatting and indentation
  • Maintain existing Bootstrap integration and structure
  • +137/-78
    connect_and_run.html
    Create SSH script execution form template                               

    templates/pages/connect_and_run.html

  • Create new template with form for SSH connection details
  • Add input fields for server address, username, and script name
  • Include success message display for executed commands
  • Use Bootstrap styling for form elements
  • +45/-0   

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • This commit introduces a new view and template for connecting to a server and executing a script via SSH. It also updates the navigation bar to include links to the new functionality and enhances the base template with improved structure and Bootstrap integration.
    @coderabbitai

    coderabbitai Bot commented Jun 30, 2025

    Copy link
    Copy Markdown

    Important

    Review skipped

    Auto reviews are disabled on base/target branches other than the default branch.

    Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

    You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


    🪧 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.

    @azigler

    azigler commented Jun 30, 2025

    Copy link
    Copy Markdown
    Contributor Author

    /review

    @qodo-code-review

    qodo-code-review Bot commented Jun 30, 2025

    Copy link
    Copy Markdown

    PR Reviewer Guide 🔍

    (Review updated until commit 7e31173)

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 Security concerns

    Command injection vulnerability:
    The code uses os.system() with unsanitized user input from POST parameters (server, username, script). An attacker can inject arbitrary shell commands by manipulating these fields. For example, entering ; rm -rf / in any field would execute destructive commands. The SSH command construction at line 24 concatenates user input directly without validation, escaping, or using safer alternatives like subprocess with argument lists.

    ⚡ Recommended focus areas for review

    Security Vulnerability

    The SSH command execution uses os.system() with unsanitized user input, creating a critical command injection vulnerability. User input is directly concatenated into shell commands without validation or escaping.

    cmd = f'ssh {username}@{server} "bash /opt/scripts/{script}.sh"'
    os.system(cmd)
    Broken Navigation

    Navigation links reference URL names that don't match the actual URL patterns defined in urls.py, which will cause template rendering errors.

      <a class="nav-link" href="{% url 'unsafe_system_call' %}"
        >Unsafe Example</a
      >
    </li>
    <li class="nav-item">
      <a class="nav-link" href="{% url 'connect_and_run' %}"
        >Connect & Run</a
      >
    Missing Function

    The syscall function is imported and referenced in URLs but not defined in the views module, which will cause import errors.

    from django.http import HttpResponse
    from django.shortcuts import render

    @qodo-code-review

    Copy link
    Copy Markdown

    Persistent review updated to latest commit 7e31173

    @qodo-code-review

    Copy link
    Copy Markdown

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Security
    Prevent command injection vulnerability

    The current implementation is vulnerable to command injection attacks since user
    input is directly concatenated into shell commands without sanitization. Use
    subprocess.run() with proper argument separation and input validation instead of
    os.system().

    pages/views.py [20-26]

     def post(self, request):
         server = request.POST.get("server", "")
         username = request.POST.get("username", "")
         script = request.POST.get("script", "")
    -    cmd = f'ssh {username}@{server} "bash /opt/scripts/{script}.sh"'
    -    os.system(cmd)
    -    return render(request, "pages/connect_and_run.html", {"executed": True, "cmd": cmd})
    +    
    +    # Validate inputs to prevent command injection
    +    import re
    +    if not re.match(r'^[a-zA-Z0-9._-]+$', server):
    +        return render(request, "pages/connect_and_run.html", {"error": "Invalid server format"})
    +    if not re.match(r'^[a-zA-Z0-9._-]+$', username):
    +        return render(request, "pages/connect_and_run.html", {"error": "Invalid username format"})
    +    if not re.match(r'^[a-zA-Z0-9._-]+$', script):
    +        return render(request, "pages/connect_and_run.html", {"error": "Invalid script format"})
    +    
    +    import subprocess
    +    cmd_args = ['ssh', f'{username}@{server}', f'bash /opt/scripts/{script}.sh']
    +    try:
    +        subprocess.run(cmd_args, check=True, timeout=30)
    +        return render(request, "pages/connect_and_run.html", {"executed": True, "cmd": ' '.join(cmd_args)})
    +    except subprocess.CalledProcessError:
    +        return render(request, "pages/connect_and_run.html", {"error": "Command execution failed"})
    • Apply / Chat
    Suggestion importance[1-10]: 10

    __

    Why: The suggestion correctly identifies and fixes a critical command injection vulnerability by validating user input and using subprocess.run instead of os.system.

    High
    Possible issue
    Fix broken URL reference

    The navigation references a URL name unsafe_system_call that doesn't exist in
    the URL patterns. This will cause a NoReverseMatch error when the template is
    rendered.

    templates/_base.html [64-68]

     <li class="nav-item">
    -  <a class="nav-link" href="{% url 'unsafe_system_call' %}"
    +  <a class="nav-link" href="{% url 'syscall' %}"
         >Unsafe Example</a
       >
     </li>
    • Apply / Chat
    Suggestion importance[1-10]: 9

    __

    Why: The suggestion correctly identifies a NoReverseMatch error by pointing out that the URL name unsafe_system_call does not exist and provides the correct name syscall.

    High
    • More

    Comment thread pages/views.py
    Comment on lines +20 to +25
    def post(self, request):
    server = request.POST.get("server", "")
    username = request.POST.get("username", "")
    script = request.POST.get("script", "")
    cmd = f'ssh {username}@{server} "bash /opt/scripts/{script}.sh"'
    os.system(cmd)

    Copy link
    Copy Markdown

    Choose a reason for hiding this comment

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

    Security Vulnerability: Command Injection Risk

    This implementation contains a critical security vulnerability. The code directly interpolates user-provided inputs (server, username, and script) into a shell command without proper validation or sanitization:

    cmd = f'ssh {username}@{server} "bash /opt/scripts/{script}.sh"'
    os.system(cmd)

    This creates a command injection vulnerability where attackers could inject arbitrary commands by manipulating any of these fields. For example, an attacker could input a username like user; rm -rf / to execute destructive commands.

    Recommendation:

    1. Replace os.system() with a secure SSH library like Paramiko
    2. Implement strict input validation for all user-provided values
    3. Consider using parameterized commands rather than string interpolation
    4. Add proper error handling and logging

    This is a high-priority security issue that should be addressed before deployment.

    Suggested change
    def post(self, request):
    server = request.POST.get("server", "")
    username = request.POST.get("username", "")
    script = request.POST.get("script", "")
    cmd = f'ssh {username}@{server} "bash /opt/scripts/{script}.sh"'
    os.system(cmd)
    def post(self, request):
    server = request.POST.get("server", "")
    username = request.POST.get("username", "")
    script = request.POST.get("script", "")
    # Input validation
    if not all([server, username, script]) or not re.match(r'^[a-zA-Z0-9_-]+$', script):
    return HttpResponse("Invalid input parameters", status=400)
    try:
    # Use paramiko for secure SSH connection
    import paramiko
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # Connect with timeout
    client.connect(hostname=server, username=username, timeout=10)
    # Execute command securely
    command = f"bash /opt/scripts/{script}.sh"
    stdin, stdout, stderr = client.exec_command(command)
    # Get command output
    result = stdout.read().decode('utf-8')
    error = stderr.read().decode('utf-8')
    # Close connection
    client.close()
    if error:
    logger.error(f"Script execution error: {error}")
    return HttpResponse(f"Error executing script: {error}", status=500)
    return HttpResponse(result)
    except Exception as e:
    logger.error(f"SSH connection error: {str(e)}")
    return HttpResponse(f"Connection error: {str(e)}", status=500)

    Spotted by Diamond

    Is this helpful? React 👍 or 👎 to let us know.

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    1 participant