2022-10-16 19:29:26 -04:00
|
|
|
// Copyright 2014 The Gogs Authors. All rights reserved.
|
|
|
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
2022-11-27 13:20:29 -05:00
|
|
|
// SPDX-License-Identifier: MIT
|
2022-10-16 19:29:26 -04:00
|
|
|
|
|
|
|
package admin
|
|
|
|
|
|
|
|
import (
|
2023-01-17 10:00:19 -05:00
|
|
|
"fmt"
|
2022-10-16 19:29:26 -04:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2023-01-17 10:00:19 -05:00
|
|
|
"strconv"
|
2022-10-16 19:29:26 -04:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
system_model "code.gitea.io/gitea/models/system"
|
|
|
|
"code.gitea.io/gitea/modules/base"
|
|
|
|
"code.gitea.io/gitea/modules/context"
|
|
|
|
"code.gitea.io/gitea/modules/git"
|
|
|
|
"code.gitea.io/gitea/modules/json"
|
|
|
|
"code.gitea.io/gitea/modules/log"
|
|
|
|
"code.gitea.io/gitea/modules/setting"
|
|
|
|
"code.gitea.io/gitea/modules/util"
|
|
|
|
"code.gitea.io/gitea/services/mailer"
|
|
|
|
|
|
|
|
"gitea.com/go-chi/session"
|
|
|
|
)
|
|
|
|
|
|
|
|
const tplConfig base.TplName = "admin/config"
|
|
|
|
|
|
|
|
// SendTestMail send test mail to confirm mail service is OK
|
|
|
|
func SendTestMail(ctx *context.Context) {
|
|
|
|
email := ctx.FormString("email")
|
|
|
|
// Send a test email to the user's email address and redirect back to Config
|
|
|
|
if err := mailer.SendTestMail(email); err != nil {
|
|
|
|
ctx.Flash.Error(ctx.Tr("admin.config.test_mail_failed", email, err))
|
|
|
|
} else {
|
|
|
|
ctx.Flash.Info(ctx.Tr("admin.config.test_mail_sent", email))
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.Redirect(setting.AppSubURL + "/admin/config")
|
|
|
|
}
|
|
|
|
|
|
|
|
func shadowPasswordKV(cfgItem, splitter string) string {
|
|
|
|
fields := strings.Split(cfgItem, splitter)
|
|
|
|
for i := 0; i < len(fields); i++ {
|
|
|
|
if strings.HasPrefix(fields[i], "password=") {
|
|
|
|
fields[i] = "password=******"
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return strings.Join(fields, splitter)
|
|
|
|
}
|
|
|
|
|
|
|
|
func shadowURL(provider, cfgItem string) string {
|
|
|
|
u, err := url.Parse(cfgItem)
|
|
|
|
if err != nil {
|
|
|
|
log.Error("Shadowing Password for %v failed: %v", provider, err)
|
|
|
|
return cfgItem
|
|
|
|
}
|
|
|
|
if u.User != nil {
|
|
|
|
atIdx := strings.Index(cfgItem, "@")
|
|
|
|
if atIdx > 0 {
|
|
|
|
colonIdx := strings.LastIndex(cfgItem[:atIdx], ":")
|
|
|
|
if colonIdx > 0 {
|
|
|
|
return cfgItem[:colonIdx+1] + "******" + cfgItem[atIdx:]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return cfgItem
|
|
|
|
}
|
|
|
|
|
|
|
|
func shadowPassword(provider, cfgItem string) string {
|
|
|
|
switch provider {
|
|
|
|
case "redis":
|
|
|
|
return shadowPasswordKV(cfgItem, ",")
|
|
|
|
case "mysql":
|
|
|
|
// root:@tcp(localhost:3306)/macaron?charset=utf8
|
|
|
|
atIdx := strings.Index(cfgItem, "@")
|
|
|
|
if atIdx > 0 {
|
|
|
|
colonIdx := strings.Index(cfgItem[:atIdx], ":")
|
|
|
|
if colonIdx > 0 {
|
|
|
|
return cfgItem[:colonIdx+1] + "******" + cfgItem[atIdx:]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return cfgItem
|
|
|
|
case "postgres":
|
|
|
|
// user=jiahuachen dbname=macaron port=5432 sslmode=disable
|
|
|
|
if !strings.HasPrefix(cfgItem, "postgres://") {
|
|
|
|
return shadowPasswordKV(cfgItem, " ")
|
|
|
|
}
|
|
|
|
fallthrough
|
|
|
|
case "couchbase":
|
|
|
|
return shadowURL(provider, cfgItem)
|
|
|
|
// postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full
|
|
|
|
// Notice: use shadowURL
|
|
|
|
}
|
|
|
|
return cfgItem
|
|
|
|
}
|
|
|
|
|
|
|
|
// Config show admin config page
|
|
|
|
func Config(ctx *context.Context) {
|
|
|
|
ctx.Data["Title"] = ctx.Tr("admin.config")
|
|
|
|
ctx.Data["PageIsAdminConfig"] = true
|
|
|
|
|
2023-02-24 05:23:13 -05:00
|
|
|
systemSettings, err := system_model.GetAllSettings(ctx)
|
2022-10-16 19:29:26 -04:00
|
|
|
if err != nil {
|
|
|
|
ctx.ServerError("system_model.GetAllSettings", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// All editable settings from UI
|
|
|
|
ctx.Data["SystemSettings"] = systemSettings
|
|
|
|
ctx.PageData["adminConfigPage"] = true
|
|
|
|
|
|
|
|
ctx.Data["CustomConf"] = setting.CustomConf
|
|
|
|
ctx.Data["AppUrl"] = setting.AppURL
|
2023-04-07 03:31:41 -04:00
|
|
|
ctx.Data["AppBuiltWith"] = setting.AppBuiltWith
|
2022-10-16 19:29:26 -04:00
|
|
|
ctx.Data["Domain"] = setting.Domain
|
|
|
|
ctx.Data["OfflineMode"] = setting.OfflineMode
|
|
|
|
ctx.Data["RunUser"] = setting.RunUser
|
|
|
|
ctx.Data["RunMode"] = util.ToTitleCase(setting.RunMode)
|
|
|
|
ctx.Data["GitVersion"] = git.VersionInfo()
|
|
|
|
|
2023-07-19 05:22:57 -04:00
|
|
|
ctx.Data["AppDataPath"] = setting.AppDataPath
|
2022-10-16 19:29:26 -04:00
|
|
|
ctx.Data["RepoRootPath"] = setting.RepoRootPath
|
|
|
|
ctx.Data["CustomRootPath"] = setting.CustomPath
|
2023-02-19 11:12:01 -05:00
|
|
|
ctx.Data["LogRootPath"] = setting.Log.RootPath
|
2022-10-16 19:29:26 -04:00
|
|
|
ctx.Data["ScriptType"] = setting.ScriptType
|
|
|
|
ctx.Data["ReverseProxyAuthUser"] = setting.ReverseProxyAuthUser
|
|
|
|
ctx.Data["ReverseProxyAuthEmail"] = setting.ReverseProxyAuthEmail
|
|
|
|
|
|
|
|
ctx.Data["SSH"] = setting.SSH
|
|
|
|
ctx.Data["LFS"] = setting.LFS
|
|
|
|
|
|
|
|
ctx.Data["Service"] = setting.Service
|
|
|
|
ctx.Data["DbCfg"] = setting.Database
|
|
|
|
ctx.Data["Webhook"] = setting.Webhook
|
|
|
|
|
|
|
|
ctx.Data["MailerEnabled"] = false
|
|
|
|
if setting.MailService != nil {
|
|
|
|
ctx.Data["MailerEnabled"] = true
|
|
|
|
ctx.Data["Mailer"] = setting.MailService
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.Data["CacheAdapter"] = setting.CacheService.Adapter
|
|
|
|
ctx.Data["CacheInterval"] = setting.CacheService.Interval
|
|
|
|
|
|
|
|
ctx.Data["CacheConn"] = shadowPassword(setting.CacheService.Adapter, setting.CacheService.Conn)
|
|
|
|
ctx.Data["CacheItemTTL"] = setting.CacheService.TTL
|
|
|
|
|
|
|
|
sessionCfg := setting.SessionConfig
|
|
|
|
if sessionCfg.Provider == "VirtualSession" {
|
|
|
|
var realSession session.Options
|
|
|
|
if err := json.Unmarshal([]byte(sessionCfg.ProviderConfig), &realSession); err != nil {
|
|
|
|
log.Error("Unable to unmarshall session config for virtual provider config: %s\nError: %v", sessionCfg.ProviderConfig, err)
|
|
|
|
}
|
|
|
|
sessionCfg.Provider = realSession.Provider
|
|
|
|
sessionCfg.ProviderConfig = realSession.ProviderConfig
|
|
|
|
sessionCfg.CookieName = realSession.CookieName
|
|
|
|
sessionCfg.CookiePath = realSession.CookiePath
|
|
|
|
sessionCfg.Gclifetime = realSession.Gclifetime
|
|
|
|
sessionCfg.Maxlifetime = realSession.Maxlifetime
|
|
|
|
sessionCfg.Secure = realSession.Secure
|
|
|
|
sessionCfg.Domain = realSession.Domain
|
|
|
|
}
|
|
|
|
sessionCfg.ProviderConfig = shadowPassword(sessionCfg.Provider, sessionCfg.ProviderConfig)
|
|
|
|
ctx.Data["SessionConfig"] = sessionCfg
|
|
|
|
|
|
|
|
ctx.Data["Git"] = setting.Git
|
2023-02-19 11:12:01 -05:00
|
|
|
ctx.Data["AccessLogTemplate"] = setting.Log.AccessLogTemplate
|
2022-10-16 19:29:26 -04:00
|
|
|
ctx.Data["LogSQL"] = setting.Database.LogSQL
|
|
|
|
|
Rewrite logger system (#24726)
## ⚠️ Breaking
The `log.<mode>.<logger>` style config has been dropped. If you used it,
please check the new config manual & app.example.ini to make your
instance output logs as expected.
Although many legacy options still work, it's encouraged to upgrade to
the new options.
The SMTP logger is deleted because SMTP is not suitable to collect logs.
If you have manually configured Gitea log options, please confirm the
logger system works as expected after upgrading.
## Description
Close #12082 and maybe more log-related issues, resolve some related
FIXMEs in old code (which seems unfixable before)
Just like rewriting queue #24505 : make code maintainable, clear legacy
bugs, and add the ability to support more writers (eg: JSON, structured
log)
There is a new document (with examples): `logging-config.en-us.md`
This PR is safer than the queue rewriting, because it's just for
logging, it won't break other logic.
## The old problems
The logging system is quite old and difficult to maintain:
* Unclear concepts: Logger, NamedLogger, MultiChannelledLogger,
SubLogger, EventLogger, WriterLogger etc
* Some code is diffuclt to konw whether it is right:
`log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs
`log.DelLogger("console")`
* The old system heavily depends on ini config system, it's difficult to
create new logger for different purpose, and it's very fragile.
* The "color" trick is difficult to use and read, many colors are
unnecessary, and in the future structured log could help
* It's difficult to add other log formats, eg: JSON format
* The log outputer doesn't have full control of its goroutine, it's
difficult to make outputer have advanced behaviors
* The logs could be lost in some cases: eg: no Fatal error when using
CLI.
* Config options are passed by JSON, which is quite fragile.
* INI package makes the KEY in `[log]` section visible in `[log.sub1]`
and `[log.sub1.subA]`, this behavior is quite fragile and would cause
more unclear problems, and there is no strong requirement to support
`log.<mode>.<logger>` syntax.
## The new design
See `logger.go` for documents.
## Screenshot
<details>
![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff)
![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9)
![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee)
</details>
## TODO
* [x] add some new tests
* [x] fix some tests
* [x] test some sub-commands (manually ....)
---------
Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-05-21 18:35:11 -04:00
|
|
|
ctx.Data["Loggers"] = log.GetManager().DumpLoggers()
|
|
|
|
|
2023-07-25 23:53:37 -04:00
|
|
|
prepareDeprecatedWarningsAlert(ctx)
|
|
|
|
|
2022-10-16 19:29:26 -04:00
|
|
|
ctx.HTML(http.StatusOK, tplConfig)
|
|
|
|
}
|
|
|
|
|
|
|
|
func ChangeConfig(ctx *context.Context) {
|
|
|
|
key := strings.TrimSpace(ctx.FormString("key"))
|
|
|
|
if key == "" {
|
|
|
|
ctx.JSON(http.StatusOK, map[string]string{
|
|
|
|
"redirect": ctx.Req.URL.String(),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
value := ctx.FormString("value")
|
|
|
|
version := ctx.FormInt("version")
|
|
|
|
|
2023-01-17 10:00:19 -05:00
|
|
|
if check, ok := changeConfigChecks[key]; ok {
|
|
|
|
if err := check(ctx, value); err != nil {
|
|
|
|
log.Warn("refused to set setting: %v", err)
|
|
|
|
ctx.JSON(http.StatusOK, map[string]string{
|
|
|
|
"err": ctx.Tr("admin.config.set_setting_failed", key),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Add context cache as a request level cache (#22294)
To avoid duplicated load of the same data in an HTTP request, we can set
a context cache to do that. i.e. Some pages may load a user from a
database with the same id in different areas on the same page. But the
code is hidden in two different deep logic. How should we share the
user? As a result of this PR, now if both entry functions accept
`context.Context` as the first parameter and we just need to refactor
`GetUserByID` to reuse the user from the context cache. Then it will not
be loaded twice on an HTTP request.
But of course, sometimes we would like to reload an object from the
database, that's why `RemoveContextData` is also exposed.
The core context cache is here. It defines a new context
```go
type cacheContext struct {
ctx context.Context
data map[any]map[any]any
lock sync.RWMutex
}
var cacheContextKey = struct{}{}
func WithCacheContext(ctx context.Context) context.Context {
return context.WithValue(ctx, cacheContextKey, &cacheContext{
ctx: ctx,
data: make(map[any]map[any]any),
})
}
```
Then you can use the below 4 methods to read/write/del the data within
the same context.
```go
func GetContextData(ctx context.Context, tp, key any) any
func SetContextData(ctx context.Context, tp, key, value any)
func RemoveContextData(ctx context.Context, tp, key any)
func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error)
```
Then let's take a look at how `system.GetString` implement it.
```go
func GetSetting(ctx context.Context, key string) (string, error) {
return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) {
return cache.GetString(genSettingCacheKey(key), func() (string, error) {
res, err := GetSettingNoCache(ctx, key)
if err != nil {
return "", err
}
return res.SettingValue, nil
})
})
}
```
First, it will check if context data include the setting object with the
key. If not, it will query from the global cache which may be memory or
a Redis cache. If not, it will get the object from the database. In the
end, if the object gets from the global cache or database, it will be
set into the context cache.
An object stored in the context cache will only be destroyed after the
context disappeared.
2023-02-15 08:37:34 -05:00
|
|
|
if err := system_model.SetSetting(ctx, &system_model.Setting{
|
2022-11-10 01:43:53 -05:00
|
|
|
SettingKey: key,
|
|
|
|
SettingValue: value,
|
|
|
|
Version: version,
|
|
|
|
}); err != nil {
|
2022-10-16 19:29:26 -04:00
|
|
|
log.Error("set setting failed: %v", err)
|
|
|
|
ctx.JSON(http.StatusOK, map[string]string{
|
|
|
|
"err": ctx.Tr("admin.config.set_setting_failed", key),
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-07-04 14:36:08 -04:00
|
|
|
ctx.JSON(http.StatusOK, map[string]any{
|
2022-10-16 19:29:26 -04:00
|
|
|
"version": version + 1,
|
|
|
|
})
|
|
|
|
}
|
2023-01-17 10:00:19 -05:00
|
|
|
|
|
|
|
var changeConfigChecks = map[string]func(ctx *context.Context, newValue string) error{
|
|
|
|
system_model.KeyPictureDisableGravatar: func(_ *context.Context, newValue string) error {
|
|
|
|
if v, _ := strconv.ParseBool(newValue); setting.OfflineMode && !v {
|
|
|
|
return fmt.Errorf("%q should be true when OFFLINE_MODE is true", system_model.KeyPictureDisableGravatar)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
system_model.KeyPictureEnableFederatedAvatar: func(_ *context.Context, newValue string) error {
|
|
|
|
if v, _ := strconv.ParseBool(newValue); setting.OfflineMode && v {
|
|
|
|
return fmt.Errorf("%q cannot be false when OFFLINE_MODE is true", system_model.KeyPictureEnableFederatedAvatar)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|