feat: guard certificate orders for custom domains and explain the setup
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 8m21s
ci / lint (pull_request) Successful in 11m0s
ci / build (pull_request) Canceled after 8m49s
ci / image (pull_request) Canceled after 0s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 8m21s
ci / lint (pull_request) Successful in 11m0s
ci / build (pull_request) Canceled after 8m49s
ci / image (pull_request) Canceled after 0s
Status page servers order certificates on demand. Verified domains were already the only ones they would order for, but nothing bounded how many: an organization switching domains, or many organizations at once, could use up the CA's rate limits that all servers sharing an ACME account depend on, and every handshake or request for a made-up name was passed on to the API. - Before a new order (not a renewal) the server asks the API (POST /agent/v1/certificates). It allows verified domains of pages that server serves, within limits per domain and day, per organization and day, and per ACME account owner and hour (UPTIME_CERTS_*), counted across all instances. - An organization can set a new custom domain at most 10 times a day. - The server remembers names without a page for a minute and passes at most 20 unknown names a second on to the API; pages the sync cached are not affected. Only real pages are recorded as visited. - The page editor explains the three steps: the TXT record, the CNAME record with the platform's status page host as its target (or the organization's own servers), apex domains, and when HTTPS follows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
7509b8c429
commit
db36d918fe
18 files changed
+787
-161
No files matched your search
@@ -45,6 +45,15 @@ const (
|
||||
// staleNoticeAfter is when visitors are told the state may be outdated;
|
||||
// a page nobody visited is up to syncInterval old.
|
||||
staleNoticeAfter = 2 * syncInterval
|
||||
// missFor is how long a host or slug without a page is answered
|
||||
// without asking the API again.
|
||||
missFor = time.Minute
|
||||
maxMissing = 10_000
|
||||
// unknownPerSecond bounds the lookups of hosts and slugs that are
|
||||
// neither cached nor known to be missing, so a flood of made-up names
|
||||
// is not passed on to the API. Every page the API lists is cached by
|
||||
// the sync, so known pages are not affected.
|
||||
unknownPerSecond = 20
|
||||
)
|
||||
|
||||
// Source fetches snapshots; *agentapi.Client implements it.
|
||||
@@ -70,8 +79,14 @@ type Server struct {
|
||||
mu sync.Mutex
|
||||
cache map[string]entry
|
||||
refreshing map[string]bool
|
||||
// visited holds when each page was last visited.
|
||||
// visited holds when each cached page was last visited.
|
||||
visited map[string]time.Time
|
||||
// missing holds when a key was last found to have no page.
|
||||
missing map[string]time.Time
|
||||
// unknownSecond and unknownCount count lookups passed on to the API in
|
||||
// the current second.
|
||||
unknownSecond int64
|
||||
unknownCount int
|
||||
// background tracks refreshes started by visits.
|
||||
background sync.WaitGroup
|
||||
}
|
||||
@@ -104,6 +119,7 @@ func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Serve
|
||||
s := &Server{
|
||||
src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir,
|
||||
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, visited: map[string]time.Time{},
|
||||
missing: map[string]time.Time{},
|
||||
}
|
||||
for _, h := range o.Hosts {
|
||||
s.ownHosts[strings.ToLower(h)] = true
|
||||
@@ -167,6 +183,7 @@ func (s *Server) persist(e entry) {
|
||||
func (s *Server) forget(key string) {
|
||||
s.mu.Lock()
|
||||
delete(s.cache, key)
|
||||
delete(s.visited, key)
|
||||
s.mu.Unlock()
|
||||
if s.dir != "" {
|
||||
_ = os.Remove(s.fileFor(key))
|
||||
@@ -321,9 +338,15 @@ func (s *Server) localizeRequest(c *gin.Context) {
|
||||
// lookup answers from the cache whenever possible and refreshes in the
|
||||
// background; only unknown pages wait for the API.
|
||||
func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) {
|
||||
now := s.now()
|
||||
s.mu.Lock()
|
||||
e, cached := s.cache[key]
|
||||
s.visited[key] = s.now()
|
||||
if cached {
|
||||
s.visited[key] = now
|
||||
} else if !s.mayAsk(key, now) {
|
||||
s.mu.Unlock()
|
||||
return entry{}, false
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if cached {
|
||||
if s.now().Sub(e.Fetched) >= freshFor {
|
||||
@@ -331,7 +354,29 @@ func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, boo
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
return s.fetch(ctx, key, host, slug)
|
||||
e, ok := s.fetch(ctx, key, host, slug)
|
||||
if ok {
|
||||
s.mu.Lock()
|
||||
s.visited[key] = now
|
||||
s.mu.Unlock()
|
||||
}
|
||||
return e, ok
|
||||
}
|
||||
|
||||
// mayAsk reports whether an uncached key may be looked up at the API: not
|
||||
// when it was just found missing, nor beyond unknownPerSecond. s.mu is held.
|
||||
func (s *Server) mayAsk(key string, now time.Time) bool {
|
||||
if t, ok := s.missing[key]; ok && now.Sub(t) < missFor {
|
||||
return false
|
||||
}
|
||||
if sec := now.Unix(); sec != s.unknownSecond {
|
||||
s.unknownSecond, s.unknownCount = sec, 0
|
||||
}
|
||||
if s.unknownCount >= unknownPerSecond {
|
||||
return false
|
||||
}
|
||||
s.unknownCount++
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) {
|
||||
@@ -351,6 +396,12 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
|
||||
return old, true
|
||||
case errors.Is(err, agentapi.ErrNotFound):
|
||||
s.forget(key)
|
||||
s.mu.Lock()
|
||||
if len(s.missing) >= maxMissing {
|
||||
clear(s.missing)
|
||||
}
|
||||
s.missing[key] = s.now()
|
||||
s.mu.Unlock()
|
||||
return entry{}, false
|
||||
case err != nil:
|
||||
s.log.WarnContext(ctx, "fetching status page failed", "page", key, "error", err)
|
||||
@@ -362,6 +413,7 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
|
||||
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now(), Checksum: snap.Checksum()}
|
||||
s.mu.Lock()
|
||||
s.cache[key] = e
|
||||
delete(s.missing, key)
|
||||
s.mu.Unlock()
|
||||
s.persist(e)
|
||||
return e, true
|
||||
|
||||
@@ -151,6 +151,40 @@ func (s CertStorage) Unlock(ctx context.Context, name string) error {
|
||||
return s.c.StorageUnlock(ctx, name)
|
||||
}
|
||||
|
||||
// CertificateGate is asked before a new certificate is ordered;
|
||||
// *agentapi.Client implements it.
|
||||
type CertificateGate interface {
|
||||
AllowCertificate(ctx context.Context, name string) error
|
||||
}
|
||||
|
||||
// OnCertEvent is certmagic's event hook. Before a new certificate for a
|
||||
// custom domain is ordered it asks the API, which allows verified domains
|
||||
// of pages this server serves within limits shared by all servers; that
|
||||
// keeps the CA's rate limits from being used up. Renewals and the default
|
||||
// hosts are not asked about.
|
||||
func (s *Server) OnCertEvent(ctx context.Context, event string, data map[string]any) error {
|
||||
if event != "cert_obtaining" || data["renewal"] == true {
|
||||
return nil
|
||||
}
|
||||
name, _ := data["identifier"].(string)
|
||||
host := hostOnly(name)
|
||||
gate, ok := s.src.(CertificateGate)
|
||||
if s.ownHosts[host] || !ok {
|
||||
return nil
|
||||
}
|
||||
switch err := gate.AllowCertificate(ctx, host); {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, agentapi.ErrRateLimited):
|
||||
s.log.WarnContext(ctx, "certificate order refused: limit reached", "domain", host)
|
||||
return fmt.Errorf("limit on new certificates reached for %s", host)
|
||||
case errors.Is(err, agentapi.ErrNotFound):
|
||||
return fmt.Errorf("no status page for %s", host)
|
||||
default:
|
||||
return fmt.Errorf("asking whether to order a certificate for %s: %w", host, err)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package statuspage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
)
|
||||
|
||||
func (f *fakeSource) callCount() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.calls
|
||||
}
|
||||
|
||||
func TestUnknownNamesAreNotAskedAgainAtOnce(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, "", &now)
|
||||
for range 3 {
|
||||
if code, _ := h.get("nope.example.test", "/"); code != http.StatusNotFound {
|
||||
t.Fatalf("unknown host = %d, want 404", code)
|
||||
}
|
||||
}
|
||||
if n := src.callCount(); n != 1 {
|
||||
t.Errorf("the API was asked %d times about one unknown host, want 1", n)
|
||||
}
|
||||
now = now.Add(missFor)
|
||||
h.get("nope.example.test", "/")
|
||||
if n := src.callCount(); n != 2 {
|
||||
t.Errorf("after %v the API was asked %d times in all, want 2", missFor, n)
|
||||
}
|
||||
h.srv.mu.Lock()
|
||||
visited := len(h.srv.visited)
|
||||
h.srv.mu.Unlock()
|
||||
if visited != 0 {
|
||||
t.Errorf("unknown hosts were recorded as visited pages: %d", visited)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFloodOfMadeUpNamesIsThrottled(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, "", &now)
|
||||
h.srv.Sync(context.Background())
|
||||
before := src.callCount()
|
||||
for i := range 200 {
|
||||
h.get(fmt.Sprintf("x%d.example.test", i), "/")
|
||||
}
|
||||
if n := src.callCount() - before; n > unknownPerSecond {
|
||||
t.Errorf("a flood of made-up hosts reached the API %d times in one second, want at most %d", n, unknownPerSecond)
|
||||
}
|
||||
// Pages the sync cached are still served during the flood.
|
||||
if code, _ := h.get("status.acme.test", "/"); code != http.StatusOK {
|
||||
t.Errorf("a known page during the flood = %d, want 200", code)
|
||||
}
|
||||
now = now.Add(time.Second)
|
||||
if err := h.srv.AllowCertificate(context.Background(), "status.acme.test"); err != nil {
|
||||
t.Errorf("a known custom domain after the flood: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type gatedSource struct {
|
||||
*fakeSource
|
||||
asked []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (g *gatedSource) AllowCertificate(_ context.Context, name string) error {
|
||||
g.asked = append(g.asked, name)
|
||||
return g.err
|
||||
}
|
||||
|
||||
func TestNewCertificatesAreOrderedOnlyWhenTheAPIAllows(t *testing.T) {
|
||||
now := time.Now()
|
||||
g := &gatedSource{fakeSource: newSource()}
|
||||
h := newHarness(t, g.fakeSource, "", &now)
|
||||
h.srv.src = g
|
||||
ctx := context.Background()
|
||||
obtain := func(name string, renewal bool) error {
|
||||
data := map[string]any{"identifier": name}
|
||||
if renewal {
|
||||
data["renewal"] = true
|
||||
}
|
||||
return h.srv.OnCertEvent(ctx, "cert_obtaining", data)
|
||||
}
|
||||
|
||||
if err := obtain("status.acme.test", false); err != nil {
|
||||
t.Errorf("allowed order: %v", err)
|
||||
}
|
||||
// Renewals, the default hosts and other events are not asked about.
|
||||
if err := obtain("status.acme.test", true); err != nil {
|
||||
t.Errorf("renewal: %v", err)
|
||||
}
|
||||
if err := obtain("status.example.test", false); err != nil {
|
||||
t.Errorf("default host: %v", err)
|
||||
}
|
||||
if err := h.srv.OnCertEvent(ctx, "cert_obtained", map[string]any{"identifier": "status.acme.test"}); err != nil {
|
||||
t.Errorf("other event: %v", err)
|
||||
}
|
||||
if len(g.asked) != 1 || g.asked[0] != "status.acme.test" {
|
||||
t.Errorf("asked about %v, want only the new order", g.asked)
|
||||
}
|
||||
|
||||
for _, refuse := range []error{agentapi.ErrRateLimited, agentapi.ErrNotFound, errors.New("api down")} {
|
||||
g.err = refuse
|
||||
if err := obtain("status.acme.test", false); err == nil {
|
||||
t.Errorf("order went ahead although the API answered %v", refuse)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user