Files
uptimesebi/internal/statuspage/tls.go
T
Sebastian UnterschützandClaude Opus 5.5 db36d918fe
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
feat: guard certificate orders for custom domains and explain the setup
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
2026-11-25 22:39:01 +01:00

205 lines
6.1 KiB
Go

package statuspage
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"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. Values
// are mirrored to a local directory and read from there when the API is
// unreachable, so HTTPS keeps working after a restart during an outage.
type CertStorage struct {
c *agentapi.Client
dir string
}
var _ certmagic.Storage = CertStorage{}
// NewCertStorage returns storage backed by c, mirrored to dir unless dir is
// empty.
func NewCertStorage(c *agentapi.Client, dir string) CertStorage { return CertStorage{c: c, dir: dir} }
// local maps a storage key to a file below dir. Keys come from certmagic,
// but are cleaned anyway so they cannot point outside dir.
func (s CertStorage) local(key string) string {
if s.dir == "" {
return ""
}
clean := filepath.Clean("/" + key)
return filepath.Join(s.dir, filepath.FromSlash(clean))
}
func (s CertStorage) mirror(key string, value []byte) {
if p := s.local(key); p != "" {
if os.MkdirAll(filepath.Dir(p), 0o700) == nil {
_ = os.WriteFile(p, value, 0o600)
}
}
}
// unreachable reports errors that mean the API could not answer, as
// opposed to answers such as "not found".
func unreachable(err error) bool {
return err != nil && !errors.Is(err, agentapi.ErrNotFound) && !errors.Is(err, agentapi.ErrLocked)
}
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 {
if err := s.c.StoragePut(ctx, key, value); err != nil {
return err
}
s.mirror(key, value)
return nil
}
// Load implements certmagic.Storage.
func (s CertStorage) Load(ctx context.Context, key string) ([]byte, error) {
v, err := s.c.StorageGet(ctx, key)
switch {
case err == nil:
s.mirror(key, v)
return v, nil
case unreachable(err) && s.local(key) != "":
if local, lerr := os.ReadFile(s.local(key)); lerr == nil {
return local, nil
}
}
return nil, notExist(err)
}
// Delete implements certmagic.Storage.
func (s CertStorage) Delete(ctx context.Context, key string) error {
if p := s.local(key); p != "" {
_ = os.RemoveAll(p)
}
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)
if unreachable(err) && s.local(key) != "" {
_, lerr := os.Stat(s.local(key))
return lerr == nil
}
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 unreachable(err) && s.local(key) != "" {
if fi, lerr := os.Stat(s.local(key)); lerr == nil {
return certmagic.KeyInfo{Key: key, Modified: fi.ModTime(), Size: fi.Size(), IsTerminal: !fi.IsDir()}, nil
}
}
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)
}
// 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
// request certificates for arbitrary names.
//
// Names with a cached page are allowed without asking the API, so existing
// certificates can be loaded after a restart while the API is down.
func (s *Server) AllowCertificate(ctx context.Context, name string) error {
host := hostOnly(name)
if s.ownHosts[host] {
return nil
}
if _, ok := s.lookup(ctx, "host:"+host, host, ""); !ok {
return fmt.Errorf("no status page for %s", name)
}
return nil
}