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

Garde #259

Merged
merged 2 commits into from
Jun 12, 2024
Merged

Garde #259

merged 2 commits into from
Jun 12, 2024

Conversation

freedit-dev
Copy link
Member

@freedit-dev freedit-dev commented Jun 12, 2024

Summary by CodeRabbit

  • Dependencies

    • Updated dependencies: askama_axum, axum-extra, cached, reqwest, ring, webpki-roots.
    • Added new dependencies: axum_garde, garde.
  • New Features

    • Introduced garde for form validation, replacing validator.
  • Refactor

    • Replaced askama::Template with askama_axum::Template across multiple controllers.
    • Updated form validation handling from ValidatedForm to WithValidation.
    • Adjusted form data extraction methods in controller functions.
  • Bug Fixes

    • Removed redundant and unused imports to streamline codebase.
  • Chores

    • Updated Cargo.toml to reflect new and updated dependencies.

Copy link
Contributor

coderabbitai bot commented Jun 12, 2024

Walkthrough

This update focuses on enhancing form validation and template handling across the codebase. Dependencies like askama_axum and garde were integrated, replacing older libraries (askama and validator). The changes streamline form validation processes, improve template rendering, and ensure more robust and efficient handling of form data.

Changes

File(s) Change Summary
Cargo.toml Added and updated dependencies: askama_axum, axum_garde, garde, reqwest, etc.
src/controller/admin.rs, .../feed.rs, .../inn.rs Updated imports and function signatures to use askama_axum and garde for validation.
src/controller/message.rs, .../notification.rs, .../solo.rs, .../tantivy.rs, .../upload.rs, .../user.rs Replaced askama::Template with askama_axum::{into_response, Template}.
src/controller/meta_handler.rs Refactored to remove ValidatedForm and unused imports, restructured into_response.
src/controller/mod.rs Updated FormPost and SiteConfig structs to use garde for validation.
src/error.rs Replaced validator::ValidationErrors with garde::Error in AppError.
src/main.rs Changed GLOBAL static variable declaration to use tikv_jemallocator::Jemalloc.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Controller
    participant Validator
    participant Renderer

    User ->> Controller: Submit Form
    Controller ->> Validator: Validate Form Data
    Validator -->> Controller: Validation Result
    Controller ->> Renderer: Render Response
    Renderer -->> User: Display Result
Loading

Poem

In the code where templates lie,
New dependencies reach the sky,
Validation's now a smoother ride,
With garde and askama_axum by our side.
Forms and data, clean and neat,
In Rust, we've made a feat!
🌟🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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.

@freedit-dev freedit-dev merged commit 85ba7b9 into main Jun 12, 2024
6 checks passed
@freedit-dev freedit-dev deleted the garde branch June 12, 2024 16:23
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: 3

Outside diff range and nitpick comments (1)
src/controller/mod.rs (1)

457-488: The use of garde for validation in SiteConfig is well-implemented. However, consider adding comments to explain why certain fields like captcha_difficulty and captcha_name are skipped from validation. This will help maintain clarity and ensure future maintainers understand the validation strategy.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b8d47b1 and 73377f2.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (14)
  • Cargo.toml (3 hunks)
  • src/controller/admin.rs (3 hunks)
  • src/controller/feed.rs (4 hunks)
  • src/controller/inn.rs (8 hunks)
  • src/controller/message.rs (2 hunks)
  • src/controller/meta_handler.rs (2 hunks)
  • src/controller/mod.rs (3 hunks)
  • src/controller/notification.rs (1 hunks)
  • src/controller/solo.rs (3 hunks)
  • src/controller/tantivy.rs (2 hunks)
  • src/controller/upload.rs (1 hunks)
  • src/controller/user.rs (9 hunks)
  • src/error.rs (1 hunks)
  • src/main.rs (1 hunks)
Files skipped from review due to trivial changes (4)
  • src/controller/meta_handler.rs
  • src/controller/notification.rs
  • src/controller/tantivy.rs
  • src/controller/upload.rs
Additional comments not posted (25)
src/error.rs (1)

49-49: The addition of ValidationError using garde::Error aligns with the migration from validator to garde. Ensure that all parts of the application that handle validation errors are updated to handle this new error type.

Cargo.toml (1)

10-10: The updates and additions to the dependencies are consistent with the PR's objectives. Ensure to verify the compatibility of these new versions with the existing codebase and check for any potential conflicts or deprecated features.

Also applies to: 13-14, 17-17, 22-22, 36-37, 53-53

src/main.rs (1)

17-17: The update to use tikv_jemallocator::Jemalloc for the global allocator is a good improvement for memory management. Recommend thorough testing to ensure there are no performance regressions or issues in different deployment environments.

src/controller/message.rs (1)

1-1: The update to use askama_axum from askama for template handling aligns with the PR's objectives to enhance integration with axum. Ensure that all templates are correctly migrated and tested with the new library to prevent runtime issues.

Also applies to: 14-14

src/controller/mod.rs (1)

392-402: The use of garde::skip for fields like iid, is_draft, and delete_draft in FormPost is appropriate as these fields likely do not need validation. However, ensure that skipping validation on these fields does not introduce any security or logical issues, especially in contexts where these fields are critical.

src/controller/admin.rs (4)

5-5: The update to use PageData and ParamsPage from meta_handler without the previously used imports reflects a cleaner and more focused import strategy. This change should help reduce namespace clutter and potential conflicts.


14-18: Switching to askama_axum for template handling aligns with the broader refactoring to use axum frameworks more extensively. Ensure that the into_response function is adequately tested with askama_axum to handle edge cases in template rendering.


21-21: The introduction of WithValidation from axum_garde is a significant change. It's crucial to ensure that all forms now using WithValidation are correctly handling the new validation logic, especially in error handling scenarios.

Verification successful

The search results indicate that error handling is present in the files where WithValidation is used. The error handling logic involves various custom errors like AppError::NonLogin, AppError::Unauthorized, and others, which suggests that validation errors are being managed appropriately.

  • src/controller/admin.rs
  • src/controller/inn.rs
  • src/controller/solo.rs
  • src/controller/user.rs

These files contain instances of WithValidation and have corresponding error handling logic.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all forms using `WithValidation` handle validation errors correctly.

# Test: Search for error handling logic related to `WithValidation`.
rg --type rust $'WithValidation.*Err'

Length of output: 38



Script:

#!/bin/bash
# Description: Identify all instances where `WithValidation` is used and inspect their error handling.

# Step 1: Find all instances of `WithValidation`.
rg --type rust 'WithValidation' > with_validation_instances.txt

# Step 2: Check for error handling logic in files containing `WithValidation`.
while IFS= read -r file; do
  echo "Checking error handling in $file"
  rg --type rust 'Err' "$file"
done < <(cut -d: -f1 with_validation_instances.txt | sort | uniq)

Length of output: 179



Script:

#!/bin/bash
# Description: Identify all instances where `WithValidation` is used and inspect their error handling.

# Step 1: Find all instances of `WithValidation`.
rg --type rust 'WithValidation' > with_validation_instances.txt

# Step 2: Check for error handling logic in files containing `WithValidation`.
for file in $(cut -d: -f1 with_validation_instances.txt | sort | uniq); do
  echo "Checking error handling in $file"
  rg --type rust 'Err' "$file"
done

Length of output: 12555


348-356: The method admin_post now uses WithValidation for form handling, which is a good use of the new validation framework. However, ensure that the custom regex validation and HTML cleaning logic are robust against all forms of input, especially in terms of security considerations like XSS and injection attacks.

src/controller/solo.rs (1)

15-15: Updated imports to use askama_axum and axum_garde are correctly aligned with the PR objectives.

Also applies to: 25-25, 27-27

src/controller/feed.rs (1)

17-17: Updated imports to use askama_axum and garde::Validate are correctly aligned with the PR objectives.

Also applies to: 29-29

src/controller/user.rs (9)

16-16: Updated imports and validation handling align with the PR's objectives.

Also applies to: 23-23, 28-28


730-730: The WithValidation wrapper is used for form data in user_setting_post. This is a good use of the new validation framework. Ensure that all fields are appropriately validated before they are processed.


771-775: In FormPassword, the old_password field is correctly marked to skip validation, which is appropriate since it's used for verification only. The password and password2 fields are set to match and have a minimum length, which enhances security.


782-782: The WithValidation wrapper is used in user_password_post to ensure that the password change request is properly validated. This is a crucial security feature.


865-871: The FormSignup struct uses garde::Validate for validation. The username and password fields are correctly annotated to ensure they meet the specified constraints. The password2 field is set to match the password field, which is a good practice for user registration forms.


923-923: The WithValidation wrapper is used in signup_post to ensure that the signup form data is properly validated. This is essential for maintaining data integrity and security during user registration.


1006-1006: The FormRecoverySet struct and its usage in user_recovery_code are correctly set up to handle password recovery securely. The password field is validated for minimum length, which is crucial for security.

Also applies to: 1013-1013


585-591: The FormUser struct has been updated to use garde::Validate for field validation. Ensure that the home_page field, which is marked to skip validation, is handled appropriately in the logic to prevent any unintended side effects.


672-678: The FormReset struct uses garde::Validate for validation. The password and password2 fields are correctly annotated to ensure they match and meet minimum length requirements. However, ensure that the matches directive is correctly implemented in the garde crate as it is a critical security feature.

src/controller/inn.rs (5)

23-23: Updated import statements to use askama_axum and axum_garde instead of askama and validator. This aligns with the project-wide changes to use these libraries for template rendering and form validation.

Also applies to: 30-30, 41-41, 45-45


125-137: Refactored FormInn struct to use garde::Validate annotations. The use of #[garde(skip)] on certain fields like inn_type, early_birds, and limit_edit_seconds is appropriate, as these fields likely do not require validation based on their nature or context.


1765-1765: The FormComment struct and comment_post function have been updated to use garde::Validate for validation. This is a good use of the new validation library to ensure data integrity.

Also applies to: 1773-1773


1915-1915: The preview function now uses WithValidation for handling input validation. This is a good practice to ensure that the content being previewed adheres to the defined constraints.


147-147: The change from ValidatedForm to WithValidation in the function signature for mod_inn_post is consistent with the new validation approach using axum_garde. Ensure that all upstream calls to this function are updated to handle the new form validation wrapper.

Comment on lines +35 to +39
#[garde(length(min = 1, max = 1000))]
content: String,
#[garde(skip)]
solo_type: u32,
#[garde(skip)]
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Skipping validation for solo_type and reply_to is not safe due to their critical roles in determining access, behavior, and linking entities. Ensure these fields are validated or inherently safe.

  • solo_type is used in conditional checks and conversions, impacting access and behavior.
  • reply_to is used for parsing and formatting, linking or referencing other entities.
Analysis chain

The use of garde::Validate and garde attributes for validation is consistent with the PR's refactoring goals. However, ensure that skipping validation for solo_type and reply_to is intentional and secure, as it might expose the application to invalid data processing if these fields are critical.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify if skipping validation for `solo_type` and `reply_to` is safe.
# Test: Search for usage of `solo_type` and `reply_to` in the codebase. Expect: Proper handling or non-critical usage.
rg --type rust $'solo_type|reply_to'

Length of output: 3892

@@ -377,7 +381,7 @@ fn get_solos_by_uids(
/// `POST /solo/user/:uid` solo page
pub(crate) async fn solo_post(
cookie: Option<TypedHeader<Cookie>>,
ValidatedForm(input): ValidatedForm<FormSolo>,
WithValidation(input): WithValidation<Form<FormSolo>>,
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The search results indicate that there are no direct test cases involving WithValidation in the repository. This suggests that the new form handling logic might not be thoroughly tested, especially for edge cases where the form might be invalid.

  • Ensure that the new form handling logic using WithValidation is thoroughly tested.
  • Add test cases that specifically cover edge cases and invalid form submissions.
Analysis chain

The transition to WithValidation for form handling is well implemented. The use of input.into_inner() to extract validated data is a good practice. Ensure that the new form handling logic is thoroughly tested, especially for edge cases where the form might be invalid.

Also applies to: 403-403

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify comprehensive testing of form handling.
# Test: Search for test cases involving `WithValidation`. Expect: Adequate test coverage.
rg --type rust $'WithValidation' -A 10 | rg 'test'

Length of output: 47



Script:

#!/bin/bash
# Step 1: Find all test files in the repository
fd --type f --name '*test*.rs'

# Step 2: Search for test cases that might involve form validation
rg --type rust 'test' -A 10 | rg 'form|validation|WithValidation'

Length of output: 349



Script:

#!/bin/bash
# Step 1: Find all test files in the repository using the correct fd syntax
fd --type f 'test'

# Step 2: Search for test cases that might involve form validation
rg --type rust 'test' -A 10 | rg 'form|validation|WithValidation'

Length of output: 84



Script:

#!/bin/bash
# Step 1: Find all test functions in the repository
rg --type rust 'fn test_' -A 10

# Step 2: Search for references to `WithValidation` within these test functions
rg --type rust 'WithValidation'

Length of output: 2063

Comment on lines +472 to +478
#[garde(length(max = 256))]
url: String,
#[validate(length(max = 256))]
#[garde(length(max = 256))]
folder: String,
#[validate(length(max = 256))]
#[garde(length(max = 256))]
new_folder: String,
#[garde(skip)]
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The is_public field is used in various parts of the codebase, including critical sections where it determines access control and visibility of feeds. Given its importance, skipping validation for this field could indeed pose a security risk if not handled properly elsewhere.

  • Locations to review:
    • src/controller/feed.rs: Multiple instances where is_public is used to control access and visibility.
    • src/controller/admin.rs: Usage in administrative functions.

Given the critical nature of is_public, it is essential to ensure that its value is correctly set and validated to prevent unauthorized access or visibility issues.

Analysis chain

The use of garde::Validate for form validation in FormFeedAdd is consistent with the PR's refactoring goals. However, ensure that the is_public field's validation is intentionally skipped. This could be a security concern if the field is critical and expects specific values.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify if skipping validation for `is_public` is safe.
# Test: Search for usage of `is_public` in the codebase. Expect: Proper handling or non-critical usage.
rg --type rust $'is_public'

Length of output: 838



Script:

#!/bin/bash
# Description: Gather more context around the usage of `is_public` in the codebase.
# Test: Extract lines around the usage of `is_public` to understand its context.
rg --type rust -A 5 -B 5 'is_public'

Length of output: 5166

@coderabbitai coderabbitai bot mentioned this pull request Jan 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant