pages-server/server/upstream/domains.go

82 lines
2.5 KiB
Go
Raw Normal View History

2021-12-05 15:21:05 +01:00
package upstream
import (
"strings"
"time"
"github.com/rs/zerolog/log"
2021-12-05 15:21:05 +01:00
"codeberg.org/codeberg/pages/server/cache"
"codeberg.org/codeberg/pages/server/gitea"
2021-12-05 15:21:05 +01:00
)
// canonicalDomainCacheTimeout specifies the timeout for the canonical domain cache.
var canonicalDomainCacheTimeout = 15 * time.Minute
const canonicalDomainConfig = ".domains"
2021-12-09 20:16:43 +01:00
// CheckCanonicalDomain returns the canonical domain specified in the repo (using the `.domains` file).
2023-01-28 13:29:54 +01:00
func (o *Options) CheckCanonicalDomain(giteaClient *gitea.Client, actualDomain, mainDomainSuffix string, canonicalDomainCache cache.SetGetKey) (domain string, valid bool) {
// Check if this request is cached.
if cachedValue, ok := canonicalDomainCache.Get(o.TargetOwner + "/" + o.TargetRepo + "/" + o.TargetBranch); ok {
2023-01-28 13:29:54 +01:00
domains := cachedValue.([]string)
2021-12-05 15:21:05 +01:00
for _, domain := range domains {
if domain == actualDomain {
valid = true
break
}
}
2023-01-28 13:29:54 +01:00
return domains[0], valid
}
var body []byte
var err error
// Make a request to the Gitea instance.
// Do at least three attempts before bailing out.
for i := 0; i < 3; i++ {
body, err = giteaClient.GiteaRawContent(o.TargetOwner, o.TargetRepo, o.TargetBranch, canonicalDomainConfig)
if err == nil {
2023-01-28 13:29:54 +01:00
break
}
// Only log the error on the last iteration.
if i == 2 {
log.Info().Err(err).Msgf("could not read %s of %s/%s", canonicalDomainConfig, o.TargetOwner, o.TargetRepo)
2021-12-05 15:21:05 +01:00
}
2023-01-28 13:29:54 +01:00
}
var domains []string
for _, domain := range strings.Split(string(body), "\n") {
domain = strings.ToLower(domain)
domain = strings.TrimSpace(domain)
domain = strings.TrimPrefix(domain, "http://")
domain = strings.TrimPrefix(domain, "https://")
if len(domain) > 0 && !strings.HasPrefix(domain, "#") && !strings.ContainsAny(domain, "\t /") && strings.ContainsRune(domain, '.') {
domains = append(domains, domain)
2021-12-05 15:21:05 +01:00
}
2023-01-28 13:29:54 +01:00
if domain == actualDomain {
valid = true
2021-12-05 15:21:05 +01:00
}
}
2023-01-28 13:29:54 +01:00
// Add [owner].[pages-domain] as valid domnain.
domains = append(domains, o.TargetOwner+mainDomainSuffix)
if domains[len(domains)-1] == actualDomain {
valid = true
}
// If the target repository isn't called pages, add `/[repository]` to the
// previous valid domain.
if o.TargetRepo != "" && o.TargetRepo != "pages" {
domains[len(domains)-1] += "/" + o.TargetRepo
}
// Add result to cache.
_ = canonicalDomainCache.Set(o.TargetOwner+"/"+o.TargetRepo+"/"+o.TargetBranch, domains, canonicalDomainCacheTimeout)
// Return the first domain from the list and return if any of the domains
// matched the requested domain.
2021-12-09 20:16:43 +01:00
return domains[0], valid
2021-12-05 15:21:05 +01:00
}