mirror of
https://github.com/go-gitea/gitea.git
synced 2026-11-17 04:47:10 +09:00
refactor: user error system (#40308)
Introduce "FlashErrorAuto" for "XxxErrorAuto" family and simplify the error handling logic. * Use ErrorUnwrapForHTML for web error messages * Use ErrorUnwrapForUser for api error messages * Make Flash message can take up to about 3000 bytes Next step: completely refactor "ctx.ServerError" --------- Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
1 parent
518e08c2c7
commit
d1d702bea9
20 files changed
+309
-194
No files matched your search
@@ -43,7 +43,12 @@ func IsErrUserNotExist(err error) bool {
|
||||
}
|
||||
|
||||
func (err ErrUserNotExist) Error() string {
|
||||
ret := fmt.Sprintf("user does not exist [uid: %d, name: %s]", err.UID, err.Name)
|
||||
ret := "user does not exist"
|
||||
if err.UID != 0 {
|
||||
ret += fmt.Sprintf(" [id: %d]", err.UID)
|
||||
} else if err.Name != "" {
|
||||
ret += fmt.Sprintf(" [name: %s]", err.Name)
|
||||
}
|
||||
if err.ExtraMsg != "" {
|
||||
ret += ": " + err.ExtraMsg
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ func TestSanitizer(t *testing.T) {
|
||||
// Regular
|
||||
`<a onblur="alert(secret)" href="http://www.google.com">Google</a>`, `<a href="http://www.google.com" rel="nofollow">Google</a>`,
|
||||
"<scrİpt><script>alert(document.domain)</script></scrİpt>", "<script>alert(document.domain)</script>",
|
||||
`<details>unclosed`, `<details>unclosed`,
|
||||
`<div>unclosed</`, `<div>unclosed</`,
|
||||
|
||||
// Code highlighting class
|
||||
`<code class="random string"></code>`, `<code></code>`,
|
||||
|
||||
+51
-32
@@ -6,6 +6,7 @@ package util
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"html/template"
|
||||
)
|
||||
|
||||
@@ -13,13 +14,6 @@ import (
|
||||
// These errors can be used to classify errors and to provide a common,
|
||||
// safe (no server-side sensitive information), and translatable error message for end users.
|
||||
|
||||
// ErrorTranslatable wraps an error with translation information
|
||||
type ErrorTranslatable interface {
|
||||
error
|
||||
Unwrap() error
|
||||
Translate(ErrorLocaleTranslator) template.HTML
|
||||
}
|
||||
|
||||
var (
|
||||
ErrInvalidArgument = errorForUser{400, "invalid argument"}
|
||||
ErrPermissionDenied = errorForUser{403, "permission denied"}
|
||||
@@ -40,7 +34,48 @@ func (w errorForUser) Error() string {
|
||||
return w.msg
|
||||
}
|
||||
|
||||
// TODO: introduce ErrorUnwrapForHTML in the future for web error rendering
|
||||
// ErrorTranslateHTML translates the error message to HTML using the provided locale translator.
|
||||
// If the error is not translatable, it returns false.
|
||||
func ErrorTranslateHTML(err error, locale ErrorLocaleTranslator) (template.HTML, bool) {
|
||||
if errAs := errorAsTranslatable(err); errAs != nil {
|
||||
return locale.Tr(errAs.trKey, errAs.trArgs...), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// ErrorUnwrapForHTML unwraps the user error and returns the error message in HTML format and the HTTP status code.
|
||||
// An error is considered a user error if it is "errorForUser" or "errorTranslatable"
|
||||
// * errorTranslatable: The error message is translated to HTML using the provided locale translator.
|
||||
// * errorForUser: The error message is returned as is (escaped to HTML) and the HTTP status code is returned.
|
||||
// If the error is not a user error, it returns an empty message and code 0.
|
||||
func ErrorUnwrapForHTML(err error, locale ErrorLocaleTranslator) (msg template.HTML, code int) {
|
||||
if e, ok := errors.AsType[errorForUser](err); ok {
|
||||
code = e.code
|
||||
}
|
||||
if htmlMsg, ok := ErrorTranslateHTML(err, locale); ok {
|
||||
msg = htmlMsg
|
||||
code = IfZero(code, 400)
|
||||
}
|
||||
if code != 0 && msg == "" {
|
||||
errMsg := err.Error()
|
||||
switch errMsg {
|
||||
case ErrPermissionDenied.msg:
|
||||
msg = locale.Tr("error.permission_denied")
|
||||
case ErrNotExist.msg:
|
||||
msg = locale.Tr("error.not_found")
|
||||
default:
|
||||
msg = template.HTML(html.EscapeString(errMsg))
|
||||
}
|
||||
}
|
||||
return msg, code
|
||||
}
|
||||
|
||||
// ErrorUnwrapForUser unwraps the user error and returns the error message in string format and the HTTP status code.
|
||||
// It is mainly used for API error responses, and ideally only English locale should be used.
|
||||
//
|
||||
// It also accepts a locale translator to translate the error message if it is translatable:
|
||||
// * for example: there are different error messages for "ErrBlockedUser": blocked by owner, or blocked by assignee
|
||||
// * only the function returned the error message can know the exact reason
|
||||
func ErrorUnwrapForUser(err error, locale ...ErrorLocaleTranslator) (msg string, code int) {
|
||||
e, ok := errors.AsType[errorForUser](err)
|
||||
if ok {
|
||||
@@ -98,7 +133,7 @@ func NewNotExistErrorf(message string, args ...any) error {
|
||||
return ErrorWrap(ErrNotExist, message, args...)
|
||||
}
|
||||
|
||||
type errorTranslatableWrapper struct {
|
||||
type errorTranslatable struct {
|
||||
err error
|
||||
trKey string
|
||||
trArgs []any
|
||||
@@ -109,30 +144,14 @@ type ErrorLocaleTranslator interface {
|
||||
TrString(key string, args ...any) string
|
||||
}
|
||||
|
||||
func (w *errorTranslatableWrapper) Error() string { return w.err.Error() }
|
||||
func (w *errorTranslatable) Error() string { return w.err.Error() }
|
||||
func (w *errorTranslatable) Unwrap() error { return w.err }
|
||||
|
||||
func (w *errorTranslatableWrapper) Unwrap() error { return w.err }
|
||||
|
||||
func (w *errorTranslatableWrapper) Translate(t ErrorLocaleTranslator) template.HTML {
|
||||
return t.Tr(w.trKey, w.trArgs...)
|
||||
func ErrorWrapTranslatable(err error, trKey string, trArgs ...any) error {
|
||||
return &errorTranslatable{err: err, trKey: trKey, trArgs: trArgs}
|
||||
}
|
||||
|
||||
func ErrorWrapTranslatable(err error, trKey string, trArgs ...any) ErrorTranslatable {
|
||||
return &errorTranslatableWrapper{err: err, trKey: trKey, trArgs: trArgs}
|
||||
}
|
||||
|
||||
func errorAsTranslatable(err error) *errorTranslatableWrapper {
|
||||
if e, ok := errors.AsType[*errorTranslatableWrapper](err); ok {
|
||||
return e
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO: refactor ErrorAsTranslatable in the future, use ErrorUnwrapForUser or ErrorUnwrapForHTML as much as possible
|
||||
func ErrorAsTranslatable(err error) ErrorTranslatable {
|
||||
e := errorAsTranslatable(err)
|
||||
if e != nil { // avoid golang nil interface wrapper
|
||||
return e
|
||||
}
|
||||
return nil
|
||||
func errorAsTranslatable(err error) *errorTranslatable {
|
||||
e, _ := errors.AsType[*errorTranslatable](err)
|
||||
return e
|
||||
}
|
||||
@@ -5,6 +5,7 @@ package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
@@ -18,7 +19,7 @@ func TestErrorTranslatable(t *testing.T) {
|
||||
err = ErrorWrapTranslatable(io.EOF, "key", 1)
|
||||
assert.ErrorIs(t, err, io.EOF)
|
||||
assert.Equal(t, "EOF", err.Error())
|
||||
wrapped, ok := err.(*errorTranslatableWrapper)
|
||||
wrapped, ok := err.(*errorTranslatable)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "key", wrapped.trKey)
|
||||
assert.Equal(t, []any{1}, wrapped.trArgs)
|
||||
@@ -26,15 +27,36 @@ func TestErrorTranslatable(t *testing.T) {
|
||||
err = ErrorWrap(err, "new msg %d", 100)
|
||||
assert.ErrorIs(t, err, io.EOF)
|
||||
assert.Equal(t, "new msg 100", err.Error())
|
||||
}
|
||||
|
||||
errTr := ErrorAsTranslatable(err)
|
||||
assert.Equal(t, "EOF", errTr.Error())
|
||||
wrapped, ok = errTr.(*errorTranslatableWrapper)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "key", wrapped.trKey)
|
||||
type testErrorLocale struct{}
|
||||
|
||||
errTr = ErrorAsTranslatable(nil)
|
||||
assert.True(t, errTr == nil) //nolint:testifylint // assert golang nil interface wrapper
|
||||
func (l testErrorLocale) Tr(key string, args ...any) template.HTML {
|
||||
return template.HTML(l.TrString(key, args...))
|
||||
}
|
||||
|
||||
func (testErrorLocale) TrString(key string, args ...any) string {
|
||||
return fmt.Sprintf(key, args...)
|
||||
}
|
||||
|
||||
func TestErrorUnwrapForHTML(t *testing.T) {
|
||||
locale := testErrorLocale{}
|
||||
err := NewNotExistErrorf("missing <file>")
|
||||
msg, code := ErrorUnwrapForHTML(err, locale)
|
||||
assert.Equal(t, template.HTML("missing <file>"), msg)
|
||||
assert.Equal(t, 404, code)
|
||||
|
||||
msg, code = ErrorUnwrapForHTML(ErrorWrapTranslatable(err, "missing <b>%s</b>", "file"), locale)
|
||||
assert.Equal(t, template.HTML("missing <b>file</b>"), msg)
|
||||
assert.Equal(t, 404, code)
|
||||
|
||||
msg, code = ErrorUnwrapForHTML(ErrorWrapTranslatable(io.EOF, "unexpected end of input"), locale)
|
||||
assert.Equal(t, template.HTML("unexpected end of input"), msg)
|
||||
assert.Equal(t, 400, code)
|
||||
|
||||
msg, code = ErrorUnwrapForHTML(io.EOF, locale)
|
||||
assert.Empty(t, msg)
|
||||
assert.Zero(t, code)
|
||||
}
|
||||
|
||||
func TestErrorUnwrapForUser(t *testing.T) {
|
||||
|
||||
@@ -4,24 +4,29 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"encoding/base64"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"gitea.dev/modules/reqctx"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
// Flash represents a one time data transfer between two requests.
|
||||
type Flash struct {
|
||||
DataStore reqctx.RequestDataStore
|
||||
url.Values
|
||||
msgValues map[string]string
|
||||
|
||||
// message is in HTML format, and is sanitized when rendering (ref: RenderFlashMessage)
|
||||
ErrorMsg, WarningMsg, InfoMsg, SuccessMsg string
|
||||
}
|
||||
|
||||
func (f *Flash) set(name, msg string, current ...bool) {
|
||||
if f.Values == nil {
|
||||
f.Values = make(map[string][]string)
|
||||
if f.msgValues == nil {
|
||||
f.msgValues = map[string]string{}
|
||||
}
|
||||
showInCurrentPage := len(current) > 0 && current[0]
|
||||
if showInCurrentPage {
|
||||
@@ -29,59 +34,112 @@ func (f *Flash) set(name, msg string, current ...bool) {
|
||||
f.DataStore.GetData()["Flash"] = f
|
||||
} else {
|
||||
// the message map will be saved into the cookie and be shown in next response (a new page response which decodes the cookie)
|
||||
f.Set(name, msg)
|
||||
f.msgValues[name] = msg
|
||||
}
|
||||
}
|
||||
|
||||
func flashMsgStringOrHTML(msg any) string {
|
||||
switch v := msg.(type) {
|
||||
case string:
|
||||
return v
|
||||
case template.HTML:
|
||||
return string(v)
|
||||
var flashMessageReplacer = sync.OnceValue(func() (ret struct {
|
||||
encoder, decoder *strings.Replacer
|
||||
},
|
||||
) {
|
||||
ret.encoder = strings.NewReplacer("\\", "\\\\", "\n", "\\n")
|
||||
ret.decoder = strings.NewReplacer("\\\\", "\\", "\\n", "\n")
|
||||
return ret
|
||||
})
|
||||
|
||||
func flashMessageEncode(m map[string]string, limit int) string {
|
||||
if len(m) == 0 {
|
||||
return ""
|
||||
}
|
||||
panic(fmt.Sprintf("unknown type: %T", msg))
|
||||
buf := strings.Builder{}
|
||||
buf.Grow(200) // most messages are short, use a good initial size
|
||||
for k, v := range m {
|
||||
buf.WriteString(k)
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(flashMessageReplacer().encoder.Replace(v))
|
||||
buf.WriteByte('\n')
|
||||
}
|
||||
s := buf.String()
|
||||
n := min(len(s), limit)
|
||||
return base64.RawURLEncoding.EncodeToString(util.UnsafeStringToBytes(s[:n]))
|
||||
}
|
||||
|
||||
func flashMessageDecode(s string) map[string]string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
if strings.Contains(s, "=") {
|
||||
// legacy format, just parse it as query string
|
||||
vals, err := url.ParseQuery(s)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
m := make(map[string]string, len(vals))
|
||||
for k, v := range vals {
|
||||
if len(v) > 0 {
|
||||
m[k] = v[0]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
data, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
m := make(map[string]string)
|
||||
for line := range strings.SplitSeq(util.UnsafeBytesToString(data), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
k, v, _ := strings.Cut(line, "=")
|
||||
if v != "" {
|
||||
v = flashMessageReplacer().decoder.Replace(v)
|
||||
m[k] = strings.ToValidUTF8(v, "")
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (f *Flash) EncodeToString() string {
|
||||
// modern browsers support 4096 bytes for a cookie, we use base64 for encoding, so limit to 3000
|
||||
return flashMessageEncode(f.msgValues, 3000)
|
||||
}
|
||||
|
||||
// Error sets error message
|
||||
func (f *Flash) Error(msg any, current ...bool) {
|
||||
f.ErrorMsg = flashMsgStringOrHTML(msg)
|
||||
func (f *Flash) Error[T string | template.HTML](msg T, current ...bool) {
|
||||
f.ErrorMsg = string(msg)
|
||||
f.set("error", f.ErrorMsg, current...)
|
||||
}
|
||||
|
||||
// Warning sets warning message
|
||||
func (f *Flash) Warning(msg any, current ...bool) {
|
||||
f.WarningMsg = flashMsgStringOrHTML(msg)
|
||||
func (f *Flash) Warning[T string | template.HTML](msg T, current ...bool) {
|
||||
f.WarningMsg = string(msg)
|
||||
f.set("warning", f.WarningMsg, current...)
|
||||
}
|
||||
|
||||
// Info sets info message
|
||||
func (f *Flash) Info(msg any, current ...bool) {
|
||||
f.InfoMsg = flashMsgStringOrHTML(msg)
|
||||
func (f *Flash) Info[T string | template.HTML](msg T, current ...bool) {
|
||||
f.InfoMsg = string(msg)
|
||||
f.set("info", f.InfoMsg, current...)
|
||||
}
|
||||
|
||||
// Success sets success message
|
||||
func (f *Flash) Success(msg any, current ...bool) {
|
||||
f.SuccessMsg = flashMsgStringOrHTML(msg)
|
||||
func (f *Flash) Success[T string | template.HTML](msg T, current ...bool) {
|
||||
f.SuccessMsg = string(msg)
|
||||
f.set("success", f.SuccessMsg, current...)
|
||||
}
|
||||
|
||||
func ParseCookieFlashMessage(val string) *Flash {
|
||||
if vals, _ := url.ParseQuery(val); len(vals) > 0 {
|
||||
return &Flash{
|
||||
Values: vals,
|
||||
ErrorMsg: vals.Get("error"),
|
||||
SuccessMsg: vals.Get("success"),
|
||||
InfoMsg: vals.Get("info"),
|
||||
WarningMsg: vals.Get("warning"),
|
||||
}
|
||||
m := flashMessageDecode(val)
|
||||
if len(m) == 0 {
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
return &Flash{ErrorMsg: m["error"], SuccessMsg: m["success"], InfoMsg: m["info"], WarningMsg: m["warning"]}
|
||||
}
|
||||
|
||||
func GetSiteCookieFlashMessage(dataStore reqctx.RequestDataStore, req *http.Request, cookieName string) (string, *Flash) {
|
||||
// Get the last flash message from cookie
|
||||
lastFlashCookie := GetSiteCookie(req, cookieName)
|
||||
lastFlashMsg := ParseCookieFlashMessage(lastFlashCookie)
|
||||
if lastFlashMsg != nil {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestFlashMessageEncode(t *testing.T) {
|
||||
assert.Empty(t, flashMessageEncode(nil, 100))
|
||||
|
||||
messages := map[string]string{"error": "<div>\n<div>", "success": "🌞"}
|
||||
assert.Equal(t, messages, flashMessageDecode(flashMessageEncode(messages, 100)))
|
||||
assert.Equal(t, map[string]string{"error": "删除分支失败"}, flashMessageDecode(flashMessageEncode(map[string]string{"error": "删除分支\xff失败"}, 100)))
|
||||
|
||||
const limit = 99
|
||||
encoded := flashMessageEncode(map[string]string{"error": strings.Repeat("x", 200)}, limit)
|
||||
assert.Len(t, encoded, limit/3*4)
|
||||
decoded := flashMessageDecode(encoded)
|
||||
assert.Equal(t, map[string]string{"error": strings.Repeat("x", limit-len("error="))}, decoded)
|
||||
|
||||
// also support legacy format
|
||||
decoded = flashMessageDecode("error=invalid%20message")
|
||||
assert.Equal(t, map[string]string{"error": "invalid message"}, decoded)
|
||||
}
|
||||
@@ -1405,12 +1405,8 @@ func Run(ctx *context_module.Context) {
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if errTr := util.ErrorAsTranslatable(err); errTr != nil {
|
||||
ctx.Flash.Error(errTr.Translate(ctx.Locale))
|
||||
ctx.Redirect(redirectURL)
|
||||
} else {
|
||||
ctx.ServerError("DispatchActionWorkflow", err)
|
||||
}
|
||||
ctx.FlashErrorAuto(err)
|
||||
ctx.Redirect(redirectURL)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -38,8 +38,8 @@ func editorHandleFileOperationErrorRender(ctx *context_service.Context, message,
|
||||
}
|
||||
|
||||
func editorHandleFileOperationError(ctx *context_service.Context, targetBranchName string, err error) {
|
||||
if errAs := util.ErrorAsTranslatable(err); errAs != nil {
|
||||
ctx.JSONError(errAs.Translate(ctx.Locale))
|
||||
if htmlMsg, ok := util.ErrorTranslateHTML(err, ctx.Locale); ok {
|
||||
ctx.JSONError(htmlMsg)
|
||||
} else if errAs, ok := errorAs[git.ErrNotExist](err); ok {
|
||||
ctx.JSONError(ctx.Tr("repo.editor.file_modifying_no_longer_exists", errAs.RelPath))
|
||||
} else if errAs, ok := errorAs[git_model.ErrLFSFileLocked](err); ok {
|
||||
|
||||
@@ -1266,9 +1266,6 @@ func MergePullRequest(ctx *context.Context) {
|
||||
|
||||
if deleteBranchAfterMerge {
|
||||
deleteBranchAfterMergeAndFlashMessage(ctx, pr.ID)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx.JSONRedirect(issue.Link())
|
||||
}
|
||||
@@ -1279,16 +1276,11 @@ func deleteBranchAfterMergeAndFlashMessage(ctx *context.Context, prID int64) {
|
||||
if errors.Is(err, util.ErrPermissionDenied) || errors.Is(err, util.ErrNotExist) {
|
||||
// no need to show error to end users if no permission or branch not exist
|
||||
log.Debug("DeleteBranchAfterMerge (ignore unnecessary error): %v", err)
|
||||
return
|
||||
} else if errTr := util.ErrorAsTranslatable(err); errTr != nil {
|
||||
ctx.Flash.Error(errTr.Translate(ctx.Locale))
|
||||
return
|
||||
} else if err == nil {
|
||||
} else if err != nil {
|
||||
ctx.FlashErrorAuto(err)
|
||||
} else {
|
||||
ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
|
||||
return
|
||||
}
|
||||
// catch unknown errors
|
||||
ctx.ServerError("DeleteBranchAfterMerge", err)
|
||||
}
|
||||
|
||||
// CancelAutoMergePullRequest cancels a scheduled pr
|
||||
@@ -1479,9 +1471,6 @@ func CleanUpPullRequest(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
deleteBranchAfterMergeAndFlashMessage(ctx, issue.PullRequest.ID)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
ctx.JSONRedirect(issue.Link())
|
||||
}
|
||||
|
||||
|
||||
@@ -424,11 +424,7 @@ func GenerateReleaseNotes(ctx *context.Context) {
|
||||
PreviousTag: form.PreviousTag,
|
||||
})
|
||||
if err != nil {
|
||||
if errTr := util.ErrorAsTranslatable(err); errTr != nil {
|
||||
ctx.JSONError(errTr.Translate(ctx.Locale))
|
||||
} else {
|
||||
ctx.ServerError("GenerateReleaseNotes", err)
|
||||
}
|
||||
ctx.JSONErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ type fileCodeOwner struct {
|
||||
|
||||
func prepareFileCodeOwners(ctx *context.Context) {
|
||||
rules, warnings1, err := issue_service.GetCodeOwnerRules(ctx, ctx.Repo.GitRepo, ctx.Repo.Commit)
|
||||
if msg, _ := util.ErrorUnwrapForUser(err, ctx.Locale); msg != "" {
|
||||
if msg, _ := util.ErrorUnwrapForHTML(err, ctx.Locale); msg != "" {
|
||||
ctx.Flash.Error(msg, true)
|
||||
return
|
||||
} else if err != nil {
|
||||
|
||||
@@ -70,11 +70,7 @@ func BlockedUsersPost(ctx *context.Context, blocker *user_model.User, redirect s
|
||||
err := blockedUsersPost(ctx, form, blocker)
|
||||
if err == nil {
|
||||
ctx.JSONRedirect(redirect)
|
||||
} else if errTr := util.ErrorAsTranslatable(err); errTr != nil {
|
||||
ctx.JSONError(errTr.Translate(ctx.Locale))
|
||||
} else if errors.Is(err, util.ErrNotExist) {
|
||||
ctx.JSONError(ctx.Locale.Tr("error.not_found"))
|
||||
} else {
|
||||
ctx.ServerError("BlockedUsersPost", err)
|
||||
ctx.JSONErrorAuto(err)
|
||||
}
|
||||
}
|
||||
@@ -496,12 +496,7 @@ func packageSettingsPostActionDelete(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
if err := packages_service.RemovePackage(ctx, ctx.Doer, pd.Package); err != nil {
|
||||
errTr := util.ErrorAsTranslatable(err)
|
||||
if errTr == nil {
|
||||
ctx.ServerError("RemovePackage", err)
|
||||
return
|
||||
}
|
||||
ctx.Flash.Error(errTr.Translate(ctx.Locale))
|
||||
ctx.FlashErrorAuto(err)
|
||||
ctx.Redirect(pd.PackageSettingsLink())
|
||||
return
|
||||
}
|
||||
@@ -519,15 +514,11 @@ func PackageVersionDelete(ctx *context.Context) {
|
||||
}
|
||||
|
||||
if err := packages_service.RemovePackageVersion(ctx, ctx.Doer, pd.Version); err != nil {
|
||||
errTr := util.ErrorAsTranslatable(err)
|
||||
if errTr == nil {
|
||||
ctx.ServerError("RemovePackageVersion", err)
|
||||
return
|
||||
}
|
||||
ctx.Flash.Error(errTr.Translate(ctx.Locale))
|
||||
} else {
|
||||
ctx.Flash.Success(ctx.Tr("packages.settings.delete.version.success"))
|
||||
ctx.FlashErrorAuto(err)
|
||||
ctx.Redirect(pd.VersionWebLink())
|
||||
return
|
||||
}
|
||||
ctx.Flash.Success(ctx.Tr("packages.settings.delete.version.success"))
|
||||
|
||||
// redirect to the package if there are still versions available
|
||||
redirectURL := ctx.Package.Owner.HomeLink() + "/-/packages"
|
||||
|
||||
@@ -6,11 +6,8 @@ package context
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/models/unit"
|
||||
@@ -18,13 +15,11 @@ import (
|
||||
"gitea.dev/modules/cache"
|
||||
"gitea.dev/modules/httpcache"
|
||||
"gitea.dev/modules/httplib"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/reqctx"
|
||||
"gitea.dev/modules/session"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/translation"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/validation"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/modules/web/middleware"
|
||||
@@ -122,7 +117,7 @@ func NewWebContext(base *Base, render Render, session session.Store) *Context {
|
||||
Org: &Organization{},
|
||||
}
|
||||
ctx.TemplateContext = NewTemplateContextForWeb(ctx, ctx.Base.Req, ctx.Base.Locale)
|
||||
ctx.Flash = &middleware.Flash{DataStore: ctx, Values: url.Values{}}
|
||||
ctx.Flash = &middleware.Flash{DataStore: ctx}
|
||||
ctx.SetContextValue(WebContextKey, ctx)
|
||||
httplib.MarkRequestSupportPublicURL(ctx)
|
||||
return ctx
|
||||
@@ -163,13 +158,13 @@ func Contexter() func(next http.Handler) http.Handler {
|
||||
|
||||
// get the last flash message from cookie
|
||||
lastFlashCookie, lastFlashMsg := middleware.GetSiteCookieFlashMessage(ctx, ctx.Req, CookieNameFlash)
|
||||
if vals, _ := url.ParseQuery(lastFlashCookie); len(vals) > 0 {
|
||||
if lastFlashMsg != nil {
|
||||
ctx.Data["Flash"] = lastFlashMsg // store last Flash message into the template data, to render it
|
||||
}
|
||||
|
||||
// if there are new messages in the ctx.Flash, write them into cookie
|
||||
ctx.Resp.Before(func(resp ResponseWriter) {
|
||||
if val := ctx.Flash.Encode(); val != "" {
|
||||
if val := ctx.Flash.EncodeToString(); val != "" {
|
||||
middleware.SetSiteCookie(ctx.Resp, CookieNameFlash, val, 0)
|
||||
} else if lastFlashCookie != "" {
|
||||
middleware.SetSiteCookie(ctx.Resp, CookieNameFlash, "", -1)
|
||||
@@ -236,61 +231,6 @@ func (ctx *Context) GetErrMsg() string {
|
||||
return msg
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONRedirect(redirect string) {
|
||||
ctx.JSON(http.StatusOK, map[string]any{"redirect": redirect})
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONOK() {
|
||||
ctx.JSON(http.StatusOK, map[string]any{"ok": true}) // this is only a dummy response, frontend seldom uses it
|
||||
}
|
||||
|
||||
func buildJsonErrorMap[T string | template.HTML](msg T) map[string]any {
|
||||
switch v := any(msg).(type) {
|
||||
case string:
|
||||
return map[string]any{"errorMessage": v, "renderFormat": "text"}
|
||||
case template.HTML:
|
||||
return map[string]any{"errorMessage": v, "renderFormat": "html"}
|
||||
}
|
||||
panic(fmt.Sprintf("unsupported type: %T", msg))
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONErrorAuto(err error) {
|
||||
if errTr := util.ErrorAsTranslatable(err); errTr != nil {
|
||||
msg := errTr.Translate(ctx.Locale)
|
||||
ctx.JSON(http.StatusBadRequest, buildJsonErrorMap(msg))
|
||||
return
|
||||
}
|
||||
errMsg, httpCode := util.ErrorUnwrapForUser(err)
|
||||
if errMsg != "" {
|
||||
ctx.JSON(httpCode, buildJsonErrorMap(errMsg))
|
||||
return
|
||||
}
|
||||
|
||||
logLevel := util.Iif(httplib.IsClientOrNetworkError(ctx, err), log.DEBUG, log.ERROR)
|
||||
log.Log(1, logLevel, "JSONErrorAuto: server internal error: %v", err)
|
||||
|
||||
userErrorMsg := ctx.buildUserErrorMessage("internal server error", err)
|
||||
ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(userErrorMsg))
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONError[T string | template.HTML](msg T) {
|
||||
ctx.JSON(http.StatusBadRequest, buildJsonErrorMap(msg))
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONErrorWithField[T string | template.HTML](msg T, field string) {
|
||||
m := buildJsonErrorMap(msg)
|
||||
m["errorFields"] = []string{field}
|
||||
ctx.JSON(http.StatusBadRequest, m)
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONErrorNotFound(optMsg ...string) {
|
||||
msg := util.OptionalArg(optMsg)
|
||||
if msg == "" {
|
||||
msg = ctx.Locale.TrString("error.not_found")
|
||||
}
|
||||
ctx.JSON(http.StatusNotFound, buildJsonErrorMap(msg))
|
||||
}
|
||||
|
||||
func GetFetchActionForm[T middleware.Form](ctx *Context) (ret T) {
|
||||
if web.IsFormSet(ctx) {
|
||||
panic("don't mix fetch-action form validation with template-based form validation")
|
||||
|
||||
@@ -6,6 +6,7 @@ package context
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -114,7 +115,7 @@ func (ctx *Context) RenderToHTML(name templates.TplName, data any) (template.HTM
|
||||
// WARNING: in many cases, this function is not able to render the page or recover the form fields correctly.
|
||||
// And it is very difficult to test the page rendered by this function.
|
||||
// DO NOT USE IT ANYMORE.
|
||||
func (ctx *Context) RenderWithErrDeprecated(msg any, tpl templates.TplName, form any) {
|
||||
func (ctx *Context) RenderWithErrDeprecated[T string | template.HTML](msg T, tpl templates.TplName, form any) {
|
||||
if form != nil {
|
||||
middleware.AssignForm(form, ctx.Data)
|
||||
}
|
||||
@@ -153,7 +154,7 @@ func (ctx *Context) notFoundInternal(skip int, logMsg string, logErr error) {
|
||||
ctx.HTML(http.StatusNotFound, "status/404")
|
||||
}
|
||||
|
||||
func (ctx *Context) buildUserErrorMessage(msg string, err error) (userErrorMsg string) {
|
||||
func (ctx *Context) buildServerErrorMessageForUser(msg string, err error) (userErrorMsg string) {
|
||||
// it's safe to show internal error to admin users, and it helps
|
||||
if !setting.IsProd || setting.IsInTesting || (ctx.Doer != nil && ctx.Doer.IsAdmin) {
|
||||
userErrorMsg = msg
|
||||
@@ -164,6 +165,70 @@ func (ctx *Context) buildUserErrorMessage(msg string, err error) (userErrorMsg s
|
||||
return util.IfZero(userErrorMsg, ctx.Locale.TrString("error.occurred"))
|
||||
}
|
||||
|
||||
func (ctx *Context) FlashErrorAuto(err error) {
|
||||
errMsg, _ := util.ErrorUnwrapForHTML(err, ctx.Locale)
|
||||
if errMsg != "" {
|
||||
ctx.Flash.Error(errMsg)
|
||||
return
|
||||
}
|
||||
|
||||
logLevel := util.Iif(httplib.IsClientOrNetworkError(ctx, err), log.DEBUG, log.ERROR)
|
||||
log.Log(1, logLevel, "FlashErrorAuto: server internal error: %v", err)
|
||||
|
||||
userErrorMsg := ctx.buildServerErrorMessageForUser("internal server error", err)
|
||||
ctx.Flash.Error(html.EscapeString(userErrorMsg)) // flash renders HTML with sanitization, so escape the message to keep original content
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONRedirect(redirect string) {
|
||||
ctx.JSON(http.StatusOK, map[string]any{"redirect": redirect})
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONOK() {
|
||||
ctx.JSON(http.StatusOK, map[string]any{"ok": true}) // this is only a dummy response, frontend seldom uses it
|
||||
}
|
||||
|
||||
func buildJsonErrorMap[T string | template.HTML](msg T) map[string]any {
|
||||
switch v := any(msg).(type) {
|
||||
case string:
|
||||
return map[string]any{"errorMessage": v, "renderFormat": "text"}
|
||||
case template.HTML:
|
||||
return map[string]any{"errorMessage": v, "renderFormat": "html"}
|
||||
}
|
||||
panic(fmt.Sprintf("unsupported type: %T", msg))
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONErrorAuto(err error) {
|
||||
errMsg, httpCode := util.ErrorUnwrapForHTML(err, ctx.Locale)
|
||||
if errMsg != "" {
|
||||
ctx.JSON(httpCode, buildJsonErrorMap(errMsg))
|
||||
return
|
||||
}
|
||||
|
||||
logLevel := util.Iif(httplib.IsClientOrNetworkError(ctx, err), log.DEBUG, log.ERROR)
|
||||
log.Log(1, logLevel, "JSONErrorAuto: server internal error: %v", err)
|
||||
|
||||
userErrorMsg := ctx.buildServerErrorMessageForUser("internal server error", err)
|
||||
ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(userErrorMsg))
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONError[T string | template.HTML](msg T) {
|
||||
ctx.JSON(http.StatusBadRequest, buildJsonErrorMap(msg))
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONErrorWithField[T string | template.HTML](msg T, field string) {
|
||||
m := buildJsonErrorMap(msg)
|
||||
m["errorFields"] = []string{field}
|
||||
ctx.JSON(http.StatusBadRequest, m)
|
||||
}
|
||||
|
||||
func (ctx *Context) JSONErrorNotFound(optMsg ...string) {
|
||||
msg := util.OptionalArg(optMsg)
|
||||
if msg == "" {
|
||||
msg = ctx.Locale.TrString("error.not_found")
|
||||
}
|
||||
ctx.JSON(http.StatusNotFound, buildJsonErrorMap(msg))
|
||||
}
|
||||
|
||||
// ServerError displays a 500 (Internal Server Error) page and prints the given error, if any.
|
||||
// If the error is controlled by our error system, a related 404 page can be displayed instead.
|
||||
// TODO: refactor this function like APIErrorAuto in the future, and handle more error types and http codes.
|
||||
@@ -185,7 +250,7 @@ func (ctx *Context) serverErrorInternal(skip int, logMsg string, logErr error) {
|
||||
log.Log(skip+1, logLevel, "%s: %v", logMsg, logErr)
|
||||
}
|
||||
|
||||
userErrorMsg := ctx.buildUserErrorMessage(logMsg, logErr)
|
||||
userErrorMsg := ctx.buildServerErrorMessageForUser(logMsg, logErr)
|
||||
if httplib.IsGiteaFetchActionRequest(ctx.Req) {
|
||||
ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(userErrorMsg))
|
||||
return
|
||||
|
||||
@@ -588,7 +588,7 @@ func testAPIIssueAssignees(t *testing.T) {
|
||||
AddTokenAuth(token)
|
||||
resp := MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||
apiErr := DecodeJSON(t, resp, &api.APIError{})
|
||||
assert.Equal(t, "user does not exist [uid: 0, name: does-not-exist]", apiErr.Message)
|
||||
assert.Equal(t, "user does not exist [name: does-not-exist]", apiErr.Message)
|
||||
})
|
||||
|
||||
t.Run("OrganizationAssignee", func(t *testing.T) {
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestProjectWorkflowsWeb(t *testing.T) {
|
||||
assert.Equal(t, workflow.Actions, updated.Actions)
|
||||
|
||||
req = NewRequestWithJSON(t, "POST", link, &api.CreateProjectWorkflowOption{Event: "item_closed"})
|
||||
resp := session.MakeRequest(t, req, http.StatusBadRequest)
|
||||
resp := session.MakeRequest(t, req, http.StatusUnprocessableEntity)
|
||||
assert.Equal(t, "At least one action must be configured", DecodeJSON(t, resp, map[string]any{})["errorMessage"])
|
||||
|
||||
loginUser(t, "user4").MakeRequest(t, NewRequest(t, "POST", workflowLink+"/delete"), http.StatusNotFound)
|
||||
|
||||
@@ -115,7 +115,7 @@ func testPullCreateDirectly(t *testing.T, session *TestSession, opts createPullR
|
||||
return resp
|
||||
}
|
||||
|
||||
func testPullCreateFailure(t *testing.T, session *TestSession, baseRepoOwner, baseRepoName, baseBranch, headRepoOwner, headRepoName, headBranch, title string) *httptest.ResponseRecorder {
|
||||
func testPullCreateForbidden(t *testing.T, session *TestSession, baseRepoOwner, baseRepoName, baseBranch, headRepoOwner, headRepoName, headBranch, title string) *httptest.ResponseRecorder {
|
||||
headCompare := headBranch
|
||||
if headRepoOwner != "" {
|
||||
if headRepoName != "" {
|
||||
@@ -134,7 +134,7 @@ func testPullCreateFailure(t *testing.T, session *TestSession, baseRepoOwner, ba
|
||||
req = NewRequestWithValues(t, "POST", link, map[string]string{
|
||||
"title": title,
|
||||
})
|
||||
resp = session.MakeRequest(t, req, http.StatusBadRequest)
|
||||
resp = session.MakeRequest(t, req, http.StatusForbidden)
|
||||
return resp
|
||||
}
|
||||
|
||||
@@ -477,7 +477,8 @@ func TestCreatePullWhenBlocked(t *testing.T) {
|
||||
testEditFile(t, sessionFork, ForkOwner, "forkrepo1", "master", "README.md", "Hello, World (Edited)\n")
|
||||
|
||||
// 3. User1 attempts to create a pull request
|
||||
testPullCreateFailure(t, sessionFork, RepoOwner, "repo1", "master", ForkOwner, "forkrepo1", "master", "This is a pull title")
|
||||
resp := testPullCreateForbidden(t, sessionFork, RepoOwner, "repo1", "master", ForkOwner, "forkrepo1", "master", "This is a pull title")
|
||||
assert.Equal(t, "Cannot create an issue or pull request because you are blocked by the repository owner.", test.ParseJSONError(resp.Body.Bytes()).ErrorMessage)
|
||||
|
||||
// Teardown
|
||||
// Unblock user
|
||||
|
||||
@@ -61,7 +61,13 @@ func testPullReviewReviewerMissed(t *testing.T) {
|
||||
|
||||
func testPullReviewLockedOrBlocked(t *testing.T) {
|
||||
require.NoError(t, issues_model.UpdateIssueCols(t.Context(), &issues_model.Issue{ID: 3, IsLocked: true}, "is_locked"))
|
||||
for _, tc := range []struct{ reviewerID, index, replyCommentID int64 }{{4, 3, 7}, {34, 2, 4}} {
|
||||
for _, tc := range []struct {
|
||||
reviewerID, index, replyCommentID int64
|
||||
webStatus int
|
||||
}{
|
||||
{4, 3, 7, http.StatusBadRequest},
|
||||
{34, 2, 4, http.StatusForbidden},
|
||||
} {
|
||||
reviewer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: tc.reviewerID})
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: 1, Index: tc.index})
|
||||
pendingReview, err := issues_model.CreateReview(t.Context(), issues_model.CreateReviewOptions{Type: issues_model.ReviewTypePending, Issue: issue, Reviewer: reviewer})
|
||||
@@ -71,10 +77,10 @@ func testPullReviewLockedOrBlocked(t *testing.T) {
|
||||
session := loginUser(t, reviewer.Name)
|
||||
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
|
||||
|
||||
testSubmitReview(t, session, "user2", "repo1", strconv.FormatInt(tc.index, 10), "", "comment", http.StatusBadRequest)
|
||||
testSubmitReview(t, session, "user2", "repo1", strconv.FormatInt(tc.index, 10), "", "comment", tc.webStatus)
|
||||
session.MakeRequest(t, NewRequestWithValues(t, "POST", "/"+pullPath+"/files/reviews/comments", map[string]string{
|
||||
"origin": "diff", "content": "test", "path": "README.md", "side": "proposed", "line": "1",
|
||||
}), http.StatusBadRequest)
|
||||
}), tc.webStatus)
|
||||
MakeRequest(t, NewRequestWithJSON(t, "POST", "/api/v1/repos/"+pullPath+"/reviews", &api.CreatePullReviewOptions{Event: api.ReviewStateComment, Body: "test"}).AddTokenAuth(token), http.StatusForbidden)
|
||||
MakeRequest(t, NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/reviews/%d", pullPath, pendingReview.ID), &api.SubmitPullReviewOptions{Event: api.ReviewStateComment, Body: "test"}).AddTokenAuth(token), http.StatusForbidden)
|
||||
MakeRequest(t, NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/comments/%d/replies", pullPath, tc.replyCommentID), &api.CreatePullReviewCommentReplyOptions{Body: "test"}).AddTokenAuth(token), http.StatusForbidden)
|
||||
@@ -82,7 +88,7 @@ func testPullReviewLockedOrBlocked(t *testing.T) {
|
||||
}
|
||||
MakeRequest(t, NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/pulls/3/reviews", &api.CreatePullReviewOptions{Event: api.ReviewStateComment, Body: "test"}).AddTokenAuth(getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository)), http.StatusOK)
|
||||
|
||||
for name, status := range map[string]int{"user5": http.StatusBadRequest, "user40": http.StatusOK} {
|
||||
for name, status := range map[string]int{"user5": http.StatusForbidden, "user40": http.StatusOK} {
|
||||
require.NoError(t, db.Insert(t.Context(), &user_model.Blocking{BlockerID: 1, BlockeeID: unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: name}).ID}))
|
||||
testSubmitReview(t, loginUser(t, name), "user2", "repo1", "2", "", "comment", status)
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ func TestWebAuthnRename(t *testing.T) {
|
||||
rename(cred.ID, "RENAMED credential", http.StatusOK)
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: cred.ID, Name: "RENAMED credential"})
|
||||
|
||||
resp := rename(cred.ID, "other CREDENTIAL", http.StatusBadRequest)
|
||||
resp := rename(cred.ID, "other CREDENTIAL", http.StatusConflict)
|
||||
assert.Equal(t, "A security key with the same nickname already exists.", test.ParseJSONError(resp.Body.Bytes()).ErrorMessage)
|
||||
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: cred.ID, Name: "RENAMED credential"})
|
||||
|
||||
|
||||
Reference in new issue
Block a user