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

File manager exception fix #2229

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

Conversation

KesterTan
Copy link
Contributor

Description

This PR fixes the routing when a user is not allowed to access a path. This also adds unit tests which tests this functionality for this fix.

Resolves #2228

How Has This Been Tested?

  • Create a course and assign a student to that course
  • Navigate to that course in the file manager and copy the link
  • Sign in as a student using dev login and try to access the link
  • Note that you will not be able to see anything in that path and note the flash[:error]
  • Run the new unit tests: rake spec SPEC=./spec/controllers/file_manager_controller_spec.rb and make sure that everything passes

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • I have run rubocop and erblint for style check. If you haven't, run overcommit --install && overcommit --sign to use pre-commit hook for linting
  • My change requires a change to the documentation, which is located at Autolab Docs
  • I have updated the documentation accordingly, included in this PR

Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

💤 Files selected but had no reviewable changes (1)
  • spec/fixtures/files/test_file.txt

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

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in the pull request involve modifications to the FileManagerController to enhance error handling and authorization checks for file management actions. Key methods such as index, delete, rename, download_tar, and upload_file have been updated to include authorization checks, ensuring unauthorized users are redirected to the file manager index with an appropriate flash error message. Additionally, the test suite for the controller has been expanded to include shared examples for unauthorized access scenarios, improving coverage for various actions.

Changes

File Change Summary
app/controllers/file_manager_controller.rb Enhanced error handling and authorization checks in index, delete, rename, download_tar, and upload_file methods.
spec/controllers/file_manager_controller_spec.rb Added shared examples for unauthorized access tests and modified existing tests for various actions to include authorization checks.

Assessment against linked issues

Objective Addressed Explanation
Ensure users are redirected to the index page if not authorized (2228)
Prevent unauthorized access to file management actions (2228)

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

@KesterTan KesterTan requested review from a team and jlge and removed request for a team October 4, 2024 18:46
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: 10

🧹 Outside diff range and nitpick comments (1)
spec/controllers/file_manager_controller_spec.rb (1)

164-164: Redundant sign_in calls within test examples

In several test examples (lines 164, 221, 278, 284, 351, and 358), sign_in is called inside the test block even though the user is already signed in within the before(:each) block. This is unnecessary and can be removed to clean up the tests.

Consider removing the redundant sign_in calls:

-        sign_in(instructor)

Also applies to: 221-221, 278-278, 284-284, 351-351, 358-358

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between be48fe4 and 59f9684.

📒 Files selected for processing (2)
  • app/controllers/file_manager_controller.rb (5 hunks)
  • spec/controllers/file_manager_controller_spec.rb (2 hunks)
🔇 Additional comments (2)
spec/controllers/file_manager_controller_spec.rb (2)

26-33: Well-defined shared example for unauthorized access

The unauthorized_access shared example is correctly implemented. It enhances test coverage by ensuring unauthorized access scenarios are consistently tested across different contexts.


352-352: ⚠️ Potential issue

Verify correctness of constructed path parameters

At lines 352 and 359, the path parameter in get :download_tar includes "autopopulated/test/#{dir_path}" and "autopopulated/test/#{file_path}". Ensure that these paths are correctly constructed and correspond to the actual file system paths used in the application.

Run the following script to check the constructed paths:

Also applies to: 359-359

Comment on lines +57 to +65
if check_instructor(absolute_path)
parent = absolute_path.parent
raise "Unable to delete courses in the root directory." if parent == BASE_DIRECTORY

FileUtils.rm_rf(absolute_path)
FileUtils.rm_rf(absolute_path)
else
flash[:error] = "You are not authorized to delete this"
redirect_to file_manager_index_path
end
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

Refactor Authorization Checks to Avoid Duplication

The authorization check if check_instructor(absolute_path) is repeated across multiple actions. To enhance maintainability and adhere to the DRY (Don't Repeat Yourself) principle, consider using a before_action filter.

Implement a before_action callback:

before_action :authorize_instructor!, only: [:delete]

private

def authorize_instructor!
  unless check_instructor(absolute_path)
    flash[:error] = "You are not authorized to perform this action"
    redirect_to file_manager_index_path and return
  end
end

Comment on lines +107 to +136
if check_instructor(absolute_path)
if File.directory?(absolute_path)
tar_stream = StringIO.new("")
Gem::Package::TarWriter.new(tar_stream) do |tar|
Dir[File.join(absolute_path.to_s, '**', '**')].each do |file|
mode = File.stat(file).mode
relative_path = file.sub(%r{^#{Regexp.escape(absolute_path.to_s)}/?}, '')
if File.directory?(file)
tar.mkdir relative_path, mode
else
tar.add_file relative_path, mode do |tar_file|
File.open(file, "rb") { |f| tar_file.write f.read }
end
end
end
end
tar_stream.rewind
tar_stream.close
send_data tar_stream.string.force_encoding("binary"),
filename: "file_manager.tar",
type: "application/x-tar",
disposition: "attachment"
else
send_file(absolute_path,
filename: File.basename(absolute_path),
disposition: 'attachment')
end
tar_stream.rewind
tar_stream.close
send_data tar_stream.string.force_encoding("binary"),
filename: "file_manager.tar",
type: "application/x-tar",
disposition: "attachment"
else
send_file(absolute_path,
filename: File.basename(absolute_path),
disposition: 'attachment')
flash[:error] = "You are not authorized to download atttachments at this path"
redirect_to file_manager_index_path
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

Extract File Download Logic to Improve Readability

The code for downloading tar files contains nested logic that can be difficult to read and maintain. Consider extracting the file download and tar creation logic into separate private methods.

Refactor the code as follows:

def download_tar
  path = params[:path]&.split("/")&.drop(2)&.join("/")
  path = CGI.unescape(path)
  absolute_path = check_path_exist(path)

  if check_instructor(absolute_path)
    if File.directory?(absolute_path)
      send_tarball(absolute_path)
    else
      send_file_download(absolute_path)
    end
  else
    flash[:error] = "You are not authorized to download attachments at this path"
    redirect_to file_manager_index_path, status: :forbidden
  end
end

private

def send_tarball(absolute_path)
  tar_stream = StringIO.new("")
  Gem::Package::TarWriter.new(tar_stream) do |tar|
    Dir[File.join(absolute_path.to_s, '**', '**')].each do |file|
      mode = File.stat(file).mode
      relative_path = file.sub(%r{^#{Regexp.escape(absolute_path.to_s)}/?}, '')
      if File.directory?(file)
        tar.mkdir relative_path, mode
      else
        tar.add_file relative_path, mode do |tar_file|
          File.open(file, "rb") { |f| tar_file.write f.read }
        end
      end
    end
  end
  tar_stream.rewind
  tar_stream.close
  send_data tar_stream.string.force_encoding("binary"),
            filename: "file_manager.tar",
            type: "application/x-tar",
            disposition: "attachment"
end

def send_file_download(absolute_path)
  send_file(absolute_path,
            filename: File.basename(absolute_path),
            disposition: 'attachment')
end

Comment on lines +135 to +136
flash[:error] = "You are not authorized to download atttachments at this path"
redirect_to file_manager_index_path
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

Correct Typographical Error in Error Message

There's a typo in the error message: "You are not authorized to download atttachments at this path."

Correct the misspelled word:

 flash[:error] = "You are not authorized to download atttachments at this path"
+flash[:error] = "You are not authorized to download attachments at this path"
📝 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
flash[:error] = "You are not authorized to download atttachments at this path"
redirect_to file_manager_index_path
flash[:error] = "You are not authorized to download attachments at this path"
redirect_to file_manager_index_path

Comment on lines +174 to +176
else
flash[:error] = "You are not authorized to upload files at this path"
redirect_to file_manager_index_path
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

Ensure Method Execution Halts After Redirect

After calling redirect_to, the method continues execution unless explicitly halted. This might lead to unexpected behavior or errors.

Add and return to halt execution:

 else
   flash[:error] = "You are not authorized to upload files at this path"
-  redirect_to file_manager_index_path
+  redirect_to file_manager_index_path and return
 end
📝 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
else
flash[:error] = "You are not authorized to upload files at this path"
redirect_to file_manager_index_path
else
flash[:error] = "You are not authorized to upload files at this path"
redirect_to file_manager_index_path and return

Comment on lines +45 to +47
else
flash[:error] = "You are not authorized to view this path"
redirect_to file_manager_index_path
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

Consider Using Proper HTTP Status Code for Unauthorized Access

When a user is not authorized to view a path, it's advisable to return a 403 Forbidden HTTP status code to clearly communicate the nature of the error.

Update the redirect to include the status:

 else
   flash[:error] = "You are not authorized to view this path"
-  redirect_to file_manager_index_path
+  redirect_to file_manager_index_path, status: :forbidden
📝 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
else
flash[:error] = "You are not authorized to view this path"
redirect_to file_manager_index_path
else
flash[:error] = "You are not authorized to view this path"
redirect_to file_manager_index_path, status: :forbidden

Comment on lines +95 to +97
else
flash[:error] = "You are not authorized to rename this path"
redirect_to file_manager_index_path
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

Consistent Use of HTTP Status Codes for Unauthorized Actions

For consistency and better client-side error handling, consider returning a 403 Forbidden status code when a user is not authorized to rename a path.

Modify the redirect to include the status:

 else
   flash[:error] = "You are not authorized to rename this path"
-  redirect_to file_manager_index_path
+  redirect_to file_manager_index_path, status: :forbidden
📝 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
else
flash[:error] = "You are not authorized to rename this path"
redirect_to file_manager_index_path
else
flash[:error] = "You are not authorized to rename this path"
redirect_to file_manager_index_path, status: :forbidden

get :download_tar, params: { path: '' }
expect(response).to redirect_to(file_manager_index_path)
expect(flash[:error]).to eq("You are not authorized to download atttachments at this path")
end
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

Spelling error in flash error message

The error message in lines 369, 395, and 401 contains a typo: "atttachments" should be "attachments".

Correct the spelling in the error messages:

-        expect(flash[:error]).to eq("You are not authorized to download atttachments at this path")
+        expect(flash[:error]).to eq("You are not authorized to download attachments at this path")

Also applies to: 395-395, 401-401

end

it "renames the file successfully" do
sign_in(:instructor)
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

Incorrect argument in sign_in method

At line 221, sign_in(:instructor) uses a symbol :instructor instead of the variable instructor. This could lead to authentication issues in the test.

Update the sign_in method to use the instructor variable:

-        sign_in(:instructor)
+        sign_in(instructor)
📝 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
sign_in(:instructor)
sign_in(instructor)

sign_in(:instructor)
put :rename, params: { relative_path: file_path, new_name:, path: file_path }
expect(flash[:success]).to eq("Successfully renamed file to #{new_name}")
expect(File.exist?(File.join(@base_dir, course.name, new_name))).to be_truthy
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

Undefined variable course used in file path

In line 224, course.name is used, but course is not defined in this context. The course variable is referenced as @course elsewhere in the code.

Modify the code to use @course.name:

-        expect(File.exist?(File.join(@base_dir, course.name, new_name))).to be_truthy
+        expect(File.exist?(File.join(@base_dir, @course.name, new_name))).to be_truthy
📝 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
expect(File.exist?(File.join(@base_dir, course.name, new_name))).to be_truthy
expect(File.exist?(File.join(@base_dir, @course.name, new_name))).to be_truthy

Comment on lines +116 to +139
context "when user is not an instructor of the course" do
let(:unauthorized_path) { "#{@course.name}/secret_folder" }
let!(:instructor) { instructor_user }

before(:each) do
sign_in(instructor)
# Set up the BASE_DIRECTORY and create the course directory
@base_dir = Dir.mktmpdir
stub_const('FileManagerController::BASE_DIRECTORY', Pathname.new(@base_dir))
FileUtils.mkdir_p(File.join(@base_dir, unauthorized_path))
# Ensure that the controller uses the modified BASE_DIRECTORY
allow(FileManagerController).to receive(:const_get)
.with(:BASE_DIRECTORY)
.and_return(Pathname.new(@base_dir))
end

let!(:u) { student_user }
it_behaves_like "unauthorized_access"

after(:each) do
delete_course_files(course_hash[:course])
end
end
end
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

Potential confusion with user sign-in in the context

In the context "when user is not an instructor of the course", the before(:each) block at line 121 signs in the instructor, but the test is meant to simulate a student attempting unauthorized access. At line 132, u is set to student_user, and the shared example likely uses u for the tests.

Adjust the before block to sign in u instead of instructor to reflect the student user's perspective:

-      before(:each) do
-        sign_in(instructor)
+      before(:each) do
+        sign_in(u)
📝 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
context "when user is not an instructor of the course" do
let(:unauthorized_path) { "#{@course.name}/secret_folder" }
let!(:instructor) { instructor_user }
before(:each) do
sign_in(instructor)
# Set up the BASE_DIRECTORY and create the course directory
@base_dir = Dir.mktmpdir
stub_const('FileManagerController::BASE_DIRECTORY', Pathname.new(@base_dir))
FileUtils.mkdir_p(File.join(@base_dir, unauthorized_path))
# Ensure that the controller uses the modified BASE_DIRECTORY
allow(FileManagerController).to receive(:const_get)
.with(:BASE_DIRECTORY)
.and_return(Pathname.new(@base_dir))
end
let!(:u) { student_user }
it_behaves_like "unauthorized_access"
after(:each) do
delete_course_files(course_hash[:course])
end
end
end
context "when user is not an instructor of the course" do
let(:unauthorized_path) { "#{@course.name}/secret_folder" }
let!(:instructor) { instructor_user }
before(:each) do
sign_in(u)
# Set up the BASE_DIRECTORY and create the course directory
@base_dir = Dir.mktmpdir
stub_const('FileManagerController::BASE_DIRECTORY', Pathname.new(@base_dir))
FileUtils.mkdir_p(File.join(@base_dir, unauthorized_path))
# Ensure that the controller uses the modified BASE_DIRECTORY
allow(FileManagerController).to receive(:const_get)
.with(:BASE_DIRECTORY)
.and_return(Pathname.new(@base_dir))
end
let!(:u) { student_user }
it_behaves_like "unauthorized_access"
after(:each) do
delete_course_files(course_hash[:course])
end
end
end

Copy link
Contributor

@jlge jlge left a comment

Choose a reason for hiding this comment

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

When I login as a student user and access the file_manager path, it shows the base screen, but no error flash is displayed.
image
I think a more ideal behavior would be to redirect back to the Autolab homepage and flash the "You are not authorized to view this page." message there. Also when an unauthorized user views the file manager, they can still press the "create folder" and "upload files" buttons which I know don't work but I think it's unideal, so this can be prevented by redirecting out to a different page.

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.

Fix File Manager Authentication and Add File Manager Tests
2 participants