Files
uptimesebi/internal/config/config.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

259 lines
10 KiB
Go

// Package config reads component settings from UPTIME_* environment
// variables.
package config
import (
"fmt"
"log/slog"
"net/url"
"strings"
"time"
"github.com/caarlos0/env/v11"
)
// Edition switches features that only make sense when we operate the
// service, such as billing.
type Edition string
// Editions.
const (
EditionCloud Edition = "cloud"
EditionSelfHosted Edition = "selfhosted"
)
// Common holds settings shared by all components.
type Common struct {
Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"`
LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"`
ShutdownTimeout time.Duration `env:"UPTIME_SHUTDOWN_TIMEOUT" envDefault:"20s"`
// TrustedProxies are addresses or CIDRs of reverse proxies whose
// X-Forwarded-For is believed. Client addresses feed rate limits and
// the audit log, so the default trusts no proxy.
TrustedProxies []string `env:"UPTIME_TRUSTED_PROXIES" envSeparator:","`
}
// Storage locates Postgres and Redis. Only the API connects to them; every
// other component goes through the API.
type Storage struct {
DatabaseURL string `env:"UPTIME_DATABASE_URL"`
RedisURL string `env:"UPTIME_REDIS_URL"`
RedisSentinel Sentinel
}
// Agent configures how checkers and status page servers reach the API.
type Agent struct {
APIURL string `env:"UPTIME_API_URL,required,notEmpty"`
Token string `env:"UPTIME_AGENT_TOKEN,required,notEmpty"`
}
// Sentinel switches the redis client to failover mode. UPTIME_REDIS_URL then
// only contributes credentials, db and TLS for the master; its host is ignored.
type Sentinel struct {
Master string `env:"UPTIME_REDIS_SENTINEL_MASTER"`
Addrs []string `env:"UPTIME_REDIS_SENTINEL_ADDRS" envSeparator:","`
Username string `env:"UPTIME_REDIS_SENTINEL_USERNAME"`
Password string `env:"UPTIME_REDIS_SENTINEL_PASSWORD"`
}
// Enabled reports whether a sentinel master name is configured.
func (s Sentinel) Enabled() bool { return s.Master != "" }
// SignupMode controls who may create an account and organization.
type SignupMode string
// Signup modes. SignupFirstUser allows exactly one account, the operator of a
// fresh self-hosted installation.
const (
SignupOpen SignupMode = "open"
SignupFirstUser SignupMode = "first-user"
SignupClosed SignupMode = "closed"
)
// API configures cmd/api.
type API struct {
Common
Storage
Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"`
SecretKeys string `env:"UPTIME_SECRET_KEYS"`
Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"`
// SignupVerify is "auto", "required" or "off": whether new accounts
// confirm their email address before signing in. Auto requires it in
// the cloud edition and wherever mail can be sent.
SignupVerify string `env:"UPTIME_SIGNUP_VERIFY" envDefault:"auto"`
// SignupsPerIP limits sign-ups per client address (IPv6: per /64) in
// 24 hours; 0 means unlimited.
SignupsPerIP int `env:"UPTIME_SIGNUPS_PER_IP" envDefault:"2"`
SessionIdle time.Duration `env:"UPTIME_SESSION_IDLE" envDefault:"168h"`
SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"`
// PublicURL is the externally reachable base URL, used for SSO callbacks.
PublicURL string `env:"UPTIME_PUBLIC_URL" envDefault:"http://localhost:8080"`
// SSOPrivateNetworks is "auto", "true" or "false". Auto allows
// organizations' IdPs on private networks only in the self-hosted edition.
SSOPrivateNetworks string `env:"UPTIME_SSO_ALLOW_PRIVATE_NETWORKS" envDefault:"auto"`
// SMTPURL configures outgoing mail for email notification channels,
// e.g. smtp://user:pass@host:587?from=alerts@example.com. Empty disables
// email channels.
SMTPURL string `env:"UPTIME_SMTP_URL"`
// StatusPageURL is where the platform's status page servers are
// reachable; the console links pages as <StatusPageURL>/<slug>.
StatusPageURL string `env:"UPTIME_STATUSPAGE_URL" envDefault:"http://localhost:8082"`
// AgentImage is the image name agents are installed and updated from;
// "-checker" or "-statuspage" is appended. Change it for a mirror.
AgentImage string `env:"UPTIME_AGENT_IMAGE" envDefault:"git.zb-server.de/zb-server/uptimesebi"`
// RegionAlertAfter is how long a region with monitors may have no live
// checker before its admins or owners are told; 0 disables it.
RegionAlertAfter time.Duration `env:"UPTIME_REGION_ALERT_AFTER" envDefault:"5m"`
// Certificates bounds the certificates status page servers may order
// for custom domains.
Certificates Certificates
Retention Retention
}
// Certificates limits new ACME orders for custom domains, so neither one
// organization nor a flood of names uses up the CA's rate limits, which
// apply per ACME account and so to all servers of an owner together.
// Renewals are not counted.
type Certificates struct {
// PerOrgPerDay is for the domains of one organization.
PerOrgPerDay int `env:"UPTIME_CERTS_PER_ORG_PER_DAY" envDefault:"20"`
// PerOwnerPerHour is for all servers of the platform, or of one
// organization, together.
PerOwnerPerHour int `env:"UPTIME_CERTS_PER_HOUR" envDefault:"30"`
// PerNamePerDay stops a domain whose orders keep failing from using
// up the rest.
PerNamePerDay int `env:"UPTIME_CERTS_PER_NAME_PER_DAY" envDefault:"5"`
}
// Retention sets how long data is kept. Zero keeps it forever.
type Retention struct {
// Raw check results; charts up to 24h and the recent checks list read them.
Raw time.Duration `env:"UPTIME_RETENTION_RAW" envDefault:"2160h"`
// Hourly aggregate, read by 7d and 30d charts.
Hourly time.Duration `env:"UPTIME_RETENTION_HOURLY" envDefault:"9600h"`
// Daily aggregate and resolved incidents, read by charts up to a year.
Daily time.Duration `env:"UPTIME_RETENTION_DAILY" envDefault:"26280h"`
// Delivered notifications, expired invitations and expired API tokens.
Housekeeping time.Duration `env:"UPTIME_RETENTION_HOUSEKEEPING" envDefault:"720h"`
// Audit log entries.
Audit time.Duration `env:"UPTIME_RETENTION_AUDIT" envDefault:"8760h"`
// What checkers saw of HTTP responses.
Evidence time.Duration `env:"UPTIME_RETENTION_EVIDENCE" envDefault:"720h"`
}
// SSOAllowPrivate resolves SSOPrivateNetworks.
func (a API) SSOAllowPrivate() bool {
switch a.SSOPrivateNetworks {
case "true":
return true
case "false":
return false
}
return a.Edition == EditionSelfHosted
}
// Validate checks API-specific settings in addition to Common.Validate.
func (a API) Validate() error {
if err := a.Common.Validate(); err != nil {
return err
}
if err := a.Storage.Validate(); err != nil {
return err
}
if a.SecretKeys == "" {
return fmt.Errorf("config: UPTIME_SECRET_KEYS is required (format id:base64-32-bytes)")
}
switch a.Signup {
case SignupOpen, SignupFirstUser, SignupClosed:
default:
return fmt.Errorf("config: unknown UPTIME_SIGNUP %q", a.Signup)
}
switch a.SignupVerify {
case "auto", "required":
case "off":
if a.Edition == EditionCloud {
return fmt.Errorf("config: UPTIME_SIGNUP_VERIFY=off is not allowed in the cloud edition")
}
default:
return fmt.Errorf("config: UPTIME_SIGNUP_VERIFY must be auto, required or off")
}
if a.SignupsPerIP < 0 {
return fmt.Errorf("config: UPTIME_SIGNUPS_PER_IP must not be negative")
}
switch a.SSOPrivateNetworks {
case "auto", "true", "false":
default:
return fmt.Errorf("config: UPTIME_SSO_ALLOW_PRIVATE_NETWORKS must be auto, true or false")
}
if u, err := url.Parse(a.PublicURL); err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || strings.HasSuffix(a.PublicURL, "/") {
return fmt.Errorf("config: UPTIME_PUBLIC_URL must be an absolute http(s) URL without trailing slash")
}
if a.SessionIdle <= 0 || a.SessionAbsolute < a.SessionIdle {
return fmt.Errorf("config: UPTIME_SESSION_ABSOLUTE must be >= UPTIME_SESSION_IDLE > 0")
}
return nil
}
// Checker configures cmd/checker. Its region is bound to the agent token.
type Checker struct {
Common
Agent
HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"`
// Concurrency caps checks running at the same time in one instance.
Concurrency int `env:"UPTIME_CHECKER_CONCURRENCY" envDefault:"64"`
}
// StatusPage configures cmd/statuspage.
type StatusPage struct {
Common
Agent
Listen string `env:"UPTIME_STATUSPAGE_LISTEN" envDefault:":8082"`
// 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"`
// CacheDir keeps snapshots and certificates so pages survive restarts
// while the API is down. Defaults to the user cache directory; on
// Kubernetes mount a persistent volume or at least an emptyDir.
CacheDir string `env:"UPTIME_STATUSPAGE_CACHE_DIR"`
// 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.
func Load[T any]() (T, error) {
var cfg T
if err := env.Parse(&cfg); err != nil {
return cfg, fmt.Errorf("config: %w", err)
}
return cfg, nil
}
// Validate reports an unknown edition.
func (c Common) Validate() error {
switch c.Edition {
case EditionCloud, EditionSelfHosted:
return nil
}
return fmt.Errorf("config: unknown edition %q", c.Edition)
}
// Validate reports missing or contradictory database and Redis settings.
func (c Storage) Validate() error {
if c.DatabaseURL == "" {
return fmt.Errorf("config: UPTIME_DATABASE_URL is required")
}
switch {
case c.RedisSentinel.Enabled() && len(c.RedisSentinel.Addrs) == 0:
return fmt.Errorf("config: UPTIME_REDIS_SENTINEL_ADDRS is required with UPTIME_REDIS_SENTINEL_MASTER")
case !c.RedisSentinel.Enabled() && c.RedisURL == "":
return fmt.Errorf("config: UPTIME_REDIS_URL or UPTIME_REDIS_SENTINEL_MASTER is required")
}
return nil
}