From e887f922ca3f62cba5001f2fda580515d3422f27 Mon Sep 17 00:00:00 2001 From: Gary Kim Date: Fri, 2 Aug 2019 15:31:41 +0800 Subject: [PATCH] Check commit message hashes before making links Previously, when formatting commit messages, anything that looked like SHA1 hashes was turned into a link using regex. This meant that certain phrases or numbers such as `777777` or `deadbeef` could be recognized as a commit even if the repository has no commit with those hashes. This change will make it so that anything that looks like a SHA1 hash using regex will then also be checked to ensure that there is a commit in the repository with that hash before making a link. Signed-off-by: Gary Kim --- models/repo.go | 5 +++-- modules/markup/html.go | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/models/repo.go b/models/repo.go index fe296c1a11..dbd1f2b688 100644 --- a/models/repo.go +++ b/models/repo.go @@ -508,8 +508,9 @@ func (repo *Repository) mustOwnerName(e Engine) string { func (repo *Repository) ComposeMetas() map[string]string { if repo.ExternalMetas == nil { repo.ExternalMetas = map[string]string{ - "user": repo.MustOwner().Name, - "repo": repo.Name, + "user": repo.MustOwner().Name, + "repo": repo.Name, + "repoPath": repo.RepoPath(), } unit, err := repo.GetUnit(UnitTypeExternalTracker) if err != nil { diff --git a/modules/markup/html.go b/modules/markup/html.go index 825a41dd1f..a3db925f76 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -13,6 +13,7 @@ import ( "strings" "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" @@ -657,6 +658,14 @@ func sha1CurrentPatternProcessor(ctx *postProcessCtx, node *html.Node) { // but that is not always the case. // Although unlikely, deadbeef and 1234567 are valid short forms of SHA1 hash // as used by git and github for linking and thus we have to do similar. + // Because of this, we check to make sure that a matched hash is actually + // a commit in the repository before making it a link. + if ctx.metas["repoPath"] != "" { + if _, err := git.NewCommand("log", "-1", hash).RunInDirBytes(ctx.metas["repoPath"]); err != nil { + return + } + } + replaceContent(node, m[2], m[3], createCodeLink(util.URLJoin(setting.AppURL, ctx.metas["user"], ctx.metas["repo"], "commit", hash), base.ShortSha(hash))) }