feat: Add audit logging (#38189)

Co-authored-by: bircni <bircni@users.noreply.github.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
bircni
2026-09-12 10:15:23 +02:00
committed by GitHub
parent 4d43445532
commit da37b7916b
136 changed files with 3864 additions and 209 deletions
+26
View File
@@ -0,0 +1,26 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package common
import (
"net/http"
audit_model "gitea.dev/models/audit"
"gitea.dev/modules/httplib"
"gitea.dev/modules/reqctx"
audit_service "gitea.dev/services/audit"
)
// AuditOrigin publishes the origin and the client address of the request, so
// audit events recorded while serving it are attributed to it.
func AuditOrigin(origin audit_model.Origin) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if store := reqctx.GetRequestDataStore(req.Context()); store != nil {
audit_service.SetRequestInfo(store, origin, httplib.RemoteHost(req))
}
next.ServeHTTP(resp, req)
})
}
}
+13
View File
@@ -5,6 +5,7 @@ package common
import (
user_model "gitea.dev/models/user"
"gitea.dev/modules/log"
"gitea.dev/modules/web/middleware"
auth_service "gitea.dev/services/auth"
"gitea.dev/services/context"
@@ -30,6 +31,18 @@ func AuthShared(ctx *context.Base, sessionStore auth_service.SessionStore, authM
ctx.Data[middleware.ContextDataKeySignedUser] = ar.Doer
ctx.Data["SignedUserID"] = ar.Doer.ID
ctx.Data["IsAdmin"] = ar.Doer.IsAdmin
if sessionStore != nil {
if uid := auth_service.ImpersonatorUserID(sessionStore); uid != 0 {
impersonator, err := user_model.GetUserByID(ctx, uid)
if err != nil {
// the session stays usable, but audit events must not silently lose the admin behind it
log.Error("Unable to resolve impersonator %d: %v", uid, err)
} else {
ctx.Data[middleware.ContextDataKeyImpersonator] = impersonator
}
}
}
} else {
ctx.Data["SignedUserID"] = int64(0)
}