0
0
mirror of https://github.com/go-gitea/gitea.git synced 2026-05-13 19:45:47 +02:00

Pass ServeHeaderOptions by value instead of pointer, fine tune httplib tests (#36982)

Pass `ServeHeaderOptions` by value instead of pointer across all call
sites — no nil-check semantics are needed and the struct is small enough
that copying is fine.

## Changes

- **`services/context/base.go`**: `SetServeHeaders` and `ServeContent`
accept `ServeHeaderOptions` (value, not pointer); internal unsafe
pointer cast replaced with a clean type conversion
- **`routers/api/packages/helper/helper.go`**: `ServePackageFile`
variadic changed from `...*context.ServeHeaderOptions` to
`...context.ServeHeaderOptions`; internal variable is now a value type
- **All call sites** (13 files): `&context.ServeHeaderOptions{...}` →
`context.ServeHeaderOptions{...}`

Before/after at the definition level:
```go
// Before
func (b *Base) SetServeHeaders(opt *ServeHeaderOptions) { ... }
func (b *Base) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions) { ... }
func ServePackageFile(..., forceOpts ...*context.ServeHeaderOptions) { ... }

// After
func (b *Base) SetServeHeaders(opts ServeHeaderOptions) { ... }
func (b *Base) ServeContent(r io.ReadSeeker, opts ServeHeaderOptions) { ... }
func ServePackageFile(..., forceOpts ...context.ServeHeaderOptions) { ... }
```

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: wxiaoguang <2114189+wxiaoguang@users.noreply.github.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
Copilot 2026-03-25 16:07:59 -07:00 committed by GitHub
parent bc5c554072
commit a3cc34472b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 77 additions and 97 deletions

View File

@ -87,7 +87,7 @@ func serveSetHeadersByUserContent(w http.ResponseWriter, contentPrefetchBuf []by
if setting.MimeTypeMap.Enabled { if setting.MimeTypeMap.Enabled {
fileExtension := strings.ToLower(path.Ext(opts.Filename)) fileExtension := strings.ToLower(path.Ext(opts.Filename))
opts.ContentType = setting.MimeTypeMap.Map[fileExtension] opts.ContentType = setting.MimeTypeMap.Map[fileExtension]
detectCharset = !strings.Contains(opts.ContentType, "charset=") detectCharset = strings.HasPrefix(opts.ContentType, "text/") && !strings.Contains(opts.ContentType, "charset=")
} }
if opts.ContentType == "" { if opts.ContentType == "" {

View File

@ -496,7 +496,7 @@ func (ar artifactRoutes) downloadArtifact(ctx *ArtifactContext) {
ctx.Resp.Header().Set("Content-Encoding", "gzip") ctx.Resp.Header().Set("Content-Encoding", "gzip")
} }
log.Debug("[artifact] downloadArtifact, name: %s, path: %s, storage: %s, size: %d", artifact.ArtifactName, artifact.ArtifactPath, artifact.StoragePath, artifact.FileSize) log.Debug("[artifact] downloadArtifact, name: %s, path: %s, storage: %s, size: %d", artifact.ArtifactName, artifact.ArtifactPath, artifact.StoragePath, artifact.FileSize)
ctx.ServeContent(fd, &context.ServeHeaderOptions{ ctx.ServeContent(fd, context.ServeHeaderOptions{
Filename: artifact.ArtifactName, Filename: artifact.ArtifactName,
LastModified: artifact.CreatedUnix.AsLocalTime(), LastModified: artifact.CreatedUnix.AsLocalTime(),
}) })

View File

@ -54,7 +54,7 @@ func GetRepositoryKey(ctx *context.Context) {
return return
} }
ctx.ServeContent(strings.NewReader(pub), &context.ServeHeaderOptions{ ctx.ServeContent(strings.NewReader(pub), context.ServeHeaderOptions{
ContentType: "application/x-pem-file", ContentType: "application/x-pem-file",
Filename: fmt.Sprintf("%s@%s.rsa.pub", ctx.Package.Owner.LowerName, hex.EncodeToString(fingerprint)), Filename: fmt.Sprintf("%s@%s.rsa.pub", ctx.Package.Owner.LowerName, hex.EncodeToString(fingerprint)),
}) })

View File

@ -35,7 +35,7 @@ func GetRepositoryKey(ctx *context.Context) {
return return
} }
ctx.ServeContent(strings.NewReader(pub), &context.ServeHeaderOptions{ ctx.ServeContent(strings.NewReader(pub), context.ServeHeaderOptions{
ContentType: "application/pgp-keys", ContentType: "application/pgp-keys",
}) })
} }
@ -232,7 +232,7 @@ func GetPackageOrRepositoryFile(ctx *context.Context) {
return return
} }
ctx.ServeContent(bytes.NewReader(data), &context.ServeHeaderOptions{ ctx.ServeContent(bytes.NewReader(data), context.ServeHeaderOptions{
Filename: filenameOrig, Filename: filenameOrig,
}) })
return return

View File

@ -35,7 +35,7 @@ func GetRepositoryKey(ctx *context.Context) {
return return
} }
ctx.ServeContent(strings.NewReader(pub), &context.ServeHeaderOptions{ ctx.ServeContent(strings.NewReader(pub), context.ServeHeaderOptions{
ContentType: "application/pgp-keys", ContentType: "application/pgp-keys",
Filename: "repository.key", Filename: "repository.key",
}) })
@ -233,7 +233,7 @@ func DownloadPackageFile(ctx *context.Context) {
return return
} }
helper.ServePackageFile(ctx, s, u, pf, &context.ServeHeaderOptions{ helper.ServePackageFile(ctx, s, u, pf, context.ServeHeaderOptions{
ContentType: "application/vnd.debian.binary-package", ContentType: "application/vnd.debian.binary-package",
Filename: pf.Name, Filename: pf.Name,
LastModified: pf.CreatedUnix.AsLocalTime(), LastModified: pf.CreatedUnix.AsLocalTime(),

View File

@ -39,7 +39,7 @@ func ProcessErrorForUser(ctx *context.Context, status int, errObj any) string {
// ServePackageFile the content of the package file // ServePackageFile the content of the package file
// If the url is set it will redirect the request, otherwise the content is copied to the response. // If the url is set it will redirect the request, otherwise the content is copied to the response.
func ServePackageFile(ctx *context.Context, s io.ReadSeekCloser, u *url.URL, pf *packages_model.PackageFile, forceOpts ...*context.ServeHeaderOptions) { func ServePackageFile(ctx *context.Context, s io.ReadSeekCloser, u *url.URL, pf *packages_model.PackageFile, forceOpts ...context.ServeHeaderOptions) {
if u != nil { if u != nil {
ctx.Redirect(u.String()) ctx.Redirect(u.String())
return return
@ -47,11 +47,11 @@ func ServePackageFile(ctx *context.Context, s io.ReadSeekCloser, u *url.URL, pf
defer s.Close() defer s.Close()
var opts *context.ServeHeaderOptions var opts context.ServeHeaderOptions
if len(forceOpts) > 0 { if len(forceOpts) > 0 {
opts = forceOpts[0] opts = forceOpts[0]
} else { } else {
opts = &context.ServeHeaderOptions{ opts = context.ServeHeaderOptions{
Filename: pf.Name, Filename: pf.Name,
LastModified: pf.CreatedUnix.AsLocalTime(), LastModified: pf.CreatedUnix.AsLocalTime(),
} }

View File

@ -200,7 +200,7 @@ func servePackageFile(ctx *context.Context, params parameters, serveContent bool
return return
} }
opts := &context.ServeHeaderOptions{ opts := context.ServeHeaderOptions{
ContentLength: &pb.Size, ContentLength: &pb.Size,
LastModified: pf.CreatedUnix.AsLocalTime(), LastModified: pf.CreatedUnix.AsLocalTime(),
} }

View File

@ -57,7 +57,7 @@ func GetRepositoryKey(ctx *context.Context) {
return return
} }
ctx.ServeContent(strings.NewReader(pub), &context.ServeHeaderOptions{ ctx.ServeContent(strings.NewReader(pub), context.ServeHeaderOptions{
ContentType: "application/pgp-keys", ContentType: "application/pgp-keys",
Filename: "repository.key", Filename: "repository.key",
}) })
@ -80,7 +80,7 @@ func CheckRepositoryFileExistence(ctx *context.Context) {
return return
} }
ctx.SetServeHeaders(&context.ServeHeaderOptions{ ctx.SetServeHeaders(context.ServeHeaderOptions{
Filename: pf.Name, Filename: pf.Name,
LastModified: pf.CreatedUnix.AsLocalTime(), LastModified: pf.CreatedUnix.AsLocalTime(),
}) })

View File

@ -79,7 +79,7 @@ func enumeratePackages(ctx *context.Context, filename string, pvs []*packages_mo
}) })
} }
ctx.SetServeHeaders(&context.ServeHeaderOptions{ ctx.SetServeHeaders(context.ServeHeaderOptions{
Filename: filename + ".gz", Filename: filename + ".gz",
}) })
@ -119,7 +119,7 @@ func ServePackageSpecification(ctx *context.Context) {
return return
} }
ctx.SetServeHeaders(&context.ServeHeaderOptions{ ctx.SetServeHeaders(context.ServeHeaderOptions{
Filename: filename, Filename: filename,
}) })

View File

@ -281,7 +281,7 @@ func DownloadManifest(ctx *context.Context) {
filename = fmt.Sprintf("Package@swift-%s.swift", swiftVersion) filename = fmt.Sprintf("Package@swift-%s.swift", swiftVersion)
} }
ctx.ServeContent(strings.NewReader(m.Content), &context.ServeHeaderOptions{ ctx.ServeContent(strings.NewReader(m.Content), context.ServeHeaderOptions{
ContentType: "text/x-swift", ContentType: "text/x-swift",
Filename: filename, Filename: filename,
LastModified: pv.CreatedUnix.AsLocalTime(), LastModified: pv.CreatedUnix.AsLocalTime(),
@ -437,7 +437,7 @@ func DownloadPackageFile(ctx *context.Context) {
Digest: pd.Files[0].Blob.HashSHA256, Digest: pd.Files[0].Blob.HashSHA256,
}) })
helper.ServePackageFile(ctx, s, u, pf, &context.ServeHeaderOptions{ helper.ServePackageFile(ctx, s, u, pf, context.ServeHeaderOptions{
Filename: pf.Name, Filename: pf.Name,
ContentType: "application/zip", ContentType: "application/zip",
LastModified: pf.CreatedUnix.AsLocalTime(), LastModified: pf.CreatedUnix.AsLocalTime(),

View File

@ -58,7 +58,7 @@ func DownloadActionsRunJobLogs(ctx *context.Base, ctxRepo *repo_model.Repository
if p := strings.Index(workflowName, "."); p > 0 { if p := strings.Index(workflowName, "."); p > 0 {
workflowName = workflowName[0:p] workflowName = workflowName[0:p]
} }
ctx.ServeContent(reader, &context.ServeHeaderOptions{ ctx.ServeContent(reader, context.ServeHeaderOptions{
Filename: fmt.Sprintf("%v-%v-%v.log", workflowName, curJob.Name, task.ID), Filename: fmt.Sprintf("%v-%v-%v.log", workflowName, curJob.Name, task.ID),
ContentLength: &task.LogSize, ContentLength: &task.LogSize,
ContentType: "text/plain; charset=utf-8", ContentType: "text/plain; charset=utf-8",

View File

@ -112,7 +112,7 @@ func RegenerateChefKeyPair(ctx *context.Context) {
return return
} }
ctx.ServeContent(strings.NewReader(priv), &context.ServeHeaderOptions{ ctx.ServeContent(strings.NewReader(priv), context.ServeHeaderOptions{
ContentType: "application/x-pem-file", ContentType: "application/x-pem-file",
Filename: ctx.Doer.Name + ".priv", Filename: ctx.Doer.Name + ".priv",
}) })

View File

@ -170,15 +170,15 @@ func (b *Base) Redirect(location string, status ...int) {
http.Redirect(b.Resp, b.Req, location, code) http.Redirect(b.Resp, b.Req, location, code)
} }
type ServeHeaderOptions httplib.ServeHeaderOptions type ServeHeaderOptions = httplib.ServeHeaderOptions
func (b *Base) SetServeHeaders(opt *ServeHeaderOptions) { func (b *Base) SetServeHeaders(opts ServeHeaderOptions) {
httplib.ServeSetHeaders(b.Resp, *(*httplib.ServeHeaderOptions)(opt)) httplib.ServeSetHeaders(b.Resp, opts)
} }
// ServeContent serves content to http request // ServeContent serves content to http request
func (b *Base) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions) { func (b *Base) ServeContent(r io.ReadSeeker, opts ServeHeaderOptions) {
httplib.ServeSetHeaders(b.Resp, *(*httplib.ServeHeaderOptions)(opts)) httplib.ServeSetHeaders(b.Resp, opts)
http.ServeContent(b.Resp, b.Req, opts.Filename, opts.LastModified, r) http.ServeContent(b.Resp, b.Req, opts.Filename, opts.LastModified, r)
} }

View File

@ -359,7 +359,7 @@ func ServeRepoArchive(ctx *gitea_context.Base, archiveReq *ArchiveRequest) error
} }
defer fr.Close() defer fr.Close()
ctx.ServeContent(fr, &gitea_context.ServeHeaderOptions{ ctx.ServeContent(fr, gitea_context.ServeHeaderOptions{
Filename: downloadName, Filename: downloadName,
LastModified: archiver.CreatedUnix.AsLocalTime(), LastModified: archiver.CreatedUnix.AsLocalTime(),
}) })

View File

@ -8,86 +8,66 @@ import (
"testing" "testing"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests" "code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestDownloadByID(t *testing.T) { func TestDownloadRepoContent(t *testing.T) {
defer tests.PrepareTestEnv(t)() defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user2") session := loginUser(t, "user2")
// Request raw blob t.Run("RawBlob", func(t *testing.T) {
req := NewRequest(t, "GET", "/user2/repo1/raw/blob/4b4851ad51df6a7d9f25c979345979eaeb5b349f") req := NewRequest(t, "GET", "/user2/repo1/raw/blob/4b4851ad51df6a7d9f25c979345979eaeb5b349f")
resp := session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "# repo1\n\nDescription for repo1", resp.Body.String())
})
assert.Equal(t, "# repo1\n\nDescription for repo1", resp.Body.String()) t.Run("SVGUsesSecureHeaders", func(t *testing.T) {
} req := NewRequest(t, "GET", "/user2/repo2/raw/blob/6395b68e1feebb1e4c657b4f9f6ba2676a283c0b")
resp := session.MakeRequest(t, req, http.StatusOK)
func TestDownloadByIDForSVGUsesSecureHeaders(t *testing.T) { assert.Equal(t, "default-src 'none'; style-src 'unsafe-inline'; sandbox", resp.Header().Get("Content-Security-Policy"))
defer tests.PrepareTestEnv(t)() assert.Equal(t, "image/svg+xml", resp.Header().Get("Content-Type"))
assert.Equal(t, "nosniff", resp.Header().Get("X-Content-Type-Options"))
session := loginUser(t, "user2") })
// Request raw blob t.Run("MediaBlob", func(t *testing.T) {
req := NewRequest(t, "GET", "/user2/repo2/raw/blob/6395b68e1feebb1e4c657b4f9f6ba2676a283c0b") req := NewRequest(t, "GET", "/user2/repo1/media/blob/4b4851ad51df6a7d9f25c979345979eaeb5b349f")
resp := session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "# repo1\n\nDescription for repo1", resp.Body.String())
assert.Equal(t, "default-src 'none'; style-src 'unsafe-inline'; sandbox", resp.Header().Get("Content-Security-Policy")) })
assert.Equal(t, "image/svg+xml", resp.Header().Get("Content-Type"))
assert.Equal(t, "nosniff", resp.Header().Get("X-Content-Type-Options")) t.Run("MediaSVGUsesSecureHeaders", func(t *testing.T) {
} req := NewRequest(t, "GET", "/user2/repo2/media/blob/6395b68e1feebb1e4c657b4f9f6ba2676a283c0b")
resp := session.MakeRequest(t, req, http.StatusOK)
func TestDownloadByIDMedia(t *testing.T) { assert.Equal(t, "default-src 'none'; style-src 'unsafe-inline'; sandbox", resp.Header().Get("Content-Security-Policy"))
defer tests.PrepareTestEnv(t)() assert.Equal(t, "image/svg+xml", resp.Header().Get("Content-Type"))
assert.Equal(t, "nosniff", resp.Header().Get("X-Content-Type-Options"))
session := loginUser(t, "user2") })
// Request raw blob t.Run("MimeTypeMap", func(t *testing.T) {
req := NewRequest(t, "GET", "/user2/repo1/media/blob/4b4851ad51df6a7d9f25c979345979eaeb5b349f") req := NewRequest(t, "GET", "/user2/repo2/raw/branch/master/test.xml")
resp := session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequest(t, req, http.StatusOK)
// although the file is a valid XML file, it is served as "text/plain" to avoid site content spamming (the same to "text/html" files)
assert.Equal(t, "# repo1\n\nDescription for repo1", resp.Body.String()) assert.Equal(t, "text/plain; charset=utf-8", resp.Header().Get("Content-Type"))
}
defer tests.PrepareTestEnv(t)()
func TestDownloadByIDMediaForSVGUsesSecureHeaders(t *testing.T) { defer test.MockVariableValue(&setting.MimeTypeMap)()
defer tests.PrepareTestEnv(t)() setting.MimeTypeMap.Enabled = true
session := loginUser(t, "user2") setting.MimeTypeMap.Map[".xml"] = "text/xml"
req = NewRequest(t, "GET", "/user2/repo2/raw/branch/master/test.xml")
// Request raw blob resp = session.MakeRequest(t, req, http.StatusOK)
req := NewRequest(t, "GET", "/user2/repo2/media/blob/6395b68e1feebb1e4c657b4f9f6ba2676a283c0b") // respect the mime mapping, and "text/plain" protection isn't used anymore
resp := session.MakeRequest(t, req, http.StatusOK) assert.Equal(t, "text/xml; charset=utf-8", resp.Header().Get("Content-Type"))
assert.Equal(t, "inline; filename=test.xml", resp.Header().Get("Content-Disposition"))
assert.Equal(t, "default-src 'none'; style-src 'unsafe-inline'; sandbox", resp.Header().Get("Content-Security-Policy"))
assert.Equal(t, "image/svg+xml", resp.Header().Get("Content-Type")) setting.MimeTypeMap.Map[".xml"] = "application/xml"
assert.Equal(t, "nosniff", resp.Header().Get("X-Content-Type-Options")) req = NewRequest(t, "GET", "/user2/repo2/raw/branch/master/test.xml")
} resp = session.MakeRequest(t, req, http.StatusOK)
// non-text file don't have "charset"
func TestDownloadRawTextFileWithoutMimeTypeMapping(t *testing.T) { assert.Equal(t, "application/xml", resp.Header().Get("Content-Type"))
defer tests.PrepareTestEnv(t)() })
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user2/repo2/raw/branch/master/test.xml")
resp := session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "text/plain; charset=utf-8", resp.Header().Get("Content-Type"))
}
func TestDownloadRawTextFileWithMimeTypeMapping(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.MimeTypeMap.Map[".xml"] = "text/xml"
setting.MimeTypeMap.Enabled = true
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user2/repo2/raw/branch/master/test.xml")
resp := session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "text/xml; charset=utf-8", resp.Header().Get("Content-Type"))
delete(setting.MimeTypeMap.Map, ".xml")
setting.MimeTypeMap.Enabled = false
} }