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

Add file size restriction for legacy API #561

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

Conversation

Ceredron
Copy link
Collaborator

@Ceredron Ceredron commented Oct 28, 2024

Description

Add file size restriction for legacy API. Same as A2 file size restriction.

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • New Features

    • Added a ContentLength property to enhance file upload information.
    • Introduced a method to determine maximum upload size based on resource configuration.
  • Bug Fixes

    • Improved file size validation logic to streamline processing.
  • Tests

    • Added a test for validating file upload size limits, ensuring proper error handling for oversized files.
    • Introduced a FakeFileStream class for simulating file streams in tests.

Copy link

coderabbitai bot commented Oct 28, 2024

📝 Walkthrough

Walkthrough

The pull request introduces changes to the LegacyFileController and related components in the Altinn Broker API. Key modifications include the addition of a ContentLength property in the UploadFileRequest object within the UploadFileStreamed method. The UploadFileHandler class now includes a private method for determining maximum upload sizes, enhancing file size validation. A new FakeFileStream class is added for testing, along with a test method in LegacyFileControllerTests to validate behavior when uploading oversized files.

Changes

File Path Change Summary
src/Altinn.Broker.API/Controllers/LegacyFileController.cs Added ContentLength property to UploadFileRequest in UploadFileStreamed method.
src/Altinn.Broker.Application/UploadFile/UploadFileHandler.cs Added private method GetMaxUploadSize(ResourceEntity resource, bool isLegacy) for upload size validation. Updated logic to use this method.
tests/Altinn.Broker.Tests/Helpers/FakeFileStream.cs Introduced FakeFileStream class to simulate file streams for testing, overriding necessary methods and properties.
tests/Altinn.Broker.Tests/LegacyFileControllerTests.cs Added test method UploadTooBigFile_ToLegacyApi_FailsWithValidationError to test oversized file uploads.

Possibly related PRs

  • Fix: Require Download started before Confirmation #559: The changes in the LegacyFileControllerTests class, which include new test methods related to file upload and confirmation processes, are relevant as they may interact with the UploadFileStreamed method in the LegacyFileController, particularly in scenarios involving file size validation and upload handling.

Suggested labels

kind/bug

Suggested reviewers

  • Andreass2

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.

@Ceredron Ceredron marked this pull request as ready for review October 28, 2024 17:52
@Ceredron Ceredron marked this pull request as draft October 28, 2024 17:52
@Ceredron Ceredron added the kind/user-story Used for issues that describes functionality for our users. label Oct 28, 2024
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: 5

🧹 Outside diff range and nitpick comments (4)
tests/Altinn.Broker.Tests/Helpers/FakeFileStream.cs (2)

1-11: Add XML documentation to improve test helper clarity.

Consider adding XML documentation to describe the purpose and usage of this test helper class, which will improve maintainability and help other developers understand how to use it in their tests.

 namespace Altinn.Broker.Tests.Helpers;

+/// <summary>
+/// A fake stream implementation that simulates a file of a specific size for testing purposes.
+/// This helper is particularly useful for testing file size validation scenarios without actual file I/O.
+/// </summary>
 public class FakeFileStream : Stream
 {
     private readonly long _length;
     private long _position;

+    /// <summary>
+    /// Initializes a new instance of the <see cref="FakeFileStream"/> class.
+    /// </summary>
+    /// <param name="length">The total length of the fake stream in bytes.</param>
     public FakeFileStream(long length)
     {
         _length = length;
         _position = 0;
     }

56-58: Add descriptive exception messages.

Consider adding more descriptive exception messages to help developers understand why these operations are not supported.

     public override void Flush() { }
-    public override void SetLength(long value) => throw new NotImplementedException();
-    public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException();
+    public override void SetLength(long value) => throw new NotImplementedException("SetLength is not supported in this read-only test stream");
+    public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException("Write operations are not supported in this read-only test stream");
src/Altinn.Broker.API/Controllers/LegacyFileController.cs (1)

80-81: Add XML documentation for the size restriction.

Since this is a breaking change that adds file size restrictions, it should be documented in the method's XML documentation to inform API consumers.

Add this to the method's XML documentation:

     /// Upload to an initialized file using a binary stream.
     /// </summary>
+    /// <remarks>
+    /// The file size is restricted according to the resource configuration. 
+    /// The Content-Length header is required for all uploads.
+    /// </remarks>
     /// <returns></returns>
tests/Altinn.Broker.Tests/LegacyFileControllerTests.cs (1)

449-469: LGTM with suggestions for improvement!

The test effectively validates the file size restriction for the legacy API. A few suggestions to enhance the test:

  1. Extract the file size limit as a constant for better maintainability
  2. Consider verifying the error message content to ensure the correct validation error is returned

Consider applying these improvements:

+ private const long MAX_FILE_SIZE = 1024 * 1000 * 1000; // 1GB
+ private const long OVERSIZED_FILE = MAX_FILE_SIZE + 1;

 [Fact]
 public async Task UploadTooBigFile_ToLegacyApi_FailsWithValidationError()
 {
     // Initialize
     var initializeFileResponse = await _legacyClient.PostAsJsonAsync("broker/api/legacy/v1/file", FileTransferInitializeExtTestFactory.BasicFileTransfer());
     string onBehalfOfConsumer = FileTransferInitializeExtTestFactory.BasicFileTransfer().Sender;
     Assert.True(initializeFileResponse.IsSuccessStatusCode, await initializeFileResponse.Content.ReadAsStringAsync());
     var fileId = await initializeFileResponse.Content.ReadAsStringAsync();
     var fileAfterInitialize = await _legacyClient.GetFromJsonAsync<LegacyFileOverviewExt>($"broker/api/legacy/v1/file/{fileId}?onBehalfOfConsumer={onBehalfOfConsumer}", _responseSerializerOptions);
     Assert.NotNull(fileAfterInitialize);
     Assert.Equal(LegacyFileStatusExt.Initialized, fileAfterInitialize.FileStatus);

     // Upload
-    var fileSize = 1024 * 1000 * 1000 + 1;
+    var fileSize = OVERSIZED_FILE;
     var content = new FakeFileStream(fileSize);
     var streamContent = new StreamContent(content);
     streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
     streamContent.Headers.ContentLength = fileSize;
     var uploadResponse = await _legacyClient.PostAsync($"broker/api/legacy/v1/file/{fileId}/upload?onBehalfOfConsumer={onBehalfOfConsumer}", streamContent);
     Assert.Equal(HttpStatusCode.BadRequest, uploadResponse.StatusCode);
+    var errorContent = await uploadResponse.Content.ReadAsStringAsync();
+    Assert.Contains("file size exceeds the maximum allowed limit", errorContent.ToLower());
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between dcd05f3 and e7ba180.

📒 Files selected for processing (4)
  • src/Altinn.Broker.API/Controllers/LegacyFileController.cs (1 hunks)
  • src/Altinn.Broker.Application/UploadFile/UploadFileHandler.cs (3 hunks)
  • tests/Altinn.Broker.Tests/Helpers/FakeFileStream.cs (1 hunks)
  • tests/Altinn.Broker.Tests/LegacyFileControllerTests.cs (1 hunks)
🔇 Additional comments (3)
tests/Altinn.Broker.Tests/Helpers/FakeFileStream.cs (1)

13-21: LGTM! Stream properties are correctly implemented.

The properties are properly overridden and their implementations align with the intended read-only behavior of this test helper.

src/Altinn.Broker.Application/UploadFile/UploadFileHandler.cs (1)

54-57: LGTM! File size validation is properly implemented.

The validation is correctly placed before the file upload process begins, ensuring early failure for oversized files.

src/Altinn.Broker.API/Controllers/LegacyFileController.cs (1)

80-81: Verify the impact on existing clients.

The addition of file size restrictions is a breaking change that could affect existing clients of the legacy API.

Let's analyze the potential impact:

Comment on lines +80 to +81
IsLegacy = true,
ContentLength = Request.ContentLength ?? Request.Body.Length
Copy link

@coderabbitai coderabbitai bot Oct 28, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider potential memory issues with Request.Body.Length.

The fallback to Request.Body.Length when Request.ContentLength is null could cause memory issues with large files, as it requires reading the entire stream into memory.

Consider this alternative implementation:

-            IsLegacy = true,
-            ContentLength = Request.ContentLength ?? Request.Body.Length
+            IsLegacy = true,
+            ContentLength = Request.ContentLength ?? 
+                throw new ValidationException("Content-Length header is required for file uploads")
📝 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
IsLegacy = true,
ContentLength = Request.ContentLength ?? Request.Body.Length
IsLegacy = true,
ContentLength = Request.ContentLength ??
throw new ValidationException("Content-Length header is required for file uploads")

Copy link
Collaborator

Choose a reason for hiding this comment

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

Should we consider this or some other error handling?
May be unneccessary if we know all filesizes is smaller

Copy link

Choose a reason for hiding this comment

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

@Andreass2, understood. If we can ensure that all file sizes are small and the Content-Length header is always present, then additional error handling may not be necessary.


✏️ Learnings added
Learnt from: Andreass2
PR: Altinn/altinn-broker#561
File: src/Altinn.Broker.API/Controllers/LegacyFileController.cs:80-81
Timestamp: 2024-10-29T10:43:15.889Z
Learning: In the Altinn Broker API, specifically in `src/Altinn.Broker.API/Controllers/LegacyFileController.cs`, when handling file uploads in the `UploadFileStreamed` method, we can assume that all uploaded files are small and that the `Content-Length` header is always provided. Therefore, additional error handling for missing `Content-Length` is not required.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

All the other comments were a bit stupid, but this one is very valid. I'm inclined to close this Pull Request as this is the Legacy API calling us (and file size is restricted there). Main purpose of this PR was to have it explicit in our code too, but not really worth it if it causes memory issues itself.

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

On the other side, we should require content-length header to be set for the normal upload operation.

@Ceredron Ceredron marked this pull request as ready for review October 29, 2024 09:24
Copy link
Collaborator

@Andreass2 Andreass2 left a comment

Choose a reason for hiding this comment

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

I would look into some of the codeRabbit comments

Comment on lines +80 to +81
IsLegacy = true,
ContentLength = Request.ContentLength ?? Request.Body.Length
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should we consider this or some other error handling?
May be unneccessary if we know all filesizes is smaller

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind/user-story Used for issues that describes functionality for our users.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants