Skip to content

Commit 4ebb00a

Browse files
authored
Merge branch 'main' into support-trace
2 parents 5647c41 + 6073e2f commit 4ebb00a

File tree

13 files changed

+208
-75
lines changed

13 files changed

+208
-75
lines changed

modules/git/repo_branch_gogit.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ func (repo *Repository) IsBranchExist(name string) bool {
5757

5858
// GetBranches returns branches from the repository, skipping "skip" initial branches and
5959
// returning at most "limit" branches, or all branches if "limit" is 0.
60-
// Branches are returned with sort of `-commiterdate` as the nogogit
60+
// Branches are returned with sort of `-committerdate` as the nogogit
6161
// implementation. This requires full fetch, sort and then the
6262
// skip/limit applies later as gogit returns in undefined order.
6363
func (repo *Repository) GetBranchNames(skip, limit int) ([]string, int, error) {

options/gitignore/Node

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,12 @@ dist
104104
.temp
105105
.cache
106106

107+
# vitepress build output
108+
**/.vitepress/dist
109+
110+
# vitepress cache directory
111+
**/.vitepress/cache
112+
107113
# Docusaurus cache and generated files
108114
.docusaurus
109115

options/gitignore/Python

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,5 +167,8 @@ cython_debug/
167167
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
168168
#.idea/
169169

170+
# Ruff stuff:
171+
.ruff_cache/
172+
170173
# PyPI configuration file
171174
.pypirc

options/gitignore/Rust

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,6 @@
33
debug/
44
target/
55

6-
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
7-
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
8-
Cargo.lock
9-
106
# These are backup files generated by rustfmt
117
**/*.rs.bk
128

routers/common/middleware.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,11 @@ func ProtocolMiddlewares() (handlers []any) {
4444

4545
func RequestContextHandler() func(h http.Handler) http.Handler {
4646
return func(next http.Handler) http.Handler {
47-
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
47+
return http.HandlerFunc(func(respOrig http.ResponseWriter, req *http.Request) {
48+
// this response writer might not be the same as the one in context.Base.Resp
49+
// because there might be a "gzip writer" in the middle, so the "written size" here is the compressed size
50+
respWriter := context.WrapResponseWriter(respOrig)
51+
4852
profDesc := fmt.Sprintf("HTTP: %s %s", req.Method, req.RequestURI)
4953
ctx, finished := reqctx.NewRequestContext(req.Context(), profDesc)
5054
defer finished()
@@ -59,7 +63,7 @@ func RequestContextHandler() func(h http.Handler) http.Handler {
5963

6064
defer func() {
6165
if err := recover(); err != nil {
62-
RenderPanicErrorPage(resp, req, err) // it should never panic
66+
RenderPanicErrorPage(respWriter, req, err) // it should never panic
6367
}
6468
}()
6569

@@ -71,7 +75,7 @@ func RequestContextHandler() func(h http.Handler) http.Handler {
7175
_ = req.MultipartForm.RemoveAll() // remove the temp files buffered to tmp directory
7276
}
7377
})
74-
next.ServeHTTP(context.WrapResponseWriter(resp), req)
78+
next.ServeHTTP(respWriter, req)
7579
})
7680
}
7781
}

routers/web/auth/linkaccount.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ var tplLinkAccount templates.TplName = "user/auth/link_account"
2929

3030
// LinkAccount shows the page where the user can decide to login or create a new account
3131
func LinkAccount(ctx *context.Context) {
32+
// FIXME: these common template variables should be prepared in one common function, but not just copy-paste again and again.
3233
ctx.Data["DisablePassword"] = !setting.Service.RequireExternalRegistrationPassword || setting.Service.AllowOnlyExternalRegistration
3334
ctx.Data["Title"] = ctx.Tr("link_account")
3435
ctx.Data["LinkAccountMode"] = true
@@ -43,13 +44,19 @@ func LinkAccount(ctx *context.Context) {
4344
ctx.Data["CfTurnstileSitekey"] = setting.Service.CfTurnstileSitekey
4445
ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
4546
ctx.Data["AllowOnlyInternalRegistration"] = setting.Service.AllowOnlyInternalRegistration
47+
ctx.Data["EnablePasswordSignInForm"] = setting.Service.EnablePasswordSignInForm
4648
ctx.Data["ShowRegistrationButton"] = false
4749

4850
// use this to set the right link into the signIn and signUp templates in the link_account template
4951
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/link_account_signin"
5052
ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/link_account_signup"
5153

5254
gothUser, ok := ctx.Session.Get("linkAccountGothUser").(goth.User)
55+
56+
// If you'd like to quickly debug the "link account" page layout, just uncomment the blow line
57+
// Don't worry, when the below line exists, the lint won't pass: ineffectual assignment to gothUser (ineffassign)
58+
// gothUser, ok = goth.User{Email: "invalid-email", Name: "."}, true // intentionally use invalid data to avoid pass the registration check
59+
5360
if !ok {
5461
// no account in session, so just redirect to the login page, then the user could restart the process
5562
ctx.Redirect(setting.AppSubURL + "/user/login")
@@ -135,6 +142,8 @@ func LinkAccountPostSignIn(ctx *context.Context) {
135142
ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL
136143
ctx.Data["CfTurnstileSitekey"] = setting.Service.CfTurnstileSitekey
137144
ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
145+
ctx.Data["AllowOnlyInternalRegistration"] = setting.Service.AllowOnlyInternalRegistration
146+
ctx.Data["EnablePasswordSignInForm"] = setting.Service.EnablePasswordSignInForm
138147
ctx.Data["ShowRegistrationButton"] = false
139148

140149
// use this to set the right link into the signIn and signUp templates in the link_account template
@@ -223,6 +232,8 @@ func LinkAccountPostRegister(ctx *context.Context) {
223232
ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL
224233
ctx.Data["CfTurnstileSitekey"] = setting.Service.CfTurnstileSitekey
225234
ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration
235+
ctx.Data["AllowOnlyInternalRegistration"] = setting.Service.AllowOnlyInternalRegistration
236+
ctx.Data["EnablePasswordSignInForm"] = setting.Service.EnablePasswordSignInForm
226237
ctx.Data["ShowRegistrationButton"] = false
227238

228239
// use this to set the right link into the signIn and signUp templates in the link_account template

services/context/access_log.go

Lines changed: 59 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,14 @@ import (
1818
"code.gitea.io/gitea/modules/web/middleware"
1919
)
2020

21-
type routerLoggerOptions struct {
22-
req *http.Request
21+
type accessLoggerTmplData struct {
2322
Identity *string
2423
Start *time.Time
25-
ResponseWriter http.ResponseWriter
26-
Ctx map[string]any
27-
RequestID *string
24+
ResponseWriter struct {
25+
Status, Size int
26+
}
27+
Ctx map[string]any
28+
RequestID *string
2829
}
2930

3031
const keyOfRequestIDInTemplate = ".RequestID"
@@ -51,51 +52,65 @@ func parseRequestIDFromRequestHeader(req *http.Request) string {
5152
return requestID
5253
}
5354

55+
type accessLogRecorder struct {
56+
logger log.BaseLogger
57+
logTemplate *template.Template
58+
needRequestID bool
59+
}
60+
61+
func (lr *accessLogRecorder) record(start time.Time, respWriter ResponseWriter, req *http.Request) {
62+
var requestID string
63+
if lr.needRequestID {
64+
requestID = parseRequestIDFromRequestHeader(req)
65+
}
66+
67+
reqHost, _, err := net.SplitHostPort(req.RemoteAddr)
68+
if err != nil {
69+
reqHost = req.RemoteAddr
70+
}
71+
72+
identity := "-"
73+
data := middleware.GetContextData(req.Context())
74+
if signedUser, ok := data[middleware.ContextDataKeySignedUser].(*user_model.User); ok {
75+
identity = signedUser.Name
76+
}
77+
buf := bytes.NewBuffer([]byte{})
78+
tmplData := accessLoggerTmplData{
79+
Identity: &identity,
80+
Start: &start,
81+
Ctx: map[string]any{
82+
"RemoteAddr": req.RemoteAddr,
83+
"RemoteHost": reqHost,
84+
"Req": req,
85+
},
86+
RequestID: &requestID,
87+
}
88+
tmplData.ResponseWriter.Status = respWriter.Status()
89+
tmplData.ResponseWriter.Size = respWriter.WrittenSize()
90+
err = lr.logTemplate.Execute(buf, tmplData)
91+
if err != nil {
92+
log.Error("Could not execute access logger template: %v", err.Error())
93+
}
94+
95+
lr.logger.Log(1, log.INFO, "%s", buf.String())
96+
}
97+
98+
func newAccessLogRecorder() *accessLogRecorder {
99+
return &accessLogRecorder{
100+
logger: log.GetLogger("access"),
101+
logTemplate: template.Must(template.New("log").Parse(setting.Log.AccessLogTemplate)),
102+
needRequestID: len(setting.Log.RequestIDHeaders) > 0 && strings.Contains(setting.Log.AccessLogTemplate, keyOfRequestIDInTemplate),
103+
}
104+
}
105+
54106
// AccessLogger returns a middleware to log access logger
55107
func AccessLogger() func(http.Handler) http.Handler {
56-
logger := log.GetLogger("access")
57-
needRequestID := len(setting.Log.RequestIDHeaders) > 0 && strings.Contains(setting.Log.AccessLogTemplate, keyOfRequestIDInTemplate)
58-
logTemplate, _ := template.New("log").Parse(setting.Log.AccessLogTemplate)
108+
recorder := newAccessLogRecorder()
59109
return func(next http.Handler) http.Handler {
60110
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
61111
start := time.Now()
62-
63-
var requestID string
64-
if needRequestID {
65-
requestID = parseRequestIDFromRequestHeader(req)
66-
}
67-
68-
reqHost, _, err := net.SplitHostPort(req.RemoteAddr)
69-
if err != nil {
70-
reqHost = req.RemoteAddr
71-
}
72-
73112
next.ServeHTTP(w, req)
74-
rw := w.(ResponseWriter)
75-
76-
identity := "-"
77-
data := middleware.GetContextData(req.Context())
78-
if signedUser, ok := data[middleware.ContextDataKeySignedUser].(*user_model.User); ok {
79-
identity = signedUser.Name
80-
}
81-
buf := bytes.NewBuffer([]byte{})
82-
err = logTemplate.Execute(buf, routerLoggerOptions{
83-
req: req,
84-
Identity: &identity,
85-
Start: &start,
86-
ResponseWriter: rw,
87-
Ctx: map[string]any{
88-
"RemoteAddr": req.RemoteAddr,
89-
"RemoteHost": reqHost,
90-
"Req": req,
91-
},
92-
RequestID: &requestID,
93-
})
94-
if err != nil {
95-
log.Error("Could not execute access logger template: %v", err.Error())
96-
}
97-
98-
logger.Info("%s", buf.String())
113+
recorder.record(start, w.(ResponseWriter), req)
99114
})
100115
}
101116
}
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// Copyright 2025 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package context
5+
6+
import (
7+
"fmt"
8+
"net/http"
9+
"net/url"
10+
"testing"
11+
"time"
12+
13+
"code.gitea.io/gitea/modules/log"
14+
"code.gitea.io/gitea/modules/setting"
15+
16+
"github.com/stretchr/testify/assert"
17+
)
18+
19+
type testAccessLoggerMock struct {
20+
logs []string
21+
}
22+
23+
func (t *testAccessLoggerMock) Log(skip int, level log.Level, format string, v ...any) {
24+
t.logs = append(t.logs, fmt.Sprintf(format, v...))
25+
}
26+
27+
func (t *testAccessLoggerMock) GetLevel() log.Level {
28+
return log.INFO
29+
}
30+
31+
type testAccessLoggerResponseWriterMock struct{}
32+
33+
func (t testAccessLoggerResponseWriterMock) Header() http.Header {
34+
return nil
35+
}
36+
37+
func (t testAccessLoggerResponseWriterMock) Before(f func(ResponseWriter)) {}
38+
39+
func (t testAccessLoggerResponseWriterMock) WriteHeader(statusCode int) {}
40+
41+
func (t testAccessLoggerResponseWriterMock) Write(bytes []byte) (int, error) {
42+
return 0, nil
43+
}
44+
45+
func (t testAccessLoggerResponseWriterMock) Flush() {}
46+
47+
func (t testAccessLoggerResponseWriterMock) WrittenStatus() int {
48+
return http.StatusOK
49+
}
50+
51+
func (t testAccessLoggerResponseWriterMock) Status() int {
52+
return t.WrittenStatus()
53+
}
54+
55+
func (t testAccessLoggerResponseWriterMock) WrittenSize() int {
56+
return 123123
57+
}
58+
59+
func TestAccessLogger(t *testing.T) {
60+
setting.Log.AccessLogTemplate = `{{.Ctx.RemoteHost}} - {{.Identity}} {{.Start.Format "[02/Jan/2006:15:04:05 -0700]" }} "{{.Ctx.Req.Method}} {{.Ctx.Req.URL.RequestURI}} {{.Ctx.Req.Proto}}" {{.ResponseWriter.Status}} {{.ResponseWriter.Size}} "{{.Ctx.Req.Referer}}" "{{.Ctx.Req.UserAgent}}"`
61+
recorder := newAccessLogRecorder()
62+
mockLogger := &testAccessLoggerMock{}
63+
recorder.logger = mockLogger
64+
req := &http.Request{
65+
RemoteAddr: "remote-addr",
66+
Method: "GET",
67+
Proto: "https",
68+
URL: &url.URL{Path: "/path"},
69+
}
70+
req.Header = http.Header{}
71+
req.Header.Add("Referer", "referer")
72+
req.Header.Add("User-Agent", "user-agent")
73+
recorder.record(time.Date(2000, 1, 2, 3, 4, 5, 0, time.UTC), &testAccessLoggerResponseWriterMock{}, req)
74+
assert.Equal(t, []string{`remote-addr - - [02/Jan/2000:03:04:05 +0000] "GET /path https" 200 123123 "referer" "user-agent"`}, mockLogger.logs)
75+
}

0 commit comments

Comments
 (0)