Files
uptimesebi/internal/platform/run.go
T
Sebastian UnterschützandClaude Opus 5.5 ccc0fe58b8 feat(tenant): enforce tenant isolation with row-level security
Every query runs inside a transaction carrying app.org_id, app.user_id
or the explicit system scope. Without a scope no rows are visible.

Closes #2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-21 23:48:02 +01:00

76 lines
1.8 KiB
Go

package platform
import (
"context"
"fmt"
"log/slog"
"os"
"os/signal"
"syscall"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
)
type Deps struct {
Log *slog.Logger
DB *pgxpool.Pool
Redis *redis.Client
}
func (d *Deps) Close() {
if d.DB != nil {
d.DB.Close()
}
if d.Redis != nil {
_ = d.Redis.Close()
}
}
func (d *Deps) Probes() map[string]Probe {
return map[string]Probe{
"postgres": func(ctx context.Context) error { return d.DB.Ping(ctx) },
"redis": func(ctx context.Context) error { return d.Redis.Ping(ctx).Err() },
}
}
func SignalContext() (context.Context, context.CancelFunc) {
return signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
}
func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, error) {
if err := c.Validate(); err != nil {
return nil, err
}
pending, err := migrations.Pending(ctx, c.DatabaseURL)
if err != nil {
return nil, err
}
if pending {
return nil, fmt.Errorf("database schema is behind this release, run \"api migrate up\" first")
}
d := &Deps{Log: log}
if d.DB, err = OpenPostgres(ctx, c.DatabaseURL); err != nil {
return nil, err
}
if d.Redis, err = OpenRedis(ctx, c); err != nil {
d.Close()
return nil, err
}
warnIfRLSBypassed(ctx, d)
return d, nil
}
// warnIfRLSBypassed flags deployments where tenant isolation silently degrades
// to application-level filtering only.
func warnIfRLSBypassed(ctx context.Context, d *Deps) {
var bypass bool
err := d.DB.QueryRow(ctx, `SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user`).Scan(&bypass)
if err == nil && bypass {
d.Log.Warn("database role bypasses row-level security; connect as a non-superuser role without BYPASSRLS")
}
}