improve & refactor & return specific error pages

This commit is contained in:
6543 2022-11-07 22:47:03 +01:00
parent 60aefb4bf5
commit 70871e77be
No known key found for this signature in database
GPG key ID: B8BE6D610E61C862
4 changed files with 45 additions and 24 deletions

View file

@ -2,6 +2,7 @@ package gitea
import ( import (
"bytes" "bytes"
"fmt"
"io" "io"
"net/http" "net/http"
"time" "time"
@ -55,6 +56,8 @@ func (f FileResponse) createHttpResponse() *http.Response {
} }
resp.Header.Set(eTagHeader, f.ETag) resp.Header.Set(eTagHeader, f.ETag)
resp.Header.Set(contentTypeHeader, f.MimeType) resp.Header.Set(contentTypeHeader, f.MimeType)
resp.Header.Set(contentLengthHeader, fmt.Sprint(len(f.Body)))
resp.Header.Set(pagesCacheIndicator, "true")
return resp return resp
} }

View file

@ -27,6 +27,9 @@ const (
defaultBranchCacheKeyPrefix = "defaultBranch" defaultBranchCacheKeyPrefix = "defaultBranch"
rawContentCacheKeyPrefix = "rawContent" rawContentCacheKeyPrefix = "rawContent"
// pages server
pagesCacheIndicator = "X-Pages-Cache"
// gitea // gitea
giteaObjectTypeHeader = "X-Gitea-Object-Type" giteaObjectTypeHeader = "X-Gitea-Object-Type"
objTypeSymlink = "symlink" objTypeSymlink = "symlink"

View file

@ -1,7 +1,9 @@
package server package server
import ( import (
"fmt"
"net/http" "net/http"
"path"
"strings" "strings"
"github.com/rs/zerolog" "github.com/rs/zerolog"
@ -58,7 +60,7 @@ func Handler(mainDomainSuffix, rawDomain string,
// Block blacklisted paths (like ACME challenges) // Block blacklisted paths (like ACME challenges)
for _, blacklistedPath := range blacklistedPaths { for _, blacklistedPath := range blacklistedPaths {
if strings.HasPrefix(ctx.Path(), blacklistedPath) { if strings.HasPrefix(ctx.Path(), blacklistedPath) {
html.ReturnErrorPage(ctx, "", http.StatusForbidden) html.ReturnErrorPage(ctx, "requested blacklisted path", http.StatusForbidden)
return return
} }
} }
@ -90,7 +92,7 @@ func Handler(mainDomainSuffix, rawDomain string,
// tryBranch checks if a branch exists and populates the target variables. If canonicalLink is non-empty, it will // tryBranch checks if a branch exists and populates the target variables. If canonicalLink is non-empty, it will
// also disallow search indexing and add a Link header to the canonical URL. // also disallow search indexing and add a Link header to the canonical URL.
tryBranch := func(log zerolog.Logger, repo, branch string, path []string, canonicalLink string) bool { tryBranch := func(log zerolog.Logger, repo, branch string, _path []string, canonicalLink string) bool {
if repo == "" { if repo == "" {
log.Debug().Msg("tryBranch: repo == ''") log.Debug().Msg("tryBranch: repo == ''")
return false return false
@ -109,7 +111,7 @@ func Handler(mainDomainSuffix, rawDomain string,
// Branch exists, use it // Branch exists, use it
targetRepo = repo targetRepo = repo
targetPath = strings.Trim(strings.Join(path, "/"), "/") targetPath = path.Join(_path...)
targetBranch = branchTimestampResult.Branch targetBranch = branchTimestampResult.Branch
targetOptions.BranchTimestamp = branchTimestampResult.Timestamp targetOptions.BranchTimestamp = branchTimestampResult.Timestamp
@ -157,8 +159,8 @@ func Handler(mainDomainSuffix, rawDomain string,
canonicalDomainCache) canonicalDomainCache)
return return
} }
log.Debug().Msg("missing branch") log.Debug().Msg("missing branch info")
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency) html.ReturnErrorPage(ctx, "missing branch info", http.StatusFailedDependency)
return return
} }
@ -198,8 +200,9 @@ func Handler(mainDomainSuffix, rawDomain string,
} }
log.Debug().Msg("main domain preparations, now trying with specified repo & branch") log.Debug().Msg("main domain preparations, now trying with specified repo & branch")
branch := pathElements[1][1:]
if tryBranch(log, if tryBranch(log,
pathElements[0], pathElements[1][1:], pathElements[2:], pathElements[0], branch, pathElements[2:],
"/"+pathElements[0]+"/%p", "/"+pathElements[0]+"/%p",
) { ) {
log.Debug().Msg("tryBranch, now trying upstream 3") log.Debug().Msg("tryBranch, now trying upstream 3")
@ -207,7 +210,9 @@ func Handler(mainDomainSuffix, rawDomain string,
targetOptions, targetOwner, targetRepo, targetBranch, targetPath, targetOptions, targetOwner, targetRepo, targetBranch, targetPath,
canonicalDomainCache) canonicalDomainCache)
} else { } else {
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency) html.ReturnErrorPage(ctx,
fmt.Sprintf("explizite set branch '%s' do not exist at '%s/%s'", branch, targetOwner, targetRepo),
http.StatusFailedDependency)
} }
return return
} }
@ -216,14 +221,17 @@ func Handler(mainDomainSuffix, rawDomain string,
// example.codeberg.page/@main/index.html // example.codeberg.page/@main/index.html
if strings.HasPrefix(pathElements[0], "@") { if strings.HasPrefix(pathElements[0], "@") {
log.Debug().Msg("main domain preparations, now trying with specified branch") log.Debug().Msg("main domain preparations, now trying with specified branch")
branch := pathElements[0][1:]
if tryBranch(log, if tryBranch(log,
"pages", pathElements[0][1:], pathElements[1:], "/%p") { "pages", branch, pathElements[1:], "/%p") {
log.Debug().Msg("tryBranch, now trying upstream 4") log.Debug().Msg("tryBranch, now trying upstream 4")
tryUpstream(ctx, giteaClient, mainDomainSuffix, trimmedHost, tryUpstream(ctx, giteaClient, mainDomainSuffix, trimmedHost,
targetOptions, targetOwner, targetRepo, targetBranch, targetPath, targetOptions, targetOwner, "pages", targetBranch, targetPath,
canonicalDomainCache) canonicalDomainCache)
} else { } else {
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency) html.ReturnErrorPage(ctx,
fmt.Sprintf("explizite set branch '%s' do not exist at '%s/%s'", branch, targetOwner, "pages"),
http.StatusFailedDependency)
} }
return return
} }
@ -254,15 +262,19 @@ func Handler(mainDomainSuffix, rawDomain string,
} }
// Couldn't find a valid repo/branch // Couldn't find a valid repo/branch
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency) html.ReturnErrorPage(ctx,
fmt.Sprintf("couldn't find a valid repo[%s]/branch[%s]", targetRepo, targetBranch),
http.StatusFailedDependency)
return return
} else { } else {
trimmedHostStr := string(trimmedHost) trimmedHostStr := string(trimmedHost)
// Serve pages from external domains // Serve pages from custom domains
targetOwner, targetRepo, targetBranch = dns.GetTargetFromDNS(trimmedHostStr, string(mainDomainSuffix), dnsLookupCache) targetOwner, targetRepo, targetBranch = dns.GetTargetFromDNS(trimmedHostStr, string(mainDomainSuffix), dnsLookupCache)
if targetOwner == "" { if targetOwner == "" {
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency) html.ReturnErrorPage(ctx,
"could not obtain repo owner from custom domain",
http.StatusFailedDependency)
return return
} }
@ -280,7 +292,7 @@ func Handler(mainDomainSuffix, rawDomain string,
targetRepo, targetBranch, pathElements, canonicalLink) { targetRepo, targetBranch, pathElements, canonicalLink) {
canonicalDomain, valid := upstream.CheckCanonicalDomain(giteaClient, targetOwner, targetRepo, targetBranch, trimmedHostStr, string(mainDomainSuffix), canonicalDomainCache) canonicalDomain, valid := upstream.CheckCanonicalDomain(giteaClient, targetOwner, targetRepo, targetBranch, trimmedHostStr, string(mainDomainSuffix), canonicalDomainCache)
if !valid { if !valid {
html.ReturnErrorPage(ctx, "", http.StatusMisdirectedRequest) html.ReturnErrorPage(ctx, "domain not specified in <code>.domains</code> file", http.StatusMisdirectedRequest)
return return
} else if canonicalDomain != trimmedHostStr { } else if canonicalDomain != trimmedHostStr {
// only redirect if the target is also a codeberg page! // only redirect if the target is also a codeberg page!
@ -290,7 +302,7 @@ func Handler(mainDomainSuffix, rawDomain string,
return return
} }
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency) html.ReturnErrorPage(ctx, "target is no codeberg page", http.StatusFailedDependency)
return return
} }
@ -301,7 +313,7 @@ func Handler(mainDomainSuffix, rawDomain string,
return return
} }
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency) html.ReturnErrorPage(ctx, "could not find target for custom domain", http.StatusFailedDependency)
return return
} }
} }

View file

@ -2,6 +2,7 @@ package upstream
import ( import (
"errors" "errors"
"fmt"
"io" "io"
"net/http" "net/http"
"strings" "strings"
@ -56,23 +57,25 @@ type Options struct {
func (o *Options) Upstream(ctx *context.Context, giteaClient *gitea.Client) (final bool) { func (o *Options) Upstream(ctx *context.Context, giteaClient *gitea.Client) (final bool) {
log := log.With().Strs("upstream", []string{o.TargetOwner, o.TargetRepo, o.TargetBranch, o.TargetPath}).Logger() log := log.With().Strs("upstream", []string{o.TargetOwner, o.TargetRepo, o.TargetBranch, o.TargetPath}).Logger()
if o.TargetOwner == "" || o.TargetRepo == "" {
html.ReturnErrorPage(ctx, "either repo owner or name info is missing", http.StatusBadRequest)
return true
}
// Check if the branch exists and when it was modified // Check if the branch exists and when it was modified
if o.BranchTimestamp.IsZero() { if o.BranchTimestamp.IsZero() {
branch := GetBranchTimestamp(giteaClient, o.TargetOwner, o.TargetRepo, o.TargetBranch) branch := GetBranchTimestamp(giteaClient, o.TargetOwner, o.TargetRepo, o.TargetBranch)
if branch == nil { if branch == nil || branch.Branch == "" {
html.ReturnErrorPage(ctx, "", http.StatusFailedDependency) html.ReturnErrorPage(ctx,
fmt.Sprintf("could not get timestamp of branch '%s'", o.TargetBranch),
http.StatusFailedDependency)
return true return true
} }
o.TargetBranch = branch.Branch o.TargetBranch = branch.Branch
o.BranchTimestamp = branch.Timestamp o.BranchTimestamp = branch.Timestamp
} }
if o.TargetOwner == "" || o.TargetRepo == "" || o.TargetBranch == "" {
html.ReturnErrorPage(ctx, "", http.StatusBadRequest)
return true
}
// Check if the browser has a cached version // Check if the browser has a cached version
if ifModifiedSince, err := time.Parse(time.RFC1123, string(ctx.Response().Header.Get(headerIfModifiedSince))); err == nil { if ifModifiedSince, err := time.Parse(time.RFC1123, string(ctx.Response().Header.Get(headerIfModifiedSince))); err == nil {
if !ifModifiedSince.Before(o.BranchTimestamp) { if !ifModifiedSince.Before(o.BranchTimestamp) {
@ -127,7 +130,7 @@ func (o *Options) Upstream(ctx *context.Context, giteaClient *gitea.Client) (fin
} }
if res != nil && (err != nil || res.StatusCode != http.StatusOK) { if res != nil && (err != nil || res.StatusCode != http.StatusOK) {
log.Printf("Couldn't fetch contents (status code %d): %v\n", res.StatusCode, err) log.Printf("Couldn't fetch contents (status code %d): %v\n", res.StatusCode, err)
html.ReturnErrorPage(ctx, "", http.StatusInternalServerError) html.ReturnErrorPage(ctx, fmt.Sprintf("%v", err), http.StatusInternalServerError)
return true return true
} }