feat: Allow specifying a custom CSP
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
This commit is contained in:
@@ -18,6 +18,10 @@ var (
|
||||
|
||||
// Caching the existence of an user
|
||||
userCache = cache.New(24*time.Hour, 12*time.Hour)
|
||||
|
||||
// Caches the existence of a Content-Security-Policy
|
||||
// Mapping: Repository key -> CSPCacheEntry
|
||||
cspCache = cache.New(24*time.Hour, 12*time.Hour)
|
||||
)
|
||||
|
||||
type PageCacheEntry struct {
|
||||
@@ -25,10 +29,19 @@ type PageCacheEntry struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
type CSPCacheEntry struct {
|
||||
CSP string
|
||||
LastRequested time.Time
|
||||
}
|
||||
|
||||
func makePageCacheKey(domain, path string) string {
|
||||
return domain + "/" + path
|
||||
}
|
||||
|
||||
func makeCSPCacheKey(username, repositoryName string) string {
|
||||
return username + ":" + repositoryName
|
||||
}
|
||||
|
||||
// / Try to find the repository with name @reponame of the user @username. If @cname
|
||||
// / is not "", then it also verifies that the repository contains a "CNAME" with
|
||||
// / the value of @cname as its content. @host, @domain, and @path are passed for
|
||||
@@ -164,3 +177,41 @@ func CanRequestCertificate(username string, giteaClient *GiteaClient) bool {
|
||||
}
|
||||
return hasUser
|
||||
}
|
||||
|
||||
// Checks the repository username/repository@PagesBranch for a file named CSP. If it exists,
|
||||
// read it and return the value. If it does not exist, return defaultCsp.
|
||||
func GetCSPForRepository(username, repositoryName, defaultCsp string, giteaClient *GiteaClient) string {
|
||||
key := makeCSPCacheKey(username, repositoryName)
|
||||
cachedCsp, found := cspCache.Get(key)
|
||||
var since time.Time
|
||||
if found {
|
||||
since = cachedCsp.(CSPCacheEntry).LastRequested
|
||||
}
|
||||
|
||||
fetchedCsp, changed, err := giteaClient.GetFile(
|
||||
username,
|
||||
repositoryName,
|
||||
constants.PagesBranch,
|
||||
"CSP",
|
||||
&since,
|
||||
)
|
||||
csp := ""
|
||||
if err != nil {
|
||||
if found {
|
||||
return cachedCsp.(CSPCacheEntry).CSP
|
||||
}
|
||||
|
||||
csp = defaultCsp
|
||||
} else {
|
||||
csp = string(fetchedCsp)
|
||||
|
||||
if !found || changed {
|
||||
cspCache.Set(key, CSPCacheEntry{
|
||||
CSP: csp,
|
||||
LastRequested: time.Now(),
|
||||
}, cache.DefaultExpiration)
|
||||
}
|
||||
}
|
||||
|
||||
return csp
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
func clearCache() {
|
||||
pathCache.Flush()
|
||||
userCache.Flush()
|
||||
cspCache.Flush()
|
||||
}
|
||||
|
||||
func TestPickingCorrectRepositoryDefault(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user