Skip to content

Commit a8dc5a5

Browse files
committed
support hsts
1 parent 072bdfa commit a8dc5a5

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

modules/setting/hsts.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright 2019 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package setting
6+
7+
import "time"
8+
9+
const (
10+
defaultMaxAge = time.Hour * 24 * 365
11+
)
12+
13+
// HSTS is the configuration of HSTS
14+
var HSTS = struct {
15+
Enabled bool
16+
MaxAge time.Duration
17+
SendPreloadDirective bool
18+
}{
19+
Enabled: false,
20+
MaxAge: defaultMaxAge,
21+
SendPreloadDirective: false,
22+
}
23+
24+
func configHSTS() {
25+
sec := Cfg.Section("hsts")
26+
// Check mailer setting.
27+
if !sec.Key("ENABLED").MustBool() {
28+
return
29+
}
30+
31+
HSTS.Enabled = true
32+
HSTS.MaxAge = sec.Key("MAX_AGE").MustDuration(defaultMaxAge)
33+
HSTS.SendPreloadDirective = sec.Key("SEND_PRELOAD_DIRECTIVE").MustBool()
34+
}

modules/setting/setting.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -910,6 +910,7 @@ func NewContext() {
910910

911911
newCron()
912912
newGit()
913+
configHSTS()
913914

914915
sec = Cfg.Section("mirror")
915916
Mirror.MinInterval = sec.Key("MIN_INTERVAL").MustDuration(10 * time.Minute)

routers/routes/routes.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"net/http"
1111
"os"
1212
"path"
13+
"strconv"
1314
"text/template"
1415
"time"
1516

@@ -102,6 +103,16 @@ func RouterHandler(level log.Level) func(ctx *macaron.Context) {
102103
}
103104
}
104105

106+
func createHeaderValueNew(maxAge time.Duration, sendPreloadDirective bool) string {
107+
buf := bytes.NewBufferString("max-age=")
108+
buf.WriteString(strconv.Itoa(int(maxAge.Seconds())))
109+
buf.WriteString("; includeSubDomains")
110+
if sendPreloadDirective {
111+
buf.WriteString("; preload")
112+
}
113+
return buf.String()
114+
}
115+
105116
// NewMacaron initializes Macaron instance.
106117
func NewMacaron() *macaron.Macaron {
107118
gob.Register(&u2f.Challenge{})
@@ -131,6 +142,13 @@ func NewMacaron() *macaron.Macaron {
131142
if setting.Protocol == setting.FCGI {
132143
m.SetURLPrefix(setting.AppSubURL)
133144
}
145+
if setting.HSTS.Enabled {
146+
m.Use(func() macaron.Handler {
147+
return func(ctx *macaron.Context) {
148+
ctx.Resp.Header().Set("Strict-Transport-Security", createHeaderValueNew(setting.HSTS.MaxAge, setting.HSTS.SendPreloadDirective))
149+
}
150+
})
151+
}
134152
m.Use(public.Custom(
135153
&public.Options{
136154
SkipLogging: setting.DisableRouterLog,

0 commit comments

Comments
 (0)