From 65ba5b924f189d649da58c59ad37c54a75c744c9 Mon Sep 17 00:00:00 2001 From: Giteabot Date: Sun, 14 Apr 2024 20:27:36 +0800 Subject: [PATCH 01/20] fix: Fix to delete cookie when AppSubURL is non-empty (#30375) (#30469) Backport #30375 by @jtran Cookies may exist on "/subpath" and "/subpath/" for some legacy reasons (eg: changed CookiePath behavior in code). The legacy cookie should be removed correctly. Co-authored-by: Jonathan Tran Co-authored-by: wxiaoguang Co-authored-by: Kyle D (cherry picked from commit e64926c5193e9ccc30b34f187d96c74d104179ae) --- modules/session/store.go | 7 ++++++ modules/web/middleware/cookie.go | 34 +++++++++++++++++++++++----- services/auth/source/oauth2/store.go | 3 ++- 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/modules/session/store.go b/modules/session/store.go index 4fa4d2848f..2f7ab7760b 100644 --- a/modules/session/store.go +++ b/modules/session/store.go @@ -6,6 +6,9 @@ package session import ( "net/http" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/web/middleware" + "gitea.com/go-chi/session" ) @@ -18,6 +21,10 @@ type Store interface { // RegenerateSession regenerates the underlying session and returns the new store func RegenerateSession(resp http.ResponseWriter, req *http.Request) (Store, error) { + // Ensure that a cookie with a trailing slash does not take precedence over + // the cookie written by the middleware. + middleware.DeleteLegacySiteCookie(resp, setting.SessionConfig.CookieName) + s, err := session.RegenerateSession(resp, req) return s, err } diff --git a/modules/web/middleware/cookie.go b/modules/web/middleware/cookie.go index 621640895b..0bed726793 100644 --- a/modules/web/middleware/cookie.go +++ b/modules/web/middleware/cookie.go @@ -45,10 +45,32 @@ func SetSiteCookie(resp http.ResponseWriter, name, value string, maxAge int) { SameSite: setting.SessionConfig.SameSite, } resp.Header().Add("Set-Cookie", cookie.String()) - if maxAge < 0 { - // There was a bug in "setting.SessionConfig.CookiePath" code, the old default value of it was empty "". - // So we have to delete the cookie on path="" again, because some old code leaves cookies on path="". - cookie.Path = strings.TrimSuffix(setting.SessionConfig.CookiePath, "/") - resp.Header().Add("Set-Cookie", cookie.String()) - } + // Previous versions would use a cookie path with a trailing /. + // These are more specific than cookies without a trailing /, so + // we need to delete these if they exist. + DeleteLegacySiteCookie(resp, name) +} + +// DeleteLegacySiteCookie deletes the cookie with the given name at the cookie +// path with a trailing /, which would unintentionally override the cookie. +func DeleteLegacySiteCookie(resp http.ResponseWriter, name string) { + if setting.SessionConfig.CookiePath == "" || strings.HasSuffix(setting.SessionConfig.CookiePath, "/") { + // If the cookie path ends with /, no legacy cookies will take + // precedence, so do nothing. The exception is that cookies with no + // path could override other cookies, but it's complicated and we don't + // currently handle that. + return + } + + cookie := &http.Cookie{ + Name: name, + Value: "", + MaxAge: -1, + Path: setting.SessionConfig.CookiePath + "/", + Domain: setting.SessionConfig.Domain, + Secure: setting.SessionConfig.Secure, + HttpOnly: true, + SameSite: setting.SessionConfig.SameSite, + } + resp.Header().Add("Set-Cookie", cookie.String()) } diff --git a/services/auth/source/oauth2/store.go b/services/auth/source/oauth2/store.go index 394bf99463..90fa965602 100644 --- a/services/auth/source/oauth2/store.go +++ b/services/auth/source/oauth2/store.go @@ -9,6 +9,7 @@ import ( "net/http" "code.gitea.io/gitea/modules/log" + session_module "code.gitea.io/gitea/modules/session" chiSession "gitea.com/go-chi/session" "github.com/gorilla/sessions" @@ -65,7 +66,7 @@ func (st *SessionsStore) Save(r *http.Request, w http.ResponseWriter, session *s chiStore := chiSession.GetSession(r) if session.IsNew { - _, _ = chiSession.RegenerateSession(w, r) + _, _ = session_module.RegenerateSession(w, r) session.IsNew = false } From 55447525f67de417382be9f87ce65cbd5bd1162c Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Mon, 15 Apr 2024 01:22:14 +0800 Subject: [PATCH 02/20] Improve "must-change-password" logic and document (#30472) Unify the behaviors of "user create" and "user change-password". Co-authored-by: KN4CK3R (cherry picked from commit 4c6e2da088cf092a9790df5c84b7b338508fede7) Conflicts: - cmd/admin_user_create.go Resolved by favoring Gitea's version of the conflicting areas. - docs/content/administration/command-line.en-us.md Removed, Gitea specific. (cherry picked from commit b122c6ef8b9254120432aed373cbe075331132ac) --- cmd/admin_user_change_password.go | 14 +++++------- cmd/admin_user_create.go | 37 ++++++++++++++++++++----------- models/db/engine.go | 4 ++-- 3 files changed, 31 insertions(+), 24 deletions(-) diff --git a/cmd/admin_user_change_password.go b/cmd/admin_user_change_password.go index 824d66d112..bd9063a8e4 100644 --- a/cmd/admin_user_change_password.go +++ b/cmd/admin_user_change_password.go @@ -36,6 +36,7 @@ var microcmdUserChangePassword = &cli.Command{ &cli.BoolFlag{ Name: "must-change-password", Usage: "User must change password", + Value: true, }, }, } @@ -57,23 +58,18 @@ func runChangePassword(c *cli.Context) error { return err } - var mustChangePassword optional.Option[bool] - if c.IsSet("must-change-password") { - mustChangePassword = optional.Some(c.Bool("must-change-password")) - } - opts := &user_service.UpdateAuthOptions{ Password: optional.Some(c.String("password")), - MustChangePassword: mustChangePassword, + MustChangePassword: optional.Some(c.Bool("must-change-password")), } if err := user_service.UpdateAuth(ctx, user, opts); err != nil { switch { case errors.Is(err, password.ErrMinLength): - return fmt.Errorf("Password is not long enough. Needs to be at least %d", setting.MinPasswordLength) + return fmt.Errorf("password is not long enough, needs to be at least %d characters", setting.MinPasswordLength) case errors.Is(err, password.ErrComplexity): - return errors.New("Password does not meet complexity requirements") + return errors.New("password does not meet complexity requirements") case errors.Is(err, password.ErrIsPwned): - return errors.New("The password you chose is on a list of stolen passwords previously exposed in public data breaches. Please try again with a different password.\nFor more details, see https://haveibeenpwned.com/Passwords") + return errors.New("the password is in a list of stolen passwords previously exposed in public data breaches, please try again with a different password, to see more details: https://haveibeenpwned.com/Passwords") default: return err } diff --git a/cmd/admin_user_create.go b/cmd/admin_user_create.go index 10965c7e8f..caafef536c 100644 --- a/cmd/admin_user_create.go +++ b/cmd/admin_user_create.go @@ -8,6 +8,7 @@ import ( "fmt" auth_model "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" pwd "code.gitea.io/gitea/modules/auth/password" "code.gitea.io/gitea/modules/optional" @@ -46,9 +47,10 @@ var microcmdUserCreate = &cli.Command{ Usage: "Generate a random password for the user", }, &cli.BoolFlag{ - Name: "must-change-password", - Usage: "Set this option to false to prevent forcing the user to change their password after initial login", - Value: true, + Name: "must-change-password", + Usage: "Set this option to false to prevent forcing the user to change their password after initial login", + Value: true, + DisableDefaultText: true, }, &cli.IntFlag{ Name: "random-password-length", @@ -72,10 +74,10 @@ func runCreateUser(c *cli.Context) error { } if c.IsSet("name") && c.IsSet("username") { - return errors.New("Cannot set both --name and --username flags") + return errors.New("cannot set both --name and --username flags") } if !c.IsSet("name") && !c.IsSet("username") { - return errors.New("One of --name or --username flags must be set") + return errors.New("one of --name or --username flags must be set") } if c.IsSet("password") && c.IsSet("random-password") { @@ -111,12 +113,21 @@ func runCreateUser(c *cli.Context) error { return errors.New("must set either password or random-password flag") } - changePassword := c.Bool("must-change-password") - - // If this is the first user being created. - // Take it as the admin and don't force a password update. - if n := user_model.CountUsers(ctx, nil); n == 0 { - changePassword = false + isAdmin := c.Bool("admin") + mustChangePassword := true // always default to true + if c.IsSet("must-change-password") { + // if the flag is set, use the value provided by the user + mustChangePassword = c.Bool("must-change-password") + } else { + // check whether there are users in the database + hasUserRecord, err := db.IsTableNotEmpty(&user_model.User{}) + if err != nil { + return fmt.Errorf("IsTableNotEmpty: %w", err) + } + if !hasUserRecord && isAdmin { + // if this is the first admin being created, don't force to change password (keep the old behavior) + mustChangePassword = false + } } restricted := optional.None[bool]() @@ -132,8 +143,8 @@ func runCreateUser(c *cli.Context) error { Name: username, Email: c.String("email"), Passwd: password, - IsAdmin: c.Bool("admin"), - MustChangePassword: changePassword, + IsAdmin: isAdmin, + MustChangePassword: mustChangePassword, Visibility: visibility, } diff --git a/models/db/engine.go b/models/db/engine.go index 27e5fb9e1a..b3a4171e3f 100755 --- a/models/db/engine.go +++ b/models/db/engine.go @@ -296,8 +296,8 @@ func MaxBatchInsertSize(bean any) int { } // IsTableNotEmpty returns true if table has at least one record -func IsTableNotEmpty(tableName string) (bool, error) { - return x.Table(tableName).Exist() +func IsTableNotEmpty(beanOrTableName any) (bool, error) { + return x.Table(beanOrTableName).Exist() } // DeleteAllRecords will delete all the records of this table From ce31e611e21cec4e5e4b798de7a8b448969c1e8e Mon Sep 17 00:00:00 2001 From: Giteabot Date: Mon, 15 Apr 2024 16:58:09 +0800 Subject: [PATCH 03/20] Fix overflow on issue dependency (#30484) (#30494) Backport #30484 by @silverwind Small tweak here to prevent this and likely other events from overflowing in the timeline: Screenshot 2024-04-14 at 22 53 17 Co-authored-by: silverwind (cherry picked from commit 2efc81d200106cd8707dae1a1bf50ea586b4c846) --- web_src/css/repo.css | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/web_src/css/repo.css b/web_src/css/repo.css index 53766ac0f9..51e134e7e3 100644 --- a/web_src/css/repo.css +++ b/web_src/css/repo.css @@ -1083,6 +1083,12 @@ td .commit-summary { margin-left: 15px; } +.repository.view.issue .comment-list .event .detail .text { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + .repository.view.issue .comment-list .event .segments { box-shadow: none; } From 05523fc96f2269b859c244982dfbb43ce4737341 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 15 Apr 2024 17:31:14 +0800 Subject: [PATCH 04/20] Fix commit status cache which missed target_url (#30426) (#30444) Fix #30421 Backport #30426 Co-authored-by: Jason Song (cherry picked from commit 7ffc0acc424b3116e1a478962b3ea51611c710e3) Conflicts: services/repository/commitstatus/commitstatus.go resolved in the same way as https://codeberg.org/forgejo/forgejo/pulls/3245/files#diff-1122f6e98dabe36f18c4ec06bce75fc9a799d83c --- .../repository/commitstatus/commitstatus.go | 54 ++++++++++++++----- 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/services/repository/commitstatus/commitstatus.go b/services/repository/commitstatus/commitstatus.go index 0bb738e2ad..992889c454 100644 --- a/services/repository/commitstatus/commitstatus.go +++ b/services/repository/commitstatus/commitstatus.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/gitrepo" + "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/services/automerge" @@ -25,12 +26,41 @@ func getCacheKey(repoID int64, brancheName string) string { return fmt.Sprintf("commit_status:%x", hashBytes) } -func updateCommitStatusCache(ctx context.Context, repoID int64, branchName string, status api.CommitStatusState) error { - c := cache.GetCache() - return c.Put(getCacheKey(repoID, branchName), string(status), 3*24*60) +type commitStatusCacheValue struct { + State string `json:"state"` + TargetURL string `json:"target_url"` } -func deleteCommitStatusCache(ctx context.Context, repoID int64, branchName string) error { +func getCommitStatusCache(repoID int64, branchName string) *commitStatusCacheValue { + c := cache.GetCache() + statusStr, ok := c.Get(getCacheKey(repoID, branchName)).(string) + if ok && statusStr != "" { + var cv commitStatusCacheValue + err := json.Unmarshal([]byte(statusStr), &cv) + if err == nil && cv.State != "" { + return &cv + } + if err != nil { + log.Warn("getCommitStatusCache: json.Unmarshal failed: %v", err) + } + } + return nil +} + +func updateCommitStatusCache(repoID int64, branchName string, state api.CommitStatusState, targetURL string) error { + c := cache.GetCache() + bs, err := json.Marshal(commitStatusCacheValue{ + State: state.String(), + TargetURL: targetURL, + }) + if err != nil { + log.Warn("updateCommitStatusCache: json.Marshal failed: %v", err) + return nil + } + return c.Put(getCacheKey(repoID, branchName), string(bs), 3*24*60) +} + +func deleteCommitStatusCache(repoID int64, branchName string) error { c := cache.GetCache() return c.Delete(getCacheKey(repoID, branchName)) } @@ -74,7 +104,7 @@ func CreateCommitStatus(ctx context.Context, repo *repo_model.Repository, creato } if commit.ID.String() == defaultBranchCommit.ID.String() { // since one commit status updated, the combined commit status should be invalid - if err := deleteCommitStatusCache(ctx, repo.ID, repo.DefaultBranch); err != nil { + if err := deleteCommitStatusCache(repo.ID, repo.DefaultBranch); err != nil { log.Error("deleteCommitStatusCache[%d:%s] failed: %v", repo.ID, repo.DefaultBranch, err) } } @@ -91,12 +121,12 @@ func CreateCommitStatus(ctx context.Context, repo *repo_model.Repository, creato // FindReposLastestCommitStatuses loading repository default branch latest combinded commit status with cache func FindReposLastestCommitStatuses(ctx context.Context, repos []*repo_model.Repository) ([]*git_model.CommitStatus, error) { results := make([]*git_model.CommitStatus, len(repos)) - c := cache.GetCache() - for i, repo := range repos { - status, ok := c.Get(getCacheKey(repo.ID, repo.DefaultBranch)).(string) - if ok && status != "" { - results[i] = &git_model.CommitStatus{State: api.CommitStatusState(status)} + if cv := getCommitStatusCache(repo.ID, repo.DefaultBranch); cv != nil { + results[i] = &git_model.CommitStatus{ + State: api.CommitStatusState(cv.State), + TargetURL: cv.TargetURL, + } } } @@ -123,8 +153,8 @@ func FindReposLastestCommitStatuses(ctx context.Context, repos []*repo_model.Rep for i, repo := range repos { if results[i] == nil { results[i] = git_model.CalcCommitStatus(repoToItsLatestCommitStatuses[repo.ID]) - if results[i] != nil { - if err := updateCommitStatusCache(ctx, repo.ID, repo.DefaultBranch, results[i].State); err != nil { + if results[i] != nil && results[i].State != "" { + if err := updateCommitStatusCache(repo.ID, repo.DefaultBranch, results[i].State, results[i].TargetURL); err != nil { log.Error("updateCommitStatusCache[%d:%s] failed: %v", repo.ID, repo.DefaultBranch, err) } } From 889469fb7420ce8d3fe883a0b11095b301d6a3de Mon Sep 17 00:00:00 2001 From: Giteabot Date: Tue, 16 Apr 2024 03:42:15 +0800 Subject: [PATCH 05/20] Convert max file name length to 255 (#30489) (#30504) Backport #30489 by @yp05327 Quick/Partly fix #29907 In Linux and MacOS, by default the max file name length is 255. In windows, it depends on the version and settings, and has no file name length limitation, but has path length limitation. By default it is 260, considering path length is longer than filename, so I think it is ok to do this. For Windows, see https://learn.microsoft.com/windows/win32/fileio/maximum-file-path-limitation?tabs=registry For Linux, see https://github.com/torvalds/linux/blob/master/include/uapi/linux/limits.h#L12-L13 For MacOS, see https://discussions.apple.com/thread/254788848?sortBy=best Co-authored-by: yp05327 <576951401@qq.com> (cherry picked from commit f52b1db305f887c917e6c875b8ac4f8b784b825b) --- templates/repo/editor/edit.tmpl | 2 +- templates/repo/editor/upload.tmpl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/repo/editor/edit.tmpl b/templates/repo/editor/edit.tmpl index 1f5652f6b5..71cecf1514 100644 --- a/templates/repo/editor/edit.tmpl +++ b/templates/repo/editor/edit.tmpl @@ -15,7 +15,7 @@ {{range $i, $v := .TreeNames}} {{if eq $i $l}} - + {{svg "octicon-info"}} {{else}} {{$v}} diff --git a/templates/repo/editor/upload.tmpl b/templates/repo/editor/upload.tmpl index 0a7c49dae3..5725020406 100644 --- a/templates/repo/editor/upload.tmpl +++ b/templates/repo/editor/upload.tmpl @@ -13,7 +13,7 @@ {{range $i, $v := .TreeNames}} {{if eq $i $l}} - + {{svg "octicon-info"}} {{else}} {{$v}} From c044cb2de3e746a96af338414933509d9638de3b Mon Sep 17 00:00:00 2001 From: Giteabot Date: Tue, 16 Apr 2024 08:24:06 +0800 Subject: [PATCH 06/20] Fix various overflows on actions view (#30344) (#30505) Backport #30344 by @silverwind Fix a number of text overflow issues in actions view and run list. Also improve mobile view of run list. Fixes: https://github.com/go-gitea/gitea/issues/30328 Screenshot 2024-04-08 at 23 10 16 Screenshot 2024-04-08 at 23 17 46 Screenshot 2024-04-08 at 23 49 05 Screenshot 2024-04-08 at 23 55 30 Co-authored-by: silverwind (cherry picked from commit 00179f637d9add4e42edf6185cd641eb98115970) --- templates/repo/actions/runs_list.tmpl | 14 ++++++------- web_src/css/actions.css | 26 +++++++++++++++++++++++- web_src/js/components/RepoActionView.vue | 16 ++++++++++----- 3 files changed, 43 insertions(+), 13 deletions(-) diff --git a/templates/repo/actions/runs_list.tmpl b/templates/repo/actions/runs_list.tmpl index ac5049cf56..20330b5d62 100644 --- a/templates/repo/actions/runs_list.tmpl +++ b/templates/repo/actions/runs_list.tmpl @@ -1,4 +1,4 @@ -
+
{{if not .Runs}}
{{svg "octicon-no-entry" 48}} @@ -28,14 +28,14 @@
{{if .RefLink}} - {{.PrettyRef}} + {{.PrettyRef}} {{else}} - {{.PrettyRef}} + {{.PrettyRef}} {{end}} -
-
-
{{svg "octicon-calendar" 16}}{{TimeSinceUnix .Updated ctx.Locale}}
-
{{svg "octicon-stopwatch" 16}}{{.Duration}}
+
+
{{svg "octicon-calendar" 16}}{{TimeSinceUnix .Updated ctx.Locale}}
+
{{svg "octicon-stopwatch" 16}}{{.Duration}}
+
{{end}} diff --git a/web_src/css/actions.css b/web_src/css/actions.css index 1d5bea2395..0ab09f537a 100644 --- a/web_src/css/actions.css +++ b/web_src/css/actions.css @@ -44,9 +44,10 @@ } .run-list-item-right { - flex: 0 0 min(20%, 130px); + width: 130px; display: flex; flex-direction: column; + flex-shrink: 0; gap: 3px; color: var(--color-text-light); } @@ -57,3 +58,26 @@ gap: .25rem; align-items: center; } + +.run-list .flex-item-trailing { + flex-wrap: nowrap; + width: 280px; + flex: 0 0 280px; +} + +.run-list-ref { + display: inline-block !important; +} + +@media (max-width: 767.98px) { + .run-list .flex-item-trailing { + flex-direction: column; + align-items: flex-end; + width: auto; + flex-basis: auto; + } + .run-list-item-right, + .run-list-ref { + max-width: 110px; + } +} diff --git a/web_src/js/components/RepoActionView.vue b/web_src/js/components/RepoActionView.vue index 378f726688..28d1b754a2 100644 --- a/web_src/js/components/RepoActionView.vue +++ b/web_src/js/components/RepoActionView.vue @@ -382,7 +382,7 @@ export function initRepositoryActionView() { -
@@ -391,8 +391,8 @@ export function initRepositoryActionView() { {{ run.commit.shortSHA }} {{ run.commit.localePushedBy }} {{ run.commit.pusher.displayName }} - - {{ run.commit.branch.name }} + + {{ run.commit.branch.name }}
@@ -435,8 +435,8 @@ export function initRepositoryActionView() {
-
-

+
+

{{ currentJob.title }}

@@ -512,6 +512,7 @@ export function initRepositoryActionView() { display: flex; align-items: center; justify-content: space-between; + gap: 8px; } .action-info-summary-title { @@ -522,6 +523,7 @@ export function initRepositoryActionView() { font-size: 20px; margin: 0 0 0 8px; flex: 1; + overflow-wrap: anywhere; } .action-summary { @@ -737,6 +739,10 @@ export function initRepositoryActionView() { font-size: 12px; } +.job-info-header-left { + flex: 1; +} + .job-step-container { max-height: 100%; border-radius: 0 0 var(--border-radius) var(--border-radius); From 9de4bebbf76c93937d82758524064f9e9e0becbd Mon Sep 17 00:00:00 2001 From: Giteabot Date: Wed, 17 Apr 2024 01:34:48 +0800 Subject: [PATCH 07/20] Fix empty field `login_name` in API response JSON when creating user (#30511) (#30516) Backport #30511 by @yp05327 Fix #30508 ps: if `sourceID` is not set, `LoginName` will be ignored Co-authored-by: yp05327 <576951401@qq.com> (cherry picked from commit f9a025f6a358aa6e34408743a59f5081f397d47c) --- routers/api/v1/admin/user.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 12da8a9597..98c9a2697f 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -30,7 +30,7 @@ import ( user_service "code.gitea.io/gitea/services/user" ) -func parseAuthSource(ctx *context.APIContext, u *user_model.User, sourceID int64, loginName string) { +func parseAuthSource(ctx *context.APIContext, u *user_model.User, sourceID int64) { if sourceID == 0 { return } @@ -47,7 +47,6 @@ func parseAuthSource(ctx *context.APIContext, u *user_model.User, sourceID int64 u.LoginType = source.Type u.LoginSource = source.ID - u.LoginName = loginName } // CreateUser create a user @@ -83,12 +82,13 @@ func CreateUser(ctx *context.APIContext) { Passwd: form.Password, MustChangePassword: true, LoginType: auth.Plain, + LoginName: form.LoginName, } if form.MustChangePassword != nil { u.MustChangePassword = *form.MustChangePassword } - parseAuthSource(ctx, u, form.SourceID, form.LoginName) + parseAuthSource(ctx, u, form.SourceID) if ctx.Written() { return } From 6724373288919d366e798694f3b316bee6e7f4eb Mon Sep 17 00:00:00 2001 From: Giteabot Date: Wed, 17 Apr 2024 15:15:02 +0800 Subject: [PATCH 08/20] Tweak and fix toggle checkboxes (#30527) (#30531) Backport #30527 by @silverwind Fixes: https://github.com/go-gitea/gitea/issues/30524. Slightly restyled them so that the "knob" is contained inside the background. Screenshot 2024-04-16 at 21 58 09 Screenshot 2024-04-16 at 21 58 50 Co-authored-by: silverwind (cherry picked from commit d5525b714322bf8a39334b045dffe368c6207e01) --- web_src/css/modules/checkbox.css | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/web_src/css/modules/checkbox.css b/web_src/css/modules/checkbox.css index d3e45714a4..8d73573bfa 100644 --- a/web_src/css/modules/checkbox.css +++ b/web_src/css/modules/checkbox.css @@ -66,7 +66,7 @@ input[type="radio"] { } .ui.toggle.checkbox input { width: 3.5rem; - height: 1.5rem; + height: 21px; opacity: 0; z-index: 3; } @@ -81,29 +81,30 @@ input[type="radio"] { content: ""; z-index: 1; top: 0; - width: 3.5rem; - height: 1.5rem; + width: 49px; + height: 21px; border-radius: 500rem; left: 0; } .ui.toggle.checkbox label::after { background: var(--color-white); + box-shadow: 1px 1px 4px 1px var(--color-shadow); position: absolute; content: ""; opacity: 1; z-index: 2; - width: 1.5rem; - height: 1.5rem; - top: 0; - left: 0; + width: 18px; + height: 18px; + top: 1.5px; + left: 1.5px; border-radius: 500rem; transition: background 0.3s ease, left 0.3s ease; } .ui.toggle.checkbox input ~ label::after { - left: -0.05rem; + left: 1.5px; } .ui.toggle.checkbox input:checked ~ label::after { - left: 2.15rem; + left: 29px; } .ui.toggle.checkbox input:focus ~ label::before, .ui.toggle.checkbox label::before { From 141efd58df1c894bf8b3f19ef5753a274ffb93a3 Mon Sep 17 00:00:00 2001 From: Giteabot Date: Wed, 17 Apr 2024 16:51:38 +0800 Subject: [PATCH 09/20] Fix install page checkboxes and dropdown width (#30526) (#30538) Backport #30526 by @silverwind Fixes: https://github.com/go-gitea/gitea/issues/30523 1. Fix checkbox rendering: Screenshot 2024-04-16 at 21 37 03 2. Fix width of selection dropdowns (was too small): Screenshot 2024-04-16 at 21 37 09 Co-authored-by: silverwind Co-authored-by: delvh (cherry picked from commit caeed3af6ea239541d0f319c1f2da8233e04b173) --- web_src/css/install.css | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web_src/css/install.css b/web_src/css/install.css index 4ac294e902..ee2395e6c5 100644 --- a/web_src/css/install.css +++ b/web_src/css/install.css @@ -18,7 +18,8 @@ width: auto; } -.page-content.install form.ui.form input { +.page-content.install form.ui.form input:not([type="checkbox"],[type="radio"]), +.page-content.install form.ui.form .ui.selection.dropdown { width: 60%; } From d6689b88a8cc437a4ac641021b433393138c2f36 Mon Sep 17 00:00:00 2001 From: silverwind Date: Wed, 17 Apr 2024 11:40:35 +0200 Subject: [PATCH 10/20] Run `go generate` and `go vet` on all packages (#30529) Fixes: https://github.com/go-gitea/gitea/issues/30512 I think this does mean those tools would run on a potential `vendor` directory, but I'm not sure we really support vendoring of dependencies anymore. `release` has a `vendor` prerequisite so likely the source tarballs contain vendor files? (cherry picked from commit 8e12ef911a1d10dedb03e3127c42ca76f9850aca) Conflicts: - Makefile Manually adjusted the changes. (cherry picked from commit 3918db10c82e31196f75631aceb991c4a0a93cc7) --- Makefile | 5 ++--- tests/integration/api_comment_attachment_test.go | 3 +-- tests/integration/api_issue_attachment_test.go | 3 +-- tests/integration/api_packages_cargo_test.go | 3 +-- tests/integration/markup_external_test.go | 3 +-- tests/integration/repo_mergecommit_revert_test.go | 3 +++ 6 files changed, 9 insertions(+), 11 deletions(-) diff --git a/Makefile b/Makefile index fec96de982..fe989d2add 100644 --- a/Makefile +++ b/Makefile @@ -121,7 +121,6 @@ LDFLAGS := $(LDFLAGS) -X "main.ReleaseVersion=$(RELEASE_VERSION)" -X "main.MakeV LINUX_ARCHS ?= linux/amd64,linux/386,linux/arm-5,linux/arm-6,linux/arm64 ifeq ($(HAS_GO), yes) - GO_PACKAGES ?= $(filter-out code.gitea.io/gitea/tests/integration/migration-test code.gitea.io/gitea/tests code.gitea.io/gitea/tests/integration code.gitea.io/gitea/tests/e2e,$(shell $(GO) list ./... | grep -v /vendor/)) GO_TEST_PACKAGES ?= $(filter-out $(shell $(GO) list code.gitea.io/gitea/models/migrations/...) $(shell $(GO) list code.gitea.io/gitea/models/forgejo_migrations/...) code.gitea.io/gitea/tests/integration/migration-test code.gitea.io/gitea/tests code.gitea.io/gitea/tests/integration code.gitea.io/gitea/tests/e2e,$(shell $(GO) list ./... | grep -v /vendor/)) endif @@ -457,7 +456,7 @@ lint-go-windows: .PHONY: lint-go-vet lint-go-vet: @echo "Running go vet..." - @$(GO) vet $(GO_PACKAGES) + @$(GO) vet ./... .PHONY: lint-editorconfig lint-editorconfig: @@ -823,7 +822,7 @@ generate-backend: $(TAGS_PREREQ) generate-go .PHONY: generate-go generate-go: $(TAGS_PREREQ) @echo "Running go generate..." - @CC= GOOS= GOARCH= $(GO) generate -tags '$(TAGS)' $(GO_PACKAGES) + @CC= GOOS= GOARCH= $(GO) generate -tags '$(TAGS)' ./... .PHONY: merge-locales merge-locales: diff --git a/tests/integration/api_comment_attachment_test.go b/tests/integration/api_comment_attachment_test.go index b6f3d3bc81..d4368d51fe 100644 --- a/tests/integration/api_comment_attachment_test.go +++ b/tests/integration/api_comment_attachment_test.go @@ -1,6 +1,5 @@ // Copyright 2021 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package integration diff --git a/tests/integration/api_issue_attachment_test.go b/tests/integration/api_issue_attachment_test.go index 375fe9ced8..b6a0cca6d5 100644 --- a/tests/integration/api_issue_attachment_test.go +++ b/tests/integration/api_issue_attachment_test.go @@ -1,6 +1,5 @@ // Copyright 2021 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package integration diff --git a/tests/integration/api_packages_cargo_test.go b/tests/integration/api_packages_cargo_test.go index 869d90066a..55cce50c7b 100644 --- a/tests/integration/api_packages_cargo_test.go +++ b/tests/integration/api_packages_cargo_test.go @@ -1,6 +1,5 @@ // Copyright 2021 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package integration diff --git a/tests/integration/markup_external_test.go b/tests/integration/markup_external_test.go index 5f102f8d62..e50f5c1356 100644 --- a/tests/integration/markup_external_test.go +++ b/tests/integration/markup_external_test.go @@ -1,6 +1,5 @@ // Copyright 2022 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package integration diff --git a/tests/integration/repo_mergecommit_revert_test.go b/tests/integration/repo_mergecommit_revert_test.go index 7041861f11..eb75d45c15 100644 --- a/tests/integration/repo_mergecommit_revert_test.go +++ b/tests/integration/repo_mergecommit_revert_test.go @@ -1,3 +1,6 @@ +// Copyright 2024 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + package integration import ( From f436cb86d409ed027b7155281224778ab513b22a Mon Sep 17 00:00:00 2001 From: Giteabot Date: Wed, 17 Apr 2024 21:50:49 +0800 Subject: [PATCH 11/20] Fix branch_protection api shows users/teams who has no readAccess (#30291) (#30544) Backport #30291 by @edwardzhanged Add some logic in `convert.ToBranchProtection` to return only the names associated with readAccess instead of returning all names. This will ensure consistency in behavior between the frontend and backend. Fixes: #27694 Co-authored-by: Edward Zhang <45360012+edwardzhanged@users.noreply.github.com> Co-authored-by: techknowlogick Co-authored-by: wenzhuo.zhang (cherry picked from commit d88958bb99eabc07dead6965e396755e7b6d947f) --- routers/api/v1/repo/branch.go | 8 ++--- services/convert/convert.go | 56 ++++++++++++++++++++++------------- 2 files changed, 39 insertions(+), 25 deletions(-) diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index c33beee0ae..852b7a2ee0 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -437,7 +437,7 @@ func GetBranchProtection(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToBranchProtection(ctx, bp)) + ctx.JSON(http.StatusOK, convert.ToBranchProtection(ctx, bp, repo)) } // ListBranchProtections list branch protections for a repo @@ -470,7 +470,7 @@ func ListBranchProtections(ctx *context.APIContext) { } apiBps := make([]*api.BranchProtection, len(bps)) for i := range bps { - apiBps[i] = convert.ToBranchProtection(ctx, bps[i]) + apiBps[i] = convert.ToBranchProtection(ctx, bps[i], repo) } ctx.JSON(http.StatusOK, apiBps) @@ -682,7 +682,7 @@ func CreateBranchProtection(ctx *context.APIContext) { return } - ctx.JSON(http.StatusCreated, convert.ToBranchProtection(ctx, bp)) + ctx.JSON(http.StatusCreated, convert.ToBranchProtection(ctx, bp, repo)) } // EditBranchProtection edits a branch protection for a repo @@ -964,7 +964,7 @@ func EditBranchProtection(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToBranchProtection(ctx, bp)) + ctx.JSON(http.StatusOK, convert.ToBranchProtection(ctx, bp, repo)) } // DeleteBranchProtection deletes a branch protection for a repo diff --git a/services/convert/convert.go b/services/convert/convert.go index dd2239458e..70ca5da2ec 100644 --- a/services/convert/convert.go +++ b/services/convert/convert.go @@ -21,6 +21,7 @@ import ( repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/container" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" api "code.gitea.io/gitea/modules/structs" @@ -105,33 +106,46 @@ func ToBranch(ctx context.Context, repo *repo_model.Repository, branchName strin return branch, nil } +// getWhitelistEntities returns the names of the entities that are in the whitelist +func getWhitelistEntities[T *user_model.User | *organization.Team](entities []T, whitelistIDs []int64) []string { + whitelistUserIDsSet := container.SetOf(whitelistIDs...) + whitelistNames := make([]string, 0) + for _, entity := range entities { + switch v := any(entity).(type) { + case *user_model.User: + if whitelistUserIDsSet.Contains(v.ID) { + whitelistNames = append(whitelistNames, v.Name) + } + case *organization.Team: + if whitelistUserIDsSet.Contains(v.ID) { + whitelistNames = append(whitelistNames, v.Name) + } + } + } + + return whitelistNames +} + // ToBranchProtection convert a ProtectedBranch to api.BranchProtection -func ToBranchProtection(ctx context.Context, bp *git_model.ProtectedBranch) *api.BranchProtection { - pushWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.WhitelistUserIDs) +func ToBranchProtection(ctx context.Context, bp *git_model.ProtectedBranch, repo *repo_model.Repository) *api.BranchProtection { + readers, err := access_model.GetRepoReaders(ctx, repo) if err != nil { - log.Error("GetUserNamesByIDs (WhitelistUserIDs): %v", err) + log.Error("GetRepoReaders: %v", err) } - mergeWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.MergeWhitelistUserIDs) + + pushWhitelistUsernames := getWhitelistEntities(readers, bp.WhitelistUserIDs) + mergeWhitelistUsernames := getWhitelistEntities(readers, bp.MergeWhitelistUserIDs) + approvalsWhitelistUsernames := getWhitelistEntities(readers, bp.ApprovalsWhitelistUserIDs) + + teamReaders, err := organization.OrgFromUser(repo.Owner).TeamsWithAccessToRepo(ctx, repo.ID, perm.AccessModeRead) if err != nil { - log.Error("GetUserNamesByIDs (MergeWhitelistUserIDs): %v", err) - } - approvalsWhitelistUsernames, err := user_model.GetUserNamesByIDs(ctx, bp.ApprovalsWhitelistUserIDs) - if err != nil { - log.Error("GetUserNamesByIDs (ApprovalsWhitelistUserIDs): %v", err) - } - pushWhitelistTeams, err := organization.GetTeamNamesByID(ctx, bp.WhitelistTeamIDs) - if err != nil { - log.Error("GetTeamNamesByID (WhitelistTeamIDs): %v", err) - } - mergeWhitelistTeams, err := organization.GetTeamNamesByID(ctx, bp.MergeWhitelistTeamIDs) - if err != nil { - log.Error("GetTeamNamesByID (MergeWhitelistTeamIDs): %v", err) - } - approvalsWhitelistTeams, err := organization.GetTeamNamesByID(ctx, bp.ApprovalsWhitelistTeamIDs) - if err != nil { - log.Error("GetTeamNamesByID (ApprovalsWhitelistTeamIDs): %v", err) + log.Error("Repo.Owner.TeamsWithAccessToRepo: %v", err) } + pushWhitelistTeams := getWhitelistEntities(teamReaders, bp.WhitelistTeamIDs) + mergeWhitelistTeams := getWhitelistEntities(teamReaders, bp.MergeWhitelistTeamIDs) + approvalsWhitelistTeams := getWhitelistEntities(teamReaders, bp.ApprovalsWhitelistTeamIDs) + branchName := "" if !git_model.IsRuleNameSpecial(bp.RuleName) { branchName = bp.RuleName From cb4246ed570f14a3320658f5693246deeebad64a Mon Sep 17 00:00:00 2001 From: Giteabot Date: Thu, 18 Apr 2024 17:38:32 +0800 Subject: [PATCH 12/20] Disable enter key for accepting code completion in Monaco (#30548) (#30559) Backport #30548 by @silverwind Fixes https://github.com/go-gitea/gitea/issues/28114 and behaviour matches vscode on desktop as well. Co-authored-by: silverwind (cherry picked from commit c9633f2d74490211ffd9fd6b3a17180e86fa1fb9) --- web_src/js/features/codeeditor.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/web_src/js/features/codeeditor.js b/web_src/js/features/codeeditor.js index 4fb8bb9e63..f5e4e74dc6 100644 --- a/web_src/js/features/codeeditor.js +++ b/web_src/js/features/codeeditor.js @@ -112,6 +112,10 @@ export async function createMonaco(textarea, filename, editorOpts) { ...other, }); + monaco.editor.addKeybindingRules([ + {keybinding: monaco.KeyCode.Enter, command: null}, // disable enter from accepting code completion + ]); + const model = editor.getModel(); model.onDidChangeContent(() => { textarea.value = editor.getValue({preserveBOM: true}); From 1d8316f27831d6a77837d649ea09b94c66926cba Mon Sep 17 00:00:00 2001 From: Giteabot Date: Thu, 18 Apr 2024 18:04:47 +0800 Subject: [PATCH 13/20] Fix border-radius on view, blame and code search (#30545) (#30560) Backport #30545 by @silverwind Fixes: https://github.com/go-gitea/gitea/issues/30540 1. Fix all these boxes by adding `bottom attached` and removing a problematic CSS rule: Screenshot 2024-04-17 at 22 25 31 Screenshot 2024-04-17 at 22 21 18 2. Change the "last commit" box to `ui segment` which has correct border-radius. Also included is a tiny tweak to make author name ellipse instead of wrap. Screenshot 2024-04-17 at 22 23 23 Co-authored-by: silverwind (cherry picked from commit b4a38318c333519b1008d03fd01e14a803363498) --- templates/repo/blame.tmpl | 2 +- templates/repo/settings/lfs_file.tmpl | 2 +- templates/repo/view_file.tmpl | 4 ++-- web_src/css/repo.css | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/templates/repo/blame.tmpl b/templates/repo/blame.tmpl index 45cf841748..01978dacf7 100644 --- a/templates/repo/blame.tmpl +++ b/templates/repo/blame.tmpl @@ -28,7 +28,7 @@

-
+
{{if .IsFileTooLarge}} diff --git a/templates/repo/settings/lfs_file.tmpl b/templates/repo/settings/lfs_file.tmpl index 43afba96c3..5bcd2af5bf 100644 --- a/templates/repo/settings/lfs_file.tmpl +++ b/templates/repo/settings/lfs_file.tmpl @@ -11,7 +11,7 @@ {{ctx.Locale.Tr "repo.settings.lfs_findcommits"}} -
+
{{template "repo/unicode_escape_prompt" dict "EscapeStatus" .EscapeStatus "root" $}}
{{if .IsMarkup}} diff --git a/templates/repo/view_file.tmpl b/templates/repo/view_file.tmpl index 333121c205..dfbc45dd61 100644 --- a/templates/repo/view_file.tmpl +++ b/templates/repo/view_file.tmpl @@ -11,7 +11,7 @@ {{end}} {{if not .ReadmeInList}} -
+
{{template "repo/latest_commit" .}}
@@ -93,7 +93,7 @@ {{end}}
-
+
{{if not (or .IsMarkup .IsRenderedHTML)}} {{template "repo/unicode_escape_prompt" dict "EscapeStatus" .EscapeStatus "root" $}} {{end}} diff --git a/web_src/css/repo.css b/web_src/css/repo.css index 51e134e7e3..0093cb3eb5 100644 --- a/web_src/css/repo.css +++ b/web_src/css/repo.css @@ -435,7 +435,6 @@ td .commit-summary { padding: 0 !important; } -.non-diff-file-content .attached.segment, .non-diff-file-content .pdfobject { border-radius: 0 0 var(--border-radius) var(--border-radius); } @@ -2524,6 +2523,7 @@ tbody.commit-list { .author-wrapper { max-width: 180px; align-self: center; + white-space: nowrap; } /* in the commit list, messages can wrap so we can use inline */ From 6ad77581178291f6f9b2c976fdefb1bd9269b628 Mon Sep 17 00:00:00 2001 From: Jerry Jacobs Date: Thu, 18 Apr 2024 13:22:06 +0200 Subject: [PATCH 14/20] Fixup app.example.ini for task section, which is now queue.task (#30555) Config section `[task]` has been deprecated in favor of `[queue.task]` --------- Co-authored-by: wxiaoguang (cherry picked from commit 86d4c8a4662e9ab49888569d77529d2d22292e6b) Conflicts: - docs/content/administration/config-cheat-sheet.en-us.md - docs/content/administration/config-cheat-sheet.zh-cn.md Removed, they're Gitea specific. (cherry picked from commit 5271792666c9e9c8a854f79deffc836628bfb3f3) --- custom/conf/app.example.ini | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index 74999b5bb3..72dcaddb60 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -2387,22 +2387,6 @@ LEVEL = Info ;; Enable issue by repository metrics; default is false ;ENABLED_ISSUE_BY_REPOSITORY = false -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;[task] -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; Task queue type, could be `channel` or `redis`. -;QUEUE_TYPE = channel -;; -;; Task queue length, available only when `QUEUE_TYPE` is `channel`. -;QUEUE_LENGTH = 1000 -;; -;; Task queue connection string, available only when `QUEUE_TYPE` is `redis`. -;; If there is a password of redis, use `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s` or `redis+cluster://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s` for `redis-clsuter`. -;QUEUE_CONN_STR = "redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s" - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;[migrations] From f31879069f7db9250232009cee06c88179d6ee19 Mon Sep 17 00:00:00 2001 From: Giteabot Date: Fri, 19 Apr 2024 03:58:37 +0800 Subject: [PATCH 15/20] Improve "Reference in new issue" modal (#30547) (#30574) Backport #30547 by @silverwind Fixes: https://github.com/go-gitea/gitea/issues/29994 Also some misc enhancements done to the form in the modal. Screenshot 2024-04-17 at 23 02 55 Co-authored-by: silverwind (cherry picked from commit 42019677e6cce6ae44a922e68b91d2a002450fa0) --- .../view_content/reference_issue_dialog.tmpl | 34 +++++++++---------- web_src/css/base.css | 7 ++++ 2 files changed, 23 insertions(+), 18 deletions(-) diff --git a/templates/repo/issue/view_content/reference_issue_dialog.tmpl b/templates/repo/issue/view_content/reference_issue_dialog.tmpl index 5f338f6768..f6ac4192ab 100644 --- a/templates/repo/issue/view_content/reference_issue_dialog.tmpl +++ b/templates/repo/issue/view_content/reference_issue_dialog.tmpl @@ -5,26 +5,24 @@
{{.CsrfTokenHtml}} -
-
- {{ctx.Locale.Tr "repository"}} - -
-
- {{ctx.Locale.Tr "repo.milestones.title"}} - -
-
- {{ctx.Locale.Tr "repo.issues.reference_issue.body"}} - -
-
- +
+ +
+
+ + +
+
+ + +
+
+ +
diff --git a/web_src/css/base.css b/web_src/css/base.css index a1f9c087fd..7c13f352cd 100644 --- a/web_src/css/base.css +++ b/web_src/css/base.css @@ -496,6 +496,7 @@ ol.ui.list li, .ui.selection.dropdown .menu > .item { border-color: var(--color-secondary); + white-space: nowrap; } .ui.selection.visible.dropdown > .text:not(.default) { @@ -517,6 +518,12 @@ ol.ui.list li, color: var(--color-text-light-2); } +.ui.dropdown > .text { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + /* extend fomantic style '.ui.dropdown > .text > img' to include svg.img */ .ui.dropdown > .text > .img { margin-left: 0; From 0412657132ea7bcb964aa428aa940e004c98bd9a Mon Sep 17 00:00:00 2001 From: Giteabot Date: Fri, 19 Apr 2024 15:44:24 +0800 Subject: [PATCH 16/20] Avoid importing `modules/web/middleware` in `modules/session` (#30584) (#30589) Backport #30584 by @wolfogre Related to #30375. It doesn't make sense to import `modules/web/middleware` and `modules/setting` in `modules/web/session` since the last one is more low-level. And it looks like a workaround to call `DeleteLegacySiteCookie` in `RegenerateSession`, so maybe we could reverse the importing by registering hook functions. Co-authored-by: Jason Song (cherry picked from commit 199397a852ec2d45524cefcc3c119fce4710560e) --- modules/session/store.go | 13 ++++++------- modules/web/middleware/cookie.go | 15 ++++++++++++--- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/modules/session/store.go b/modules/session/store.go index 2f7ab7760b..70988fcdc5 100644 --- a/modules/session/store.go +++ b/modules/session/store.go @@ -6,9 +6,6 @@ package session import ( "net/http" - "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/web/middleware" - "gitea.com/go-chi/session" ) @@ -21,10 +18,12 @@ type Store interface { // RegenerateSession regenerates the underlying session and returns the new store func RegenerateSession(resp http.ResponseWriter, req *http.Request) (Store, error) { - // Ensure that a cookie with a trailing slash does not take precedence over - // the cookie written by the middleware. - middleware.DeleteLegacySiteCookie(resp, setting.SessionConfig.CookieName) - + for _, f := range BeforeRegenerateSession { + f(resp, req) + } s, err := session.RegenerateSession(resp, req) return s, err } + +// BeforeRegenerateSession is a list of functions that are called before a session is regenerated. +var BeforeRegenerateSession []func(http.ResponseWriter, *http.Request) diff --git a/modules/web/middleware/cookie.go b/modules/web/middleware/cookie.go index 0bed726793..ec6b06f993 100644 --- a/modules/web/middleware/cookie.go +++ b/modules/web/middleware/cookie.go @@ -9,6 +9,7 @@ import ( "net/url" "strings" + "code.gitea.io/gitea/modules/session" "code.gitea.io/gitea/modules/setting" ) @@ -48,12 +49,12 @@ func SetSiteCookie(resp http.ResponseWriter, name, value string, maxAge int) { // Previous versions would use a cookie path with a trailing /. // These are more specific than cookies without a trailing /, so // we need to delete these if they exist. - DeleteLegacySiteCookie(resp, name) + deleteLegacySiteCookie(resp, name) } -// DeleteLegacySiteCookie deletes the cookie with the given name at the cookie +// deleteLegacySiteCookie deletes the cookie with the given name at the cookie // path with a trailing /, which would unintentionally override the cookie. -func DeleteLegacySiteCookie(resp http.ResponseWriter, name string) { +func deleteLegacySiteCookie(resp http.ResponseWriter, name string) { if setting.SessionConfig.CookiePath == "" || strings.HasSuffix(setting.SessionConfig.CookiePath, "/") { // If the cookie path ends with /, no legacy cookies will take // precedence, so do nothing. The exception is that cookies with no @@ -74,3 +75,11 @@ func DeleteLegacySiteCookie(resp http.ResponseWriter, name string) { } resp.Header().Add("Set-Cookie", cookie.String()) } + +func init() { + session.BeforeRegenerateSession = append(session.BeforeRegenerateSession, func(resp http.ResponseWriter, _ *http.Request) { + // Ensure that a cookie with a trailing slash does not take precedence over + // the cookie written by the middleware. + deleteLegacySiteCookie(resp, setting.SessionConfig.CookieName) + }) +} From d802a8c0cf8b8cb788f1fd200de464ab56418826 Mon Sep 17 00:00:00 2001 From: Giteabot Date: Sat, 20 Apr 2024 04:32:49 +0800 Subject: [PATCH 17/20] Fix HEAD method for robots.txt (#30603) (#30605) Backport #30603 by @wxiaoguang Fix #30601 ``` ~$ curl --head localhost:3000/robots.txt HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: max-age=0, private, must-revalidate Content-Length: 5 Content-Type: text/plain; charset=utf-8 Last-Modified: Wed, 19 Jul 2023 04:56:12 GMT X-Gitea-Debug: RUN_MODE=dev Date: Fri, 19 Apr 2024 12:59:44 GMT ``` Co-authored-by: wxiaoguang (cherry picked from commit 7eaf7907d7f71e103baced018e6eeb271085789d) --- routers/web/web.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/web/web.go b/routers/web/web.go index 40f4ffc018..1d085a37cb 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -258,7 +258,7 @@ func Routes() *web.Route { routes.Get("/metrics", append(mid, Metrics)...) } - routes.Get("/robots.txt", append(mid, misc.RobotsTxt)...) + routes.Methods("GET,HEAD", "/robots.txt", append(mid, misc.RobotsTxt)...) routes.Get("/ssh_info", misc.SSHInfo) routes.Get("/api/healthz", healthcheck.Check) From 0a9bbdcfeff673b94af2e8e51971bf45823c7a6a Mon Sep 17 00:00:00 2001 From: yp05327 <576951401@qq.com> Date: Sat, 20 Apr 2024 09:35:29 +0900 Subject: [PATCH 18/20] Use action user as the trigger user of schedules (#30581) Follow https://github.com/go-gitea/gitea/pull/30357 When user push to default branch, the schedule trigger user will be the user. When disable then enable action units in settings, the schedule trigger user will be action user. When repo is a mirror, the schedule trigger user will be action user. ( before it will return error, fixed by #30357) As scheduled job is a cron, the trigger user should be action user from Gitea, not a real user. --------- Co-authored-by: Giteabot (cherry picked from commit cb6814adad4dc81a683b50826a211ce7bce731d7) Conflicts: - services/actions/notifier_helper.go Conflict resolved by keeping Forgejo's version of the line. (cherry picked from commit 829c3c683837b8c7e278565d64369a5216c271f1) --- services/actions/notifier_helper.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/services/actions/notifier_helper.go b/services/actions/notifier_helper.go index ef37ff87ee..365212d9c2 100644 --- a/services/actions/notifier_helper.go +++ b/services/actions/notifier_helper.go @@ -80,6 +80,11 @@ func newNotifyInput(repo *repo_model.Repository, doer *user_model.User, event we } } +func newNotifyInputForSchedules(repo *repo_model.Repository) *notifyInput { + // the doer here will be ignored as we force using action user when handling schedules + return newNotifyInput(repo, user_model.NewActionsUser(), webhook_module.HookEventSchedule) +} + func (input *notifyInput) WithDoer(doer *user_model.User) *notifyInput { input.Doer = doer return input @@ -562,7 +567,7 @@ func DetectAndHandleSchedules(ctx context.Context, repo *repo_model.Repository) // We need a notifyInput to call handleSchedules // if repo is a mirror, commit author maybe an external user, // so we use action user as the Doer of the notifyInput - notifyInput := newNotifyInput(repo, user_model.NewActionsUser(), webhook_module.HookEventSchedule) + notifyInput := newNotifyInputForSchedules(repo) return handleSchedules(ctx, scheduleWorkflows, commit, notifyInput, repo.DefaultBranch) } From 4777ba210f4c78e12d3700a0f4c45343b5459fd5 Mon Sep 17 00:00:00 2001 From: Giteabot Date: Sun, 21 Apr 2024 08:50:50 +0800 Subject: [PATCH 19/20] Fix package list performance (#30520) (#30616) Backport #30520 by @KN4CK3R Fixes #28255 The new query uses the id field to sort by "newer". This most not be correct (usually it is) but it's faster (see #28255). If someone has a better idea, please propose changes. Co-authored-by: KN4CK3R (cherry picked from commit ea2ea8ef28b6a2207ec00bafaf42d428612d69eb) --- models/packages/package_version.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/models/packages/package_version.go b/models/packages/package_version.go index 505dbaa0a5..278e8e3a86 100644 --- a/models/packages/package_version.go +++ b/models/packages/package_version.go @@ -287,9 +287,10 @@ func (opts *PackageSearchOptions) configureOrderBy(e db.Engine) { // SearchVersions gets all versions of packages matching the search options func SearchVersions(ctx context.Context, opts *PackageSearchOptions) ([]*PackageVersion, int64, error) { sess := db.GetEngine(ctx). - Where(opts.ToConds()). + Select("package_version.*"). Table("package_version"). - Join("INNER", "package", "package.id = package_version.package_id") + Join("INNER", "package", "package.id = package_version.package_id"). + Where(opts.ToConds()) opts.configureOrderBy(sess) @@ -304,19 +305,18 @@ func SearchVersions(ctx context.Context, opts *PackageSearchOptions) ([]*Package // SearchLatestVersions gets the latest version of every package matching the search options func SearchLatestVersions(ctx context.Context, opts *PackageSearchOptions) ([]*PackageVersion, int64, error) { - cond := opts.ToConds(). - And(builder.Expr("pv2.id IS NULL")) - - joinCond := builder.Expr("package_version.package_id = pv2.package_id AND (package_version.created_unix < pv2.created_unix OR (package_version.created_unix = pv2.created_unix AND package_version.id < pv2.id))") - if opts.IsInternal.Has() { - joinCond = joinCond.And(builder.Eq{"pv2.is_internal": opts.IsInternal.Value()}) - } + in := builder. + Select("MAX(package_version.id)"). + From("package_version"). + InnerJoin("package", "package.id = package_version.package_id"). + Where(opts.ToConds()). + GroupBy("package_version.package_id") sess := db.GetEngine(ctx). + Select("package_version.*"). Table("package_version"). - Join("LEFT", "package_version pv2", joinCond). Join("INNER", "package", "package.id = package_version.package_id"). - Where(cond) + Where(builder.In("package_version.id", in)) opts.configureOrderBy(sess) From eefa82087461027aefde1185e54f3d99b4942cd3 Mon Sep 17 00:00:00 2001 From: Earl Warren Date: Sun, 21 Apr 2024 18:44:11 +0200 Subject: [PATCH 20/20] [DEADCODE] update --- .deadcode-out | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.deadcode-out b/.deadcode-out index 940551da04..5e6f81780f 100644 --- a/.deadcode-out +++ b/.deadcode-out @@ -66,6 +66,7 @@ package "code.gitea.io/gitea/models/migrations/base" func MainTest package "code.gitea.io/gitea/models/organization" + func GetTeamNamesByID func UpdateTeamUnits func (SearchMembersOptions).ToConds func UsersInTeamsCount @@ -131,6 +132,7 @@ package "code.gitea.io/gitea/models/user" func GetUserAllSettings func DeleteUserSetting func GetUserEmailsByNames + func GetUserNamesByIDs package "code.gitea.io/gitea/modules/activitypub" func CurrentTime