mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2026-05-13 06:20:24 +00:00
One of the security patches released 2026-03-09 [fixed a vulnerability](https://codeberg.org/forgejo/forgejo/pulls/11513/commits/d1c7b04d09f6a13896eaa1322ac690b2021539da) caused by a misapplication of Go `case` statements, where the implementation would have been correct if Go `case` statements automatically fall through to the next case block, but they do not. This PR adds a semgrep rule which detects any empty `case` statement and raises an error, in order to prevent this coding mistake in the future. For example, code like this will now trigger a build error: ```go switch setting.Protocol { case setting.HTTPUnix: case setting.FCGI: case setting.FCGIUnix: default: defaultLocalURL := string(setting.Protocol) + "://" } ``` Example error: ``` cmd/web.go ❯❯❱ semgrep.config.forgejo-switch-empty-case switch has a case block with no content. This is treated as "break" by Go, but developers may confuse it for "fallthrough". To fix this error, disambiguate by using "break" or "fallthrough". 279┆ switch setting.Protocol { 280┆ case setting.HTTPUnix: 281┆ case setting.FCGI: 282┆ case setting.FCGIUnix: 283┆ default: 284┆ defaultLocalURL := string(setting.Protocol) + "://" 285┆ if setting.HTTPAddr == "0.0.0.0" { 286┆ defaultLocalURL += "localhost" 287┆ } else { 288┆ defaultLocalURL += setting.HTTPAddr ``` As described in the error output, this error can be fixed by explicitly listing `break` (the real Go behaviour, to do nothing in the block), or by listing `fallthrough` (if the intent was to fall through). All existing code triggering this detection has been changed to `break` (or, rarely, irrelevant cases have been removed), which should maintain the same code functionality. While performing this fixup, a light analysis was performed on each case and they *appeared* correct, but with ~65 cases I haven't gone into extreme depth. Tests are present for the semgrep rule in `.semgrep/tests/go.go`. ## Checklist The [contributor guide](https://forgejo.org/docs/next/contributor/) contains information that will be helpful to first time contributors. There also are a few [conditions for merging Pull Requests in Forgejo repositories](https://codeberg.org/forgejo/governance/src/branch/main/PullRequestsAgreement.md). You are also welcome to join the [Forgejo development chatroom](https://matrix.to/#/#forgejo-development:matrix.org). ### Documentation - [ ] I created a pull request [to the documentation](https://codeberg.org/forgejo/docs) to explain to Forgejo users how to use this change. - [x] I did not document these changes and I do not expect someone else to do it. ### Release notes - [ ] This change will be noticed by a Forgejo user or admin (feature, bug fix, performance, etc.). I suggest to include a release note for this change. - [x] This change is not visible to a Forgejo user or admin (refactor, dependency upgrade, etc.). I think there is no need to add a release note for this change. Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/11593 Reviewed-by: Gusted <gusted@noreply.codeberg.org> Co-authored-by: Mathieu Fenniak <mathieu@fenniak.net> Co-committed-by: Mathieu Fenniak <mathieu@fenniak.net>
149 lines
4.3 KiB
Go
149 lines
4.3 KiB
Go
// Copyright 2024 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package templates
|
|
|
|
import (
|
|
"fmt"
|
|
"html"
|
|
"html/template"
|
|
"strings"
|
|
"time"
|
|
|
|
"forgejo.org/modules/setting"
|
|
"forgejo.org/modules/timeutil"
|
|
"forgejo.org/modules/translation"
|
|
)
|
|
|
|
type DateUtils struct{}
|
|
|
|
func NewDateUtils() *DateUtils {
|
|
return (*DateUtils)(nil) // the util is stateless, and we do not need to create an instance
|
|
}
|
|
|
|
// AbsoluteShort renders in "Jan 01, 2006" format
|
|
func (du *DateUtils) AbsoluteShort(time any) template.HTML {
|
|
return dateTimeFormat("short", time)
|
|
}
|
|
|
|
// AbsoluteLong renders in "January 01, 2006" format
|
|
func (du *DateUtils) AbsoluteLong(time any) template.HTML {
|
|
return dateTimeFormat("long", time)
|
|
}
|
|
|
|
// FullTime renders in "Jan 01, 2006 20:33:44" format
|
|
func (du *DateUtils) FullTime(time any) template.HTML {
|
|
return dateTimeFormat("full", time)
|
|
}
|
|
|
|
func (du *DateUtils) TimeSince(time any) template.HTML {
|
|
return TimeSince(time)
|
|
}
|
|
|
|
// ParseLegacy parses the datetime in legacy format, eg: "2016-01-02" in server's timezone.
|
|
// It shouldn't be used in new code. New code should use Time or TimeStamp as much as possible.
|
|
func (du *DateUtils) ParseLegacy(datetime string) time.Time {
|
|
return parseLegacy(datetime)
|
|
}
|
|
|
|
func parseLegacy(datetime string) time.Time {
|
|
t, err := time.Parse(time.RFC3339, datetime)
|
|
if err != nil {
|
|
t, _ = time.ParseInLocation(time.DateOnly, datetime, setting.DefaultUILocation)
|
|
}
|
|
return t
|
|
}
|
|
|
|
func dateTimeLegacy(format string, datetime any, _ ...string) template.HTML {
|
|
if !setting.IsProd || setting.IsInTesting {
|
|
panic("dateTimeLegacy is for backward compatibility only, do not use it in new code")
|
|
}
|
|
if s, ok := datetime.(string); ok {
|
|
datetime = parseLegacy(s)
|
|
}
|
|
return dateTimeFormat(format, datetime)
|
|
}
|
|
|
|
func timeSinceLegacy(time any, _ translation.Locale) template.HTML {
|
|
if !setting.IsProd || setting.IsInTesting {
|
|
panic("timeSinceLegacy is for backward compatibility only, do not use it in new code")
|
|
}
|
|
return TimeSince(time)
|
|
}
|
|
|
|
func anyToTime(any any) (t time.Time, isZero bool) {
|
|
switch v := any.(type) {
|
|
case nil:
|
|
// it is zero
|
|
break
|
|
case *time.Time:
|
|
if v != nil {
|
|
t = *v
|
|
}
|
|
case time.Time:
|
|
t = v
|
|
case timeutil.TimeStamp:
|
|
t = v.AsTime()
|
|
case timeutil.TimeStampNano:
|
|
t = v.AsTime()
|
|
case int:
|
|
t = timeutil.TimeStamp(v).AsTime()
|
|
case int64:
|
|
t = timeutil.TimeStamp(v).AsTime()
|
|
default:
|
|
panic(fmt.Sprintf("Unsupported time type %T", any))
|
|
}
|
|
return t, t.IsZero() || t.Unix() == 0
|
|
}
|
|
|
|
func dateTimeFormat(format string, datetime any) template.HTML {
|
|
t, isZero := anyToTime(datetime)
|
|
if isZero {
|
|
return "-"
|
|
}
|
|
var textEscaped string
|
|
datetimeEscaped := html.EscapeString(t.Format(time.RFC3339))
|
|
if format == "full" {
|
|
textEscaped = html.EscapeString(t.Format("2006-01-02 15:04:05 -07:00"))
|
|
} else {
|
|
textEscaped = html.EscapeString(t.Format("2006-01-02"))
|
|
}
|
|
|
|
attrs := []string{`weekday=""`, `year="numeric"`}
|
|
switch format {
|
|
case "short", "long": // date only
|
|
attrs = append(attrs, `month="`+format+`"`, `day="numeric"`)
|
|
return template.HTML(fmt.Sprintf(`<absolute-date %s date="%s">%s</absolute-date>`, strings.Join(attrs, " "), datetimeEscaped, textEscaped))
|
|
case "full": // full date including time
|
|
attrs = append(attrs, `format="datetime"`, `month="short"`, `day="numeric"`, `hour="numeric"`, `minute="numeric"`, `second="numeric"`, `data-tooltip-content`, `data-tooltip-interactive="true"`)
|
|
return template.HTML(fmt.Sprintf(`<relative-time %s datetime="%s">%s</relative-time>`, strings.Join(attrs, " "), datetimeEscaped, textEscaped))
|
|
default:
|
|
panic(fmt.Sprintf("Unsupported format %s", format))
|
|
}
|
|
}
|
|
|
|
func timeSinceTo(then any, now time.Time) template.HTML {
|
|
thenTime, isZero := anyToTime(then)
|
|
if isZero {
|
|
return "-"
|
|
}
|
|
|
|
friendlyText := thenTime.Format("2006-01-02 15:04:05 -07:00")
|
|
|
|
// document: https://github.com/github/relative-time-element
|
|
attrs := `tense="past"`
|
|
isFuture := now.Before(thenTime)
|
|
if isFuture {
|
|
attrs = `tense="future"`
|
|
}
|
|
|
|
// declare data-tooltip-content attribute to switch from "title" tooltip to "tippy" tooltip
|
|
htm := fmt.Sprintf(`<relative-time prefix="" %s datetime="%s" data-tooltip-content data-tooltip-interactive="true">%s</relative-time>`,
|
|
attrs, thenTime.Format(time.RFC3339), friendlyText)
|
|
return template.HTML(htm)
|
|
}
|
|
|
|
// TimeSince renders relative time HTML given a time
|
|
func TimeSince(then any) template.HTML {
|
|
return timeSinceTo(then, time.Now())
|
|
}
|