feat: Allow specifying a custom CSP
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
2024-01-06 17:42:08 +01:00
parent fb54cc73f0
commit 308a72e1b5
5 changed files with 87 additions and 12 deletions

View File

@@ -27,10 +27,23 @@ func makePageContentCacheEntry(username, path string) string {
return username + ":" + path
}
func ServeFile(username, reponame, path string, giteaClient *repo.GiteaClient, w http.ResponseWriter) {
// Provide a default
if path == "" {
func addHeaders(csp, contentType string, w http.ResponseWriter) {
w.Header().Set("Content-Type", contentType)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Strict-Transport-Security", "max-age=31536000")
if csp != "" {
w.Header().Set("Content-Security-Policy", csp)
}
}
func ServeFile(username, reponame, path, defaultCsp string, giteaClient *repo.GiteaClient, w http.ResponseWriter) {
// Provide a default file.
switch {
case path == "":
path = "/index.html"
case path[len(path)-1] == '/':
path = path + "index.html"
}
// Strip away a starting / as it messes with Gitea
@@ -59,15 +72,17 @@ func ServeFile(username, reponame, path string, giteaClient *repo.GiteaClient, w
path,
since,
)
csp := repo.GetCSPForRepository(username, reponame, "", giteaClient)
if err != nil {
if !found {
log.Errorf("Failed to get file %s/%s/%s (%s)", username, reponame, path, err)
addHeaders(csp, "text/html", w)
w.WriteHeader(404)
} else {
log.Debugf("Request failed but page %s is cached in memory", path)
addHeaders(csp, mimeType, w)
w.WriteHeader(200)
w.Header().Set("Content-Type", mimeType)
w.Write(content)
}
@@ -76,8 +91,8 @@ func ServeFile(username, reponame, path string, giteaClient *repo.GiteaClient, w
if found && !changed {
log.Debugf("Page %s is unchanged and cached in memory", path)
addHeaders(csp, mimeType, w)
w.WriteHeader(200)
w.Header().Set("Content-Type", mimeType)
w.Write(content)
return
}
@@ -98,7 +113,7 @@ func ServeFile(username, reponame, path string, giteaClient *repo.GiteaClient, w
)
log.Debugf("Page %s requested from Gitea and cached in memory at %v", path, now)
w.Header().Set("Content-Type", mimeType)
addHeaders(csp, mimeType, w)
w.WriteHeader(200)
w.Write(content)
}