-
Notifications
You must be signed in to change notification settings - Fork 9
Feat: Implement file handling #93
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
Draft
Crusader99
wants to merge
9
commits into
mdouchement:master
Choose a base branch
from
Crusader99:file-handling
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
84d0589
Feat: Experimental support for file handling
Crusader99 89b164d
Refactor: Encapsulate file handling
Crusader99 86eb6a3
Fix: Handle errors in file-upload
Crusader99 bebfa14
Style: Rewrite comment
Crusader99 10c222a
Chore: Add todo comments to GetFilePath function
Crusader99 74a7e52
Style: Use golang's convention in variable names
Crusader99 8884185
Chore: Use v1valet routes for file-api
Crusader99 ce45445
Fix: Correct error handling for file-api
Crusader99 3ebd92c
Feat: Configurable filesServerUrl
Crusader99 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,190 @@ | ||
| package server | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "encoding/base64" | ||
| "encoding/json" | ||
| "errors" | ||
| "io" | ||
| "io/fs" | ||
| "net/http" | ||
| "os" | ||
| "path/filepath" | ||
|
|
||
| "github.com/gofrs/uuid" | ||
| "github.com/labstack/echo/v4" | ||
| ) | ||
|
|
||
| type files struct{} | ||
|
|
||
| type Resource struct { | ||
| RemoteIdentifier string `json:"remoteIdentifier"` | ||
| } | ||
|
|
||
| func respond(context echo.Context, code int, message string) error { | ||
| success := code < 300 | ||
| return context.JSON(code, echo.Map{ | ||
| "success": success, | ||
| "message": message, | ||
| }) | ||
| } | ||
|
|
||
| func readValetToken(context echo.Context) (*ValetToken, error) { | ||
| valetTokenBase64 := context.Request().Header.Get("x-valet-token") | ||
| valetTokenBytes, err := base64.StdEncoding.DecodeString(valetTokenBase64) | ||
| if err != nil { | ||
| return nil, errors.New("Unable to parse base64 valet token") | ||
| } | ||
| valetTokenJson := string(valetTokenBytes) | ||
| var token ValetToken | ||
| if err := json.Unmarshal([]byte(valetTokenJson), &token); err != nil { | ||
| return nil, errors.New("Unable to parse json valet token") | ||
| } | ||
| return &token, nil | ||
| } | ||
|
|
||
| type ValetRequestParams struct { | ||
| Operation string `json:"operation"` | ||
| Resources []Resource | ||
| } | ||
|
|
||
| type ValetToken struct { | ||
| Authorization string `json:"authorization"` | ||
| FileID string `json:"fileId"` | ||
| } | ||
|
|
||
| func (token *ValetToken) getFilePath() (*string, error) { | ||
| id, err := uuid.FromString(token.FileID) | ||
| if err != nil { | ||
| return nil, errors.New("Unable to parse json valet token") | ||
| } else if !fs.ValidPath(id.String()) { | ||
| return nil, errors.New("Invalid path") | ||
| } | ||
| // TODO: Allow custom path in config | ||
| // TODO: Subfolders for each user (Compatible format with official server) | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. go1.24 added https://pkg.go.dev/os#Root which helps to improve filesystem security. |
||
| path := filepath.Join("etc", "standardfile", "database", id.String()) | ||
| return &path, nil | ||
| } | ||
|
|
||
| // Provides a valet token that is required to execute an operation | ||
| func (h *files) ValetTokens(c echo.Context) error { | ||
| var params ValetRequestParams | ||
| if err := c.Bind(¶ms); err != nil { | ||
| return respond(c, http.StatusBadRequest, "Unable to parse request") | ||
| } else if len(params.Resources) != 1 { | ||
| return respond(c, http.StatusBadRequest, "Multi file requests unsupported") | ||
| } | ||
|
|
||
| // Generate valet token. Used for actual file operations | ||
| var token ValetToken | ||
| token.Authorization = c.Request().Header.Get(echo.HeaderAuthorization) | ||
| token.FileID = params.Resources[0].RemoteIdentifier | ||
| valetTokenJson, err := json.Marshal(token) | ||
| if err != nil { | ||
| return c.JSON(http.StatusBadRequest, err) | ||
| } | ||
| return c.JSON(http.StatusOK, echo.Map{ | ||
| "success": true, | ||
| "valetToken": base64.StdEncoding.EncodeToString(valetTokenJson), | ||
| }) | ||
| } | ||
|
|
||
| // Called before uploading chunks of a file | ||
| func (h *files) CreateUploadSession(c echo.Context) error { | ||
| token, err := readValetToken(c) | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } | ||
|
|
||
| // Validate file path | ||
| path, err := token.getFilePath() | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } | ||
|
|
||
| // Create empty file | ||
| if _, err := os.Create(*path); err != nil { | ||
| return c.JSON(http.StatusBadRequest, err) | ||
| } | ||
|
|
||
| return c.JSON(http.StatusOK, echo.Map{ | ||
| "success": true, | ||
| "uploadId": token.FileID, | ||
| }) | ||
| } | ||
|
|
||
| // Called when uploaded all chunks of a file | ||
| func (h *files) CloseUploadSession(c echo.Context) error { | ||
| token, err := readValetToken(c) | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } | ||
| path, err := token.getFilePath() | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } else if _, err := os.Stat(*path); errors.Is(err, os.ErrNotExist) { | ||
| return respond(c, http.StatusBadRequest, "File not created") | ||
| } | ||
| return respond(c, http.StatusOK, "File uploaded successfully") | ||
| } | ||
|
|
||
| // Upload parts of a file in an existing session | ||
| func (h *files) UploadChunk(c echo.Context) error { | ||
| token, err := readValetToken(c) | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } | ||
|
|
||
| // Validate file path | ||
| path, err := token.getFilePath() | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } else if _, err := os.Stat(*path); errors.Is(err, os.ErrNotExist) { | ||
| return c.JSON(http.StatusBadRequest, "File not created") | ||
| } | ||
|
|
||
| // Open file | ||
| f, err := os.OpenFile(*path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, "Unable to open file") | ||
| } | ||
| defer f.Close() | ||
|
|
||
| // Append chunk to file via buffer | ||
| writer := bufio.NewWriter(f) | ||
| reader := c.Request().Body | ||
| if _, err := io.Copy(writer, reader); err != nil { | ||
| return respond(c, http.StatusBadRequest, "Unable to store file") | ||
| } | ||
| return respond(c, http.StatusOK, "Chunk uploaded successfully") | ||
| } | ||
|
|
||
| // Delete file from server | ||
| func (h *files) Delete(c echo.Context) error { | ||
| token, err := readValetToken(c) | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } | ||
| path, err := token.getFilePath() | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } else if err := os.Remove(*path); err != nil { | ||
| return respond(c, http.StatusBadRequest, "Unable to remove file") | ||
| } | ||
| return respond(c, http.StatusOK, "File removed successfully") | ||
| } | ||
|
|
||
| // Send encrypted file to client | ||
| func (h *files) Download(c echo.Context) error { | ||
| token, err := readValetToken(c) | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } | ||
|
|
||
| // Validate file path | ||
| path, err := token.getFilePath() | ||
| if err != nil { | ||
| return respond(c, http.StatusBadRequest, err.Error()) | ||
| } | ||
| return c.File(*path) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -21,6 +21,7 @@ type Controller struct { | |
| NoRegistration bool | ||
| ShowRealVersion bool | ||
| EnableSubscription bool | ||
| FilesServerUrl string | ||
| // JWT params | ||
| SigningKey []byte | ||
| // Session params | ||
|
|
@@ -35,7 +36,12 @@ func EchoEngine(ctrl Controller) *echo.Echo { | |
| engine.Use(middleware.Recover()) | ||
| // engine.Use(middleware.CSRF()) // not supported by StandardNotes | ||
| engine.Use(middleware.Secure()) | ||
| engine.Use(middleware.CORSWithConfig(middleware.DefaultCORSConfig)) | ||
|
|
||
| // Expose headers for file download | ||
| cors := middleware.DefaultCORSConfig | ||
| cors.ExposeHeaders = append(cors.ExposeHeaders, "Content-Range", "Accept-Ranges") | ||
| engine.Use(middleware.CORSWithConfig(cors)) | ||
|
|
||
| engine.Use(middleware.Gzip()) | ||
|
|
||
| engine.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ | ||
|
|
@@ -68,6 +74,7 @@ func EchoEngine(ctrl Controller) *echo.Echo { | |
| v1 := router.Group("/v1") | ||
| v1restricted := restricted.Group("/v1") | ||
|
|
||
| // | ||
| // generic handlers | ||
| // | ||
| router.GET("/version", func(c echo.Context) error { | ||
|
|
@@ -142,13 +149,28 @@ func EchoEngine(ctrl Controller) *echo.Echo { | |
| v2 := router.Group("/v2") | ||
| v2.POST("/login", auth.LoginPKCE) | ||
| v2.POST("/login-params", auth.ParamsPKCE) | ||
| //v2restricted := restricted.Group("/v2") | ||
|
|
||
| // | ||
| // files | ||
| // | ||
| files := &files{} | ||
| v1restricted.POST("/files/valet-tokens", files.ValetTokens) | ||
| v1valet := v1.Group("") | ||
| // TODO: v1valet.Use(a valet middleware for authentication) | ||
| // Following endpoints are authorized via valet token | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So we should do something like: |
||
| v1valet.POST("/files/upload/create-session", files.CreateUploadSession) | ||
| v1valet.POST("/files/upload/close-session", files.CloseUploadSession) | ||
| v1valet.POST("/files/upload/chunk", files.UploadChunk) | ||
| v1valet.DELETE("/files", files.Delete) | ||
| v1valet.GET("/files", files.Download) | ||
|
|
||
| // | ||
| // subscription handlers | ||
| // | ||
| if ctrl.EnableSubscription { | ||
| subscription := &subscription{} | ||
| subscription := &subscription{ | ||
| filesServerUrl: ctrl.FilesServerUrl, | ||
| } | ||
| router.GET("/v2/subscriptions", func(c echo.Context) error { | ||
| return c.HTML(http.StatusInternalServerError, "getaddrinfo EAI_AGAIN payments") | ||
| }) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.