diff --git a/cmd/api/main.go b/cmd/api/main.go index d94334f..a7e7ac4 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -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 import ( @@ -18,19 +20,21 @@ import ( ) func main() { - log := platform.NewLogger("api") - if err := run(log, os.Args[1:]); err != nil { + log, level := platform.NewLogger("api") + // 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) 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]() if err != nil { return err } - platform.SetLogLevel(cfg.LogLevel) + level.Set(cfg.LogLevel) ctx, stop := platform.SignalContext() defer stop() diff --git a/cmd/checker/main.go b/cmd/checker/main.go index cb3d925..b813983 100644 --- a/cmd/checker/main.go +++ b/cmd/checker/main.go @@ -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 import ( @@ -9,19 +11,21 @@ import ( ) func main() { - log := platform.NewLogger("checker") - if err := run(log); err != nil { + log, level := platform.NewLogger("checker") + // 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) os.Exit(1) } } -func run(log *slog.Logger) error { +func run(log *slog.Logger, level *slog.LevelVar) error { cfg, err := config.Load[config.Checker]() if err != nil { return err } - platform.SetLogLevel(cfg.LogLevel) + level.Set(cfg.LogLevel) ctx, stop := platform.SignalContext() defer stop() diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index 570ae37..c827959 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -1,3 +1,5 @@ +// Command statuspage serves public status pages, including on customer +// domains. package main import ( @@ -11,19 +13,21 @@ import ( ) func main() { - log := platform.NewLogger("statuspage") - if err := run(log); err != nil { + log, level := platform.NewLogger("statuspage") + // 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) os.Exit(1) } } -func run(log *slog.Logger) error { +func run(log *slog.Logger, level *slog.LevelVar) error { cfg, err := config.Load[config.StatusPage]() if err != nil { return err } - platform.SetLogLevel(cfg.LogLevel) + level.Set(cfg.LogLevel) ctx, stop := platform.SignalContext() defer stop() diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go index f703540..71267ab 100644 --- a/internal/auth/middleware.go +++ b/internal/auth/middleware.go @@ -8,6 +8,7 @@ import ( "github.com/gin-gonic/gin" ) +// Names shared with the browser side. const ( CookieName = "__Host-session" CSRFHeader = "X-CSRF-Token" @@ -15,6 +16,8 @@ const ( 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) { http.SetCookie(c.Writer, &http.Cookie{ 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) { 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 { return func(c *gin.Context) { if Current(c) == nil { @@ -104,6 +109,7 @@ func sameOrigin(r *http.Request) bool { return err == nil && u.Host == r.Host } +// Current returns the session attached by Load, or nil. func Current(c *gin.Context) *Session { v, ok := c.Get(ctxKey) if !ok { diff --git a/internal/auth/password.go b/internal/auth/password.go index 8e1ebb1..5d02621 100644 --- a/internal/auth/password.go +++ b/internal/auth/password.go @@ -7,11 +7,11 @@ import ( "errors" "fmt" "strings" + "sync" "golang.org/x/crypto/argon2" ) -// OWASP 2024 baseline for argon2id. type argonParams struct { memory uint32 time uint32 @@ -19,24 +19,32 @@ type argonParams struct { 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 +// ErrPasswordTooShort is returned by HashPassword. 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) { if len([]rune(pw)) < MinPasswordLength { return "", ErrPasswordTooShort } + return hashPassword(pw, defaultParams), nil +} + +func hashPassword(pw string, p argonParams) string { salt := make([]byte, 16) _, _ = rand.Read(salt) - p := current 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", argon2.Version, p.memory, p.time, p.threads, base64.RawStdEncoding.EncodeToString(salt), - base64.RawStdEncoding.EncodeToString(hash)), nil + base64.RawStdEncoding.EncodeToString(hash)) } // 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))) 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, _ = HashPassword("not-a-real-password-for-timing") +var dummyHash = sync.OnceValue(func() string { return hashPassword("timing-equalizer", defaultParams) }) -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) { var p argonParams diff --git a/internal/auth/ratelimit.go b/internal/auth/ratelimit.go index c4410d4..1f01c63 100644 --- a/internal/auth/ratelimit.go +++ b/internal/auth/ratelimit.go @@ -7,10 +7,12 @@ import ( "github.com/redis/go-redis/v9" ) +// Limiter counts attempts per key in fixed windows stored in Redis. type Limiter struct { rdb redis.UniversalClient } +// NewLimiter returns a Limiter backed by rdb. func NewLimiter(rdb redis.UniversalClient) *Limiter { return &Limiter{rdb: rdb} } 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 } +// Reset clears the counter for key, e.g. after a successful login. func (l *Limiter) Reset(ctx context.Context, key string) error { return l.rdb.Del(ctx, "rl:"+key).Err() } diff --git a/internal/auth/session.go b/internal/auth/session.go index 32341ce..5e5a6a7 100644 --- a/internal/auth/session.go +++ b/internal/auth/session.go @@ -1,3 +1,5 @@ +// Package auth implements sessions, password and TOTP verification, rate +// limiting and CSRF protection. package auth import ( @@ -16,8 +18,11 @@ import ( "github.com/redis/go-redis/v9" ) +// ErrNoSession is returned for unknown, expired or malformed sessions. 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 { Token string UserID uuid.UUID @@ -27,10 +32,12 @@ type Session struct { CreatedAt time.Time } +// CheckCSRF compares token with the session's CSRF token in constant time. func (s *Session) CheckCSRF(token string) bool { 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 { rdb redis.UniversalClient idle time.Duration @@ -38,6 +45,8 @@ type Sessions struct { 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 { 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() } +// RandomToken returns 256 bits of randomness, URL-safe encoded. func RandomToken() string { b := make([]byte, 32) _, _ = rand.Read(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) { sess := &Session{ Token: RandomToken(), @@ -86,6 +97,7 @@ func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID, locale strin 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) { if token == "" { return nil, ErrNoSession @@ -115,6 +127,8 @@ func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) { 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 { if err := s.rdb.HSet(ctx, key(sess.Token), "org", orgString(org)).Err(); err != nil { 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 } +// SetLocale changes the session language. 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 { 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 } +// Delete ends sess. func (s *Sessions) Delete(ctx context.Context, sess *Session) error { k := key(sess.Token) _, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { diff --git a/internal/auth/totp.go b/internal/auth/totp.go index 1ea913d..636e497 100644 --- a/internal/auth/totp.go +++ b/internal/auth/totp.go @@ -12,6 +12,8 @@ import ( 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) { return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account}) } @@ -23,10 +25,13 @@ type TOTPVerifier struct { now func() time.Time } +// NewTOTPVerifier returns a verifier that records used codes in rdb. func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier { 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) { ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{ Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1, diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.go index 37e8fec..00ca997 100644 --- a/internal/buildinfo/buildinfo.go +++ b/internal/buildinfo/buildinfo.go @@ -1,6 +1,10 @@ +// Package buildinfo exposes release metadata injected via -ldflags -X. package buildinfo +// Set by the release build; see Makefile and Dockerfile. var ( + // Version is the release tag, or "dev" for local builds. Version = "dev" - Commit = "none" + // Commit is the short git revision the binary was built from. + Commit = "none" ) diff --git a/internal/config/config.go b/internal/config/config.go index a01ceb2..92d7ae8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,3 +1,5 @@ +// Package config reads component settings from UPTIME_* environment +// variables. package config import ( @@ -8,13 +10,17 @@ import ( "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"` @@ -33,16 +39,21 @@ type Sentinel struct { 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 Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"` @@ -52,6 +63,7 @@ type API struct { SessionAbsolute time.Duration `env:"UPTIME_SESSION_ABSOLUTE" envDefault:"720h"` } +// Validate checks API-specific settings in addition to Common.Validate. func (a API) Validate() error { if err := a.Common.Validate(); err != nil { return err @@ -70,17 +82,21 @@ func (a API) Validate() error { 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 { Common Region string `env:"UPTIME_CHECKER_REGION,required,notEmpty"` HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"` } +// StatusPage configures cmd/statuspage. type StatusPage struct { Common Listen string `env:"UPTIME_STATUSPAGE_LISTEN" envDefault:":8082"` } +// 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 { @@ -89,6 +105,7 @@ func Load[T any]() (T, error) { return cfg, nil } +// Validate reports missing or contradictory settings. func (c Common) Validate() error { switch c.Edition { case EditionCloud, EditionSelfHosted: diff --git a/internal/migrations/migrations.go b/internal/migrations/migrations.go index 0440d61..26587b3 100644 --- a/internal/migrations/migrations.go +++ b/internal/migrations/migrations.go @@ -1,3 +1,5 @@ +// Package migrations embeds the SQL schema migrations and applies them with +// goose. package migrations import ( @@ -7,7 +9,7 @@ import ( "fmt" "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/lock" ) @@ -40,30 +42,33 @@ func newProvider(dsn string) (*goose.Provider, *sql.DB, error) { return p, db, nil } +// Up applies all pending migrations. func Up(ctx context.Context, dsn string) ([]*goose.MigrationResult, error) { p, db, err := newProvider(dsn) if err != nil { return nil, fmt.Errorf("migrate: %w", err) } - defer db.Close() + defer func() { _ = db.Close() }() return p.Up(ctx) } +// Down rolls back the most recent migration. func Down(ctx context.Context, dsn string) (*goose.MigrationResult, error) { p, db, err := newProvider(dsn) if err != nil { return nil, fmt.Errorf("migrate: %w", err) } - defer db.Close() + defer func() { _ = db.Close() }() return p.Down(ctx) } +// Status lists every migration with its applied state. func Status(ctx context.Context, dsn string) ([]*goose.MigrationStatus, error) { p, db, err := newProvider(dsn) if err != nil { return nil, fmt.Errorf("migrate: %w", err) } - defer db.Close() + defer func() { _ = db.Close() }() return p.Status(ctx) } @@ -74,6 +79,6 @@ func Pending(ctx context.Context, dsn string) (bool, error) { if err != nil { return false, fmt.Errorf("migrate: %w", err) } - defer db.Close() + defer func() { _ = db.Close() }() return p.HasPending(ctx) } diff --git a/internal/platform/health.go b/internal/platform/health.go index 1ab176b..a9645ef 100644 --- a/internal/platform/health.go +++ b/internal/platform/health.go @@ -9,6 +9,7 @@ import ( "github.com/gin-gonic/gin" ) +// Probe reports whether a dependency is usable. type Probe func(context.Context) error // Health separates liveness from readiness so a draining instance drops out @@ -18,12 +19,15 @@ type Health struct { draining atomic.Bool } +// NewHealth returns a Health that is ready while all probes pass. func NewHealth(probes map[string]Probe) *Health { return &Health{probes: probes} } +// Drain makes /readyz fail permanently. Call it before shutdown. func (h *Health) Drain() { h.draining.Store(true) } +// Register mounts /healthz (liveness) and /readyz (readiness). func (h *Health) Register(r gin.IRoutes) { r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusNoContent) }) r.GET("/readyz", h.ready) diff --git a/internal/platform/log.go b/internal/platform/log.go index 313d5f9..5592947 100644 --- a/internal/platform/log.go +++ b/internal/platform/log.go @@ -7,15 +7,13 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" ) -var logLevel = new(slog.LevelVar) - -// NewLogger installs a JSON logger as the process default so output from the -// standard log package and dependencies ends up in the same format. -func NewLogger(component string) *slog.Logger { - l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel})). +// NewLogger returns a JSON logger tagged with component and the release +// version, and the level variable controlling it. The level can be changed +// once configuration is loaded; the logger is needed before that to report +// configuration errors. +func NewLogger(component string) (*slog.Logger, *slog.LevelVar) { + level := new(slog.LevelVar) + l := slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: level})). With("component", component, "app_version", buildinfo.Version) - slog.SetDefault(l) - return l + return l, level } - -func SetLogLevel(l slog.Level) { logLevel.Set(l) } diff --git a/internal/platform/postgres.go b/internal/platform/postgres.go index 493d2bc..a3b4320 100644 --- a/internal/platform/postgres.go +++ b/internal/platform/postgres.go @@ -1,3 +1,5 @@ +// Package platform wires the infrastructure shared by all commands: +// logging, Postgres, Redis, HTTP serving and health probes. package platform import ( @@ -7,6 +9,7 @@ import ( "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) { cfg, err := pgxpool.ParseConfig(url) if err != nil { diff --git a/internal/platform/redis.go b/internal/platform/redis.go index bbd82ae..585704f 100644 --- a/internal/platform/redis.go +++ b/internal/platform/redis.go @@ -9,6 +9,8 @@ import ( "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) { var rdb *redis.Client if c.RedisSentinel.Enabled() { diff --git a/internal/platform/router.go b/internal/platform/router.go index 06b32f7..2dd1219 100644 --- a/internal/platform/router.go +++ b/internal/platform/router.go @@ -12,6 +12,8 @@ import ( 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 { gin.SetMode(gin.ReleaseMode) gin.DefaultWriter = io.Discard diff --git a/internal/platform/run.go b/internal/platform/run.go index 7eefe7f..3b3a715 100644 --- a/internal/platform/run.go +++ b/internal/platform/run.go @@ -15,12 +15,14 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/migrations" ) +// Deps are the connections every command needs. type Deps struct { Log *slog.Logger DB *pgxpool.Pool Redis *redis.Client } +// Close releases all connections. It is safe on a partially built Deps. func (d *Deps) Close() { if d.DB != nil { 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 { return map[string]Probe{ "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) { 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) { if err := c.Validate(); err != nil { return nil, err diff --git a/internal/platform/server.go b/internal/platform/server.go index 441f132..9d3fb01 100644 --- a/internal/platform/server.go +++ b/internal/platform/server.go @@ -34,6 +34,7 @@ func Serve(ctx context.Context, log *slog.Logger, srv *http.Server, health *Heal return srv.Shutdown(sctx) } +// NewHTTPServer returns a server with timeouts that bound slow clients. func NewHTTPServer(addr string, h http.Handler) *http.Server { return &http.Server{ Addr: addr, diff --git a/internal/sealed/sealed.go b/internal/sealed/sealed.go index 7ad1752..4f64df3 100644 --- a/internal/sealed/sealed.go +++ b/internal/sealed/sealed.go @@ -12,6 +12,8 @@ import ( "strings" ) +// ErrUnknownKey is returned for values sealed with a key that was removed +// from the keyring. var ErrUnknownKey = errors.New("sealed: unknown key id") // 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) } +// Open decrypts a value produced by Seal with the same aad. func (k *Keyring) Open(sealed, aad []byte) ([]byte, error) { id, rest, ok := strings.Cut(string(sealed), ":") 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) } +// NeedsReseal reports whether sealed was produced with a retired key and +// should be rewritten. func (k *Keyring) NeedsReseal(sealed []byte) bool { id, _, _ := strings.Cut(string(sealed), ":") return id != k.active diff --git a/internal/tenant/tenant.go b/internal/tenant/tenant.go index 8a10fdc..b9376e7 100644 --- a/internal/tenant/tenant.go +++ b/internal/tenant/tenant.go @@ -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 import ( @@ -21,6 +23,7 @@ type Scope struct { 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} } // 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. func System() Scope { return Scope{system: true} } +// ErrNoScope is returned by Tx for the zero 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 } +// New returns a DB using 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 { if s == (Scope{}) { return ErrNoScope diff --git a/internal/web/web.go b/internal/web/web.go index b3191be..4823f6c 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -1,3 +1,5 @@ +// Package web contains the templ components and static assets shared by +// the console and status pages. package web import ( @@ -12,6 +14,7 @@ import ( //go:embed all:static var static embed.FS +// Static serves the embedded build output of npm run build. func Static() http.FileSystem { sub, err := fs.Sub(static, "static") if err != nil { @@ -20,6 +23,8 @@ func Static() http.FileSystem { 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) { c.Status(status) c.Header("Content-Type", "text/html; charset=utf-8")