Validate hex colors when creating/editing labels (#34623)

Resolves #34618.

---------

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
Kemal Zebari 2025-06-07 01:25:08 -07:00 committed by GitHub
parent b38f2d31fd
commit 47d69b7749
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 151 additions and 76 deletions

View File

@ -7,10 +7,10 @@ import (
"fmt" "fmt"
"regexp" "regexp"
"strings" "strings"
) "sync"
// colorPattern is a regexp which can validate label color "code.gitea.io/gitea/modules/util"
var colorPattern = regexp.MustCompile("^#?(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})$") )
// Label represents label information loaded from template // Label represents label information loaded from template
type Label struct { type Label struct {
@ -21,6 +21,10 @@ type Label struct {
ExclusiveOrder int `yaml:"exclusive_order,omitempty"` ExclusiveOrder int `yaml:"exclusive_order,omitempty"`
} }
var colorPattern = sync.OnceValue(func() *regexp.Regexp {
return regexp.MustCompile(`^#([\da-fA-F]{3}|[\da-fA-F]{6})$`)
})
// NormalizeColor normalizes a color string to a 6-character hex code // NormalizeColor normalizes a color string to a 6-character hex code
func NormalizeColor(color string) (string, error) { func NormalizeColor(color string) (string, error) {
// normalize case // normalize case
@ -31,8 +35,8 @@ func NormalizeColor(color string) (string, error) {
color = "#" + color color = "#" + color
} }
if !colorPattern.MatchString(color) { if !colorPattern().MatchString(color) {
return "", fmt.Errorf("bad color code: %s", color) return "", util.NewInvalidArgumentErrorf("invalid color: %s", color)
} }
// convert 3-character shorthand into 6-character version // convert 3-character shorthand into 6-character version

View File

@ -17,6 +17,7 @@ import (
// RedirectURL returns the redirect URL of a http response. // RedirectURL returns the redirect URL of a http response.
// It also works for JSONRedirect: `{"redirect": "..."}` // It also works for JSONRedirect: `{"redirect": "..."}`
// FIXME: it should separate the logic of checking from header and JSON body
func RedirectURL(resp http.ResponseWriter) string { func RedirectURL(resp http.ResponseWriter) string {
loc := resp.Header().Get("Location") loc := resp.Header().Get("Location")
if loc != "" { if loc != "" {
@ -34,6 +35,15 @@ func RedirectURL(resp http.ResponseWriter) string {
return "" return ""
} }
func ParseJSONError(buf []byte) (ret struct {
ErrorMessage string `json:"errorMessage"`
RenderFormat string `json:"renderFormat"`
},
) {
_ = json.Unmarshal(buf, &ret)
return ret
}
func IsNormalPageCompleted(s string) bool { func IsNormalPageCompleted(s string) bool {
return strings.Contains(s, `<footer class="page-footer"`) && strings.Contains(s, `</html>`) return strings.Contains(s, `<footer class="page-footer"`) && strings.Contains(s, `</html>`)
} }

View File

@ -1433,7 +1433,6 @@ commitstatus.success = Success
ext_issues = Access to External Issues ext_issues = Access to External Issues
ext_issues.desc = Link to an external issue tracker. ext_issues.desc = Link to an external issue tracker.
projects = Projects
projects.desc = Manage issues and pulls in projects. projects.desc = Manage issues and pulls in projects.
projects.description = Description (optional) projects.description = Description (optional)
projects.description_placeholder = Description projects.description_placeholder = Description
@ -1653,6 +1652,7 @@ issues.save = Save
issues.label_title = Name issues.label_title = Name
issues.label_description = Description issues.label_description = Description
issues.label_color = Color issues.label_color = Color
issues.label_color_invalid = Invalid color
issues.label_exclusive = Exclusive issues.label_exclusive = Exclusive
issues.label_archive = Archive Label issues.label_archive = Archive Label
issues.label_archived_filter = Show archived labels issues.label_archived_filter = Show archived labels

View File

@ -4,13 +4,15 @@
package org package org
import ( import (
"net/http" "errors"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/modules/label" "code.gitea.io/gitea/modules/label"
repo_module "code.gitea.io/gitea/modules/repository" repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/modules/web"
shared_label "code.gitea.io/gitea/routers/web/shared/label"
"code.gitea.io/gitea/services/context" "code.gitea.io/gitea/services/context"
"code.gitea.io/gitea/services/forms" "code.gitea.io/gitea/services/forms"
) )
@ -32,14 +34,8 @@ func RetrieveLabels(ctx *context.Context) {
// NewLabel create new label for organization // NewLabel create new label for organization
func NewLabel(ctx *context.Context) { func NewLabel(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.CreateLabelForm) form := shared_label.GetLabelEditForm(ctx)
ctx.Data["Title"] = ctx.Tr("repo.labels") if ctx.Written() {
ctx.Data["PageIsLabels"] = true
ctx.Data["PageIsOrgSettings"] = true
if ctx.HasError() {
ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
ctx.Redirect(ctx.Org.OrgLink + "/settings/labels")
return return
} }
@ -55,20 +51,22 @@ func NewLabel(ctx *context.Context) {
ctx.ServerError("NewLabel", err) ctx.ServerError("NewLabel", err)
return return
} }
ctx.Redirect(ctx.Org.OrgLink + "/settings/labels") ctx.JSONRedirect(ctx.Org.OrgLink + "/settings/labels")
} }
// UpdateLabel update a label's name and color // UpdateLabel update a label's name and color
func UpdateLabel(ctx *context.Context) { func UpdateLabel(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.CreateLabelForm) form := shared_label.GetLabelEditForm(ctx)
l, err := issues_model.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, form.ID) if ctx.Written() {
if err != nil { return
switch {
case issues_model.IsErrOrgLabelNotExist(err):
ctx.HTTPError(http.StatusNotFound)
default:
ctx.ServerError("UpdateLabel", err)
} }
l, err := issues_model.GetLabelInOrgByID(ctx, ctx.Org.Organization.ID, form.ID)
if errors.Is(err, util.ErrNotExist) {
ctx.JSONErrorNotFound()
return
} else if err != nil {
ctx.ServerError("GetLabelInOrgByID", err)
return return
} }
@ -82,7 +80,7 @@ func UpdateLabel(ctx *context.Context) {
ctx.ServerError("UpdateLabel", err) ctx.ServerError("UpdateLabel", err)
return return
} }
ctx.Redirect(ctx.Org.OrgLink + "/settings/labels") ctx.JSONRedirect(ctx.Org.OrgLink + "/settings/labels")
} }
// DeleteLabel delete a label // DeleteLabel delete a label

View File

@ -4,6 +4,7 @@
package repo package repo
import ( import (
"errors"
"net/http" "net/http"
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
@ -13,7 +14,9 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
repo_module "code.gitea.io/gitea/modules/repository" repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/templates"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/modules/web"
shared_label "code.gitea.io/gitea/routers/web/shared/label"
"code.gitea.io/gitea/services/context" "code.gitea.io/gitea/services/context"
"code.gitea.io/gitea/services/forms" "code.gitea.io/gitea/services/forms"
issue_service "code.gitea.io/gitea/services/issue" issue_service "code.gitea.io/gitea/services/issue"
@ -100,13 +103,8 @@ func RetrieveLabelsForList(ctx *context.Context) {
// NewLabel create new label for repository // NewLabel create new label for repository
func NewLabel(ctx *context.Context) { func NewLabel(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.CreateLabelForm) form := shared_label.GetLabelEditForm(ctx)
ctx.Data["Title"] = ctx.Tr("repo.labels") if ctx.Written() {
ctx.Data["PageIsLabels"] = true
if ctx.HasError() {
ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
ctx.Redirect(ctx.Repo.RepoLink + "/labels")
return return
} }
@ -122,34 +120,36 @@ func NewLabel(ctx *context.Context) {
ctx.ServerError("NewLabel", err) ctx.ServerError("NewLabel", err)
return return
} }
ctx.Redirect(ctx.Repo.RepoLink + "/labels") ctx.JSONRedirect(ctx.Repo.RepoLink + "/labels")
} }
// UpdateLabel update a label's name and color // UpdateLabel update a label's name and color
func UpdateLabel(ctx *context.Context) { func UpdateLabel(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.CreateLabelForm) form := shared_label.GetLabelEditForm(ctx)
l, err := issues_model.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, form.ID) if ctx.Written() {
if err != nil {
switch {
case issues_model.IsErrRepoLabelNotExist(err):
ctx.HTTPError(http.StatusNotFound)
default:
ctx.ServerError("UpdateLabel", err)
}
return return
} }
l, err := issues_model.GetLabelInRepoByID(ctx, ctx.Repo.Repository.ID, form.ID)
if errors.Is(err, util.ErrNotExist) {
ctx.JSONErrorNotFound()
return
} else if err != nil {
ctx.ServerError("GetLabelInRepoByID", err)
return
}
l.Name = form.Title l.Name = form.Title
l.Exclusive = form.Exclusive l.Exclusive = form.Exclusive
l.ExclusiveOrder = form.ExclusiveOrder l.ExclusiveOrder = form.ExclusiveOrder
l.Description = form.Description l.Description = form.Description
l.Color = form.Color l.Color = form.Color
l.SetArchived(form.IsArchived) l.SetArchived(form.IsArchived)
if err := issues_model.UpdateLabel(ctx, l); err != nil { if err := issues_model.UpdateLabel(ctx, l); err != nil {
ctx.ServerError("UpdateLabel", err) ctx.ServerError("UpdateLabel", err)
return return
} }
ctx.Redirect(ctx.Repo.RepoLink + "/labels") ctx.JSONRedirect(ctx.Repo.RepoLink + "/labels")
} }
// DeleteLabel delete a label // DeleteLabel delete a label

View File

@ -6,10 +6,12 @@ package repo
import ( import (
"net/http" "net/http"
"strconv" "strconv"
"strings"
"testing" "testing"
issues_model "code.gitea.io/gitea/models/issues" issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/modules/web"
@ -19,19 +21,20 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func int64SliceToCommaSeparated(a []int64) string { func TestIssueLabel(t *testing.T) {
s := "" unittest.PrepareTestEnv(t)
for i, n := range a { t.Run("RetrieveLabels", testRetrieveLabels)
if i > 0 { t.Run("NewLabel", testNewLabel)
s += "," t.Run("NewLabelInvalidColor", testNewLabelInvalidColor)
} t.Run("UpdateLabel", testUpdateLabel)
s += strconv.Itoa(int(n)) t.Run("UpdateLabelInvalidColor", testUpdateLabelInvalidColor)
} t.Run("UpdateIssueLabelClear", testUpdateIssueLabelClear)
return s t.Run("UpdateIssueLabelToggle", testUpdateIssueLabelToggle)
t.Run("InitializeLabels", testInitializeLabels)
t.Run("DeleteLabel", testDeleteLabel)
} }
func TestInitializeLabels(t *testing.T) { func testInitializeLabels(t *testing.T) {
unittest.PrepareTestEnv(t)
assert.NoError(t, repository.LoadRepoConfig()) assert.NoError(t, repository.LoadRepoConfig())
ctx, _ := contexttest.MockContext(t, "user2/repo1/labels/initialize") ctx, _ := contexttest.MockContext(t, "user2/repo1/labels/initialize")
contexttest.LoadUser(t, ctx, 2) contexttest.LoadUser(t, ctx, 2)
@ -47,8 +50,7 @@ func TestInitializeLabels(t *testing.T) {
assert.Equal(t, "/user2/repo2/labels", test.RedirectURL(ctx.Resp)) assert.Equal(t, "/user2/repo2/labels", test.RedirectURL(ctx.Resp))
} }
func TestRetrieveLabels(t *testing.T) { func testRetrieveLabels(t *testing.T) {
unittest.PrepareTestEnv(t)
for _, testCase := range []struct { for _, testCase := range []struct {
RepoID int64 RepoID int64
Sort string Sort string
@ -74,9 +76,8 @@ func TestRetrieveLabels(t *testing.T) {
} }
} }
func TestNewLabel(t *testing.T) { func testNewLabel(t *testing.T) {
unittest.PrepareTestEnv(t) ctx, respWriter := contexttest.MockContext(t, "user2/repo1/labels/edit")
ctx, _ := contexttest.MockContext(t, "user2/repo1/labels/edit")
contexttest.LoadUser(t, ctx, 2) contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1) contexttest.LoadRepo(t, ctx, 1)
web.SetForm(ctx, &forms.CreateLabelForm{ web.SetForm(ctx, &forms.CreateLabelForm{
@ -84,17 +85,32 @@ func TestNewLabel(t *testing.T) {
Color: "#abcdef", Color: "#abcdef",
}) })
NewLabel(ctx) NewLabel(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus()) assert.Equal(t, http.StatusOK, ctx.Resp.WrittenStatus())
unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ unittest.AssertExistsAndLoadBean(t, &issues_model.Label{
Name: "newlabel", Name: "newlabel",
Color: "#abcdef", Color: "#abcdef",
}) })
assert.Equal(t, "/user2/repo1/labels", test.RedirectURL(ctx.Resp)) assert.Equal(t, "/user2/repo1/labels", test.RedirectURL(respWriter))
} }
func TestUpdateLabel(t *testing.T) { func testNewLabelInvalidColor(t *testing.T) {
unittest.PrepareTestEnv(t) ctx, respWriter := contexttest.MockContext(t, "user2/repo1/labels/edit")
ctx, _ := contexttest.MockContext(t, "user2/repo1/labels/edit") contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1)
web.SetForm(ctx, &forms.CreateLabelForm{
Title: "newlabel-x",
Color: "bad-label-code",
})
NewLabel(ctx)
assert.Equal(t, http.StatusBadRequest, ctx.Resp.WrittenStatus())
assert.Equal(t, "repo.issues.label_color_invalid", test.ParseJSONError(respWriter.Body.Bytes()).ErrorMessage)
unittest.AssertNotExistsBean(t, &issues_model.Label{
Name: "newlabel-x",
})
}
func testUpdateLabel(t *testing.T) {
ctx, respWriter := contexttest.MockContext(t, "user2/repo1/labels/edit")
contexttest.LoadUser(t, ctx, 2) contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1) contexttest.LoadRepo(t, ctx, 1)
web.SetForm(ctx, &forms.CreateLabelForm{ web.SetForm(ctx, &forms.CreateLabelForm{
@ -104,17 +120,37 @@ func TestUpdateLabel(t *testing.T) {
IsArchived: true, IsArchived: true,
}) })
UpdateLabel(ctx) UpdateLabel(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus()) assert.Equal(t, http.StatusOK, ctx.Resp.WrittenStatus())
unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ unittest.AssertExistsAndLoadBean(t, &issues_model.Label{
ID: 2, ID: 2,
Name: "newnameforlabel", Name: "newnameforlabel",
Color: "#abcdef", Color: "#abcdef",
}) })
assert.Equal(t, "/user2/repo1/labels", test.RedirectURL(ctx.Resp)) assert.Equal(t, "/user2/repo1/labels", test.RedirectURL(respWriter))
} }
func TestDeleteLabel(t *testing.T) { func testUpdateLabelInvalidColor(t *testing.T) {
unittest.PrepareTestEnv(t) ctx, respWriter := contexttest.MockContext(t, "user2/repo1/labels/edit")
contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1)
web.SetForm(ctx, &forms.CreateLabelForm{
ID: 1,
Title: "label1",
Color: "bad-label-code",
})
UpdateLabel(ctx)
assert.Equal(t, http.StatusBadRequest, ctx.Resp.WrittenStatus())
assert.Equal(t, "repo.issues.label_color_invalid", test.ParseJSONError(respWriter.Body.Bytes()).ErrorMessage)
unittest.AssertExistsAndLoadBean(t, &issues_model.Label{
ID: 1,
Name: "label1",
Color: "#abcdef",
})
}
func testDeleteLabel(t *testing.T) {
ctx, _ := contexttest.MockContext(t, "user2/repo1/labels/delete") ctx, _ := contexttest.MockContext(t, "user2/repo1/labels/delete")
contexttest.LoadUser(t, ctx, 2) contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1) contexttest.LoadRepo(t, ctx, 1)
@ -126,8 +162,7 @@ func TestDeleteLabel(t *testing.T) {
assert.EqualValues(t, ctx.Tr("repo.issues.label_deletion_success"), ctx.Flash.SuccessMsg) assert.EqualValues(t, ctx.Tr("repo.issues.label_deletion_success"), ctx.Flash.SuccessMsg)
} }
func TestUpdateIssueLabel_Clear(t *testing.T) { func testUpdateIssueLabelClear(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels") ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
contexttest.LoadUser(t, ctx, 2) contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1) contexttest.LoadRepo(t, ctx, 1)
@ -140,7 +175,7 @@ func TestUpdateIssueLabel_Clear(t *testing.T) {
unittest.CheckConsistencyFor(t, &issues_model.Label{}) unittest.CheckConsistencyFor(t, &issues_model.Label{})
} }
func TestUpdateIssueLabel_Toggle(t *testing.T) { func testUpdateIssueLabelToggle(t *testing.T) {
for _, testCase := range []struct { for _, testCase := range []struct {
Action string Action string
IssueIDs []int64 IssueIDs []int64
@ -156,7 +191,8 @@ func TestUpdateIssueLabel_Toggle(t *testing.T) {
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels") ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
contexttest.LoadUser(t, ctx, 2) contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1) contexttest.LoadRepo(t, ctx, 1)
ctx.Req.Form.Set("issue_ids", int64SliceToCommaSeparated(testCase.IssueIDs))
ctx.Req.Form.Set("issue_ids", strings.Join(base.Int64sToStrings(testCase.IssueIDs), ","))
ctx.Req.Form.Set("action", testCase.Action) ctx.Req.Form.Set("action", testCase.Action)
ctx.Req.Form.Set("id", strconv.Itoa(int(testCase.LabelID))) ctx.Req.Form.Set("id", strconv.Itoa(int(testCase.LabelID)))
UpdateIssueLabel(ctx) UpdateIssueLabel(ctx)

View File

@ -0,0 +1,26 @@
// Copyright 2025 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package label
import (
"code.gitea.io/gitea/modules/label"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/services/context"
"code.gitea.io/gitea/services/forms"
)
func GetLabelEditForm(ctx *context.Context) *forms.CreateLabelForm {
form := web.GetForm(ctx).(*forms.CreateLabelForm)
if ctx.HasError() {
ctx.JSONError(ctx.Data["ErrorMsg"].(string))
return nil
}
var err error
form.Color, err = label.NormalizeColor(form.Color)
if err != nil {
ctx.JSONError(ctx.Tr("repo.issues.label_color_invalid"))
return nil
}
return form
}

View File

@ -5,7 +5,7 @@
> >
<div class="header"></div> <div class="header"></div>
<div class="content"> <div class="content">
<form class="ui form ignore-dirty" method="post"> <form class="ui form ignore-dirty form-fetch-action" method="post">
{{.CsrfTokenHtml}} {{.CsrfTokenHtml}}
<input name="id" type="hidden"> <input name="id" type="hidden">
<div class="required field"> <div class="required field">
@ -50,7 +50,8 @@
<div class="field"> <div class="field">
<label for="color">{{ctx.Locale.Tr "repo.issues.label_color"}}</label> <label for="color">{{ctx.Locale.Tr "repo.issues.label_color"}}</label>
<div class="column js-color-picker-input"> <div class="column js-color-picker-input">
<input name="color" value="#70c24a" placeholder="#c320f6" required maxlength="7"> <!-- the "#" is optional because backend NormalizeColor is able to handle it, API also accepts both formats, and it is easier for users to directly copy-paste a hex value -->
<input name="color" value="#70c24a" placeholder="#c320f6" required pattern="^#?([\dA-Fa-f]{3}|[\dA-Fa-f]{6})$" maxlength="7">
{{template "repo/issue/label_precolors"}} {{template "repo/issue/label_precolors"}}
</div> </div>
</div> </div>

View File

@ -70,7 +70,7 @@ export function initCompLabelEdit(pageSelector: string) {
form.reportValidity(); form.reportValidity();
return false; return false;
} }
form.submit(); form.dispatchEvent(new Event('submit', {bubbles: true}));
}, },
}).modal('show'); }).modal('show');
}; };