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
Session Management (#80243)
Nathan Voxland9eb4ce852464
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 8154a05372a..7e01dd218f9 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -3809,12 +3809,14 @@:api #{metabase-enterprise.support-access-grants.apimetabase-enterprise.support-access-grants.init}:uses #{api+ app-dbauth-identityeventsmodelsrequestsettingssystem+ taskutil}:model-imports #{:model/AuthIdentity :model/Session :model/User}}diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/core.cljindex 0abf51f86fc..e6f6951882b 100644--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj@@ -5,11 +5,16 @@[metabase-enterprise.support-access-grants.models.support-access-grant-log :as sag.model][metabase-enterprise.support-access-grants.provider :as sag.provider][metabase-enterprise.support-access-grants.settings :as sag.settings]+ [metabase.app-db.cluster-lock :as cluster-lock][metabase.events.core :as events][metabase.system.core :as system][metabase.util.i18n :refer [tru]]+ [metabase.util.log :as log][toucan2.core :as t2]))+(def ^:private grant-lifecycle-lock+ ::grant-lifecycle)+(defn- active-grant-exists?"Check if there is an active (non-revoked, non-expired) grant."[]@@ -31,33 +36,33 @@Throws if an active grant already exists."[user-id grant-duration-minutes ticket-number notes]- (when (active-grant-exists?)- (throw (ex-info (tru "Cannot create grant: an active grant already exists")- {:status-code 409})))- (t2/with-transaction [_]- (let [now (t/instant)- grant-end (t/plus now (t/minutes grant-duration-minutes))- grant-record {:user_id user-id- :ticket_number ticket-number- :notes notes- :grant_start_timestamp now- :grant_end_timestamp grant-end}- grant (-> (t2/insert-returning-instance! :model/SupportAccessGrantLog grant-record)- (t2/hydrate :user_info))- support-email (sag.settings/support-access-grant-email)- support-user (sag.model/fetch-or-create-support-user!)- token (sag.provider/create-support-access-reset! (:id support-user) grant)+ (cluster-lock/with-cluster-lock grant-lifecycle-lock+ (when (active-grant-exists?)+ (throw (ex-info (tru "Cannot create grant: an active grant already exists")+ {:status-code 409})))+ (let [now (t/instant)+ grant-end (t/plus now (t/minutes grant-duration-minutes))+ grant-record {:user_id user-id+ :ticket_number ticket-number+ :notes notes+ :grant_start_timestamp now+ :grant_end_timestamp grant-end}+ grant (-> (t2/insert-returning-instance! :model/SupportAccessGrantLog grant-record)+ (t2/hydrate :user_info))+ support-email (sag.settings/support-access-grant-email)+ support-user (sag.model/fetch-or-create-support-user!)+ token (sag.provider/create-support-access-reset! (:id support-user) grant)password-reset-url (when token(str (system/site-url) "/auth/reset_password/" token))];; Publish event - the notification system handles email sending automatically(when (and token password-reset-url)(events/publish-event! :event/support-access-grant-created- {:support_email support-email- :ticket_number ticket-number- :duration_minutes grant-duration-minutes- :grant_end_time grant-end+ {:support_email support-email+ :ticket_number ticket-number+ :duration_minutes grant-duration-minutes+ :grant_end_time grant-end:password_reset_url password-reset-url- :notes notes}))+ :notes notes}));; Return grant with token(cond-> granttoken (assoc :token token)))))@@ -89,6 +94,21 @@(-> (t2/select-one :model/SupportAccessGrantLog :id grant-id)(t2/hydrate :user_info)))))+(defn expire-ended-grants!+ "Tear down the support user's access once every grant has ended.++ A no-op when there is no support user, when a grant is still running, or when access is already torn down."+ []+ (when-let [{support-user-id :id, superuser? :is_superuser}+ (t2/select-one [:model/User :id :is_superuser] :email (sag.settings/support-access-grant-email))]+ (when (or superuser? (t2/exists? :model/Session :user_id support-user-id))+ (cluster-lock/with-cluster-lock grant-lifecycle-lock+ ;; Re-check after acquiring the same lock used by grant creation. This makes credential teardown and grant+ ;; creation mutually exclusive across the cluster, so teardown cannot invalidate a newly created grant.+ (when-not (active-grant-exists?)+ (log/infof "Support access grant has ended; revoking access for support user %d" support-user-id)+ (sag.model/revoke-support-user-access! support-user-id (t/instant)))))))+(defn list-grants"List support access grants with optional filtering and pagination.diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/init.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/init.cljindex 475c7f602b8..c58693af30d 100644--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/init.clj+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/init.clj@@ -2,4 +2,5 @@(:require[metabase-enterprise.support-access-grants.events][metabase-enterprise.support-access-grants.provider]- [metabase-enterprise.support-access-grants.settings]))+ [metabase-enterprise.support-access-grants.settings]+ [metabase-enterprise.support-access-grants.task.expire-grants]))diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.cljindex 61eb79dd276..3d0eeb61d20 100644--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj@@ -47,18 +47,25 @@:user_name (:first_name user-info):user_email (:email user-info))))))+(defn revoke-support-user-access!+ "Tear down the support user's access as of `ended-at`: drop superuser, expire every AuthIdentity so the+ time-limited password can't be used again, and delete their sessions. Called both when a grant is explicitly+ revoked and when one simply runs out."+ [support-user-id ended-at]+ (let [auth-identity-ids (t2/select-pks-vec :model/AuthIdentity :user_id support-user-id)]+ (try+ (t2/update! :model/User support-user-id {:is_superuser false})+ (catch Exception e+ ;; If the support user is somehow the last admin, we can't remove superuser via model hooks.+ ;; Sessions and auth identities are still cleaned up below, preventing further access.+ (log/warnf "Could not remove superuser from support user %d: %s" support-user-id (ex-message e))))+ (when (seq auth-identity-ids)+ (t2/update! :model/AuthIdentity :id [:in auth-identity-ids] {:expires_at ended-at}))+ (t2/delete! :model/Session :user_id support-user-id)))+(t2/define-after-update :model/SupportAccessGrantLog[{revoked-at :revoked_at :as grant}](u/prog1 grant(when revoked-at(when-let [support-user (t2/select-one :model/User :email (sag.settings/support-access-grant-email))]- (let [support-user-id (:id support-user)- auth-identity-ids (t2/select-pks-vec :model/AuthIdentity :user_id support-user-id)]- (try- (t2/update! :model/User support-user-id {:is_superuser false})- (catch Exception e- ;; If the support user is somehow the last admin, we can't remove superuser via model hooks.- ;; Sessions and auth identities are still cleaned up below, preventing further access.- (log/warnf "Could not remove superuser from support user %d: %s" support-user-id (ex-message e))))- (t2/update! :model/AuthIdentity :id [:in auth-identity-ids] {:expires_at revoked-at})- (t2/delete! :model/Session :user_id support-user-id))))))+ (revoke-support-user-access! (:id support-user) revoked-at)))))diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/task/expire_grants.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/task/expire_grants.cljnew file mode 100644index 00000000000..17fb82f135e--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/task/expire_grants.clj@@ -0,0 +1,38 @@+(ns metabase-enterprise.support-access-grants.task.expire-grants+ "Periodically tear down support-access-grant access once the grant window has closed.++ Revoking a grant cleans up immediately, but a grant that just runs out has no such trigger. Session validation and+ session cleanup already refuse and reap sessions past their `expires_at`, so this sweep is defense-in-depth: it+ drops the support user's leftover superuser bit, sessions, and usable credentials promptly instead of leaving them+ around until someone revokes."+ (:require+ [clojurewerkz.quartzite.jobs :as jobs]+ [clojurewerkz.quartzite.schedule.cron :as cron]+ [clojurewerkz.quartzite.triggers :as triggers]+ [metabase-enterprise.support-access-grants.core :as grants]+ [metabase.task.core :as task]))++(set! *warn-on-reflection* true)++(task/defjob ^{org.quartz.DisallowConcurrentExecution true+ :doc "Revoke support access once its grant has ended"}+ ExpireSupportAccessGrants [_ctx]+ (grants/expire-ended-grants!))++(def ^:private job+ (jobs/build+ (jobs/with-description "Revoke support access once its grant has ended")+ (jobs/of-type ExpireSupportAccessGrants)+ (jobs/with-identity (jobs/key "metabase-enterprise.support-access-grants.expire-grants.job"))+ (jobs/store-durably)))++(def ^:private trigger+ (triggers/build+ (triggers/with-identity (triggers/key "metabase-enterprise.support-access-grants.expire-grants.trigger"))+ (triggers/start-now)+ (triggers/with-schedule+ ;; every five minutes — a grant is granted in minutes, so the sweep should not lag it by much+ (cron/cron-schedule "0 0/5 * * * ? *"))))++(defmethod task/init! ::ExpireSupportAccessGrants [_]+ (task/schedule-task! job trigger))diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.cljindex bc38c54c2f2..c1e72817c9e 100644--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.clj+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.clj@@ -5,11 +5,14 @@[clojure.test :refer :all][java-time.api :as t][metabase-enterprise.support-access-grants.core :as grants]+ [metabase-enterprise.support-access-grants.models.support-access-grant-log :as sag.model][metabase-enterprise.support-access-grants.provider :as sag.provider][metabase-enterprise.support-access-grants.settings :as sag.settings][metabase.events.core :as events][metabase.test :as mt]- [toucan2.core :as t2]))+ [metabase.test.util.dynamic-redefs :as dynamic-redefs]+ [toucan2.core :as t2]+ [toucan2.tools.with-temp :as t2.with-temp]))(set! *warn-on-reflection* true)@@ -391,3 +394,116 @@diff-seconds (t/as (t/duration expected-end grant-end-time) :seconds)](is (< (Math/abs ^long diff-seconds) 2)"Grant end time should be approximately duration_minutes in the future")))))))))++(deftest expire-ended-grants-tears-down-support-access-test+ (testing "a grant that ends naturally, without ever being revoked, has the support user's access torn down"+ (let [support-email "[email protected]"]+ ;; the creator is an admin so the support user isn't the last one, and can actually be demoted+ (mt/with-temp [:model/User {creator-id :id} {:is_superuser true}]+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly support-email)]+ (let [grant (grants/create-grant! creator-id 60 "SUPPORT-NATURAL-EXPIRY" "Time-boxed access")+ support-user-id (t2/select-one-pk :model/User :email support-email)]+ (t2/insert! :model/Session {:id "expiregrant1"+ :user_id support-user-id+ :session_key (str (random-uuid))})+ (testing "while the grant is still running the sweep leaves everything alone"+ (grants/expire-ended-grants!)+ (is (:is_superuser (t2/select-one :model/User :id support-user-id)))+ (is (t2/exists? :model/Session :user_id support-user-id)))+ (testing "once the grant window has passed the sweep revokes access"+ ;; Move the grant's end into the past; `revoked_at` stays nil, so nothing else cleans up.+ (t2/update! :model/SupportAccessGrantLog (:id grant)+ {:grant_end_timestamp (t/minus (t/instant) (t/minutes 1))})+ (grants/expire-ended-grants!)+ (is (not (:is_superuser (t2/select-one :model/User :id support-user-id)))+ "Support user should lose admin access once the grant ends")+ (is (not (t2/exists? :model/Session :user_id support-user-id))+ "Support user sessions should be deleted once the grant ends")+ (is (every? :expires_at (t2/select :model/AuthIdentity :user_id support-user-id))+ "Support user auth identities should be expired once the grant ends"))+ (testing "the sweep is idempotent"+ (grants/expire-ended-grants!)+ (is (not (:is_superuser (t2/select-one :model/User :id support-user-id))))+ (is (not (t2/exists? :model/Session :user_id support-user-id)))))))))))++(deftest expire-ended-grants-ignores-other-users-test+ (testing "the natural-expiry sweep only touches the support user"+ (let [support-email "[email protected]"]+ (mt/with-temp [:model/User {creator-id :id} {}+ :model/User {other-user-id :id} {:is_superuser true}]+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly support-email)]+ (let [grant (grants/create-grant! creator-id 60 "SUPPORT-EXPIRY-SCOPE" "Time-boxed access")]+ (t2/insert! :model/Session {:id "otheruser001"+ :user_id other-user-id+ :session_key (str (random-uuid))})+ (t2/update! :model/SupportAccessGrantLog (:id grant)+ {:grant_end_timestamp (t/minus (t/instant) (t/minutes 1))})+ (grants/expire-ended-grants!)+ (is (:is_superuser (t2/select-one :model/User :id other-user-id)))+ (is (t2/exists? :model/Session :user_id other-user-id)))))))))++(deftest expire-ended-grants-does-not-tear-down-a-concurrently-created-grant-test+ (testing "grant creation waits for an in-progress natural-expiry teardown"+ (let [support-email "[email protected]"]+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly support-email)]+ ;; The creator is inserted directly rather than with `with-temp`, which would run this body inside a+ ;; transaction. `future` conveys that connection, so both threads below would share one transaction and+ ;; their `SELECT ... FOR UPDATE` on the lock row could never conflict — the cluster lock would be a no-op+ ;; and the race this test guards against would go undetected on every appdb except h2.+ ;; The creator is an admin so the support user isn't the last one, and can actually be demoted.+ (let [creator-id (t2/insert-returning-pk! :model/User+ (assoc (t2.with-temp/with-temp-defaults :model/User)+ :is_superuser true))+ ended-grant (grants/create-grant! creator-id 60 "SUPPORT-EXPIRED" nil)+ support-user-id (t2/select-one-pk :model/User :email support-email)+ teardown-started (promise)+ allow-teardown (promise)+ create-started (promise)+ original-revoke-user-access! (dynamic-redefs/original-fn+ #'sag.model/revoke-support-user-access!)]+ (t2/update! :model/SupportAccessGrantLog (:id ended-grant)+ {:grant_end_timestamp (t/minus (t/instant) (t/minutes 1))})+ (mt/with-dynamic-fn-redefs+ [sag.model/revoke-support-user-access!+ (fn [user-id ended-at]+ (deliver teardown-started true)+ (when (= ::timeout (deref allow-teardown 5000 ::timeout))+ (throw (ex-info "Timed out waiting to finish support access teardown" {})))+ (original-revoke-user-access! user-id ended-at))]+ (let [expire-result (future (grants/expire-ended-grants!))]+ (is (true? (deref teardown-started 5000 ::timeout))+ "Expiry should reach credential teardown")+ (let [create-result (future+ (deliver create-started true)+ (grants/create-grant! creator-id 60 "SUPPORT-CURRENT" nil))]+ (try+ (is (true? (deref create-started 5000 ::timeout)))+ (is (= ::timeout (deref create-result 250 ::timeout))+ "Grant creation must wait until the expiry teardown releases its lifecycle lock")+ (deliver allow-teardown true)+ (is (not= ::timeout (deref expire-result 5000 ::timeout)))+ (let [new-grant (deref create-result 5000 ::timeout)+ support-user (t2/select-one :model/User support-user-id)+ auth-identity (t2/select-one :model/AuthIdentity+ :user_id support-user-id+ :provider "support-access-grant")]+ (is (map? new-grant) "Concurrent grant creation should complete")+ (is (= "SUPPORT-CURRENT" (:ticket_number new-grant)))+ (is (:is_superuser support-user)+ "The new grant should restore support admin access")+ (is (= (:grant_end_timestamp new-grant) (:expires_at auth-identity))+ "The new grant's credentials must survive the old grant's expiry sweep"))+ (finally+ (deliver allow-teardown true)+ (future-cancel expire-result)+ (future-cancel create-result))))))))))))++(deftest expire-ended-grants-no-support-user-test+ (testing "the natural-expiry sweep is a no-op when no support user exists"+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")]+ (is (nil? (grants/expire-ended-grants!)))+ (is (not (t2/exists? :model/User :email "[email protected]"))+ "the sweep must not conjure a support user into existence"))))diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.cljindex ad19611c8c7..946d628cc69 100644--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj@@ -432,3 +432,26 @@:provider "password")](is (some? (:expires_at pw-auth))"Password AuthIdentity should have an expiration from the grant")))))))))))))++(deftest support-grant-session-does-not-outlive-the-grant-test+ (testing "a session minted from a support access grant stops authenticating once the grant window has passed"+ (mt/with-temp [:model/User {creator-id :id} {}]+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]+ (mt/with-dynamic-fn-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")+ sag.settings/support-access-grant-first-name (constantly "Support")+ sag.settings/support-access-grant-last-name (constantly "User")]+ (let [grant (grants/create-grant! creator-id 60 "SUPPORT-SESSION-EXPIRY" "Time-boxed access")+ session-key (:session_id (mt/client :post 200 "session/reset_password"+ {:token (:token grant) :password "SupportPass!2468"}))+ session (t2/select-one :model/Session :key_hashed (session/hash-session-key session-key))]+ (testing "the session records the grant's end as its own expires_at"+ (is (some? (:expires_at session))))+ (testing "inside the grant window the support session works"+ (is (true? (:is_superuser (mt/client session-key :get 200 "user/current")))))+ (testing "past the grant window the support session is rejected"+ ;; Sessions cannot be updated through the model and the clock cannot be wound forward, so+ ;; simulate the grant window elapsing by moving expires_at into the past.+ (t2/query-one {:update (t2/table-name :model/Session)+ :set {:expires_at (t/minus (t/instant) (t/minutes 1))}+ :where [:= :id (:id session)]})+ (is (= "Unauthenticated" (mt/client session-key :get 401 "user/current"))))))))))diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex cf70c296c2b..dd28bdfbe32 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -134,6 +134,8 @@[:= :user.is_active true][:= :session.key_hashed ^:allow-raw-sql [:raw "?"]][:> :session.created_at (oldest-allowed-expr db-type max-age-minutes :minute)]+ [:or [:= :session.expires_at nil]+ [:> :session.expires_at (h2x/current-datetime-honeysql-form db-type)]][:= :session.anti_csrf_token (case session-type:normal nil:full-app-embed ^:allow-raw-sql [:raw "?"])]]diff --git a/src/metabase/session/task/session_cleanup.clj b/src/metabase/session/task/session_cleanup.cljindex fbd125d5321..c0c2c244857 100644--- a/src/metabase/session/task/session_cleanup.clj+++ b/src/metabase/session/task/session_cleanup.clj@@ -16,23 +16,26 @@(defn- cleanup-sessions!"Deletes sessions from the database which are no longer valid. Removes sessions that exceed MAX_SESSION_AGE- (absolute lifetime) and also sessions that have been idle longer than the session-timeout setting (if configured)."+ (absolute lifetime), sessions past their own `expires_at`, and sessions that have been idle longer than the+ session-timeout setting (if configured)."[]- (let [oldest-allowed (h2x/add-interval-honeysql-form (mdb/db-type)- :%now+ (let [db-type (mdb/db-type)+ now (h2x/current-datetime-honeysql-form db-type)+ oldest-allowed (h2x/add-interval-honeysql-form db-type+ now(- (config/config-int :max-session-age)):minute)timeout-seconds (request/enabled-session-timeout-seconds)timeout-oldest (when timeout-seconds- (h2x/add-interval-honeysql-form (mdb/db-type)- :%now+ (h2x/add-interval-honeysql-form db-type+ now(- timeout-seconds):second))- where-clause (if timeout-oldest- [:or- [:< :created_at oldest-allowed]- [:< [:coalesce :last_active_at :created_at] timeout-oldest]]- [:< :created_at oldest-allowed])+ where-clause (cond-> [:or+ [:< :created_at oldest-allowed]+ [:and [:not= :expires_at nil] [:< :expires_at now]]]+ timeout-oldest+ (conj [:< [:coalesce :last_active_at :created_at] timeout-oldest]))hsql {:delete-from [(t2/table-name :model/Session)]:where where-clause}](tracing/with-span :tasks "task.session-cleanup.delete" {:db/statement (tracing/best-effort-sanitize-sql hsql)}diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.cljindex bc797dd82f7..2085aaf5601 100644--- a/test/metabase/server/middleware/session_test.clj+++ b/test/metabase/server/middleware/session_test.clj@@ -55,6 +55,36 @@(is (nil? session))(is (some? session)))))))))))+(defn- insert-test-session!+ "Insert a `core_session` row directly, bypassing the model hooks so that columns like `created_at` and `expires_at`+ can be set to arbitrary (including DB-side) expressions. Returns the plaintext session key."+ [user-id extra-cols]+ (let [session-key (str (random-uuid))]+ (t2/insert! (t2/table-name :model/Session)+ (merge {:id (session/generate-session-id)+ :key_hashed (session/hash-session-key session-key)+ :user_id user-id}+ extra-cols))+ session-key))++(deftest session-expires-at-test+ (init-status/set-complete!)+ (testing "`expires_at` is enforced server-side, even for a session well within `max-session-age`"+ (let [db-type (mdb/db-type)+ now (h2x/current-datetime-honeysql-form db-type)]+ (doseq [[expires-at expected msg]+ [[nil false "session with no expires_at"]+ [(h2x/add-interval-honeysql-form db-type now 60 :second) false "session that expires in 60 seconds"]+ [(h2x/add-interval-honeysql-form db-type now -1 :second) true "session that expired 1 second ago"]+ [#t "1970-01-01T00:00:01Z" true "session that expired long ago"]]]+ (testing (format "\n%s %s be expired." msg (if expected "SHOULD" "SHOULD NOT"))+ (mt/with-temp [:model/User {user-id :id}]+ (let [session-key (insert-test-session! user-id {:created_at now, :expires_at expires-at})+ session (#'mw.session/current-user-info-for-session session-key nil)]+ (if expected+ (is (nil? session))+ (is (some? session))))))))))+;;; ---------------------------------------- TEST wrap-session-key middleware -----------------------------------------(def ^:private session-header @#'mw.session/metabase-session-header)diff --git a/test/metabase/session/task/session_cleanup_test.clj b/test/metabase/session/task/session_cleanup_test.cljindex 05758d39b90..2022fc67752 100644--- a/test/metabase/session/task/session_cleanup_test.clj+++ b/test/metabase/session/task/session_cleanup_test.clj@@ -24,4 +24,28 @@(is (not (t2/exists? :model/Session :id (:id old-session))))(is (t2/exists? :model/Session :id (:id new-session)))))))+(deftest clean-expired-sessions-test+ (mt/with-temp-env-var-value! [:max-session-age (str (* 60 24))] ;; one day+ (let [recently (t/minus (t/local-date-time) (t/hours 1))]+ (mt/with-temp [:model/User {user-id :id} {}+ :model/Session expired-session {:id "c"+ :key_hashed "c1"+ :user_id user-id+ :created_at recently+ :expires_at (t/minus (t/instant) (t/minutes 1))}+ :model/Session unexpired-session {:id "d"+ :key_hashed "d1"+ :user_id user-id+ :created_at recently+ :expires_at (t/plus (t/instant) (t/hours 1))}+ :model/Session no-expiry-session {:id "e"+ :key_hashed "e1"+ :user_id user-id+ :created_at recently}]+ (testing "session-cleanup reaps sessions past their expires_at, even when they are within max-session-age"+ (#'session-cleanup/cleanup-sessions!)+ (is (not (t2/exists? :model/Session :id (:id expired-session))))+ (is (t2/exists? :model/Session :id (:id unexpired-session)))+ (is (t2/exists? :model/Session :id (:id no-expiry-session))))))))+;; cleanup-idle-sessions-test is in metabase-enterprise.api.session-test because it requires EE features.