refactor: follow the google go style guide

Document every package and exported identifier, return the log level
from NewLogger instead of keeping it in a package variable, and stop
tests from mutating the argon2 parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 00:18:02 +01:00
1 parent 048e114fd9
commit d20225982a
21 files changed
+146 -35

No files matched your search

+8 -4
View File
@@ -1,3 +1,5 @@
// Command api serves the management API and console. It also owns schema
// migrations: run "api migrate up" before rolling out a new release.
package main package main
import ( import (
@@ -18,19 +20,21 @@ import (
) )
func main() { func main() {
log := platform.NewLogger("api") log, level := platform.NewLogger("api")
if err := run(log, os.Args[1:]); err != nil { // Route the standard log package and dependencies through the same handler.
slog.SetDefault(log)
if err := run(log, level, os.Args[1:]); err != nil {
log.Error("exit", "error", err) log.Error("exit", "error", err)
os.Exit(1) os.Exit(1)
} }
} }
func run(log *slog.Logger, args []string) error { func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
cfg, err := config.Load[config.API]() cfg, err := config.Load[config.API]()
if err != nil { if err != nil {
return err return err
} }
platform.SetLogLevel(cfg.LogLevel) level.Set(cfg.LogLevel)
ctx, stop := platform.SignalContext() ctx, stop := platform.SignalContext()
defer stop() defer stop()
+8 -4
View File
@@ -1,3 +1,5 @@
// Command checker executes uptime checks for one region and pulls data from
// external sources. Any number of instances per region may run.
package main package main
import ( import (
@@ -9,19 +11,21 @@ import (
) )
func main() { func main() {
log := platform.NewLogger("checker") log, level := platform.NewLogger("checker")
if err := run(log); err != nil { // Route the standard log package and dependencies through the same handler.
slog.SetDefault(log)
if err := run(log, level); err != nil {
log.Error("exit", "error", err) log.Error("exit", "error", err)
os.Exit(1) os.Exit(1)
} }
} }
func run(log *slog.Logger) error { func run(log *slog.Logger, level *slog.LevelVar) error {
cfg, err := config.Load[config.Checker]() cfg, err := config.Load[config.Checker]()
if err != nil { if err != nil {
return err return err
} }
platform.SetLogLevel(cfg.LogLevel) level.Set(cfg.LogLevel)
ctx, stop := platform.SignalContext() ctx, stop := platform.SignalContext()
defer stop() defer stop()
+8 -4
View File
@@ -1,3 +1,5 @@
// Command statuspage serves public status pages, including on customer
// domains.
package main package main
import ( import (
@@ -11,19 +13,21 @@ import (
) )
func main() { func main() {
log := platform.NewLogger("statuspage") log, level := platform.NewLogger("statuspage")
if err := run(log); err != nil { // Route the standard log package and dependencies through the same handler.
slog.SetDefault(log)
if err := run(log, level); err != nil {
log.Error("exit", "error", err) log.Error("exit", "error", err)
os.Exit(1) os.Exit(1)
} }
} }
func run(log *slog.Logger) error { func run(log *slog.Logger, level *slog.LevelVar) error {
cfg, err := config.Load[config.StatusPage]() cfg, err := config.Load[config.StatusPage]()
if err != nil { if err != nil {
return err return err
} }
platform.SetLogLevel(cfg.LogLevel) level.Set(cfg.LogLevel)
ctx, stop := platform.SignalContext() ctx, stop := platform.SignalContext()
defer stop() defer stop()
+6
View File
@@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// Names shared with the browser side.
const ( const (
CookieName = "__Host-session" CookieName = "__Host-session"
CSRFHeader = "X-CSRF-Token" CSRFHeader = "X-CSRF-Token"
@@ -15,6 +16,8 @@ const (
ctxKey = "auth.session" ctxKey = "auth.session"
) )
// SetCookie sends the session cookie. The __Host- prefix makes browsers
// reject it unless it is Secure, host-only and scoped to /.
func SetCookie(c *gin.Context, sess *Session, maxAge int) { func SetCookie(c *gin.Context, sess *Session, maxAge int) {
http.SetCookie(c.Writer, &http.Cookie{ http.SetCookie(c.Writer, &http.Cookie{
Name: CookieName, Name: CookieName,
@@ -27,6 +30,7 @@ func SetCookie(c *gin.Context, sess *Session, maxAge int) {
}) })
} }
// ClearCookie removes the session cookie.
func ClearCookie(c *gin.Context) { func ClearCookie(c *gin.Context) {
http.SetCookie(c.Writer, &http.Cookie{Name: CookieName, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}) http.SetCookie(c.Writer, &http.Cookie{Name: CookieName, Value: "", Path: "/", MaxAge: -1, Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode})
} }
@@ -54,6 +58,7 @@ func (s *Sessions) Load() gin.HandlerFunc {
} }
} }
// Require aborts with 401 unless Load attached a session.
func Require() gin.HandlerFunc { func Require() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
if Current(c) == nil { if Current(c) == nil {
@@ -104,6 +109,7 @@ func sameOrigin(r *http.Request) bool {
return err == nil && u.Host == r.Host return err == nil && u.Host == r.Host
} }
// Current returns the session attached by Load, or nil.
func Current(c *gin.Context) *Session { func Current(c *gin.Context) *Session {
v, ok := c.Get(ctxKey) v, ok := c.Get(ctxKey)
if !ok { if !ok {
+17 -8
View File
@@ -7,11 +7,11 @@ import (
"errors" "errors"
"fmt" "fmt"
"strings" "strings"
"sync"
"golang.org/x/crypto/argon2" "golang.org/x/crypto/argon2"
) )
// OWASP 2024 baseline for argon2id.
type argonParams struct { type argonParams struct {
memory uint32 memory uint32
time uint32 time uint32
@@ -19,24 +19,32 @@ type argonParams struct {
keyLen uint32 keyLen uint32
} }
var current = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32} // defaultParams is the OWASP baseline for argon2id. Raising it makes
// VerifyPassword request a rehash of older hashes on their next login.
var defaultParams = argonParams{memory: 19 * 1024, time: 2, threads: 1, keyLen: 32}
// MinPasswordLength follows NIST SP 800-63B; no composition rules apply.
const MinPasswordLength = 12 const MinPasswordLength = 12
// ErrPasswordTooShort is returned by HashPassword.
var ErrPasswordTooShort = fmt.Errorf("auth: password must have at least %d characters", MinPasswordLength) var ErrPasswordTooShort = fmt.Errorf("auth: password must have at least %d characters", MinPasswordLength)
// HashPassword returns an argon2id hash in PHC string format.
func HashPassword(pw string) (string, error) { func HashPassword(pw string) (string, error) {
if len([]rune(pw)) < MinPasswordLength { if len([]rune(pw)) < MinPasswordLength {
return "", ErrPasswordTooShort return "", ErrPasswordTooShort
} }
return hashPassword(pw, defaultParams), nil
}
func hashPassword(pw string, p argonParams) string {
salt := make([]byte, 16) salt := make([]byte, 16)
_, _ = rand.Read(salt) _, _ = rand.Read(salt)
p := current
hash := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, p.keyLen) hash := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, p.keyLen)
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version, p.memory, p.time, p.threads, argon2.Version, p.memory, p.time, p.threads,
base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(hash)), nil base64.RawStdEncoding.EncodeToString(hash))
} }
// VerifyPassword reports whether pw matches and whether the stored hash uses // VerifyPassword reports whether pw matches and whether the stored hash uses
@@ -48,13 +56,14 @@ func VerifyPassword(encoded, pw string) (ok, rehash bool, err error) {
} }
got := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, uint32(len(want))) got := argon2.IDKey([]byte(pw), salt, p.time, p.memory, p.threads, uint32(len(want)))
ok = subtle.ConstantTimeCompare(got, want) == 1 ok = subtle.ConstantTimeCompare(got, want) == 1
return ok, ok && p != current, nil return ok, ok && p != defaultParams, nil
} }
// dummyHash keeps the response time of unknown accounts equal to known ones. var dummyHash = sync.OnceValue(func() string { return hashPassword("timing-equalizer", defaultParams) })
var dummyHash, _ = HashPassword("not-a-real-password-for-timing")
func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash, pw) } // BurnPasswordCheck spends the time of a real verification. Call it when the
// account does not exist so response times do not reveal that.
func BurnPasswordCheck(pw string) { _, _, _ = VerifyPassword(dummyHash(), pw) }
func decodeHash(s string) (argonParams, []byte, []byte, error) { func decodeHash(s string) (argonParams, []byte, []byte, error) {
var p argonParams var p argonParams
+3
View File
@@ -7,10 +7,12 @@ import (
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
// Limiter counts attempts per key in fixed windows stored in Redis.
type Limiter struct { type Limiter struct {
rdb redis.UniversalClient rdb redis.UniversalClient
} }
// NewLimiter returns a Limiter backed by rdb.
func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} } func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} }
var incrWithTTL = redis.NewScript(` var incrWithTTL = redis.NewScript(`
@@ -27,6 +29,7 @@ func (l *Limiter) Allow(ctx context.Context, key string, limit int, window time.
return n <= limit, nil return n <= limit, nil
} }
// Reset clears the counter for key, e.g. after a successful login.
func (l *Limiter) Reset(ctx context.Context, key string) error { func (l *Limiter) Reset(ctx context.Context, key string) error {
return l.rdb.Del(ctx, "rl:"+key).Err() return l.rdb.Del(ctx, "rl:"+key).Err()
} }
+16
View File
@@ -1,3 +1,5 @@
// Package auth implements sessions, password and TOTP verification, rate
// limiting and CSRF protection.
package auth package auth
import ( import (
@@ -16,8 +18,11 @@ import (
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
// ErrNoSession is returned for unknown, expired or malformed sessions.
var ErrNoSession = errors.New("auth: no session") var ErrNoSession = errors.New("auth: no session")
// Session is a signed-in browser. Token is the cookie value and never
// stored server side.
type Session struct { type Session struct {
Token string Token string
UserID uuid.UUID UserID uuid.UUID
@@ -27,10 +32,12 @@ type Session struct {
CreatedAt time.Time CreatedAt time.Time
} }
// CheckCSRF compares token with the session's CSRF token in constant time.
func (s *Session) CheckCSRF(token string) bool { func (s *Session) CheckCSRF(token string) bool {
return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1 return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1
} }
// Sessions stores sessions in Redis so any API replica can serve any request.
type Sessions struct { type Sessions struct {
rdb redis.UniversalClient rdb redis.UniversalClient
idle time.Duration idle time.Duration
@@ -38,6 +45,8 @@ type Sessions struct {
now func() time.Time now func() time.Time
} }
// NewSessions returns a store whose sessions expire after idle without use
// and after absolute regardless of use.
func NewSessions(rdb redis.UniversalClient, idle, absolute time.Duration) *Sessions { func NewSessions(rdb redis.UniversalClient, idle, absolute time.Duration) *Sessions {
return &Sessions{rdb: rdb, idle: idle, absolute: absolute, now: time.Now} return &Sessions{rdb: rdb, idle: idle, absolute: absolute, now: time.Now}
} }
@@ -51,12 +60,14 @@ func key(token string) string {
func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() } func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() }
// RandomToken returns 256 bits of randomness, URL-safe encoded.
func RandomToken() string { func RandomToken() string {
b := make([]byte, 32) b := make([]byte, 32)
_, _ = rand.Read(b) _, _ = rand.Read(b)
return base64.RawURLEncoding.EncodeToString(b) return base64.RawURLEncoding.EncodeToString(b)
} }
// Create starts a session. org and locale may be empty.
func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale string) (*Session, error) { func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale string) (*Session, error) {
sess := &Session{ sess := &Session{
Token: RandomToken(), Token: RandomToken(),
@@ -86,6 +97,7 @@ func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale strin
return sess, nil return sess, nil
} }
// Get loads the session for token and extends its idle expiry.
func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) { func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
if token == "" { if token == "" {
return nil, ErrNoSession return nil, ErrNoSession
@@ -115,6 +127,8 @@ func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
return sess, nil return sess, nil
} }
// SwitchOrg changes the active organization. Membership must be checked
// by the caller.
func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) error { func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) error {
if err := s.rdb.HSet(ctx, key(sess.Token), "org", orgString(org)).Err(); err != nil { if err := s.rdb.HSet(ctx, key(sess.Token), "org", orgString(org)).Err(); err != nil {
return fmt.Errorf("auth: switch org: %w", err) return fmt.Errorf("auth: switch org: %w", err)
@@ -123,6 +137,7 @@ func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID)
return nil return nil
} }
// SetLocale changes the session language.
func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) error { func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) error {
if err := s.rdb.HSet(ctx, key(sess.Token), "locale", locale).Err(); err != nil { if err := s.rdb.HSet(ctx, key(sess.Token), "locale", locale).Err(); err != nil {
return fmt.Errorf("auth: set locale: %w", err) return fmt.Errorf("auth: set locale: %w", err)
@@ -131,6 +146,7 @@ func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string)
return nil return nil
} }
// Delete ends sess.
func (s *Sessions) Delete(ctx context.Context, sess *Session) error { func (s *Sessions) Delete(ctx context.Context, sess *Session) error {
k := key(sess.Token) k := key(sess.Token)
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
+5
View File
@@ -12,6 +12,8 @@ import (
const totpIssuer = "uptimesebi" const totpIssuer = "uptimesebi"
// NewTOTPKey generates a secret for account using the defaults every common
// authenticator app supports (SHA-1, 6 digits, 30 s).
func NewTOTPKey(account string) (*otp.Key, error) { func NewTOTPKey(account string) (*otp.Key, error) {
return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account}) return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account})
} }
@@ -23,10 +25,13 @@ type TOTPVerifier struct {
now func() time.Time now func() time.Time
} }
// NewTOTPVerifier returns a verifier that records used codes in rdb.
func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier { func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier {
return &TOTPVerifier{rdb: rdb, now: time.Now} return &TOTPVerifier{rdb: rdb, now: time.Now}
} }
// Verify accepts code for secret within one step of clock skew, at most once
// per user.
func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) { func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) {
ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{ ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{
Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1,
+4
View File
@@ -1,6 +1,10 @@
// Package buildinfo exposes release metadata injected via -ldflags -X.
package buildinfo package buildinfo
// Set by the release build; see Makefile and Dockerfile.
var ( var (
// Version is the release tag, or "dev" for local builds.
Version = "dev" Version = "dev"
// Commit is the short git revision the binary was built from.
Commit = "none" Commit = "none"
) )
+17
View File
@@ -1,3 +1,5 @@
// Package config reads component settings from UPTIME_* environment
// variables.
package config package config
import ( import (
@@ -8,13 +10,17 @@ import (
"github.com/caarlos0/env/v11" "github.com/caarlos0/env/v11"
) )
// Edition switches features that only make sense when we operate the
// service, such as billing.
type Edition string type Edition string
// Editions.
const ( const (
EditionCloud Edition = "cloud" EditionCloud Edition = "cloud"
EditionSelfHosted Edition = "selfhosted" EditionSelfHosted Edition = "selfhosted"
) )
// Common holds settings shared by all components.
type Common struct { type Common struct {
Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"` Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"`
LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"` LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"`
@@ -33,16 +39,21 @@ type Sentinel struct {
Password string `env:"UPTIME_REDIS_SENTINEL_PASSWORD"` Password string `env:"UPTIME_REDIS_SENTINEL_PASSWORD"`
} }
// Enabled reports whether a sentinel master name is configured.
func (s Sentinel) Enabled() bool { return s.Master != "" } func (s Sentinel) Enabled() bool { return s.Master != "" }
// SignupMode controls who may create an account and organization.
type SignupMode string type SignupMode string
// Signup modes. SignupFirstUser allows exactly one account, the operator of a
// fresh self-hosted installation.
const ( const (
SignupOpen SignupMode = "open" SignupOpen SignupMode = "open"
SignupFirstUser SignupMode = "first-user" SignupFirstUser SignupMode = "first-user"
SignupClosed SignupMode = "closed" SignupClosed SignupMode = "closed"
) )
// API configures cmd/api.
type API struct { type API struct {
Common Common
Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"` Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"`
@@ -52,6 +63,7 @@ type API struct {
SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"` SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"`
} }
// Validate checks API-specific settings in addition to Common.Validate.
func (a API) Validate() error { func (a API) Validate() error {
if err := a.Common.Validate(); err != nil { if err := a.Common.Validate(); err != nil {
return err return err
@@ -70,17 +82,21 @@ func (a API) Validate() error {
return nil return nil
} }
// Checker configures cmd/checker. Region names the location this instance
// checks from and must match the regions assigned to monitors.
type Checker struct { type Checker struct {
Common Common
Region string `env:"UPTIME_CHECKER_REGION,required,notEmpty"` Region string `env:"UPTIME_CHECKER_REGION,required,notEmpty"`
HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"` HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"`
} }
// StatusPage configures cmd/statuspage.
type StatusPage struct { type StatusPage struct {
Common Common
Listen string `env:"UPTIME_STATUSPAGE_LISTEN" envDefault:":8082"` Listen string `env:"UPTIME_STATUSPAGE_LISTEN" envDefault:":8082"`
} }
// Load parses the environment into a T, applying envDefault tags.
func Load[T any]() (T, error) { func Load[T any]() (T, error) {
var cfg T var cfg T
if err := env.Parse(&cfg); err != nil { if err := env.Parse(&cfg); err != nil {
@@ -89,6 +105,7 @@ func Load[T any]() (T, error) {
return cfg, nil return cfg, nil
} }
// Validate reports missing or contradictory settings.
func (c Common) Validate() error { func (c Common) Validate() error {
switch c.Edition { switch c.Edition {
case EditionCloud, EditionSelfHosted: case EditionCloud, EditionSelfHosted:
+10 -5
View File
@@ -1,3 +1,5 @@
// Package migrations embeds the SQL schema migrations and applies them with
// goose.
package migrations package migrations
import ( import (
@@ -7,7 +9,7 @@ import (
"fmt" "fmt"
"io/fs" "io/fs"
_ "github.com/jackc/pgx/v5/stdlib" _ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" database/sql driver
"github.com/pressly/goose/v3" "github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/lock" "github.com/pressly/goose/v3/lock"
) )
@@ -40,30 +42,33 @@ func newProvider(dsn string) (*goose.Provider, *sql.DB, error) {
return p, db, nil return p, db, nil
} }
// Up applies all pending migrations.
func Up(ctx context.Context, dsn string) ([]*goose.MigrationResult, error) { func Up(ctx context.Context, dsn string) ([]*goose.MigrationResult, error) {
p, db, err := newProvider(dsn) p, db, err := newProvider(dsn)
if err != nil { if err != nil {
return nil, fmt.Errorf("migrate: %w", err) return nil, fmt.Errorf("migrate: %w", err)
} }
defer db.Close() defer func() { _ = db.Close() }()
return p.Up(ctx) return p.Up(ctx)
} }
// Down rolls back the most recent migration.
func Down(ctx context.Context, dsn string) (*goose.MigrationResult, error) { func Down(ctx context.Context, dsn string) (*goose.MigrationResult, error) {
p, db, err := newProvider(dsn) p, db, err := newProvider(dsn)
if err != nil { if err != nil {
return nil, fmt.Errorf("migrate: %w", err) return nil, fmt.Errorf("migrate: %w", err)
} }
defer db.Close() defer func() { _ = db.Close() }()
return p.Down(ctx) return p.Down(ctx)
} }
// Status lists every migration with its applied state.
func Status(ctx context.Context, dsn string) ([]*goose.MigrationStatus, error) { func Status(ctx context.Context, dsn string) ([]*goose.MigrationStatus, error) {
p, db, err := newProvider(dsn) p, db, err := newProvider(dsn)
if err != nil { if err != nil {
return nil, fmt.Errorf("migrate: %w", err) return nil, fmt.Errorf("migrate: %w", err)
} }
defer db.Close() defer func() { _ = db.Close() }()
return p.Status(ctx) return p.Status(ctx)
} }
@@ -74,6 +79,6 @@ func Pending(ctx context.Context, dsn string) (bool, error) {
if err != nil { if err != nil {
return false, fmt.Errorf("migrate: %w", err) return false, fmt.Errorf("migrate: %w", err)
} }
defer db.Close() defer func() { _ = db.Close() }()
return p.HasPending(ctx) return p.HasPending(ctx)
} }
+4
View File
@@ -9,6 +9,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// Probe reports whether a dependency is usable.
type Probe func(context.Context) error type Probe func(context.Context) error
// Health separates liveness from readiness so a draining instance drops out // Health separates liveness from readiness so a draining instance drops out
@@ -18,12 +19,15 @@ type Health struct {
draining atomic.Bool draining atomic.Bool
} }
// NewHealth returns a Health that is ready while all probes pass.
func NewHealth(probes map[string]Probe) *Health { func NewHealth(probes map[string]Probe) *Health {
return &Health{probes: probes} return &Health{probes: probes}
} }
// Drain makes /readyz fail permanently. Call it before shutdown.
func (h *Health) Drain() { h.draining.Store(true) } func (h *Health) Drain() { h.draining.Store(true) }
// Register mounts /healthz (liveness) and /readyz (readiness).
func (h *Health) Register(r gin.IRoutes) { func (h *Health) Register(r gin.IRoutes) {
r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) }) r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) })
r.GET("/readyz", h.ready) r.GET("/readyz", h.ready)
+8 -10
View File
@@ -7,15 +7,13 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
) )
var logLevel = new(slog.LevelVar) // NewLogger returns a JSON logger tagged with component and the release
// version, and the level variable controlling it. The level can be changed
// NewLogger installs a JSON logger as the process default so output from the // once configuration is loaded; the logger is needed before that to report
// standard log package and dependencies ends up in the same format. // configuration errors.
func NewLogger(component string) *slog.Logger { func NewLogger(component string) (*slog.Logger, *slog.LevelVar) {
l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel})). level := new(slog.LevelVar)
l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})).
With("component", component, "app_version", buildinfo.Version) With("component", component, "app_version", buildinfo.Version)
slog.SetDefault(l) return l, level
return l
} }
func SetLogLevel(l slog.Level) { logLevel.Set(l) }
+3
View File
@@ -1,3 +1,5 @@
// Package platform wires the infrastructure shared by all commands:
// logging, Postgres, Redis, HTTP serving and health probes.
package platform package platform
import ( import (
@@ -7,6 +9,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
) )
// OpenPostgres connects a pool and verifies it with a ping.
func OpenPostgres(ctx context.Context, url string) (*pgxpool.Pool, error) { func OpenPostgres(ctx context.Context, url string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(url) cfg, err := pgxpool.ParseConfig(url)
if err != nil { if err != nil {
+2
View File
@@ -9,6 +9,8 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/config"
) )
// OpenRedis connects to a single server or, when c.RedisSentinel is enabled,
// to the current master via sentinel with automatic failover.
func OpenRedis(ctx context.Context, c config.Common) (*redis.Client, error) { func OpenRedis(ctx context.Context, c config.Common) (*redis.Client, error) {
var rdb *redis.Client var rdb *redis.Client
if c.RedisSentinel.Enabled() { if c.RedisSentinel.Enabled() {
+2
View File
@@ -12,6 +12,8 @@ import (
var quietPaths = map[string]bool{"/healthz": true, "/readyz": true} var quietPaths = map[string]bool{"/healthz": true, "/readyz": true}
// NewRouter returns a gin engine that logs requests and panics through log
// as JSON and writes nothing to stdout itself.
func NewRouter(log *slog.Logger) *gin.Engine { func NewRouter(log *slog.Logger) *gin.Engine {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
gin.DefaultWriter = io.Discard gin.DefaultWriter = io.Discard
+6
View File
@@ -15,12 +15,14 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
) )
// Deps are the connections every command needs.
type Deps struct { type Deps struct {
Log *slog.Logger Log *slog.Logger
DB *pgxpool.Pool DB *pgxpool.Pool
Redis *redis.Client Redis *redis.Client
} }
// Close releases all connections. It is safe on a partially built Deps.
func (d *Deps) Close() { func (d *Deps) Close() {
if d.DB != nil { if d.DB != nil {
d.DB.Close() d.DB.Close()
@@ -30,6 +32,7 @@ func (d *Deps) Close() {
} }
} }
// Probes returns readiness probes for the connections.
func (d *Deps) Probes() map[string]Probe { func (d *Deps) Probes() map[string]Probe {
return map[string]Probe{ return map[string]Probe{
"postgres": func(ctx context.Context) error { return d.DB.Ping(ctx) }, "postgres": func(ctx context.Context) error { return d.DB.Ping(ctx) },
@@ -37,10 +40,13 @@ func (d *Deps) Probes() map[string]Probe {
} }
} }
// SignalContext is cancelled on SIGINT or SIGTERM.
func SignalContext() (context.Context, context.CancelFunc) { func SignalContext() (context.Context, context.CancelFunc) {
return signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) return signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
} }
// Connect validates c, refuses to start against an outdated schema, and
// opens Postgres and Redis.
func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, error) { func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, error) {
if err := c.Validate(); err != nil { if err := c.Validate(); err != nil {
return nil, err return nil, err
+1
View File
@@ -34,6 +34,7 @@ func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Heal
return srv.Shutdown(sctx) return srv.Shutdown(sctx)
} }
// NewHTTPServer returns a server with timeouts that bound slow clients.
func NewHTTPServer(addr string, h http.Handler) *http.Server { func NewHTTPServer(addr string, h http.Handler) *http.Server {
return &http.Server{ return &http.Server{
Addr: addr, Addr: addr,
+5
View File
@@ -12,6 +12,8 @@ import (
"strings" "strings"
) )
// ErrUnknownKey is returned for values sealed with a key that was removed
// from the keyring.
var ErrUnknownKey = errors.New("sealed: unknown key id") var ErrUnknownKey = errors.New("sealed: unknown key id")
// Keyring holds one active key for sealing and any number of retired keys // Keyring holds one active key for sealing and any number of retired keys
@@ -62,6 +64,7 @@ func (k *Keyring) Seal(plain, aad []byte) []byte {
return aead.Seal(out, nonce, plain, aad) return aead.Seal(out, nonce, plain, aad)
} }
// Open decrypts a value produced by Seal with the same aad.
func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) { func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) {
id, rest, ok := strings.Cut(string(sealed), ":") id, rest, ok := strings.Cut(string(sealed), ":")
if !ok { if !ok {
@@ -78,6 +81,8 @@ func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) {
return aead.Open(nil, body[:aead.NonceSize()], body[aead.NonceSize():], aad) return aead.Open(nil, body[:aead.NonceSize()], body[aead.NonceSize():], aad)
} }
// NeedsReseal reports whether sealed was produced with a retired key and
// should be rewritten.
func (k *Keyring) NeedsReseal(sealed []byte) bool { func (k *Keyring) NeedsReseal(sealed []byte) bool {
id, _, _ := strings.Cut(string(sealed), ":") id, _, _ := strings.Cut(string(sealed), ":")
return id != k.active return id != k.active
+8
View File
@@ -1,3 +1,5 @@
// Package tenant runs queries inside a row-level-security context. All
// database access from request handlers must go through DB.Tx.
package tenant package tenant
import ( import (
@@ -21,6 +23,7 @@ type Scope struct {
global bool global bool
} }
// Org scopes to one organization. user may be uuid.Nil for background work.
func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} } func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} }
// User grants access to the user's own memberships and the orgs behind them, // User grants access to the user's own memberships and the orgs behind them,
@@ -35,12 +38,17 @@ func Global() Scope { return Scope{global: true} }
// cross-tenant, never for request handling. // cross-tenant, never for request handling.
func System() Scope { return Scope{system: true} } func System() Scope { return Scope{system: true} }
// ErrNoScope is returned by Tx for the zero Scope.
var ErrNoScope = errors.New("tenant: empty scope") var ErrNoScope = errors.New("tenant: empty scope")
// DB wraps a pool so that every transaction carries a Scope.
type DB struct{ pool *pgxpool.Pool } type DB struct{ pool *pgxpool.Pool }
// New returns a DB using pool.
func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} } func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} }
// Tx runs fn in a transaction whose row-level-security settings come from s.
// The transaction commits if fn returns nil and rolls back otherwise.
func (d *DB) Tx(ctx context.Context, s Scope, fn func(*store.Queries) error) error { func (d *DB) Tx(ctx context.Context, s Scope, fn func(*store.Queries) error) error {
if s == (Scope{}) { if s == (Scope{}) {
return ErrNoScope return ErrNoScope
+5
View File
@@ -1,3 +1,5 @@
// Package web contains the templ components and static assets shared by
// the console and status pages.
package web package web
import ( import (
@@ -12,6 +14,7 @@ import (
//go:embed all:static //go:embed all:static
var static embed.FS var static embed.FS
// Static serves the embedded build output of npm run build.
func Static() http.FileSystem { func Static() http.FileSystem {
sub, err := fs.Sub(static, "static") sub, err := fs.Sub(static, "static")
if err != nil { if err != nil {
@@ -20,6 +23,8 @@ func Static() http.FileSystem {
return http.FS(sub) return http.FS(sub)
} }
// Render writes comp as HTML. Rendering errors are attached to c so the
// access log records them; the status has already been sent.
func Render(c *gin.Context, status int, comp templ.Component) { func Render(c *gin.Context, status int, comp templ.Component) {
c.Status(status) c.Status(status)
c.Header("Content-Type", "text/html; charset=utf-8") c.Header("Content-Type", "text/html; charset=utf-8")