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 support for API blob upload of release attachments #29507

Merged
merged 6 commits into from
Mar 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 29 additions & 10 deletions routers/api/v1/repo/release_attachment.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
package repo

import (
"io"
"net/http"
"strings"

repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/modules/log"
Expand Down Expand Up @@ -154,6 +156,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
// - application/json
// consumes:
// - multipart/form-data
// - application/octet-stream
// parameters:
// - name: owner
// in: path
Expand All @@ -180,7 +183,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
// in: formData
// description: attachment to upload
// type: file
// required: true
// required: false
// responses:
// "201":
// "$ref": "#/responses/Attachment"
Expand All @@ -202,20 +205,36 @@ func CreateReleaseAttachment(ctx *context.APIContext) {
}

// Get uploaded file from request
file, header, err := ctx.Req.FormFile("attachment")
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetFile", err)
return
var content io.ReadCloser
var filename string
var size int64 = -1

if strings.HasPrefix(strings.ToLower(ctx.Req.Header.Get("Content-Type")), "multipart/form-data") {
file, header, err := ctx.Req.FormFile("attachment")
if err != nil {
ctx.Error(http.StatusInternalServerError, "GetFile", err)
return
}
defer file.Close()

content = file
size = header.Size
filename = header.Filename
if name := ctx.FormString("name"); name != "" {
filename = name
}
} else {
content = ctx.Req.Body
filename = ctx.FormString("name")
}
defer file.Close()

filename := header.Filename
if query := ctx.FormString("name"); query != "" {
filename = query
if filename == "" {
ctx.Error(http.StatusBadRequest, "CreateReleaseAttachment", "Could not determine name of attachment.")
return
}

// Create a new attachment and save the file
attach, err := attachment.UploadAttachment(ctx, file, setting.Repository.Release.AllowedTypes, header.Size, &repo_model.Attachment{
attach, err := attachment.UploadAttachment(ctx, content, setting.Repository.Release.AllowedTypes, size, &repo_model.Attachment{
delvh marked this conversation as resolved.
Show resolved Hide resolved
Name: filename,
UploaderID: ctx.Doer.ID,
RepoID: ctx.Repo.Repository.ID,
Expand Down
6 changes: 3 additions & 3 deletions services/attachment/attachment.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ func NewAttachment(ctx context.Context, attach *repo_model.Attachment, file io.R
}

// UploadAttachment upload new attachment into storage and update database
func UploadAttachment(ctx context.Context, file io.Reader, allowedTypes string, fileSize int64, opts *repo_model.Attachment) (*repo_model.Attachment, error) {
func UploadAttachment(ctx context.Context, file io.Reader, allowedTypes string, fileSize int64, attach *repo_model.Attachment) (*repo_model.Attachment, error) {
buf := make([]byte, 1024)
n, _ := util.ReadAtMost(file, buf)
buf = buf[:n]

if err := upload.Verify(buf, opts.Name, allowedTypes); err != nil {
if err := upload.Verify(buf, attach.Name, allowedTypes); err != nil {
return nil, err
}

return NewAttachment(ctx, opts, io.MultiReader(bytes.NewReader(buf), file), fileSize)
return NewAttachment(ctx, attach, io.MultiReader(bytes.NewReader(buf), file), fileSize)
}
6 changes: 3 additions & 3 deletions templates/swagger/v1_json.tmpl

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 52 additions & 16 deletions tests/integration/api_releases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,24 +262,60 @@ func TestAPIUploadAssetRelease(t *testing.T) {

filename := "image.png"
buff := generateImg()
body := &bytes.Buffer{}

writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("attachment", filename)
assert.NoError(t, err)
_, err = io.Copy(part, &buff)
assert.NoError(t, err)
err = writer.Close()
assert.NoError(t, err)
assetURL := fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d/assets", owner.Name, repo.Name, r.ID)

req := NewRequestWithBody(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d/assets?name=test-asset", owner.Name, repo.Name, r.ID), body).
AddTokenAuth(token)
req.Header.Add("Content-Type", writer.FormDataContentType())
resp := MakeRequest(t, req, http.StatusCreated)
t.Run("multipart/form-data", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()

body := &bytes.Buffer{}

writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("attachment", filename)
assert.NoError(t, err)
_, err = io.Copy(part, bytes.NewReader(buff.Bytes()))
assert.NoError(t, err)
err = writer.Close()
assert.NoError(t, err)

req := NewRequestWithBody(t, http.MethodPost, assetURL, bytes.NewReader(body.Bytes())).
AddTokenAuth(token).
SetHeader("Content-Type", writer.FormDataContentType())
resp := MakeRequest(t, req, http.StatusCreated)

var attachment *api.Attachment
DecodeJSON(t, resp, &attachment)

assert.EqualValues(t, filename, attachment.Name)
assert.EqualValues(t, 104, attachment.Size)

req = NewRequestWithBody(t, http.MethodPost, assetURL+"?name=test-asset", bytes.NewReader(body.Bytes())).
AddTokenAuth(token).
SetHeader("Content-Type", writer.FormDataContentType())
resp = MakeRequest(t, req, http.StatusCreated)

var attachment2 *api.Attachment
DecodeJSON(t, resp, &attachment2)

assert.EqualValues(t, "test-asset", attachment2.Name)
assert.EqualValues(t, 104, attachment2.Size)
})

t.Run("application/octet-stream", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()

req := NewRequestWithBody(t, http.MethodPost, assetURL, bytes.NewReader(buff.Bytes())).
AddTokenAuth(token)
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
AddTokenAuth(token)
AddTokenAuth(token)
SetHeader("Content-Type", "application/octet-stream")

Just so we test what is specced.

Copy link
Member Author

@KN4CK3R KN4CK3R Mar 2, 2024

Choose a reason for hiding this comment

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

Use the required Content-Type header to provide the media type of the asset. For a list of media types, see Media Types. For example:

application/zip

That's not specced. The Github docs state that you must pass the content type of the attachment. We do not use the content type, therefore application/octet-stream is not really needed. If we want to make that header required too (even we don't use it), I need to add such a check.

Copy link
Member

Choose a reason for hiding this comment

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

Maybe adding a check is better.

Copy link
Member

@silverwind silverwind Mar 2, 2024

Choose a reason for hiding this comment

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

Right, we accept any content-type except multipart, so it's fine. I suppose GitHub will error when content-type is absent, but we can do that, I see no drawback.

Copy link
Member

Choose a reason for hiding this comment

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

BTW, with openapi 3.0 or higher, one could do a oneOf check on content-type in the schema validation, but we use swagger 2.0 and it does not support that.

We should eventually migrate to ideally openapi 3.1, but it will require a new validator module.

MakeRequest(t, req, http.StatusBadRequest)

req = NewRequestWithBody(t, http.MethodPost, assetURL+"?name=stream.bin", bytes.NewReader(buff.Bytes())).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusCreated)

var attachment *api.Attachment
DecodeJSON(t, resp, &attachment)
var attachment *api.Attachment
DecodeJSON(t, resp, &attachment)

assert.EqualValues(t, "test-asset", attachment.Name)
assert.EqualValues(t, 104, attachment.Size)
assert.EqualValues(t, "stream.bin", attachment.Name)
assert.EqualValues(t, 104, attachment.Size)
})
}
Loading