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

feat: allow passing URL as X-Sendfile header value #99

Closed

Conversation

rmikalkenas
Copy link

@rmikalkenas rmikalkenas commented Feb 8, 2024

Reason for This PR

A POC of discussion: https://github.com/orgs/roadrunner-server/discussions/1842
Probably it would be good to abstract if/else block and have some sort of generic struct, but since it's a POC - haven't done it yet

Description of Changes

Allow to pass url as X-Sendfile header value and let roadrunner stream files.
Usage case: backend app generates presigned S3 url and responds with X-Sendfile header, instead of streaming file by itself.

License Acceptance

By submitting this pull request, I confirm that my contribution is made under
the terms of the MIT license.

PR Checklist

[Author TODO: Meet these criteria.]
[Reviewer TODO: Verify that these criteria are met. Request changes if not]

  • All commits in this PR are signed (git commit -s).
  • The reason for this PR is clearly provided (issue no. or explanation).
  • The description of changes is clear and encompassing.
  • Any required documentation changes (code and docs) are included in this PR.
  • Any user-facing changes are mentioned in CHANGELOG.md.
  • All added/changed functionality is tested.

Copy link

coderabbitai bot commented Feb 8, 2024

Walkthrough

The recent update enhances the way our plugin manages file operations. It now discerns between HTTP URLs and local file paths, fetching files over the web or from the local storage accordingly. Furthermore, it introduces smarter buffer handling by adjusting the allocation size based on the file's size, optimizing memory usage and performance.

Changes

File(s) Summary of Changes
plugin.go Updated to differentiate file retrieval between HTTP URLs and local paths, and to adjust buffer sizes based on file size.

🐰✨
In the land of code and byte,
A rabbit hopped with sheer delight.
Files fetched from near and far,
Smarter, faster, here we are!
🌟📁✨

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-tests for this file.
  • 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 tests 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 from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 4

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 6d38e0a and ed3f73c.
Files selected for processing (1)
  • plugin.go (2 hunks)
Additional comments: 1
plugin.go (1)
  • 137-140: Good security practice to prevent directory traversal attacks.

Comment on lines +117 to +160
if strings.HasPrefix(path, "http") {
resp, err := http.Get(path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

f, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()

defer func() {
_ = f.Close()
}()
if resp.StatusCode != http.StatusOK {
http.Error(w, http.StatusText(resp.StatusCode), resp.StatusCode)
return
}

f = resp.Body
size = resp.ContentLength
} else {
// do not allow paths like ../../resource, security
// only specified folder and resources in it
// see: https://lgtm.com/rules/1510366186013/
if strings.Contains(path, "..") {
w.WriteHeader(http.StatusForbidden)
return
}

// check if the file exists
fs, err := os.Stat(path)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}

f, err = os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

defer func() {
_ = f.Close()
}()

size = fs.Size()
}
Copy link

Choose a reason for hiding this comment

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

Consider using http.Client with a timeout instead of http.Get to avoid hanging requests.

- resp, err := http.Get(path)
+ client := &http.Client{Timeout: time.Second * 10}
+ resp, err := client.Get(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.

Suggested change
if strings.HasPrefix(path, "http") {
resp, err := http.Get(path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
f, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
defer func() {
_ = f.Close()
}()
if resp.StatusCode != http.StatusOK {
http.Error(w, http.StatusText(resp.StatusCode), resp.StatusCode)
return
}
f = resp.Body
size = resp.ContentLength
} else {
// do not allow paths like ../../resource, security
// only specified folder and resources in it
// see: https://lgtm.com/rules/1510366186013/
if strings.Contains(path, "..") {
w.WriteHeader(http.StatusForbidden)
return
}
// check if the file exists
fs, err := os.Stat(path)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
f, err = os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer func() {
_ = f.Close()
}()
size = fs.Size()
}
if strings.HasPrefix(path, "http") {
client := &http.Client{Timeout: time.Second * 10}
resp, err := client.Get(path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
http.Error(w, http.StatusText(resp.StatusCode), resp.StatusCode)
return
}
f = resp.Body
size = resp.ContentLength
} else {
// do not allow paths like ../../resource, security
// only specified folder and resources in it
// see: https://lgtm.com/rules/1510366186013/
if strings.Contains(path, "..") {
w.WriteHeader(http.StatusForbidden)
return
}
// check if the file exists
fs, err := os.Stat(path)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
f, err = os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer func() {
_ = f.Close()
}()
size = fs.Size()
}

Comment on lines +143 to +147
fs, err := os.Stat(path)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
Copy link

Choose a reason for hiding this comment

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

Missing error handling for os.Stat to distinguish between different types of errors (e.g., permission issues).

- if err != nil {
+ if os.IsNotExist(err) {
+   http.Error(w, "not found", http.StatusNotFound)
+ } else if err != nil {
+   http.Error(w, err.Error(), http.StatusInternalServerError)
}

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.

Suggested change
fs, err := os.Stat(path)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
fs, err := os.Stat(path)
if os.IsNotExist(err) {
http.Error(w, "not found", http.StatusNotFound)
} else if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}

for {
n, err := f.ReadAt(buf, int64(off))
n, err := f.Read(buf)
Copy link

Choose a reason for hiding this comment

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

Use of goto for control flow is generally discouraged due to readability and maintainability concerns.

- if n > 0 {
-   goto out
- }
+ if n > 0 {
+   _, err = w.Write(buf[:n])
+   if err != nil {
+     p.log.Error("write response", zap.Error(err))
+     return
+   }
+ }

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.

Suggested change
n, err := f.Read(buf)
if n > 0 {
_, err = w.Write(buf[:n])
if err != nil {
p.log.Error("write response", zap.Error(err))
return
}
}

Error handling inside the loop does not account for non-EOF errors properly, potentially leading to silent failures.

- if errors.Is(err, io.EOF) {
+ if err != nil {
+   if !errors.Is(err, io.EOF) {
+     http.Error(w, err.Error(), http.StatusInternalServerError)
+     return
+   }
+   if n > 0 {
+     _, err = w.Write(buf[:n])
+     if err != nil {
+       p.log.Error("write response", zap.Error(err))
+       return
+     }
+   }
+   break
}

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.

Suggested change
n, err := f.Read(buf)
if err != nil {
if !errors.Is(err, io.EOF) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if n > 0 {
_, err = w.Write(buf[:n])
if err != nil {
p.log.Error("write response", zap.Error(err))
return
}
}
break
}

@rustatian rustatian changed the title Allow to pass url as X-Sendfile header value feat: allow passing URL as X-Sendfile header value Feb 8, 2024
@rustatian rustatian self-requested a review February 8, 2024 10:07
@rustatian rustatian added the enhancement New feature or request label Feb 8, 2024
@rustatian
Copy link
Member

Hey @rmikalkenas 👋 Thank you for the PR 👍
Might be it would be better to have a separate plugin with RPC bridge to do that? That way, we would be able to handle these links independently and w/o abusing the headers.
Moreover, if someone would be needed to have some different types of uploads, it would be easy to add a new RPC method.

@rmikalkenas
Copy link
Author

Hey @rmikalkenas 👋 Thank you for the PR 👍 Might be it would be better to have a separate plugin with RPC bridge to do that? That way, we would be able to handle these links independently and w/o abusing the headers. Moreover, if someone would be needed to have some different types of uploads, it would be easy to add a new RPC method.

@rustatian I'm trying to understand how would it work.. Could you elaborate more on your idea?
I agree that maybe separate header and therefore separate plugin could be introduced, but I find it hard to get where the RPC stands in this idea 🤔

@rustatian
Copy link
Member

Sure @rmikalkenas 😃
Here you may find a tutorial about how to create a plugin: link.
You may also reach me in our Discord RR channel if you need help 😃

But, I guess since the payload should be streamed as the response... Not sure now. I mean, is that something you currently need to solve some needs using RR at work?

@rustatian rustatian marked this pull request as draft February 11, 2024 15:52
@rustatian
Copy link
Member

Since we already discussed this functionality, do you @rmikalkenas still need this PR to be opened?

@rustatian rustatian closed this Feb 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: ✅ Done
Development

Successfully merging this pull request may close these issues.

2 participants