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:
1 parent
048e114fd9
commit
d20225982a
21 files changed
+147
-36
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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) }
|
||||
@@ -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 {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user