You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

web_letsencrypt.go 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "net/http"
  7. "strings"
  8. "code.gitea.io/gitea/modules/log"
  9. "code.gitea.io/gitea/modules/setting"
  10. "github.com/caddyserver/certmagic"
  11. context2 "github.com/gorilla/context"
  12. )
  13. func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error {
  14. // If HTTP Challenge enabled, needs to be serving on port 80. For TLSALPN needs 443.
  15. // Due to docker port mapping this can't be checked programatically
  16. // TODO: these are placeholders until we add options for each in settings with appropriate warning
  17. enableHTTPChallenge := true
  18. enableTLSALPNChallenge := true
  19. magic := certmagic.NewDefault()
  20. magic.Storage = &certmagic.FileStorage{Path: directory}
  21. myACME := certmagic.NewACMEManager(magic, certmagic.ACMEManager{
  22. Email: email,
  23. Agreed: setting.LetsEncryptTOS,
  24. DisableHTTPChallenge: !enableHTTPChallenge,
  25. DisableTLSALPNChallenge: !enableTLSALPNChallenge,
  26. })
  27. magic.Issuer = myACME
  28. // this obtains certificates or renews them if necessary
  29. err := magic.ManageSync([]string{domain})
  30. if err != nil {
  31. return err
  32. }
  33. tlsConfig := magic.TLSConfig()
  34. if enableHTTPChallenge {
  35. go func() {
  36. log.Info("Running Let's Encrypt handler on %s", setting.HTTPAddr+":"+setting.PortToRedirect)
  37. // all traffic coming into HTTP will be redirect to HTTPS automatically (LE HTTP-01 validation happens here)
  38. var err = runHTTP("tcp", setting.HTTPAddr+":"+setting.PortToRedirect, "Let's Encrypt HTTP Challenge", myACME.HTTPChallengeHandler(http.HandlerFunc(runLetsEncryptFallbackHandler)))
  39. if err != nil {
  40. log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err)
  41. }
  42. }()
  43. }
  44. return runHTTPSWithTLSConfig("tcp", listenAddr, "Web", tlsConfig, context2.ClearHandler(m))
  45. }
  46. func runLetsEncryptFallbackHandler(w http.ResponseWriter, r *http.Request) {
  47. if r.Method != "GET" && r.Method != "HEAD" {
  48. http.Error(w, "Use HTTPS", http.StatusBadRequest)
  49. return
  50. }
  51. // Remove the trailing slash at the end of setting.AppURL, the request
  52. // URI always contains a leading slash, which would result in a double
  53. // slash
  54. target := strings.TrimSuffix(setting.AppURL, "/") + r.URL.RequestURI()
  55. http.Redirect(w, r, target, http.StatusFound)
  56. }