From 4d1db0943e375b1e31bb1f9e97211fc54ded949a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 08:54:08 +0100 Subject: [PATCH] feat(statuspage): obtain tls certificates on demand for custom domains With UPTIME_STATUSPAGE_TLS the server serves HTTPS with ACME certificates for its hosts and for verified custom domains of pages it may serve, shared by all instances through the API. Plain HTTP answers ACME challenges and health checks and redirects everything else. Closes #22 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .env.example | 7 ++ cmd/statuspage/main.go | 67 ++++++++++++++++++- go.mod | 10 ++- go.sum | 30 ++++++++- internal/api/statuspages_test.go | 26 +++++--- internal/config/config.go | 8 +++ internal/platform/server.go | 13 +++- internal/statuspage/tls.go | 111 +++++++++++++++++++++++++++++++ 8 files changed, 255 insertions(+), 17 deletions(-) create mode 100644 internal/statuspage/tls.go diff --git a/.env.example b/.env.example index 4721dac..6c27465 100644 --- a/.env.example +++ b/.env.example @@ -22,3 +22,10 @@ UPTIME_API_URL=http://localhost:8080 # Integration tests (make test). The Redis database is flushed by the tests. UPTIME_TEST_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime_test?sslmode=disable UPTIME_TEST_REDIS_URL=redis://localhost:6379/15 + +# Status page server: hosts serving pages by slug; enable TLS for custom domains. +UPTIME_STATUSPAGE_URL=http://localhost:8082 +UPTIME_STATUSPAGE_HOSTS=localhost +# UPTIME_STATUSPAGE_TLS=true +# UPTIME_ACME_EMAIL=ops@example.com +# UPTIME_ACME_CA=https://acme-staging-v02.api.letsencrypt.org/directory diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index 149838e..e8f5ee0 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -4,12 +4,18 @@ package main import ( "context" + "crypto/tls" + "errors" "fmt" "log/slog" + "net" + "net/http" "os" "time" + "github.com/caddyserver/certmagic" "github.com/google/uuid" + "go.uber.org/zap" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" @@ -61,7 +67,64 @@ func run(log *slog.Logger, level *slog.LevelVar) error { r := platform.NewRouter(log) health.Register(r) r.StaticFS("/static", web.Static()) - statuspage.New(client, catalog, log, cfg.Hosts).Mount(r) + pages := statuspage.New(client, catalog, log, cfg.Hosts) + pages.Mount(r) - return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) + if !cfg.TLS { + return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) + } + tlsConfig, challenges, err := certificates(ctx, cfg, client, pages, log) + if err != nil { + return err + } + https := platform.NewHTTPServer(cfg.TLSListen, r) + https.TLSConfig = tlsConfig + plain := platform.NewHTTPServer(cfg.Listen, challenges(redirectToHTTPS(r))) + + errs := make(chan error, 2) + go func() { errs <- platform.Serve(ctx, log, plain, health, 5*time.Second, cfg.ShutdownTimeout) }() + go func() { errs <- platform.ServeTLS(ctx, log, https, health, 5*time.Second, cfg.ShutdownTimeout) }() + err = <-errs + stop() + return errors.Join(err, <-errs) +} + +// certificates sets up on-demand ACME certificates stored through the API, +// shared by every instance of this status page server. +func certificates(ctx context.Context, cfg config.StatusPage, client *agentapi.Client, pages *statuspage.Server, log *slog.Logger) (*tls.Config, func(http.Handler) http.Handler, error) { + var magic *certmagic.Config + cache := certmagic.NewCache(certmagic.CacheOptions{ + GetConfigForCert: func(certmagic.Certificate) (*certmagic.Config, error) { return magic, nil }, + }) + magic = certmagic.New(cache, certmagic.Config{ + Storage: statuspage.NewCertStorage(client), + OnDemand: &certmagic.OnDemandConfig{DecisionFunc: pages.AllowCertificate}, + Logger: zap.NewNop(), + }) + issuer := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{CA: cfg.ACMECA, Email: cfg.ACMEEmail, Agreed: true}) + magic.Issuers = []certmagic.Issuer{issuer} + go func() { + <-ctx.Done() + cache.Stop() + }() + tc := magic.TLSConfig() + tc.NextProtos = append([]string{"h2", "http/1.1"}, tc.NextProtos...) + log.Info("tls enabled", "ca", cfg.ACMECA, "listen", cfg.TLSListen) + return tc, issuer.HTTPChallengeHandler, nil +} + +// redirectToHTTPS sends page requests to HTTPS but keeps health checks on +// plain HTTP for load balancers and orchestrators. +func redirectToHTTPS(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/healthz" || r.URL.Path == "/readyz" { + next.ServeHTTP(w, r) + return + } + host, _, err := net.SplitHostPort(r.Host) + if err != nil { + host = r.Host + } + http.Redirect(w, r, "https://"+host+r.URL.RequestURI(), http.StatusMovedPermanently) + }) } diff --git a/go.mod b/go.mod index c932653..e9df13b 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.27.1 require ( github.com/a-h/templ v0.3.1118 github.com/caarlos0/env/v11 v11.4.2 + github.com/caddyserver/certmagic v0.25.6 github.com/coreos/go-oidc/v3 v3.21.0 github.com/gin-gonic/gin v1.12.0 github.com/go-jose/go-jose/v4 v4.1.4 @@ -15,7 +16,9 @@ require ( github.com/pquerna/otp v1.5.0 github.com/pressly/goose/v3 v3.30.1 github.com/redis/go-redis/v9 v9.23.0 + go.uber.org/zap v1.28.0 golang.org/x/crypto v0.59.0 + golang.org/x/net v0.63.0 golang.org/x/oauth2 v0.38.0 golang.org/x/text v0.44.0 ) @@ -27,6 +30,7 @@ require ( github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/caddyserver/zerossl v0.1.6 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cli/browser v1.3.0 // indirect @@ -45,9 +49,12 @@ require ( github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.4.0 // indirect github.com/leodido/go-urn v1.5.0 // indirect + github.com/libdns/libdns v1.1.1 // indirect github.com/mattn/go-colorable v0.1.16 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/mfridman/interpolate v0.2.0 // indirect + github.com/mholt/acmez/v3 v3.1.7 // indirect + github.com/miekg/dns v1.1.73 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/atomic v1.0.1 // indirect @@ -57,12 +64,13 @@ require ( github.com/sethvargo/go-retry v0.5.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.1 // indirect + github.com/zeebo/blake3 v0.2.4 // indirect go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap/exp v0.3.0 // indirect golang.org/x/arch v0.22.0 // indirect golang.org/x/mod v0.43.0 // indirect - golang.org/x/net v0.63.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect golang.org/x/tools v0.52.0 // indirect diff --git a/go.sum b/go.sum index 21e3652..4c4b8e9 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE= +code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ= @@ -20,6 +22,10 @@ github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiD github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= github.com/caarlos0/env/v11 v11.4.2 h1:fosEVW/SjFBBzATf+buI6vsAfOzXxPrchST/RNzmBWQ= github.com/caarlos0/env/v11 v11.4.2/go.mod h1:sH0CUPGS25jkIKlk2q4qs0c+C7y++K7W3crU70JVB/k= +github.com/caddyserver/certmagic v0.25.6 h1:vHMtFSLKTa6kuZz6w0SnRMpQ388tSkww8ye355BgAM4= +github.com/caddyserver/certmagic v0.25.6/go.mod h1:xq6cRNimqW+Tv91XNc5lNHs2XYTsLhQhYiH01H4AySs= +github.com/caddyserver/zerossl v0.1.6 h1:1yrhTx5DWi43wOJPQ+Y4mVl++EPmSqqT/4REW//lsas= +github.com/caddyserver/zerossl v0.1.6/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= @@ -78,12 +84,22 @@ github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV91 github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= +github.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU= +github.com/letsencrypt/challtestsrv v1.4.2/go.mod h1:GhqMqcSoeGpYd5zX5TgwA6er/1MbWzx/o7yuuVya+Wk= +github.com/letsencrypt/pebble/v2 v2.10.1 h1:oKHx3lgN4e5Nno2LKTMrVx+b+NkDptkO9aDireiBDGE= +github.com/letsencrypt/pebble/v2 v2.10.1/go.mod h1:KtYhQ4YTjT5MtoCZ6RTCXlbrrz6cKyXROCuTpIUDJFY= +github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U= +github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ= github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A= github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg= github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q= +github.com/mholt/acmez/v3 v3.1.7 h1:XTqpuUcRdRoIBuDoI+M4mCnRnPTPN4rqH3Mb723Rg4U= +github.com/mholt/acmez/v3 v3.1.7/go.mod h1:Lwv6P/czh/AOq+c99tAzP68/VP92s+8y+hDs4FCgxvo= +github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= +github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -130,16 +146,28 @@ github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= +github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI= +github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE= +github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo= +github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4= github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= +go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= +go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U= +go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ= go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= @@ -148,8 +176,6 @@ golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= -golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= -golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI= diff --git a/internal/api/statuspages_test.go b/internal/api/statuspages_test.go index 76085ec..b3a64b1 100644 --- a/internal/api/statuspages_test.go +++ b/internal/api/statuspages_test.go @@ -143,16 +143,7 @@ func TestStatusPages(t *testing.T) { if _, err := platform.Page(context.Background(), domain, ""); !errors.Is(err, agentapi.ErrNotFound) { t.Errorf("Page(unverified domain) error = %v, want not found", err) } - saved := *api.LookupTXT - t.Cleanup(func() { *api.LookupTXT = saved }) - *api.LookupTXT = func(_ context.Context, name string) ([]string, error) { - if name == record["name"] { - return []string{"something else", record["value"].(string)}, nil - } - return nil, errors.New("no such record") - } - st, body = owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/domain/verify", nil) - expect(t, "verify domain", st, body, http.StatusNoContent, "") + verifyDomain(t, owner, pageID, record) if snap, err := platform.Page(context.Background(), domain, ""); err != nil || snap.Title != "Acme Status" { t.Errorf("Page(verified domain) = %v, %v", snap.Title, err) } @@ -203,3 +194,18 @@ func editorEmail(b *browser) string { _, me := b.do("GET", "/api/v1/me", nil) return me["email"].(string) } + +// verifyDomain answers the TXT lookup with record and verifies the domain. +func verifyDomain(t *testing.T, owner *browser, pageID string, record map[string]any) { + t.Helper() + saved := *api.LookupTXT + t.Cleanup(func() { *api.LookupTXT = saved }) + *api.LookupTXT = func(_ context.Context, name string) ([]string, error) { + if name == record["name"] { + return []string{"something else", record["value"].(string)}, nil + } + return nil, errors.New("no such record") + } + st, body := owner.do("POST", "/api/v1/org/statuspages/"+pageID+"/domain/verify", nil) + expect(t, "verify domain", st, body, http.StatusNoContent, "") +} diff --git a/internal/config/config.go b/internal/config/config.go index 6dd7c43..325b027 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -147,6 +147,14 @@ type StatusPage struct { // Hosts are the host names that serve pages by slug, e.g. // status.example.com. Any other host is treated as a custom domain. Hosts []string `env:"UPTIME_STATUSPAGE_HOSTS" envSeparator:"," envDefault:"localhost"` + // TLS obtains certificates via ACME for the hosts and verified custom + // domains and serves HTTPS on TLSListen; Listen then answers ACME HTTP + // challenges and redirects to HTTPS. + TLS bool `env:"UPTIME_STATUSPAGE_TLS"` + TLSListen string `env:"UPTIME_STATUSPAGE_TLS_LISTEN" envDefault:":443"` + ACMEEmail string `env:"UPTIME_ACME_EMAIL"` + // ACMECA defaults to Let's Encrypt; use its staging URL for testing. + ACMECA string `env:"UPTIME_ACME_CA" envDefault:"https://acme-v02.api.letsencrypt.org/directory"` } // Load parses the environment into a T, applying envDefault tags. diff --git a/internal/platform/server.go b/internal/platform/server.go index 9d3fb01..6687bbe 100644 --- a/internal/platform/server.go +++ b/internal/platform/server.go @@ -11,10 +11,19 @@ import ( // Serve blocks until ctx is cancelled, then marks the instance as draining, // waits drainDelay for load balancers to notice and shuts down gracefully. func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Health, drainDelay, timeout time.Duration) error { + return serve(ctx, log, srv, health, drainDelay, timeout, srv.ListenAndServe) +} + +// ServeTLS is Serve for a server whose TLSConfig provides certificates. +func ServeTLS(ctx context.Context, log *slog.Logger, srv *http.Server, health *Health, drainDelay, timeout time.Duration) error { + return serve(ctx, log, srv, health, drainDelay, timeout, func() error { return srv.ListenAndServeTLS("", "") }) +} + +func serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Health, drainDelay, timeout time.Duration, listen func() error) error { errc := make(chan error, 1) go func() { - log.Info("http listening", "addr", srv.Addr) - if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Info("http listening", "addr", srv.Addr, "tls", srv.TLSConfig != nil) + if err := listen(); err != nil && !errors.Is(err, http.ErrServerClosed) { errc <- err } close(errc) diff --git a/internal/statuspage/tls.go b/internal/statuspage/tls.go new file mode 100644 index 0000000..f5716f0 --- /dev/null +++ b/internal/statuspage/tls.go @@ -0,0 +1,111 @@ +package statuspage + +import ( + "context" + "errors" + "fmt" + "io/fs" + "time" + + "github.com/caddyserver/certmagic" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" +) + +// CertStorage keeps certmagic's certificates and locks in the API, so every +// instance of a status page server shares them without a database. +type CertStorage struct { + c *agentapi.Client +} + +var _ certmagic.Storage = CertStorage{} + +// NewCertStorage returns storage backed by c. +func NewCertStorage(c *agentapi.Client) CertStorage { return CertStorage{c: c} } + +func notExist(err error) error { + if errors.Is(err, agentapi.ErrNotFound) { + return fs.ErrNotExist + } + return err +} + +// Store implements certmagic.Storage. +func (s CertStorage) Store(ctx context.Context, key string, value []byte) error { + return s.c.StoragePut(ctx, key, value) +} + +// Load implements certmagic.Storage. +func (s CertStorage) Load(ctx context.Context, key string) ([]byte, error) { + v, err := s.c.StorageGet(ctx, key) + return v, notExist(err) +} + +// Delete implements certmagic.Storage. +func (s CertStorage) Delete(ctx context.Context, key string) error { + return notExist(s.c.StorageDelete(ctx, key)) +} + +// Exists implements certmagic.Storage. +func (s CertStorage) Exists(ctx context.Context, key string) bool { + _, err := s.c.StorageStat(ctx, key) + return err == nil +} + +// List implements certmagic.Storage. +func (s CertStorage) List(ctx context.Context, path string, recursive bool) ([]string, error) { + keys, err := s.c.StorageList(ctx, path, recursive) + if err == nil && len(keys) == 0 { + return nil, fs.ErrNotExist + } + return keys, err +} + +// Stat implements certmagic.Storage. +func (s CertStorage) Stat(ctx context.Context, key string) (certmagic.KeyInfo, error) { + info, err := s.c.StorageStat(ctx, key) + if err != nil { + return certmagic.KeyInfo{}, notExist(err) + } + return certmagic.KeyInfo{Key: info.Key, Modified: info.Modified, Size: info.Size, IsTerminal: info.IsTerminal}, nil +} + +// Lock implements certmagic.Locker. It blocks until the lock is free or ctx +// ends; locks expire on the API side if their holder dies. +func (s CertStorage) Lock(ctx context.Context, name string) error { + wait := 200 * time.Millisecond + for { + err := s.c.StorageLock(ctx, name) + if err == nil { + return nil + } + if !errors.Is(err, agentapi.ErrLocked) { + return err + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(wait): + } + wait = min(wait*2, 5*time.Second) + } +} + +// Unlock implements certmagic.Locker. +func (s CertStorage) Unlock(ctx context.Context, name string) error { + return s.c.StorageUnlock(ctx, name) +} + +// AllowCertificate decides whether to obtain a certificate for name on +// demand: only for the default hosts and for verified custom domains of +// pages this server may serve. Anything else would let strangers make us +// request certificates for arbitrary names. +func (s *Server) AllowCertificate(ctx context.Context, name string) error { + if s.ownHosts[hostOnly(name)] { + return nil + } + if _, err := s.src.Page(ctx, hostOnly(name), ""); err != nil { + return fmt.Errorf("no status page for %s: %w", name, err) + } + return nil +}