about summary refs log tree commit diff stats
path: root/internal
diff options
context:
space:
mode:
Diffstat (limited to 'internal')
-rw-r--r--internal/config/config.go3
-rw-r--r--internal/server/server.go32
-rw-r--r--internal/server/tls.go39
-rw-r--r--internal/vcs/repository.go34
4 files changed, 83 insertions, 25 deletions
diff --git a/internal/config/config.go b/internal/config/config.go
index 47d5de8..7ccad85 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -42,7 +42,8 @@ type Config struct {
 	OriginalDomain   string `toml:"original_domain"`
 	GoatCounter      URL    `toml:"goatcounter"`
 	Domains          []string
-	OIDCHost         URL `toml:"oidc_host"`
+	WildcardDomain   string `toml:"wildcard_domain"`
+	OIDCHost         URL    `toml:"oidc_host"`
 	Taxonomies       []Taxonomy
 	CSP              *CSP `toml:"content-security-policy"`
 	Extra            struct {
diff --git a/internal/server/server.go b/internal/server/server.go
index b174c0c..269ed9e 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -8,6 +8,7 @@ import (
 	"net/url"
 	"os"
 	"path/filepath"
+	"regexp"
 	"slices"
 	"strconv"
 	"strings"
@@ -74,7 +75,6 @@ func applyDevModeOverrides(config *cfg.Config, runtimeConfig *Config) {
 }
 
 func updateCSPHashes(config *cfg.Config, r *builder.Result) {
-	clear(config.CSP.StyleSrc)
 	for i, h := range r.Hashes {
 		config.CSP.StyleSrc[i] = fmt.Sprintf("'%s'", h)
 	}
@@ -184,21 +184,35 @@ func New(runtimeConfig *Config, log *log.Logger) (*Server, error) {
 	}
 
 	if runtimeConfig.Redirect {
+		re := regexp.MustCompile(
+			"^(.*)\\." + strings.ReplaceAll(config.WildcardDomain, ".", `\.`) + "$",
+		)
+		replace := "${1}." + config.Domains[0]
 		loggingMux.Handle(config.BaseURL.Hostname()+"/", mux)
 		loggingMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
-			path, _ := website.CanonicalisePath(r.URL.Path)
-			newURL := config.BaseURL.JoinPath(path)
-			http.Redirect(w, r, newURL.String(), http.StatusMovedPermanently)
+			if slices.Contains(config.Domains, r.Host) {
+				path, _ := website.CanonicalisePath(r.URL.Path)
+				newURL := config.BaseURL.JoinPath(path)
+				http.Redirect(w, r, newURL.String(), http.StatusMovedPermanently)
+			} else {
+				url := config.BaseURL
+				url.Host = re.ReplaceAllString(r.Host, replace)
+				http.Redirect(w, r, url.String(), http.StatusTemporaryRedirect)
+			}
 		})
 	} else {
 		loggingMux.Handle("/", mux)
 	}
 
-	top.Handle("/",
-		serverHeaderHandler(
-			wrapHandlerWithLogging(loggingMux, log),
-		),
-	)
+	if runtimeConfig.Development {
+		top.Handle("/",
+			serverHeaderHandler(
+				wrapHandlerWithLogging(loggingMux, log),
+			),
+		)
+	} else {
+		top.Handle("/", serverHeaderHandler(loggingMux))
+	}
 
 	top.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
 		w.WriteHeader(http.StatusNoContent)
diff --git a/internal/server/tls.go b/internal/server/tls.go
index 9481b6a..4d52b8d 100644
--- a/internal/server/tls.go
+++ b/internal/server/tls.go
@@ -12,6 +12,7 @@ import (
 	"github.com/ardanlabs/conf/v3"
 	"github.com/caddyserver/caddy/v2"
 	"github.com/caddyserver/certmagic"
+	"github.com/libdns/acmedns"
 	certmagic_redis "github.com/pberkel/caddy-storage-redis"
 	"gitlab.com/tozd/go/errors"
 )
@@ -24,6 +25,13 @@ type redisConfig struct {
 	KeyPrefix     string `conf:"default:certmagic"`
 }
 
+type acmeConfig struct {
+	Username  string `conf:"required"`
+	Password  string `conf:"required"`
+	Subdomain string `conf:"required"`
+	ServerURL string `conf:"env:SERVER_URL,default:https://acme.alanpearce.eu"`
+}
+
 func (s *Server) serveTLS() (err error) {
 	log := s.log.Named("tls")
 
@@ -32,10 +40,7 @@ func (s *Server) serveTLS() (err error) {
 	cfg := certmagic.NewDefault()
 	cfg.DefaultServerName = s.config.Domains[0]
 
-	issuer := &certmagic.DefaultACME
-	certmagic.DefaultACME.Agreed = true
-	certmagic.DefaultACME.Email = s.config.Email
-	certmagic.DefaultACME.Logger = certmagic.Default.Logger
+	var issuer *certmagic.ACMEIssuer
 
 	if s.runtimeConfig.Development {
 		ca := s.runtimeConfig.ACMECA
@@ -63,8 +68,8 @@ func (s *Server) serveTLS() (err error) {
 			ListenHost:              s.runtimeConfig.ListenAddress,
 			AltHTTPPort:             s.runtimeConfig.Port,
 			AltTLSALPNPort:          s.runtimeConfig.TLSPort,
+			Logger:                  certmagic.Default.Logger,
 		})
-		cfg.Issuers[0] = issuer
 	} else {
 		rc := &redisConfig{}
 		_, err = conf.Parse("REDIS", rc)
@@ -72,6 +77,27 @@ func (s *Server) serveTLS() (err error) {
 			return errors.Wrap(err, "could not parse redis config")
 		}
 
+		acme := &acmedns.Provider{}
+		_, err = conf.Parse("ACME", acme)
+		if err != nil {
+			return errors.Wrap(err, "could not parse ACME config")
+		}
+
+		issuer = certmagic.NewACMEIssuer(cfg, certmagic.ACMEIssuer{
+			CA:     certmagic.LetsEncryptProductionCA,
+			Email:  s.config.Email,
+			Agreed: true,
+			Logger: certmagic.Default.Logger,
+			DNS01Solver: &certmagic.DNS01Solver{
+				DNSManager: certmagic.DNSManager{
+					DNSProvider: acme,
+					Logger:      certmagic.Default.Logger,
+				},
+			},
+		})
+
+		log.Info("acme", "username", acme.Username, "subdomain", acme.Subdomain, "server_url", acme.ServerURL)
+
 		rs := certmagic_redis.New()
 		rs.Address = []string{rc.Address}
 		rs.Username = rc.Username
@@ -87,6 +113,7 @@ func (s *Server) serveTLS() (err error) {
 			return errors.Wrap(err, "could not provision redis storage")
 		}
 	}
+	cfg.Issuers[0] = issuer
 
 	ln, err := listenfd.GetListener(
 		1,
@@ -137,7 +164,7 @@ func (s *Server) serveTLS() (err error) {
 		"https_port",
 		s.runtimeConfig.TLSPort,
 	)
-	err = cfg.ManageSync(context.TODO(), s.config.Domains)
+	err = cfg.ManageAsync(context.TODO(), s.config.Domains)
 	if err != nil {
 		return errors.Wrap(err, "could not enable TLS")
 	}
diff --git a/internal/vcs/repository.go b/internal/vcs/repository.go
index e034ea4..5950e53 100644
--- a/internal/vcs/repository.go
+++ b/internal/vcs/repository.go
@@ -7,6 +7,7 @@ import (
 	"go.alanpearce.eu/x/log"
 
 	"github.com/go-git/go-git/v5"
+	"github.com/go-git/go-git/v5/plumbing"
 	"gitlab.com/tozd/go/errors"
 )
 
@@ -61,13 +62,8 @@ func (r *Repository) Update() (bool, error) {
 	}
 
 	r.log.Info("updating from", "rev", head.Hash().String())
-	wt, err := r.repo.Worktree()
-	if err != nil {
-		return false, err
-	}
-	err = wt.Pull(&git.PullOptions{
-		SingleBranch: true,
-		Force:        true,
+	err = r.repo.Fetch(&git.FetchOptions{
+		Prune: true,
 	})
 	if err != nil {
 		if errors.Is(err, git.NoErrAlreadyUpToDate) {
@@ -79,11 +75,31 @@ func (r *Repository) Update() (bool, error) {
 		return false, err
 	}
 
-	head, err = r.repo.Head()
+	rem, err := r.repo.Remote("origin")
 	if err != nil {
 		return false, err
 	}
-	r.log.Info("updated to", "rev", head.Hash().String())
+	refs, err := rem.List(&git.ListOptions{
+		Timeout: 5,
+	})
+
+	var hash plumbing.Hash
+	for _, ref := range refs {
+		if ref.Name() == plumbing.Main {
+			hash = ref.Hash()
+		}
+	}
+
+	wt, err := r.repo.Worktree()
+	if err != nil {
+		return false, err
+	}
+	wt.Checkout(&git.CheckoutOptions{
+		Hash:  hash,
+		Force: true,
+	})
+
+	r.log.Info("updated to", "rev", hash)
 
 	return true, r.Clean(wt)
 }