Skip to content
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

Validate file path in serve_docs function to enhance security #52

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

Zingzy
Copy link
Member

@Zingzy Zingzy commented Nov 28, 2024

This PR addresses Issue #47

Summary by Sourcery

Bug Fixes:

  • Fix a potential security issue by validating the file path in the serve_docs function to prevent invalid or malicious file paths.

@Zingzy Zingzy added backend Changes related to Backand/API Security Issues related to Security labels Nov 28, 2024
@Zingzy Zingzy linked an issue Nov 28, 2024 that may be closed by this pull request
1 task
Copy link
Contributor

sourcery-ai bot commented Nov 28, 2024

Reviewer's Guide by Sourcery

The PR implements a security enhancement for the serve_docs function by adding input validation for file paths. It uses regex pattern matching to ensure only alphanumeric characters, underscores, and hyphens are allowed in the file path parameter.

Sequence diagram for serve_docs function with file path validation

sequenceDiagram
    participant User
    participant Server
    User->>Server: Request serve_docs(file_path)
    Server->>Server: Validate file_path with regex
    alt Valid file_path
        Server->>Server: Check if file exists
        alt File exists
            Server->>User: Render requested document
        else File not found
            Server->>User: Render error.html
        end
    else Invalid file_path
        Server->>User: Render error.html
    end
Loading

File-Level Changes

Change Details Files
Added input validation for file paths using regex pattern matching
  • Implemented regex pattern validation to restrict file paths to alphanumeric characters, underscores, and hyphens
  • Added specific error handling by replacing generic except clause with Exception
  • Added re module import for regex functionality
blueprints/docs.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @Zingzy - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The file path validation regex is too restrictive and doesn't support subdirectories. Consider using a more robust path validation approach that can safely handle nested paths while preventing traversal attacks.
  • Catching all exceptions generically can mask security issues. Consider catching and handling specific exceptions (ValueError, FileNotFoundError) separately and logging them appropriately.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟡 Security: 1 issue found
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -16,10 +17,13 @@ def serve_docs_index():
@limiter.exempt
def serve_docs(file_path):
try:
# Validate file_path
if not re.match(r'^[a-zA-Z0-9_-]+$', file_path):
raise ValueError("Invalid file path")
if not os.path.exists(f"templates/docs/{file_path}.html"):
Copy link
Contributor

Choose a reason for hiding this comment

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

🚨 issue (security): Use os.path.join() instead of f-string concatenation for file paths to prevent path traversal vulnerabilities

String concatenation with file paths can be dangerous. Use os.path.join('templates', 'docs', f'{file_path}.html') for safer path handling.

if not os.path.exists(f"templates/docs/{file_path}.html"):
raise FileNotFoundError
return render_template(f"docs/{file_path}.html", host_url=request.host_url)
except:
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (bug_risk): Consider catching specific exceptions instead of generic Exception

Catching specific exceptions (ValueError, FileNotFoundError) would make error handling more predictable and prevent masking of unexpected errors.

    except (FileNotFoundError, TemplateNotFound):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend Changes related to Backand/API Security Issues related to Security
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Fix code scanning alert - Uncontrolled data used in path expression
1 participant