Remove unnecessary conversion (#139)

- Remove unnecessary type conversion.
- Enforce via CI

Co-authored-by: Gusted <williamzijl7@hotmail.com>
Reviewed-on: https://codeberg.org/Codeberg/pages-server/pulls/139
Reviewed-by: 6543 <6543@obermui.de>
Co-authored-by: Gusted <gusted@noreply.codeberg.org>
Co-committed-by: Gusted <gusted@noreply.codeberg.org>
This commit is contained in:
Gusted 2022-11-15 16:15:11 +01:00 committed by 6543
parent 3c61a39864
commit f2f943c0d8
14 changed files with 64 additions and 43 deletions

20
.golangci.yml Normal file
View file

@ -0,0 +1,20 @@
linters-settings:
gocritic:
enabled-tags:
- diagnostic
- experimental
- opinionated
- performance
- style
disabled-checks:
- importShadow
- ifElseChain
- hugeParam
linters:
enable:
- unconvert
- gocritic
run:
timeout: 5m

View file

@ -65,7 +65,7 @@ func Serve(ctx *cli.Context) error {
} }
allowedCorsDomains := AllowedCorsDomains allowedCorsDomains := AllowedCorsDomains
if len(rawDomain) != 0 { if rawDomain != "" {
allowedCorsDomains = append(allowedCorsDomains, rawDomain) allowedCorsDomains = append(allowedCorsDomains, rawDomain)
} }

View file

@ -124,7 +124,7 @@ func TestLFSSupport(t *testing.T) {
func TestGetOptions(t *testing.T) { func TestGetOptions(t *testing.T) {
log.Println("=== TestGetOptions ===") log.Println("=== TestGetOptions ===")
req, _ := http.NewRequest(http.MethodOptions, "https://mock-pages.codeberg-test.org:4430/README.md", nil) req, _ := http.NewRequest(http.MethodOptions, "https://mock-pages.codeberg-test.org:4430/README.md", http.NoBody)
resp, err := getTestHTTPSClient().Do(req) resp, err := getTestHTTPSClient().Do(req)
assert.NoError(t, err) assert.NoError(t, err)
if !assert.NotNil(t, resp) { if !assert.NotNil(t, resp) {

View file

@ -28,7 +28,7 @@ func TestMain(m *testing.M) {
time.Sleep(10 * time.Second) time.Sleep(10 * time.Second)
os.Exit(m.Run()) m.Run()
} }
func startServer(ctx context.Context) error { func startServer(ctx context.Context) error {

View file

@ -53,17 +53,19 @@ func TLSConfig(mainDomainSuffix string,
if info.SupportedProtos != nil { if info.SupportedProtos != nil {
for _, proto := range info.SupportedProtos { for _, proto := range info.SupportedProtos {
if proto == tlsalpn01.ACMETLS1Protocol { if proto != tlsalpn01.ACMETLS1Protocol {
challenge, ok := challengeCache.Get(sni) continue
if !ok {
return nil, errors.New("no challenge for this domain")
}
cert, err := tlsalpn01.ChallengeCert(sni, challenge.(string))
if err != nil {
return nil, err
}
return cert, nil
} }
challenge, ok := challengeCache.Get(sni)
if !ok {
return nil, errors.New("no challenge for this domain")
}
cert, err := tlsalpn01.ChallengeCert(sni, challenge.(string))
if err != nil {
return nil, err
}
return cert, nil
} }
} }
@ -195,7 +197,7 @@ func (a AcmeHTTPChallengeProvider) CleanUp(domain, token, _ string) error {
func retrieveCertFromDB(sni, mainDomainSuffix, dnsProvider string, acmeUseRateLimits bool, certDB database.CertDB) (tls.Certificate, bool) { func retrieveCertFromDB(sni, mainDomainSuffix, dnsProvider string, acmeUseRateLimits bool, certDB database.CertDB) (tls.Certificate, bool) {
// parse certificate from database // parse certificate from database
res, err := certDB.Get(string(sni)) res, err := certDB.Get(sni)
if err != nil { if err != nil {
panic(err) // TODO: no panic panic(err) // TODO: no panic
} }
@ -216,7 +218,7 @@ func retrieveCertFromDB(sni, mainDomainSuffix, dnsProvider string, acmeUseRateLi
} }
// renew certificates 7 days before they expire // renew certificates 7 days before they expire
if !tlsCertificate.Leaf.NotAfter.After(time.Now().Add(7 * 24 * time.Hour)) { if tlsCertificate.Leaf.NotAfter.Before(time.Now().Add(7 * 24 * time.Hour)) {
// TODO: add ValidUntil to custom res struct // TODO: add ValidUntil to custom res struct
if res.CSR != nil && len(res.CSR) > 0 { if res.CSR != nil && len(res.CSR) > 0 {
// CSR stores the time when the renewal shall be tried again // CSR stores the time when the renewal shall be tried again
@ -227,9 +229,9 @@ func retrieveCertFromDB(sni, mainDomainSuffix, dnsProvider string, acmeUseRateLi
} }
go (func() { go (func() {
res.CSR = nil // acme client doesn't like CSR to be set res.CSR = nil // acme client doesn't like CSR to be set
tlsCertificate, err = obtainCert(acmeClient, []string{string(sni)}, res, "", dnsProvider, mainDomainSuffix, acmeUseRateLimits, certDB) tlsCertificate, err = obtainCert(acmeClient, []string{sni}, res, "", dnsProvider, mainDomainSuffix, acmeUseRateLimits, certDB)
if err != nil { if err != nil {
log.Error().Msgf("Couldn't renew certificate for %s: %v", string(sni), err) log.Error().Msgf("Couldn't renew certificate for %s: %v", sni, err)
} }
})() })()
} }
@ -262,7 +264,7 @@ func obtainCert(acmeClient *lego.Client, domains []string, renew *certificate.Re
defer obtainLocks.Delete(name) defer obtainLocks.Delete(name)
if acmeClient == nil { if acmeClient == nil {
return mockCert(domains[0], "ACME client uninitialized. This is a server error, please report!", string(mainDomainSuffix), keyDatabase), nil return mockCert(domains[0], "ACME client uninitialized. This is a server error, please report!", mainDomainSuffix, keyDatabase), nil
} }
// request actual cert // request actual cert
@ -305,12 +307,12 @@ func obtainCert(acmeClient *lego.Client, domains []string, renew *certificate.Re
// avoid sending a mock cert instead of a still valid cert, instead abuse CSR field to store time to try again at // avoid sending a mock cert instead of a still valid cert, instead abuse CSR field to store time to try again at
renew.CSR = []byte(strconv.FormatInt(time.Now().Add(6*time.Hour).Unix(), 10)) renew.CSR = []byte(strconv.FormatInt(time.Now().Add(6*time.Hour).Unix(), 10))
if err := keyDatabase.Put(name, renew); err != nil { if err := keyDatabase.Put(name, renew); err != nil {
return mockCert(domains[0], err.Error(), string(mainDomainSuffix), keyDatabase), err return mockCert(domains[0], err.Error(), mainDomainSuffix, keyDatabase), err
} }
return tlsCertificate, nil return tlsCertificate, nil
} }
} }
return mockCert(domains[0], err.Error(), string(mainDomainSuffix), keyDatabase), err return mockCert(domains[0], err.Error(), mainDomainSuffix, keyDatabase), err
} }
log.Debug().Msgf("Obtained certificate for %v", domains) log.Debug().Msgf("Obtained certificate for %v", domains)
@ -408,7 +410,7 @@ func SetupAcmeConfig(acmeAPI, acmeMail, acmeEabHmac, acmeEabKID string, acmeAcce
func SetupCertificates(mainDomainSuffix, dnsProvider string, acmeConfig *lego.Config, acmeUseRateLimits, enableHTTPServer bool, challengeCache cache.SetGetKey, certDB database.CertDB) error { func SetupCertificates(mainDomainSuffix, dnsProvider string, acmeConfig *lego.Config, acmeUseRateLimits, enableHTTPServer bool, challengeCache cache.SetGetKey, certDB database.CertDB) error {
// getting main cert before ACME account so that we can fail here without hitting rate limits // getting main cert before ACME account so that we can fail here without hitting rate limits
mainCertBytes, err := certDB.Get(string(mainDomainSuffix)) mainCertBytes, err := certDB.Get(mainDomainSuffix)
if err != nil { if err != nil {
return fmt.Errorf("cert database is not working") return fmt.Errorf("cert database is not working")
} }
@ -452,7 +454,7 @@ func SetupCertificates(mainDomainSuffix, dnsProvider string, acmeConfig *lego.Co
} }
if mainCertBytes == nil { if mainCertBytes == nil {
_, err = obtainCert(mainDomainAcmeClient, []string{"*" + string(mainDomainSuffix), string(mainDomainSuffix[1:])}, nil, "", dnsProvider, mainDomainSuffix, acmeUseRateLimits, certDB) _, err = obtainCert(mainDomainAcmeClient, []string{"*" + mainDomainSuffix, mainDomainSuffix[1:]}, nil, "", dnsProvider, mainDomainSuffix, acmeUseRateLimits, certDB)
if err != nil { if err != nil {
log.Error().Err(err).Msg("Couldn't renew main domain certificate, continuing with mock certs only") log.Error().Err(err).Msg("Couldn't renew main domain certificate, continuing with mock certs only")
} }
@ -479,7 +481,7 @@ func MaintainCertDB(ctx context.Context, interval time.Duration, mainDomainSuffi
} }
tlsCertificates, err := certcrypto.ParsePEMBundle(res.Certificate) tlsCertificates, err := certcrypto.ParsePEMBundle(res.Certificate)
if err != nil || !tlsCertificates[0].NotAfter.After(now) { if err != nil || tlsCertificates[0].NotAfter.Before(now) {
err := certDB.Delete(string(key)) err := certDB.Delete(string(key))
if err != nil { if err != nil {
log.Error().Err(err).Msgf("Deleting expired certificate for %q failed", string(key)) log.Error().Err(err).Msgf("Deleting expired certificate for %q failed", string(key))
@ -501,18 +503,18 @@ func MaintainCertDB(ctx context.Context, interval time.Duration, mainDomainSuffi
} }
// update main cert // update main cert
res, err := certDB.Get(string(mainDomainSuffix)) res, err := certDB.Get(mainDomainSuffix)
if err != nil { if err != nil {
log.Error().Msgf("Couldn't get cert for domain %q", mainDomainSuffix) log.Error().Msgf("Couldn't get cert for domain %q", mainDomainSuffix)
} else if res == nil { } else if res == nil {
log.Error().Msgf("Couldn't renew certificate for main domain %q expected main domain cert to exist, but it's missing - seems like the database is corrupted", string(mainDomainSuffix)) log.Error().Msgf("Couldn't renew certificate for main domain %q expected main domain cert to exist, but it's missing - seems like the database is corrupted", mainDomainSuffix)
} else { } else {
tlsCertificates, err := certcrypto.ParsePEMBundle(res.Certificate) tlsCertificates, err := certcrypto.ParsePEMBundle(res.Certificate)
// renew main certificate 30 days before it expires // renew main certificate 30 days before it expires
if !tlsCertificates[0].NotAfter.After(time.Now().Add(30 * 24 * time.Hour)) { if tlsCertificates[0].NotAfter.Before(time.Now().Add(30 * 24 * time.Hour)) {
go (func() { go (func() {
_, err = obtainCert(mainDomainAcmeClient, []string{"*" + string(mainDomainSuffix), string(mainDomainSuffix[1:])}, res, "", dnsProvider, mainDomainSuffix, acmeUseRateLimits, certDB) _, err = obtainCert(mainDomainAcmeClient, []string{"*" + mainDomainSuffix, mainDomainSuffix[1:]}, res, "", dnsProvider, mainDomainSuffix, acmeUseRateLimits, certDB)
if err != nil { if err != nil {
log.Error().Err(err).Msg("Couldn't renew certificate for main domain") log.Error().Err(err).Msg("Couldn't renew certificate for main domain")
} }

View file

@ -44,7 +44,7 @@ func (p aDB) Get(name string) (*certificate.Resource, error) {
if resBytes == nil { if resBytes == nil {
return nil, nil return nil, nil
} }
if err = gob.NewDecoder(bytes.NewBuffer(resBytes)).Decode(cert); err != nil { if err := gob.NewDecoder(bytes.NewBuffer(resBytes)).Decode(cert); err != nil {
return nil, err return nil, err
} }
return cert, nil return cert, nil

View file

@ -42,9 +42,8 @@ func (f FileResponse) IsEmpty() bool {
return len(f.Body) != 0 return len(f.Body) != 0
} }
func (f FileResponse) createHttpResponse(cacheKey string) (http.Header, int) { func (f FileResponse) createHttpResponse(cacheKey string) (header http.Header, statusCode int) {
header := make(http.Header) header = make(http.Header)
var statusCode int
if f.Exists { if f.Exists {
statusCode = http.StatusOK statusCode = http.StatusOK

View file

@ -28,7 +28,7 @@ func Handler(mainDomainSuffix, rawDomain string,
dnsLookupCache, canonicalDomainCache cache.SetGetKey, dnsLookupCache, canonicalDomainCache cache.SetGetKey,
) http.HandlerFunc { ) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) { return func(w http.ResponseWriter, req *http.Request) {
log := log.With().Strs("Handler", []string{string(req.Host), req.RequestURI}).Logger() log := log.With().Strs("Handler", []string{req.Host, req.RequestURI}).Logger()
ctx := context.New(w, req) ctx := context.New(w, req)
ctx.RespWriter.Header().Set("Server", "CodebergPages/"+version.Version) ctx.RespWriter.Header().Set("Server", "CodebergPages/"+version.Version)

View file

@ -54,7 +54,7 @@ func handleCustomDomain(log zerolog.Logger, ctx *context.Context, giteaClient *g
// only redirect if the target is also a codeberg page! // only redirect if the target is also a codeberg page!
targetOwner, _, _ = dns.GetTargetFromDNS(strings.SplitN(canonicalDomain, "/", 2)[0], mainDomainSuffix, dnsLookupCache) targetOwner, _, _ = dns.GetTargetFromDNS(strings.SplitN(canonicalDomain, "/", 2)[0], mainDomainSuffix, dnsLookupCache)
if targetOwner != "" { if targetOwner != "" {
ctx.Redirect("https://"+canonicalDomain+string(targetOpt.TargetPath), http.StatusTemporaryRedirect) ctx.Redirect("https://"+canonicalDomain+targetOpt.TargetPath, http.StatusTemporaryRedirect)
return return
} }

View file

@ -29,7 +29,7 @@ func handleSubDomain(log zerolog.Logger, ctx *context.Context, giteaClient *gite
if targetOwner == "www" { if targetOwner == "www" {
// www.codeberg.page redirects to codeberg.page // TODO: rm hardcoded - use cname? // www.codeberg.page redirects to codeberg.page // TODO: rm hardcoded - use cname?
ctx.Redirect("https://"+string(mainDomainSuffix[1:])+string(ctx.Path()), http.StatusPermanentRedirect) ctx.Redirect("https://"+mainDomainSuffix[1:]+ctx.Path(), http.StatusPermanentRedirect)
return return
} }

View file

@ -21,8 +21,8 @@ func tryUpstream(ctx *context.Context, giteaClient *gitea.Client,
) { ) {
// check if a canonical domain exists on a request on MainDomain // check if a canonical domain exists on a request on MainDomain
if strings.HasSuffix(trimmedHost, mainDomainSuffix) { if strings.HasSuffix(trimmedHost, mainDomainSuffix) {
canonicalDomain, _ := options.CheckCanonicalDomain(giteaClient, "", string(mainDomainSuffix), canonicalDomainCache) canonicalDomain, _ := options.CheckCanonicalDomain(giteaClient, "", mainDomainSuffix, canonicalDomainCache)
if !strings.HasSuffix(strings.SplitN(canonicalDomain, "/", 2)[0], string(mainDomainSuffix)) { if !strings.HasSuffix(strings.SplitN(canonicalDomain, "/", 2)[0], mainDomainSuffix) {
canonicalPath := ctx.Req.RequestURI canonicalPath := ctx.Req.RequestURI
if options.TargetRepo != defaultPagesRepo { if options.TargetRepo != defaultPagesRepo {
path := strings.SplitN(canonicalPath, "/", 3) path := strings.SplitN(canonicalPath, "/", 3)
@ -35,8 +35,8 @@ func tryUpstream(ctx *context.Context, giteaClient *gitea.Client,
} }
} }
// add host for debugging // Add host for debugging.
options.Host = string(trimmedHost) options.Host = trimmedHost
// Try to request the file from the Gitea API // Try to request the file from the Gitea API
if !options.Upstream(ctx, giteaClient) { if !options.Upstream(ctx, giteaClient) {

View file

@ -15,13 +15,13 @@ func SetupHTTPACMEChallengeServer(challengeCache cache.SetGetKey) http.HandlerFu
return func(w http.ResponseWriter, req *http.Request) { return func(w http.ResponseWriter, req *http.Request) {
ctx := context.New(w, req) ctx := context.New(w, req)
if strings.HasPrefix(ctx.Path(), challengePath) { if strings.HasPrefix(ctx.Path(), challengePath) {
challenge, ok := challengeCache.Get(utils.TrimHostPort(ctx.Host()) + "/" + string(strings.TrimPrefix(ctx.Path(), challengePath))) challenge, ok := challengeCache.Get(utils.TrimHostPort(ctx.Host()) + "/" + strings.TrimPrefix(ctx.Path(), challengePath))
if !ok || challenge == nil { if !ok || challenge == nil {
ctx.String("no challenge for this token", http.StatusNotFound) ctx.String("no challenge for this token", http.StatusNotFound)
} }
ctx.String(challenge.(string)) ctx.String(challenge.(string))
} else { } else {
ctx.Redirect("https://"+string(ctx.Host())+string(ctx.Path()), http.StatusMovedPermanently) ctx.Redirect("https://"+ctx.Host()+ctx.Path(), http.StatusMovedPermanently)
} }
} }
} }

View file

@ -13,7 +13,7 @@ import (
func (o *Options) GetBranchTimestamp(giteaClient *gitea.Client) (bool, error) { func (o *Options) GetBranchTimestamp(giteaClient *gitea.Client) (bool, error) {
log := log.With().Strs("BranchInfo", []string{o.TargetOwner, o.TargetRepo, o.TargetBranch}).Logger() log := log.With().Strs("BranchInfo", []string{o.TargetOwner, o.TargetRepo, o.TargetBranch}).Logger()
if len(o.TargetBranch) == 0 { if o.TargetBranch == "" {
// Get default branch // Get default branch
defaultBranch, err := giteaClient.GiteaGetRepoDefaultBranch(o.TargetOwner, o.TargetRepo) defaultBranch, err := giteaClient.GiteaGetRepoDefaultBranch(o.TargetOwner, o.TargetRepo)
if err != nil { if err != nil {

View file

@ -82,8 +82,8 @@ func (o *Options) Upstream(ctx *context.Context, giteaClient *gitea.Client) (fin
// Check if the browser has a cached version // Check if the browser has a cached version
if ctx.Response() != nil { if ctx.Response() != nil {
if ifModifiedSince, err := time.Parse(time.RFC1123, string(ctx.Response().Header.Get(headerIfModifiedSince))); err == nil { if ifModifiedSince, err := time.Parse(time.RFC1123, ctx.Response().Header.Get(headerIfModifiedSince)); err == nil {
if !ifModifiedSince.Before(o.BranchTimestamp) { if ifModifiedSince.After(o.BranchTimestamp) {
ctx.RespWriter.WriteHeader(http.StatusNotModified) ctx.RespWriter.WriteHeader(http.StatusNotModified)
log.Trace().Msg("check response against last modified: valid") log.Trace().Msg("check response against last modified: valid")
return true return true