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

Lectures: Use attachment name for file downloads #9775

Merged
merged 3 commits into from
Nov 16, 2024

Conversation

SimonEntholzer
Copy link
Contributor

@SimonEntholzer SimonEntholzer commented Nov 13, 2024

Checklist

General

  • I tested all changes and their related features with all corresponding user types on a test server.
  • This is a small issue that I tested locally and was confirmed by another developer on a test server.
  • I chose a title conforming to the naming conventions for pull requests.

Server

  • Important: I implemented the changes with a very good performance and prevented too many (unnecessary) and too complex database calls.
  • I strictly followed the principle of data economy for all database calls.
  • I strictly followed the server coding and design guidelines.
  • I documented the Java code using JavaDoc style.

Motivation and Context

Issue: In #9721 the cryptic attachment text was removed from the filename. Unfortunately, only superficially. When actually saving the file, with Ctrl + S, the cryptic timestamp is still there.
In the URL:
image
But when saving:
image

Description

Fixes this issue, by simply using the defined attachment name.

Steps for Testing

  1. Instructor: upload files to lecture attachments, and to lecture unit attachments.
  2. Download the files (really download it, not just look at the url, but use Ctrl + S / the download button)
    image
  3. Make sure the file name simply is the name specified when creating the attachment.
  4. Please tick the test checkboxes

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2
  • Test - Firefox
  • Test - Chrome
  • Test - Safari

Test Coverage

Screenshots

With the fix:
image
image
image

Summary by CodeRabbit

  • New Features

    • Improved file handling with flexible filename options and enhanced caching behavior for file responses.
    • Streamlined response creation process for file handling.
  • Bug Fixes

    • Adjusted caching settings for specific file response methods to ensure correct behavior.
  • Refactor

    • Simplified method signatures for better clarity and maintainability in the FileResource class.

@SimonEntholzer SimonEntholzer requested a review from a team as a code owner November 13, 2024 22:15
@github-actions github-actions bot added server Pull requests that update Java code. (Added Automatically!) core Pull requests that affect the corresponding module labels Nov 13, 2024
Copy link

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes in this pull request primarily involve modifications to the FileResource class in the src/main/java/de/tum/cit/aet/artemis/core/web directory. The updates focus on the buildFileResponse method, which now accepts optional parameters for filename replacements and caching behavior. This allows for more flexible file handling. Additionally, method calls within getMarkdownFile, getLectureAttachment, and getAttachmentUnitAttachment have been adjusted to reflect these new signatures, enhancing clarity and maintainability in file response generation.

Changes

File Path Change Summary
src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java - Updated buildFileResponse method signatures to include Optional<String> for filename replacement and clarify caching behavior.
- Refactored buildFileResponse to streamline response creation.
- Modified calls to buildFileResponse in getMarkdownFile, getLectureAttachment, and getAttachmentUnitAttachment to accommodate new method signatures.

Possibly related PRs

  • Lectures: Fix lecture unit file attachment names #9721: The changes in this PR involve updating the getLectureAttachment method in the FileResource class to improve filename handling, which directly relates to the modifications made in the main PR regarding file response handling and filename parameters.

Suggested labels

bugfix, ready to merge, server, tests, core, client, lecture

Suggested reviewers

  • JohannesStoehr
  • MaximilianAnzinger
  • pzdr7
  • bassner

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 or @coderabbitai title anywhere in the PR title to generate the title automatically.

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

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

🧹 Outside diff range and nitpick comments (2)
src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java (2)

Line range hint 611-636: Enhance error logging for troubleshooting

While the implementation is robust, the error logging could be more detailed to aid in troubleshooting file download issues.

Consider enhancing the error logging to include more context:

         catch (IOException ex) {
-            log.error("Failed to download file: {} on path: {}", filename, path, ex);
+            log.error("Failed to download file: {} (replaced name: {}) on path: {}", 
+                filename, replaceFilename.orElse("<none>"), path, ex);
             return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
         }

Line range hint 644-651: Consider enhancing path traversal protection

While the current sanitization is good, consider adding additional protection against path traversal attacks.

Consider adding normalized path validation:

     private static void sanitizeFilenameElseThrow(String filename) {
         String sanitizedFileName = FileService.sanitizeFilename(filename);
         if (!sanitizedFileName.equals(filename)) {
             throw new EntityNotFoundException("The filename contains invalid characters. Only characters a-z, A-Z, 0-9, '_', '.' and '-' are allowed!");
         }
+        // Additional protection against path traversal
+        if (!Paths.get(filename).normalize().toString().equals(filename)) {
+            throw new EntityNotFoundException("Invalid filename: potential path traversal detected");
+        }
     }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 383945a and b2723a9.

📒 Files selected for processing (1)
  • src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java (6 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

🔇 Additional comments (2)
src/main/java/de/tum/cit/aet/artemis/core/web/FileResource.java (2)

575-611: LGTM: Well-structured method overloads

The method overloads are well-organized with clear parameter naming and comprehensive documentation. The delegation pattern reduces code duplication.


434-434: LGTM: Improved file download naming

The implementation correctly uses the attachment name for downloads, providing a better user experience with meaningful filenames instead of system-generated ones.

Also applies to: 490-490

Copy link

@sachmii sachmii left a comment

Choose a reason for hiding this comment

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

Tested on TS3, worked fine for regular attachments and attachment units.

Bildschirmfoto 2024-11-13 um 23 45 35

Copy link

@JanaNF JanaNF left a comment

Choose a reason for hiding this comment

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

Manual tested on TS§. Worked as expected

Copy link

@HawKhiem HawKhiem left a comment

Choose a reason for hiding this comment

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

Tested on TS3. The names of attachments and lecture units were displayed correctly

Screenshot 2024-11-13 234655
Screenshot 2024-11-13 234756

Copy link
Member

@BBesrour BBesrour left a comment

Choose a reason for hiding this comment

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

code lgtm

Copy link

@ahbitaqu ahbitaqu left a comment

Choose a reason for hiding this comment

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

[Tested on TS1]
Works as described, couldn't find any issues.
(Might be unrelated but when deploying this PR to TS2, I was unable to login and got an internal server error)

Copy link

@vinceclifford vinceclifford left a comment

Choose a reason for hiding this comment

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

Tested on TS5, works as expected

Copy link

@HanyangXu0508 HanyangXu0508 left a comment

Choose a reason for hiding this comment

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

Tested locally and worked as expected.

Copy link

@sawys777 sawys777 left a comment

Choose a reason for hiding this comment

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

Tested on TS1, everything works as described

@krusche krusche added this to the 7.7.1 milestone Nov 16, 2024
@krusche krusche changed the title Lectures: Fix naming of downloaded files by using attachment name Lectures: Use attachment name for file downloads Nov 16, 2024
@krusche krusche merged commit 0ffa44f into develop Nov 16, 2024
89 of 95 checks passed
@krusche krusche deleted the bugfix/lectures/file-download-use-attachment-name branch November 16, 2024 09:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix core Pull requests that affect the corresponding module ready for review server Pull requests that update Java code. (Added Automatically!)
Projects
Status: Merged
Development

Successfully merging this pull request may close these issues.

10 participants