From 84f7d51ecfc70b7af91bc11b100d343427811563 Mon Sep 17 00:00:00 2001 From: Ansh Goyal Date: Sun, 22 Nov 2026 17:08:01 +0100 Subject: [PATCH] Namespace Redis keys; read DB user and name from Consul Environments that share a Postgres or Redis server need to keep their data apart. The deploy template hardcoded the database user and name, and every Redis key and the live-update channel used one fixed set of names. store.Redis wraps the client and carries a namespace set once from redis.namespace (or SYNAPSE_REDIS_NAMESPACE). The live publisher and hub, the OAuth token cache, the rate limiter and the Telegram connect flow name their keys and channels through rdb.Name. An empty namespace leaves every name unchanged. The deploy template now reads pg_user and pg_dbname with the same KEY helper as pg_password, and redis_namespace as an optional key. The keys must exist in Consul before this release is deployed, or the render fails at startup. --- cmd/ingest/main.go | 3 +- config.example.yaml | 1 + deploy/config.yaml.ctmpl | 8 ++- e2e/helpers_test.go | 10 ++- e2e/live_publish_test.go | 2 +- e2e/me_cors_test.go | 5 +- e2e/stream_test.go | 7 +- internal/adapter/adapter.go | 4 +- internal/adapter/options.go | 4 +- internal/adapter/telegram/adapter.go | 4 +- internal/adapter/telegram/connect.go | 25 ++++--- internal/adapter/telegram/connect_key_test.go | 25 +++++++ internal/adapter/telegram/ratelimit.go | 4 +- internal/api/router.go | 4 +- internal/config/config.go | 7 +- internal/config/loader.go | 1 + internal/live/hub.go | 11 +-- internal/live/hub_test.go | 13 ++-- internal/live/namespace_test.go | 69 +++++++++++++++++++ internal/live/nudge.go | 7 +- internal/live/publisher.go | 13 ++-- internal/live/publisher_test.go | 16 ++--- internal/oauth/introspect.go | 15 ++-- internal/oauth/introspect_cache_test.go | 40 +++++++++-- internal/ratelimit/ratelimit.go | 10 +-- internal/ratelimit/ratelimit_test.go | 45 ++++++++++++ internal/store/namespace.go | 13 ++++ internal/store/redis.go | 25 ++++++- 28 files changed, 303 insertions(+), 88 deletions(-) create mode 100644 internal/adapter/telegram/connect_key_test.go create mode 100644 internal/live/namespace_test.go create mode 100644 internal/ratelimit/ratelimit_test.go create mode 100644 internal/store/namespace.go diff --git a/cmd/ingest/main.go b/cmd/ingest/main.go index bff5042..8814f99 100644 --- a/cmd/ingest/main.go +++ b/cmd/ingest/main.go @@ -18,7 +18,6 @@ import ( "github.com/metabrainz/synapse/internal/observability" "github.com/metabrainz/synapse/internal/store" "github.com/metabrainz/synapse/internal/store/subscriptions" - "github.com/redis/go-redis/v9" ) func main() { @@ -87,7 +86,7 @@ func main() { fan := fanout.New(cache, adapter.MaxAttemptsFor, reg). WithExpiry(fanout.NewExpiry(cfg.TenantInAppRetentionDays())) // No ping: publishing is best-effort, ingest must not depend on Redis. - rdb := redis.NewClient(&redis.Options{Addr: cfg.Redis.Addr, Password: cfg.Redis.Password, DB: cfg.Redis.DB}) + rdb := store.NewRedisClient(cfg.Redis) defer rdb.Close() consumer := ingest.NewConsumer(pool, fan, reg, live.NewPublisher(rdb)) diff --git a/config.example.yaml b/config.example.yaml index 42b46f4..ddf6d3d 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -14,6 +14,7 @@ redis: addr: localhost:6379 password: "" db: 0 + namespace: "" oauth: client_id: "" diff --git a/deploy/config.yaml.ctmpl b/deploy/config.yaml.ctmpl index 1a0a8c9..9ebfb44 100644 --- a/deploy/config.yaml.ctmpl +++ b/deploy/config.yaml.ctmpl @@ -14,18 +14,20 @@ http: postgres: host: {{ if $pg }}{{ with index $pg 0 }}{{ .Address }}{{ end }}{{ else }}SERVICEDOESNOTEXIST_pgbouncer-master{{ end }} port: {{ if $pg }}{{ with index $pg 0 }}{{ .Port }}{{ end }}{{ else }}0{{ end }} - user: synapse + user: {{ template "KEY" "pg_user" }} password: "{{ template "KEY" "pg_password" }}" - dbname: synapse + dbname: {{ template "KEY" "pg_dbname" }} sslmode: disable pgbouncer: true - direct_dsn: "postgres://synapse:{{ template "KEY" "pg_password" }}@{{ if $pgdirect }}{{ with index $pgdirect 0 }}{{ .Address }}:{{ .Port }}{{ end }}{{ else }}SERVICEDOESNOTEXIST_virtual-postgres-master{{ end }}/synapse?sslmode=disable" + direct_dsn: "postgres://{{ template "KEY" "pg_user" }}:{{ template "KEY" "pg_password" }}@{{ if $pgdirect }}{{ with index $pgdirect 0 }}{{ .Address }}:{{ .Port }}{{ end }}{{ else }}SERVICEDOESNOTEXIST_virtual-postgres-master{{ end }}/{{ template "KEY" "pg_dbname" }}?sslmode=disable" {{ $redis := service "synapse-redis" -}} redis: addr: {{ if $redis }}{{ with index $redis 0 }}{{ .Address }}:{{ .Port }}{{ end }}{{ else }}SERVICEDOESNOTEXIST_synapse-redis{{ end }} password: "" db: 0 + # Environments that share this Redis set a namespace so their keys and channels stay apart. + namespace: "{{ template "OPTKEY" "redis_namespace" }}" {{ $rmq := service "rabbitmq-listenbrainz" -}} rabbitmq: diff --git a/e2e/helpers_test.go b/e2e/helpers_test.go index b3f7fde..7ea6a61 100644 --- a/e2e/helpers_test.go +++ b/e2e/helpers_test.go @@ -17,9 +17,6 @@ import ( "time" "github.com/jackc/pgx/v5/pgxpool" - amqp "github.com/rabbitmq/amqp091-go" - "github.com/redis/go-redis/v9" - "github.com/metabrainz/synapse/internal/adapter" "github.com/metabrainz/synapse/internal/api" "github.com/metabrainz/synapse/internal/broker" @@ -40,6 +37,7 @@ import ( "github.com/metabrainz/synapse/internal/store/usertenant" "github.com/metabrainz/synapse/internal/worker" "github.com/metabrainz/synapse/testutil" + amqp "github.com/rabbitmq/amqp091-go" ) const ( @@ -52,7 +50,7 @@ type env struct { ctx context.Context t *testing.T pool *pgxpool.Pool - rdb *redis.Client + rdb *store.Redis server *httptest.Server amqpURL string apiKey string // static tenant API key for testTenantID @@ -66,7 +64,7 @@ type env struct { // wires the full HTTP router, and returns a ready env. Cleanup is registered via // t.Cleanup in LIFO order: cancel → pool.Close → container teardown. // setup builds the test environment; opts adjust the API config. -func setup(t *testing.T, opts ...func(*api.Config, *redis.Client)) *env { +func setup(t *testing.T, opts ...func(*api.Config, *store.Redis)) *env { t.Helper() ctx, cancel := context.WithCancel(context.Background()) @@ -106,7 +104,7 @@ func setup(t *testing.T, opts ...func(*api.Config, *redis.Client)) *env { t.Fatalf("rabbitmq topology: %v", err) } - rdb, err := store.NewRedis(ctx, config.RedisConfig{Addr: rdbAddr}) + rdb, err := store.NewRedis(ctx, config.RedisConfig{Addr: rdbAddr, Namespace: "e2e"}) if err != nil { t.Fatalf("redis client: %v", err) } diff --git a/e2e/live_publish_test.go b/e2e/live_publish_test.go index 911f7d9..dbb34cb 100644 --- a/e2e/live_publish_test.go +++ b/e2e/live_publish_test.go @@ -15,7 +15,7 @@ import ( func (e *env) subscribe(user string) <-chan live.Nudge { e.t.Helper() - sub := e.rdb.Subscribe(e.ctx, live.Channel(user)) + sub := e.rdb.Subscribe(e.ctx, live.Channel(e.rdb.Namespace, user)) e.t.Cleanup(func() { sub.Close() }) if _, err := sub.Receive(e.ctx); err != nil { e.t.Fatalf("subscribe: %v", err) diff --git a/e2e/me_cors_test.go b/e2e/me_cors_test.go index cbd69f0..08485e9 100644 --- a/e2e/me_cors_test.go +++ b/e2e/me_cors_test.go @@ -7,10 +7,9 @@ import ( "strings" "testing" - "github.com/redis/go-redis/v9" - "github.com/metabrainz/synapse/internal/api" "github.com/metabrainz/synapse/internal/oauth" + "github.com/metabrainz/synapse/internal/store" ) const ( @@ -108,7 +107,7 @@ func TestMeCORSPreflight(t *testing.T) { func TestMeCORSTenantScoped(t *testing.T) { const bbOrigin = "https://bookbrainz.org" // The registry knows only testTenantID; "bookbrainz" exists only in the origins config. - e := setup(t, func(c *api.Config, _ *redis.Client) { + e := setup(t, func(c *api.Config, _ *store.Redis) { c.StreamOrigins = map[string][]string{testTenantID: {lbOrigin}, "bookbrainz": {bbOrigin}} }) tok := e.token("user-a") diff --git a/e2e/stream_test.go b/e2e/stream_test.go index 5155e6c..4c959a7 100644 --- a/e2e/stream_test.go +++ b/e2e/stream_test.go @@ -14,11 +14,10 @@ import ( "testing" "time" - "github.com/redis/go-redis/v9" - "github.com/metabrainz/synapse/internal/api" "github.com/metabrainz/synapse/internal/live" "github.com/metabrainz/synapse/internal/ratelimit" + "github.com/metabrainz/synapse/internal/store" ) const lbOrigin = "https://listenbrainz.org" @@ -251,7 +250,7 @@ func TestStreamIntrospectionDown(t *testing.T) { } func TestStreamOpensAreRateLimited(t *testing.T) { - e := setup(t, func(c *api.Config, rdb *redis.Client) { c.Limiter = ratelimit.New(rdb, 2, 1) }) + e := setup(t, func(c *api.Config, rdb *store.Redis) { c.Limiter = ratelimit.New(rdb, 2, 1) }) tok := e.token("alice") for range 2 { e.openOK(tenantStreamPath, tok) @@ -376,7 +375,7 @@ func TestStreamEndToEnd(t *testing.T) { } func TestStreamDeliversToManyStreams(t *testing.T) { - e := setup(t, func(c *api.Config, _ *redis.Client) { c.StreamLifetime = time.Minute }) + e := setup(t, func(c *api.Config, _ *store.Redis) { c.StreamLifetime = time.Minute }) const users = 2000 got := make([]chan string, users) var wg sync.WaitGroup diff --git a/internal/adapter/adapter.go b/internal/adapter/adapter.go index 570607a..7a18e13 100644 --- a/internal/adapter/adapter.go +++ b/internal/adapter/adapter.go @@ -9,8 +9,8 @@ import ( "github.com/go-chi/chi/v5" "github.com/metabrainz/synapse/internal/fanout" + "github.com/metabrainz/synapse/internal/store" "github.com/metabrainz/synapse/internal/store/userchannels" - "github.com/redis/go-redis/v9" ) // Adapter delivers a single WorkerMessage to its target channel. @@ -31,7 +31,7 @@ type Starter interface { // NewRouter calls MountRoutes once at startup for every registered adapter // that satisfies this interface. type RouteProvider interface { - MountRoutes(r chi.Router, userMW func(http.Handler) http.Handler, rdb *redis.Client, channels *userchannels.Repo) + MountRoutes(r chi.Router, userMW func(http.Handler) http.Handler, rdb *store.Redis, channels *userchannels.Repo) } // ConfigValidator is implemented by adapters that can validate a proposed channel diff --git a/internal/adapter/options.go b/internal/adapter/options.go index 31cbd74..f7624c3 100644 --- a/internal/adapter/options.go +++ b/internal/adapter/options.go @@ -2,7 +2,7 @@ package adapter import ( "github.com/metabrainz/synapse/internal/eventtype" - "github.com/redis/go-redis/v9" + "github.com/metabrainz/synapse/internal/store" ) // TelegramOptions configures the Telegram adapter. @@ -33,7 +33,7 @@ type Options struct { Webhook WebhookOptions Telegram TelegramOptions MailService MailServiceOptions - Redis *redis.Client + Redis *store.Redis // Registry supplies event templates to the Telegram adapter. Registry *eventtype.Registry } diff --git a/internal/adapter/telegram/adapter.go b/internal/adapter/telegram/adapter.go index 9ed5b5b..e22d4da 100644 --- a/internal/adapter/telegram/adapter.go +++ b/internal/adapter/telegram/adapter.go @@ -9,7 +9,7 @@ import ( "github.com/metabrainz/synapse/internal/eventtype" "github.com/metabrainz/synapse/internal/fanout" - "github.com/redis/go-redis/v9" + "github.com/metabrainz/synapse/internal/store" ) type channelConfig struct { @@ -29,7 +29,7 @@ type Adapter struct { // New creates the Telegram adapter. // rdb may be nil; when nil, the per-chat and global rate limit pre-checks are // skipped (the adapter still handles 429 responses from the API gracefully). -func New(botToken, webhookURL, webhookSecret string, rdb *redis.Client, reg *eventtype.Registry) *Adapter { +func New(botToken, webhookURL, webhookSecret string, rdb *store.Redis, reg *eventtype.Registry) *Adapter { a := &Adapter{ bot: NewBot(botToken), webhookURL: webhookURL, diff --git a/internal/adapter/telegram/connect.go b/internal/adapter/telegram/connect.go index 7576f1d..9b2bc7c 100644 --- a/internal/adapter/telegram/connect.go +++ b/internal/adapter/telegram/connect.go @@ -13,8 +13,8 @@ import ( "github.com/go-chi/chi/v5" "github.com/metabrainz/synapse/internal/api/middleware" + "github.com/metabrainz/synapse/internal/store" "github.com/metabrainz/synapse/internal/store/userchannels" - "github.com/redis/go-redis/v9" ) const ( @@ -27,13 +27,18 @@ const ( type connectHandler struct { bot *Bot - rdb *redis.Client + rdb *store.Redis channels *userchannels.Repo secret string } -func connectKey(token string) string { return "synapse:tg:connect:" + token } -func connectDoneKey(token string) string { return "synapse:tg:connect:done:" + token } +func (h *connectHandler) connectKey(token string) string { + return h.rdb.Name("synapse:tg:connect:" + token) +} + +func (h *connectHandler) connectDoneKey(token string) string { + return h.rdb.Name("synapse:tg:connect:done:" + token) +} func writeJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") @@ -56,7 +61,7 @@ func requireUser(w http.ResponseWriter, r *http.Request) (string, bool) { // MountRoutes registers the Telegram connect flow under the given root router. // It is a no-op if the adapter has no bot configured. -func (a *Adapter) MountRoutes(r chi.Router, userMW func(http.Handler) http.Handler, rdb *redis.Client, channels *userchannels.Repo) { +func (a *Adapter) MountRoutes(r chi.Router, userMW func(http.Handler) http.Handler, rdb *store.Redis, channels *userchannels.Repo) { if a.bot == nil { return } @@ -84,7 +89,7 @@ func (h *connectHandler) initiate(w http.ResponseWriter, req *http.Request) { token := hex.EncodeToString(raw) ctx := req.Context() - if err := h.rdb.Set(ctx, connectKey(token), uid, connectTTL).Err(); err != nil { + if err := h.rdb.Set(ctx, h.connectKey(token), uid, connectTTL).Err(); err != nil { writeError(w, http.StatusInternalServerError, "token storage failed") return } @@ -113,12 +118,12 @@ func (h *connectHandler) status(w http.ResponseWriter, req *http.Request) { token := chi.URLParam(req, "token") ctx := req.Context() - if owner, err := h.rdb.Get(ctx, connectKey(token)).Result(); err == nil && owner != uid { + if owner, err := h.rdb.Get(ctx, h.connectKey(token)).Result(); err == nil && owner != uid { writeError(w, http.StatusForbidden, "token does not belong to this user") return } - channelID, err := h.rdb.Get(ctx, connectDoneKey(token)).Result() + channelID, err := h.rdb.Get(ctx, h.connectDoneKey(token)).Result() if err != nil { writeJSON(w, http.StatusOK, map[string]string{"status": "pending"}) return @@ -177,7 +182,7 @@ func (h *connectHandler) webhook(w http.ResponseWriter, req *http.Request) { } func (h *connectHandler) handleConnect(ctx context.Context, chatID, token, firstName string) { - userID, err := h.rdb.GetDel(ctx, connectKey(token)).Result() + userID, err := h.rdb.GetDel(ctx, h.connectKey(token)).Result() if err != nil { _ = h.bot.Send(ctx, chatID, "This link has expired or is invalid. Please generate a new one from the Synapse UI.") return @@ -200,6 +205,6 @@ func (h *connectHandler) handleConnect(ctx context.Context, chatID, token, first return } - h.rdb.Set(ctx, connectDoneKey(token), strconv.FormatInt(channelID, 10), connectTTL) + h.rdb.Set(ctx, h.connectDoneKey(token), strconv.FormatInt(channelID, 10), connectTTL) _ = h.bot.Send(ctx, chatID, "✓ Connected! You'll receive Synapse notifications here.") } diff --git a/internal/adapter/telegram/connect_key_test.go b/internal/adapter/telegram/connect_key_test.go new file mode 100644 index 0000000..0eb70df --- /dev/null +++ b/internal/adapter/telegram/connect_key_test.go @@ -0,0 +1,25 @@ +package telegram + +import ( + "testing" + + "github.com/metabrainz/synapse/internal/store" +) + +func TestConnectKeysFollowTheNamespace(t *testing.T) { + plain := &connectHandler{rdb: &store.Redis{}} + if got := plain.connectKey("tok"); got != "synapse:tg:connect:tok" { + t.Errorf("connectKey = %q", got) + } + if got := plain.connectDoneKey("tok"); got != "synapse:tg:connect:done:tok" { + t.Errorf("connectDoneKey = %q", got) + } + + ns := &connectHandler{rdb: &store.Redis{Namespace: "test"}} + if got := ns.connectKey("tok"); got != "test:synapse:tg:connect:tok" { + t.Errorf("namespaced connectKey = %q", got) + } + if got := ns.connectDoneKey("tok"); got != "test:synapse:tg:connect:done:tok" { + t.Errorf("namespaced connectDoneKey = %q", got) + } +} diff --git a/internal/adapter/telegram/ratelimit.go b/internal/adapter/telegram/ratelimit.go index 84873c7..8c9fae3 100644 --- a/internal/adapter/telegram/ratelimit.go +++ b/internal/adapter/telegram/ratelimit.go @@ -20,7 +20,7 @@ import ( "github.com/metabrainz/synapse/internal/fanout" "github.com/metabrainz/synapse/internal/ratelimit" - "github.com/redis/go-redis/v9" + "github.com/metabrainz/synapse/internal/store" ) const ( @@ -33,7 +33,7 @@ type rateLimiter struct { global *ratelimit.Limiter // burst=30, rate=30/s — key: synapse:rl:tg:global } -func newRateLimiter(rdb *redis.Client) *rateLimiter { +func newRateLimiter(rdb *store.Redis) *rateLimiter { return &rateLimiter{ perChat: ratelimit.New(rdb, perChatRate, perChatRate), global: ratelimit.New(rdb, globalRate, globalRate), diff --git a/internal/api/router.go b/internal/api/router.go index cbe5cc5..d9823e3 100644 --- a/internal/api/router.go +++ b/internal/api/router.go @@ -21,13 +21,13 @@ import ( "github.com/metabrainz/synapse/internal/live" "github.com/metabrainz/synapse/internal/oauth" "github.com/metabrainz/synapse/internal/ratelimit" + "github.com/metabrainz/synapse/internal/store" "github.com/metabrainz/synapse/internal/store/notifications" "github.com/metabrainz/synapse/internal/store/preferences" "github.com/metabrainz/synapse/internal/store/userchannels" "github.com/metabrainz/synapse/internal/store/usereventsubs" "github.com/metabrainz/synapse/internal/store/users" "github.com/metabrainz/synapse/internal/store/usertenant" - "github.com/redis/go-redis/v9" ) // HealthChecks holds optional probe functions for /health/ready. @@ -51,7 +51,7 @@ type Config struct { // Deps bundles the data-layer dependencies injected into the router. type Deps struct { Pool *pgxpool.Pool - Redis *redis.Client + Redis *store.Redis Users *users.Repo UserChannels *userchannels.Repo TenantMappings *usertenant.Repo diff --git a/internal/config/config.go b/internal/config/config.go index 96802af..0f36ceb 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -94,9 +94,10 @@ func (c PostgresConfig) URL() string { } type RedisConfig struct { - Addr string `yaml:"addr"` - Password string `yaml:"password"` - DB int `yaml:"db"` + Addr string `yaml:"addr"` + Password string `yaml:"password"` + DB int `yaml:"db"` + Namespace string `yaml:"namespace"` } type RabbitMQConfig struct { diff --git a/internal/config/loader.go b/internal/config/loader.go index fd2b48c..7e7296c 100644 --- a/internal/config/loader.go +++ b/internal/config/loader.go @@ -158,6 +158,7 @@ func applyEnv(cfg *Config) error { str(&cfg.Postgres.DBName, "SYNAPSE_PG_DBNAME") str(&cfg.Postgres.DirectDSN, "SYNAPSE_PG_DIRECT_DSN") str(&cfg.Redis.Addr, "SYNAPSE_REDIS_ADDR") + str(&cfg.Redis.Namespace, "SYNAPSE_REDIS_NAMESPACE") str(&cfg.RabbitMQ.URL, "SYNAPSE_RABBITMQ_URL") str(&cfg.OAuth.ClientID, "SYNAPSE_OAUTH_CLIENT_ID") str(&cfg.OAuth.ClientSecret, "SYNAPSE_OAUTH_CLIENT_SECRET") diff --git a/internal/live/hub.go b/internal/live/hub.go index d0d4383..e7e4dc1 100644 --- a/internal/live/hub.go +++ b/internal/live/hub.go @@ -9,6 +9,7 @@ import ( "sync" "time" + "github.com/metabrainz/synapse/internal/store" "github.com/redis/go-redis/v9" ) @@ -34,7 +35,7 @@ type userStreams struct { // Hub fans nudges from one shared Redis PubSub connection out to this // instance's open streams. Maps are keyed by Redis channel name. type Hub struct { - rdb *redis.Client + rdb *store.Redis mu sync.Mutex ps *redis.PubSub @@ -47,16 +48,16 @@ type Hub struct { // NewHub gives the hub its own Redis client pinned to RESP2. With go-redis's // default RESP3, the hub lost nudges once thousands of users had streams open. -func NewHub(rdb *redis.Client) *Hub { +func NewHub(rdb *store.Redis) *Hub { o := rdb.Options() - sub := redis.NewClient(&redis.Options{ + sub := store.WrapRedis(redis.NewClient(&redis.Options{ Addr: o.Addr, Username: o.Username, Password: o.Password, DB: o.DB, TLSConfig: o.TLSConfig, Protocol: 2, - }) + }), rdb.Namespace) return &Hub{ rdb: sub, ps: sub.Subscribe(context.Background()), @@ -132,7 +133,7 @@ func (h *Hub) Run(ctx context.Context) { // Register returns once Redis has confirmed the user's subscription, so a // nudge published after it returns is delivered. func (h *Hub) Register(ctx context.Context, userID string) (<-chan Nudge, func(), error) { - channel := Channel(userID) + channel := Channel(h.rdb.Namespace, userID) h.mu.Lock() if h.closed { diff --git a/internal/live/hub_test.go b/internal/live/hub_test.go index 9fb7e97..b9ebcfc 100644 --- a/internal/live/hub_test.go +++ b/internal/live/hub_test.go @@ -9,12 +9,11 @@ import ( "testing" "time" - "github.com/redis/go-redis/v9" - "github.com/metabrainz/synapse/internal/live" + "github.com/metabrainz/synapse/internal/store" ) -func startHub(t *testing.T) (*redis.Client, *live.Hub, *live.Publisher) { +func startHub(t *testing.T) (*store.Redis, *live.Hub, *live.Publisher) { t.Helper() rdb := startRedis(t) hub := live.NewHub(rdb) @@ -42,16 +41,16 @@ func register(t *testing.T, hub *live.Hub, user string) (<-chan live.Nudge, func return ch, unregister } -func numSub(t *testing.T, rdb *redis.Client, user string) int64 { +func numSub(t *testing.T, rdb *store.Redis, user string) int64 { t.Helper() - res, err := rdb.PubSubNumSub(context.Background(), live.Channel(user)).Result() + res, err := rdb.PubSubNumSub(context.Background(), live.Channel("", user)).Result() if err != nil { t.Fatalf("numsub: %v", err) } - return res[live.Channel(user)] + return res[live.Channel("", user)] } -func waitNumSub(t *testing.T, rdb *redis.Client, user string, want int64) { +func waitNumSub(t *testing.T, rdb *store.Redis, user string, want int64) { t.Helper() deadline := time.Now().Add(2 * time.Second) for { diff --git a/internal/live/namespace_test.go b/internal/live/namespace_test.go new file mode 100644 index 0000000..7b39b46 --- /dev/null +++ b/internal/live/namespace_test.go @@ -0,0 +1,69 @@ +//go:build integration + +package live_test + +import ( + "context" + "testing" + "time" + + "github.com/metabrainz/synapse/internal/live" + "github.com/metabrainz/synapse/internal/store" +) + +func TestPublishGoesToTheNamespacedChannel(t *testing.T) { + rdb := startRedis(t) + plain := subscribe(t, rdb, "alice") // the un-namespaced channel + + sub := rdb.Subscribe(context.Background(), live.Channel("test", "alice")) + t.Cleanup(func() { sub.Close() }) + if _, err := sub.Receive(context.Background()); err != nil { + t.Fatalf("subscribe: %v", err) + } + + live.NewPublisher(store.WrapRedis(rdb.Client, "test")).Publish(context.Background(), "alice", live.Nudge{Kind: live.KindChanged, Tenant: "t"}) + + expect(t, sub.Channel(), `{"kind":"changed","tenant":"t"}`) + select { + case m := <-plain: + t.Fatalf("un-namespaced subscriber got %s", m.Payload) + case <-time.After(300 * time.Millisecond): + } +} + +func TestHubOnlyHearsItsOwnNamespace(t *testing.T) { + rdb := startRedis(t) + hub := live.NewHub(store.WrapRedis(rdb.Client, "a")) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + hub.Run(ctx) + close(done) + }() + t.Cleanup(func() { + cancel() + <-done + }) + nudges, unregister := register(t, hub, "alice") + defer unregister() + + nudge := live.Nudge{Kind: live.KindCreated, Tenant: "t"} + for _, ns := range []store.Namespace{"b", ""} { + live.NewPublisher(store.WrapRedis(rdb.Client, ns)).Publish(context.Background(), "alice", nudge) + } + select { + case n := <-nudges: + t.Fatalf("got a nudge from another namespace: %+v", n) + case <-time.After(300 * time.Millisecond): + } + + live.NewPublisher(store.WrapRedis(rdb.Client, "a")).Publish(context.Background(), "alice", nudge) + select { + case n := <-nudges: + if n != nudge { + t.Fatalf("nudge = %+v, want %+v", n, nudge) + } + case <-time.After(3 * time.Second): + t.Fatal("no nudge from the hub's own namespace") + } +} diff --git a/internal/live/nudge.go b/internal/live/nudge.go index 3743187..85e6cfc 100644 --- a/internal/live/nudge.go +++ b/internal/live/nudge.go @@ -1,5 +1,7 @@ package live +import "github.com/metabrainz/synapse/internal/store" + type Kind string const ( @@ -13,6 +15,7 @@ type Nudge struct { Tenant string `json:"tenant"` } -func Channel(userID string) string { - return "synapse:inbox:" + userID +// Channel is the user's pub/sub channel inside a Redis namespace. +func Channel(ns store.Namespace, userID string) string { + return ns.Name("synapse:inbox:" + userID) } diff --git a/internal/live/publisher.go b/internal/live/publisher.go index 4a63aa7..dd75d90 100644 --- a/internal/live/publisher.go +++ b/internal/live/publisher.go @@ -6,6 +6,7 @@ import ( "log/slog" "time" + "github.com/metabrainz/synapse/internal/store" "github.com/redis/go-redis/v9" ) @@ -15,21 +16,21 @@ const ( ) type Publisher struct { - rdb *redis.Client + rdb *store.Redis } // NewPublisher opens its own client so publishTimeout bounds socket I/O without // changing timeouts for the other users of rdb. -func NewPublisher(rdb *redis.Client) *Publisher { +func NewPublisher(rdb *store.Redis) *Publisher { o := rdb.Options() - return &Publisher{rdb: redis.NewClient(&redis.Options{ + return &Publisher{rdb: store.WrapRedis(redis.NewClient(&redis.Options{ Addr: o.Addr, Username: o.Username, Password: o.Password, DB: o.DB, TLSConfig: o.TLSConfig, ContextTimeoutEnabled: true, - })} + }), rdb.Namespace)} } type Target struct { @@ -44,7 +45,7 @@ func (p *Publisher) Publish(ctx context.Context, userID string, n Nudge) { defer cancel() payload, _ := json.Marshal(n) - if err := p.rdb.Publish(ctx, Channel(userID), payload).Err(); err != nil { + if err := p.rdb.Publish(ctx, Channel(p.rdb.Namespace, userID), payload).Err(); err != nil { slog.Warn("live: publish failed", "user", userID, "err", err) } } @@ -68,7 +69,7 @@ func (p *Publisher) publishChunk(ctx context.Context, chunk []Target) error { pipe := p.rdb.Pipeline() for _, t := range chunk { payload, _ := json.Marshal(t.Nudge) - pipe.Publish(ctx, Channel(t.UserID), payload) + pipe.Publish(ctx, Channel(p.rdb.Namespace, t.UserID), payload) } _, err := pipe.Exec(ctx) return err diff --git a/internal/live/publisher_test.go b/internal/live/publisher_test.go index 9299899..12bbd7c 100644 --- a/internal/live/publisher_test.go +++ b/internal/live/publisher_test.go @@ -8,34 +8,34 @@ import ( "testing" "time" - "github.com/redis/go-redis/v9" - "github.com/metabrainz/synapse/internal/live" + "github.com/metabrainz/synapse/internal/store" "github.com/metabrainz/synapse/testutil" + "github.com/redis/go-redis/v9" ) -func startRedis(t *testing.T) *redis.Client { +func startRedis(t *testing.T) *store.Redis { t.Helper() addr, cleanup, err := testutil.StartRedis(context.Background()) if err != nil { t.Fatalf("start redis: %v", err) } t.Cleanup(cleanup) - rdb := redis.NewClient(&redis.Options{Addr: addr}) + rdb := store.WrapRedis(redis.NewClient(&redis.Options{Addr: addr}), "") t.Cleanup(func() { rdb.Close() }) return rdb } -func deadRedis(t *testing.T) *redis.Client { +func deadRedis(t *testing.T) *store.Redis { t.Helper() - rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:1", MaxRetries: -1}) + rdb := store.WrapRedis(redis.NewClient(&redis.Options{Addr: "127.0.0.1:1", MaxRetries: -1}), "") t.Cleanup(func() { rdb.Close() }) return rdb } -func subscribe(t *testing.T, rdb *redis.Client, user string) <-chan *redis.Message { +func subscribe(t *testing.T, rdb *store.Redis, user string) <-chan *redis.Message { t.Helper() - sub := rdb.Subscribe(context.Background(), live.Channel(user)) + sub := rdb.Subscribe(context.Background(), live.Channel("", user)) t.Cleanup(func() { sub.Close() }) if _, err := sub.Receive(context.Background()); err != nil { t.Fatalf("subscribe: %v", err) diff --git a/internal/oauth/introspect.go b/internal/oauth/introspect.go index d24ae15..11c3789 100644 --- a/internal/oauth/introspect.go +++ b/internal/oauth/introspect.go @@ -14,6 +14,7 @@ import ( "strings" "time" + "github.com/metabrainz/synapse/internal/store" "github.com/redis/go-redis/v9" ) @@ -54,12 +55,12 @@ type MBIntrospector struct { clientID string clientSecret string endpoint string - rdb *redis.Client + rdb *store.Redis httpClient *http.Client } // NewMBIntrospector constructs a MBIntrospector. -func NewMBIntrospector(clientID, clientSecret, endpoint string, rdb *redis.Client) *MBIntrospector { +func NewMBIntrospector(clientID, clientSecret, endpoint string, rdb *store.Redis) *MBIntrospector { return &MBIntrospector{ clientID: clientID, clientSecret: clientSecret, @@ -69,9 +70,9 @@ func NewMBIntrospector(clientID, clientSecret, endpoint string, rdb *redis.Clien } } -func cacheKey(token string) string { +func (m *MBIntrospector) cacheKey(token string) string { h := sha256.Sum256([]byte(token)) - return "oauth:token:" + hex.EncodeToString(h[:]) + return m.rdb.Name("oauth:token:" + hex.EncodeToString(h[:])) } // Introspect validates the given token against the MetaBrainz introspection endpoint. @@ -79,7 +80,7 @@ func cacheKey(token string) string { // or a wrapped error for network/protocol failures. func (m *MBIntrospector) Introspect(ctx context.Context, token string) (Claims, error) { if m.rdb != nil { - if cached, err := m.rdb.Get(ctx, cacheKey(token)).Result(); err == nil { + if cached, err := m.rdb.Get(ctx, m.cacheKey(token)).Result(); err == nil { if cached == "" { return Claims{}, ErrInactive } @@ -126,7 +127,7 @@ func (m *MBIntrospector) Introspect(ctx context.Context, token string) (Claims, if !ir.Active || (ir.ExpiresAt > 0 && time.Now().Unix() > ir.ExpiresAt) || ir.Sub == "" || ir.Sub == "-1" { if m.rdb != nil { - if err := m.rdb.Set(ctx, cacheKey(token), "", 30*time.Second).Err(); err != nil { + if err := m.rdb.Set(ctx, m.cacheKey(token), "", 30*time.Second).Err(); err != nil { slog.Warn("oauth: redis cache write failed", "err", err) } } @@ -149,7 +150,7 @@ func (m *MBIntrospector) Introspect(ctx context.Context, token string) (Claims, } if ttl > 0 { b, _ := json.Marshal(claims) - if err := m.rdb.Set(ctx, cacheKey(token), b, ttl).Err(); err != nil { + if err := m.rdb.Set(ctx, m.cacheKey(token), b, ttl).Err(); err != nil { slog.Warn("oauth: redis cache write failed", "err", err) } } diff --git a/internal/oauth/introspect_cache_test.go b/internal/oauth/introspect_cache_test.go index a43161c..85aef51 100644 --- a/internal/oauth/introspect_cache_test.go +++ b/internal/oauth/introspect_cache_test.go @@ -10,10 +10,10 @@ import ( "testing" "time" - "github.com/redis/go-redis/v9" - "github.com/metabrainz/synapse/internal/oauth" + "github.com/metabrainz/synapse/internal/store" "github.com/metabrainz/synapse/testutil" + "github.com/redis/go-redis/v9" ) func TestMBIntrospector_CacheCappedAt15Minutes(t *testing.T) { @@ -36,7 +36,7 @@ func TestMBIntrospector_CacheCappedAt15Minutes(t *testing.T) { })) defer ts.Close() - i := oauth.NewMBIntrospector("client-id", "client-secret", ts.URL, rdb) + i := oauth.NewMBIntrospector("client-id", "client-secret", ts.URL, store.WrapRedis(rdb, "")) if _, err := i.Introspect(ctx, "valid-token"); err != nil { t.Fatalf("introspect: %v", err) } @@ -76,7 +76,7 @@ func TestMBIntrospector_CacheKeepsScope(t *testing.T) { })) defer ts.Close() - i := oauth.NewMBIntrospector("client-id", "client-secret", ts.URL, rdb) + i := oauth.NewMBIntrospector("client-id", "client-secret", ts.URL, store.WrapRedis(rdb, "")) want := oauth.Claims{ID: "42", Username: "testuser", Inbox: true} for range 2 { if got, err := i.Introspect(ctx, "inbox-token"); err != nil || got != want { @@ -87,3 +87,35 @@ func TestMBIntrospector_CacheKeepsScope(t *testing.T) { t.Fatalf("want 1 introspection call, got %d", calls) } } + +func TestMBIntrospector_CacheKeyFollowsNamespace(t *testing.T) { + ctx := context.Background() + addr, cleanup, err := testutil.StartRedis(ctx) + if err != nil { + t.Fatalf("start redis: %v", err) + } + t.Cleanup(cleanup) + rdb := redis.NewClient(&redis.Options{Addr: addr}) + t.Cleanup(func() { rdb.Close() }) + + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(map[string]any{ + "active": true, + "sub": "42", + "username": "testuser", + "expires_at": time.Now().Add(time.Hour).Unix(), + }) + })) + defer ts.Close() + + i := oauth.NewMBIntrospector("client-id", "client-secret", ts.URL, store.WrapRedis(rdb, "test")) + if _, err := i.Introspect(ctx, "valid-token"); err != nil { + t.Fatalf("introspect: %v", err) + } + if keys, _ := rdb.Keys(ctx, "test:oauth:token:*").Result(); len(keys) != 1 { + t.Fatalf("want one key under the namespace, got %v", keys) + } + if keys, _ := rdb.Keys(ctx, "oauth:token:*").Result(); len(keys) != 0 { + t.Fatalf("token cached outside the namespace: %v", keys) + } +} diff --git a/internal/ratelimit/ratelimit.go b/internal/ratelimit/ratelimit.go index 4e9f589..cd7d456 100644 --- a/internal/ratelimit/ratelimit.go +++ b/internal/ratelimit/ratelimit.go @@ -10,6 +10,7 @@ import ( "net/http" "time" + "github.com/metabrainz/synapse/internal/store" "github.com/redis/go-redis/v9" ) @@ -52,21 +53,22 @@ return 1 `) type Limiter struct { - rdb *redis.Client + rdb *store.Redis burst int rate int // tokens per second } // New creates a token bucket limiter. burst is max concurrent tokens; ratePerSec is sustained fill rate. -func New(rdb *redis.Client, burst, ratePerSec int) *Limiter { +func New(rdb *store.Redis, burst, ratePerSec int) *Limiter { return &Limiter{rdb: rdb, burst: burst, rate: ratePerSec} } // AllowKey runs the token bucket against an arbitrary Redis key. -// Use this when the caller manages its own key namespace (e.g. adapter-level limiters). +// Use this when the caller manages its own key names (e.g. adapter-level limiters). +// The Limiter's Redis namespace is applied on top. func (l *Limiter) AllowKey(ctx context.Context, key string) (bool, error) { nowNs := time.Now().UnixNano() - result, err := tokenBucketScript.Run(ctx, l.rdb, []string{key}, + result, err := tokenBucketScript.Run(ctx, l.rdb, []string{l.rdb.Name(key)}, l.burst, l.rate, nowNs, ).Int() if err != nil { diff --git a/internal/ratelimit/ratelimit_test.go b/internal/ratelimit/ratelimit_test.go new file mode 100644 index 0000000..9a47823 --- /dev/null +++ b/internal/ratelimit/ratelimit_test.go @@ -0,0 +1,45 @@ +//go:build integration + +package ratelimit_test + +import ( + "context" + "testing" + + "github.com/metabrainz/synapse/internal/ratelimit" + "github.com/metabrainz/synapse/internal/store" + "github.com/metabrainz/synapse/testutil" + "github.com/redis/go-redis/v9" +) + +func TestBucketsStayInsideTheirNamespace(t *testing.T) { + ctx := context.Background() + addr, cleanup, err := testutil.StartRedis(ctx) + if err != nil { + t.Fatalf("start redis: %v", err) + } + t.Cleanup(cleanup) + rdb := redis.NewClient(&redis.Options{Addr: addr}) + t.Cleanup(func() { rdb.Close() }) + + // burst 1: a second request in the same bucket is refused. + a := ratelimit.New(store.WrapRedis(rdb, "a"), 1, 1) + b := ratelimit.New(store.WrapRedis(rdb, "b"), 1, 1) + for name, l := range map[string]*ratelimit.Limiter{"a": a, "b": b} { + if ok, err := l.Allow(ctx, "tenant"); err != nil || !ok { + t.Fatalf("%s: first request = %v, %v; want allowed", name, ok, err) + } + } + if ok, _ := a.Allow(ctx, "tenant"); ok { + t.Fatal("namespace a: second request allowed, so the bucket was not used") + } + + for _, key := range []string{"a:synapse:rl:tenant", "b:synapse:rl:tenant"} { + if n, _ := rdb.Exists(ctx, key).Result(); n != 1 { + t.Errorf("key %s not found", key) + } + } + if n, _ := rdb.Exists(ctx, "synapse:rl:tenant").Result(); n != 0 { + t.Error("un-namespaced key was written") + } +} diff --git a/internal/store/namespace.go b/internal/store/namespace.go new file mode 100644 index 0000000..1d85184 --- /dev/null +++ b/internal/store/namespace.go @@ -0,0 +1,13 @@ +package store + +// Namespace keeps environments that share a Redis server apart by prefixing +// every key and pub/sub channel name. The zero value leaves names unchanged. +type Namespace string + +// Name returns name inside the namespace. +func (n Namespace) Name(name string) string { + if n == "" { + return name + } + return string(n) + ":" + name +} diff --git a/internal/store/redis.go b/internal/store/redis.go index 397e0b4..aa96a61 100644 --- a/internal/store/redis.go +++ b/internal/store/redis.go @@ -8,12 +8,31 @@ import ( "github.com/redis/go-redis/v9" ) -func NewRedis(ctx context.Context, cfg config.RedisConfig) (*redis.Client, error) { - rdb := redis.NewClient(&redis.Options{ +// Redis is the shared client. It carries the environment's Namespace, set once +// from config, so every component that gets the client names its keys and +// channels with rdb.Name and none has to be told the namespace separately. +type Redis struct { + *redis.Client + Namespace +} + +// NewRedisClient builds the client without connecting. +func NewRedisClient(cfg config.RedisConfig) *Redis { + return WrapRedis(redis.NewClient(&redis.Options{ Addr: cfg.Addr, Password: cfg.Password, DB: cfg.DB, - }) + }), Namespace(cfg.Namespace)) +} + +// WrapRedis puts a namespace on an existing client, e.g. one derived with +// different timeouts or one made for a test. +func WrapRedis(c *redis.Client, ns Namespace) *Redis { + return &Redis{Client: c, Namespace: ns} +} + +func NewRedis(ctx context.Context, cfg config.RedisConfig) (*Redis, error) { + rdb := NewRedisClient(cfg) if err := rdb.Ping(ctx).Err(); err != nil { rdb.Close()