feat: refine AutoCert logic (#843)

* feat: refine AutoCert logic

Signed-off-by: eternal-flame-AD <yume@yumechi.jp>

* add a configurable name to the roundtripper

Signed-off-by: eternal-flame-AD <yume@yumechi.jp>
This commit is contained in:
饺子w (Yumechi) 2025-09-19 04:43:09 -05:00 committed by GitHub
parent 9e1455ff7d
commit 9262a24abc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 47 additions and 7 deletions

View File

@ -17,6 +17,10 @@ server:
enabled: false # if the certificate should be requested from letsencrypt
accepttos: false # if you accept the tos from letsencrypt
cache: data/certs # the directory of the cache from letsencrypt
directoryurl: # override the directory url of the ACME server
# Let's Encrypt highly recommend testing against their staging environment before using their production environment.
# Staging server has high rate limits for testing and debugging, issued certificates are not valid
# example: https://acme-staging-v02.api.letsencrypt.org/directory
hosts: # the hosts for which letsencrypt should request certificates
# - mydomain.tld
# - myotherdomain.tld

View File

@ -23,10 +23,11 @@ type Configuration struct {
CertFile string `default:""`
CertKey string `default:""`
LetsEncrypt struct {
Enabled bool `default:"false"`
AcceptTOS bool `default:"false"`
Cache string `default:"data/certs"`
Hosts []string
Enabled bool `default:"false"`
AcceptTOS bool `default:"false"`
Cache string `default:"data/certs"`
DirectoryURL string `default:""`
Hosts []string
}
}
ResponseHeaders map[string]string

View File

@ -2,8 +2,8 @@ package runner
import (
"context"
"crypto/tls"
"fmt"
"log"
"net"
"net/http"
"os"
@ -13,6 +13,7 @@ import (
"time"
"github.com/gotify/server/v2/config"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
)
@ -31,6 +32,8 @@ func Run(router http.Handler, conf *config.Configuration) error {
if conf.Server.SSL.Enabled {
if conf.Server.SSL.LetsEncrypt.Enabled {
applyLetsEncrypt(s, conf)
} else if conf.Server.SSL.CertFile == "" || conf.Server.SSL.CertKey == "" {
log.Fatalln("CertFile and CertKey must be set to use HTTPS when LetsEncrypt is disabled, please set GOTIFY_SERVER_SSL_CERTFILE and GOTIFY_SERVER_SSL_CERTKEY")
}
httpsListener, err := startListening("TLS connection", conf.Server.SSL.ListenAddr, conf.Server.SSL.Port, conf.Server.KeepAlivePeriodSeconds)
@ -94,12 +97,44 @@ func getNetworkAndAddr(listenAddr string, port int) (string, string) {
return "tcp", fmt.Sprintf("%s:%d", listenAddr, port)
}
type LoggingRoundTripper struct {
Name string
RoundTripper http.RoundTripper
}
func (l *LoggingRoundTripper) RoundTrip(r *http.Request) (resp *http.Response, err error) {
resp, err = l.RoundTripper.RoundTrip(r)
if resp.StatusCode == 429 {
log.Printf("%s Rate Limited: Retry-After %s on %s %s\n", l.Name, resp.Header.Get("Retry-After"), r.Method, r.URL.String())
} else if resp.StatusCode >= 400 {
log.Printf("%s Request Failed: Unexpected status code %d on %s %s\n", l.Name, resp.StatusCode, r.Method, r.URL.String())
} else if err != nil {
log.Printf("%s Request Failed: %s on %s %s\n", l.Name, err.Error(), r.Method, r.URL.String())
}
return
}
func applyLetsEncrypt(s *http.Server, conf *config.Configuration) {
httpClient := &http.Client{
Transport: &LoggingRoundTripper{Name: "Let's Encrypt", RoundTripper: http.DefaultTransport},
Timeout: 60 * time.Second,
}
acmeClient := &acme.Client{
HTTPClient: httpClient,
DirectoryURL: conf.Server.SSL.LetsEncrypt.DirectoryURL,
}
certManager := autocert.Manager{
Prompt: func(tosURL string) bool { return conf.Server.SSL.LetsEncrypt.AcceptTOS },
Client: acmeClient,
Prompt: func(tosURL string) bool {
if !conf.Server.SSL.LetsEncrypt.AcceptTOS {
log.Fatalf("Let's Encrypt TOS must be accepted to use Let's Encrypt, please acknowledge TOS at %s and set GOTIFY_SERVER_SSL_LETSENCRYPT_ACCEPTTOS=true\n", tosURL)
}
return true
},
HostPolicy: autocert.HostWhitelist(conf.Server.SSL.LetsEncrypt.Hosts...),
Cache: autocert.DirCache(conf.Server.SSL.LetsEncrypt.Cache),
}
s.Handler = certManager.HTTPHandler(s.Handler)
s.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate}
s.TLSConfig = certManager.TLSConfig()
}