diff options
author | feistel <6742251-feistel@users.noreply.gitlab.com> | 2022-04-20 22:21:56 +0300 |
---|---|---|
committer | feistel <6742251-feistel@users.noreply.gitlab.com> | 2022-06-05 22:53:52 +0300 |
commit | 185d9aed1b2645f7c110513685b7ff1b61c50c0f (patch) | |
tree | 7966c31b0721fa3ac0410a5fdcb23ec2e37b486f /internal/handlers/acme.go | |
parent | fd62cfc0771c627bd1bda001fd1fa71178dd447b (diff) |
Refactor acme tests and middleware for lazy domain resolution
Diffstat (limited to 'internal/handlers/acme.go')
-rw-r--r-- | internal/handlers/acme.go | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/internal/handlers/acme.go b/internal/handlers/acme.go new file mode 100644 index 00000000..258aaebe --- /dev/null +++ b/internal/handlers/acme.go @@ -0,0 +1,46 @@ +package handlers + +import ( + "errors" + "net/http" + "net/url" + + "gitlab.com/gitlab-org/gitlab-pages/internal/acme" + "gitlab.com/gitlab-org/gitlab-pages/internal/domain" + "gitlab.com/gitlab-org/gitlab-pages/internal/httperrors" + "gitlab.com/gitlab-org/gitlab-pages/internal/logging" + "gitlab.com/gitlab-org/gitlab-pages/internal/request" + "gitlab.com/gitlab-org/gitlab-pages/internal/source" +) + +func AcmeMiddleware(handler http.Handler, s source.Source, gitlabURL string) http.Handler { + if gitlabURL == "" { + return handler + } + + u, _ := url.Parse(gitlabURL) + fn := serveFromDomain(s) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if acme.ServeAcmeChallenges(w, r, fn, u) { + return + } + + handler.ServeHTTP(w, r) + }) +} + +func serveFromDomain(s source.Source) acme.FallbackStrategy { + return func(w http.ResponseWriter, r *http.Request) bool { + d, err := s.GetDomain(r.Context(), request.GetHostWithoutPort(r)) + + if err != nil && !errors.Is(err, domain.ErrDomainDoesNotExist) { + logging.LogRequest(r).WithError(err).Error("could not fetch domain information from a source") + + httperrors.Serve502(w) + return true + } + + return d.ServeFileHTTP(w, r) + } +} |