The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Rate-limit new-device login emails per user to protect SMTP budget (#73031)
Ngoc Khuat942e35fd9265
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 2b1f13ff746..f0b8dc31e9d 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1148,6 +1148,7 @@metabase.login-history.init}:uses #{analyticsapi+ app-dbchannelrequestsettingsdiff --git a/src/metabase/login_history/models/login_history.clj b/src/metabase/login_history/models/login_history.cljindex d2b0e6db700..9efe0a6cca4 100644--- a/src/metabase/login_history/models/login_history.clj+++ b/src/metabase/login_history/models/login_history.clj@@ -1,8 +1,11 @@(ns metabase.login-history.models.login-history(:require[java-time.api :as t]+ [metabase.app-db.core :as mdb]+ [metabase.login-history.settings :as login-history.settings][metabase.request.core :as request][metabase.util.date-2 :as u.date]+ [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :as i18n :refer [tru]][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]@@ -75,5 +78,28 @@count(= 1)))+(def ^:private new-device-email-rate-limit-window-hours 24)++(defn too-many-new-device-emails-recently?+ "Per-user circuit breaker — true if this user has already triggered+ `new-device-email-rate-limit-cap` first-time `(user_id, device_id)` events in the last+ window. Over-counts first-login-ever rows (those never email) — safe direction for a+ breaker."+ [user-id]+ (let [cutoff (h2x/add-interval-honeysql-form+ (mdb/db-type) :%now (- new-device-email-rate-limit-window-hours) :hour)]+ (> (t2/count :model/LoginHistory+ {:where [:and+ [:= :user_id user-id]+ [:> :timestamp cutoff]+ [:not [:exists+ {:select [1]+ :from [[:login_history :lh2]]+ :where [:and+ [:= :lh2.user_id :login_history.user_id]+ [:= :lh2.device_id :login_history.device_id]+ [:< :lh2.id :login_history.id]]}]]]})+ (login-history.settings/new-device-email-rate-limit-cap))))+(t2/define-before-update :model/LoginHistory [_login-history](throw (RuntimeException. (tru "You can''t update a LoginHistory after it has been created."))))diff --git a/src/metabase/login_history/record.clj b/src/metabase/login_history/record.cljindex 0988ffd54c0..b646beed511 100644--- a/src/metabase/login_history/record.clj+++ b/src/metabase/login_history/record.clj@@ -16,7 +16,8 @@[history-record](when (and (login-history.settings/send-email-on-first-login-from-new-device)(login-history/first-login-on-this-device? history-record)- (not (login-history/first-login-ever? history-record)))+ (not (login-history/first-login-ever? history-record))+ (not (login-history/too-many-new-device-emails-recently? (:user_id history-record))));; if there's an existing open connection (and there seems to be one, but I'm not 100% sure why) we can't try to use;; it across threads since it can close at any moment! So unbind it so the future can get its own thread.(binding [t2.conn/*current-connectable* nil]diff --git a/src/metabase/login_history/settings.clj b/src/metabase/login_history/settings.cljindex c3f4892289a..ffdd8a3a735 100644--- a/src/metabase/login_history/settings.clj+++ b/src/metabase/login_history/settings.clj@@ -13,3 +13,15 @@:default true:doc "This variable also controls the geocoding service that Metabase uses to know the location of your logged in users.Setting this variable to false also disables this reverse geocoding functionality.")++(defsetting new-device-email-rate-limit-cap+ "Maximum number of new-device login emails to send per user per day. Circuit breaker that+ protects the instance's shared SMTP budget (alerts, subscriptions, password resets) from+ being drained by cookie-churn patterns — typically a single user in an incognito loop or+ behind a broken embed integration that keeps minting new device_ids. Env-only so an+ attacker with admin creds cannot disable it."+ :type :integer+ :visibility :internal+ :setter :none+ :export? false+ :default 10)diff --git a/test/metabase/login_history/models/login_history_test.clj b/test/metabase/login_history/models/login_history_test.cljindex db5745043d4..27008a6b34f 100644--- a/test/metabase/login_history/models/login_history_test.clj+++ b/test/metabase/login_history/models/login_history_test.clj@@ -1,8 +1,11 @@(ns metabase.login-history.models.login-history-test(:require[clojure.test :refer :all]+ [java-time.api :as t][metabase.login-history.models.login-history :as login-history]- [metabase.test :as mt]))+ [metabase.login-history.settings :as login-history.settings]+ [metabase.test :as mt]+ [toucan2.core :as t2]))(set! *warn-on-reflection* true)@@ -28,3 +31,47 @@(#'login-history/first-login-on-this-device? history-1)))(is (= false(#'login-history/first-login-ever? history-1))))))))))++(defn- insert-login-histories! [rows]+ (t2/insert! :model/LoginHistory+ (map #(merge {:device_description "test-agent"+ :ip_address "127.0.0.1"} %)+ rows)))++(defn- new-devices [user-id n]+ (for [_ (range n)]+ {:user_id user-id :device_id (str (random-uuid))}))++(deftest too-many-new-device-emails-recently?-test+ (mt/with-model-cleanup [:model/LoginHistory]+ (testing "per-user circuit breaker for new-device emails"+ (let [cap (login-history.settings/new-device-email-rate-limit-cap)]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/User {other-user-id :id} {}]+ (testing "false when the user has no prior first-device events"+ (is (false? (#'login-history/too-many-new-device-emails-recently? user-id))))++ (testing "false at the cap (comparison is strict greater-than)"+ (insert-login-histories! (new-devices user-id cap))+ (is (false? (#'login-history/too-many-new-device-emails-recently? user-id))))++ (testing "true when the user is past the cap"+ (insert-login-histories! (new-devices user-id 1))+ (is (true? (#'login-history/too-many-new-device-emails-recently? user-id))))++ (testing "repeated logins from the same device count as one first-device event"+ (mt/with-temp [:model/User {repeat-user-id :id} {}]+ (insert-login-histories! (repeat 20 {:user_id repeat-user-id :device_id (str (random-uuid))}))+ (is (false? (#'login-history/too-many-new-device-emails-recently? repeat-user-id)))))++ (testing "another user's activity does not count toward this user's limit"+ (insert-login-histories! (new-devices other-user-id 10))+ (mt/with-temp [:model/User {fresh-user-id :id} {}]+ (is (false? (#'login-history/too-many-new-device-emails-recently? fresh-user-id)))))++ (testing "events outside the rate-limit window do not count"+ (mt/with-temp [:model/User {old-user-id :id} {}]+ (let [two-days-ago (t/minus (t/offset-date-time) (t/days 2))]+ (insert-login-histories! (map #(assoc % :timestamp two-days-ago)+ (new-devices old-user-id 10))))+ (is (false? (#'login-history/too-many-new-device-emails-recently? old-user-id))))))))))