Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Session management (#82285)

John Swanson34fc3bfe53fc
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 4e1127dee82..e953a7d5c60 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1371,6 +1371,7 @@
server
session
settings
+ sso.auth-identity
system
task
transforms
@@ -1380,7 +1381,8 @@
warehouse-schema-overlay
warehouses
warehouses.schema}
- :model-imports #{:model/Card
+ :model-imports #{:model/AuthIdentity
+ :model/Card
:model/Collection
:model/Dashboard
:model/Database
@@ -2619,6 +2621,7 @@
channel
lib.schema
request
+ session
settings
util}
:model-exports #{:model/LoginHistory}}
@@ -4361,6 +4364,18 @@
util}
:model-imports :bypass}
+ enterprise/session-management
+ {:team "UX West"
+ :api #{metabase-enterprise.session-management.api}
+ :uses #{api
+ events
+ lib.schema
+ request
+ session
+ users
+ util}
+ :model-imports #{:model/User}}
+
enterprise/sso
{:team "UX West"
:module-exports #{enterprise/sso.auth-identity
@@ -4382,7 +4397,7 @@
task
util
enterprise/sso.scim}
- :model-imports #{:model/PermissionsGroup :model/Session}}
+ :model-imports #{:model/PermissionsGroup}}
enterprise/sso.auth-identity
{:team "UX West"
@@ -4436,6 +4451,7 @@
lib.schema
models
request
+ session
settings
sso.auth-identity
system
diff --git a/e2e/support/config.js b/e2e/support/config.js
index c629f1f6ee7..1ac44b282f6 100644
--- a/e2e/support/config.js
+++ b/e2e/support/config.js
@@ -22,7 +22,10 @@ import {
verifyDownloadTasks,
} from "./commands/downloads/downloadUtils";
import * as dbTasks from "./db_tasks";
-import { requestAsAdmin } from "./helpers/e2e-admin-request-tasks";
+import {
+ backendRequest,
+ requestAsAdmin,
+} from "./helpers/e2e-admin-request-tasks";
import {
startCustomVizDevServer,
stopCustomVizDevServer,
@@ -303,6 +306,7 @@ const defaultConfig = {
copyDirectory,
removeDirectory,
signJwt,
+ backendRequest,
requestAsAdmin,
startMockLlmServer,
stopMockLlmServer,
diff --git a/e2e/support/helpers/e2e-admin-request-tasks.ts b/e2e/support/helpers/e2e-admin-request-tasks.ts
index 6e3d13bc52c..2227db4634a 100644
--- a/e2e/support/helpers/e2e-admin-request-tasks.ts
+++ b/e2e/support/helpers/e2e-admin-request-tasks.ts
@@ -12,17 +12,74 @@ type AdminRequest = {
body?: unknown;
};
-async function send(url: string, init: RequestInit) {
- const response = await fetch(`${BASE_URL}${url}`, {
- ...init,
- headers: { "Content-Type": "application/json", ...init.headers },
- });
+export type BackendRequest = AdminRequest & {
+ /** Sent as `X-Metabase-Session`; omit to make the request unauthenticated */
+ sessionId?: string;
+ /** Like `cy.request`: when false, a non-2xx status is returned rather than thrown */
+ failOnStatusCode?: boolean;
+};
+
+export type BackendResponse<TBody = unknown> = {
+ status: number;
+ body: TBody;
+ /** The `Set-Cookie` cookies of the response, by name */
+ cookies: Record<string, string>;
+};
+
+function parseBody(text: string) {
+ try {
+ return text ? JSON.parse(text) : null;
+ } catch {
+ return text;
+ }
+}
+
+function parseCookies(headers: Headers) {
+ return Object.fromEntries(
+ headers.getSetCookie().map((cookie) => {
+ const [pair] = cookie.split(";");
+ const separator = pair.indexOf("=");
+ return [pair.slice(0, separator), pair.slice(separator + 1)];
+ }),
+ );
+}
+
+/**
+ Makes a request from Node rather than the browser, so it neither reads nor
+ changes the browser's cookies. Redirects are not followed.
+ */
+export async function backendRequest<TBody = unknown>({
+ method = "GET",
+ url,
+ body,
+ sessionId,
+ failOnStatusCode = true,
+}: BackendRequest): Promise<BackendResponse<TBody>> {
+ let response: Response;
+ try {
+ response = await fetch(`${BASE_URL}${url}`, {
+ method,
+ redirect: "manual",
+ headers: {
+ "Content-Type": "application/json",
+ ...(sessionId ? { "X-Metabase-Session": sessionId } : {}),
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch (error) {
+ // undici's bare "fetch failed" doesn't say which of a test's many requests it was
+ throw new Error(`${method} ${url} failed to send`, { cause: error });
+ }
const text = await response.text();
- if (!response.ok) {
- throw new Error(`${init.method} ${url} → ${response.status}: ${text}`);
+ if (failOnStatusCode && !response.ok) {
+ throw new Error(`${method} ${url} → ${response.status}: ${text}`);
}
- return text ? JSON.parse(text) : null;
+ return {
+ status: response.status,
+ body: parseBody(text),
+ cookies: parseCookies(response.headers),
+ };
}
function cachedAdminSession(): string | undefined {
@@ -37,30 +94,25 @@ function cachedAdminSession(): string | undefined {
async function freshAdminSession(): Promise<string | undefined> {
const { email: username, password } = USERS.admin;
- const { id } = await send("/api/session", {
+ const { body } = await backendRequest<{ id?: string } | null>({
method: "POST",
- body: JSON.stringify({ username, password }),
+ url: "/api/session",
+ body: { username, password },
});
- return id;
+ return body?.id;
}
/**
- Acts as the admin without touching the browser's cookies
+ Acts as the admin without touching the browser's cookies. The cached admin session is the one
+ `cy.signInAsAdmin()` puts in the browser, so revoking that session would break both.
*/
-export async function requestAsAdmin({
- method = "GET",
- url,
- body,
-}: AdminRequest) {
+export async function requestAsAdmin(request: AdminRequest) {
const sessionId = cachedAdminSession() ?? (await freshAdminSession());
if (!sessionId) {
throw new Error("Could not resolve an admin session");
}
- return send(url, {
- method,
- headers: { "X-Metabase-Session": sessionId },
- body: body === undefined ? undefined : JSON.stringify(body),
- });
+ const { body } = await backendRequest({ ...request, sessionId });
+ return body;
}
diff --git a/e2e/test/scenarios/monitor/session-management/session-management.cy.spec.ts b/e2e/test/scenarios/monitor/session-management/session-management.cy.spec.ts
new file mode 100644
index 00000000000..da8edddcfba
--- /dev/null
+++ b/e2e/test/scenarios/monitor/session-management/session-management.cy.spec.ts
@@ -0,0 +1,506 @@
+import { USERS } from "e2e/support/cypress_data";
+import {
+ NODATA_USER_ID,
+ NORMAL_USER_ID,
+} from "e2e/support/cypress_sample_instance_data";
+import type { BackendResponse } from "e2e/support/helpers/e2e-admin-request-tasks";
+import {
+ JWT_SHARED_SECRET,
+ enableJwtAuth,
+} from "e2e/support/helpers/e2e-jwt-helpers";
+import type { SessionListResponse } from "metabase-types/api";
+
+const { H } = cy;
+
+const { normal, nodata } = USERS;
+
+const JWT_USER = {
+ email: "[email protected]",
+ first_name: "Jay",
+ last_name: "Doubleyoo",
+};
+
+const LDAP_USER = { email: "[email protected]", password: "123456" };
+
+/** What creating a support access grant returns: the grant, and the token that redeems it */
+type CreatedGrant = { id: number; token: string };
+
+/** A session created outside the browser: its credential, and its id as the admin's list shows it */
+type TestSession = { key: string; id: string };
+
+describe("scenarios > monitor > session management", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ cy.intercept("POST", "/api/ee/session-management/revoke").as("revoke");
+ });
+
+ it(
+ "an admin finds and revokes sessions across auth methods",
+ { tags: "@external" },
+ () => {
+ enableJwtAuth();
+ H.setupLdap();
+ startSession(passwordLogin(normal)).as("normalA");
+ startSession(passwordLogin(normal)).as("normalB");
+ startSession(passwordLogin(nodata)).as("nodataA");
+ startSession(passwordLogin(nodata)).as("nodataB");
+ startSession(passwordLogin(USERS.readonly)).as("readonly");
+ startSession(passwordLogin(USERS.nocollection)).as("nocollection");
+ startSession(passwordLogin(USERS.nosql)).as("signedOut");
+ startSession(jwtLogin(JWT_USER)).as("jwt");
+ startSession(passwordLogin(LDAP_USER)).as("ldap");
+
+ withSessions(
+ [
+ "normalA",
+ "normalB",
+ "nodataA",
+ "nodataB",
+ "readonly",
+ "nocollection",
+ "signedOut",
+ "jwt",
+ "ldap",
+ ],
+ (s) => {
+ cy.log("One user signs themselves out before the admin arrives");
+ cy.task<BackendResponse>("backendRequest", {
+ method: "DELETE",
+ url: "/api/session",
+ sessionId: s.signedOut.key,
+ });
+ expectEnded(s.signedOut);
+
+ cy.log("Each live session shows the auth method it was created with");
+ visitSessions();
+ sessionRow(s.normalA)
+ .should("contain", "Robert Tableton")
+ .and("contain", "Password");
+ sessionRow(s.jwt)
+ .should("contain", "Jay Doubleyoo")
+ .and("contain", "JWT");
+ sessionRow(s.ldap).should("contain", "LDAP");
+ sessionRow(s.signedOut).should("not.exist");
+
+ cy.log(
+ "The admin narrows the list to SSO sessions and revokes the LDAP one",
+ );
+ cy.button("Show filters").click();
+ H.popover().findByRole("button", { name: "JWT" }).click();
+ H.popover().findByRole("button", { name: "LDAP" }).click();
+ H.popover().button("Apply").click();
+ sessionRow(s.jwt).should("be.visible");
+ sessionRow(s.ldap).should("be.visible");
+ sessionRow(s.normalA).should("not.exist");
+
+ sessionRow(s.ldap).click();
+ sessionSidebar().button("Revoke session").click();
+ confirmRevoke("Revoke this session?");
+ expectToast("Revoked 1 session");
+ expectEnded(s.ldap);
+ expectLive(s.jwt);
+ sessionRow(s.ldap).should("not.exist");
+ expectRevokedOnEndedTab(s.ldap);
+
+ cy.button("Show filters").click();
+ H.popover().button("Clear filters").click();
+
+ cy.log(
+ "The admin searches for a user and revokes one of their sessions",
+ );
+ cy.findByLabelText("Search sessions").type("Robert");
+ sessionRow(s.normalA).should("be.visible");
+ sessionRow(s.normalB).should("be.visible");
+ sessionRow(s.nodataA).should("not.exist");
+
+ sessionRow(s.normalA).click();
+ sessionSidebar().button("Revoke session").click();
+ confirmRevoke("Revoke this session?");
+ expectToast("Revoked 1 session");
+ expectEnded(s.normalA);
+ expectLive(s.normalB);
+ expectRevokedOnEndedTab(s.normalA);
+
+ cy.log(
+ "The admin finds another user and revokes all of their sessions",
+ );
+ cy.findByLabelText("Search sessions").clear().type("No Data");
+ sessionRow(s.nodataA).should("be.visible");
+ sessionRow(s.normalB).should("not.exist");
+
+ sessionRow(s.nodataA).click();
+ sessionSidebar().button("Revoke active sessions").click();
+ confirmRevoke("Revoke all sessions for No Data Tableton?");
+ // no count: the other users' cached sessions H.restore() brings back are revoked too
+ expectToast("Revoked");
+ expectEnded(s.nodataA);
+ expectEnded(s.nodataB);
+ expectLive(s.normalB);
+ expectRevokedOnEndedTab(s.nodataA, s.nodataB);
+
+ cy.log("The admin clears the search and revokes a selection in bulk");
+ cy.findByLabelText("Search sessions").clear();
+ sessionRow(s.normalB).findByRole("checkbox").click();
+ sessionRow(s.readonly).findByRole("checkbox").click();
+ cy.findByTestId("toast-card")
+ .should("contain", "2 sessions selected")
+ .button("Revoke")
+ .click();
+ confirmRevoke("Revoke 2 sessions?");
+ expectToast("Revoked 2 sessions");
+ expectEnded(s.normalB);
+ expectEnded(s.readonly);
+ expectLive(s.nocollection);
+ expectRevokedOnEndedTab(s.normalB, s.readonly);
+
+ cy.log("The admin revokes everyone else, and stays signed in");
+ cy.button("Revoke all active sessions").click();
+ confirmRevoke("Revoke all sessions?");
+ // no count: the other users' cached sessions H.restore() brings back are revoked too
+ expectToast("Revoked");
+ expectEnded(s.nocollection);
+ expectEnded(s.jwt);
+ expectRevokedOnEndedTab(s.nocollection, s.jwt);
+
+ visitSessions();
+ cy.findByTestId("sessions-table")
+ .findByText("This session")
+ .should("be.visible");
+
+ cy.log(
+ "The admin's own session can't be selected or revoked from here",
+ );
+ currentSessionRow().findByRole("checkbox").should("be.disabled");
+ currentSessionRow().click();
+ sessionSidebar().should("contain", "Bobby Tables");
+ sessionSidebar()
+ .findByRole("button", { name: "Revoke session" })
+ .should("not.exist");
+ sessionSidebar()
+ .findByRole("button", { name: "Revoke active sessions" })
+ .should("not.exist");
+ sessionSidebar().button("Close").click();
+
+ cy.log("Every revoked session is on record as revoked by an admin");
+ cy.findByTestId("sessions-tab-ended").click();
+ sessionRow(s.signedOut).should("contain", "Signed out");
+
+ cy.button("Show filters").click();
+ H.popover().findByRole("textbox", { name: "Reason" }).click();
+ cy.findByRole("option", { name: "Revoked by admin" }).click();
+ H.popover().button("Apply").click();
+ sessionRow(s.signedOut).should("not.exist");
+ [
+ s.ldap,
+ s.normalA,
+ s.nodataA,
+ s.nodataB,
+ s.normalB,
+ s.readonly,
+ s.nocollection,
+ s.jwt,
+ ].forEach((session) =>
+ sessionRow(session).should("contain", "Revoked by admin"),
+ );
+
+ cy.log("Ended sessions are read-only");
+ cy.findByTestId("sessions-table")
+ .findAllByRole("checkbox")
+ .should("not.exist");
+ sessionRow(s.ldap).click();
+ sessionSidebar().should("contain", "Revoked by admin");
+ sessionSidebar()
+ .findByRole("button", { name: "Revoke session" })
+ .should("not.exist");
+ },
+ );
+ },
+ );
+
+ it("records why a session ended when it ended outside the page", () => {
+ startSession(passwordLogin(USERS.readonly)).as("loggedOut");
+ startSession(passwordLogin(nodata)).as("deactivated");
+ startSession(passwordLogin(normal)).as("passwordChanged");
+ cy.task<CreatedGrant>("requestAsAdmin", {
+ method: "POST",
+ url: "/api/ee/support-access-grant",
+ body: { grant_duration_minutes: 60 },
+ }).as("grant");
+ cy.get<CreatedGrant>("@grant").then(({ token }) =>
+ startSession(supportAccessLogin(token)).as("supportAccess"),
+ );
+
+ withSessions(
+ ["loggedOut", "deactivated", "passwordChanged", "supportAccess"],
+ (s) => {
+ cy.log("A support access session is attributed to its grant");
+ visitSessions();
+ sessionRow(s.supportAccess).should("contain", "Support access");
+
+ cy.log("The user logs themselves out");
+ cy.task<BackendResponse>("backendRequest", {
+ method: "DELETE",
+ url: "/api/session",
+ sessionId: s.loggedOut.key,
+ });
+
+ cy.log("An admin deactivates another user");
+ cy.task("requestAsAdmin", {
+ method: "DELETE",
+ url: `/api/user/${NODATA_USER_ID}`,
+ });
+
+ cy.log("An admin changes a third user's password");
+ cy.task("requestAsAdmin", {
+ method: "PUT",
+ url: `/api/user/${NORMAL_USER_ID}/password`,
+ body: { password: "NewPassword!session123" },
+ });
+
+ cy.log("An admin revokes the support access grant");
+ cy.get<CreatedGrant>("@grant").then(({ id }) =>
+ cy.task("requestAsAdmin", {
+ method: "PUT",
+ url: `/api/ee/support-access-grant/${id}/revoke`,
+ }),
+ );
+
+ expectEnded(s.loggedOut);
+ expectEnded(s.deactivated);
+ expectEnded(s.passwordChanged);
+ expectEnded(s.supportAccess);
+
+ cy.findByTestId("sessions-tab-ended").click();
+ sessionRow(s.loggedOut).should("contain", "Signed out");
+ sessionRow(s.deactivated).should("contain", "User deactivated");
+ sessionRow(s.passwordChanged).should("contain", "Password changed");
+ sessionRow(s.supportAccess).should("contain", "Support access revoked");
+
+ const ended = [
+ s.loggedOut,
+ s.deactivated,
+ s.passwordChanged,
+ s.supportAccess,
+ ];
+ const expectOnlyListed = (...listed: TestSession[]) =>
+ ended.forEach((session) =>
+ sessionRow(session).should(
+ listed.includes(session) ? "be.visible" : "not.exist",
+ ),
+ );
+
+ cy.log("Filtering by reason narrows the ended sessions");
+ cy.button("Show filters").click();
+ H.popover().findByRole("textbox", { name: "Reason" }).click();
+ cy.findByRole("option", { name: "Password changed" }).click();
+ H.popover().button("Apply").click();
+ expectOnlyListed(s.passwordChanged);
+
+ cy.log("Clearing the filters brings every ended session back");
+ cy.button("Show filters").click();
+ H.popover().button("Clear filters").click();
+ expectOnlyListed(...ended);
+
+ cy.log("Filtering by auth method narrows them too");
+ cy.button("Show filters").click();
+ H.popover().findByRole("button", { name: "Support access" }).click();
+ H.popover().button("Apply").click();
+ expectOnlyListed(s.supportAccess);
+
+ cy.log("Searching matches the owner of an ended session");
+ cy.button("Show filters").click();
+ H.popover().button("Clear filters").click();
+ cy.findByLabelText("Search sessions").type("Read Only");
+ expectOnlyListed(s.loggedOut);
+ },
+ );
+ });
+});
+
+describe("scenarios > monitor > session management > access", () => {
+ beforeEach(() => {
+ H.restore();
+ });
+
+ it("shows the upsell to an admin without the feature", () => {
+ cy.signInAsAdmin();
+ // a valid token that lacks the feature, rather than no token at all
+ H.activateToken("starter");
+ cy.visit("/monitor/sessions");
+ cy.findByTestId("monitor-main")
+ .findByText(
+ /See who is signed in to your Metabase. Revoke individual sessions/,
+ )
+ .should("be.visible");
+ cy.findByTestId("sessions-table").should("not.exist");
+ });
+
+ it("is admin-only", () => {
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ cy.signInAsNormalUser();
+ cy.visit("/monitor/sessions");
+ cy.location("pathname").should("eq", "/unauthorized");
+ });
+});
+
+// ---------------------------------------------------------------------------------------------------------------------
+
+type SessionAlias = string;
+
+/** Signs in from Node with a username and password (which LDAP also uses), returning the session key */
+function passwordLogin({
+ email,
+ password,
+}: {
+ email: string;
+ password: string;
+}) {
+ return () =>
+ cy
+ .task<BackendResponse<{ id: string }>>("backendRequest", {
+ method: "POST",
+ url: "/api/session",
+ body: { username: email, password },
+ })
+ .then(({ body }) => body.id);
+}
+
+/** Redeems a support access grant from Node, as the support engineer would, returning the session key */
+function supportAccessLogin(token: string) {
+ return () =>
+ cy
+ .task<BackendResponse<{ session_id: string }>>("backendRequest", {
+ method: "POST",
+ url: "/api/session/reset_password",
+ body: { token, password: "SupportPassword!123" },
+ })
+ .then(({ body }) => body.session_id);
+}
+
+/** Signs in from Node through JWT SSO, returning the session key from the cookie it sets */
+function jwtLogin(payload: typeof JWT_USER) {
+ return () =>
+ cy
+ .task<string>("signJwt", { payload, secret: JWT_SHARED_SECRET })
+ .then((jwt) =>
+ cy.task<BackendResponse>("backendRequest", {
+ url: `/auth/sso?jwt=${jwt}`,
+ failOnStatusCode: false,
+ }),
+ )
+ .then(({ status, cookies }) => {
+ expect(status, "the SSO redirect").to.eq(302);
+ return cookies["metabase.SESSION"];
+ });
+}
+
+function liveSessionIds() {
+ return cy
+ .task<SessionListResponse>("requestAsAdmin", {
+ url: "/api/ee/session-management",
+ })
+ .then(({ data }) => data.map((session) => session.id));
+}
+
+/**
+ Signs in with `login` outside the browser, so the admin's browser session is untouched. The session's id is
+ whatever the login added to the admin's list.
+ */
+function startSession(
+ login: () => Cypress.Chainable<string>,
+): Cypress.Chainable<TestSession> {
+ return liveSessionIds().then((before) =>
+ login().then((key) =>
+ liveSessionIds().then((after) => {
+ const added = after.filter((id) => !before.includes(id));
+ expect(added, "sessions the login created").to.have.length(1);
+ return { key, id: added[0] };
+ }),
+ ),
+ );
+}
+
+function withSessions<T extends SessionAlias>(
+ aliases: T[],
+ fn: (sessions: Record<T, TestSession>) => void,
+) {
+ // filled in by the `cy.get` chain below, which Cypress runs before `fn`
+ const sessions = {} as Record<T, TestSession>;
+ aliases.forEach((alias) =>
+ cy.get<TestSession>(`@${alias}`).then((session) => {
+ sessions[alias] = session;
+ }),
+ );
+ cy.then(() => fn(sessions));
+}
+
+/** The status `GET /api/user/current` answers with when presented with `session`'s key */
+function currentUserStatus(session: TestSession) {
+ return cy
+ .task<BackendResponse>("backendRequest", {
+ url: "/api/user/current",
+ sessionId: session.key,
+ failOnStatusCode: false,
+ })
+ .its("status");
+}
+
+function expectLive(session: TestSession) {
+ currentUserStatus(session).should("eq", 200);
+}
+
+function expectEnded(session: TestSession) {
+ currentUserStatus(session).should("eq", 401);
+}
+
+function visitSessions() {
+ // a fresh intercept per visit: a reused alias would be satisfied by a request from earlier in the test
+ cy.intercept({
+ method: "GET",
+ pathname: "/api/ee/session-management",
+ }).as("visitListSessions");
+ cy.visit("/monitor/sessions");
+ cy.wait("@visitListSessions");
+}
+
+function sessionRow(session: TestSession) {
+ return cy.findByTestId(`session-row-${session.id}`);
+}
+
+/** The row of the session the admin's own browser is using, flagged "This session" */
+function currentSessionRow() {
+ return cy
+ .findByTestId("sessions-table")
+ .findByText("This session")
+ .closest("[role='row']");
+}
+
+function sessionSidebar() {
+ return cy.findByTestId("session-detail-sidebar");
+}
+
+function confirmRevoke(title: string) {
+ H.modal().within(() => {
+ cy.findByText(title).should("be.visible");
+ cy.button("Revoke").click();
+ });
+ cy.wait("@revoke");
+}
+
+/** Switches to the Ended tab, checks that `sessions` are listed as revoked by an admin, and switches back */
+function expectRevokedOnEndedTab(...sessions: TestSession[]) {
+ cy.findByTestId("sessions-tab-ended").click();
+ sessions.forEach((session) =>
+ sessionRow(session).should("contain", "Revoked by admin"),
+ );
+ cy.findByTestId("sessions-tab-active").click();
+}
+
+function expectToast(message: string) {
+ H.undoToast().should("contain", message);
+ H.undoToast().icon("close").click();
+ H.undoToast().should("not.exist");
+}
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index cc85aa06e17..3aa3acf8d28 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -40,6 +40,7 @@
[metabase-enterprise.security-center.api]
[metabase-enterprise.semantic-search.api]
[metabase-enterprise.serialization.api]
+ [metabase-enterprise.session-management.api]
[metabase-enterprise.stale.api]
[metabase-enterprise.support-access-grants.api]
[metabase-enterprise.tenants.api]
@@ -74,6 +75,7 @@
:semantic-search (deferred-tru "Semantic Search")
:admin-security-center (deferred-tru "Security Center")
:serialization (deferred-tru "Serialization")
+ :session-management (deferred-tru "Session management")
:table-data-editing (deferred-tru "Table Data Editing")
:tenants (deferred-tru "Tenants")
:upload-management (deferred-tru "Upload Management")
@@ -160,6 +162,7 @@
"/semantic-search" (premium-handler metabase-enterprise.semantic-search.api/routes :semantic-search)
"/security-center" (premium-handler metabase-enterprise.security-center.api/routes :admin-security-center)
"/serialization" (premium-handler metabase-enterprise.serialization.api/routes :serialization)
+ "/session-management" (premium-handler metabase-enterprise.session-management.api/routes :session-management)
"/stale" (premium-handler metabase-enterprise.stale.api/routes :collection-cleanup)
"/support-access-grant" (premium-handler metabase-enterprise.support-access-grants.api/routes :support-users)
"/tenant" (premium-handler metabase-enterprise.tenants.api/routes :tenants)
diff --git a/enterprise/backend/src/metabase_enterprise/session_management/api.clj b/enterprise/backend/src/metabase_enterprise/session_management/api.clj
new file mode 100644
index 00000000000..5c1ade1f53c
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/session_management/api.clj
@@ -0,0 +1,294 @@
+(ns metabase-enterprise.session-management.api
+ "`/api/ee/session-management` endpoints — the admin-facing view of who is currently logged in."
+ (:require
+ [java-time.api :as t]
+ [metabase-enterprise.session-management.db :as sm.db]
+ [metabase-enterprise.session-management.schema :as sm.schema]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.events.core :as events]
+ [metabase.request.core :as request]
+ [metabase.session.core :as session]
+ [metabase.session.schema :as session.schema]
+ [metabase.users.models.user :as user]
+ [metabase.util.date-2 :as u.date]
+ [metabase.util.log :as log]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private session-providers
+ "The `auth_identity.provider` values a listable session can have, plus the `unknown` bucket for sessions with no
+ auth identity row: `core_session` rows predating the v58 `auth_identity_id` column. A password reset creates a
+ session attributed to the `password` identity, so `emailed-secret-password-reset` never appears here."
+ ["password" "ldap" "google" "slack-connect" "custom-oidc" "jwt" "saml" "support-access-grant" "unknown"])
+
+(mr/def ::FilterParams
+ "The criteria the list and the revoke share: every one of them can match a live session."
+ [:map {:closed true}
+ [:user-id {:optional true} ms/PositiveInt]
+ ;; a single `?ids=` arrives as a bare string; coerce so one id and many behave the same. `:and` decodes through
+ ;; its first child only, so the coercion runs before the length check
+ [:ids {:optional true} [:and (ms/QueryVectorOf :string) [:vector {:max 1000} :string]]]
+ ;; a single `?provider=` arrives as a bare string, coerced like `ids` above so one value and many behave the same
+ [:provider {:optional true} [:and
+ (ms/QueryVectorOf (into [:enum] session-providers))
+ [:vector {:max (count session-providers)}
+ (into [:enum] session-providers)]]]
+ [:type {:optional true} ::sm.schema/session-type]
+ [:tenancy {:default :all} [:enum :all :internal :external]]
+ [:created-before {:optional true} ms/TemporalString]
+ [:created-after {:optional true} ms/TemporalString]
+ [:last-active-before {:optional true} ms/TemporalString]
+ [:last-active-after {:optional true} ms/TemporalString]])
+
+(mr/def ::SortParams
+ [:map {:closed true}
+ [:sort-column {:default :created_at} ::sm.schema/session-sort-column]
+ [:sort-direction {:default :desc} [:enum :asc :desc]]])
+
+(mr/def ::ListParams
+ "The list's criteria: [[::FilterParams]], the sort, `query`, and `status` with the filters that only match ended
+ sessions."
+ ;; `query` lives here rather than in ::FilterParams because the revoke endpoint merges those filters, and revoking
+ ;; everyone whose name happens to match a substring is far easier to get wrong than revoking by explicit criteria.
+ [:merge
+ ::FilterParams
+ ::SortParams
+ [:map {:closed true}
+ [:query {:optional true} ms/NonBlankString]
+ [:status {:default :live} ::sm.schema/session-status]
+ [:reason {:optional true} ::session.schema/end-reason]
+ [:ended-before {:optional true} ms/TemporalString]
+ [:ended-after {:optional true} ms/TemporalString]]])
+
+(mr/def ::Session
+ [:map {:closed true}
+ [:id :string]
+ [:user [:map {:closed true}
+ [:id ms/PositiveInt]
+ [:email :string]
+ [:common_name [:maybe :string]]]]
+ [:type ::sm.schema/session-type]
+ [:provider :string]
+ [:created_at ms/TemporalInstant]
+ [:last_active_at [:maybe ms/TemporalInstant]]
+ [:expires_at ms/TemporalInstant]
+ [:user_agent [:maybe :string]]
+ [:device_description [:maybe :string]]
+ [:ip_address [:maybe :string]]
+ [:device_id [:maybe :string]]
+ [:current :boolean]
+ [:status [:enum "live" "ended"]]
+ ;; all three null for a live session, and for an ended one whose ending the nightly sweep has not recorded yet
+ [:ended_at [:maybe ms/TemporalInstant]]
+ [:end_reason [:maybe ::session.schema/end-reason]]
+ [:ended_by [:maybe ms/PositiveInt]]])
+
+(mr/def ::EndedOnlyCriterion
+ ;; declared purely to refuse the key: an undeclared key would be stripped rather than rejected, and a schema that
+ ;; only rejects a value would still let an explicit JSON `null` through and drop the filter
+ [:fn {:error/message "only live sessions can be revoked, so a filter that only matches ended ones is not allowed"}
+ (constantly false)])
+
+(mr/def ::RevokeByCriteriaParams
+ ;; [[::FilterParams]] rather than [[::ListParams]]: an ended session cannot be revoked, or removed early, so a
+ ;; `status` other than `live` — or `reason`, `ended-before`, `ended-after`, which only match ended sessions — is a
+ ;; 400 rather than something silently narrowed away
+ [:merge
+ ::FilterParams
+ [:map {:closed true}
+ [:status {:optional true} [:enum {:error/message "only live sessions can be revoked"} :live]]
+ [:reason {:optional true} ::EndedOnlyCriterion]
+ [:ended-before {:optional true} ::EndedOnlyCriterion]
+ [:ended-after {:optional true} ::EndedOnlyCriterion]
+ ;; in a JSON body `ids` arrives as a real array, so it needs none of the single-value coercion a query string does
+ [:ids {:optional true} [:sequential {:max 1000} :string]]
+ [:exclude-current {:default true} :boolean]
+ ;; Declared purely to refuse it: an undeclared key would be stripped rather than rejected
+ ;; ([[metabase.api.macros]]'s `strip-extra-keys-transformer`), so a caller who meant to narrow the revoke by name
+ ;; would instead revoke every live session.
+ [:query {:optional true}
+ [:fn {:error/message "not supported when revoking; list the sessions first, then revoke them by `ids`"}
+ (constantly false)]]]])
+
+(mr/def ::RevokeByCriteriaResult
+ [:map {:closed true}
+ [:revoked ms/IntGreaterThanOrEqualToZero]
+ [:remaining ms/IntGreaterThanOrEqualToZero]
+ [:user_ids [:sequential ms/PositiveInt]]])
+
+(mr/def ::RevokeByCriteriaResponse
+ ;; the second alternative is what a caller who revoked their own session gets: the same result inside a Ring
+ ;; response that clears their session cookie, exactly as `DELETE /api/session` does on logout. That is a transport
+ ;; detail, so `:openapi/response-schema` documents the result alone rather than both alternatives.
+ [:or {:openapi/response-schema ::RevokeByCriteriaResult}
+ ::RevokeByCriteriaResult
+ [:map {:closed true}
+ [:status [:= 200]]
+ [:body ::RevokeByCriteriaResult]
+ [:cookies [:map-of :string :map]]]])
+
+(mr/def ::SessionsResponse
+ [:map {:closed true}
+ [:total ms/IntGreaterThanOrEqualToZero]
+ [:limit [:maybe ms/PositiveInt]]
+ [:offset [:maybe ms/IntGreaterThanOrEqualToZero]]
+ [:data [:sequential ::Session]]])
+
+(defn- params->filters
+ "Turn the query params into the filter map [[metabase-enterprise.session-management.query/session-where]] takes,
+ parsing the date strings into instants."
+ [{:keys [status user-id ids provider type tenancy query
+ created-before created-after last-active-before last-active-after
+ reason ended-before ended-after]}]
+ {:status status
+ :user-id user-id
+ :ids ids
+ :provider provider
+ :type type
+ :tenancy (or tenancy :all)
+ ;; only the list endpoint can send this; the revoke endpoint's schema rejects it, so it arrives nil there
+ :query query
+ :created-before (some-> created-before u.date/parse)
+ :created-after (some-> created-after u.date/parse)
+ :last-active-before (some-> last-active-before u.date/parse)
+ :last-active-after (some-> last-active-after u.date/parse)
+ :reason reason
+ :ended-before (some-> ended-before u.date/parse)
+ :ended-after (some-> ended-after u.date/parse)})
+
+(defn- effective-expires-at
+ "When this session stops working: the earlier of the row's own hard `expires_at` and the `max-session-age` cap
+ measured from `created_at`. Nil only if the row has neither.
+
+ Not derived from the idle timeout — that is a sliding window which using the session pushes out, so this value does
+ not move when the session is used."
+ [created-at expires-at max-age-minutes]
+ ;; computed here rather than as SQL `LEAST(...)` because the cap needs date arithmetic that differs across H2,
+ ;; Postgres and MySQL, and nothing sorts on the result
+ (let [cap (when max-age-minutes (u.date/add created-at :minute max-age-minutes))]
+ (cond
+ (nil? cap) expires-at
+ (nil? expires-at) cap
+ (t/before? expires-at cap) expires-at
+ :else cap)))
+
+(defn- ->response-item
+ [max-age-minutes
+ {:keys [id user_id user_email user_first_name user_last_name created_at last_active_at expires_at
+ provider type current device_id ip_address user_agent live ended_at end_reason ended_by_user_id]}]
+ {:id id
+ :user (-> {:id user_id
+ :email user_email
+ :first_name user_first_name
+ :last_name user_last_name}
+ user/add-common-name
+ (select-keys [:id :email :common_name]))
+ :type type
+ ;; already coalesced to "unknown" in SQL, so what is sorted on is exactly what is shown
+ :provider provider
+ :created_at created_at
+ :last_active_at last_active_at
+ :expires_at (effective-expires-at created_at expires_at max-age-minutes)
+ :user_agent user_agent
+ :device_description (some-> user_agent request/describe-user-agent)
+ :ip_address ip_address
+ :device_id device_id
+ ;; the SQL returns 1/0 so that MySQL, which has no boolean type, can't hand back something else
+ :current (= 1 (long current))
+ ;; likewise; computed in SQL so the client never has to work out liveness itself
+ :status (if (= 1 (long live)) "live" "ended")
+ :ended_at ended_at
+ :end_reason end_reason
+ :ended_by ended_by_user_id})
+
+(api.macros/defendpoint :get "/" :- ::SessionsResponse
+ "List sessions. By default the ones that are currently live — the ones that would still authenticate a request.
+ `status=ended` lists instead the sessions that have ended: revoked, logged out, expired, idle past the session
+ timeout, or belonging to a deactivated user or an inactive tenant. An ended session stays on record for thirty
+ days, with when and why it ended (`ended_at`, `end_reason`) and who ended it (`ended_by`) once the nightly sweep
+ or the ending itself has recorded that; a session that has merely stopped being live since the last sweep is
+ already `ended`, with those three null. `status=all` lists both. `total` counts whatever the filters match.
+
+ Superuser only."
+ [_route-params
+ {:keys [sort-column sort-direction] :as params} :- [:maybe ::ListParams]
+ _body
+ {authed-session-key-hash :metabase/authed-session-key-hash, :as _request}]
+ (api/check-superuser)
+ (let [liveness (session/liveness-params)
+ filters (params->filters params)
+ limit (request/limit)
+ offset (request/offset)]
+ {:total (sm.db/session-count liveness filters)
+ :limit limit
+ :offset offset
+ :data (mapv (partial ->response-item (:max-age-minutes liveness))
+ (sm.db/sessions liveness filters
+ (or sort-column :created_at)
+ (or sort-direction :desc)
+ limit offset
+ authed-session-key-hash))}))
+
+(defn- record-revocation!
+ "Write the audit trail for a revoke by criteria: one `:event/sessions-revoked` summary row for the whole call, plus
+ one `:event/session-revoked` row per affected user, tied back to the summary by the criteria they share. Never
+ throws."
+ [criteria revoked remaining user-ids]
+ ;; published outside any transaction, and failures are swallowed after logging: the sessions are already gone by
+ ;; the time this runs, and an audit problem must not report otherwise to the caller
+ (try
+ (events/publish-event! :event/sessions-revoked
+ {:user-id api/*current-user-id*
+ :details {:criteria criteria, :count revoked, :remaining remaining}})
+ (doseq [[user-id revoked-for-user] (frequencies user-ids)]
+ (events/publish-event! :event/session-revoked
+ {:user-id api/*current-user-id*
+ :model :model/User
+ :model-id user-id
+ :details {:criteria criteria, :count revoked-for-user}}))
+ (catch Throwable e
+ (log/warn e "Error recording a session revocation in the audit log"))))
+
+(api.macros/defendpoint :post "/revoke" :- ::RevokeByCriteriaResponse
+ "Revoke — end — every live session matching the given criteria, which are the filters the list endpoint takes.
+ All of them have to hold, so a revoke ends exactly the sessions the same filters would have listed. An empty
+ body matches every live session: that is how an admin logs everybody out. A revoked session is destroyed as a
+ credential at once, and stays on record as ended for thirty days.
+
+ Only live sessions can be revoked, so `status` may only be `live` (or absent), and `reason`, `ended-before` and
+ `ended-after` — which only match ended sessions — are rejected with a 400.
+
+ `exclude-current` (default true) excludes the session this request was made with. Pass false to log the caller
+ out too, in which case the response also clears their session cookie.
+
+ Sessions that are no longer live are left for the nightly cleanup task to record rather than revoked, and sessions
+ belonging to MCP clients are never matched.
+
+ Returns how many sessions were `revoked`, how many live sessions still match the criteria afterwards (`remaining`,
+ non-zero only when a login raced the revoke), and the `user_ids` whose sessions were revoked. Superuser only."
+ [_route-params
+ _query-params
+ body :- [:maybe ::RevokeByCriteriaParams]
+ {current-hash :metabase/authed-session-key-hash, :as _request}]
+ (api/check-superuser)
+ (let [criteria (dissoc (or body {}) :exclude-current)
+ exclude-current? (get body :exclude-current true)
+ liveness (session/liveness-params)
+ filters (params->filters criteria)
+ {:keys [revoked user-ids current-revoked?]}
+ (sm.db/revoke-live-sessions! liveness filters current-hash exclude-current? api/*current-user-id*)]
+ (log/infof "User %s revoked %d session(s) matching %s" api/*current-user-id* revoked (pr-str criteria))
+ (let [remaining (sm.db/revocable-session-count liveness filters current-hash exclude-current?)
+ response {:revoked revoked, :remaining remaining, :user_ids (vec (distinct user-ids))}]
+ (record-revocation! criteria revoked remaining user-ids)
+ (if current-revoked?
+ (request/clear-session-cookie response)
+ response))))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/session-management` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/session_management/db.clj b/enterprise/backend/src/metabase_enterprise/session_management/db.clj
new file mode 100644
index 00000000000..24d1b0aa851
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/session_management/db.clj
@@ -0,0 +1,131 @@
+(ns metabase-enterprise.session-management.db
+ "Application database queries for session management, so that no other namespace in the module runs a query itself.
+ The HoneySQL they are assembled from lives in [[metabase-enterprise.session-management.query]]."
+ (:require
+ [metabase-enterprise.session-management.query :as sm.query]
+ [metabase-enterprise.session-management.schema :as sm.schema]
+ [metabase.lib.schema.id :as lib.schema.id]
+ [metabase.session.core :as session]
+ [metabase.session.schema :as session.schema]
+ [metabase.util.honey-sql-2 :as h2x]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.schema :as ms]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Listing sessions |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(mu/defn sessions :- [:sequential :map]
+ "The sessions matching `filters` — live ones unless `:status` says otherwise — ordered per
+ `sort-column`/`sort-direction`. `:live` (1/0) says whether each row is live, whatever `:status` asked for.
+
+ `current-key-hash` is the hashed session key of the request being served (nil when the caller authenticated some
+ other way); the `:current` column is computed in SQL against it so that `key_hashed` itself never leaves the
+ database. `anti_csrf_token` likewise stays in the database — only the derived `:type` comes back."
+ [liveness :- ::session.schema/liveness-params
+ filters :- ::sm.schema/session-filters
+ sort-column :- ::sm.schema/session-sort-column
+ sort-direction :- [:enum :asc :desc]
+ limit :- [:maybe ms/PositiveInt]
+ offset :- [:maybe ms/IntGreaterThanOrEqualToZero]
+ current-key-hash :- [:maybe :string]]
+ (t2/query
+ (cond-> (merge sm.query/session-list-from-and-joins
+ {:select [[:session.id :id]
+ [:session.user_id :user_id]
+ [:user.email :user_email]
+ [:user.first_name :user_first_name]
+ [:user.last_name :user_last_name]
+ [:session.created_at :created_at]
+ [:session.last_active_at :last_active_at]
+ [:session.expires_at :expires_at]
+ [:session.ended_at :ended_at]
+ [:session.end_reason :end_reason]
+ [:session.ended_by_user_id :ended_by_user_id]
+ [(session/live-expr liveness) :live]
+ [sm.query/provider-expr :provider]
+ [sm.query/type-expr :type]
+ ;; 1/0 rather than a boolean: MySQL has no boolean type and would hand back a number
+ ;; from a bare comparison anyway, so be explicit and normalise in Clojure
+ [(if current-key-hash
+ [:case [:= :session.key_hashed current-key-hash] [:inline 1] :else [:inline 0]]
+ [:inline 0])
+ :current]
+ [:lh.device_id :device_id]
+ [:lh.ip_address :ip_address]
+ [:lh.device_description :user_agent]]
+ :where (sm.query/session-where liveness filters)
+ :order-by (sm.query/session-order-by sort-column sort-direction)})
+ limit (assoc :limit limit)
+ offset (assoc :offset offset))))
+
+(mu/defn- count-where :- ms/IntGreaterThanOrEqualToZero
+ "How many `core_session` rows satisfy `where`."
+ [where :- ::h2x/honeysql-expr]
+ (-> (t2/query (merge sm.query/session-list-from-and-joins
+ {:select [[[:count [:inline 1]] :count]]
+ :where where}))
+ first
+ :count
+ long))
+
+(mu/defn session-count :- ms/IntGreaterThanOrEqualToZero
+ "How many sessions match `filters`, `:status` included. Uses the same joins and predicates as [[sessions]], so the
+ total can never disagree with the rows being paged through."
+ [liveness :- ::session.schema/liveness-params
+ filters :- ::sm.schema/session-filters]
+ (count-where (sm.query/session-where liveness filters)))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Revoking sessions |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(mu/defn revocable-session-count :- ms/IntGreaterThanOrEqualToZero
+ "How many live sessions [[revoke-live-sessions!]] would end for these arguments. Called again after a revoke to
+ report how many still match — 0 unless a login raced it."
+ [liveness :- ::session.schema/liveness-params
+ filters :- ::sm.schema/session-filters
+ current-key-hash :- [:maybe :string]
+ exclude-current? :- :boolean]
+ (count-where (sm.query/revoke-where liveness filters current-key-hash exclude-current?)))
+
+(mu/defn revoke-live-sessions! :- ::sm.schema/revocation
+ "End every live session matching `filters`, recording `actor-id` as the admin who revoked it, and report what that
+ did. The criteria are the ones [[sessions]] takes, so a revoke ends exactly the set a list with the same filters
+ would have shown; rows that are no longer live (and MCP-backed rows, which never are) are left alone for the
+ cleanup task.
+
+ When `exclude-current?` the session `current-key-hash` identifies is held back, so a caller sweeping every session
+ stays logged in. Either way `:current-revoked?` says whether the caller's own session was one of the rows ended.
+
+ `:user-ids` has one entry per session ended rather than per user, so `frequencies` gives the per-user count."
+ [liveness :- ::session.schema/liveness-params
+ filters :- ::sm.schema/session-filters
+ current-key-hash :- [:maybe :string]
+ exclude-current? :- :boolean
+ actor-id :- ::lib.schema.id/user]
+ (let [current-expr (if current-key-hash
+ ;; 1/0 rather than a boolean, for the same reason as in [[sessions]]
+ [:case [:= :session.key_hashed current-key-hash] [:inline 1] :else [:inline 0]]
+ [:inline 0])
+ matched (t2/query (merge session/session-from-and-joins
+ {:select [[:session.id :id]
+ [:session.user_id :user_id]
+ [current-expr :current]]
+ :where (sm.query/revoke-where liveness filters current-key-hash
+ exclude-current?)}))
+ ;; the select is what tells us which rows (and whose) went, for the response and the audit trail; an UPDATE
+ ;; over these joined criteria also has no single-statement form that works on H2, MySQL, and Postgres
+ revoked (session/end-sessions-by-ids! (mapv :id matched) "admin" actor-id)]
+ (when (not= revoked (count matched))
+ ;; benign, and only ever fewer: the update names the matched ids, so a session that logs in after the select is
+ ;; untouched (it is what `remaining` reports), while one logged out or swept by cleanup in between is a miss here
+ (log/infof "Revoke matched %d session(s) but ended %d; the rest went away in between"
+ (count matched) revoked))
+ {:revoked revoked
+ :user-ids (mapv :user_id matched)
+ :current-revoked? (boolean (some #(= 1 (long (:current %))) matched))}))
diff --git a/enterprise/backend/src/metabase_enterprise/session_management/query.clj b/enterprise/backend/src/metabase_enterprise/session_management/query.clj
new file mode 100644
index 00000000000..65c239f8db9
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/session_management/query.clj
@@ -0,0 +1,159 @@
+(ns metabase-enterprise.session-management.query
+ "The HoneySQL session management builds but does not run: how the live sessions are filtered and sorted.
+ [[metabase-enterprise.session-management.db]] is what executes these against the application database. The
+ liveness predicates themselves come from the `session` module, so whatever would not authenticate a request is not
+ listed either."
+ (:require
+ [clojure.string :as str]
+ [metabase-enterprise.session-management.schema :as sm.schema]
+ [metabase.session.core :as session]
+ [metabase.session.schema :as session.schema]
+ [metabase.util.honey-sql-2 :as h2x]
+ [metabase.util.malli :as mu]))
+
+(set! *warn-on-reflection* true)
+
+(def session-list-from-and-joins
+ "[[metabase.session.core/session-from-and-joins]] plus the `lh` alias for the device columns. `login_history` has at
+ most one row per session, so this cannot multiply rows."
+ ;; kept separate because the per-request auth lookup runs on every API call and must not pay for this join
+ (update session/session-from-and-joins :left-join into [[:login_history :lh] [:= :lh.session_id :session.id]]))
+
+(def last-active-expr
+ "`last_active_at`, falling back to `created_at` for a session that has never been touched. The same expression the
+ idle-timeout predicate uses, so filtering and sorting agree with expiry."
+ [:coalesce :session.last_active_at :session.created_at])
+
+(def provider-expr
+ "The provider as callers see it: a session with no auth identity row reads as `unknown` rather than null."
+ [:coalesce :auth_identity.provider (h2x/literal "unknown")])
+
+(def type-expr
+ "The session type as callers see it. Derived from whether the row carries an anti-CSRF token, so that
+ `anti_csrf_token` itself never has to leave the database."
+ [:case [:= :session.anti_csrf_token nil] (h2x/literal "normal")
+ :else (h2x/literal "full-app-embed")])
+
+(defn- provider-where
+ "The predicate for a set of auth methods. `unknown` is the bucket for sessions with no auth identity row rather than
+ a provider anyone can log in with, so it tests the column for NULL while the rest test membership; selecting both
+ asks for either. An empty selection matches nothing."
+ [providers]
+ (let [named (remove #{"unknown"} providers)
+ terms (cond-> []
+ (some #{"unknown"} providers) (conj [:= :auth_identity.provider nil])
+ (seq named) (conj [:in :auth_identity.provider named]))]
+ (case (count terms)
+ 0 [:inline false]
+ 1 (first terms)
+ (into [:or] terms))))
+
+(defn- owner-search-where
+ "The predicate for a free-text search over the session owner. Every whitespace-separated term has to match the
+ first name, last name or email, so a full name matches even though no single column contains it."
+ [search]
+ (into [:and]
+ (for [term (str/split (str/trim search) #"\s+")
+ :let [wildcard (h2x/like-substring term)]]
+ [:or
+ [:like [:lower :user.first_name] wildcard]
+ [:like [:lower :user.last_name] wildcard]
+ [:like [:lower :user.email] wildcard]])))
+
+(mu/defn- status-conditions :- [:sequential :any]
+ "The HoneySQL predicates for a `status` filter. `:live` is the `session` module's own liveness. `:ended` is its
+ negation, or a recorded ending — so a session that stopped being live since the last sweep is already ended, and a
+ recorded ending stays ended whatever the predicates would say now. `:all` is both. MCP-backed rows are not sessions
+ and are excluded under every value."
+ [liveness :- ::session.schema/liveness-params
+ status :- [:maybe ::sm.schema/session-status]]
+ (case (or status :live)
+ :live (session/live-session-conditions liveness)
+ :ended [session/not-mcp-session
+ [:or
+ [:not= :session.ended_at nil]
+ [:not (into [:and] (session/live-session-conditions liveness))]]]
+ :all [session/not-mcp-session]))
+
+(mu/defn filters->where :- [:sequential :any]
+ "The HoneySQL predicates for `filters` (see `::sm.schema/session-filters`) other than `status`, for a query using
+ [[metabase.session.core/session-from-and-joins]]. Independent of the current request so that listing sessions and
+ revoking them by criteria stay in lockstep: whatever a filtered list shows is exactly what the same filters would
+ revoke.
+
+ Date ranges are half-open — `after` is inclusive, `before` exclusive — so adjacent ranges neither overlap nor
+ leave a gap."
+ [{:keys [user-id ids provider type tenancy query
+ created-before created-after last-active-before last-active-after
+ reason ended-before ended-after]}
+ :- ::sm.schema/session-filters]
+ (cond-> []
+ user-id
+ (conj [:= :session.user_id user-id])
+
+ ;; an explicitly empty id list matches nothing; `IN ()` is not valid SQL anywhere
+ (some? ids)
+ (conj (if (seq ids) [:in :session.id ids] [:inline false]))
+
+ ;; an explicitly empty provider list matches nothing, for the same reason as `ids` above
+ (some? provider)
+ (conj (provider-where provider))
+
+ ;; only full-app-embed sessions carry an anti-CSRF token
+ (= type "normal")
+ (conj [:= :session.anti_csrf_token nil])
+
+ (= type "full-app-embed")
+ (conj [:not= :session.anti_csrf_token nil])
+
+ (= tenancy :internal)
+ (conj [:= :user.tenant_id nil])
+
+ (= tenancy :external)
+ (conj [:not= :user.tenant_id nil])
+
+ (not (str/blank? query))
+ (conj (owner-search-where query))
+
+ created-after (conj [:>= :session.created_at created-after])
+ created-before (conj [:< :session.created_at created-before])
+ last-active-after (conj [:>= last-active-expr last-active-after])
+ last-active-before (conj [:< last-active-expr last-active-before])
+
+ ;; these three only ever match a session whose ending has been recorded
+ reason (conj [:= :session.end_reason reason])
+ ended-after (conj [:>= :session.ended_at ended-after])
+ ended-before (conj [:< :session.ended_at ended-before])))
+
+(mu/defn session-where :- ::h2x/honeysql-expr
+ "The `:where` for a session-management query: the sessions of the `status` in `filters` (live by default) matching
+ the rest of `filters`."
+ [liveness :- ::session.schema/liveness-params
+ filters :- ::sm.schema/session-filters]
+ (into [:and] cat [(status-conditions liveness (:status filters)) (filters->where filters)]))
+
+(mu/defn revoke-where :- ::h2x/honeysql-expr
+ "The predicates a `core_session` row must satisfy to be revoked by these criteria: live (whatever `status` says: an
+ ended session cannot be revoked, or removed early), matching `filters`, and — when `exclude-current?` — not the
+ session `current-key-hash` identifies. The hash is only ever compared in SQL, so `key_hashed` never leaves the
+ database."
+ [liveness :- ::session.schema/liveness-params
+ filters :- ::sm.schema/session-filters
+ current-key-hash :- [:maybe :string]
+ exclude-current? :- :boolean]
+ (cond-> (session-where liveness (assoc filters :status :live))
+ (and exclude-current? current-key-hash)
+ (conj [:not= :session.key_hashed current-key-hash])))
+
+(defn session-order-by
+ "The `:order-by` for the session list."
+ [sort-column sort-direction]
+ [[(case sort-column
+ :last_active_at last-active-expr
+ :user_email :user.email
+ :provider provider-expr
+ :ended_at :session.ended_at
+ :session.created_at)
+ sort-direction]
+ ;; a stable tiebreaker, so paging can't show or skip a row because two sessions share a timestamp
+ [:session.id :asc]])
diff --git a/enterprise/backend/src/metabase_enterprise/session_management/schema.clj b/enterprise/backend/src/metabase_enterprise/session_management/schema.clj
new file mode 100644
index 00000000000..482875948fc
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/session_management/schema.clj
@@ -0,0 +1,52 @@
+(ns metabase-enterprise.session-management.schema
+ (:require
+ [metabase.lib.schema.id :as lib.schema.id]
+ [metabase.session.schema :as session.schema]
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]))
+
+(set! *warn-on-reflection* true)
+
+(mr/def ::session-type
+ "How a session was created: an ordinary login, or a full-app embedding one. Derived from whether the `core_session`
+ row carries an anti-CSRF token, which only full-app-embed sessions do."
+ [:enum "normal" "full-app-embed"])
+
+(mr/def ::session-status
+ "Which sessions a query is about: the `live` ones (the default), the `ended` ones, or `all` of them."
+ [:enum :live :ended :all])
+
+(mr/def ::session-filters
+ "The filters accepted by [[metabase-enterprise.session-management.query/filters->where]]. Temporal values arrive
+ already parsed. `:query` is a free-text search over the session owner's name and email; only the list endpoint
+ accepts it, since revoking by a name search is far easier to get wrong than revoking by an explicit criterion.
+ `status` defaults to `:live`; the `reason` and `ended-*` filters only ever match ended sessions."
+ [:map {:closed true}
+ [:status {:optional true} [:maybe ::session-status]]
+ [:user-id {:optional true} [:maybe ::lib.schema.id/user]]
+ [:ids {:optional true} [:maybe [:sequential :string]]]
+ [:provider {:optional true} [:maybe [:sequential :string]]]
+ [:type {:optional true} [:maybe ::session-type]]
+ [:tenancy {:optional true} [:maybe [:enum :all :internal :external]]]
+ [:query {:optional true} [:maybe :string]]
+ [:created-before {:optional true} [:maybe ms/TemporalInstant]]
+ [:created-after {:optional true} [:maybe ms/TemporalInstant]]
+ [:last-active-before {:optional true} [:maybe ms/TemporalInstant]]
+ [:last-active-after {:optional true} [:maybe ms/TemporalInstant]]
+ [:reason {:optional true} [:maybe ::session.schema/end-reason]]
+ [:ended-before {:optional true} [:maybe ms/TemporalInstant]]
+ [:ended-after {:optional true} [:maybe ms/TemporalInstant]]])
+
+(mr/def ::revocation
+ "What [[metabase-enterprise.session-management.db/revoke-live-sessions!]] reports about a revoke."
+ [:map {:closed true}
+ [:revoked ms/IntGreaterThanOrEqualToZero]
+ [:user-ids [:sequential ::lib.schema.id/user]]
+ [:current-revoked? :boolean]])
+
+(mr/def ::session-sort-column
+ "Columns the session list can be sorted by. `:last_active_at` sorts on the same
+ `COALESCE(last_active_at, created_at)` the idle-timeout predicate uses, so a session that has never been touched
+ sorts by when it was created rather than last. `:ended_at` is null for a live session, and for an ended one whose
+ ending the nightly sweep has not recorded yet."
+ [:enum :created_at :last_active_at :user_email :provider :ended_at])
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
index 577821928dd..a7a03e54d34 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
@@ -105,9 +105,9 @@
{:keys [email sso_source saml_session_index saml_name_id saml_name_id_format]}
(sso.db/session-user-email-and-source metabase-session-key-hashed)]
;; If a user doesn't have SLO setup on their IdP,
- ;; they will never hit "/handle_slo" so we must delete the session here:
+ ;; they will never hit "/handle_slo" so we must end the session here:
(when-not (sso-settings/saml-slo-enabled)
- (sso.db/delete-session! metabase-session-key-hashed))
+ (session/end-sessions! {:key_hashed metabase-session-key-hashed} "sso-logout" :self))
{:saml-logout-url
(when (and (sso-settings/saml-slo-enabled)
(= sso_source "saml"))
diff --git a/enterprise/backend/src/metabase_enterprise/sso/db.clj b/enterprise/backend/src/metabase_enterprise/sso/db.clj
index 8765e862fab..ae3d303e0ef 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/db.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/db.clj
@@ -19,11 +19,6 @@
:join [[:core_session :session] [:= :u.id :session.user_id]]
:where [:= :key_hashed session-key-hashed]}))
-(mu/defn delete-session!
- "Delete the Session with `session-key-hashed`, returning the number deleted."
- [session-key-hashed :- :string]
- (t2/delete! :model/Session :key_hashed session-key-hashed))
-
(mu/defn group-ids-by-name
"The IDs of the PermissionsGroups named one of `group-names`."
[group-names :- [:set :string]]
diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj
index 3ad5013796a..d76c40896b1 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj
@@ -32,7 +32,6 @@
[clojure.string :as str]
[java-time.api :as t]
[metabase-enterprise.sso.api.interface :as sso.i]
- [metabase-enterprise.sso.db :as sso.db]
[metabase-enterprise.sso.integrations.saml-utils :as saml-utils]
[metabase-enterprise.sso.integrations.sso-utils :as sso-utils]
[metabase-enterprise.sso.integrations.token-utils :as token-utils]
@@ -242,7 +241,7 @@
:response-validators [:signature :require-authenticated :issuer]})]
(if-let [metabase-session-key (and (saml/logout-success? response) (get-in cookies [request/metabase-session-cookie :value]))]
(do
- (sso.db/delete-session! (session/hash-session-key metabase-session-key))
+ (session/end-sessions! {:key_hashed (session/hash-session-key metabase-session-key)} "sso-logout" :self)
(request/clear-session-cookie (response/redirect (system/site-url))))
{:status 500 :body "SAML logout failed."}))
(log/warn "SAML SLO is not enabled, not continuing Single Log Out flow.")))
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj
index 9e3bf710ff2..6c3553d433a 100644
--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj
@@ -100,13 +100,13 @@
[]
(when-let [{support-user-id :id, superuser? :is_superuser}
(support-access-grants.db/user-superuser-flag-by-email (sag.settings/support-access-grant-email))]
- (when (or superuser? (support-access-grants.db/session-exists-for-user? support-user-id))
+ (when (or superuser? (support-access-grants.db/unended-session-exists-for-user? 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)))))))
+ (sag.model/revoke-support-user-access! support-user-id (t/instant) nil))))))
(defn list-grants
"List support access grants with optional filtering and pagination.
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/db.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/db.clj
index f05ef8f1466..e52cf47bde5 100644
--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/db.clj
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/db.clj
@@ -106,15 +106,10 @@
changes :- (mut/select-keys ::users.schema/user.update [:is_active :is_superuser])]
(t2/update! :model/User user-id changes))
-(mu/defn session-exists-for-user?
- "Whether the User with `user-id` has a Session."
+(mu/defn unended-session-exists-for-user?
+ "Whether the User with `user-id` has a Session whose ending has not been recorded."
[user-id :- ::lib.schema.id/user]
- (t2/exists? :model/Session :user_id user-id))
-
-(mu/defn delete-sessions-of-user!
- "Delete the Sessions of the User with `user-id`, returning the number deleted."
- [user-id :- ::lib.schema.id/user]
- (t2/delete! :model/Session :user_id user-id))
+ (t2/exists? :model/Session :user_id user-id :ended_at nil))
(mu/defn auth-identity-ids-of-user
"The IDs of the AuthIdentities of the User with `user-id`."
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.clj
index 445dd20b794..77a9f5ca17c 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
@@ -4,6 +4,7 @@
[metabase-enterprise.support-access-grants.db :as support-access-grants.db]
[metabase-enterprise.support-access-grants.settings :as sag.settings]
[metabase.models.interface :as mi]
+ [metabase.session.core :as session]
[metabase.util :as u]
[metabase.util.log :as log]
[methodical.core :as methodical]
@@ -47,9 +48,9 @@
(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]
+ time-limited password can't be used again, and end their sessions, recorded as ended by `ended-by` (the revoking
+ user, or nil when the grant simply ran out). Called both when a grant is explicitly revoked and when one runs out."
+ [support-user-id ended-at ended-by]
(let [auth-identity-ids (support-access-grants.db/auth-identity-ids-of-user support-user-id)]
(try
(support-access-grants.db/update-user! support-user-id {:is_superuser false})
@@ -59,11 +60,11 @@
(log/warnf "Could not remove superuser from support user %d: %s" support-user-id (ex-message e))))
(when (seq auth-identity-ids)
(support-access-grants.db/expire-auth-identities! auth-identity-ids ended-at))
- (support-access-grants.db/delete-sessions-of-user! support-user-id)))
+ (session/end-sessions! {:user_id support-user-id} "support-grant-revoked" ended-by)))
(t2/define-after-update :model/SupportAccessGrantLog
- [{revoked-at :revoked_at :as grant}]
+ [{revoked-at :revoked_at, revoked-by :revoked_by_user_id, :as grant}]
(u/prog1 grant
(when revoked-at
(when-let [support-user (support-access-grants.db/user-by-email (sag.settings/support-access-grant-email))]
- (revoke-support-user-access! (:id support-user) revoked-at)))))
+ (revoke-support-user-access! (:id support-user) revoked-at revoked-by)))))
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj
index 9a37a94769d..08c480077f2 100644
--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj
@@ -106,5 +106,6 @@
(:id user) grant-ends-at)
(t2/with-transaction [_]
(support-access-grants.db/update-auth-identity! (:id auth-identity) (auth-identity/mark-token-consumed auth-identity))
- (auth-identity/set-password! (:id user) password {:expires-at grant-ends-at}))))
+ ;; the support user is who is changing their own password here, so they are who ends their sessions
+ (auth-identity/set-password! (:id user) password {:expires-at grant-ends-at, :ended-by (:id user)}))))
result)
diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
index f2da7ea8bdd..331de7c103d 100644
--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
@@ -52,6 +52,7 @@
:scim
:semantic-search
:serialization
+ :session-management
:session-timeout-config
:snippet-collections
:sso-google
@@ -106,6 +107,7 @@
:scim true
:semantic_search true
:serialization true
+ :session-management true
:session_timeout_config true
:snippet_collections true
:sso_google true
@@ -198,25 +200,26 @@
(t2/insert! (t2/table-name :model/Session)
{:id session-id :key_hashed key-hashed :user_id user-id :created_at :%now})
(testing "first call should update last_active_at"
- (#'mw.session/maybe-update-session-activity! session-key)
+ (#'mw.session/maybe-update-session-activity! key-hashed)
(is (some? (t2/select-one-fn :last_active_at (t2/table-name :model/Session) :key_hashed key-hashed))))
(testing "immediate second call should be throttled (no error, just skipped)"
(let [first-value (t2/select-one-fn :last_active_at (t2/table-name :model/Session) :key_hashed key-hashed)]
- (#'mw.session/maybe-update-session-activity! session-key)
+ (#'mw.session/maybe-update-session-activity! key-hashed)
(is (= first-value
(t2/select-one-fn :last_active_at (t2/table-name :model/Session) :key_hashed key-hashed)))))))))))
;;; ---------------------------------------- session cleanup idle sessions test ----------------------------------------
(deftest cleanup-idle-sessions-test
- (testing "With session-timeout configured, idle sessions are also cleaned up"
+ (testing "With session-timeout configured, idle sessions are recorded as timed out by the sweep"
(mt/with-premium-features #{:session-timeout-config}
(mt/with-temporary-setting-values [session-timeout {:amount 5 :unit "minutes"}]
(mt/with-temp [:model/User {user-id :id}]
(let [active-id (session/generate-session-id)
active-key (session/hash-session-key (str (random-uuid)))
idle-id (session/generate-session-id)
- idle-key (session/hash-session-key (str (random-uuid)))
+ idle-cookie (session/generate-session-key)
+ idle-key (session/hash-session-key idle-cookie)
no-activity-id (session/generate-session-id)
no-activity-key (session/hash-session-key (str (random-uuid)))]
;; Active session: last_active_at = now
@@ -233,9 +236,50 @@
{:id no-activity-id :key_hashed no-activity-key :user_id user-id
:created_at :%now})
(#'session-cleanup/cleanup-sessions!)
- (testing "active session is kept"
- (is (t2/exists? :model/Session :id active-id)))
- (testing "idle session is deleted"
- (is (not (t2/exists? :model/Session :id idle-id))))
- (testing "session with NULL last_active_at but recent created_at is kept"
- (is (t2/exists? :model/Session :id no-activity-id)))))))))
+ (testing "active session is kept live"
+ (is (nil? (t2/select-one-fn :ended_at :model/Session :id active-id))))
+ (testing "idle session is recorded as timed out, its key destroyed, and the row kept"
+ (is (=? {:end_reason "timed-out", :ended_at some?, :ended_by_user_id nil, :key_hashed nil}
+ (t2/select-one :model/Session :id idle-id))))
+ (testing "session with NULL last_active_at but recent created_at is kept live"
+ (is (nil? (t2/select-one-fn :ended_at :model/Session :id no-activity-id))))
+ (testing "raising the idle timeout afterwards does not revive the timed-out session"
+ (mt/with-temporary-setting-values [session-timeout {:amount 1 :unit "hours"}]
+ (is (= "Unauthenticated" (mt/client idle-cookie :get 401 "user/current")))))))))))
+
+(deftest cleanup-tenant-deactivated-sessions-test
+ (testing "the sweep records a session of a deactivated tenant's user as tenant-deactivated"
+ (mt/with-additional-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "SM41 T1" :slug "sm41-t1" :is_active true}
+ :model/User {external :id} {:tenant_id tenant-id}
+ :model/User {internal :id} {}]
+ (let [session! (fn [user-id]
+ (let [id (session/generate-session-id)]
+ (t2/insert! (t2/table-name :model/Session)
+ {:id id
+ :key_hashed (session/hash-session-key (str (random-uuid)))
+ :user_id user-id
+ :created_at :%now})
+ id))
+ ended (fn [session-id]
+ (select-keys (t2/select-one :model/Session :id session-id)
+ [:end_reason :ended_by_user_id :key_hashed]))
+ external-session (session! external)
+ internal-session (session! internal)]
+ (t2/update! (t2/table-name :model/Tenant) tenant-id {:is_active false})
+ (#'session-cleanup/cleanup-sessions!)
+ (is (= {:end_reason "tenant-deactivated", :ended_by_user_id nil, :key_hashed nil}
+ (ended external-session)))
+ (is (nil? (:end_reason (ended internal-session)))
+ "a user without a tenant is unaffected")
+ (testing "with tenants switched off, a user with any tenant at all is not live"
+ (t2/update! (t2/table-name :model/Tenant) tenant-id {:is_active true})
+ (mt/with-temporary-setting-values [use-tenants false]
+ ;; switching tenants off deactivates their users, and that deactivation ends their sessions on the
+ ;; spot; reactivate through the raw table and start a fresh session, so that the tenant predicate
+ ;; is the only thing rejecting it
+ (t2/update! (t2/table-name :model/User) external {:is_active true})
+ (let [another (session! external)]
+ (#'session-cleanup/cleanup-sessions!)
+ (is (= "tenant-deactivated" (:end_reason (ended another)))))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj b/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj
index d6838d0d514..66d3a32c9dc 100644
--- a/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/mfa/gate_test.clj
@@ -108,7 +108,10 @@
;; child must be classified here on its own when it ships
:provider/emailed-secret :exempt
;; the second factor itself, never a first factor
- :provider/totp :exempt}]
+ :provider/totp :exempt
+ ;; not a login provider: it attributes the `core_session` rows an MCP handshake creates,
+ ;; which never run `login!`; the user proved their identity to obtain the OAuth grant
+ :provider/mcp :exempt}]
(testing "every registered provider has a deliberate MFA classification"
(is (= (set (keys classification))
(set (auth-identity/descendants :metabase.auth-identity.provider/provider)))))
diff --git a/enterprise/backend/test/metabase_enterprise/session_management/api_test.clj b/enterprise/backend/test/metabase_enterprise/session_management/api_test.clj
new file mode 100644
index 00000000000..cb34f08f4d4
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/session_management/api_test.clj
@@ -0,0 +1,686 @@
+(ns metabase-enterprise.session-management.api-test
+ "Tests for the `/api/ee/session-management` endpoints."
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [medley.core :as m]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.open-api :as open-api]
+ [metabase.app-db.core :as mdb]
+ [metabase.request.core :as request]
+ [metabase.session.core :as session]
+ [metabase.session.db :as session.db]
+ [metabase.test :as mt]
+ [metabase.test.data.users :as test.users]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util :as u]
+ [metabase.util.date-2 :as u.date]
+ [metabase.util.honey-sql-2 :as h2x]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :db :web-server :test-users))
+
+(use-fixtures :each (fn [f] (mt/with-premium-features #{:session-management}
+ (f))))
+
+(defn- ago [amount unit]
+ (h2x/add-interval-honeysql-form (mdb/db-type) (h2x/current-datetime-honeysql-form (mdb/db-type)) (- amount) unit))
+
+(defn- from-now [amount unit]
+ (h2x/add-interval-honeysql-form (mdb/db-type) (h2x/current-datetime-honeysql-form (mdb/db-type)) amount unit))
+
+(defn- insert-session!
+ "Insert a `core_session` row directly, bypassing the model hooks so timestamps can be arbitrary (including DB-side)
+ expressions. Returns the session id."
+ [user-id & {:as extra-cols}]
+ (let [id (session/generate-session-id)]
+ (t2/insert! (t2/table-name :model/Session)
+ (merge {:id id
+ :key_hashed (session/hash-session-key (str (random-uuid)))
+ :user_id user-id
+ :created_at :%now}
+ extra-cols))
+ id))
+
+(defn- list-sessions
+ "`GET /api/ee/session-management` as crowberto, scoped to `user-id` so parallel tests can't leak into the assertions."
+ [user-id & {:as params}]
+ (apply mt/user-http-request :crowberto :get 200 "ee/session-management"
+ (mapcat identity (merge {:user-id user-id} params))))
+
+(defn- ids [response]
+ (mapv :id (:data response)))
+
+(defn- insert-session-with-key!
+ "Insert a `core_session` row for `user-id` the way a login would, returning `[session-id session-key]`. The key is
+ the plaintext credential a client sends in the `X-Metabase-Session` header; only its hash is stored."
+ [user-id & {:as extra-cols}]
+ (let [session-key (session/generate-session-key)
+ session-id (apply insert-session! user-id
+ (mapcat identity (merge {:key_hashed (session/hash-session-key session-key)}
+ extra-cols)))]
+ [session-id session-key]))
+
+(defn- ended?
+ "Whether the session's ending has been recorded: `ended_at` set. Every revoke keeps the row, so \"revoked\" means
+ ended, not gone."
+ [session-id]
+ (some? (t2/select-one-fn :ended_at (t2/table-name :model/Session) :id session-id)))
+
+(defn- ending
+ "How the session ended: its reason and actor, and whether its key was destroyed."
+ [session-id]
+ (select-keys (t2/select-one :model/Session :id session-id) [:end_reason :ended_by_user_id :key_hashed]))
+
+(deftest api-requires-session-management-feature-test
+ (testing "without the feature every endpoint answers 402, whoever is asking"
+ (mt/with-premium-features #{}
+ (let [message (str "Session management is a paid feature not currently available to your instance. "
+ "Please upgrade to use it. Learn more at metabase.com/upgrade/")]
+ (doseq [[method path body] [[:get "ee/session-management"]
+ [:post "ee/session-management/revoke" {}]]
+ user [:crowberto :rasta]]
+ (testing (str method " " path " as " user)
+ (is (=? {:message message}
+ (apply mt/user-http-request user method 402 path (when body [body]))))))
+ (testing "unauthenticated"
+ (is (=? {:message message}
+ (mt/client :get 402 "ee/session-management"))))))))
+
+(deftest permissions-test
+ (testing "GET /api/ee/session-management is superuser-only"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/session-management")))
+ (is (map? (mt/user-http-request :crowberto :get 200 "ee/session-management")))))
+
+(deftest shape-test
+ (testing "each item carries the user, device, and expiry columns — and never the session credential"
+ (mt/with-temp [:model/User {user-id :id} {:first_name "Sess" :last_name "Ion" :email "[email protected]"}]
+ (let [session-id (insert-session! user-id)
+ ;; device_id is CHAR(36); a shorter value comes back space-padded on H2
+ device-id (str (random-uuid))]
+ (t2/insert! :model/LoginHistory {:user_id user-id
+ :session_id session-id
+ :device_id device-id
+ :device_description (str "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/124.0 Safari/537.36")
+ :ip_address "127.0.0.1"})
+ (let [item (first (:data (list-sessions user-id)))]
+ (is (= session-id (:id item)))
+ (is (= {:id user-id :email "[email protected]" :common_name "Sess Ion"} (:user item)))
+ (is (= "normal" (:type item)))
+ (is (= "unknown" (:provider item)))
+ (is (= device-id (:device_id item)))
+ (is (= "127.0.0.1" (:ip_address item)))
+ (is (str/includes? (:user_agent item) "Chrome"))
+ (testing "device_description is the humanized user agent, not the raw string"
+ (is (= (request/describe-user-agent (:user_agent item)) (:device_description item)))
+ (is (not= (:user_agent item) (:device_description item))))
+ (testing "the hashed session key is never returned"
+ (is (not (contains? item :key_hashed)))
+ (is (not (contains? item :anti_csrf_token)))))))))
+
+(deftest ended-sessions-are-hidden-by-default-test
+ (testing "ended rows are absent from both `data` and `total` unless `status` asks for them"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [live (insert-session! user-id)
+ ended (insert-session! user-id :key_hashed nil :ended_at (ago 1 :hour) :end_reason "logout")
+ ;; stopped being live since the last sweep, so nothing is recorded on it yet
+ expired (insert-session! user-id :expires_at (ago 1 :second))]
+ (testing "the default is live"
+ (let [response (list-sessions user-id)]
+ (is (= 1 (:total response)))
+ (is (= [live] (ids response)))
+ (is (=? {:status "live", :ended_at nil, :end_reason nil, :ended_by nil} (first (:data response))))))
+ (testing "`status=ended` lists the ended sessions with when, why, and by whom"
+ (let [response (list-sessions user-id :status "ended")]
+ (is (= 2 (:total response)))
+ (is (= #{ended expired} (set (ids response))))
+ (is (=? {:id ended, :status "ended", :ended_at some?, :end_reason "logout", :ended_by nil, :current false}
+ (m/find-first #(= ended (:id %)) (:data response))))
+ (testing "a session that expired since the last sweep is ended, with those three null"
+ (is (=? {:id expired, :status "ended", :ended_at nil, :end_reason nil, :ended_by nil}
+ (m/find-first #(= expired (:id %)) (:data response)))))))
+ (testing "`status=all` lists both"
+ (let [response (list-sessions user-id :status "all")]
+ (is (= 3 (:total response)))
+ (is (= #{live ended expired} (set (ids response))))
+ (is (= {live "live", ended "ended", expired "ended"}
+ (into {} (map (juxt :id :status)) (:data response))))))
+ (testing "any other status is a 400"
+ (is (=? {:errors {:status some?}}
+ (mt/user-http-request :crowberto :get 400 "ee/session-management" :status "dead"))))))))
+
+(deftest ended-filters-and-sort-test
+ (testing "`reason` and `ended-after` narrow the ended sessions; `sort-column=ended_at` orders them"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [older (insert-session! user-id :key_hashed nil :ended_at (ago 2 :hour) :end_reason "admin"
+ :ended_by_user_id (mt/user->id :crowberto))
+ newer (insert-session! user-id :key_hashed nil :ended_at (ago 1 :hour) :end_reason "admin"
+ :ended_by_user_id (mt/user->id :crowberto))
+ logout (insert-session! user-id :key_hashed nil :ended_at (ago 3 :hour) :end_reason "logout")
+ _live (insert-session! user-id)
+ an-hour-and-a-half-ago (u.date/add (t/zoned-date-time) :minute -90)]
+ (let [response (list-sessions user-id :status "ended" :reason "admin")]
+ (is (= 2 (:total response)))
+ (is (= #{older newer} (set (ids response))))
+ (is (every? #(= (mt/user->id :crowberto) (:ended_by %)) (:data response))))
+ (is (= [newer] (ids (list-sessions user-id :status "ended" :ended-after (str an-hour-and-a-half-ago)))))
+ (is (= #{older logout} (set (ids (list-sessions user-id :status "ended"
+ :ended-before (str an-hour-and-a-half-ago))))))
+ (is (= [logout older newer] (ids (list-sessions user-id :status "ended" :sort-column "ended_at"
+ :sort-direction "asc"))))
+ (is (= [newer older logout] (ids (list-sessions user-id :status "ended" :sort-column "ended_at"
+ :sort-direction "desc"))))
+ (testing "`reason` on the live list is a valid request that matches nothing"
+ (is (= 0 (:total (list-sessions user-id :reason "admin")))))
+ (testing "an unknown reason is a 400"
+ (is (=? {:errors {:reason some?}}
+ (mt/user-http-request :crowberto :get 400 "ee/session-management" :reason "boredom"))))))))
+
+(deftest ended-session-is-never-current-test
+ (testing "the caller's own ended session is `current: false`: a destroyed key cannot match theirs"
+ (mt/with-temp [:model/User {admin-id :id} {:is_superuser true}]
+ (let [[current session-key] (insert-session-with-key! admin-id)
+ revoked (insert-session! admin-id)]
+ (mt/client session-key :post 200 "ee/session-management/revoke" {:ids [revoked]})
+ (let [response (mt/client session-key :get 200 "ee/session-management" :user-id admin-id :status "all")]
+ (is (= {current true, revoked false} (into {} (map (juxt :id :current)) (:data response)))))))))
+
+(deftest expired-sessions-are-excluded-test
+ (testing "expired rows are absent from both `data` and `total`"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [live (insert-session! user-id)
+ _hard (insert-session! user-id :expires_at (ago 1 :second))
+ _future (insert-session! user-id :expires_at (from-now 1 :hour))
+ response (list-sessions user-id)]
+ (is (= 2 (:total response)))
+ (is (= 2 (count (:data response))))
+ (is (contains? (set (ids response)) live))))))
+
+(deftest deactivated-user-sessions-are-excluded-test
+ (testing "a deactivated user's sessions vanish from the list even though the rows survive"
+ (mt/with-temp [:model/User {user-id :id} {:is_active true}]
+ (let [session-id (insert-session! user-id)]
+ (is (= 1 (:total (list-sessions user-id))))
+ ;; the raw table, not `:model/User`: the model's before-update publishes
+ ;; `:event/user-credentials-revoked`, whose handler deletes the user's sessions outright (SEC-863). Going
+ ;; through the model would leave no row for the liveness predicate to reject, so this test would pass even
+ ;; with `[:= :user.is_active true]` deleted from `live-session-conditions`.
+ (t2/update! (t2/table-name :model/User) user-id {:is_active false})
+ (is (t2/exists? (t2/table-name :model/Session) :id session-id)
+ "the session row survives deactivation; it is the predicate that must reject it")
+ (let [response (list-sessions user-id)]
+ (is (= 0 (:total response)))
+ (is (= [] (:data response))))))))
+
+(deftest mcp-sessions-are-never-listed-test
+ (testing "an MCP-stamped session is invisible whatever the filters"
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity {mcp-id :id} {:user_id user-id :provider "mcp"}]
+ (let [normal (insert-session! user-id)]
+ (insert-session! user-id :auth_identity_id mcp-id)
+ (is (= [normal] (ids (list-sessions user-id))))
+ (is (= 1 (:total (list-sessions user-id))))
+ (is (= [normal] (ids (list-sessions user-id :provider "unknown"))))
+ (is (= [] (ids (list-sessions user-id :type "full-app-embed"))))))))
+
+(deftest expires-at-test
+ (testing "`expires_at` is the earlier of the row's own expiry and the max-session-age cap"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [_capped (insert-session! user-id)
+ item (first (:data (list-sessions user-id)))
+ created (t/instant (u.date/parse (str (:created_at item))))]
+ (is (some? (:expires_at item)) "never null")
+ (testing "with no hard expiry it is created_at + max-session-age (14 days by default)"
+ (is (= (t/plus created (t/minutes 20160))
+ (t/instant (u.date/parse (str (:expires_at item)))))))))))
+
+(deftest expires-at-does-not-move-when-the-session-is-used-test
+ (testing "using a session must not push out the reported expiry — it is a hard cap, not the idle window"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (insert-session! user-id)
+ (let [before (:expires_at (first (:data (list-sessions user-id))))]
+ ;; this is what `touch-session!` does on every authenticated request
+ (t2/query {:update (t2/table-name :model/Session)
+ :set {:last_active_at :%now}
+ :where [:= :user_id user-id]})
+ (is (= before (:expires_at (first (:data (list-sessions user-id))))))))))
+
+(deftest filter-by-ids-test
+ (testing "`ids` selects an explicit set of sessions, and an empty set selects none"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [a (insert-session! user-id)
+ b (insert-session! user-id)
+ c (insert-session! user-id)]
+ (is (= 3 (:total (list-sessions user-id))))
+ (is (= #{a c} (set (ids (list-sessions user-id :ids [a c])))))
+ (is (= 2 (:total (list-sessions user-id :ids [a c]))))
+ (is (= #{b} (set (ids (list-sessions user-id :ids [b])))))))))
+
+(deftest search-by-owner-test
+ (testing "`query` searches the session owner's first name, last name, and email"
+ (mt/with-temp [:model/User {ann :id} {:first_name "Ann" :last_name "Admin"
+ :email "[email protected]"}
+ :model/User {bob :id} {:first_name "Bob" :last_name "Boss"
+ :email "[email protected]"}]
+ (let [ann-session (insert-session! ann)
+ bob-session (insert-session! bob)
+ listed (fn [& {:as params}]
+ (set (ids (apply mt/user-http-request :crowberto :get 200 "ee/session-management"
+ (mapcat identity (merge {:ids [ann-session bob-session]} params))))))]
+ (testing "first name"
+ (is (= #{ann-session} (listed :query "ann"))))
+ (testing "last name, case-insensitively"
+ (is (= #{bob-session} (listed :query "BOSS"))))
+ (testing "email"
+ (is (= #{ann-session} (listed :query "ann@search"))))
+ (testing "every whitespace-separated term has to match, so a full name works"
+ (is (= #{ann-session} (listed :query "ann admin")))
+ (is (= #{} (listed :query "ann boss"))))
+ (testing "a term matching nobody lists nothing"
+ (is (= #{} (listed :query "nobody"))))
+ (testing "`total` agrees with the filtered rows"
+ (is (= 1 (:total (mt/user-http-request :crowberto :get 200 "ee/session-management"
+ :ids [ann-session bob-session] :query "ann")))))
+ (testing "LIKE wildcards in the query are matched literally"
+ (is (= #{} (listed :query "a%n"))))))))
+
+(deftest revoke-rejects-a-query-test
+ (testing "POST /revoke does not accept `query`: a name search is too blunt an instrument to revoke by"
+ (mt/with-temp [:model/User {user-id :id} {:first_name "Ann" :last_name "Admin"}]
+ (let [session-id (insert-session! user-id)]
+ (is (some? (mt/user-http-request :crowberto :post 400 "ee/session-management/revoke"
+ {:query "ann"})))
+ (is (not (ended? session-id))
+ "a rejected request revokes nothing")))))
+
+(deftest filter-by-type-test
+ (testing "`type` splits normal sessions from full-app-embed ones by whether they carry an anti-CSRF token"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [normal (insert-session! user-id)
+ embed (insert-session! user-id :anti_csrf_token "0123456789abcdef0123456789abcdef")]
+ (is (= [normal] (ids (list-sessions user-id :type "normal"))))
+ (is (= [embed] (ids (list-sessions user-id :type "full-app-embed"))))
+ (is (= "full-app-embed" (:type (first (:data (list-sessions user-id :type "full-app-embed"))))))))))
+
+(deftest filter-by-provider-test
+ (testing "`provider` filters on the auth identity, with `unknown` for sessions that have none"
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity {pw-id :id} {:user_id user-id :provider "password" :credentials {:plaintext_password "sM28-p4ssw0rd!"}}]
+ (let [unknown (insert-session! user-id)
+ password (insert-session! user-id :auth_identity_id pw-id)]
+ (is (= [password] (ids (list-sessions user-id :provider "password"))))
+ (is (= [unknown] (ids (list-sessions user-id :provider "unknown"))))
+ (is (= "password" (:provider (first (:data (list-sessions user-id :provider "password"))))))
+ (is (= "unknown" (:provider (first (:data (list-sessions user-id :provider "unknown"))))))
+ (testing "`mcp` is not an accepted filter value: those sessions are never listed"
+ (is (some? (mt/user-http-request :crowberto :get 400 "ee/session-management" :provider "mcp"))))))))
+
+(deftest filter-by-several-providers-test
+ (testing "`provider` accepts a list: the sessions on any of the named auth methods"
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity {saml-id :id} {:user_id user-id :provider "saml"}
+ :model/AuthIdentity {jwt-id :id} {:user_id user-id :provider "jwt"}]
+ (let [unknown (insert-session! user-id)
+ saml (insert-session! user-id :auth_identity_id saml-id)
+ jwt (insert-session! user-id :auth_identity_id jwt-id)]
+ (testing "two named providers"
+ (is (= #{saml jwt} (set (ids (list-sessions user-id :provider ["saml" "jwt"])))))
+ (is (= 2 (:total (list-sessions user-id :provider ["saml" "jwt"])))))
+ (testing "`unknown` mixed with a named one asks for either, since it means \"no auth identity row\""
+ (is (= #{unknown saml} (set (ids (list-sessions user-id :provider ["unknown" "saml"]))))))
+ (testing "one value behaves the same whether sent bare or as a list"
+ (is (= [saml] (ids (list-sessions user-id :provider "saml"))))
+ (is (= [saml] (ids (list-sessions user-id :provider ["saml"])))))
+ (testing "an unaccepted value is rejected even alongside valid ones"
+ (is (some? (mt/user-http-request :crowberto :get 400 "ee/session-management"
+ :provider ["saml" "mcp"]))))))))
+
+(deftest ids-length-limit-test
+ (testing "`ids` may name at most 1000 sessions: every id is a bind parameter, and a page never holds more"
+ (let [at-limit (vec (repeat 1000 "a"))
+ too-many (conj at-limit "a")]
+ (testing "GET"
+ ;; one-character ids keep the 1001-key query string under Jetty's request header limit, so the 400 is malli's
+ (is (some? (mt/user-http-request :crowberto :get 400 "ee/session-management" :ids too-many)))
+ (is (= 0 (:total (mt/user-http-request :crowberto :get 200 "ee/session-management" :ids at-limit)))
+ "the limit is inclusive")
+ (is (= 0 (:total (mt/user-http-request :crowberto :get 200 "ee/session-management" :ids "a")))
+ "and a single bare id is still coerced to a vector before the length check"))
+ (testing "POST"
+ (is (some? (mt/user-http-request :crowberto :post 400 "ee/session-management/revoke" {:ids too-many})))
+ (is (= 0 (:revoked (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke" {:ids at-limit})))
+ "the limit is inclusive")))))
+
+(deftest filter-by-created-at-test
+ (testing "`created-before`/`created-after` bound a half-open range on created_at"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [old (insert-session! user-id :created_at (ago 3 :day))
+ new (insert-session! user-id)]
+ (is (= [new] (ids (list-sessions user-id :created-after (str (t/minus (t/offset-date-time) (t/days 1)))))))
+ (is (= [old] (ids (list-sessions user-id :created-before (str (t/minus (t/offset-date-time) (t/days 1)))))))))))
+
+(deftest filter-by-last-active-test
+ (testing "`last-active-*` filter on COALESCE(last_active_at, created_at), so an untouched session uses created_at"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [stale (insert-session! user-id :created_at (ago 3 :day) :last_active_at (ago 3 :day))
+ recent (insert-session! user-id :created_at (ago 3 :day) :last_active_at (ago 1 :minute))
+ fresh (insert-session! user-id)
+ cutoff (str (t/minus (t/offset-date-time) (t/days 1)))]
+ (is (= #{recent fresh} (set (ids (list-sessions user-id :last-active-after cutoff)))))
+ (is (= [stale] (ids (list-sessions user-id :last-active-before cutoff))))))))
+
+(deftest sort-test
+ (mt/with-temp [:model/User {user-a :id} {:email "[email protected]"}
+ :model/User {user-b :id} {:email "[email protected]"}
+ :model/AuthIdentity {pw-id :id} {:user_id user-b :provider "password" :credentials {:plaintext_password "sM28-p4ssw0rd!"}}]
+ ;; `older` was created first but touched most recently; `newer` has never been touched, so its
+ ;; COALESCE(last_active_at, created_at) is its creation time. That makes the two orderings disagree, which is the
+ ;; whole point of the last_active_at case.
+ (let [older (insert-session! user-a :created_at (ago 1 :hour) :last_active_at (ago 10 :second))
+ newer (insert-session! user-b :created_at (ago 5 :minute) :auth_identity_id pw-id)
+ listed (fn [& {:as params}]
+ (mapv :id (:data (apply mt/user-http-request :crowberto :get 200 "ee/session-management"
+ (mapcat identity (merge {:ids [older newer]} params))))))]
+ (testing "created_at desc is the default"
+ (is (= [newer older] (listed))))
+ (is (= [older newer] (listed :sort-column "created_at" :sort-direction "asc")))
+ (testing "last_active_at sorts on the COALESCE, so the older but recently-touched session wins"
+ (is (= [older newer] (listed :sort-column "last_active_at" :sort-direction "desc"))))
+ (testing "user_email"
+ (is (= [older newer] (listed :sort-column "user_email" :sort-direction "asc")))
+ (is (= [newer older] (listed :sort-column "user_email" :sort-direction "desc"))))
+ (testing "provider sorts on the displayed value, so a null provider orders as \"unknown\" rather than by where
+ the app DB happens to put NULLs (first on H2/MySQL, last on Postgres)"
+ (is (= {older "unknown" newer "password"}
+ (into {} (map (juxt :id :provider))
+ (:data (mt/user-http-request :crowberto :get 200 "ee/session-management" :ids [older newer])))))
+ (is (= [newer older] (listed :sort-column "provider" :sort-direction "asc"))
+ "\"password\" sorts before \"unknown\"")
+ (is (= [older newer] (listed :sort-column "provider" :sort-direction "desc")))))))
+
+(deftest current-test
+ (testing "the session the request itself was made with is flagged, and no other"
+ (let [crowberto (mt/user->id :crowberto)
+ other (insert-session! crowberto)
+ response (mt/user-http-request :crowberto :get 200 "ee/session-management" :user-id crowberto)
+ by-id (into {} (map (juxt :id :current)) (:data response))]
+ (is (false? (get by-id other)))
+ (is (= 1 (count (filter true? (vals by-id))))
+ "exactly one session is current"))))
+
+(deftest pagination-test
+ (testing "limit/offset page the list while `total` stays the unpaged count"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (dotimes [i 3]
+ (insert-session! user-id :created_at (ago (inc i) :minute)))
+ (let [page (mt/user-http-request :crowberto :get 200 "ee/session-management" :user-id user-id :limit 2 :offset 0)]
+ (is (= 3 (:total page)))
+ (is (= 2 (count (:data page))))
+ (is (= 2 (:limit page)))
+ (is (= 0 (:offset page))))
+ (testing "no limit means every row, per house convention"
+ (let [all (list-sessions user-id)]
+ (is (= 3 (count (:data all))))
+ (is (nil? (:limit all))))))))
+
+(deftest tenancy-test
+ ;; Tenants are enterprise-only: :model/Tenant is not on the OSS classpath, so guard the body out of OSS builds
+ ;; entirely (with-premium-features only flips the flag, it does not load EE code).
+ (mt/when-ee-evailable
+ (mt/with-additional-premium-features #{:tenants}
+ (mt/with-temporary-setting-values [use-tenants true]
+ (mt/with-temp [:model/Tenant {tenant-id :id} {:name "SM28 T1" :slug "sm28-t1"}
+ :model/User {external :id} {:tenant_id tenant-id}
+ :model/User {internal :id} {}]
+ (let [ext-session (insert-session! external)
+ int-session (insert-session! internal)
+ listed (fn [& {:as params}]
+ (set (ids (apply mt/user-http-request :crowberto :get 200 "ee/session-management"
+ (mapcat identity (merge {:ids [ext-session int-session]} params))))))]
+ (testing "external-tenant sessions are listed by default"
+ (is (= #{ext-session int-session} (listed)))
+ (is (= #{ext-session int-session} (listed :tenancy "all"))))
+ (testing "tenancy=internal hides them"
+ (is (= #{int-session} (listed :tenancy "internal"))))
+ (testing "tenancy=external shows only them"
+ (is (= #{ext-session} (listed :tenancy "external"))))
+ (testing "a session belonging to a deactivated tenant is not live at all"
+ (t2/update! :model/Tenant tenant-id {:is_active false})
+ (is (= #{int-session} (listed))))))))))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | POST /api/ee/session-management/revoke |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(deftest revoke-by-criteria-permissions-test
+ (testing "POST /api/ee/session-management/revoke is superuser-only"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [session-id (insert-session! user-id)]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "ee/session-management/revoke" {:ids [session-id]})))
+ (is (not (ended? session-id))
+ "a rejected request revokes nothing")))))
+
+(deftest revoke-everything-test
+ (testing "an empty filter map means every live session — except the caller's, which `exclude-current` holds back"
+ (mt/with-temp [:model/User {admin-id :id} {:is_superuser true}
+ :model/User {user-id :id} {}]
+ (let [[caller session-key] (insert-session-with-key! admin-id)
+ other (insert-session! user-id)]
+ (try
+ (let [response (mt/client session-key :post 200 "ee/session-management/revoke" {})]
+ (is (zero? (:remaining response))
+ "nothing live still matches, so the caller's own session was excluded from the count too")
+ (is (<= 2 (:revoked response)))
+ (is (contains? (set (:user_ids response)) user-id))
+ (is (ended? other))
+ (is (not (ended? caller))
+ "the caller stays logged in"))
+ (finally
+ ;; the sweep took the cached test-user sessions with it; the next request has to log in again
+ (test.users/clear-cached-session-tokens!)))))))
+
+(deftest revoke-including-current-test
+ (testing "`exclude-current` false revokes the caller's own session too, and clears their session cookie"
+ (mt/with-temp [:model/User {admin-id :id} {:is_superuser true}]
+ (let [[caller session-key] (insert-session-with-key! admin-id)
+ response (mt/client-full-response session-key :post 200 "ee/session-management/revoke"
+ {:user-id admin-id :exclude-current false})
+ cookies (str/join " " (u/one-or-many (get-in response [:headers "Set-Cookie"])))]
+ (is (= 1 (:revoked (:body response))))
+ (is (zero? (:remaining (:body response))))
+ (is (ended? caller))
+ (is (str/includes? cookies "metabase.SESSION=;")
+ "the session cookie is cleared, as it is on logout")))))
+
+(deftest revoke-by-ids-test
+ (testing "`ids` revokes exactly those sessions; one that is no longer live is left for the cleanup task"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [live-a (insert-session! user-id)
+ live-b (insert-session! user-id)
+ expired (insert-session! user-id :expires_at (ago 1 :second))
+ untouched (insert-session! user-id)
+ response (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke"
+ {:ids [live-a live-b expired]})]
+ (is (= 2 (:revoked response)))
+ (is (zero? (:remaining response)))
+ (is (= [user-id] (:user_ids response)))
+ (testing "a revoked session is recorded as ended by the admin, and its key destroyed"
+ (is (= {:end_reason "admin", :ended_by_user_id (mt/user->id :crowberto), :key_hashed nil} (ending live-a)))
+ (is (= {:end_reason "admin", :ended_by_user_id (mt/user->id :crowberto), :key_hashed nil} (ending live-b))))
+ (is (not (ended? expired))
+ "an expired row is not live, so the revoke leaves it to the nightly sweep")
+ (is (not (ended? untouched))
+ "a live session outside the id list is untouched")
+ (testing "a repeat is a no-op: the ended ids match nothing"
+ (is (= {:revoked 0, :remaining 0, :user_ids []}
+ (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke"
+ {:ids [live-a live-b]}))))))))
+
+(deftest revoke-refuses-ended-only-criteria-test
+ (testing "criteria that could only select ended sessions are a 400, and nothing changes"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [live (insert-session! user-id)
+ ended (insert-session! user-id :key_hashed nil :ended_at (ago 1 :hour) :end_reason "logout")]
+ (doseq [body [{:user-id user-id :status "all"}
+ {:user-id user-id :status "ended"}
+ {:user-id user-id :reason "logout"}
+ {:user-id user-id :ended-before "2030-01-01T00:00:00Z"}
+ {:user-id user-id :ended-after "2020-01-01T00:00:00Z"}
+ ;; the key's presence is what is refused, whatever its value: an explicit null must not be
+ ;; read as "no filter" and drop away, leaving every live session matched
+ {:user-id user-id :reason nil}
+ {:user-id user-id :ended-before nil}
+ {:user-id user-id :ended-after nil}]]
+ (testing (pr-str body)
+ (is (=? {:errors map?}
+ (mt/user-http-request :crowberto :post 400 "ee/session-management/revoke" body)))))
+ (is (not (ended? live)) "nothing was revoked")
+ (is (= "logout" (:end_reason (ending ended))) "and nothing was touched")
+ (testing "`status: live` is the one value accepted, and means what the default means"
+ (is (= 1 (:revoked (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke"
+ {:user-id user-id :status "live"})))))
+ (testing "with none of those keys present the revoke goes ahead as usual"
+ (insert-session! user-id)
+ (is (= 1 (:revoked (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke"
+ {:user-id user-id})))))))))
+
+(deftest revoke-by-ids-and-provider-test
+ (testing "every criterion has to hold: `ids` narrows to a set, `provider` narrows within it"
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity {saml-id :id} {:user_id user-id :provider "saml"}
+ :model/AuthIdentity {pw-id :id} {:user_id user-id :provider "password"
+ :credentials {:plaintext_password "sM30-p4ssw0rd!"}}]
+ (let [saml-in (insert-session! user-id :auth_identity_id saml-id)
+ saml-out (insert-session! user-id :auth_identity_id saml-id)
+ password (insert-session! user-id :auth_identity_id pw-id)
+ response (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke"
+ {:ids [saml-in password] :provider "saml"})]
+ (is (= 1 (:revoked response)))
+ (is (ended? saml-in))
+ (is (not (ended? password))
+ "in the id list, but not a SAML session")
+ (is (not (ended? saml-out))
+ "a SAML session, but not in the id list")))))
+
+(deftest revoke-batches-the-update-test
+ (testing "a revoke bigger than one statement can name is still revoked in full, and counted in full"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [session-ids (vec (repeatedly 5 #(insert-session! user-id)))
+ end! (mt/original-fn #'session/end-sessions-by-ids!)]
+ ;; a real revoke batches at 1000 ids because every id is a bind parameter; two and a half batches of two
+ ;; exercises the same code, including the short final batch, without inserting thousands of rows
+ (mt/with-dynamic-fn-redefs [session/end-sessions-by-ids! (fn [ids reason ended-by]
+ (end! ids reason ended-by 2))]
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke" {:user-id user-id})]
+ (is (= 5 (:revoked response))
+ "every batch is counted, not just the last one")
+ (is (zero? (:remaining response)))
+ (is (every? ended? session-ids)
+ "including the rows in the short final batch")))))))
+
+(deftest revoke-race-test
+ (testing "a login that lands between the select and the delete is reported as `remaining`, not silently revoked"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [_matched (insert-session! user-id)
+ raced (atom nil)
+ end! (mt/original-fn #'session/end-sessions-by-ids!)]
+ (mt/with-dynamic-fn-redefs [session/end-sessions-by-ids! (fn [ids reason ended-by]
+ (reset! raced (insert-session! user-id))
+ (end! ids reason ended-by))]
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke" {:user-id user-id})]
+ (is (= 1 (:revoked response)))
+ (is (= 1 (:remaining response))
+ "the session created after the select is still live and still matches")
+ (is (not (ended? @raced))
+ "and it was not revoked")))))))
+
+(deftest revoke-count-mismatch-is-logged-test
+ (testing "a matched session that ends before the update is logged, not hidden in the counts"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [kept (insert-session! user-id)
+ gone (insert-session! user-id)
+ end! (mt/original-fn #'session/end-sessions-by-ids!)]
+ (mt/with-dynamic-fn-redefs [session/end-sessions-by-ids! (fn [ids reason ended-by]
+ ;; a logout between the select and the update
+ (session.db/end-sessions! {:id [gone]} "logout" :self)
+ (end! ids reason ended-by))]
+ (mt/with-log-messages-for-level [messages [metabase-enterprise.session-management.db :info]]
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke" {:user-id user-id})]
+ (is (= 1 (:revoked response)) "only the row actually ended by the revoke is counted")
+ (is (= "admin" (:end_reason (ending kept))))
+ (is (= "logout" (:end_reason (ending gone))) "the earlier ending is kept")
+ (is (some #(str/includes? (:message %) "matched 2 session(s) but ended 1") (messages))
+ "and the gap is written to the log"))))))))
+
+(deftest revoke-audit-test
+ (testing "a revoke writes one summary row plus one row per affected user, and never touches an MCP session"
+ (mt/with-additional-premium-features #{:audit-app}
+ (mt/with-model-cleanup [:model/AuditLog]
+ (mt/with-temp [:model/User {user-a :id} {}
+ :model/User {user-b :id} {}
+ :model/AuthIdentity {mcp-id :id} {:user_id user-a :provider "mcp"}]
+ (let [a1 (insert-session! user-a)
+ a2 (insert-session! user-a)
+ b1 (insert-session! user-b)
+ mcp (insert-session! user-a :auth_identity_id mcp-id)
+ response (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke"
+ {:ids [a1 a2 b1 mcp]})]
+ (is (= 3 (:revoked response)))
+ (is (= #{user-a user-b} (set (:user_ids response))))
+ (is (not (ended? mcp))
+ "an MCP-backed session is never live, so it is never matched")
+ (testing "the summary row carries the criteria, the count, and what is left"
+ (let [{:keys [topic user_id model model_id details]} (mt/latest-audit-log-entry "sessions-revoked")]
+ (is (= :sessions-revoked topic))
+ (is (= (mt/user->id :crowberto) user_id))
+ (is (nil? model))
+ (is (nil? model_id))
+ (is (= 3 (:count details)))
+ (is (= 0 (:remaining details)))
+ (is (= #{a1 a2 b1 mcp} (set (get-in details [:criteria :ids]))))
+ (testing "and never a session key or its hash"
+ (is (not (str/includes? (str details) "key_hashed"))))))
+ (testing "one row per affected user, naming that user"
+ (doseq [[user-id revoked] {user-a 2, user-b 1}]
+ (let [{:keys [topic user_id model model_id details]}
+ (mt/latest-audit-log-entry "session-revoked" user-id)]
+ (is (= :session-revoked topic))
+ (is (= (mt/user->id :crowberto) user_id) "the actor, not the affected user")
+ (is (= "User" model))
+ (is (= user-id model_id))
+ (is (= revoked (:count details))))))))))))
+
+(deftest revoke-logs-without-audit-feature-test
+ (testing "the revoke is logged even when the audit log is not being written"
+ (mt/with-premium-features #{:session-management}
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [session-id (insert-session! user-id)]
+ (mt/with-log-messages-for-level [messages [metabase-enterprise.session-management.api :info]]
+ (mt/user-http-request :crowberto :post 200 "ee/session-management/revoke" {:ids [session-id]})
+ (let [line (some #(when (str/includes? (:message %) "revoked") (:message %)) (messages))
+ hashes (t2/select-fn-set :key_hashed (t2/table-name :model/Session)
+ :user_id (mt/user->id :crowberto) :ended_at nil)]
+ (is (some? line) "an info line is written whatever the token allows")
+ (is (str/includes? line (format "User %d revoked 1 session" (mt/user->id :crowberto)))
+ "the actor and the count, not just some digits")
+ (is (str/includes? line session-id) "the criteria")
+ (testing "and never the hash of a live session key"
+ (is (seq hashes) "sanity check: crowberto has a session whose hash could have leaked")
+ (is (not-any? #(str/includes? line %) hashes))))))))))
+
+;; The endpoint has to return a Ring response to set cookie headers, and must not let that transport detail become
+;; the documented response body.
+(deftest ^:parallel revoke-openapi-response-test
+ (let [paths (:paths (open-api/open-api-spec (api.macros/ns-handler 'metabase-enterprise.session-management.api) "/api/ee/session-management"))
+ schema (fn [path method]
+ (get-in paths [path method :responses "2XX" :content "application/json" :schema]))]
+ (testing "POST /revoke documents the result map, not the cookie-clearing alternative alongside it"
+ (is (= {:$ref "#/components/schemas/metabase-enterprise.session-management.api.RevokeByCriteriaResult"}
+ (schema "/api/ee/session-management/revoke" :post))))))
diff --git a/enterprise/backend/test/metabase_enterprise/session_management/query_test.clj b/enterprise/backend/test/metabase_enterprise/session_management/query_test.clj
new file mode 100644
index 00000000000..65d02c878a4
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/session_management/query_test.clj
@@ -0,0 +1,204 @@
+(ns metabase-enterprise.session-management.query-test
+ "Tests for the shared live-session query fragments. `metabase.server.middleware.session-test` covers the same
+ predicates from the authentication side; these cover them from the listing side, so that a change which makes a
+ session stop authenticating also makes it stop being listed. They run the fragments through
+ `metabase-enterprise.session-management.db`, which is what executes them."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.session-management.db :as sm.db]
+ [metabase-enterprise.session-management.query :as sm.query]
+ [metabase.app-db.core :as mdb]
+ [metabase.session.core :as session]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util.honey-sql-2 :as h2x]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :db))
+
+(defn- liveness
+ "Liveness params with everything switched off but `max-age-minutes`, so a test only opts into the predicate it is
+ about."
+ [& {:as overrides}]
+ (merge {:db-type (mdb/db-type)
+ :max-age-minutes 20160
+ :enable-tenants? false
+ :session-timeout-seconds nil}
+ overrides))
+
+(defn- insert-session!
+ "Insert a `core_session` row directly, bypassing the model hooks so `created_at`, `expires_at` and friends can be
+ arbitrary (including DB-side) expressions. Returns the session id."
+ [user-id & {:as extra-cols}]
+ (let [id (session/generate-session-id)]
+ (t2/insert! (t2/table-name :model/Session)
+ (merge {:id id
+ :key_hashed (session/hash-session-key (str (random-uuid)))
+ :user_id user-id
+ :created_at :%now}
+ extra-cols))
+ id))
+
+(defn- listed-ids
+ "The ids of the sessions matching `filters` (live ones, unless `:status` says otherwise). Every caller passes
+ `:user-id` so a test never sees sessions other tests left lying around."
+ [liveness-params & {:as filters}]
+ (into #{}
+ (map :id)
+ (sm.db/sessions liveness-params filters :created_at :desc nil nil nil)))
+
+(defn- ago [amount unit]
+ (h2x/add-interval-honeysql-form (mdb/db-type) (h2x/current-datetime-honeysql-form (mdb/db-type)) (- amount) unit))
+
+(defn- from-now [amount unit]
+ (h2x/add-interval-honeysql-form (mdb/db-type) (h2x/current-datetime-honeysql-form (mdb/db-type)) amount unit))
+
+(deftest live-session-conditions-max-age-test
+ (testing "a session past `max-session-age` is neither listed nor counted"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [fresh (insert-session! user-id)
+ old (insert-session! user-id :created_at (ago 61 :second))
+ lp (liveness :max-age-minutes 1)]
+ (is (= #{fresh} (listed-ids lp :user-id user-id)))
+ (is (= 1 (sm.db/session-count lp {:user-id user-id})))
+ (testing "and is listed again once the cap is wide enough to cover it"
+ (let [lp (liveness :max-age-minutes 20160)]
+ (is (= #{fresh old} (listed-ids lp :user-id user-id)))
+ (is (= 2 (sm.db/session-count lp {:user-id user-id})))))))))
+
+(deftest live-session-conditions-expires-at-test
+ (testing "`expires_at` in the past excludes a session even when it is well within `max-session-age`"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [no-expiry (insert-session! user-id)
+ not-yet (insert-session! user-id :expires_at (from-now 60 :second))
+ expired (insert-session! user-id :expires_at (ago 1 :second))
+ lp (liveness)]
+ (is (= #{no-expiry not-yet} (listed-ids lp :user-id user-id)))
+ (is (not (contains? (listed-ids lp :user-id user-id) expired)))
+ (is (= 2 (sm.db/session-count lp {:user-id user-id})))))))
+
+(deftest live-session-conditions-idle-timeout-test
+ (testing "with a session timeout configured, an idle session drops out — and `last_active_at` nil falls back to
+ `created_at` rather than counting as idle forever"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [never-touched (insert-session! user-id)
+ recently-active (insert-session! user-id
+ :created_at (ago 10 :minute)
+ :last_active_at (ago 10 :second))
+ idle (insert-session! user-id
+ :created_at (ago 10 :minute)
+ :last_active_at (ago 10 :minute))
+ lp (liveness :session-timeout-seconds 60)]
+ (is (= #{never-touched recently-active} (listed-ids lp :user-id user-id)))
+ (is (not (contains? (listed-ids lp :user-id user-id) idle)))
+ (is (= 2 (sm.db/session-count lp {:user-id user-id})))))))
+
+(deftest live-session-conditions-inactive-user-test
+ (testing "a deactivated user's surviving session rows are dead"
+ (mt/with-temp [:model/User {user-id :id} {:is_active true}]
+ (let [id (insert-session! user-id)
+ lp (liveness)]
+ (is (= #{id} (listed-ids lp :user-id user-id)))
+ ;; the raw table, not `:model/User`: the model's before-update publishes
+ ;; `:event/user-credentials-revoked`, whose handler deletes the user's sessions outright (SEC-863). Going
+ ;; through the model would leave nothing for `[:= :user.is_active true]` to reject, and this test would pass
+ ;; with that predicate deleted.
+ (t2/update! (t2/table-name :model/User) user-id {:is_active false})
+ (is (t2/exists? (t2/table-name :model/Session) :id id)
+ "the session row survives deactivation; it is the predicate that must reject it")
+ (is (= #{} (listed-ids lp :user-id user-id)))
+ (is (zero? (sm.db/session-count lp {:user-id user-id})))))))
+
+(deftest live-session-conditions-mcp-test
+ (testing "a session stamped with the `mcp` provider is never live, whatever the filters"
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity {mcp-id :id} {:user_id user-id :provider "mcp"}]
+ (let [normal (insert-session! user-id)
+ _mcp (insert-session! user-id :auth_identity_id mcp-id)
+ lp (liveness)]
+ (is (= #{normal} (listed-ids lp :user-id user-id)))
+ (is (= 1 (sm.db/session-count lp {:user-id user-id})))
+ (testing "not even when explicitly asking for the `unknown` provider bucket, which is what a null provider is"
+ ;; a list, not a bare string: the single-value coercion happens in the API schema, not down here
+ (is (= #{normal} (listed-ids lp :user-id user-id :provider ["unknown"]))))))))
+
+(deftest filters->where-test
+ (testing "an explicitly empty id list matches nothing rather than everything — `IN ()` is not valid SQL"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [id (insert-session! user-id)
+ lp (liveness)]
+ (is (= #{id} (listed-ids lp :user-id user-id)))
+ (is (= #{id} (listed-ids lp :user-id user-id :ids [id])))
+ (is (= #{} (listed-ids lp :user-id user-id :ids [])))
+ (is (= 0 (sm.db/session-count lp {:user-id user-id :ids []}))))))
+ (testing "`filters->where` is request-independent: the same map produces the same clauses"
+ (is (= (sm.query/filters->where {:user-id 1 :tenancy :internal})
+ (sm.query/filters->where {:user-id 1 :tenancy :internal})))
+ (is (empty? (sm.query/filters->where {})))
+ (is (empty? (sm.query/filters->where {:tenancy :all})))))
+
+(deftest filters->where-date-ranges-are-half-open-test
+ (testing "`created-after` is inclusive and `created-before` exclusive, so adjacent ranges neither overlap nor gap"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [t #t "2024-03-05T12:00:00Z"
+ id (insert-session! user-id :created_at t)
+ ;; no max-age cap, or the fixed timestamp above would age out and the range filter would never be reached
+ lp (liveness :max-age-minutes nil)]
+ (is (= #{id} (listed-ids lp :user-id user-id :created-after t)))
+ (is (= #{} (listed-ids lp :user-id user-id :created-before t)))
+ (is (= #{id} (listed-ids lp :user-id user-id
+ :created-after #t "2024-03-05T11:00:00Z"
+ :created-before #t "2024-03-05T13:00:00Z")))))))
+
+(deftest status-conditions-test
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity {mcp-id :id} {:user_id user-id :provider "mcp"}]
+ (let [live (insert-session! user-id)
+ stamped (insert-session! user-id :key_hashed nil :ended_at (ago 1 :hour) :end_reason "logout")
+ ;; not live, but the sweep has not recorded it yet
+ expired (insert-session! user-id :expires_at (ago 1 :second))
+ _mcp (insert-session! user-id :auth_identity_id mcp-id :expires_at (ago 1 :second))
+ lp (liveness)]
+ (testing "`:live` (the default) is the liveness predicate"
+ (is (= #{live} (listed-ids lp :user-id user-id)))
+ (is (= #{live} (listed-ids lp :user-id user-id :status :live))))
+ (testing "`:ended` is a recorded ending or the negation of liveness, so an unstamped expired row is ended too"
+ (is (= #{stamped expired} (listed-ids lp :user-id user-id :status :ended)))
+ (is (= 2 (sm.db/session-count lp {:user-id user-id :status :ended}))))
+ (testing "`:all` is both"
+ (is (= #{live stamped expired} (listed-ids lp :user-id user-id :status :all)))
+ (is (= 3 (sm.db/session-count lp {:user-id user-id :status :all}))))
+ (testing "an MCP-backed row is excluded under every status"
+ (is (= 4 (t2/count :model/Session :user_id user-id)) "sanity check: the MCP row exists"))
+ (testing "a recorded ending stays ended even though the row would pass the liveness predicates now"
+ (let [revived (insert-session! user-id :key_hashed nil :ended_at (ago 1 :second) :end_reason "admin")]
+ (is (not (contains? (listed-ids lp :user-id user-id) revived)))
+ (is (contains? (listed-ids lp :user-id user-id :status :ended) revived)))))))
+
+(deftest ended-filters-test
+ (testing "`reason` is an exact match on `end_reason`; `ended-after` is inclusive and `ended-before` exclusive"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [t #t "2024-03-05T12:00:00Z"
+ admin (insert-session! user-id :key_hashed nil :ended_at t :end_reason "admin")
+ logout (insert-session! user-id :key_hashed nil :ended_at t :end_reason "logout")
+ ;; unstamped: not live, but no `ended_at` for a range to match
+ _blank (insert-session! user-id :expires_at (ago 1 :second))
+ lp (liveness :max-age-minutes nil)]
+ (is (= #{admin} (listed-ids lp :user-id user-id :status :ended :reason "admin")))
+ (is (= #{admin logout} (listed-ids lp :user-id user-id :status :ended :ended-after t)))
+ (is (= #{} (listed-ids lp :user-id user-id :status :ended :ended-before t)))
+ (is (= #{logout} (listed-ids lp :user-id user-id :status :ended :reason "logout"
+ :ended-after #t "2024-03-05T11:00:00Z"
+ :ended-before #t "2024-03-05T13:00:00Z")))
+ (testing "the ended-only filters match nothing under `:live`, since a live session has no ending"
+ (is (= #{} (listed-ids lp :user-id user-id :reason "admin")))
+ (is (= #{} (listed-ids lp :user-id user-id :ended-after t))))))))
+
+(deftest ^:parallel revoke-where-ignores-status-test
+ (testing "`revoke-where` is always the live predicate, whatever `status` the filters carry"
+ (let [lp (liveness)]
+ (is (= (sm.query/revoke-where lp {:user-id 1} nil false)
+ (sm.query/revoke-where lp {:user-id 1 :status :all} nil false)
+ (sm.query/revoke-where lp {:user-id 1 :status :ended} nil false))))))
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
index 1670d00ad94..f3b38e678f4 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
@@ -794,13 +794,15 @@
default-redirect-uri)]
(client/client-real-response :post 401 "/auth/sso" req-options)))))))
-(deftest logout-should-delete-session-test-slo-enabled
- (testing "Successful SAML SLO logouts should delete the user's session, when saml-slo-enabled."
+(deftest logout-should-end-session-slo-enabled-test
+ (testing "Successful SAML SLO logouts should end the user's session, when saml-slo-enabled."
(with-other-sso-types-disabled!
(let [session-key (session/generate-session-key)
session-key-hashed (session/hash-session-key session-key)]
(mt/with-temp [:model/User user {:email "[email protected]" :sso_source "saml"}
- :model/Session _ {:user_id (:id user) :id (session/generate-session-id) :key_hashed session-key-hashed}]
+ :model/Session {session-id :id} {:user_id (:id user)
+ :id (session/generate-session-id)
+ :key_hashed session-key-hashed}]
(with-saml-default-setup!
(mt/with-temporary-setting-values [saml-slo-enabled true
saml-identity-provider-issuer "http://localhost:9090/realms/master"
@@ -814,11 +816,12 @@
response (client/client-real-response :post 302 "/auth/sso/handle_slo" req-options)]
(is (str/blank? (get-in response [:cookies request/metabase-session-cookie :value]))
"After a successful log-out, you don't have a session")
- (is (not (t2/exists? :model/Session :key_hashed session-key-hashed))
- "After a successful log-out, the session is deleted")))))))))
+ (is (=? {:end_reason "sso-logout", :ended_by_user_id (:id user), :ended_at some?, :key_hashed nil}
+ (t2/select-one :model/Session :id session-id))
+ "After a successful log-out, the session is ended and its key destroyed")))))))))
-(deftest logout-should-delete-session-test-slo-disabled
- (testing "Successful SAML SLO logouts should not delete the user's session, when not saml-slo-enabled."
+(deftest logout-should-end-session-slo-disabled-test
+ (testing "Successful SAML SLO logouts should not end the user's session, when not saml-slo-enabled."
(with-other-sso-types-disabled!
(mt/with-temporary-setting-values [saml-slo-enabled false]
(let [session-key (session/generate-session-key)
@@ -836,20 +839,24 @@
(is (str/blank? (get-in response [:cookies request/metabase-session-cookie :value]))
"After a successful log-out, you don't have a session")
(is (t2/exists? :model/Session :key_hashed session-key-hashed)
- "After a successful log-out, the session is deleted")))))))))
+ "Without SLO the handler leaves the session live")))))))))
-(deftest logout-should-delete-session-when-idp-slo-conf-missing-test
- (testing "Missing SAML SLO config logouts should still delete the user's session."
+(deftest logout-should-end-session-when-idp-slo-conf-missing-test
+ (testing "Missing SAML SLO config logouts should still end the user's session."
(with-other-sso-types-disabled!
(mt/with-temporary-setting-values [saml-slo-enabled false]
(let [session-key (session/generate-session-key)
session-key-hashed (session/hash-session-key session-key)]
(mt/with-temp [:model/User user {:email "[email protected]" :sso_source "saml"}
- :model/Session _ {:user_id (:id user) :id (session/generate-session-id) :key_hashed session-key-hashed}]
+ :model/Session {session-id :id} {:user_id (:id user)
+ :id (session/generate-session-id)
+ :key_hashed session-key-hashed}]
(is (t2/exists? :model/Session :key_hashed session-key-hashed))
(let [req-options (assoc-in {} [:request-options :cookies request/metabase-session-cookie :value] session-key)]
(client/client :post "/auth/sso/logout" req-options)
- (is (not (t2/exists? :model/Session :key_hashed session-key-hashed))))))))))
+ (is (=? {:end_reason "sso-logout", :ended_by_user_id (:id user), :ended_at some?, :key_hashed nil}
+ (t2/select-one :model/Session :id session-id))
+ "the session is ended, attributed to the user, and its key destroyed"))))))))
(deftest saml-embedding-sdk-integration-returns-idp-url-tests
(testing "should return IdP URL and method info when embedding SDK header is present"
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.clj
index c1e72817c9e..879ee7ab41c 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
@@ -410,7 +410,7 @@
(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)))
+ (is (t2/exists? :model/Session :user_id support-user-id :ended_at nil)))
(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)
@@ -418,14 +418,18 @@
(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 (not (t2/exists? :model/Session :user_id support-user-id :ended_at nil))
+ "Support user sessions should be ended once the grant ends")
+ (is (= {:end_reason "support-grant-revoked", :ended_by_user_id nil, :key_hashed nil}
+ (select-keys (t2/select-one :model/Session :id "expiregrant1")
+ [:end_reason :ended_by_user_id :key_hashed]))
+ "with no actor, since nobody revoked it")
(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)))))))))))
+ (is (not (t2/exists? :model/Session :user_id support-user-id :ended_at nil)))))))))))
(deftest expire-ended-grants-ignores-other-users-test
(testing "the natural-expiry sweep only touches the support user"
@@ -468,11 +472,11 @@
{: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]
+ (fn [user-id ended-at ended-by]
(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))]
+ (original-revoke-user-access! user-id ended-at ended-by))]
(let [expire-result (future (grants/expire-ended-grants!))]
(is (true? (deref teardown-started 5000 ::timeout))
"Expiry should reach credential teardown")
diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj
index b0c51773f5f..febcc9d5250 100644
--- a/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj
@@ -31,8 +31,8 @@
:session_key "test1"
:auth_identity_id (t2/select-one-pk :model/AuthIdentity :user_id support-user-id)}]
(t2/update! :model/SupportAccessGrantLog grant-id {:notes "Updated notes"})
- (is (some? (t2/select-one :model/Session :id session-id))
- "Session should still exist after non-revocation update")
+ (is (nil? (t2/select-one-fn :ended_at :model/Session :id session-id))
+ "Session should still be live after non-revocation update")
(is (nil? (:expires_at (t2/select-one :model/AuthIdentity :provider "password" :user_id support-user-id)))
"Auth identity expires_at should remain unchanged")))))))
@@ -68,11 +68,13 @@
:user_id other-user-id
:provider "password")}]
(let [revoked-timestamp (t/offset-date-time)]
- (t2/update! :model/SupportAccessGrantLog grant-id {:revoked_at revoked-timestamp})
- (is (nil? (t2/select-one :model/Session :id support-session-id))
- "Support user session should be deleted")
- (is (some? (t2/select-one :model/Session :id other-session-id))
- "Other user session should remain")
+ (t2/update! :model/SupportAccessGrantLog grant-id {:revoked_at revoked-timestamp
+ :revoked_by_user_id grant-creator-id})
+ (is (=? {:end_reason "support-grant-revoked", :ended_by_user_id grant-creator-id, :key_hashed nil}
+ (t2/select-one :model/Session :id support-session-id))
+ "Support user session should be ended, attributed to the revoker, and its key destroyed")
+ (is (nil? (t2/select-one-fn :ended_at :model/Session :id other-session-id))
+ "Other user session should remain live")
(is (some? (:expires_at (t2/select-one :model/AuthIdentity
:user_id support-user-id :provider "password")))
"Support user auth identity should have expires_at set")
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.clj
index ed56e6063d6..58fcbe0d584 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
@@ -12,6 +12,7 @@
[metabase.auth-identity.provider :as auth.provider]
[metabase.session.api :as api.session]
[metabase.session.core :as session]
+ [metabase.sso.ldap-test-util :as ldap.test]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
@@ -66,6 +67,34 @@
:ip_address "127.0.0.1"}})]
(is (:success? login-result) "Should be able to login with new password")))))))))))
+(deftest reset-password-with-support-access-grant-works-when-password-login-disabled-test
+ (testing "POST /api/session/reset_password redeems a support access grant on an SSO-only instance"
+ (ldap.test/with-ldap-server!
+ (mt/with-premium-features #{:support-access-grants :disable-password-login}
+ (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 [token (:token (grants/create-grant! creator-id 60 "TICKET-SSO-ONLY" "Test notes"))]
+ (mt/with-temporary-setting-values [enable-password-login false]
+ (is (false? (session/enable-password-login))
+ "sanity check: password login really is disabled")
+ (is (true? (:success (mt/client :post 200 "session/reset_password"
+ {:token token :password "NewSecurePassword123!"})))
+ "the support grant is redeemed even though password login is off")
+ (let [support-user-id (t2/select-one-pk :model/User :email "[email protected]")
+ grant-identity-id (t2/select-one-pk :model/AuthIdentity
+ :user_id support-user-id
+ :provider "support-access-grant")
+ sessions (t2/query {:select [:auth_identity_id]
+ :from [:core_session]
+ :where [:= :user_id support-user-id]})]
+ (is (= 1 (count sessions))
+ "the redeemed grant left exactly one session")
+ (is (= grant-identity-id (:auth_identity_id (first sessions)))
+ "the support session is attributed to the support-access-grant identity")))))))))))
+
(deftest reset-password-fallback-to-regular-token-test
(testing "POST /api/session/reset_password falls back to regular password reset when support grant token is invalid"
(mt/with-temp [:model/User user {:email "[email protected]"}]
diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.ts
index 52d3150b8fe..675499db647 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts
@@ -21,6 +21,7 @@ export * from "./oidc";
export * from "./replacement";
export * from "./saml";
export * from "./scim";
+export * from "./session-management";
export * from "./support-access-grants";
export * from "./table";
export * from "./tags";
diff --git a/enterprise/frontend/src/metabase-enterprise/api/session-management.ts b/enterprise/frontend/src/metabase-enterprise/api/session-management.ts
new file mode 100644
index 00000000000..217d61e10b6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/api/session-management.ts
@@ -0,0 +1,42 @@
+import type {
+ RevokeSessionsRequest,
+ RevokeSessionsResponse,
+ SessionListParams,
+ SessionListResponse,
+} from "metabase-types/api";
+
+import { EnterpriseApi } from "./api";
+import { invalidateTags, listTag, provideSessionListTags } from "./tags";
+
+export const sessionManagementApi = EnterpriseApi.injectEndpoints({
+ endpoints: (builder) => ({
+ listSessions: builder.query<SessionListResponse, SessionListParams>({
+ query: (params) => ({
+ method: "GET",
+ url: "/api/ee/session-management",
+ params,
+ }),
+ providesTags: (response) =>
+ response ? provideSessionListTags(response.data) : [],
+ }),
+
+ revokeSessions: builder.mutation<
+ RevokeSessionsResponse,
+ RevokeSessionsRequest
+ >({
+ query: (body) => ({
+ method: "POST",
+ url: "/api/ee/session-management/revoke",
+ body,
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [listTag("session")]),
+ }),
+ }),
+});
+
+export const {
+ useListSessionsQuery,
+ useLazyListSessionsQuery,
+ useRevokeSessionsMutation,
+} = sessionManagementApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
index a8afdcd4763..baa31804a76 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
@@ -20,6 +20,7 @@ import {
type PythonLibrary,
type SandboxDependencyNode,
type SegmentDependencyNode,
+ type Session,
type SnippetDependencyNode,
type SourceReplacementRun,
type SupportAccessGrant,
@@ -51,6 +52,7 @@ export const ENTERPRISE_TAG_TYPES = [
"ai-controls-usage-tenant-limits",
"data-complexity-scores",
"security-advisory",
+ "session",
] as const;
export type EnterpriseTagType = TagType | (typeof ENTERPRISE_TAG_TYPES)[number];
@@ -243,6 +245,18 @@ export function provideSupportAccessGrantListTags(
];
}
+export function provideSessionTags(
+ session: Session,
+): TagDescription<EnterpriseTagType>[] {
+ return [idTag("session", session.id), ...provideUserTags(session.user)];
+}
+
+export function provideSessionListTags(
+ sessions: Session[],
+): TagDescription<EnterpriseTagType>[] {
+ return [listTag("session"), ...sessions.flatMap(provideSessionTags)];
+}
+
export function provideSourceReplacementRunTags(
run: SourceReplacementRun,
): TagDescription<EnterpriseTagType>[] {
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.module.css b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.module.css
new file mode 100644
index 00000000000..c6690acc57b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.module.css
@@ -0,0 +1,5 @@
+.footer {
+ border-top: 1px solid var(--mb-color-border-neutral);
+ padding: var(--mantine-spacing-xl);
+ background-color: var(--mb-color-background_page-primary);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.tsx
new file mode 100644
index 00000000000..67911d82b53
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.tsx
@@ -0,0 +1,86 @@
+import { t } from "ttag";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { getUser } from "metabase/current-user";
+import { useSelector } from "metabase/redux";
+import { Flex, Stack, Text } from "metabase/ui";
+
+import { SessionDetails } from "./SessionDetails";
+import { SessionTitle } from "./SessionTitle";
+import { SidebarFooter } from "./SidebarFooter";
+import { SidebarHeader } from "./SidebarHeader";
+import type { SessionDetailSidebarProps } from "./types";
+import { useShownSession } from "./use-shown-session";
+
+export const SessionDetailSidebar = ({
+ sessionId,
+ sessionFromPage,
+ prevSessionId,
+ nextSessionId,
+ isRevoking,
+ onNavigate,
+ onRevokeSession,
+ onRevokeUserSessions,
+ onClose,
+}: SessionDetailSidebarProps) => {
+ const { session, isLoading, error } = useShownSession(
+ sessionId,
+ sessionFromPage,
+ );
+ const currentUser = useSelector(getUser);
+
+ const canRevokeSession =
+ session !== undefined && !session.current && session.status === "live";
+ const canRevokeUserSessions =
+ session !== undefined && session.user.id !== currentUser?.id;
+
+ return (
+ <Flex
+ direction="column"
+ h="100%"
+ flex="1 1 auto"
+ miw={0}
+ style={{
+ borderLeft: "1px solid var(--mb-color-border-neutral)",
+ }}
+ bg="background_page-primary"
+ data-testid="session-detail-sidebar"
+ >
+ <Stack
+ flex="1 1 auto"
+ mih={0}
+ p="xl"
+ gap="xl"
+ style={{ overflowY: "auto" }}
+ >
+ <SidebarHeader
+ sessionId={sessionId}
+ prevSessionId={prevSessionId}
+ nextSessionId={nextSessionId}
+ onNavigate={onNavigate}
+ onClose={onClose}
+ />
+ <LoadingAndErrorWrapper loading={isLoading} error={error} noWrapper>
+ {session ? (
+ <>
+ <SessionTitle user={session.user} />
+ <SessionDetails session={session} />
+ </>
+ ) : (
+ <Text c="text-secondary">{t`This session is no longer active.`}</Text>
+ )}
+ </LoadingAndErrorWrapper>
+ </Stack>
+ {session && (canRevokeSession || canRevokeUserSessions) && (
+ <SidebarFooter
+ session={session}
+ isRevoking={isRevoking}
+ canRevokeSession={canRevokeSession}
+ canRevokeUserSessions={canRevokeUserSessions}
+ onRevokeSession={onRevokeSession}
+ onRevokeUserSessions={onRevokeUserSessions}
+ />
+ )}
+ </Flex>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.unit.spec.tsx
new file mode 100644
index 00000000000..30b8f883fea
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetailSidebar.unit.spec.tsx
@@ -0,0 +1,226 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupListSessionsEndpoint } from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";
+import type { Session, SessionId } from "metabase-types/api";
+import {
+ createMockSession,
+ createMockSessionUser,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { SessionDetailSidebar } from "./SessionDetailSidebar";
+
+const ADMIN_ID = 1;
+const OTHER_USER = createMockSessionUser({
+ id: 2,
+ email: "[email protected]",
+ common_name: "Rasta Toucan",
+});
+
+const LIVE_SESSION = createMockSession({
+ id: "live-session",
+ user: OTHER_USER,
+ ip_address: "10.0.0.1",
+});
+const ENDED_SESSION = createMockSession({
+ id: "ended-session",
+ user: OTHER_USER,
+ status: "ended",
+ ended_at: "2026-09-16T12:00:00Z",
+ end_reason: "admin",
+ ended_by: ADMIN_ID,
+});
+
+type SetupOpts = {
+ sessionId?: SessionId;
+ /** `null` when the session isn't on the current page, so the sidebar has to look it up */
+ sessionFromPage?: Session | null;
+ lookupResult?: Session[];
+ isRevoking?: boolean;
+};
+
+const setup = ({
+ sessionId = LIVE_SESSION.id,
+ sessionFromPage = LIVE_SESSION,
+ lookupResult = [],
+ isRevoking = false,
+}: SetupOpts = {}) => {
+ setupListSessionsEndpoint(lookupResult);
+
+ renderWithProviders(
+ <SessionDetailSidebar
+ sessionId={sessionId}
+ sessionFromPage={sessionFromPage ?? undefined}
+ prevSessionId={undefined}
+ nextSessionId={undefined}
+ isRevoking={isRevoking}
+ onNavigate={jest.fn()}
+ onRevokeSession={jest.fn()}
+ onRevokeUserSessions={jest.fn()}
+ onClose={jest.fn()}
+ />,
+ {
+ withUndos: true,
+ storeInitialState: {
+ currentUser: createMockUser({ id: ADMIN_ID, is_superuser: true }),
+ },
+ },
+ );
+};
+
+const queryRevokeSessionButton = () =>
+ screen.queryByRole("button", { name: "Revoke session" });
+const queryRevokeUserSessionsButton = () =>
+ screen.queryByRole("button", { name: "Revoke active sessions" });
+
+describe("SessionDetailSidebar", () => {
+ describe("details", () => {
+ it("shows a live session's details, with when it expires", () => {
+ setup({ sessionFromPage: LIVE_SESSION });
+
+ expect(
+ screen.getByRole("heading", { name: "Rasta Toucan" }),
+ ).toBeInTheDocument();
+ expect(screen.getByText("[email protected]")).toBeInTheDocument();
+ expect(screen.getByText("Password")).toBeInTheDocument();
+ expect(screen.getByText("10.0.0.1")).toBeInTheDocument();
+ expect(screen.getByText("Expires")).toBeInTheDocument();
+ expect(screen.queryByText("Ended")).not.toBeInTheDocument();
+ expect(screen.queryByText("Reason")).not.toBeInTheDocument();
+ });
+
+ it("shows when and why an ended session ended, instead of when it expires", () => {
+ setup({ sessionId: ENDED_SESSION.id, sessionFromPage: ENDED_SESSION });
+
+ expect(screen.getByText("Ended")).toBeInTheDocument();
+ expect(screen.getByText("Reason")).toBeInTheDocument();
+ expect(screen.getByText("Revoked by admin")).toBeInTheDocument();
+ expect(screen.queryByText("Expires")).not.toBeInTheDocument();
+ });
+
+ it("shows a placeholder for each detail the session doesn't have", () => {
+ setup({
+ sessionFromPage: createMockSession({
+ user: OTHER_USER,
+ device_description: null,
+ user_agent: null,
+ ip_address: null,
+ device_id: null,
+ last_active_at: null,
+ }),
+ });
+
+ expect(screen.getAllByText(EMPTY_CELL_PLACEHOLDER)).toHaveLength(5);
+ });
+ });
+
+ describe("revoke actions", () => {
+ it.each([
+ {
+ description: "another user's live session",
+ session: LIVE_SESSION,
+ canRevokeSession: true,
+ canRevokeUserSessions: true,
+ },
+ {
+ description: "the session this browser is using",
+ session: createMockSession({
+ user: createMockSessionUser({ id: ADMIN_ID }),
+ current: true,
+ }),
+ canRevokeSession: false,
+ canRevokeUserSessions: false,
+ },
+ {
+ description: "another of the admin's own sessions",
+ session: createMockSession({
+ user: createMockSessionUser({ id: ADMIN_ID }),
+ }),
+ canRevokeSession: true,
+ canRevokeUserSessions: false,
+ },
+ {
+ description: "another user's ended session",
+ session: ENDED_SESSION,
+ canRevokeSession: false,
+ canRevokeUserSessions: true,
+ },
+ ])(
+ "offers the right actions for $description",
+ ({ session, canRevokeSession, canRevokeUserSessions }) => {
+ setup({ sessionId: session.id, sessionFromPage: session });
+
+ expect(queryRevokeSessionButton() !== null).toBe(canRevokeSession);
+ expect(queryRevokeUserSessionsButton() !== null).toBe(
+ canRevokeUserSessions,
+ );
+ },
+ );
+
+ it("disables the revoke actions while a revoke is in flight", () => {
+ setup({ isRevoking: true });
+
+ expect(
+ screen.getByRole("button", { name: "Revoke session" }),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole("button", { name: "Revoke active sessions" }),
+ ).toBeDisabled();
+ });
+ });
+
+ describe("header", () => {
+ it("copies a link to the session", async () => {
+ setup();
+ jest.mocked(navigator.clipboard.writeText).mockClear();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Copy link to clipboard" }),
+ );
+
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ `${window.location.origin}/monitor/sessions/${LIVE_SESSION.id}`,
+ );
+ expect(
+ await screen.findByText("Link copied to clipboard"),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("a session that isn't on the current page", () => {
+ it("is looked up by its id", async () => {
+ setup({
+ sessionId: LIVE_SESSION.id,
+ sessionFromPage: null,
+ lookupResult: [LIVE_SESSION],
+ });
+
+ expect(
+ await screen.findByRole("heading", { name: "Rasta Toucan" }),
+ ).toBeInTheDocument();
+ const [lookup] = fetchMock.callHistory.calls(
+ "path:/api/ee/session-management",
+ );
+ expect(new URL(lookup.url).searchParams.getAll("ids")).toEqual([
+ LIVE_SESSION.id,
+ ]);
+ });
+
+ it("says so when the lookup finds nothing", async () => {
+ setup({
+ sessionId: "gone-session",
+ sessionFromPage: null,
+ lookupResult: [],
+ });
+
+ expect(
+ await screen.findByText("This session is no longer active."),
+ ).toBeInTheDocument();
+ expect(queryRevokeSessionButton()).not.toBeInTheDocument();
+ expect(queryRevokeUserSessionsButton()).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetails.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetails.tsx
new file mode 100644
index 00000000000..4a7f09aa821
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionDetails.tsx
@@ -0,0 +1,107 @@
+import { t } from "ttag";
+
+import { DateTime } from "metabase/common/components/DateTime";
+import {
+ DetailsRow,
+ DetailsTable,
+ SidebarSection,
+} from "metabase/monitor/components/DetailSidebar";
+import { Text } from "metabase/ui";
+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";
+
+import {
+ getEndReasonLabel,
+ getProviderLabel,
+ getSessionTypeLabel,
+ getSessionUserName,
+} from "../utils";
+
+import type { SessionDetailsProps } from "./types";
+
+const DateValue = ({ value }: { value: string }) => (
+ <Text size="md" c="text-primary">
+ <DateTime value={value} unit="minute" />
+ </Text>
+);
+
+export const SessionDetails = ({ session }: SessionDetailsProps) => {
+ const isEnded = session.status === "ended";
+
+ return (
+ <SidebarSection title={t`Details`}>
+ <DetailsTable>
+ <DetailsRow
+ label={t`User`}
+ value={getSessionUserName(session.user)}
+ bold
+ />
+ <DetailsRow label={t`Email`} value={session.user.email} />
+ <DetailsRow
+ label={t`Auth method`}
+ value={getProviderLabel(session.provider)}
+ />
+ <DetailsRow
+ label={t`Session type`}
+ value={getSessionTypeLabel(session.type)}
+ />
+ <DetailsRow
+ label={t`Device`}
+ value={session.device_description ?? EMPTY_CELL_PLACEHOLDER}
+ />
+ <DetailsRow
+ label={t`User agent`}
+ value={session.user_agent ?? EMPTY_CELL_PLACEHOLDER}
+ />
+ <DetailsRow
+ label={t`IP address`}
+ value={session.ip_address ?? EMPTY_CELL_PLACEHOLDER}
+ />
+ <DetailsRow
+ label={t`Device ID`}
+ value={session.device_id ?? EMPTY_CELL_PLACEHOLDER}
+ />
+ <DetailsRow
+ label={t`Signed in`}
+ value={<DateValue value={session.created_at} />}
+ />
+ <DetailsRow
+ label={t`Last active`}
+ value={
+ session.last_active_at ? (
+ <DateValue value={session.last_active_at} />
+ ) : (
+ EMPTY_CELL_PLACEHOLDER
+ )
+ }
+ />
+ {isEnded ? (
+ <>
+ <DetailsRow
+ label={t`Ended`}
+ value={
+ session.ended_at ? (
+ <DateValue value={session.ended_at} />
+ ) : (
+ EMPTY_CELL_PLACEHOLDER
+ )
+ }
+ />
+ <DetailsRow
+ label={t`Reason`}
+ value={
+ session.end_reason
+ ? getEndReasonLabel(session.end_reason)
+ : EMPTY_CELL_PLACEHOLDER
+ }
+ />
+ </>
+ ) : (
+ <DetailsRow
+ label={t`Expires`}
+ value={<DateValue value={session.expires_at} />}
+ />
+ )}
+ </DetailsTable>
+ </SidebarSection>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionTitle.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionTitle.tsx
new file mode 100644
index 00000000000..7e48993c52c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SessionTitle.tsx
@@ -0,0 +1,18 @@
+import { t } from "ttag";
+
+import { Stack, Text, Title } from "metabase/ui";
+
+import { getSessionUserName } from "../utils";
+
+import type { SessionTitleProps } from "./types";
+
+export const SessionTitle = ({ user }: SessionTitleProps) => (
+ <Stack gap={0}>
+ <Text size="sm" c="text-secondary">
+ {t`Session`}
+ </Text>
+ <Title order={3} c="text-primary">
+ {getSessionUserName(user)}
+ </Title>
+ </Stack>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SidebarFooter.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SidebarFooter.tsx
new file mode 100644
index 00000000000..d72a1a36e3d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SidebarFooter.tsx
@@ -0,0 +1,31 @@
+import { t } from "ttag";
+
+import { Button, Group } from "metabase/ui";
+
+import S from "./SessionDetailSidebar.module.css";
+import type { SidebarFooterProps } from "./types";
+
+export const SidebarFooter = ({
+ session,
+ isRevoking,
+ canRevokeSession,
+ canRevokeUserSessions,
+ onRevokeSession,
+ onRevokeUserSessions,
+}: SidebarFooterProps) => (
+ <Group className={S.footer} gap="sm" grow>
+ {canRevokeSession && (
+ <Button disabled={isRevoking} onClick={() => onRevokeSession(session)}>
+ {t`Revoke session`}
+ </Button>
+ )}
+ {canRevokeUserSessions && (
+ <Button
+ disabled={isRevoking}
+ onClick={() => onRevokeUserSessions(session)}
+ >
+ {t`Revoke active sessions`}
+ </Button>
+ )}
+ </Group>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SidebarHeader.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SidebarHeader.tsx
new file mode 100644
index 00000000000..e53c9849e6a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/SidebarHeader.tsx
@@ -0,0 +1,62 @@
+import { t } from "ttag";
+
+import { SidebarNavButton } from "metabase/monitor/components/DetailSidebar";
+import { useDispatch } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+import { ActionIcon, Flex, Group, Icon } from "metabase/ui";
+import * as Urls from "metabase/urls";
+
+import type { SidebarHeaderProps } from "./types";
+
+export const SidebarHeader = ({
+ sessionId,
+ prevSessionId,
+ nextSessionId,
+ onNavigate,
+ onClose,
+}: SidebarHeaderProps) => {
+ const dispatch = useDispatch();
+
+ const handleCopyLink = async () => {
+ const url = `${window.location.origin}${Urls.monitorSessionDetail(sessionId)}`;
+ await navigator.clipboard.writeText(url);
+ dispatch(addUndo({ message: t`Link copied to clipboard` }));
+ };
+
+ return (
+ <Flex justify="space-between" align="center">
+ <Group gap="sm">
+ <SidebarNavButton
+ direction="previous"
+ label={t`Previous session`}
+ disabled={prevSessionId === undefined}
+ onClick={() => prevSessionId && onNavigate(prevSessionId)}
+ />
+ <SidebarNavButton
+ direction="next"
+ label={t`Next session`}
+ disabled={nextSessionId === undefined}
+ onClick={() => nextSessionId && onNavigate(nextSessionId)}
+ />
+ </Group>
+ <Group gap="sm">
+ <ActionIcon
+ aria-label={t`Copy link to clipboard`}
+ size="lg"
+ c="icon-primary"
+ onClick={handleCopyLink}
+ >
+ <Icon name="link" />
+ </ActionIcon>
+ <ActionIcon
+ aria-label={t`Close`}
+ size="lg"
+ c="icon-primary"
+ onClick={onClose}
+ >
+ <Icon name="close" />
+ </ActionIcon>
+ </Group>
+ </Flex>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/index.ts
new file mode 100644
index 00000000000..d375aa17927
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/index.ts
@@ -0,0 +1,2 @@
+export { SessionDetailSidebar } from "./SessionDetailSidebar";
+export { useShownSession } from "./use-shown-session";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/types.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/types.ts
new file mode 100644
index 00000000000..7d40f3388d8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/types.ts
@@ -0,0 +1,38 @@
+import type { Session, SessionId, SessionUser } from "metabase-types/api";
+
+export type SessionDetailSidebarProps = {
+ sessionId: SessionId;
+ sessionFromPage: Session | undefined;
+ prevSessionId: SessionId | undefined;
+ nextSessionId: SessionId | undefined;
+ isRevoking: boolean;
+ onNavigate: (sessionId: SessionId) => void;
+ onRevokeSession: (session: Session) => void;
+ onRevokeUserSessions: (session: Session) => void;
+ onClose: () => void;
+};
+
+export type SidebarHeaderProps = {
+ sessionId: SessionId;
+ prevSessionId: SessionId | undefined;
+ nextSessionId: SessionId | undefined;
+ onNavigate: (sessionId: SessionId) => void;
+ onClose: () => void;
+};
+
+export type SidebarFooterProps = {
+ session: Session;
+ isRevoking: boolean;
+ canRevokeSession: boolean;
+ canRevokeUserSessions: boolean;
+ onRevokeSession: (session: Session) => void;
+ onRevokeUserSessions: (session: Session) => void;
+};
+
+export type SessionTitleProps = {
+ user: SessionUser;
+};
+
+export type SessionDetailsProps = {
+ session: Session;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/use-shown-session.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/use-shown-session.ts
new file mode 100644
index 00000000000..48b0748a257
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionDetailSidebar/use-shown-session.ts
@@ -0,0 +1,19 @@
+import { skipToken } from "metabase/api";
+import { useListSessionsQuery } from "metabase-enterprise/api";
+import type { Session, SessionId } from "metabase-types/api";
+
+export function useShownSession(
+ sessionId: SessionId | undefined,
+ sessionFromPage: Session | undefined,
+) {
+ const { currentData, error } = useListSessionsQuery(
+ sessionId === undefined ? skipToken : { ids: [sessionId], status: "all" },
+ );
+ const session = sessionFromPage ?? currentData?.data[0];
+
+ return {
+ session,
+ isLoading: session === undefined && currentData === undefined,
+ error: session === undefined ? error : undefined,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/SessionsFilters.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/SessionsFilters.tsx
new file mode 100644
index 00000000000..9d82756f7cc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/SessionsFilters.tsx
@@ -0,0 +1,175 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import {
+ FilterPill,
+ FilterSection,
+ ListFilterPopover,
+} from "metabase/common/components/ListFilterPopover";
+import { type ComboboxProps, Select } from "metabase/ui";
+import {
+ SESSION_END_REASONS,
+ SESSION_PROVIDERS,
+ type SessionEndReason,
+ type SessionProvider,
+} from "metabase-types/api";
+
+import {
+ SESSIONS_TIME_PRESETS,
+ type SessionsTimePreset,
+ type SessionsUrlState,
+} from "../SessionsPage/types";
+import { isEndReason, isTimePreset } from "../SessionsPage/utils";
+import {
+ getEndReasonLabel,
+ getProviderLabel,
+ getTimePresetLabel,
+} from "../utils";
+
+type SessionsFiltersProps = {
+ state: SessionsUrlState;
+ onChange: (patch: Partial<SessionsUrlState>) => void;
+};
+
+type FilterDraft = {
+ provider: SessionProvider[];
+ last_active: SessionsTimePreset | null;
+ ended: SessionsTimePreset | null;
+ reason: SessionEndReason | null;
+};
+
+const stateToDraft = (state: SessionsUrlState): FilterDraft => ({
+ provider: state.provider,
+ last_active: state.last_active,
+ ended: state.ended,
+ reason: state.reason,
+});
+
+const EMPTY_FILTERS: FilterDraft = {
+ provider: [],
+ last_active: null,
+ ended: null,
+ reason: null,
+};
+
+// Only the filters the current tab shows count towards the indicator dot
+export const hasActiveFilters = (state: SessionsUrlState): boolean =>
+ state.provider.length > 0 ||
+ (state.tab === "ended"
+ ? state.ended !== null || state.reason !== null
+ : state.last_active !== null);
+
+const FILTER_SELECT_COMBOBOX: Partial<ComboboxProps> = {
+ withinPortal: false,
+ floatingStrategy: "fixed",
+ position: "bottom-start",
+};
+
+export const SessionsFilters = ({ state, onChange }: SessionsFiltersProps) => {
+ const [draft, setDraft] = useState<FilterDraft>(() => stateToDraft(state));
+ const isEndedTab = state.tab === "ended";
+
+ const toggleProvider = (provider: SessionProvider) => {
+ setDraft((prev) => ({
+ ...prev,
+ provider: prev.provider.includes(provider)
+ ? prev.provider.filter((value) => value !== provider)
+ : [...prev.provider, provider],
+ }));
+ };
+
+ const handleLastActiveChange = (value: string | null) => {
+ setDraft((prev) => ({
+ ...prev,
+ last_active: value !== null && isTimePreset(value) ? value : null,
+ }));
+ };
+
+ const handleEndedChange = (value: string | null) => {
+ setDraft((prev) => ({
+ ...prev,
+ ended: value !== null && isTimePreset(value) ? value : null,
+ }));
+ };
+
+ const handleReasonChange = (value: string | null) => {
+ setDraft((prev) => ({
+ ...prev,
+ reason: value !== null && isEndReason(value) ? value : null,
+ }));
+ };
+
+ return (
+ <ListFilterPopover
+ hasActiveFilters={hasActiveFilters(state)}
+ onOpen={() => setDraft(stateToDraft(state))}
+ onApply={() => onChange({ ...draft, page: 0 })}
+ onClear={() => onChange({ ...EMPTY_FILTERS, page: 0 })}
+ >
+ <FilterSection label={t`Auth method`}>
+ {SESSION_PROVIDERS.map((provider) => (
+ <FilterPill
+ key={provider}
+ label={getProviderLabel(provider)}
+ selected={draft.provider.includes(provider)}
+ onClick={() => toggleProvider(provider)}
+ />
+ ))}
+ </FilterSection>
+
+ {!isEndedTab && (
+ <FilterSection label={t`Last active`}>
+ <Select
+ w="100%"
+ data={SESSIONS_TIME_PRESETS.map((preset) => ({
+ value: preset,
+ label: getTimePresetLabel(preset),
+ }))}
+ value={draft.last_active}
+ aria-label={t`Last active`}
+ placeholder={t`Any time`}
+ clearable
+ comboboxProps={FILTER_SELECT_COMBOBOX}
+ onChange={handleLastActiveChange}
+ />
+ </FilterSection>
+ )}
+
+ {isEndedTab && (
+ <FilterSection label={t`Ended`}>
+ <Select
+ w="100%"
+ data={SESSIONS_TIME_PRESETS.map((preset) => ({
+ value: preset,
+ label: getTimePresetLabel(preset),
+ }))}
+ value={draft.ended}
+ aria-label={t`Ended`}
+ placeholder={t`Any time`}
+ clearable
+ comboboxProps={FILTER_SELECT_COMBOBOX}
+ onChange={handleEndedChange}
+ />
+ </FilterSection>
+ )}
+
+ {isEndedTab && (
+ <FilterSection label={t`Reason`}>
+ <Select
+ w="100%"
+ data={SESSION_END_REASONS.map((reason) => ({
+ value: reason,
+ label: getEndReasonLabel(reason),
+ }))}
+ value={draft.reason}
+ aria-label={t`Reason`}
+ placeholder={t`Any reason`}
+ clearable
+ comboboxProps={FILTER_SELECT_COMBOBOX}
+ onChange={handleReasonChange}
+ />
+ </FilterSection>
+ )}
+ </ListFilterPopover>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/SessionsFilters.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/SessionsFilters.unit.spec.tsx
new file mode 100644
index 00000000000..126305e72f2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/SessionsFilters.unit.spec.tsx
@@ -0,0 +1,176 @@
+import userEvent from "@testing-library/user-event";
+
+import { renderWithProviders, screen, within } from "__support__/ui";
+
+import type { SessionsUrlState } from "../SessionsPage/types";
+
+import { SessionsFilters, hasActiveFilters } from "./SessionsFilters";
+
+const ACTIVE_TAB_STATE: SessionsUrlState = {
+ page: 3,
+ query: "",
+ tab: "active",
+ provider: [],
+ last_active: null,
+ ended: null,
+ reason: null,
+ sort_column: "created_at",
+ sort_direction: "desc",
+};
+
+const ENDED_TAB_STATE: SessionsUrlState = {
+ ...ACTIVE_TAB_STATE,
+ tab: "ended",
+};
+
+const NO_FILTERS = {
+ provider: [],
+ last_active: null,
+ ended: null,
+ reason: null,
+ page: 0,
+};
+
+const setup = (state: SessionsUrlState = ACTIVE_TAB_STATE) => {
+ const onChange = jest.fn();
+ renderWithProviders(<SessionsFilters state={state} onChange={onChange} />);
+ return { onChange };
+};
+
+const openFilters = () =>
+ userEvent.click(screen.getByRole("button", { name: "Show filters" }));
+
+const getPopover = () => screen.findByRole("dialog");
+
+const apply = async () =>
+ userEvent.click(
+ within(await getPopover()).getByRole("button", { name: "Apply" }),
+ );
+
+const choose = async (filter: string, option: string) => {
+ await userEvent.click(
+ within(await getPopover()).getByRole("textbox", { name: filter }),
+ );
+ await userEvent.click(await screen.findByRole("option", { name: option }));
+};
+
+describe("SessionsFilters", () => {
+ describe("hasActiveFilters", () => {
+ it.each([
+ {
+ description: "the active tab has an auth method filter",
+ state: { ...ACTIVE_TAB_STATE, provider: ["saml"] },
+ expected: true,
+ },
+ {
+ description: "the active tab has only ended-tab filters",
+ state: { ...ACTIVE_TAB_STATE, ended: "week", reason: "admin" },
+ expected: false,
+ },
+ {
+ description: "the ended tab has a reason filter",
+ state: { ...ENDED_TAB_STATE, reason: "admin" },
+ expected: true,
+ },
+ {
+ description: "the ended tab has only an active-tab filter",
+ state: { ...ENDED_TAB_STATE, last_active: "day" },
+ expected: false,
+ },
+ ] satisfies {
+ description: string;
+ state: SessionsUrlState;
+ expected: boolean;
+ }[])("is $expected when $description", ({ state, expected }) => {
+ expect(hasActiveFilters(state)).toBe(expected);
+ });
+ });
+
+ it.each([
+ {
+ state: ACTIVE_TAB_STATE,
+ shown: ["Auth method", "Last active"],
+ hidden: ["Ended", "Reason"],
+ },
+ {
+ state: ENDED_TAB_STATE,
+ shown: ["Auth method", "Ended", "Reason"],
+ hidden: ["Last active"],
+ },
+ ])(
+ "offers the $state.tab tab's filters",
+ async ({ state, shown, hidden }) => {
+ setup(state);
+ await openFilters();
+ const popover = await getPopover();
+
+ shown.forEach((label) =>
+ expect(within(popover).getByText(label)).toBeInTheDocument(),
+ );
+ hidden.forEach((label) =>
+ expect(within(popover).queryByText(label)).not.toBeInTheDocument(),
+ );
+ },
+ );
+
+ it("applies the chosen filters, back on the first page", async () => {
+ const { onChange } = setup(ACTIVE_TAB_STATE);
+ await openFilters();
+
+ await userEvent.click(within(await getPopover()).getByText("SAML"));
+ await userEvent.click(within(await getPopover()).getByText("JWT"));
+ await choose("Last active", "Past day");
+ await apply();
+
+ expect(onChange).toHaveBeenCalledWith({
+ ...NO_FILTERS,
+ provider: ["saml", "jwt"],
+ last_active: "day",
+ });
+ });
+
+ it("applies the ended tab's filters", async () => {
+ const { onChange } = setup(ENDED_TAB_STATE);
+ await openFilters();
+
+ await choose("Ended", "Past week");
+ await choose("Reason", "Revoked by admin");
+ await apply();
+
+ expect(onChange).toHaveBeenCalledWith({
+ ...NO_FILTERS,
+ ended: "week",
+ reason: "admin",
+ });
+ });
+
+ it("discards unapplied changes when closed without applying", async () => {
+ const { onChange } = setup(ACTIVE_TAB_STATE);
+ await openFilters();
+ await userEvent.click(within(await getPopover()).getByText("SAML"));
+
+ await openFilters();
+ expect(onChange).not.toHaveBeenCalled();
+
+ await openFilters();
+ await apply();
+
+ expect(onChange).toHaveBeenCalledWith(NO_FILTERS);
+ });
+
+ it("clears every filter, back on the first page", async () => {
+ const { onChange } = setup({
+ ...ENDED_TAB_STATE,
+ provider: ["saml"],
+ ended: "week",
+ reason: "admin",
+ });
+ await openFilters();
+
+ await userEvent.click(
+ within(await getPopover()).getByRole("button", { name: "Clear filters" }),
+ );
+
+ expect(onChange).toHaveBeenCalledWith(NO_FILTERS);
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/index.ts
new file mode 100644
index 00000000000..d7bb417d0eb
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsFilters/index.ts
@@ -0,0 +1 @@
+export { SessionsFilters, hasActiveFilters } from "./SessionsFilters";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.tsx
new file mode 100644
index 00000000000..da6e818ebc9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.tsx
@@ -0,0 +1,323 @@
+import { useElementSize } from "@mantine/hooks";
+import type { RowSelectionState, SortingState } from "@tanstack/react-table";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { msgid, ngettext, t } from "ttag";
+
+import {
+ BulkActionBar,
+ BulkActionButton,
+} from "metabase/common/components/BulkActionBar";
+import { DebouncedSearchInput } from "metabase/common/components/DebouncedSearchInput";
+import { PaginationControls } from "metabase/common/components/PaginationControls";
+import { useAbortableQuery } from "metabase/common/hooks/use-abortable-query";
+import { usePageInRange } from "metabase/common/hooks/use-page-in-range";
+import { useUrlState } from "metabase/common/hooks/use-url-state";
+import { usePageTitle } from "metabase/hooks/use-page-title";
+import { SIDEBAR_WIDTH } from "metabase/monitor/components/DetailSidebar";
+import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
+import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
+import { Sidebar } from "metabase/monitor/components/MonitorLayout/Sidebar";
+import { useLocation, useNavigate, useParams } from "metabase/router";
+import { Button, Flex, Text } from "metabase/ui";
+import * as Urls from "metabase/urls";
+import { useLazyListSessionsQuery } from "metabase-enterprise/api";
+import type { RevokeSessionsRequest, SessionId } from "metabase-types/api";
+
+import { SessionDetailSidebar, useShownSession } from "../SessionDetailSidebar";
+import { SessionsFilters } from "../SessionsFilters";
+import { SessionsTable } from "../SessionsTable";
+import { SessionsTabs } from "../SessionsTabs";
+
+import {
+ DEFAULT_SORT_COLUMN,
+ DEFAULT_SORT_DIRECTION,
+ PAGE_SIZE,
+ TAB_SORT_COLUMNS,
+} from "./constants";
+import type { RouteParams } from "./types";
+import { useSessionRevocation } from "./use-session-revocation";
+import {
+ buildListParams,
+ getTabChange,
+ getTimePresetCutoff,
+ isSessionRevokedBy,
+ urlStateConfig,
+} from "./utils";
+
+export const SessionsPage = () => {
+ usePageTitle(t`Session management`);
+
+ const location = useLocation();
+ const navigate = useNavigate();
+ const { sessionId } = useParams<RouteParams>();
+ const { ref: containerRef, width: containerWidth } = useElementSize();
+ const [urlState, { patchUrlState }] = useUrlState(location, urlStateConfig);
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
+ const clearSelection = useCallback(() => setRowSelection({}), []);
+
+ const lastActiveAfter = useMemo(
+ () => getTimePresetCutoff(urlState.last_active),
+ [urlState.last_active],
+ );
+ const endedAfter = useMemo(
+ () => getTimePresetCutoff(urlState.ended),
+ [urlState.ended],
+ );
+
+ const { data, isLoading, isFetching, error } = useAbortableQuery(
+ useLazyListSessionsQuery,
+ buildListParams(urlState, PAGE_SIZE, lastActiveAfter, endedAfter),
+ );
+ const sessions = data?.data;
+ const total = data?.total ?? 0;
+ const isEndedTab = urlState.tab === "ended";
+ const selectedSessions = useMemo(
+ () => sessions?.filter((session) => rowSelection[session.id]) ?? [],
+ [sessions, rowSelection],
+ );
+ const selectedCount = selectedSessions.length;
+
+ const goToPage = useCallback(
+ (page: number) => patchUrlState({ page }, { immediate: true }),
+ [patchUrlState],
+ );
+
+ // A revoke can empty a later page
+ usePageInRange({
+ page: urlState.page,
+ pageSize: PAGE_SIZE,
+ total: isFetching || error !== undefined ? undefined : data?.total,
+ onPageChange: goToPage,
+ });
+
+ useEffect(() => {
+ clearSelection();
+ }, [
+ clearSelection,
+ urlState.page,
+ urlState.query,
+ urlState.tab,
+ urlState.provider,
+ urlState.last_active,
+ urlState.ended,
+ urlState.reason,
+ urlState.sort_column,
+ urlState.sort_direction,
+ ]);
+
+ const sorting: SortingState = [
+ {
+ id: urlState.sort_column,
+ desc: urlState.sort_direction === "desc",
+ },
+ ];
+
+ const handleSortingChange = useCallback(
+ (next: SortingState) => {
+ if (next.length === 0) {
+ patchUrlState({
+ sort_column: DEFAULT_SORT_COLUMN,
+ sort_direction: DEFAULT_SORT_DIRECTION,
+ page: 0,
+ });
+ return;
+ }
+ const [first] = next;
+ const column = TAB_SORT_COLUMNS[urlState.tab].find(
+ (value) => value === first.id,
+ );
+ if (column === undefined) {
+ return;
+ }
+ patchUrlState({
+ sort_column: column,
+ sort_direction: first.desc ? "desc" : "asc",
+ page: 0,
+ });
+ },
+ [patchUrlState, urlState.tab],
+ );
+
+ const handleSearchChange = useCallback(
+ (query: string) => patchUrlState({ query, page: 0 }),
+ [patchUrlState],
+ );
+
+ // Keep page, search and sort in the URL while the sidebar opens, closes, and steps between sessions
+ const navigateToSession = useCallback(
+ (id: SessionId | undefined) => {
+ navigate({
+ pathname:
+ id === undefined
+ ? Urls.monitorSessions()
+ : Urls.monitorSessionDetail(id),
+ search: location.search,
+ });
+ },
+ [navigate, location.search],
+ );
+
+ const handleSidebarClose = useCallback(
+ () => navigateToSession(undefined),
+ [navigateToSession],
+ );
+
+ const { prevSessionId, nextSessionId, sessionFromPage } = useMemo(() => {
+ const index =
+ sessionId === undefined || sessions === undefined
+ ? -1
+ : sessions.findIndex((session) => session.id === sessionId);
+ if (sessions === undefined || index === -1) {
+ return {
+ prevSessionId: undefined,
+ nextSessionId: undefined,
+ sessionFromPage: undefined,
+ };
+ }
+ return {
+ prevSessionId: index > 0 ? sessions[index - 1].id : undefined,
+ nextSessionId:
+ index < sessions.length - 1 ? sessions[index + 1].id : undefined,
+ sessionFromPage: sessions[index],
+ };
+ }, [sessionId, sessions]);
+
+ const { session: shownSession } = useShownSession(sessionId, sessionFromPage);
+
+ const handleRevoked = useCallback(
+ (request: RevokeSessionsRequest) => {
+ clearSelection();
+ const isShownSessionGone =
+ shownSession === undefined || isSessionRevokedBy(shownSession, request);
+ if (sessionId !== undefined && isShownSessionGone) {
+ navigateToSession(undefined);
+ }
+ },
+ [clearSelection, navigateToSession, shownSession, sessionId],
+ );
+
+ const {
+ isRevoking,
+ confirmModal,
+ revokeSelected,
+ revokeSession,
+ revokeUserSessions,
+ revokeAll,
+ } = useSessionRevocation({ onRevoked: handleRevoked });
+
+ return (
+ <>
+ <Flex ref={containerRef} h="100%" wrap="nowrap">
+ <MonitorMain>
+ <MonitorHeaderTitle mb="sm">{t`Session management`}</MonitorHeaderTitle>
+
+ <SessionsTabs
+ tab={urlState.tab}
+ onChange={(tab) => patchUrlState(getTabChange(urlState, tab))}
+ />
+
+ {isEndedTab && (
+ <Text size="sm" c="text-secondary">
+ {t`Ended sessions are kept for 30 days.`}
+ </Text>
+ )}
+
+ <Flex gap="md" align="center">
+ <DebouncedSearchInput
+ value={urlState.query}
+ placeholder={t`Search by name or email…`}
+ aria-label={t`Search sessions`}
+ onChange={handleSearchChange}
+ />
+ <SessionsFilters state={urlState} onChange={patchUrlState} />
+ {!isEndedTab && (
+ // not tied to the listed total: revoking all ignores the search and filters
+ <Button disabled={isRevoking} onClick={revokeAll}>
+ {t`Revoke all active sessions`}
+ </Button>
+ )}
+ </Flex>
+
+ <SessionsTable
+ sessions={sessions}
+ error={error}
+ isFetching={isFetching}
+ isEndedTab={isEndedTab}
+ page={urlState.page}
+ rowSelection={rowSelection}
+ selectedSessionId={sessionId}
+ sorting={sorting}
+ emptyLabel={
+ isEndedTab
+ ? t`Sessions that have ended will start appearing here as they are timed out, revoked or as users log out`
+ : t`No active sessions`
+ }
+ onSortingChange={handleSortingChange}
+ onRowSelectionChange={setRowSelection}
+ onRowClick={navigateToSession}
+ />
+
+ {!isLoading && error === undefined && (
+ <Flex justify="end">
+ <PaginationControls
+ page={urlState.page}
+ pageSize={PAGE_SIZE}
+ itemsLength={sessions?.length ?? 0}
+ total={total}
+ showTotal
+ onPreviousPage={() =>
+ patchUrlState(
+ { page: urlState.page - 1 },
+ { immediate: true },
+ )
+ }
+ onNextPage={() =>
+ patchUrlState(
+ { page: urlState.page + 1 },
+ { immediate: true },
+ )
+ }
+ />
+ </Flex>
+ )}
+ </MonitorMain>
+
+ {sessionId !== undefined && (
+ <Sidebar containerWidth={containerWidth} defaultWidth={SIDEBAR_WIDTH}>
+ <SessionDetailSidebar
+ sessionId={sessionId}
+ sessionFromPage={sessionFromPage}
+ prevSessionId={prevSessionId}
+ nextSessionId={nextSessionId}
+ isRevoking={isRevoking}
+ onNavigate={navigateToSession}
+ onRevokeSession={revokeSession}
+ onRevokeUserSessions={revokeUserSessions}
+ onClose={handleSidebarClose}
+ />
+ </Sidebar>
+ )}
+ </Flex>
+
+ <BulkActionBar
+ opened={selectedCount > 0}
+ message={ngettext(
+ msgid`${selectedCount} session selected`,
+ `${selectedCount} sessions selected`,
+ selectedCount,
+ )}
+ >
+ <BulkActionButton
+ danger
+ disabled={isRevoking}
+ onClick={() => revokeSelected(selectedSessions)}
+ >
+ {t`Revoke`}
+ </BulkActionButton>
+ <BulkActionButton onClick={clearSelection}>{t`Clear`}</BulkActionButton>
+ </BulkActionBar>
+
+ {confirmModal}
+ </>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.unit.spec.tsx
new file mode 100644
index 00000000000..1d7d62e083c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/SessionsPage.unit.spec.tsx
@@ -0,0 +1,524 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupListSessionsEndpoint,
+ setupListSessionsErrorEndpoint,
+ setupRevokeSessionsEndpoint,
+ setupRevokeSessionsErrorEndpoint,
+} from "__support__/server-mocks";
+import {
+ mockGetBoundingClientRect,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import { MonitorContent } from "metabase/monitor/components/MonitorLayout/MonitorContent";
+import { Route } from "metabase/router";
+import type {
+ RevokeSessionsResponse,
+ Session,
+ SessionListResponse,
+} from "metabase-types/api";
+import {
+ createMockRevokeSessionsResponse,
+ createMockSession,
+ createMockSessionUser,
+ createMockUser,
+} from "metabase-types/api/mocks";
+
+import { SessionsPage } from "./SessionsPage";
+import { PAGE_SIZE } from "./constants";
+
+const PATHNAME = "/monitor/sessions";
+
+const ANN_SESSION = createMockSession({
+ id: "ann-session",
+ user: createMockSessionUser({ id: 2, common_name: "Ann Admin" }),
+});
+const BOB_SESSION = createMockSession({
+ id: "bob-session",
+ user: createMockSessionUser({ id: 3, common_name: "Bob Boss" }),
+});
+const CARL_SESSION = createMockSession({
+ id: "carl-session",
+ user: createMockSessionUser({ id: 4, common_name: "Carl Coder" }),
+});
+
+type SetupOpts = {
+ sessions?: Session[];
+ total?: number;
+ listFails?: boolean;
+ /** Answers each list request from its query params, in place of `sessions` and `total` */
+ getListResponse?: (params: URLSearchParams) => SessionListResponse;
+ initialRoute?: string;
+ revokeResponse?: RevokeSessionsResponse;
+ revokeError?: Parameters<typeof setupRevokeSessionsErrorEndpoint>[0];
+};
+
+const setup = ({
+ sessions = [ANN_SESSION, BOB_SESSION, CARL_SESSION],
+ total = sessions.length,
+ listFails = false,
+ getListResponse,
+ initialRoute = PATHNAME,
+ revokeResponse = createMockRevokeSessionsResponse(),
+ revokeError,
+}: SetupOpts = {}) => {
+ if (listFails) {
+ setupListSessionsErrorEndpoint();
+ } else if (getListResponse) {
+ fetchMock.get("path:/api/ee/session-management", (call) =>
+ getListResponse(new URL(call.url).searchParams),
+ );
+ } else {
+ setupListSessionsEndpoint(sessions, { total });
+ }
+ if (revokeError) {
+ setupRevokeSessionsErrorEndpoint(revokeError);
+ } else {
+ setupRevokeSessionsEndpoint(revokeResponse);
+ }
+
+ return renderWithProviders(
+ <Route
+ path={PATHNAME}
+ element={
+ <MonitorContent>
+ <SessionsPage />
+ </MonitorContent>
+ }
+ >
+ <Route path=":sessionId" />
+ </Route>,
+ {
+ withRouter: true,
+ withUndos: true,
+ initialRoute,
+ storeInitialState: {
+ currentUser: createMockUser({ id: 1, is_superuser: true }),
+ },
+ },
+ );
+};
+
+const getSidebar = () => screen.findByTestId("session-detail-sidebar");
+
+const getConfirmModal = () => screen.findByTestId("confirm-modal");
+
+const clickSidebarButton = async (name: string) =>
+ userEvent.click(
+ await within(await getSidebar()).findByRole("button", { name }),
+ );
+
+const clickBulkRevoke = () =>
+ userEvent.click(
+ within(screen.getByTestId("toast-card")).getByRole("button", {
+ name: "Revoke",
+ }),
+ );
+
+const clickRevokeAll = async () =>
+ userEvent.click(
+ await screen.findByRole("button", { name: "Revoke all active sessions" }),
+ );
+
+const confirmRevoke = async () =>
+ userEvent.click(
+ within(await getConfirmModal()).getByRole("button", { name: "Revoke" }),
+ );
+
+const clickRowCheckbox = async (sessionId: string) =>
+ userEvent.click(
+ within(await screen.findByTestId(`session-row-${sessionId}`)).getByRole(
+ "checkbox",
+ ),
+ );
+
+/** The query params of the latest list request */
+const getLastListParams = () => {
+ const calls = fetchMock.callHistory.calls("path:/api/ee/session-management");
+ return new URL(calls[calls.length - 1].url).searchParams;
+};
+
+const queryBulkActionBar = () => screen.queryByTestId("toast-card");
+
+const getRevokeBodies = () =>
+ fetchMock.callHistory
+ .calls("path:/api/ee/session-management/revoke")
+ .map((call) => JSON.parse(String(call.options.body)));
+
+describe("SessionsPage", () => {
+ beforeEach(() => {
+ mockGetBoundingClientRect({ height: 800, width: 1000 });
+ });
+
+ describe("list", () => {
+ it("requests the tab in the URL, sorted by sign-in time by default", async () => {
+ setup({ initialRoute: `${PATHNAME}?tab=ended` });
+ await screen.findByTestId("session-row-ann-session");
+
+ const params = getLastListParams();
+ expect(params.get("status")).toBe("ended");
+ expect(params.get("limit")).toBe(String(PAGE_SIZE));
+ expect(params.get("offset")).toBe("0");
+ expect(params.get("sort-column")).toBe("created_at");
+ expect(params.get("sort-direction")).toBe("desc");
+ });
+
+ it("says when there are no active sessions", async () => {
+ setup({ sessions: [] });
+
+ expect(await screen.findByText("No active sessions")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Ended sessions are kept for 30 days."),
+ ).not.toBeInTheDocument();
+ });
+
+ it("keeps revoke all available when the search matches nothing, since it ignores the search", async () => {
+ setup({ sessions: [], initialRoute: `${PATHNAME}?query=nobody` });
+
+ expect(await screen.findByText("No active sessions")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Revoke all active sessions" }),
+ ).toBeEnabled();
+ });
+
+ it("explains the empty ended tab, and how long ended sessions are kept", async () => {
+ setup({ sessions: [], initialRoute: `${PATHNAME}?tab=ended` });
+
+ expect(
+ await screen.findByText(
+ "Sessions that have ended will start appearing here as they are timed out, revoked or as users log out",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("Ended sessions are kept for 30 days."),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Revoke all active sessions" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows an error when the sessions cannot be loaded", async () => {
+ setup({ listFails: true });
+
+ expect(await screen.findByText("An error occurred")).toBeInTheDocument();
+ });
+
+ it("switches tabs from the first page, dropping the selection", async () => {
+ const { router } = setup({ initialRoute: `${PATHNAME}?page=2` });
+ await clickRowCheckbox("ann-session");
+ expect(queryBulkActionBar()).toBeInTheDocument();
+
+ await userEvent.click(screen.getByTestId("sessions-tab-ended"));
+
+ await waitFor(() => {
+ expect(router?.location.search).toBe("?tab=ended");
+ });
+ await waitFor(() => {
+ expect(getLastListParams().get("status")).toBe("ended");
+ });
+ expect(getLastListParams().get("offset")).toBe("0");
+ expect(queryBulkActionBar()).not.toBeInTheDocument();
+ });
+
+ it("drops a sort by auth method when switching to the ended tab, which has no such column", async () => {
+ setup({ initialRoute: `${PATHNAME}?sort_column=provider` });
+ await screen.findByTestId("session-row-ann-session");
+
+ await userEvent.click(screen.getByTestId("sessions-tab-ended"));
+
+ await waitFor(() => {
+ expect(getLastListParams().get("status")).toBe("ended");
+ });
+ expect(getLastListParams().get("sort-column")).toBe("created_at");
+ });
+
+ it("sorts by a column header from the first page, dropping the selection", async () => {
+ const { router } = setup({ initialRoute: `${PATHNAME}?page=2` });
+ await clickRowCheckbox("ann-session");
+
+ await userEvent.click(screen.getByRole("columnheader", { name: "User" }));
+
+ await waitFor(() => {
+ expect(getLastListParams().get("sort-column")).toBe("user_email");
+ });
+ await waitFor(() => {
+ expect(router?.location.search).toContain("sort_column=user_email");
+ });
+ expect(router?.location.search).not.toContain("page=");
+ expect(queryBulkActionBar()).not.toBeInTheDocument();
+ });
+
+ it("pages to the next set of sessions, dropping the selection", async () => {
+ setup({ total: PAGE_SIZE + 10 });
+ await clickRowCheckbox("ann-session");
+
+ await userEvent.click(screen.getByRole("button", { name: "Next page" }));
+
+ await waitFor(() => {
+ expect(getLastListParams().get("offset")).toBe(String(PAGE_SIZE));
+ });
+ expect(queryBulkActionBar()).not.toBeInTheDocument();
+ });
+ });
+
+ describe("detail sidebar", () => {
+ it("opens a session from its row and closes again, keeping the search in the URL", async () => {
+ const { router } = setup({ initialRoute: `${PATHNAME}?query=ann` });
+
+ await userEvent.click(
+ await screen.findByTestId("session-row-ann-session"),
+ );
+
+ expect(router?.location.pathname).toBe(`${PATHNAME}/ann-session`);
+ expect(router?.location.search).toBe("?query=ann");
+ expect(
+ within(await getSidebar()).getByRole("heading", { name: "Ann Admin" }),
+ ).toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("button", { name: "Close" }));
+
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(PATHNAME);
+ });
+ expect(router?.location.search).toBe("?query=ann");
+ expect(
+ screen.queryByTestId("session-detail-sidebar"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("steps through the sessions in the order the table shows them", async () => {
+ const { router } = setup({ initialRoute: `${PATHNAME}/ann-session` });
+ const sidebar = await getSidebar();
+
+ expect(
+ await within(sidebar).findByRole("heading", { name: "Ann Admin" }),
+ ).toBeInTheDocument();
+ expect(
+ within(sidebar).getByRole("button", { name: "Previous session" }),
+ ).toBeDisabled();
+
+ await clickSidebarButton("Next session");
+
+ expect(router?.location.pathname).toBe(`${PATHNAME}/bob-session`);
+ expect(
+ await within(await getSidebar()).findByRole("heading", {
+ name: "Bob Boss",
+ }),
+ ).toBeInTheDocument();
+ });
+
+ it("stays open when a revoke doesn't include the session it shows", async () => {
+ const { router } = setup({ initialRoute: `${PATHNAME}/ann-session` });
+ await getSidebar();
+
+ await clickRowCheckbox("bob-session");
+ await clickBulkRevoke();
+ await confirmRevoke();
+
+ await waitFor(() => {
+ expect(getRevokeBodies()).toEqual([{ ids: ["bob-session"] }]);
+ });
+ expect(router?.location.pathname).toBe(`${PATHNAME}/ann-session`);
+ expect(await getSidebar()).toBeInTheDocument();
+ });
+ });
+
+ describe("revoking", () => {
+ it.each([
+ {
+ action: "a single session from the sidebar",
+ initialRoute: `${PATHNAME}/ann-session`,
+ trigger: () => clickSidebarButton("Revoke session"),
+ title: "Revoke this session?",
+ body: { ids: ["ann-session"] },
+ },
+ {
+ action: "every session of a user from the sidebar",
+ initialRoute: `${PATHNAME}/ann-session`,
+ trigger: () => clickSidebarButton("Revoke active sessions"),
+ title: "Revoke all sessions for Ann Admin?",
+ body: { "user-id": 2 },
+ },
+ {
+ action: "the selected sessions",
+ initialRoute: PATHNAME,
+ trigger: async () => {
+ await clickRowCheckbox("ann-session");
+ await clickRowCheckbox("bob-session");
+ await clickBulkRevoke();
+ },
+ title: "Revoke 2 sessions?",
+ body: { ids: ["ann-session", "bob-session"] },
+ },
+ {
+ action: "every active session",
+ initialRoute: PATHNAME,
+ trigger: clickRevokeAll,
+ title: "Revoke all sessions?",
+ body: {},
+ },
+ ])(
+ "confirms before revoking $action, then sends its criteria and closes any sidebar",
+ async ({ initialRoute, trigger, title, body }) => {
+ const { router } = setup({ initialRoute });
+
+ await trigger();
+
+ expect(
+ within(await getConfirmModal()).getByText(title),
+ ).toBeInTheDocument();
+ expect(getRevokeBodies()).toEqual([]);
+
+ await confirmRevoke();
+
+ await waitFor(() => {
+ expect(getRevokeBodies()).toEqual([body]);
+ });
+ await waitFor(() => {
+ expect(router?.location.pathname).toBe(PATHNAME);
+ });
+ },
+ );
+
+ it("re-requests the list after a revoke", async () => {
+ setup();
+ await screen.findByTestId("session-row-ann-session");
+ const listCalls = () =>
+ fetchMock.callHistory.calls("path:/api/ee/session-management").length;
+ const callsBefore = listCalls();
+
+ await clickRevokeAll();
+ await confirmRevoke();
+
+ await waitFor(() => {
+ expect(listCalls()).toBeGreaterThan(callsBefore);
+ });
+ });
+
+ it("goes back to the last page when a revoke empties a later one", async () => {
+ const lastSession = createMockSession({
+ id: "last-session",
+ user: createMockSessionUser({ id: 5, common_name: "Lee Last" }),
+ });
+ let isLastSessionRevoked = false;
+ const { router } = setup({
+ initialRoute: `${PATHNAME}?page=1`,
+ getListResponse: (params) => {
+ const isFirstPage = params.get("offset") === "0";
+ const secondPage = isLastSessionRevoked ? [] : [lastSession];
+ return {
+ data: isFirstPage
+ ? [ANN_SESSION, BOB_SESSION, CARL_SESSION]
+ : secondPage,
+ total: isLastSessionRevoked ? PAGE_SIZE : PAGE_SIZE + 1,
+ limit: PAGE_SIZE,
+ offset: Number(params.get("offset")),
+ };
+ },
+ });
+
+ await clickRowCheckbox("last-session");
+ await clickBulkRevoke();
+ isLastSessionRevoked = true;
+ await confirmRevoke();
+
+ expect(
+ await screen.findByTestId("session-row-ann-session"),
+ ).toBeInTheDocument();
+ expect(getLastListParams().get("offset")).toBe("0");
+ expect(router?.location.search).not.toContain("page=");
+ expect(screen.queryByText("No active sessions")).not.toBeInTheDocument();
+ });
+
+ it("revokes nothing when the confirmation is cancelled", async () => {
+ setup({ initialRoute: `${PATHNAME}/ann-session` });
+
+ await clickSidebarButton("Revoke session");
+ await userEvent.click(
+ within(await getConfirmModal()).getByRole("button", { name: "Cancel" }),
+ );
+
+ await waitFor(() => {
+ expect(screen.queryByTestId("confirm-modal")).not.toBeInTheDocument();
+ });
+ expect(getRevokeBodies()).toEqual([]);
+ });
+
+ it.each([
+ { remaining: 0, warns: false },
+ { remaining: 2, warns: true },
+ ])(
+ "reports how many were revoked, warning only if sessions started meanwhile (remaining: $remaining)",
+ async ({ remaining, warns }) => {
+ setup({
+ revokeResponse: createMockRevokeSessionsResponse({
+ revoked: 3,
+ remaining,
+ }),
+ });
+
+ await clickRevokeAll();
+ await confirmRevoke();
+
+ expect(
+ await screen.findByText("Revoked 3 sessions"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ `${remaining} new sessions started while revoking`,
+ ) !== null,
+ ).toBe(warns);
+ },
+ );
+
+ it("stays open after revoking the user of the ended session it shows", async () => {
+ const ended = createMockSession({
+ id: "ended-session",
+ user: ANN_SESSION.user,
+ status: "ended",
+ end_reason: "logout",
+ });
+ const { router } = setup({
+ sessions: [ended],
+ initialRoute: `${PATHNAME}/ended-session?tab=ended`,
+ });
+
+ await clickSidebarButton("Revoke active sessions");
+ await confirmRevoke();
+
+ await waitFor(() => {
+ expect(getRevokeBodies()).toEqual([{ "user-id": 2 }]);
+ });
+ expect(router?.location.pathname).toBe(`${PATHNAME}/ended-session`);
+ });
+
+ it("shows the server's reason when a revoke is refused", async () => {
+ setup({ revokeError: { status: 400, message: "Too many sessions" } });
+
+ await clickRevokeAll();
+ await confirmRevoke();
+
+ expect(await screen.findByText("Too many sessions")).toBeInTheDocument();
+ });
+
+ it("shows an error, and keeps the sidebar open, when the revoke fails", async () => {
+ const { router } = setup({
+ initialRoute: `${PATHNAME}/ann-session`,
+ revokeError: {},
+ });
+
+ await clickSidebarButton("Revoke session");
+ await confirmRevoke();
+
+ expect(
+ await screen.findByText("Could not revoke sessions."),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/^Revoked /)).not.toBeInTheDocument();
+ expect(router?.location.pathname).toBe(`${PATHNAME}/ann-session`);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/constants.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/constants.ts
new file mode 100644
index 00000000000..1b441df298a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/constants.ts
@@ -0,0 +1,25 @@
+import type {
+ SessionSortColumn,
+ SessionStatusFilter,
+ SortDirection,
+} from "metabase-types/api";
+
+import type { SessionsTab } from "./types";
+
+export const PAGE_SIZE = 50;
+
+export const DEFAULT_TAB: SessionsTab = "active";
+
+export const TAB_STATUS: Record<SessionsTab, SessionStatusFilter> = {
+ active: "live",
+ ended: "ended",
+};
+
+export const DEFAULT_SORT_COLUMN: SessionSortColumn = "created_at";
+export const DEFAULT_SORT_DIRECTION: SortDirection = "desc";
+
+// The ended tab has no auth method column, so it can't sort by one
+export const TAB_SORT_COLUMNS: Record<SessionsTab, SessionSortColumn[]> = {
+ active: ["created_at", "user_email", "provider"],
+ ended: ["created_at", "user_email"],
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/index.ts
new file mode 100644
index 00000000000..dfd008bd25c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/index.ts
@@ -0,0 +1 @@
+export { SessionsPage } from "./SessionsPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/types.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/types.ts
new file mode 100644
index 00000000000..cc364f635e1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/types.ts
@@ -0,0 +1,28 @@
+import type {
+ SessionEndReason,
+ SessionProvider,
+ SessionSortColumn,
+ SortDirection,
+} from "metabase-types/api";
+
+export type RouteParams = {
+ sessionId?: string;
+};
+
+export const SESSIONS_TABS = ["active", "ended"] as const;
+export type SessionsTab = (typeof SESSIONS_TABS)[number];
+
+export const SESSIONS_TIME_PRESETS = ["hour", "day", "week", "month"] as const;
+export type SessionsTimePreset = (typeof SESSIONS_TIME_PRESETS)[number];
+
+export type SessionsUrlState = {
+ page: number;
+ query: string;
+ tab: SessionsTab;
+ provider: SessionProvider[];
+ last_active: SessionsTimePreset | null;
+ ended: SessionsTimePreset | null;
+ reason: SessionEndReason | null;
+ sort_column: SessionSortColumn;
+ sort_direction: SortDirection;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/use-session-revocation.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/use-session-revocation.ts
new file mode 100644
index 00000000000..b6ed9ae7618
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/use-session-revocation.ts
@@ -0,0 +1,137 @@
+import { useCallback } from "react";
+import { msgid, ngettext, t } from "ttag";
+
+import { getErrorMessage } from "metabase/api/utils";
+import { useConfirmation } from "metabase/common/hooks/use-confirmation";
+import { useDispatch } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+import { useRevokeSessionsMutation } from "metabase-enterprise/api";
+import type { RevokeSessionsRequest, Session } from "metabase-types/api";
+
+import { getSessionUserName } from "../utils";
+
+type RevokeConfirmation = {
+ title: string;
+ message: string;
+ request: RevokeSessionsRequest;
+};
+
+type UseSessionRevocationOptions = {
+ onRevoked: (request: RevokeSessionsRequest) => void;
+};
+
+export function useSessionRevocation({
+ onRevoked,
+}: UseSessionRevocationOptions) {
+ const dispatch = useDispatch();
+ const [revokeSessions, { isLoading: isRevoking }] =
+ useRevokeSessionsMutation();
+ const { modalContent: confirmModal, show: showConfirm } = useConfirmation();
+
+ const revoke = useCallback(
+ async (request: RevokeSessionsRequest) => {
+ try {
+ const { revoked, remaining } = await revokeSessions(request).unwrap();
+ dispatch(
+ addUndo({
+ message: ngettext(
+ msgid`Revoked ${revoked} session`,
+ `Revoked ${revoked} sessions`,
+ revoked,
+ ),
+ }),
+ );
+ if (remaining > 0) {
+ dispatch(
+ addUndo({
+ icon: "warning",
+ message: ngettext(
+ msgid`${remaining} new session started while revoking`,
+ `${remaining} new sessions started while revoking`,
+ remaining,
+ ),
+ }),
+ );
+ }
+ onRevoked(request);
+ } catch (error) {
+ dispatch(
+ addUndo({
+ icon: "warning",
+ message: getErrorMessage(error, t`Could not revoke sessions.`),
+ }),
+ );
+ }
+ },
+ [dispatch, onRevoked, revokeSessions],
+ );
+
+ const confirmRevoke = useCallback(
+ ({ title, message, request }: RevokeConfirmation) => {
+ showConfirm({
+ title,
+ message,
+ confirmButtonText: t`Revoke`,
+ onConfirm: () => revoke(request),
+ });
+ },
+ [revoke, showConfirm],
+ );
+
+ const revokeSelected = useCallback(
+ (sessions: Session[]) => {
+ const count = sessions.length;
+ confirmRevoke({
+ title: ngettext(
+ msgid`Revoke ${count} session?`,
+ `Revoke ${count} sessions?`,
+ count,
+ ),
+ message: t`Anyone using them will be signed out and need to sign in again.`,
+ request: { ids: sessions.map((session) => session.id) },
+ });
+ },
+ [confirmRevoke],
+ );
+
+ const revokeSession = useCallback(
+ (session: Session) => {
+ const name = getSessionUserName(session.user);
+ confirmRevoke({
+ title: t`Revoke this session?`,
+ message: t`${name} will be signed out of this session and need to sign in again.`,
+ request: { ids: [session.id] },
+ });
+ },
+ [confirmRevoke],
+ );
+
+ const revokeUserSessions = useCallback(
+ (session: Session) => {
+ const name = getSessionUserName(session.user);
+ confirmRevoke({
+ title: t`Revoke all sessions for ${name}?`,
+ message: t`${name} will be signed out everywhere.`,
+ request: { "user-id": session.user.id },
+ });
+ },
+ [confirmRevoke],
+ );
+
+ const revokeAll = useCallback(() => {
+ confirmRevoke({
+ title: t`Revoke all sessions?`,
+ message: t`Everyone will be signed out and need to sign in again, except you in this session.`,
+ request: {},
+ });
+ }, [confirmRevoke]);
+
+ return {
+ isRevoking,
+ confirmModal,
+ revokeSelected,
+ revokeSession,
+ revokeUserSessions,
+ revokeAll,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/utils.ts
new file mode 100644
index 00000000000..8f2091c60ec
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/utils.ts
@@ -0,0 +1,168 @@
+import type {
+ QueryParam,
+ UrlStateConfig,
+} from "metabase/common/hooks/use-url-state";
+import {
+ getAllParamValues,
+ getFirstParamValue,
+ parsePage,
+ parseSortColumn,
+ parseSortDirection,
+} from "metabase/common/hooks/use-url-state";
+import { dayjs } from "metabase/dayjs";
+import {
+ type RevokeSessionsRequest,
+ SESSION_END_REASONS,
+ SESSION_PROVIDERS,
+ type Session,
+ type SessionEndReason,
+ type SessionListParams,
+ type SessionProvider,
+} from "metabase-types/api";
+
+import {
+ DEFAULT_SORT_COLUMN,
+ DEFAULT_SORT_DIRECTION,
+ DEFAULT_TAB,
+ TAB_SORT_COLUMNS,
+ TAB_STATUS,
+} from "./constants";
+import {
+ SESSIONS_TABS,
+ SESSIONS_TIME_PRESETS,
+ type SessionsTab,
+ type SessionsTimePreset,
+ type SessionsUrlState,
+} from "./types";
+
+const parseQuery = (param: QueryParam): string => {
+ const value = getFirstParamValue(param);
+ return typeof value === "string" ? value.trim() : "";
+};
+
+const isProvider = (value: string): value is SessionProvider =>
+ SESSION_PROVIDERS.some((provider) => provider === value);
+
+// An unrecognised provider in the URL is dropped rather than sent on: the endpoint's enum would reject the whole
+// request, taking the rest of the filters down with it.
+const parseProviders = (param: QueryParam): SessionProvider[] =>
+ getAllParamValues(param).filter(isProvider);
+
+export const isTab = (value: string): value is SessionsTab =>
+ SESSIONS_TABS.some((tab) => tab === value);
+
+const parseTab = (param: QueryParam): SessionsTab => {
+ const value = getFirstParamValue(param);
+ return typeof value === "string" && isTab(value) ? value : DEFAULT_TAB;
+};
+
+export const isTimePreset = (value: string): value is SessionsTimePreset =>
+ SESSIONS_TIME_PRESETS.some((preset) => preset === value);
+
+const parseTimePreset = (param: QueryParam): SessionsTimePreset | null => {
+ const value = getFirstParamValue(param);
+ return typeof value === "string" && isTimePreset(value) ? value : null;
+};
+
+export const isEndReason = (value: string): value is SessionEndReason =>
+ SESSION_END_REASONS.some((reason) => reason === value);
+
+const parseEndReason = (param: QueryParam): SessionEndReason | null => {
+ const value = getFirstParamValue(param);
+ return typeof value === "string" && isEndReason(value) ? value : null;
+};
+
+export const urlStateConfig: UrlStateConfig<SessionsUrlState> = {
+ parse: (query) => {
+ const tab = parseTab(query.tab);
+ return {
+ page: parsePage(query.page),
+ query: parseQuery(query.query),
+ tab,
+ provider: parseProviders(query.provider),
+ last_active: parseTimePreset(query.last_active),
+ ended: parseTimePreset(query.ended),
+ reason: parseEndReason(query.reason),
+ sort_column: parseSortColumn(
+ query.sort_column,
+ TAB_SORT_COLUMNS[tab],
+ DEFAULT_SORT_COLUMN,
+ ),
+ sort_direction: parseSortDirection(
+ query.sort_direction,
+ DEFAULT_SORT_DIRECTION,
+ ),
+ };
+ },
+ serialize: (state) => ({
+ page: state.page === 0 ? undefined : String(state.page),
+ query: state.query || undefined,
+ tab: state.tab === DEFAULT_TAB ? undefined : state.tab,
+ provider: state.provider.length === 0 ? undefined : state.provider,
+ last_active: state.last_active ?? undefined,
+ ended: state.ended ?? undefined,
+ reason: state.reason ?? undefined,
+ sort_column:
+ state.sort_column === DEFAULT_SORT_COLUMN ? undefined : state.sort_column,
+ sort_direction:
+ state.sort_direction === DEFAULT_SORT_DIRECTION
+ ? undefined
+ : state.sort_direction,
+ }),
+};
+
+export const getTimePresetCutoff = (
+ preset: SessionsTimePreset | null,
+): string | undefined =>
+ preset === null ? undefined : dayjs().subtract(1, preset).toISOString();
+
+export const buildListParams = (
+ state: SessionsUrlState,
+ pageSize: number,
+ lastActiveAfter: string | undefined,
+ endedAfter: string | undefined,
+): SessionListParams => {
+ // The ended-only criteria never match a live session, so each tab sends only the filters it shows
+ const isEnded = state.tab === "ended";
+ return {
+ limit: pageSize,
+ offset: state.page * pageSize,
+ // the endpoint rejects a blank query, so send it only when there is something to search for
+ query: state.query.trim() || undefined,
+ status: TAB_STATUS[state.tab],
+ // an empty list would be sent as no filter at all, which is what we want; a populated one filters on any of them
+ provider: state.provider.length === 0 ? undefined : state.provider,
+ "last-active-after": isEnded ? undefined : lastActiveAfter,
+ "ended-after": isEnded ? endedAfter : undefined,
+ reason: isEnded ? (state.reason ?? undefined) : undefined,
+ "sort-column": state.sort_column,
+ "sort-direction": state.sort_direction,
+ };
+};
+
+export const getTabChange = (
+ state: SessionsUrlState,
+ tab: SessionsTab,
+): Partial<SessionsUrlState> => {
+ const isSortShown = TAB_SORT_COLUMNS[tab].includes(state.sort_column);
+ return {
+ tab,
+ page: 0,
+ ...(isSortShown
+ ? {}
+ : {
+ sort_column: DEFAULT_SORT_COLUMN,
+ sort_direction: DEFAULT_SORT_DIRECTION,
+ }),
+ };
+};
+
+// Mirrors the endpoint: only live sessions other than the caller's are revoked, and every criterion has to hold
+export const isSessionRevokedBy = (
+ session: Session,
+ request: RevokeSessionsRequest,
+): boolean =>
+ session.status === "live" &&
+ !session.current &&
+ (request.ids === undefined || request.ids.includes(session.id)) &&
+ (request["user-id"] === undefined || request["user-id"] === session.user.id);
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/utils.unit.spec.ts
new file mode 100644
index 00000000000..6cc7304dfc3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsPage/utils.unit.spec.ts
@@ -0,0 +1,222 @@
+import {
+ createMockSession,
+ createMockSessionUser,
+} from "metabase-types/api/mocks";
+
+import { PAGE_SIZE } from "./constants";
+import type { SessionsUrlState } from "./types";
+import {
+ buildListParams,
+ getTabChange,
+ isSessionRevokedBy,
+ urlStateConfig,
+} from "./utils";
+
+const DEFAULT_STATE: SessionsUrlState = {
+ page: 0,
+ query: "",
+ tab: "active",
+ provider: [],
+ last_active: null,
+ ended: null,
+ reason: null,
+ sort_column: "created_at",
+ sort_direction: "desc",
+};
+
+const POPULATED_STATE: SessionsUrlState = {
+ page: 2,
+ query: "ann",
+ tab: "ended",
+ provider: ["saml", "jwt"],
+ last_active: "day",
+ ended: "week",
+ reason: "admin",
+ sort_column: "user_email",
+ sort_direction: "asc",
+};
+
+const LAST_ACTIVE_AFTER = "2026-10-04T12:00:00.000Z";
+const ENDED_AFTER = "2026-09-28T12:00:00.000Z";
+
+describe("SessionsPage/utils", () => {
+ describe("urlStateConfig.parse", () => {
+ it("returns defaults for an empty query", () => {
+ expect(urlStateConfig.parse({})).toEqual(DEFAULT_STATE);
+ });
+
+ it("trims the search query", () => {
+ expect(urlStateConfig.parse({ query: " ann " }).query).toBe("ann");
+ });
+
+ it("keeps only known auth methods, so an unknown one can't fail the whole request", () => {
+ expect(
+ urlStateConfig.parse({ provider: ["saml", "mcp", "jwt"] }).provider,
+ ).toEqual(["saml", "jwt"]);
+ expect(urlStateConfig.parse({ provider: "saml" }).provider).toEqual([
+ "saml",
+ ]);
+ });
+
+ it("guards the tab, time preset and reason params against unknown values", () => {
+ expect(urlStateConfig.parse({ tab: "ended" }).tab).toBe("ended");
+ expect(urlStateConfig.parse({ tab: "bogus" }).tab).toBe("active");
+
+ expect(urlStateConfig.parse({ last_active: "week" }).last_active).toBe(
+ "week",
+ );
+ expect(urlStateConfig.parse({ ended: "decade" }).ended).toBeNull();
+
+ expect(urlStateConfig.parse({ reason: "logout" }).reason).toBe("logout");
+ expect(urlStateConfig.parse({ reason: "boredom" }).reason).toBeNull();
+ });
+
+ it("only sorts by the columns the table offers", () => {
+ expect(
+ urlStateConfig.parse({ sort_column: "provider" }).sort_column,
+ ).toBe("provider");
+ expect(
+ urlStateConfig.parse({ sort_column: "last_active_at" }).sort_column,
+ ).toBe("created_at");
+ expect(
+ urlStateConfig.parse({ tab: "ended", sort_column: "provider" })
+ .sort_column,
+ ).toBe("created_at");
+ });
+ });
+
+ describe("urlStateConfig.serialize", () => {
+ it("leaves defaults out of the URL", () => {
+ expect(
+ Object.values(urlStateConfig.serialize(DEFAULT_STATE)).filter(
+ (value) => value !== undefined,
+ ),
+ ).toEqual([]);
+ });
+
+ it("round-trips a populated state", () => {
+ expect(
+ urlStateConfig.parse(urlStateConfig.serialize(POPULATED_STATE)),
+ ).toEqual(POPULATED_STATE);
+ });
+ });
+
+ describe("buildListParams", () => {
+ it("sends only the active tab's filters", () => {
+ const state = { ...POPULATED_STATE, tab: "active" as const };
+
+ expect(
+ buildListParams(state, PAGE_SIZE, LAST_ACTIVE_AFTER, ENDED_AFTER),
+ ).toMatchObject({
+ status: "live",
+ "last-active-after": LAST_ACTIVE_AFTER,
+ "ended-after": undefined,
+ reason: undefined,
+ });
+ });
+
+ it("sends only the ended tab's filters", () => {
+ expect(
+ buildListParams(
+ POPULATED_STATE,
+ PAGE_SIZE,
+ LAST_ACTIVE_AFTER,
+ ENDED_AFTER,
+ ),
+ ).toMatchObject({
+ status: "ended",
+ "last-active-after": undefined,
+ "ended-after": ENDED_AFTER,
+ reason: "admin",
+ });
+ });
+
+ it("leaves out an empty search and an empty auth method list", () => {
+ const params = buildListParams(
+ DEFAULT_STATE,
+ PAGE_SIZE,
+ undefined,
+ undefined,
+ );
+
+ expect(params.query).toBeUndefined();
+ expect(params.provider).toBeUndefined();
+ });
+
+ it("trims the search, leaving out one that is only whitespace", () => {
+ const build = (query: string) =>
+ buildListParams(
+ { ...DEFAULT_STATE, query },
+ PAGE_SIZE,
+ undefined,
+ undefined,
+ ).query;
+
+ expect(build(" ann ")).toBe("ann");
+ expect(build(" ")).toBeUndefined();
+ });
+ });
+
+ describe("getTabChange", () => {
+ it("goes back to the first page, keeping a sort the new tab shows", () => {
+ expect(
+ getTabChange({ ...POPULATED_STATE, tab: "active" }, "ended"),
+ ).toEqual({ tab: "ended", page: 0 });
+ });
+
+ it("resets a sort by a column the new tab doesn't show", () => {
+ expect(
+ getTabChange(
+ { ...DEFAULT_STATE, sort_column: "provider", sort_direction: "asc" },
+ "ended",
+ ),
+ ).toEqual({
+ tab: "ended",
+ page: 0,
+ sort_column: "created_at",
+ sort_direction: "desc",
+ });
+ });
+ });
+
+ describe("isSessionRevokedBy", () => {
+ const user = createMockSessionUser({ id: 2 });
+ const session = createMockSession({ id: "shown", user });
+
+ it.each([
+ { description: "revoking everything", request: {}, expected: true },
+ {
+ description: "revoking its id",
+ request: { ids: ["shown"] },
+ expected: true,
+ },
+ {
+ description: "revoking other ids",
+ request: { ids: ["other"] },
+ expected: false,
+ },
+ {
+ description: "revoking its user",
+ request: { "user-id": 2 },
+ expected: true,
+ },
+ {
+ description: "revoking another user",
+ request: { "user-id": 3 },
+ expected: false,
+ },
+ ])(
+ "is $expected for a live session when $description",
+ ({ request, expected }) => {
+ expect(isSessionRevokedBy(session, request)).toBe(expected);
+ },
+ );
+
+ it("is false for an ended or current session, whatever the criteria", () => {
+ expect(
+ isSessionRevokedBy({ ...session, status: "ended" }, { "user-id": 2 }),
+ ).toBe(false);
+ expect(isSessionRevokedBy({ ...session, current: true }, {})).toBe(false);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/SessionsTable.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/SessionsTable.tsx
new file mode 100644
index 00000000000..590ae43c85d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/SessionsTable.tsx
@@ -0,0 +1,156 @@
+import type {
+ OnChangeFn,
+ Row,
+ RowSelectionState,
+ SortingState,
+ Updater,
+} from "@tanstack/react-table";
+import { useCallback, useEffect, useMemo } from "react";
+import { t } from "ttag";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useScrollToTop } from "metabase/common/hooks";
+import { MonitorEmptyState } from "metabase/monitor/components/MonitorEmptyState";
+import { MonitorTableCard } from "metabase/monitor/components/MonitorTableCard";
+import {
+ Card,
+ LoadingOverlay,
+ TreeTable,
+ TreeTableSkeleton,
+ useTreeTableInstance,
+} from "metabase/ui";
+import type { Session, SessionId } from "metabase-types/api";
+
+import { getColumnWidths, getColumns } from "./utils";
+
+type SessionsTableProps = {
+ sessions: Session[] | undefined;
+ error: unknown;
+ isFetching: boolean;
+ isEndedTab: boolean;
+ page: number;
+ rowSelection: RowSelectionState;
+ selectedSessionId: SessionId | undefined;
+ sorting: SortingState;
+ emptyLabel: string;
+ onSortingChange: (sorting: SortingState) => void;
+ onRowSelectionChange: OnChangeFn<RowSelectionState>;
+ onRowClick: (sessionId: SessionId) => void;
+};
+
+const NO_SESSIONS: Session[] = [];
+
+const getNodeId = (session: Session) => session.id;
+
+// Revoking the caller's own session is done by logging out, not from this page, and the endpoint only ever ends
+// live ones — an ended session has nothing left to revoke
+const canSelectSession = (row: Row<Session>) =>
+ !row.original.current && row.original.status === "live";
+
+export const SessionsTable = ({
+ sessions,
+ error,
+ isFetching,
+ isEndedTab,
+ page,
+ rowSelection,
+ selectedSessionId,
+ sorting,
+ emptyLabel,
+ onSortingChange,
+ onRowSelectionChange,
+ onRowClick,
+}: SessionsTableProps) => {
+ const selectedRowId = selectedSessionId ?? null;
+
+ const handleSortingChange = useCallback(
+ (updater: Updater<SortingState>) => {
+ const next = typeof updater === "function" ? updater(sorting) : updater;
+ onSortingChange(next);
+ },
+ [sorting, onSortingChange],
+ );
+
+ const columns = useMemo(() => getColumns(isEndedTab), [isEndedTab]);
+
+ const handleRowActivate = useCallback(
+ (row: Row<Session>) => {
+ onRowClick(row.original.id);
+ },
+ [onRowClick],
+ );
+
+ const instance = useTreeTableInstance<Session>({
+ data: sessions ?? NO_SESSIONS,
+ columns,
+ getNodeId,
+ sorting,
+ manualSorting: true,
+ enableRowSelection: canSelectSession,
+ rowSelection,
+ onRowSelectionChange,
+ onRowActivate: handleRowActivate,
+ onSortingChange: handleSortingChange,
+ selectedRowId,
+ });
+
+ const { setActiveRowId } = instance;
+ useEffect(() => {
+ setActiveRowId(selectedRowId);
+ }, [selectedRowId, setActiveRowId]);
+
+ useScrollToTop({
+ ref: instance.containerRef,
+ keys: [page, sorting],
+ skip: isFetching,
+ });
+
+ const getRowProps = useCallback(
+ (row: Row<Session>) => ({
+ "data-testid": `session-row-${row.original.id}`,
+ }),
+ [],
+ );
+
+ if (error !== undefined) {
+ return (
+ <Card
+ flex="0 1 auto"
+ mih={0}
+ withBorder
+ p="xl"
+ data-testid="sessions-table"
+ >
+ <LoadingAndErrorWrapper error={error} />
+ </Card>
+ );
+ }
+
+ const showCheckboxes = !isEndedTab;
+
+ return (
+ <MonitorTableCard aria-busy={isFetching} data-testid="sessions-table">
+ {sessions === undefined ? (
+ <TreeTableSkeleton
+ showCheckboxes={showCheckboxes}
+ columnWidths={getColumnWidths(isEndedTab)}
+ />
+ ) : (
+ <>
+ <LoadingOverlay visible={isFetching} data-testid="loading-overlay" />
+ <TreeTable
+ instance={instance}
+ hierarchical={false}
+ showCheckboxes={showCheckboxes}
+ onHeaderCheckboxClick={() => instance.table.toggleAllRowsSelected()}
+ headerCheckboxAriaLabel={t`Select all`}
+ ariaLabel={t`Sessions`}
+ onRowClick={handleRowActivate}
+ getRowProps={getRowProps}
+ emptyState={<MonitorEmptyState label={emptyLabel} />}
+ />
+ </>
+ )}
+ </MonitorTableCard>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/SessionsTable.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/SessionsTable.unit.spec.tsx
new file mode 100644
index 00000000000..b64d8bbbaba
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/SessionsTable.unit.spec.tsx
@@ -0,0 +1,115 @@
+import {
+ mockGetBoundingClientRect,
+ renderWithProviders,
+ screen,
+ within,
+} from "__support__/ui";
+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";
+import type { Session } from "metabase-types/api";
+import { createMockSession } from "metabase-types/api/mocks";
+
+import { SessionsTable } from "./SessionsTable";
+
+type SetupOpts = {
+ sessions: Session[];
+ isEndedTab?: boolean;
+};
+
+const setup = ({ sessions, isEndedTab = false }: SetupOpts) => {
+ mockGetBoundingClientRect({ height: 800, width: 1000 });
+
+ renderWithProviders(
+ <SessionsTable
+ sessions={sessions}
+ error={undefined}
+ isFetching={false}
+ isEndedTab={isEndedTab}
+ page={0}
+ rowSelection={{}}
+ selectedSessionId={undefined}
+ sorting={[{ id: "created_at", desc: true }]}
+ emptyLabel="No sessions"
+ onSortingChange={jest.fn()}
+ onRowSelectionChange={jest.fn()}
+ onRowClick={jest.fn()}
+ />,
+ );
+};
+
+const getRow = (session: Session) =>
+ screen.findByTestId(`session-row-${session.id}`);
+
+const getColumnHeaders = () =>
+ screen
+ .getAllByRole("columnheader")
+ .map((header) => header.textContent)
+ .filter(Boolean);
+
+describe("SessionsTable", () => {
+ it("shows the active tab's columns", async () => {
+ setup({ sessions: [createMockSession()] });
+ await getRow(createMockSession());
+
+ expect(getColumnHeaders()).toEqual([
+ "User",
+ "Device",
+ "Auth method",
+ "Signed in",
+ ]);
+ });
+
+ it("shows when and why each session ended on the ended tab", async () => {
+ const revoked = createMockSession({
+ id: "revoked",
+ status: "ended",
+ ended_at: "2026-09-16T12:00:00Z",
+ end_reason: "admin",
+ });
+ const unrecorded = createMockSession({ id: "unrecorded", status: "ended" });
+ setup({ sessions: [revoked, unrecorded], isEndedTab: true });
+
+ expect(await getRow(revoked)).toHaveTextContent("Revoked by admin");
+ expect(getColumnHeaders()).toEqual([
+ "User",
+ "Device",
+ "Signed in",
+ "Ended",
+ "Reason",
+ ]);
+ expect(
+ within(await getRow(unrecorded)).getAllByText(EMPTY_CELL_PLACEHOLDER),
+ ).toHaveLength(2);
+ expect(screen.queryAllByRole("checkbox")).toHaveLength(0);
+ });
+
+ it("badges the session this browser is using, and doesn't let it be selected", async () => {
+ const current = createMockSession({ id: "current", current: true });
+ const other = createMockSession({ id: "other" });
+ setup({ sessions: [current, other] });
+
+ expect(
+ within(await getRow(current)).getByText("This session"),
+ ).toBeInTheDocument();
+ expect(within(await getRow(current)).getByRole("checkbox")).toBeDisabled();
+ expect(
+ within(await getRow(other)).queryByText("This session"),
+ ).not.toBeInTheDocument();
+ expect(within(await getRow(other)).getByRole("checkbox")).toBeEnabled();
+ });
+
+ it("badges full-app embedding sessions", async () => {
+ const embedded = createMockSession({
+ id: "embedded",
+ type: "full-app-embed",
+ });
+ const normal = createMockSession({ id: "normal", type: "normal" });
+ setup({ sessions: [embedded, normal] });
+
+ expect(
+ within(await getRow(embedded)).getByText("Embedded"),
+ ).toBeInTheDocument();
+ expect(
+ within(await getRow(normal)).queryByText("Embedded"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/index.ts
new file mode 100644
index 00000000000..3640f77198f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/index.ts
@@ -0,0 +1 @@
+export { SessionsTable } from "./SessionsTable";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/utils.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/utils.tsx
new file mode 100644
index 00000000000..71128c7f67f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTable/utils.tsx
@@ -0,0 +1,133 @@
+import { t } from "ttag";
+
+import { DateTime } from "metabase/common/components/DateTime";
+import type { TreeTableColumnDef } from "metabase/ui";
+import { Badge, Ellipsified, Flex } from "metabase/ui";
+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";
+import type { Session } from "metabase-types/api";
+
+import {
+ getEndReasonLabel,
+ getProviderLabel,
+ getSessionTypeLabel,
+ getSessionUserName,
+} from "../utils";
+
+const ACTIVE_COLUMN_WIDTHS = [0.34, 0.3, 0.16, 0.2];
+const ENDED_COLUMN_WIDTHS = [0.26, 0.22, 0.17, 0.18, 0.17];
+
+const DateCell = ({ value }: { value: string }) => (
+ <Ellipsified>
+ <DateTime value={value} unit="minute" />
+ </Ellipsified>
+);
+
+const getUserColumn = (): TreeTableColumnDef<Session> => ({
+ id: "user_email",
+ header: t`User`,
+ minWidth: 200,
+ enableSorting: true,
+ accessorFn: (session) => session.user.email,
+ cell: ({ row }) => (
+ <Flex gap="sm" align="center" miw={0}>
+ <Ellipsified tooltip={row.original.user.email} alwaysShowTooltip>
+ {getSessionUserName(row.original.user)}
+ </Ellipsified>
+ {row.original.current && (
+ <Badge variant="light" color="brand" size="xs" flex="0 0 auto">
+ {t`This session`}
+ </Badge>
+ )}
+ </Flex>
+ ),
+});
+
+const getDeviceColumn = (): TreeTableColumnDef<Session> => ({
+ id: "device",
+ header: t`Device`,
+ minWidth: 180,
+ enableSorting: false,
+ accessorFn: (session) => session.device_description ?? "",
+ cell: ({ row }) => (
+ <Flex gap="sm" align="center" miw={0}>
+ <Ellipsified tooltip={row.original.user_agent}>
+ {row.original.device_description ?? EMPTY_CELL_PLACEHOLDER}
+ </Ellipsified>
+ {row.original.type === "full-app-embed" && (
+ <Badge variant="light" size="xs" flex="0 0 auto">
+ {getSessionTypeLabel(row.original.type)}
+ </Badge>
+ )}
+ </Flex>
+ ),
+});
+
+const getProviderColumn = (): TreeTableColumnDef<Session> => ({
+ id: "provider",
+ header: t`Auth method`,
+ width: 140,
+ enableSorting: true,
+ accessorFn: (session) => getProviderLabel(session.provider),
+ cell: ({ row }) => getProviderLabel(row.original.provider),
+});
+
+const getSignedInColumn = (): TreeTableColumnDef<Session> => ({
+ id: "created_at",
+ header: t`Signed in`,
+ width: 170,
+ enableSorting: true,
+ sortDescFirst: true,
+ accessorFn: (session) => session.created_at,
+ cell: ({ row }) => <DateCell value={row.original.created_at} />,
+});
+
+const getEndedColumn = (): TreeTableColumnDef<Session> => ({
+ id: "ended_at",
+ header: t`Ended`,
+ width: 170,
+ // `ended_at` is not an offered sort column, so don't show a header that cannot round-trip
+ enableSorting: false,
+ accessorFn: (session) => session.ended_at ?? "",
+ cell: ({ row }) =>
+ row.original.ended_at ? (
+ <DateCell value={row.original.ended_at} />
+ ) : (
+ EMPTY_CELL_PLACEHOLDER
+ ),
+});
+
+const getEndReasonColumn = (): TreeTableColumnDef<Session> => ({
+ id: "end_reason",
+ header: t`Reason`,
+ width: 150,
+ enableSorting: false,
+ accessorFn: (session) => session.end_reason ?? "",
+ cell: ({ row }) => (
+ <Ellipsified>
+ {row.original.end_reason
+ ? getEndReasonLabel(row.original.end_reason)
+ : EMPTY_CELL_PLACEHOLDER}
+ </Ellipsified>
+ ),
+});
+
+export const getColumns = (
+ isEndedTab: boolean,
+): TreeTableColumnDef<Session>[] =>
+ isEndedTab
+ ? [
+ getUserColumn(),
+ getDeviceColumn(),
+ getSignedInColumn(),
+ getEndedColumn(),
+ getEndReasonColumn(),
+ ]
+ : [
+ getUserColumn(),
+ getDeviceColumn(),
+ getProviderColumn(),
+ getSignedInColumn(),
+ ];
+
+export const getColumnWidths = (isEndedTab: boolean): number[] =>
+ isEndedTab ? ENDED_COLUMN_WIDTHS : ACTIVE_COLUMN_WIDTHS;
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTabs/SessionsTabs.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTabs/SessionsTabs.tsx
new file mode 100644
index 00000000000..e3c5608c8ac
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTabs/SessionsTabs.tsx
@@ -0,0 +1,53 @@
+import { t } from "ttag";
+
+import { Icon, Tabs } from "metabase/ui";
+import type { IconName } from "metabase-types/api";
+
+import type { SessionsTab } from "../SessionsPage/types";
+
+type SessionsTabsProps = {
+ tab: SessionsTab;
+ onChange: (tab: SessionsTab) => void;
+};
+
+type TabConfig = {
+ value: SessionsTab;
+ icon: IconName;
+ label: string;
+};
+
+export const SessionsTabs = ({ tab, onChange }: SessionsTabsProps) => {
+ const tabs: TabConfig[] = [
+ { value: "active", icon: "key", label: t`Active` },
+ { value: "ended", icon: "history", label: t`Ended` },
+ ];
+
+ const handleTabChange = (value: string | null) => {
+ const next = tabs.find((config) => config.value === value);
+ if (next !== undefined) {
+ onChange(next.value);
+ }
+ };
+
+ return (
+ <Tabs
+ variant="pills"
+ value={tab}
+ onChange={handleTabChange}
+ data-testid="sessions-tabs"
+ >
+ <Tabs.List>
+ {tabs.map((config) => (
+ <Tabs.Tab
+ key={config.value}
+ value={config.value}
+ leftSection={<Icon name={config.icon} />}
+ data-testid={`sessions-tab-${config.value}`}
+ >
+ {config.label}
+ </Tabs.Tab>
+ ))}
+ </Tabs.List>
+ </Tabs>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTabs/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTabs/index.ts
new file mode 100644
index 00000000000..e1893ffea45
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/SessionsTabs/index.ts
@@ -0,0 +1 @@
+export { SessionsTabs } from "./SessionsTabs";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/index.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/index.ts
new file mode 100644
index 00000000000..5e86595a626
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/index.ts
@@ -0,0 +1,11 @@
+import { PLUGIN_MONITOR } from "metabase/plugins";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
+
+import { getSessionManagementRoutes } from "./routes";
+
+export function initializePlugin() {
+ if (hasPremiumFeature("session-management")) {
+ PLUGIN_MONITOR.isSessionManagementEnabled = true;
+ PLUGIN_MONITOR.getSessionManagementRoutes = getSessionManagementRoutes;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/routes.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/routes.tsx
new file mode 100644
index 00000000000..f89a63cc4fe
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/routes.tsx
@@ -0,0 +1,17 @@
+import { Route } from "metabase/router";
+
+const sessionsPage = () =>
+ import(
+ /* webpackChunkName: "monitor-session-management" */ "./SessionsPage"
+ ).then(({ SessionsPage }) => ({
+ Component: SessionsPage,
+ }));
+
+export function getSessionManagementRoutes() {
+ return (
+ <>
+ <Route index lazy={sessionsPage} />
+ <Route path=":sessionId" lazy={sessionsPage} />
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/session-management/utils.ts b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/utils.ts
new file mode 100644
index 00000000000..b59fcf00573
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/session-management/utils.ts
@@ -0,0 +1,53 @@
+import { match } from "ts-pattern";
+import { t } from "ttag";
+
+import type {
+ SessionEndReason,
+ SessionType,
+ SessionUser,
+} from "metabase-types/api";
+
+import type { SessionsTimePreset } from "./SessionsPage/types";
+
+export const getSessionUserName = (user: SessionUser): string =>
+ user.common_name ?? user.email;
+
+export const getProviderLabel = (provider: string): string =>
+ match(provider)
+ .with("password", () => t`Password`)
+ .with("ldap", () => t`LDAP`)
+ .with("google", () => t`Google`)
+ .with("slack-connect", () => t`Slack`)
+ .with("custom-oidc", () => t`OIDC`)
+ .with("jwt", () => t`JWT`)
+ .with("saml", () => t`SAML`)
+ .with("support-access-grant", () => t`Support access`)
+ .with("unknown", () => t`Unknown`)
+ .otherwise(() => provider);
+
+export const getSessionTypeLabel = (type: SessionType): string =>
+ match(type)
+ .with("normal", () => t`Normal`)
+ .with("full-app-embed", () => t`Embedded`)
+ .exhaustive();
+
+export const getTimePresetLabel = (preset: SessionsTimePreset): string =>
+ match(preset)
+ .with("hour", () => t`Past hour`)
+ .with("day", () => t`Past day`)
+ .with("week", () => t`Past week`)
+ .with("month", () => t`Past month`)
+ .exhaustive();
+
+export const getEndReasonLabel = (reason: SessionEndReason): string =>
+ match(reason)
+ .with("admin", () => t`Revoked by admin`)
+ .with("logout", () => t`Signed out`)
+ .with("password-change", () => t`Password changed`)
+ .with("user-deactivated", () => t`User deactivated`)
+ .with("tenant-deactivated", () => t`Tenant deactivated`)
+ .with("sso-logout", () => t`SSO logout`)
+ .with("support-grant-revoked", () => t`Support access revoked`)
+ .with("expired", () => t`Expired`)
+ .with("timed-out", () => t`Timed out`)
+ .exhaustive();
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.ts b/enterprise/frontend/src/metabase-enterprise/plugins.ts
index 1036e671f3a..4b322364e4e 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.ts
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.ts
@@ -33,6 +33,7 @@ import { initializePlugin as initializeMetabot } from "./metabot";
import { initializePlugin as initializeModelPersistence } from "./model_persistence";
import { initializePlugin as initializeModeration } from "./moderation";
import { initializePlugin as initializeMonitorDependencyDiagnostics } from "./monitor/dependency-diagnostics";
+import { initializePlugin as initializeMonitorSessionManagement } from "./monitor/session-management";
import { initializePlugin as initializeTools } from "./monitor/tools";
import { initializePlugin as initializeMultiFactorAuth } from "./multi_factor_auth";
import { initializePlugin as initializeRemoteSync } from "./remote_sync";
@@ -88,6 +89,7 @@ export function initializePlugins() {
initializeModelPersistence();
initializeModeration();
initializeMonitorDependencyDiagnostics();
+ initializeMonitorSessionManagement();
initializeMultiFactorAuth();
initializeRemoteSync();
initializeReplacement();
diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.ts
index fe01799e774..dc84fa74312 100644
--- a/frontend/src/metabase-types/analytics/event.ts
+++ b/frontend/src/metabase-types/analytics/event.ts
@@ -92,6 +92,7 @@ export type MonitorSectionClickedEvent = ValidateEvent<{
| "jobs"
| "logs"
| "model-caching"
+ | "session-management"
| "ai-auditing-usage-stats"
| "ai-auditing-conversations"
| "ai-auditing-mcp"
diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.ts
index 06140abb0d9..dcabc5312a3 100644
--- a/frontend/src/metabase-types/api/index.ts
+++ b/frontend/src/metabase-types/api/index.ts
@@ -62,6 +62,7 @@ export * from "./search";
export * from "./security-center";
export * from "./segment";
export * from "./session";
+export * from "./session-management";
export * from "./settings";
export * from "./setup";
export * from "./slack";
diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.ts
index 6bd6f254e18..1e19f6f7ba1 100644
--- a/frontend/src/metabase-types/api/mocks/index.ts
+++ b/frontend/src/metabase-types/api/mocks/index.ts
@@ -41,6 +41,7 @@ export * from "./search";
export * from "./segment";
export * from "./series";
export * from "./session";
+export * from "./session-management";
export * from "./settings";
export * from "./slack";
export * from "./snippets";
diff --git a/frontend/src/metabase-types/api/mocks/session-management.ts b/frontend/src/metabase-types/api/mocks/session-management.ts
new file mode 100644
index 00000000000..db18f05a4ed
--- /dev/null
+++ b/frontend/src/metabase-types/api/mocks/session-management.ts
@@ -0,0 +1,44 @@
+import type {
+ RevokeSessionsResponse,
+ Session,
+ SessionUser,
+} from "metabase-types/api";
+
+export const createMockSessionUser = (
+ opts: Partial<SessionUser> = {},
+): SessionUser => ({
+ id: 1,
+ email: "[email protected]",
+ common_name: "Test User",
+ ...opts,
+});
+
+export const createMockSession = (opts: Partial<Session> = {}): Session => ({
+ id: "3b2f4c1e-9a7d-4e6b-8c5a-1d0f2e3b4a5c",
+ user: createMockSessionUser(),
+ type: "normal",
+ provider: "password",
+ created_at: "2026-09-01T12:00:00Z",
+ last_active_at: "2026-09-15T09:30:00Z",
+ expires_at: "2026-09-15T12:00:00Z",
+ user_agent:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
+ device_description: "Browser (Chrome/Macintosh)",
+ ip_address: "127.0.0.1",
+ device_id: "7a6f5e4d-3c2b-4a19-8e7d-6c5b4a392817",
+ current: false,
+ status: "live",
+ ended_at: null,
+ end_reason: null,
+ ended_by: null,
+ ...opts,
+});
+
+export const createMockRevokeSessionsResponse = (
+ opts: Partial<RevokeSessionsResponse> = {},
+): RevokeSessionsResponse => ({
+ revoked: 1,
+ remaining: 0,
+ user_ids: [1],
+ ...opts,
+});
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index f7680be12ce..bb1a95ead85 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -150,6 +150,7 @@ export const createMockTokenFeatures = (
library: false,
library_retrieval: false,
"support-users": false,
+ "session-management": false,
tenants: false,
writable_connection: false,
admin_security_center: false,
diff --git a/frontend/src/metabase-types/api/session-management.ts b/frontend/src/metabase-types/api/session-management.ts
new file mode 100644
index 00000000000..86de58cc9b9
--- /dev/null
+++ b/frontend/src/metabase-types/api/session-management.ts
@@ -0,0 +1,112 @@
+import type { PaginationRequest, PaginationResponse } from "./pagination";
+import type { SortDirection } from "./sorting";
+import type { UserId } from "./user";
+
+export type SessionId = string;
+
+export type SessionType = "normal" | "full-app-embed";
+
+export const SESSION_PROVIDERS = [
+ "password",
+ "ldap",
+ "google",
+ "slack-connect",
+ "custom-oidc",
+ "jwt",
+ "saml",
+ "support-access-grant",
+ "unknown",
+] as const;
+export type SessionProvider = (typeof SESSION_PROVIDERS)[number];
+
+export type SessionTenancy = "all" | "internal" | "external";
+
+export type SessionStatus = "live" | "ended";
+
+// A session is only ever live or ended; `all` is accepted by the filter alone
+export type SessionStatusFilter = SessionStatus | "all";
+
+// One value per path that ends a session
+export const SESSION_END_REASONS = [
+ "admin",
+ "logout",
+ "password-change",
+ "user-deactivated",
+ "tenant-deactivated",
+ "sso-logout",
+ "support-grant-revoked",
+ "expired",
+ "timed-out",
+] as const;
+export type SessionEndReason = (typeof SESSION_END_REASONS)[number];
+
+export type SessionSortColumn =
+ | "created_at"
+ | "last_active_at"
+ | "user_email"
+ | "provider"
+ | "ended_at";
+
+export type SessionUser = {
+ id: UserId;
+ email: string;
+ common_name: string | null;
+};
+
+export type Session = {
+ id: SessionId;
+ user: SessionUser;
+ type: SessionType;
+ // The response schema is any string; only the filter is limited to SessionProvider
+ provider: string;
+ created_at: string;
+ last_active_at: string | null;
+ expires_at: string;
+ user_agent: string | null;
+ device_description: string | null;
+ ip_address: string | null;
+ device_id: string | null;
+ current: boolean;
+ status: SessionStatus;
+ ended_at: string | null;
+ end_reason: SessionEndReason | null;
+ ended_by: UserId | null;
+};
+
+export type SessionFilters = {
+ "user-id"?: UserId;
+ ids?: SessionId[];
+ // A list: the endpoint coerces a single `?provider=` into one, so filtering on several auth methods is one request
+ provider?: SessionProvider[];
+ type?: SessionType;
+ tenancy?: SessionTenancy;
+ "created-before"?: string;
+ "created-after"?: string;
+ "last-active-before"?: string;
+ "last-active-after"?: string;
+};
+
+export type SessionListParams = SessionFilters &
+ PaginationRequest & {
+ query?: string;
+ status?: SessionStatusFilter;
+ reason?: SessionEndReason;
+ "ended-before"?: string;
+ "ended-after"?: string;
+ "sort-column"?: SessionSortColumn;
+ "sort-direction"?: SortDirection;
+ };
+
+export type SessionListResponse = PaginationResponse & {
+ data: Session[];
+};
+
+export type RevokeSessionsRequest = SessionFilters & {
+ "exclude-current"?: boolean;
+};
+
+export type RevokeSessionsResponse = {
+ revoked: number;
+ remaining: number;
+ user_ids: UserId[];
+};
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index da982a6d368..cfdc7b13bf9 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -381,6 +381,7 @@ export const tokenFeatures = [
"library",
"library_retrieval",
"support-users",
+ "session-management",
"tenants",
"writable_connection",
"admin_security_center",
diff --git a/frontend/src/metabase/common/hooks/use-page-in-range.ts b/frontend/src/metabase/common/hooks/use-page-in-range.ts
new file mode 100644
index 00000000000..3abbc03c86a
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-page-in-range.ts
@@ -0,0 +1,30 @@
+import { useEffect } from "react";
+
+type UsePageInRangeOptions = {
+ page: number;
+ pageSize: number;
+ /** `undefined` until the total belongs to the current request, so a stale or loading one moves nothing */
+ total: number | undefined;
+ onPageChange: (page: number) => void;
+};
+
+/**
+ * Moves `page` back to the last page when it points past the end, e.g. after the rest of a later page is deleted.
+ * Pagination controls hide once everything fits on one page, which would otherwise strand the user there.
+ */
+export function usePageInRange({
+ page,
+ pageSize,
+ total,
+ onPageChange,
+}: UsePageInRangeOptions) {
+ useEffect(() => {
+ if (total === undefined) {
+ return;
+ }
+ const lastPage = Math.max(0, Math.ceil(total / pageSize) - 1);
+ if (page > lastPage) {
+ onPageChange(lastPage);
+ }
+ }, [page, pageSize, total, onPageChange]);
+}
diff --git a/frontend/src/metabase/common/hooks/use-page-in-range.unit.spec.ts b/frontend/src/metabase/common/hooks/use-page-in-range.unit.spec.ts
new file mode 100644
index 00000000000..177495c60a4
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-page-in-range.unit.spec.ts
@@ -0,0 +1,65 @@
+import { renderHook } from "@testing-library/react";
+
+import { usePageInRange } from "./use-page-in-range";
+
+const PAGE_SIZE = 50;
+
+type SetupOpts = {
+ page: number;
+ total: number | undefined;
+};
+
+const setup = ({ page, total }: SetupOpts) => {
+ const onPageChange = jest.fn();
+ const { rerender } = renderHook(
+ (props: SetupOpts) =>
+ usePageInRange({ ...props, pageSize: PAGE_SIZE, onPageChange }),
+ { initialProps: { page, total } },
+ );
+ return { onPageChange, rerender };
+};
+
+describe("usePageInRange", () => {
+ it.each([
+ { page: 0, total: 0 },
+ { page: 0, total: PAGE_SIZE },
+ { page: 1, total: PAGE_SIZE + 1 },
+ { page: 2, total: PAGE_SIZE * 3 },
+ ])("keeps page $page, which $total items reach", ({ page, total }) => {
+ const { onPageChange } = setup({ page, total });
+
+ expect(onPageChange).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { page: 1, total: PAGE_SIZE, lastPage: 0 },
+ { page: 3, total: PAGE_SIZE + 1, lastPage: 1 },
+ { page: 2, total: 0, lastPage: 0 },
+ ])(
+ "moves page $page back to page $lastPage, the last that $total items reach",
+ ({ page, total, lastPage }) => {
+ const { onPageChange } = setup({ page, total });
+
+ expect(onPageChange).toHaveBeenCalledTimes(1);
+ expect(onPageChange).toHaveBeenCalledWith(lastPage);
+ },
+ );
+
+ it("waits while the total is unknown", () => {
+ const { onPageChange } = setup({ page: 3, total: undefined });
+
+ expect(onPageChange).not.toHaveBeenCalled();
+ });
+
+ it("moves back once the total shrinks below the page", () => {
+ const { onPageChange, rerender } = setup({
+ page: 1,
+ total: PAGE_SIZE + 1,
+ });
+ expect(onPageChange).not.toHaveBeenCalled();
+
+ rerender({ page: 1, total: PAGE_SIZE });
+
+ expect(onPageChange).toHaveBeenCalledWith(0);
+ });
+});
diff --git a/frontend/src/metabase/common/monitor/selectors.ts b/frontend/src/metabase/common/monitor/selectors.ts
index 176362dd820..74068fe9668 100644
--- a/frontend/src/metabase/common/monitor/selectors.ts
+++ b/frontend/src/metabase/common/monitor/selectors.ts
@@ -32,6 +32,13 @@ export function canAccessAlertsManagement(state: State) {
return getUserIsAdmin(state);
}
+export function canAccessSessionManagement(state: State) {
+ if (isWithinIframe()) {
+ return false;
+ }
+ return getUserIsAdmin(state);
+}
+
export function canAccessAiAuditing(state: State) {
if (isWithinIframe()) {
return false;
diff --git a/frontend/src/metabase/common/monitor/selectors.unit.spec.ts b/frontend/src/metabase/common/monitor/selectors.unit.spec.ts
index d3e3268b71a..974338a1691 100644
--- a/frontend/src/metabase/common/monitor/selectors.unit.spec.ts
+++ b/frontend/src/metabase/common/monitor/selectors.unit.spec.ts
@@ -11,6 +11,7 @@ import {
canAccessMonitor,
canAccessMonitorDiagnostics,
canAccessMonitoringTools,
+ canAccessSessionManagement,
} from "./selectors";
jest.mock("metabase/utils/iframe", () => ({
@@ -234,6 +235,52 @@ describe("canAccessAlertsManagement", () => {
});
});
+describe("canAccessSessionManagement", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ isWithinIframe.mockReturnValue(false);
+ });
+
+ it("returns false when in embedding iframe", () => {
+ isWithinIframe.mockReturnValue(true);
+ const state = createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ });
+
+ expect(canAccessSessionManagement(state)).toBe(false);
+ });
+
+ it("returns true when user is admin", () => {
+ const state = createMockState({
+ currentUser: createMockUser({ is_superuser: true }),
+ });
+
+ expect(canAccessSessionManagement(state)).toBe(true);
+ });
+
+ it("returns false for an analyst without admin", () => {
+ const state = createMockState({
+ currentUser: createMockUser({
+ is_superuser: false,
+ is_data_analyst: true,
+ }),
+ });
+
+ expect(canAccessSessionManagement(state)).toBe(false);
+ });
+
+ it("returns false for a non-admin with the monitoring application permission", () => {
+ const state = createMockState({
+ currentUser: createMockUser({
+ is_superuser: false,
+ permissions: { can_access_monitoring: true },
+ }),
+ });
+
+ expect(canAccessSessionManagement(state)).toBe(false);
+ });
+});
+
describe("canAccessAiAuditing", () => {
beforeEach(() => {
jest.clearAllMocks();
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsRow.tsx b/frontend/src/metabase/monitor/components/DetailSidebar/DetailsRow.tsx
similarity index 100%
rename from frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsRow.tsx
rename to frontend/src/metabase/monitor/components/DetailSidebar/DetailsRow.tsx
diff --git a/frontend/src/metabase/monitor/components/DetailSidebar/DetailsTable.module.css b/frontend/src/metabase/monitor/components/DetailSidebar/DetailsTable.module.css
new file mode 100644
index 00000000000..b1396811449
--- /dev/null
+++ b/frontend/src/metabase/monitor/components/DetailSidebar/DetailsTable.module.css
@@ -0,0 +1,3 @@
+.detailsTable {
+ overflow: hidden;
+}
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsTable.tsx b/frontend/src/metabase/monitor/components/DetailSidebar/DetailsTable.tsx
similarity index 90%
rename from frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsTable.tsx
rename to frontend/src/metabase/monitor/components/DetailSidebar/DetailsTable.tsx
index 5103b7e920f..6d84557f2f7 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsTable.tsx
+++ b/frontend/src/metabase/monitor/components/DetailSidebar/DetailsTable.tsx
@@ -3,7 +3,7 @@ import { Children, Fragment } from "react";
import { Box, Divider } from "metabase/ui";
-import S from "./NotificationDetailSidebar.module.css";
+import S from "./DetailsTable.module.css";
export const DetailsTable = ({ children }: { children: ReactNode }) => {
const items = Children.toArray(children).filter(Boolean);
diff --git a/frontend/src/metabase/monitor/components/DetailSidebar/SidebarNavButton.module.css b/frontend/src/metabase/monitor/components/DetailSidebar/SidebarNavButton.module.css
new file mode 100644
index 00000000000..447a4a491e2
--- /dev/null
+++ b/frontend/src/metabase/monitor/components/DetailSidebar/SidebarNavButton.module.css
@@ -0,0 +1,18 @@
+.navButton {
+ color: var(--mb-color-text-primary);
+ background: var(--mb-color-background_surface-primary);
+ border: 1px solid var(--mb-color-border-neutral);
+
+ &:hover {
+ background: var(--mb-color-background_surface-hover);
+ }
+
+ &[data-disabled] {
+ color: var(--mb-color-text-disabled);
+ background: var(--mb-color-background_surface-primary);
+
+ &:hover {
+ background: var(--mb-color-background_surface-primary);
+ }
+ }
+}
diff --git a/frontend/src/metabase/monitor/components/DetailSidebar/SidebarNavButton.tsx b/frontend/src/metabase/monitor/components/DetailSidebar/SidebarNavButton.tsx
new file mode 100644
index 00000000000..0a00be0bebd
--- /dev/null
+++ b/frontend/src/metabase/monitor/components/DetailSidebar/SidebarNavButton.tsx
@@ -0,0 +1,28 @@
+import { ActionIcon, Icon } from "metabase/ui";
+import type { IconName } from "metabase-types/api";
+
+import S from "./SidebarNavButton.module.css";
+import type { SidebarNavButtonProps, SidebarNavDirection } from "./types";
+
+const NAV_ICONS: Record<SidebarNavDirection, IconName> = {
+ previous: "chevronup",
+ next: "chevrondown",
+};
+
+export const SidebarNavButton = ({
+ direction,
+ label,
+ disabled,
+ onClick,
+}: SidebarNavButtonProps) => (
+ <ActionIcon
+ aria-label={label}
+ size="lg"
+ variant="default"
+ className={S.navButton}
+ disabled={disabled}
+ onClick={onClick}
+ >
+ <Icon name={NAV_ICONS[direction]} />
+ </ActionIcon>
+);
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarSection.tsx b/frontend/src/metabase/monitor/components/DetailSidebar/SidebarSection.tsx
similarity index 100%
rename from frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarSection.tsx
rename to frontend/src/metabase/monitor/components/DetailSidebar/SidebarSection.tsx
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/constants.ts b/frontend/src/metabase/monitor/components/DetailSidebar/constants.ts
similarity index 100%
rename from frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/constants.ts
rename to frontend/src/metabase/monitor/components/DetailSidebar/constants.ts
diff --git a/frontend/src/metabase/monitor/components/DetailSidebar/index.ts b/frontend/src/metabase/monitor/components/DetailSidebar/index.ts
new file mode 100644
index 00000000000..fbf140c2dbe
--- /dev/null
+++ b/frontend/src/metabase/monitor/components/DetailSidebar/index.ts
@@ -0,0 +1,6 @@
+export * from "./constants";
+export * from "./DetailsRow";
+export * from "./DetailsTable";
+export * from "./SidebarNavButton";
+export * from "./SidebarSection";
+export type * from "./types";
diff --git a/frontend/src/metabase/monitor/components/DetailSidebar/types.ts b/frontend/src/metabase/monitor/components/DetailSidebar/types.ts
new file mode 100644
index 00000000000..aff2123f8f8
--- /dev/null
+++ b/frontend/src/metabase/monitor/components/DetailSidebar/types.ts
@@ -0,0 +1,23 @@
+import type { ReactNode } from "react";
+
+export type SidebarSectionProps = {
+ title: string;
+ titleAside?: ReactNode;
+ children: ReactNode;
+};
+
+export type DetailsRowProps = {
+ label: ReactNode;
+ value: ReactNode;
+ bold?: boolean;
+ spanLabel?: boolean;
+};
+
+export type SidebarNavDirection = "previous" | "next";
+
+export type SidebarNavButtonProps = {
+ direction: SidebarNavDirection;
+ label: string;
+ disabled: boolean;
+ onClick: () => void;
+};
diff --git a/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.tsx b/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.tsx
index 8d26a8f7aac..616d0bc0429 100644
--- a/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.tsx
+++ b/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.tsx
@@ -11,6 +11,7 @@ import {
canAccessAlertsManagement,
canAccessMonitorDiagnostics,
canAccessMonitoringTools,
+ canAccessSessionManagement,
} from "metabase/common/monitor/selectors";
import { useUserKeyValue } from "metabase/current-user";
import {
@@ -44,6 +45,10 @@ function getActiveSection(pathname: string): MonitorSection | null {
P.string.startsWith(Urls.monitorModelPersistenceLog()),
() => "model-caching",
)
+ .with(
+ P.string.startsWith(Urls.monitorSessions()),
+ () => "session-management",
+ )
.with(
P.string.startsWith(Urls.monitorAiAuditingMcp()),
() => "ai-auditing-mcp",
@@ -78,9 +83,11 @@ export function MonitorLayout() {
const hasDependenciesFeature = useHasTokenFeature("dependencies");
const hasAuditAppFeature = useHasTokenFeature("audit_app");
const hasAiControlsFeature = useHasTokenFeature("ai_controls");
+ const hasSessionManagementFeature = useHasTokenFeature("session-management");
const canAccessDiagnostics = useSelector(canAccessMonitorDiagnostics);
const canAccessTools = useSelector(canAccessMonitoringTools);
const canAccessAlerts = useSelector(canAccessAlertsManagement);
+ const canAccessSessions = useSelector(canAccessSessionManagement);
const canAccessAiAuditingTab = useSelector(canAccessAiAuditing);
const activeSection = getActiveSection(pathname);
@@ -169,6 +176,17 @@ export function MonitorLayout() {
showLabel={isNavbarOpened}
onClick={() => trackMonitorSectionClicked("model-caching")}
/>
+ {canAccessSessions && (
+ <AreaTab
+ label={t`Session management`}
+ icon="key"
+ to={Urls.monitorSessions()}
+ isSelected={activeSection === "session-management"}
+ showLabel={isNavbarOpened}
+ isGated={!hasSessionManagementFeature}
+ onClick={() => trackMonitorSectionClicked("session-management")}
+ />
+ )}
</AreaTabGroup>
)}
{canAccessAiAuditingTab && hasAuditAppFeature && (
diff --git a/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.unit.spec.tsx b/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.unit.spec.tsx
index d0dfb8ff7c9..de3e69b5b0b 100644
--- a/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/components/MonitorLayout/MonitorLayout.unit.spec.tsx
@@ -152,6 +152,7 @@ describe("MonitorLayout", () => {
["Scheduled jobs", Urls.monitorJobs()],
["Application logs", Urls.monitorLogs()],
["Model persistence log", Urls.monitorModelPersistenceLog()],
+ ["Session management", Urls.monitorSessions()],
];
expectedTabs.forEach(([name, href]) => {
@@ -195,6 +196,11 @@ describe("MonitorLayout", () => {
route: Urls.monitorModelPersistenceLog(),
section: "model-caching",
},
+ {
+ label: "Session management",
+ route: Urls.monitorSessions(),
+ section: "session-management",
+ },
] as const;
it.each(SECTION_CASES)(
@@ -426,6 +432,33 @@ describe("MonitorLayout", () => {
expect(onRender).toHaveBeenCalledTimes(renderCount);
});
+ it.each([
+ {
+ description: "an analyst",
+ user: createMockUser({ is_superuser: false, is_data_analyst: true }),
+ },
+ {
+ description: "a non-admin with the monitoring permission",
+ user: createMockUser({
+ is_superuser: false,
+ permissions: { can_access_monitoring: true },
+ }),
+ },
+ ])(
+ "hides Session management (admin-only) for $description",
+ async ({ user }) => {
+ setup({ user });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("monitor-nav")).toBeInTheDocument();
+ });
+
+ expect(
+ screen.queryByRole("link", { name: "Session management" }),
+ ).not.toBeInTheDocument();
+ },
+ );
+
const getTabGem = (name: string) =>
within(screen.getByRole("link", { name })).queryByTestId("upsell-gem");
@@ -462,6 +495,29 @@ describe("MonitorLayout", () => {
expect(getTabGem("Erroring questions")).not.toBeInTheDocument();
});
+ it.each([
+ {
+ expectation:
+ "gates Session management without the session-management feature",
+ hasFeature: false,
+ isGated: true,
+ },
+ {
+ expectation:
+ "does not gate Session management with the session-management feature",
+ hasFeature: true,
+ isGated: false,
+ },
+ ])("$expectation", async ({ hasFeature, isGated }) => {
+ setup({ tokenFeatures: { "session-management": hasFeature } });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("monitor-nav")).toBeInTheDocument();
+ });
+
+ expect(getTabGem("Session management") !== null).toBe(isGated);
+ });
+
const AI_AUDITING_GROUP = "AI Auditing";
it("shows ungated Usage stats, Conversations, and MCP analytics when audit_app and ai_controls are both enabled", async () => {
diff --git a/frontend/src/metabase/monitor/route-guards.tsx b/frontend/src/metabase/monitor/route-guards.tsx
index c257c03d9f2..bfee9a50c9e 100644
--- a/frontend/src/metabase/monitor/route-guards.tsx
+++ b/frontend/src/metabase/monitor/route-guards.tsx
@@ -4,6 +4,7 @@ import {
canAccessMonitor,
canAccessMonitorDiagnostics,
canAccessMonitoringTools,
+ canAccessSessionManagement,
} from "metabase/common/monitor/selectors";
import {
MetabaseIsSetup,
@@ -32,6 +33,11 @@ const UserCanAccessAlertsManagement = createRedirectGuard(
"/unauthorized",
);
+const UserCanAccessSessionManagement = createRedirectGuard(
+ (state) => canAccessSessionManagement(state),
+ "/unauthorized",
+);
+
const UserCanAccessAiAuditing = createRedirectGuard(
(state) => canAccessAiAuditing(state),
"/unauthorized",
@@ -65,6 +71,12 @@ export const CanAccessAlertsManagement = () => (
</UserCanAccessAlertsManagement>
);
+export const CanAccessSessionManagement = () => (
+ <UserCanAccessSessionManagement>
+ <Outlet />
+ </UserCanAccessSessionManagement>
+);
+
export const CanAccessAiAuditing = () => (
<UserCanAccessAiAuditing>
<Outlet />
diff --git a/frontend/src/metabase/monitor/routes.tsx b/frontend/src/metabase/monitor/routes.tsx
index cbbcb133b32..fcb9e2b167c 100644
--- a/frontend/src/metabase/monitor/routes.tsx
+++ b/frontend/src/metabase/monitor/routes.tsx
@@ -32,6 +32,7 @@ import {
CanAccessMonitor,
CanAccessMonitorDiagnostics,
CanAccessMonitoringTools,
+ CanAccessSessionManagement,
} from "./route-guards";
/** Lands on the first Monitor section the user can access. */
@@ -85,6 +86,13 @@ const modelPersistenceLogPage = () =>
Component: ModelPersistenceLogPage,
}));
+const sessionManagementUpsellPage = () =>
+ import(
+ /* webpackChunkName: "monitor" */ "metabase/monitor/session-management/SessionManagementUpsellPage"
+ ).then(({ SessionManagementUpsellPage }) => ({
+ Component: SessionManagementUpsellPage,
+ }));
+
// The log levels modal renders a code editor, which nothing else on the logs
// page needs. Its parent route is already lazy, but a modal declared with
// `modalRoute` holds its component eagerly.
@@ -142,6 +150,19 @@ export function getMonitorRoutes() {
<Route path="notifications">{getNotificationsRoutes()}</Route>
</Route>
+ <Route element={<CanAccessSessionManagement />}>
+ {PLUGIN_MONITOR.isSessionManagementEnabled ? (
+ <Route path="sessions">
+ {PLUGIN_MONITOR.getSessionManagementRoutes()}
+ </Route>
+ ) : (
+ <Route path="sessions">
+ <Route index lazy={sessionManagementUpsellPage} />
+ <Route path="*" lazy={sessionManagementUpsellPage} />
+ </Route>
+ )}
+ </Route>
+
<Route element={<CanAccessAiAuditing />}>
{PLUGIN_AUDIT.isAiAuditingEnabled && (
<Route path="ai-auditing">
diff --git a/frontend/src/metabase/monitor/routes.unit.spec.tsx b/frontend/src/metabase/monitor/routes.unit.spec.tsx
index 80677628252..fe3874660af 100644
--- a/frontend/src/metabase/monitor/routes.unit.spec.tsx
+++ b/frontend/src/metabase/monitor/routes.unit.spec.tsx
@@ -6,7 +6,7 @@ describe("monitor routes", () => {
it("resolves every page", async () => {
const loaders = lazyLoaders(getMonitorRoutes());
- expect(loaders).toHaveLength(13);
+ expect(loaders).toHaveLength(15);
for (const load of loaders) {
expect((await load()).Component).toBeDefined();
diff --git a/frontend/src/metabase/monitor/session-management/SessionManagementUpsellPage.tsx b/frontend/src/metabase/monitor/session-management/SessionManagementUpsellPage.tsx
new file mode 100644
index 00000000000..eebcd7f14da
--- /dev/null
+++ b/frontend/src/metabase/monitor/session-management/SessionManagementUpsellPage.tsx
@@ -0,0 +1,19 @@
+import { t } from "ttag";
+
+import { usePageTitle } from "metabase/hooks/use-page-title";
+import { BaseUpsellPage } from "metabase/monitor/upsells";
+
+export function SessionManagementUpsellPage() {
+ usePageTitle(t`Session management`);
+
+ return (
+ <BaseUpsellPage
+ campaign="session-management"
+ location="monitor-session-management-page"
+ header={t`Session management`}
+ title={t`Session management`}
+ // eslint-disable-next-line metabase/no-literal-metabase-strings
+ description={t`See who is signed in to your Metabase. Revoke individual sessions, all sessions for a single person, or all sessions for your Metabase.`}
+ />
+ );
+}
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx
index 1dbf54a5995..0fd742fc6f0 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/DetailsSection.tsx
@@ -1,13 +1,15 @@
import { t } from "ttag";
import { Link as MBLink } from "metabase/common/components/Link";
+import {
+ DetailsRow,
+ DetailsTable,
+ SidebarSection,
+} from "metabase/monitor/components/DetailSidebar";
import * as Urls from "metabase/urls";
import { NotificationSummary } from "../NotificationSummary";
-import { DetailsRow } from "./DetailsRow";
-import { DetailsTable } from "./DetailsTable";
-import { SidebarSection } from "./SidebarSection";
import type { DetailsSectionProps } from "./types";
import { formatChannelSummary } from "./utils";
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.module.css b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.module.css
index 6ac059c9aed..d773ea43947 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.module.css
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/NotificationDetailSidebar.module.css
@@ -1,22 +1,3 @@
-.navButton {
- color: var(--mb-color-text-primary);
- background: var(--mb-color-background_surface-primary);
- border: 1px solid var(--mb-color-border-neutral);
-
- &:hover {
- background: var(--mb-color-background_surface-hover);
- }
-
- &[data-disabled] {
- color: var(--mb-color-text-disabled);
- background: var(--mb-color-background_surface-primary);
-
- &:hover {
- background: var(--mb-color-background_surface-primary);
- }
- }
-}
-
.avatarStack {
flex-shrink: 0;
}
@@ -24,7 +5,3 @@
.channelAvatar {
flex-shrink: 0;
}
-
-.detailsTable {
- overflow: hidden;
-}
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/NotificationRunSummaryLog.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/NotificationRunSummaryLog.tsx
index b25d76426d0..e3740be2a87 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/NotificationRunSummaryLog.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/NotificationRunSummaryLog.tsx
@@ -2,14 +2,16 @@ import { t } from "ttag";
import { Link } from "metabase/common/components/Link";
import { dayjs } from "metabase/dayjs";
+import {
+ DetailsRow,
+ DetailsTable,
+ SidebarSection,
+} from "metabase/monitor/components/DetailSidebar";
import { Anchor, Badge, Flex, Loader, Text, Tooltip } from "metabase/ui";
import * as Urls from "metabase/urls";
import { formatRelativeDate } from "../NotificationsAdminPage/utils";
-import { DetailsRow } from "./DetailsRow";
-import { DetailsTable } from "./DetailsTable";
-import { SidebarSection } from "./SidebarSection";
import type { NotificationRunSummaryLogProps } from "./types";
export const NotificationRunSummaryLog = ({
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx
index f15dfa7bfbd..1e03e8476ea 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarBody.tsx
@@ -1,14 +1,16 @@
import { t } from "ttag";
+import {
+ DetailsTable,
+ SidebarSection,
+} from "metabase/monitor/components/DetailSidebar";
import { summarizeChannels } from "metabase/monitor/tools/notifications/utils";
import { Flex, Stack, Text } from "metabase/ui";
import { trackAlertsManagementRunHistoryViewAllClicked } from "../analytics";
import { DetailsSection } from "./DetailsSection";
-import { DetailsTable } from "./DetailsTable";
import { NotificationRunSummaryLog } from "./NotificationRunSummaryLog";
-import { SidebarSection } from "./SidebarSection";
import type { SidebarBodyProps } from "./types";
import {
getEmailRecipientLabel,
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarHeader.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarHeader.tsx
index 9dddcc8aeed..0448d8ae92d 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarHeader.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/SidebarHeader.tsx
@@ -1,5 +1,6 @@
import { t } from "ttag";
+import { SidebarNavButton } from "metabase/monitor/components/DetailSidebar";
import { useDispatch } from "metabase/redux";
import { addUndo } from "metabase/redux/undo";
import { useNavigate } from "metabase/router";
@@ -23,7 +24,6 @@ import {
} from "../analytics";
import { ChannelAvatarStack } from "./ChannelAvatarStack";
-import S from "./NotificationDetailSidebar.module.css";
import type { SidebarHeaderProps } from "./types";
export const SidebarHeader = ({
@@ -61,26 +61,18 @@ export const SidebarHeader = ({
<Stack gap="xl">
<Flex justify="space-between" align="center">
<Group gap="sm">
- <ActionIcon
- aria-label={t`Previous alert`}
- size="lg"
- variant="default"
- className={S.navButton}
+ <SidebarNavButton
+ direction="previous"
+ label={t`Previous alert`}
disabled={prevNotificationId === undefined}
onClick={() => handleNavigate(prevNotificationId)}
- >
- <Icon name="chevronup" />
- </ActionIcon>
- <ActionIcon
- aria-label={t`Next alert`}
- size="lg"
- variant="default"
- className={S.navButton}
+ />
+ <SidebarNavButton
+ direction="next"
+ label={t`Next alert`}
disabled={nextNotificationId === undefined}
onClick={() => handleNavigate(nextNotificationId)}
- >
- <Icon name="chevrondown" />
- </ActionIcon>
+ />
</Group>
<Group gap="sm">
<Menu position="bottom-end" withinPortal>
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/types.ts b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/types.ts
index 318993da115..1e7675a1994 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/types.ts
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationDetailSidebar/types.ts
@@ -1,5 +1,3 @@
-import type { ReactNode } from "react";
-
import type {
AdminNotification,
AdminNotificationDetail,
@@ -52,19 +50,6 @@ export type NotificationRunSummaryLogProps = {
onViewAllClick: () => void;
};
-export type SidebarSectionProps = {
- title: string;
- titleAside?: ReactNode;
- children: ReactNode;
-};
-
-export type DetailsRowProps = {
- label: ReactNode;
- value: ReactNode;
- bold?: boolean;
- spanLabel?: boolean;
-};
-
export type SidebarBodyProps = {
notification: AdminNotification;
isDetailFetching: boolean;
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
index 98003362b54..e38f8f2ebb6 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
@@ -18,6 +18,7 @@ import { PaginationControls } from "metabase/common/components/PaginationControl
import { useAbortableQuery } from "metabase/common/hooks/use-abortable-query";
import { useConfirmation } from "metabase/common/hooks/use-confirmation";
import { useUrlState } from "metabase/common/hooks/use-url-state";
+import { SIDEBAR_WIDTH } from "metabase/monitor/components/DetailSidebar";
import { MonitorHeaderTitle } from "metabase/monitor/components/MonitorHeaderTitle";
import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
import { Sidebar } from "metabase/monitor/components/MonitorLayout/Sidebar";
@@ -30,7 +31,6 @@ import type { NotificationId, UserId } from "metabase-types/api";
import { ChangeOwnerModal } from "../ChangeOwnerModal";
import { NotificationDetailSidebar } from "../NotificationDetailSidebar";
-import { SIDEBAR_WIDTH } from "../NotificationDetailSidebar/constants";
import { NotificationsFilters } from "../NotificationsFilters";
import { NotificationsTable } from "../NotificationsTable";
import { NotificationsTabs } from "../NotificationsTabs";
diff --git a/frontend/src/metabase/plugins/oss/monitor.ts b/frontend/src/metabase/plugins/oss/monitor.ts
index eea2cec67e8..e6195932c32 100644
--- a/frontend/src/metabase/plugins/oss/monitor.ts
+++ b/frontend/src/metabase/plugins/oss/monitor.ts
@@ -5,11 +5,15 @@ import { definePluginSlot } from "../slot";
type MonitorPlugin = {
isDependencyDiagnosticsEnabled: boolean;
getDependencyDiagnosticsRoutes: () => ReactNode;
+ isSessionManagementEnabled: boolean;
+ getSessionManagementRoutes: () => ReactNode;
};
const getDefaultPluginMonitor = (): MonitorPlugin => ({
isDependencyDiagnosticsEnabled: false,
getDependencyDiagnosticsRoutes: () => null,
+ isSessionManagementEnabled: false,
+ getSessionManagementRoutes: () => null,
});
export const PLUGIN_MONITOR = definePluginSlot(getDefaultPluginMonitor);
diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.unit.spec.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.unit.spec.tsx
index a2a96ed090a..3fb64963646 100644
--- a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.unit.spec.tsx
+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTable.unit.spec.tsx
@@ -1,9 +1,12 @@
+import type { Row, RowSelectionState } from "@tanstack/react-table";
import userEvent from "@testing-library/user-event";
+import { useCallback, useState } from "react";
import {
mockGetBoundingClientRect,
renderWithProviders,
screen,
+ within,
} from "__support__/ui";
import { TreeTable } from "./TreeTable";
@@ -60,6 +63,42 @@ function setup({
renderWithProviders(<Container />);
}
+const getNodeId = (node: TestNode) => node.id;
+
+const getRowProps = (row: Row<TestNode>) => ({
+ "data-testid": `row-${row.original.id}`,
+});
+
+function setupSelection() {
+ mockGetBoundingClientRect({ width: 200, height: 40 });
+
+ function SelectionContainer() {
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
+ const handleRowClick = useCallback(() => {}, []);
+ const instance = useTreeTableInstance<TestNode>({
+ data: DATA,
+ columns: SORTABLE_COLUMNS,
+ getNodeId,
+ enableRowSelection: true,
+ rowSelection,
+ onRowSelectionChange: setRowSelection,
+ });
+
+ return (
+ <TreeTable
+ instance={instance}
+ hierarchical={false}
+ showCheckboxes
+ ariaLabel="Test table"
+ onRowClick={handleRowClick}
+ getRowProps={getRowProps}
+ />
+ );
+ }
+
+ renderWithProviders(<SelectionContainer />);
+}
+
describe("TreeTable keyboard interaction", () => {
it("does not activate a previously keyboard-focused row when Enter sorts a column header", async () => {
const onRowActivate = jest.fn();
@@ -77,3 +116,18 @@ describe("TreeTable keyboard interaction", () => {
expect(onRowActivate).not.toHaveBeenCalled();
});
});
+
+describe("TreeTable row selection", () => {
+ // Every other prop the memoized row receives is stable here, so only the selection change itself can update it
+ it("checks a row's checkbox when the row is selected", async () => {
+ setupSelection();
+
+ const row = await screen.findByTestId("row-1");
+ await userEvent.click(within(row).getByRole("checkbox"));
+
+ expect(within(row).getByRole("checkbox")).toBeChecked();
+ expect(
+ within(screen.getByTestId("row-2")).getByRole("checkbox"),
+ ).not.toBeChecked();
+ });
+});
diff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.tsx
index 7b958cea1a2..5e6eb21a433 100644
--- a/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.tsx
+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/TreeTableRow/TreeTableRow.tsx
@@ -41,7 +41,8 @@ interface TreeTableRowContentProps<
isLoading?: boolean;
isExpanded: boolean;
canExpand: boolean;
- getSelectionState?: (row: Row<TData>) => SelectionState;
+ selectionState: SelectionState;
+ isCheckboxDisabled: boolean;
onCheckboxClick?: (row: Row<TData>, index: number, event: MouseEvent) => void;
onRowClick?: (row: Row<TData>, event: MouseEvent) => void;
onRowDoubleClick?: (row: Row<TData>, event: MouseEvent) => void;
@@ -50,6 +51,19 @@ interface TreeTableRowContentProps<
isClickable?: boolean;
}
+function getRowSelectionState<TData extends TreeNodeData>(
+ row: Row<TData>,
+ getSelectionState?: (row: Row<TData>) => SelectionState,
+): SelectionState {
+ if (getSelectionState) {
+ return getSelectionState(row);
+ }
+ if (row.getIsSelected()) {
+ return "all";
+ }
+ return row.getIsSomeSelected() ? "some" : "none";
+}
+
// Memoized component that does not depend on virtualItem for performance reasons
const TreeTableRowContent = memo(function TreeTableRowContent<
TData extends TreeNodeData,
@@ -68,7 +82,8 @@ const TreeTableRowContent = memo(function TreeTableRowContent<
isLoading,
isExpanded,
canExpand,
- getSelectionState,
+ selectionState,
+ isCheckboxDisabled,
onCheckboxClick,
onRowClick,
onRowDoubleClick,
@@ -84,17 +99,6 @@ const TreeTableRowContent = memo(function TreeTableRowContent<
const indent = row.depth * indentWidth;
const visibleCells = row.getVisibleCells();
- const selectionState = getSelectionState
- ? getSelectionState(row)
- : row.getIsSelected()
- ? "all"
- : row.getIsSomeSelected()
- ? "some"
- : "none";
-
- const isCheckboxDisabled =
- isDisabled || (!getSelectionState && !row.getCanSelect());
-
const handleCheckboxToggle = (event: MouseEvent) => {
event.stopPropagation();
if (isLoading || isCheckboxDisabled) {
@@ -256,6 +260,12 @@ export function TreeTableRow<TData extends TreeNodeData>({
}: TreeTableRowProps<TData>) {
const rowProps = useMemo(() => getRowProps?.(row), [getRowProps, row]);
+ // Selection is read outside the memoized content: a row keeps its identity when only its selection changes
+ const selectionState = getRowSelectionState(row, getSelectionState);
+ const isCheckboxDisabled = Boolean(
+ isDisabled || (!getSelectionState && !row.getCanSelect()),
+ );
+
const content = (
<TreeTableRowContent
row={row}
@@ -272,7 +282,8 @@ export function TreeTableRow<TData extends TreeNodeData>({
isLoading={isLoading}
isExpanded={isExpanded}
canExpand={canExpand}
- getSelectionState={getSelectionState}
+ selectionState={selectionState}
+ isCheckboxDisabled={isCheckboxDisabled}
onCheckboxClick={onCheckboxClick}
onRowClick={onRowClick}
onRowDoubleClick={onRowDoubleClick}
diff --git a/frontend/src/metabase/urls/monitor.ts b/frontend/src/metabase/urls/monitor.ts
index 62687e0c928..4bb2e97fdd2 100644
--- a/frontend/src/metabase/urls/monitor.ts
+++ b/frontend/src/metabase/urls/monitor.ts
@@ -90,6 +90,14 @@ export function monitorNotificationDetail(id: number) {
return `${monitorNotifications()}/${id}`;
}
+export function monitorSessions() {
+ return `${ROOT_URL}/sessions`;
+}
+
+export function monitorSessionDetail(sessionId: string) {
+ return `${monitorSessions()}/${sessionId}`;
+}
+
export function monitorAiAuditing() {
return `${ROOT_URL}/ai-auditing`;
}
diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.ts
index 8d430bd69ba..6a0ec45daf8 100644
--- a/frontend/test/__support__/server-mocks/index.ts
+++ b/frontend/test/__support__/server-mocks/index.ts
@@ -49,6 +49,7 @@ export * from "./revision";
export * from "./search";
export * from "./segment";
export * from "./session";
+export * from "./session-management";
export * from "./settings";
export * from "./setup";
export * from "./slack";
diff --git a/frontend/test/__support__/server-mocks/session-management.ts b/frontend/test/__support__/server-mocks/session-management.ts
new file mode 100644
index 00000000000..772ad5ed234
--- /dev/null
+++ b/frontend/test/__support__/server-mocks/session-management.ts
@@ -0,0 +1,42 @@
+import fetchMock from "fetch-mock";
+
+import type {
+ RevokeSessionsResponse,
+ Session,
+ SessionListResponse,
+} from "metabase-types/api";
+import { createMockRevokeSessionsResponse } from "metabase-types/api/mocks";
+
+export const setupListSessionsEndpoint = (
+ sessions: Session[] = [],
+ overrides: Partial<SessionListResponse> = {},
+) => {
+ const response: SessionListResponse = {
+ data: sessions,
+ total: sessions.length,
+ limit: null,
+ offset: null,
+ ...overrides,
+ };
+ fetchMock.get("path:/api/ee/session-management", response);
+};
+
+export const setupListSessionsErrorEndpoint = () => {
+ fetchMock.get("path:/api/ee/session-management", { status: 500 });
+};
+
+export const setupRevokeSessionsEndpoint = (
+ response: RevokeSessionsResponse = createMockRevokeSessionsResponse(),
+) => {
+ fetchMock.post("path:/api/ee/session-management/revoke", response);
+};
+
+export const setupRevokeSessionsErrorEndpoint = ({
+ status = 500,
+ message,
+}: { status?: number; message?: string } = {}) => {
+ fetchMock.post("path:/api/ee/session-management/revoke", {
+ status,
+ body: message === undefined ? undefined : { message },
+ });
+};
diff --git a/resources/migrations/065/20260917_session_end_tracking.yaml b/resources/migrations/065/20260917_session_end_tracking.yaml
new file mode 100644
index 00000000000..da8b4299eeb
--- /dev/null
+++ b/resources/migrations/065/20260917_session_end_tracking.yaml
@@ -0,0 +1,97 @@
+## Keeps an ended session on record instead of deleting it: when it ended, why, and who ended it.
+##
+## Ending a session clears its key_hashed, so that column becomes nullable. The rollback deletes the
+## ended sessions before restoring NOT NULL, since a pre-65 instance has no concept of them and would
+## have deleted those rows outright.
+
+databaseChangeLog:
+ - changeSet:
+ id: v65.2026-09-17T12:54:19
+ author: johnswanson
+ comment: Add ended_at to core_session
+ changes:
+ - addColumn:
+ tableName: core_session
+ columns:
+ - column:
+ name: ended_at
+ type: ${timestamp_type}
+ remarks: When the session ended (revoked, expired, timed out, or its user or tenant deactivated); null while live
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: core_session
+ columnName: ended_at
+
+ - changeSet:
+ id: v65.2026-09-17T12:54:20
+ author: johnswanson
+ comment: Add end_reason to core_session
+ changes:
+ - addColumn:
+ tableName: core_session
+ columns:
+ - column:
+ name: end_reason
+ type: varchar(32)
+ remarks: Why the session ended, e.g. admin, logout, password-change, expired; null while live
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: core_session
+ columnName: end_reason
+
+ - changeSet:
+ id: v65.2026-09-17T12:54:21
+ author: johnswanson
+ comment: Add ended_by_user_id to core_session
+ changes:
+ - addColumn:
+ tableName: core_session
+ columns:
+ - column:
+ name: ended_by_user_id
+ type: int
+ remarks: The user who ended the session, when a person did
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: core_session
+ columnName: ended_by_user_id
+
+ - changeSet:
+ id: v65.2026-09-17T12:54:22
+ author: johnswanson
+ comment: FK core_session.ended_by_user_id -> core_user.id, cleared when that user is deleted
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: core_session
+ baseColumnNames: ended_by_user_id
+ referencedTableName: core_user
+ referencedColumnNames: id
+ constraintName: fk_core_session_ended_by_user_id
+ onDelete: SET NULL
+ rollback:
+ - dropForeignKeyConstraint:
+ baseTableName: core_session
+ constraintName: fk_core_session_ended_by_user_id
+
+ - changeSet:
+ id: v65.2026-09-17T12:54:23
+ author: johnswanson
+ comment: Make core_session.key_hashed nullable, since ending a session clears its key
+ changes:
+ - dropNotNullConstraint:
+ tableName: core_session
+ columnName: key_hashed
+ columnDataType: varchar(254)
+ rollback:
+ - sql:
+ sql: DELETE FROM core_session WHERE key_hashed IS NULL;
+ - addNotNullConstraint:
+ tableName: core_session
+ columnName: key_hashed
+ columnDataType: varchar(254)
diff --git a/src/metabase/audit_app/events/audit_log.clj b/src/metabase/audit_app/events/audit_log.clj
index c3dcc407225..35448606cb6 100644
--- a/src/metabase/audit_app/events/audit_log.clj
+++ b/src/metabase/audit_app/events/audit_log.clj
@@ -191,6 +191,16 @@
[topic event]
(audit-log/record-event! topic event))
+;; session events
+
+(events/derive! ::session-event ::event)
+(events/derive! :event/session-revoked ::session-event)
+(events/derive! :event/sessions-revoked ::session-event)
+
+(methodical/defmethod events/publish-event! ::session-event
+ [topic event]
+ (audit-log/record-event! topic event))
+
(events/derive! ::user-update-event ::event)
(events/derive! :event/user-update ::user-update-event)
diff --git a/src/metabase/auth_identity/db.clj b/src/metabase/auth_identity/db.clj
index a50db1ed101..5fbeee54bfc 100644
--- a/src/metabase/auth_identity/db.clj
+++ b/src/metabase/auth_identity/db.clj
@@ -69,12 +69,18 @@
provider :- :string]
(t2/delete! :model/AuthIdentity :user_id (long user-id) :provider [:auto/param provider]))
-(mu/defn delete-sessions-for-user!
- "Delete every Session of the User with `user-id`, returning the number deleted. Duplicates
- `metabase.session.db/delete-sessions-for-user!`; can't delegate to it because the `session` module already depends
- on `auth-identity`, so the reverse dependency would be a module cycle."
- [user-id :- ::lib.schema.id/user]
- (t2/delete! :model/Session :user_id (long user-id)))
+(mu/defn end-sessions-for-user!
+ "Record that every Session of the User with `user-id` ended because their password changed, clearing each key so
+ none can authenticate again; `ended-by` is who changed it. Returns the number ended."
+ [user-id :- ::lib.schema.id/user
+ ended-by :- [:maybe ::lib.schema.id/user]]
+ ;; the same write `metabase.session.db/end-sessions!` makes, repeated here rather than delegated: the `session`
+ ;; module already depends on `auth-identity`, so the reverse dependency would be a module cycle
+ (t2/update! :model/Session :user_id (long user-id) :ended_at nil
+ {:ended_at :%now
+ :end_reason "password-change"
+ :ended_by_user_id ended-by
+ :key_hashed nil}))
(mu/defn user
"The User with `user-id`, or nil."
diff --git a/src/metabase/auth_identity/models/auth_identity.clj b/src/metabase/auth_identity/models/auth_identity.clj
index d65e50d995c..35ac3aff61b 100644
--- a/src/metabase/auth_identity/models/auth_identity.clj
+++ b/src/metabase/auth_identity/models/auth_identity.clj
@@ -95,7 +95,7 @@
authoritative credential store. This is the only supported way to set a user's password; the User model itself no
longer stores, hashes, or mirrors passwords.
- Always deletes the user's existing sessions: changing a password must invalidate every session authenticated with the
+ Always ends the user's existing sessions: changing a password must invalidate every session authenticated with the
old one. A caller that wants the acting user to stay logged in should create a fresh session afterward.
Also deletes the user's `emailed-secret-password-reset` AuthIdentity: this is called by the password-reset flow, so
@@ -103,7 +103,8 @@
password again until it expires.
`opts` may contain `:expires-at`, an instant after which the credential is no longer valid (used by time-limited
- support-access grants)."
+ support-access grants), and `:ended-by`, the id of the person changing the password, recorded on each session it
+ ends."
([user-id :- ms/PositiveInt
password :- ms/NonBlankString]
(set-password! user-id password nil))
@@ -112,10 +113,11 @@
password :- ms/NonBlankString
opts :- [:maybe
[:map {:closed true}
- [:expires-at {:optional true} [:maybe (ms/InstanceOfClass java.time.temporal.Temporal)]]]]]
+ [:expires-at {:optional true} [:maybe (ms/InstanceOfClass java.time.temporal.Temporal)]]
+ [:ended-by {:optional true} [:maybe ms/PositiveInt]]]]]
;; always write :expires_at (nil unless an expiry was requested) so setting a password clears any stale expiry a
;; prior support-access grant left behind — otherwise `authenticate` would reject the new password as expired
- ;; the credential write and the session delete must be atomic: if either fails the password must not change while
+ ;; the credential write and the session ending must be atomic: if either fails the password must not change while
;; sessions authenticated with the old one survive
(t2/with-transaction [_]
(let [attrs {:credentials {:plaintext_password password}
@@ -124,7 +126,7 @@
(auth-identity.db/update-auth-identity! (u/the-id pw-auth-identity) attrs)
(auth-identity.db/insert-auth-identity! (merge {:user_id user-id, :provider "password"} attrs))))
(auth-identity.db/delete-auth-identities! user-id "emailed-secret-password-reset")
- (auth-identity.db/delete-sessions-for-user! user-id))))
+ (auth-identity.db/end-sessions-for-user! user-id (:ended-by opts)))))
(mu/defn reset-token-hash :- [:maybe :string]
"The bcrypt hash of `user-id`'s current password-reset token, taken from their `emailed-secret-password-reset`
diff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.clj
index 12097a9e8d7..dfe437147ec 100644
--- a/src/metabase/auth_identity/provider.clj
+++ b/src/metabase/auth_identity/provider.clj
@@ -300,6 +300,10 @@
[:redirect-uri {:optional true} [:maybe :string]]
[:redirect-url {:optional true} [:maybe :string]]
[:saml-data {:optional true} [:maybe ms/SAMLAttributes]]
+ [:scheme {:optional true} [:maybe :keyword]]
+ [:server-name {:optional true} [:maybe :string]]
+ [:server-port {:optional true} [:maybe :int]]
+ [:session/provider {:optional true} [:maybe :keyword]]
[:slack-data {:optional true} [:maybe [:map-of :string :string]]]
[:state {:optional true} [:maybe :string]]
[:success? {:optional true} [:maybe [:or :boolean [:enum :redirect]]]]
@@ -329,8 +333,8 @@
:message disabled-account-message)))
(mu/defn- create-session!
- "Create a new session for a user with the given provider.
- Updates the last_used_at timestamp on the corresponding AuthIdentity."
+ "Create a new session for a user, attributed to the AuthIdentity of `(:session/provider request)` when a `login!`
+ method set one, otherwise to that of `provider`. Updates the last_used_at timestamp on that AuthIdentity."
[request :- [:merge
::request.schema/request
(into [:map {:closed true}
@@ -343,7 +347,7 @@
:message disabled-account-message)
(let [{:keys [user device-info saml-data]} request
session (auth-session/create-session-with-auth-tracking!
- user device-info provider nil
+ user device-info (or (:session/provider request) provider) nil
;; SAML logins carry the IdP's own identifiers; single logout needs them to
;; name the session and subject to end. Other providers have none and store NULL.
{:saml-session-index (:session-index saml-data)
@@ -376,12 +380,16 @@
[_provider login-result]
login-result)
+;; Keys the login pipeline produces itself, stripped off the incoming request before anything runs. A caller must not
+;; be able to hand itself a user-id, a session, or — via :session/provider — the AuthIdentity its session is
+;; attributed to.
+;;
;; TODO: (bshepherdson, 2026-09-04) Only a sharp-eyed code reviewer caught that `:mfa/enroll?` had been introduced
;; but not added to this blocklist. The consumers of [[authenticate-owned-keys]] should be switched to an allowlist
;; using `select-keys`, rather than `dissoc`ing all the bad fields.
(def ^:private authenticate-owned-keys
[:user-id :user_id :user :user-data :auth-identity :provider-id :success? :session
- :error :message :mfa/enroll? :mfa/pending? :mfa/methods :mfa/first-factor
+ :error :message :mfa/enroll? :mfa/pending? :mfa/methods :mfa/first-factor :session/provider
:jwt-data :claims
:tenant-slug :tenant-attributes :user-provisioning-enabled?])
diff --git a/src/metabase/auth_identity/providers/emailed_secret.clj b/src/metabase/auth_identity/providers/emailed_secret.clj
index ea3f7762618..1a592a819c3 100644
--- a/src/metabase/auth_identity/providers/emailed_secret.clj
+++ b/src/metabase/auth_identity/providers/emailed_secret.clj
@@ -185,11 +185,18 @@
After a successful password reset authentication, this method:
- Publishes a password reset event or sends admin notification (for new users)
- Updates the user's password, which also removes the now-used reset token (see
- [[metabase.auth-identity.core/set-password!]])."
+ [[metabase.auth-identity.core/set-password!]])
+ - Points the session the login is about to create at the user's `password` AuthIdentity."
[_provider {:keys [user password] :as result}]
- (when (:success? result)
- (if (:last_login user)
- (events/publish-event! :event/password-reset-successful {:object (assoc user :token (auth-identity/reset-token-hash (:id user)))})
- (messages/send-user-joined-admin-notification-email! (auth-identity.db/user (:id user))))
- (auth-identity/set-password! (:id user) password))
- result)
+ (if-not (:success? result)
+ result
+ (do
+ (if (:last_login user)
+ (events/publish-event! :event/password-reset-successful {:object (assoc user :token (auth-identity/reset-token-hash (:id user)))})
+ (messages/send-user-joined-admin-notification-email! (auth-identity.db/user (:id user))))
+ ;; the person resetting proved they own the account, so they are who ends its sessions
+ (auth-identity/set-password! (:id user) password {:ended-by (:id user)})
+ ;; The session cannot belong to the reset identity: `set-password!` has just deleted it, and its `expires_at` is
+ ;; the token's short lifetime, which has no business bounding a session. The user now holds a fresh password
+ ;; credential, so the session belongs to that. The reset itself is recorded by the event above.
+ (assoc result :session/provider :provider/password))))
diff --git a/src/metabase/events/schema.clj b/src/metabase/events/schema.clj
index d962785a73f..f61d29e57eb 100644
--- a/src/metabase/events/schema.clj
+++ b/src/metabase/events/schema.clj
@@ -139,6 +139,32 @@
(mr/def :event/action-update ::action)
(mr/def :event/action-delete ::action)
+;; session events
+
+(mr/def :event/session-revoked
+ [:map {:closed true}
+ ;; the admin who revoked, and the user whose sessions they were. `:model` is passed explicitly because the object is
+ ;; a plain map rather than a Toucan instance, so the audit log cannot derive it.
+ [:user-id pos-int?]
+ [:model [:= :model/User]]
+ [:model-id pos-int?]
+ ;; one per-user row of a revoke by criteria: the criteria and how many of that user's sessions went, which the
+ ;; `:event/sessions-revoked` summary covers
+ [:details
+ [:map {:closed true}
+ [:criteria :map]
+ [:count pos-int?]]]])
+
+(mr/def :event/sessions-revoked
+ ;; the one summary row a revoke by criteria writes. No `:model`: the call is about a set of sessions picked out by
+ ;; criteria, not about any one object.
+ [:map {:closed true}
+ [:user-id pos-int?]
+ [:details [:map {:closed true}
+ [:criteria :map]
+ [:count ms/IntGreaterThanOrEqualToZero]
+ [:remaining ms/IntGreaterThanOrEqualToZero]]]])
+
;; segment events
(mr/def ::segment
diff --git a/src/metabase/login_history/db.clj b/src/metabase/login_history/db.clj
index 6dbab0a7eb3..e00cca9f50a 100644
--- a/src/metabase/login_history/db.clj
+++ b/src/metabase/login_history/db.clj
@@ -6,18 +6,27 @@
[metabase.app-db.core :as mdb]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.login-history.schema :as login-history.schema]
+ [metabase.session.core :as session]
[metabase.util.honey-sql-2 :as h2x]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
(mu/defn login-history-for-user
- "The timestamp, session id, device description, and IP address of the LoginHistory of the User with `user-id`,
- newest first."
+ "The timestamp, device description, IP address, and `active` flag of the LoginHistory of the User with `user-id`,
+ newest first. `active` is whether the session the login created is still live — would still authenticate a
+ request — by the `session` module's own definition, so a login whose session was revoked, logged out, or expired
+ reads inactive."
[user-id :- ::lib.schema.id/user]
- (t2/select [:model/LoginHistory :timestamp :session_id :device_description :ip_address]
- :user_id user-id
- {:order-by [[:timestamp :desc]]}))
+ (t2/select :model/LoginHistory
+ {:select [:lh.timestamp :lh.device_description :lh.ip_address
+ ;; 1/0, normalised to a boolean by the model's after-select
+ [(session/live-expr (session/liveness-params)) :active]]
+ :from [[:login_history :lh]]
+ :left-join (into [[:core_session :session] [:= :session.id :lh.session_id]]
+ session/session-left-joins)
+ :where [:= :lh.user_id user-id]
+ :order-by [[:lh.timestamp :desc]]}))
(mu/defn insert-login-history!
"Insert the LoginHistory `row`, returning the number of rows inserted."
diff --git a/src/metabase/login_history/models/login_history.clj b/src/metabase/login_history/models/login_history.clj
index bc00393e41c..483a4ef12e4 100644
--- a/src/metabase/login_history/models/login_history.clj
+++ b/src/metabase/login_history/models/login_history.clj
@@ -57,11 +57,13 @@
login-history))
(t2/define-after-select :model/LoginHistory
- [{session-id :session_id, :as login-history}]
- ;; session ID is sensitive, so it's better if we don't even return it. Replace it with a more generic `active` key.
+ [{active :active, :as login-history}]
+ ;; session ID is sensitive, so it's better if we don't even return it. What callers get instead is `active`, which
+ ;; `login-history.db/login-history-for-user` computes in SQL as 1/0: whether the session the login created is
+ ;; still live.
(cond-> (t2.realize/realize login-history)
- (contains? login-history :session_id) (assoc :active (boolean session-id))
- true (dissoc :session_id)))
+ (some? active) (assoc :active (= 1 (long active)))
+ true (dissoc :session_id)))
(defn first-login-ever?
"Return true if this is the first login ever for the given user-id."
diff --git a/src/metabase/login_history/schema.clj b/src/metabase/login_history/schema.clj
index 93565609cd1..0f92a74aed3 100644
--- a/src/metabase/login_history/schema.clj
+++ b/src/metabase/login_history/schema.clj
@@ -6,7 +6,8 @@
[metabase.util.malli.schema :as ms]))
(mr/def ::login-history
- "A LoginHistory as selected from the app DB: every column of `:login_history`, plus `:active` added by the model's after-select hook."
+ "A LoginHistory as selected from the app DB: every column of `:login_history`, plus `:active` when selected by
+ [[metabase.login-history.db/login-history-for-user]]: whether the login's session is still live."
[:merge
::login-history.update
[:map {:closed true}
diff --git a/src/metabase/mcp/db.clj b/src/metabase/mcp/db.clj
index dcb03bd24e6..093a7e9f3a2 100644
--- a/src/metabase/mcp/db.clj
+++ b/src/metabase/mcp/db.clj
@@ -7,6 +7,7 @@
HoneySQL."
(:require
[metabase.app-db.core :as app-db]
+ [metabase.auth-identity.core :as auth-identity]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.mcp.schema :as mcp.schema]
[metabase.session.core :as session]
@@ -135,6 +136,10 @@
:archived (boolean archived?)
{:order-by [[:%lower.name :asc]]}))
+;; MCP is a session provider like any other as far as `auth_identity` is concerned; declaring it here is what lets
+;; the AuthIdentity model's before-insert validation accept the rows [[mcp-auth-identity-id!]] creates.
+(auth-identity/derive! :provider/mcp :metabase.auth-identity.provider/provider)
+
(mu/defn insert-feedback!
"Insert the McpFeedback `row`, returning the number inserted."
[row :- ::mcp.schema/mcp-feedback.update]
@@ -149,6 +154,18 @@
[key-hashed]
(t2/select-fn-set :user_id :core_session :key_hashed key-hashed))
+;; An AuthIdentity row rather than a new `core_session` column: `auth_identity.provider` is already the provider of
+;; record for a session, and the `(user_id, provider)` unique constraint makes one row per user the natural key —
+;; `select-or-insert!` leans on that constraint to settle a race between two concurrent MCP handshakes.
+(mu/defn- mcp-auth-identity-id! :- ms/PositiveInt
+ "The id of `user-id`'s `mcp` AuthIdentity, creating it if there isn't one. There is at most one per user."
+ [user-id :- ::lib.schema.id/user]
+ (:id (app-db/select-or-insert!
+ :model/AuthIdentity
+ {:user_id user-id
+ :provider session/mcp-provider}
+ (constantly {}))))
+
(mu/defn get-or-create-core-session!
"The `core_session` row for `key-hashed` and `user-id`, creating one with a freshly generated session id if none
exists. Uses the raw `:core_session` table (not `:model/Session`) to bypass the after-insert hook, which would
@@ -160,9 +177,12 @@
{:key_hashed key-hashed
:user_id user-id}
(fn []
- {:id (session/generate-session-id)
- :anti_csrf_token nil
- :created_at :%now})))
+ {:id (session/generate-session-id)
+ :anti_csrf_token nil
+ ;; the `mcp` provider keeps these rows out of the `/api/sessions` list and revoke endpoints, and stops the
+ ;; key from authenticating a request through the session middleware
+ :auth_identity_id (mcp-auth-identity-id! user-id)
+ :created_at :%now})))
(mu/defn insert-query-handle!
"Insert the McpQueryHandle `row` under the client-generated `handle-id`, returning the number inserted."
diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.clj
index 9d9c23f58fa..862fdd6a76f 100644
--- a/src/metabase/premium_features/core.clj
+++ b/src/metabase/premium_features/core.clj
@@ -81,6 +81,7 @@
enable-scim?
enable-semantic-search?
enable-serialization?
+ enable-session-management?
enable-session-timeout-config?
enable-snippet-collections?
enable-sso-google?
diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.clj
index 15daa264ea2..f64e13d1a1b 100644
--- a/src/metabase/premium_features/settings.clj
+++ b/src/metabase/premium_features/settings.clj
@@ -192,6 +192,10 @@
"Should we enable configuring session timeouts?"
:session-timeout-config)
+(define-premium-feature ^{:added "0.65.0"} enable-session-management?
+ "Should we enable listing and revoking users' sessions?"
+ :session-management)
+
(define-premium-feature can-disable-password-login?
"Can we disable login by password?"
:disable-password-login)
@@ -429,6 +433,7 @@
:scim (enable-scim?)
:semantic_search (enable-semantic-search?)
:serialization (enable-serialization?)
+ :session-management (enable-session-management?)
:session_timeout_config (enable-session-timeout-config?)
:snippet_collections (enable-snippet-collections?)
:sso_google (enable-sso-google?)
diff --git a/src/metabase/request/schema.clj b/src/metabase/request/schema.clj
index 5d6f9e4e713..432ba6057b6 100644
--- a/src/metabase/request/schema.clj
+++ b/src/metabase/request/schema.clj
@@ -82,6 +82,7 @@
[:is-group-manager? {:optional true} :boolean]
[:user-locale {:optional true} [:maybe :string]]
[:embedding/auth-method {:optional true} [:maybe :string]]
+ [:metabase/authed-session-key-hash {:optional true} [:maybe :string]]
[:token-exchange? {:optional true} :boolean]
[:metabase.server.middleware.offset-paging/limit {:optional true} [:maybe :int]]
[:metabase.server.middleware.offset-paging/offset {:optional true} [:maybe :int]]
diff --git a/src/metabase/server/db.clj b/src/metabase/server/db.clj
index de4305231d1..96f3b4fd82a 100644
--- a/src/metabase/server/db.clj
+++ b/src/metabase/server/db.clj
@@ -5,7 +5,7 @@
[honey.sql.helpers :as sql.helpers]
[metabase.app-db.core :as mdb]
[metabase.lib.schema.id :as lib.schema.id]
- [metabase.util.honey-sql-2 :as h2x]
+ [metabase.session.core :as session]
[metabase.util.malli :as mu]
[toucan2.core :as t2]
[toucan2.pipeline :as t2.pipeline]))
@@ -14,17 +14,6 @@
;; to optimize a bit and only compile each one to SQL once (keyed by its boolean/enum arguments) rather than every
;; time.
-(defn- oldest-allowed-expr
- "A database-specific expression for `NOW() - interval`."
- [db-type amount unit]
- (let [now (h2x/current-datetime-honeysql-form db-type)]
- (case db-type
- :postgres [:- now [::h2x/postgres-interval amount unit]]
- :h2 [:dateadd (h2x/literal (name unit))
- [:inline (- amount)]
- now]
- :mysql [:- now [::h2x/mysql-interval amount unit]])))
-
;; Hard-coded rather than `(descendants :metabase.auth-identity.provider/supports-mfa)` so the session query below is
;; compiled once rather than depending on load order of the provider namespaces.
;; [[metabase.server.middleware.session-test/mfa-providers-list-test]] keeps this in sync with the hierarchy.
@@ -36,41 +25,33 @@
(fn [db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds mfa-required]
(first
(t2.pipeline/compile*
- (cond-> {:select [[:session.user_id :metabase-user-id]
- [:user.is_superuser :is-superuser?]
- [:user.is_data_analyst :is-data-analyst?]
- [:user.locale :user-locale]
- [:auth_identity.provider :auth-provider]]
- :from [[:core_session :session]]
- :left-join [[:core_user :user] [:= :session.user_id :user.id]
- [:tenant] [:= :tenant.id :user.tenant_id]
- [:auth_identity] [:= :auth_identity.id :session.auth_identity_id]]
- :where (into [:and
- (if enable-tenants?
- [:or [:= :tenant.id nil] :tenant.is_active]
- [:= :tenant.id nil])
- [:= :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 "?"])]]
- cat
- [(when mfa-required
- [[:or
- [:not= :session.mfa_auth_identity_id nil]
- (into [:and]
- (map (fn [mfa-supporting-provider]
- [:not= :auth_identity.provider
- ^:allow-raw-sql
- [:raw (str "'" (name mfa-supporting-provider) "'")]])
- mfa-supported-methods))]])
- (when session-timeout-seconds
- [[:> [:coalesce :session.last_active_at :session.created_at]
- (oldest-allowed-expr db-type session-timeout-seconds :second)]])])
- :limit [:inline 1]}
+ (cond-> (merge session/session-from-and-joins
+ {:select [[:session.user_id :metabase-user-id]
+ [:user.is_superuser :is-superuser?]
+ [:user.is_data_analyst :is-data-analyst?]
+ [:user.locale :user-locale]
+ [:auth_identity.provider :auth-provider]]
+ :where (into [:and
+ [:= :session.key_hashed ^:allow-raw-sql [:raw "?"]]
+ [:= :session.anti_csrf_token (case session-type
+ :normal nil
+ :full-app-embed ^:allow-raw-sql [:raw "?"])]]
+ cat
+ [(session/live-session-conditions
+ {:db-type db-type
+ :max-age-minutes max-age-minutes
+ :enable-tenants? enable-tenants?
+ :session-timeout-seconds session-timeout-seconds})
+ (when mfa-required
+ [[:or
+ [:not= :session.mfa_auth_identity_id nil]
+ (into [:and]
+ (map (fn [mfa-supporting-provider]
+ [:not= :auth_identity.provider
+ ^:allow-raw-sql
+ [:raw (str "'" (name mfa-supporting-provider) "'")]])
+ mfa-supported-methods))]])])
+ :limit [:inline 1]})
enable-advanced-permissions?
(->
(sql.helpers/select
diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.clj
index 1bd4629409f..7a4c6050326 100644
--- a/src/metabase/server/middleware/session.clj
+++ b/src/metabase/server/middleware/session.clj
@@ -101,21 +101,28 @@
[session-key]
(or (not session-key) (string/valid-uuid? session-key)))
-(mu/defn- current-user-info-for-session :- [:maybe ::request.schema/current-user-info]
- "Return User ID and superuser status for Session with `session-key` if it is valid and not expired."
+(mu/defn- current-user-info-for-session :- [:maybe [:merge
+ ::request.schema/current-user-info
+ [:map {:closed true}
+ [:session-key-hash :string]]]]
+ "Return User ID and superuser status for Session with `session-key` if it is valid and not expired, plus
+ `:session-key-hash`, the `key_hashed` value the row was matched on."
[session-key :- [:maybe :string]
anti-csrf-token :- [:maybe :string]]
(when (and session-key (valid-session-key? session-key) (init-status/complete?))
- (some-> (server.db/session-user-info (session/hash-session-key session-key)
- anti-csrf-token
- (config/config-int :max-session-age)
- (premium-features/enable-advanced-permissions?)
- (and (premium-features/enable-tenants?)
- (setting/get :use-tenants))
- (request/enabled-session-timeout-seconds)
- (session/mfa-required?))
- ;; is-group-manager? could return `nil, convert it to boolean so it's guaranteed to be only true/false
- (update :is-group-manager? boolean))))
+ (let [session-key-hash (session/hash-session-key session-key)]
+ (some-> (server.db/session-user-info session-key-hash
+ anti-csrf-token
+ (config/config-int :max-session-age)
+ (premium-features/enable-advanced-permissions?)
+ (and (premium-features/enable-tenants?)
+ (setting/get :use-tenants))
+ (request/enabled-session-timeout-seconds)
+ (session/mfa-required?))
+ ;; is-group-manager? could return `nil, convert it to boolean so it's guaranteed to be only true/false
+ (update :is-group-manager? boolean)
+ ;; so that whatever refers to this session later can do so by the hash without handling the key again
+ (assoc :session-key-hash session-key-hash)))))
(def ^:private api-key-that-should-never-match (str (random-uuid)))
(def ^:private hash-that-should-never-match (u.password/hash-bcrypt "password"))
@@ -276,7 +283,14 @@
request
;; oauth-info carries `:token-scopes` in addition to the standard current-user-info keys, so
;; merging it whole both authenticates the request and records the granted scopes.
- (dissoc (or session-info api-key-info oauth-info mcp-ui-info) :auth-provider)
+ (dissoc (or session-info api-key-info oauth-info mcp-ui-info) :auth-provider :session-key-hash)
+ ;; `:metabase-session-key` is attached by [[wrap-session-key]] from an unvalidated cookie or header, so its
+ ;; presence says nothing about whether the session is the credential that authenticated this request.
+ ;; `:metabase/authed-session-key-hash` identifies the session that did, and being namespaced it cannot arrive
+ ;; from anywhere a request has been: Ring keys are unqualified, so only this function can set it. It carries the
+ ;; `key_hashed` value rather than the key itself, since that is all anything downstream needs and the key is
+ ;; the credential.
+ (when session-info {:metabase/authed-session-key-hash (:session-key-hash session-info)})
(when auth-method {:embedding/auth-method auth-method})
(when x-metabase-locale
(log/tracef "Found X-Metabase-Locale header: using %s as user locale" (pr-str x-metabase-locale))
@@ -287,7 +301,10 @@
token, API key, OAuth bearer access token, OR MCP UI credential was passed. A bearer token additionally sets
`:token-scopes` (the access it was granted); precedence is session > API key > bearer > MCP UI credential.
Bearer tokens and MCP UI credentials authenticate only when `options` supplies their `:oauth-bearer` and
- `:mcp-ui-credentials` fns."
+ `:mcp-ui-credentials` fns.
+
+ `:metabase/authed-session-key-hash` is set only when it was the session that authenticated the request, and carries
+ the `key_hashed` value of the one that did."
([handler]
(wrap-current-user-info handler nil))
([handler options]
@@ -327,16 +344,14 @@
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- maybe-update-session-activity!
- "Update the `last_active_at` column for the session identified by `session-key`, throttled to avoid a DB write on
- every request. Uses raw SQL to bypass the Session model's no-update restriction."
- [session-key]
- (when (request/enabled-session-timeout-seconds)
- (let [hashed (session/hash-session-key session-key)]
- (when (session/record-session-activity-update! hashed)
- (try
- (server.db/touch-session! hashed)
- (catch Exception e
- (log/warnf "Failed to update session last_active_at: %s" (ex-message e))))))))
+ "Update the `last_active_at` column for the session whose `key_hashed` is `session-key-hash`, throttled to avoid a
+ DB write on every request."
+ [session-key-hash]
+ (when (session/record-session-activity-update! session-key-hash)
+ (try
+ (server.db/touch-session! session-key-hash)
+ (catch Exception e
+ (log/warnf "Failed to update session last_active_at: %s" (ex-message e))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | reset-cookie-timeout |
@@ -354,8 +369,9 @@
response))
(defn reset-session-timeout
- "Middleware that resets the expiry date on session cookies according to the session-timeout setting.
- Will not change anything if the session-timeout setting is nil, or the timeout cookie has already expired."
+ "Middleware that records session activity on every session-authenticated request, and additionally resets the expiry
+ date on session cookies when the session-timeout setting is set. The cookie is left alone if that setting is nil or
+ the timeout cookie has already expired."
[handler]
(fn [request respond raise]
(let [;; The expiry time for the cookie is relative to the time the request is received, rather than the time of the
@@ -363,9 +379,7 @@
request-time (t/zoned-date-time (t/zone-id "GMT"))]
(handler request
(fn [response]
- ;; Update last_active_at for server-side timeout enforcement
- (when-let [session-key (:metabase-session-key request)]
- (when (:metabase-user-id request)
- (maybe-update-session-activity! session-key)))
+ (when-let [session-key-hash (:metabase/authed-session-key-hash request)]
+ (maybe-update-session-activity! session-key-hash))
(respond (reset-session-timeout* request response request-time)))
raise))))
diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.clj
index 1d7f2718f71..54c45ea21a3 100644
--- a/src/metabase/session/api.clj
+++ b/src/metabase/session/api.clj
@@ -288,11 +288,11 @@
[_route-params _query-params _body {:keys [metabase-session-key], :as _request}]
(api/check-404 (not-empty metabase-session-key))
(let [session-key-hashed (session/hash-session-key metabase-session-key)
- rows-deleted (session.db/delete-session-by-key-hashed! session-key-hashed)]
+ rows-ended (session.db/end-sessions! {:key_hashed session-key-hashed} "logout" :self)]
;; clear the cookie even when no row matched (e.g. a session hashed under a previous secret), or the browser
;; would keep resending the dead cookie
(request/clear-session-cookie
- (if (pos? rows-deleted)
+ (if (pos? rows-ended)
api/generic-204-no-content
{:status 404, :body "Not found."}))))
@@ -413,10 +413,22 @@
request]
(let [request-source (request/ip-address request)]
(throttle-check reset-password-throttler request-source))
- (let [auth-result (auth-identity/with-fallback auth-identity/login!
- [:provider/support-access-grant
- :provider/emailed-secret-password-reset]
- (select-keys request-body [:token :password]))]
+ (let [credentials (select-keys request-body [:token :password])
+ grant-result (auth-identity/with-fallback auth-identity/login!
+ [:provider/support-access-grant]
+ credentials)
+ ;; Refuse before the reset's `login!` runs, so nothing mutates. A reset ends in a password
+ ;; session, which `:model/Session`'s before-insert rejects while password login is off — but by
+ ;; then the password has been changed, the token consumed and every session revoked, and
+ ;; `with-fallback` would report the failure as an invalid token. Such a user is sent to
+ ;; /auth/login to use their SSO provider.
+ _ (when-not (or (:success? grant-result) (session.settings/enable-password-login))
+ (throw (ex-info (tru "Password login is disabled for this instance.") {:status-code 400})))
+ auth-result (if (:success? grant-result)
+ grant-result
+ (auth-identity/with-fallback auth-identity/login!
+ [:provider/emailed-secret-password-reset]
+ credentials))]
(cond
(not (:success? auth-result))
(api/throw-invalid-param-exception :password (tru "Invalid reset token"))
diff --git a/src/metabase/session/core.clj b/src/metabase/session/core.clj
index af4e0dd3124..2226187ccb4 100644
--- a/src/metabase/session/core.clj
+++ b/src/metabase/session/core.clj
@@ -1,16 +1,31 @@
(ns metabase.session.core
(:require
+ [metabase.session.db]
[metabase.session.models.session]
+ [metabase.session.query]
[metabase.session.settings]
[metabase.util :as u]
[potemkin :as p]))
(set! *warn-on-reflection* true)
-(comment metabase.session.models.session/keep-me
+(comment metabase.session.db/keep-me
+ metabase.session.models.session/keep-me
+ metabase.session.query/keep-me
metabase.session.settings/keep-me)
(p/import-vars
+ [metabase.session.db
+ end-sessions!
+ end-sessions-by-ids!]
+ [metabase.session.query
+ live-expr
+ live-session-conditions
+ liveness-params
+ mcp-provider
+ not-mcp-session
+ session-from-and-joins
+ session-left-joins]
[metabase.session.models.session
generate-session-key
generate-session-id
diff --git a/src/metabase/session/db.clj b/src/metabase/session/db.clj
index 84538285e49..cb843c04571 100644
--- a/src/metabase/session/db.clj
+++ b/src/metabase/session/db.clj
@@ -1,11 +1,13 @@
(ns metabase.session.db
- "Application database queries for the session module. Every function here is a direct Toucan 2 call with no
- additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."
+ "Application database queries for the session module, so that no other namespace in the module runs a query itself
+ (model definitions still use `toucan2.core`)."
(:require
[metabase.app-db.core :as mdb]
[metabase.auth-identity.db :as auth-identity.db]
[metabase.auth-identity.schema :as auth-identity.schema]
[metabase.lib.schema.id :as lib.schema.id]
+ [metabase.session.query :as session.query]
+ [metabase.session.schema :as session.schema]
[metabase.tracing.core :as tracing]
[metabase.util :as u]
[metabase.util.honey-sql-2 :as h2x]
@@ -13,19 +15,96 @@
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
-(mu/defn delete-session-by-key-hashed!
- "Delete the Session with `key-hashed`, returning the number of rows deleted."
- [key-hashed :- :string]
- (t2/delete! :model/Session :key_hashed key-hashed))
+(def ended-session-retention-days
+ "How long an ended session stays on record before [[delete-sessions-ended-long-ago!]] removes its row."
+ ;; a constant rather than a setting, and deliberately not `audit-max-retention-days`: that defaults to two years,
+ ;; and the audit tables are a different concern
+ 30)
-(mu/defn delete-sessions-for-user!
- "Delete every Session of the User with `user-id`."
- [user-id :- ::lib.schema.id/user]
- (t2/delete! :model/Session :user_id user-id))
+(def default-end-batch-size
+ "How many ids one `UPDATE ... WHERE id IN (...)` may name. Ending sessions by id has no upper bound on how many
+ there are, and every id is a bind parameter — pgjdbc refuses a statement with more than 65,535 of them."
+ 1000)
+
+(mu/defn end-sessions! :- ms/IntGreaterThanOrEqualToZero
+ "Record that every Session matching `conditions` (see `::session.schema/end-conditions`) has ended: `ended_at`
+ becomes now, `end_reason` becomes `reason`, `ended_by_user_id` becomes `ended-by`, and `key_hashed` is cleared so
+ the row can never authenticate a request again. A session that has already ended is left as it was. Returns the
+ number of sessions ended. See `::session.schema/ended-by` for `ended-by`."
+ [conditions :- ::session.schema/end-conditions
+ reason :- ::session.schema/end-reason
+ ended-by :- ::session.schema/ended-by]
+ ;; an explicitly empty id list matches nothing; `IN ()` is not valid SQL anywhere
+ (if (and (contains? conditions :id) (empty? (:id conditions)))
+ 0
+ (t2/update! :model/Session
+ (cond-> (assoc conditions :ended_at nil)
+ (:id conditions) (update :id (fn [ids] [:in ids])))
+ {:ended_at :%now
+ :end_reason reason
+ ;; a bare keyword is a column reference, so `:self` writes the row's own `user_id`
+ :ended_by_user_id (if (= ended-by :self) :user_id ended-by)
+ :key_hashed nil})))
+
+(mu/defn end-sessions-by-ids! :- ms/IntGreaterThanOrEqualToZero
+ "[[end-sessions!]] for the Sessions with `ids`, in batches of `batch-size` ids ([[default-end-batch-size]] by
+ default), returning the total number ended. An empty `ids` ends nothing."
+ ([ids :- [:sequential :string]
+ reason :- ::session.schema/end-reason
+ ended-by :- ::session.schema/ended-by]
+ (end-sessions-by-ids! ids reason ended-by default-end-batch-size))
+
+ ([ids :- [:sequential :string]
+ reason :- ::session.schema/end-reason
+ ended-by :- ::session.schema/ended-by
+ batch-size :- ms/PositiveInt]
+ (transduce (map (fn [batch] (end-sessions! {:id batch} reason ended-by)))
+ +
+ 0
+ (partition-all batch-size ids))))
+
+(mu/defn sessions-with-unrecorded-ending :- [:sequential [:map {:closed true}
+ [:id :string]
+ [:reason ::session.schema/end-reason]]]
+ "The id of every session that is no longer live but has no `ended_at` yet, with the reason the nightly sweep should
+ record: the user's or tenant's deactivation first, then expiry (its own `expires_at` or `max-session-age`), then
+ the idle timeout. MCP-backed rows are not sessions and are never included."
+ [liveness :- ::session.schema/liveness-params]
+ (let [predicates (session.query/liveness-predicates liveness)
+ ;; a not-live row fails at least one of these, so the CASE always resolves; `:else` names the last one
+ reason-expr (cond-> [:case
+ [:not (:user-active predicates)] (h2x/literal "user-deactivated")
+ [:not (:tenant-active predicates)] (h2x/literal "tenant-deactivated")]
+ (:not-timed-out predicates)
+ (conj [:not (:not-expired predicates)] (h2x/literal "expired")
+ :else (h2x/literal "timed-out"))
+
+ (not (:not-timed-out predicates))
+ (conj :else (h2x/literal "expired")))]
+ (t2/query (merge session.query/session-from-and-joins
+ {:select [[:session.id :id]
+ [reason-expr :reason]]
+ :where [:and
+ (:not-ended predicates)
+ (:not-mcp predicates)
+ [:not (into [:and] (keep predicates)
+ [:user-active :tenant-active :not-expired :not-timed-out])]]}))))
+
+(mu/defn delete-sessions-ended-long-ago! :- ms/IntGreaterThanOrEqualToZero
+ "Delete the Sessions whose recorded ending is more than [[ended-session-retention-days]] old, returning the number
+ deleted. A live session is never deleted, whatever its age."
+ []
+ (let [db-type (mdb/db-type)
+ cutoff (h2x/add-interval-honeysql-form db-type (h2x/current-datetime-honeysql-form db-type)
+ (- ended-session-retention-days) :day)]
+ (t2/delete! :model/Session :ended_at [:< cutoff])))
+
+(mu/defn delete-expired-mcp-sessions! :- ms/IntGreaterThanOrEqualToZero
+ "Delete the MCP-backed `core_session` rows older than `max-age-minutes`, past their own `expires_at`, or (when
+ `idle-timeout-seconds` is given) idle longer than `idle-timeout-seconds`. Returns the number of rows deleted.
-(mu/defn delete-expired-sessions!
- "Delete Sessions older than `max-age-minutes`, past their own `expires_at`, or (when `idle-timeout-seconds` is
- given) idle longer than `idle-timeout-seconds`. Returns the number of rows deleted."
+ Only MCP rows: they are not sessions, so they are deleted outright rather than kept on record like an ended
+ session (see [[sessions-with-unrecorded-ending]])."
[max-age-minutes :- ms/PositiveInt
idle-timeout-seconds :- [:maybe ms/PositiveInt]]
(let [db-type (mdb/db-type)
@@ -34,11 +113,16 @@
timeout-oldest (when idle-timeout-seconds
(h2x/add-interval-honeysql-form db-type now (- idle-timeout-seconds) :second))
hsql {:delete-from [(t2/table-name :model/Session)]
- :where (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]))}]
+ :where [:and
+ [:in :auth_identity_id ^:allow-subquery
+ {:select [:id]
+ :from [:auth_identity]
+ :where [:= :provider (h2x/literal session.query/mcp-provider)]}]
+ (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]))]}]
(tracing/with-span :tasks "task.session-cleanup.delete" {:db/statement (tracing/best-effort-sanitize-sql hsql)}
(t2/query-one hsql))))
diff --git a/src/metabase/session/events/revoke_on_deactivation.clj b/src/metabase/session/events/revoke_on_deactivation.clj
index e46b9bb02d0..1887712693a 100644
--- a/src/metabase/session/events/revoke_on_deactivation.clj
+++ b/src/metabase/session/events/revoke_on_deactivation.clj
@@ -1,7 +1,8 @@
(ns metabase.session.events.revoke-on-deactivation
- "Delete a user's sessions when they are deactivated, so a later reactivation can't revive a
- pre-deactivation session cookie. (SEC-863)"
+ "End a user's sessions when they are deactivated, so a later reactivation can't revive a pre-deactivation session
+ cookie. (SEC-863)"
(:require
+ [metabase.api.common :as api]
[metabase.events.core :as events]
[metabase.session.db :as session.db]
[methodical.core :as methodical]))
@@ -11,4 +12,5 @@
(methodical/defmethod events/publish-event! ::event
[_topic {:keys [user-id] :as _event}]
- (session.db/delete-sessions-for-user! user-id))
+ ;; the deactivating admin when the deactivation came in over the API; nil when it did not (SCIM, a script)
+ (session.db/end-sessions! {:user_id user-id} "user-deactivated" api/*current-user-id*))
diff --git a/src/metabase/session/models/session.clj b/src/metabase/session/models/session.clj
index c619bc83a12..b06345ec8d4 100644
--- a/src/metabase/session/models/session.clj
+++ b/src/metabase/session/models/session.clj
@@ -75,8 +75,18 @@
(derive :metabase/model)
(derive :hook/created-at-timestamped?))
-(t2/define-before-update :model/Session [_model]
- (throw (RuntimeException. "You cannot update a Session.")))
+(def ^:private ending-columns
+ "The only columns an update of a Session may touch: the ones [[metabase.session.db/end-sessions!]] writes to record
+ that the session ended. Everything else on the row is immutable."
+ #{:ended_at :end_reason :ended_by_user_id :key_hashed})
+
+(t2/define-before-update :model/Session [session]
+ (when-not (every? ending-columns (keys (t2/changes session)))
+ (throw (RuntimeException. "You cannot update a Session.")))
+ ;; a recorded ending is final
+ (when (some? (:ended_at (t2/original session)))
+ (throw (RuntimeException. "You cannot change a Session that has ended.")))
+ session)
(t2/define-before-insert :model/Session
[{session-key :session_key :as session}]
diff --git a/src/metabase/session/query.clj b/src/metabase/session/query.clj
new file mode 100644
index 00000000000..381309b6336
--- /dev/null
+++ b/src/metabase/session/query.clj
@@ -0,0 +1,98 @@
+(ns metabase.session.query
+ "The HoneySQL the session module builds but does not run: which `core_session` rows are still live.
+ `metabase.server.db` compiles [[live-session-conditions]] into its per-request authentication query, and the
+ `session-management` enterprise module builds its listing and revocation queries on the same predicates, so a
+ session that stops authenticating also stops being listed."
+ (:require
+ [metabase.app-db.core :as mdb]
+ [metabase.config.core :as config]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.request.core :as request]
+ [metabase.session.schema :as session.schema]
+ [metabase.settings.core :as setting]
+ [metabase.util.honey-sql-2 :as h2x]
+ [metabase.util.malli :as mu]))
+
+(set! *warn-on-reflection* true)
+
+(def mcp-provider
+ "The `auth_identity.provider` stamped on `core_session` rows created for MCP clients. [[live-session-conditions]]
+ treats a row carrying it as not live, so such rows neither authenticate a request nor appear in session management."
+ "mcp")
+
+(def not-mcp-session
+ "The HoneySQL predicate for \"this `core_session` row was not created for an MCP client\", for a query using
+ [[session-from-and-joins]]."
+ ;; null-safe: a null provider is a normal session (a password reset, or a row predating the v58
+ ;; `auth_identity_id` column), and `provider <> 'mcp'` alone would drop those, since NULL <> 'mcp' is NULL
+ [:or [:= :auth_identity.provider nil]
+ [:not= :auth_identity.provider (h2x/literal mcp-provider)]])
+
+(def session-left-joins
+ "The `:left-join`s from a `core_session` row aliased `session` that [[live-session-conditions]] needs: they bind
+ the aliases `user`, `tenant` and `auth_identity`. For a query that starts from another table and joins `session`
+ itself; a query that starts from `core_session` uses [[session-from-and-joins]]."
+ ;; all LEFT joins: a session whose user row, tenant, or auth identity is missing must still be *considered* (and
+ ;; then rejected, or bucketed as `unknown`) rather than silently dropped by an inner join
+ [[:core_user :user] [:= :session.user_id :user.id]
+ [:tenant] [:= :tenant.id :user.tenant_id]
+ [:auth_identity] [:= :auth_identity.id :session.auth_identity_id]])
+
+(def session-from-and-joins
+ "The `:from`/`:left-join` a query must use for [[live-session-conditions]] to resolve. Binds the aliases `session`,
+ `user`, `tenant` and `auth_identity`."
+ {:from [[:core_session :session]]
+ :left-join session-left-joins})
+
+(mu/defn liveness-params :- ::session.schema/liveness-params
+ "The [[live-session-conditions]] inputs for this instance right now."
+ ;; the tenant flag mirrors what `metabase.server.middleware.session` passes for the per-request lookup: if a
+ ;; tenant's sessions can't authenticate, they mustn't be listed as live either
+ []
+ {:db-type (mdb/db-type)
+ :max-age-minutes (config/config-int :max-session-age)
+ :enable-tenants? (boolean (and (premium-features/enable-tenants?)
+ (setting/get :use-tenants)))
+ :session-timeout-seconds (request/enabled-session-timeout-seconds)})
+
+(mu/defn liveness-predicates :- [:map-of :keyword :any]
+ "The HoneySQL predicates a `core_session` row must satisfy to be *live*, keyed by what each one checks, so that a
+ caller can name which one a row fails (the nightly sweep records that as the session's end reason). Pure, for the
+ same reason as [[live-session-conditions]]."
+ [{:keys [db-type max-age-minutes enable-tenants? session-timeout-seconds]}
+ :- ::session.schema/liveness-params]
+ (let [now (h2x/current-datetime-honeysql-form db-type)]
+ (cond-> {;; a recorded ending is final, whatever the predicates below would say now
+ :not-ended [:= :session.ended_at nil]
+ ;; deactivating a user does not delete their session rows, but those rows are dead
+ :user-active [:= :user.is_active true]
+ ;; when tenants are off, an external user's session is dead no matter what the tenant row says
+ :tenant-active (if enable-tenants?
+ [:or [:= :tenant.id nil] :tenant.is_active]
+ [:= :tenant.id nil])
+ ;; the session's own hard expiry and, below, the instance-wide maximum age: one end reason, `expired`
+ :not-expired (cond-> [:and [:or [:= :session.expires_at nil] [:> :session.expires_at now]]]
+ max-age-minutes
+ (conj [:> :session.created_at
+ (h2x/add-interval-honeysql-form db-type now (- max-age-minutes) :minute)]))
+ :not-mcp not-mcp-session}
+ session-timeout-seconds
+ (assoc :not-timed-out [:> [:coalesce :session.last_active_at :session.created_at]
+ (h2x/add-interval-honeysql-form db-type now (- session-timeout-seconds) :second)]))))
+
+(mu/defn live-session-conditions :- [:sequential :any]
+ "The HoneySQL predicates a `core_session` row must satisfy to be *live* — i.e. to still authenticate a request."
+ [liveness :- ::session.schema/liveness-params]
+ ;; session middleware calls and memoizes this per distinct combo of arguments, so it must be pure: the same
+ ;; arguments must give the same result every time. `enable-tenants?`, for one, is passed in rather than derived
+ ;; from the current setting value.
+ (let [predicates (liveness-predicates liveness)]
+ ;; a fixed order, so the compiled SQL is the same for the same inputs
+ (into [] (keep predicates) [:not-ended :user-active :tenant-active :not-expired :not-mcp :not-timed-out])))
+
+(mu/defn live-expr :- ::h2x/honeysql-expr
+ "1 when the `core_session` row is live, 0 when it has ended, whether or not the ending has been recorded yet. 1/0
+ rather than a boolean, since MySQL has no boolean type. For a query using [[session-from-and-joins]] or
+ [[session-left-joins]]."
+ [liveness :- ::session.schema/liveness-params]
+ [:case (into [:and] (live-session-conditions liveness)) [:inline 1] :else [:inline 0]])
diff --git a/src/metabase/session/schema.clj b/src/metabase/session/schema.clj
index 27e94c3c359..b0182414fd3 100644
--- a/src/metabase/session/schema.clj
+++ b/src/metabase/session/schema.clj
@@ -12,6 +12,29 @@
[:key string?]
[:type [:enum :normal :full-app-embed]]]])
+(def ^:private end-reasons
+ "Why a session can end (`core_session.end_reason`), one value per path that ends sessions: an admin's revocation,
+ the user's own logout, a password change, the user's or their tenant's deactivation, an SSO logout, a support-access
+ grant's revocation, expiry (its own `expires_at` or `max-session-age`, one reason), or the idle timeout."
+ ["admin" "logout" "password-change" "user-deactivated" "tenant-deactivated" "sso-logout" "support-grant-revoked"
+ "expired" "timed-out"])
+
+(mr/def ::end-reason
+ (into [:enum] end-reasons))
+
+(mr/def ::end-conditions
+ "Which Sessions [[metabase.session.db/end-sessions!]] ends: the ones with these ids, of this user, or with this
+ hashed key."
+ [:map {:closed true}
+ [:id {:optional true} [:sequential :string]]
+ [:user_id {:optional true} ::lib.schema.id/user]
+ [:key_hashed {:optional true} :string]])
+
+(mr/def ::ended-by
+ "Who ended a session, for [[metabase.session.db/end-sessions!]]: the id of the person who did, `:self` for the
+ session's own user (a logout), or nil when no person did (expiry, a deactivation)."
+ [:maybe [:or ::lib.schema.id/user [:= :self]]])
+
(mr/def ::session
"A Session as selected from the app DB: every column of `:core_session`."
[:merge
@@ -34,4 +57,15 @@
[:last_active_at {:optional true} [:maybe ms/TemporalInstant]]
[:saml_session_index {:optional true} [:maybe :string]]
[:saml_name_id {:optional true} [:maybe :string]]
- [:saml_name_id_format {:optional true} [:maybe :string]]])
+ [:saml_name_id_format {:optional true} [:maybe :string]]
+ [:ended_at {:optional true} [:maybe ms/TemporalInstant]]
+ [:end_reason {:optional true} [:maybe ::end-reason]]
+ [:ended_by_user_id {:optional true} [:maybe ::lib.schema.id/user]]])
+
+(mr/def ::liveness-params
+ "The instance-wide inputs to [[metabase.session.query/live-session-conditions]]."
+ [:map {:closed true}
+ [:db-type :keyword]
+ [:max-age-minutes [:maybe :int]]
+ [:enable-tenants? :boolean]
+ [:session-timeout-seconds [:maybe :int]]])
diff --git a/src/metabase/session/task/session_cleanup.clj b/src/metabase/session/task/session_cleanup.clj
index ec55cc89c8f..742e0a37ea0 100644
--- a/src/metabase/session/task/session_cleanup.clj
+++ b/src/metabase/session/task/session_cleanup.clj
@@ -11,18 +11,31 @@
(set! *warn-on-reflection* true)
+(defn- record-unrecorded-endings!
+ "Record the ending of every session that is no longer live but still has no `ended_at`: `expired` for a row past
+ its own `expires_at` or `max-session-age`, `timed-out` for one idle past the session timeout, `user-deactivated`
+ or `tenant-deactivated` for a deactivated user or tenant. Clears each key. Once recorded, an ending is final:
+ raising the idle timeout afterwards revives nothing."
+ []
+ (let [unrecorded (session.db/sessions-with-unrecorded-ending (session/liveness-params))]
+ (doseq [[reason rows] (group-by :reason unrecorded)]
+ (session.db/end-sessions-by-ids! (mapv :id rows) reason nil))))
+
(defn- cleanup-sessions!
- "Deletes sessions from the database which are no longer valid. Removes sessions that exceed MAX_SESSION_AGE
- (absolute lifetime), sessions past their own `expires_at`, and sessions that have been idle longer than the
- session-timeout setting (if configured)."
+ "Two passes over `core_session`: record the ending of every session that has stopped being live, then delete the
+ rows whose recorded ending is older than the retention period. MCP-backed rows are not sessions and are simply
+ deleted once they expire, as they always were."
[]
- (session.db/delete-expired-sessions! (config/config-int :max-session-age)
- (request/enabled-session-timeout-seconds)))
+ (session.db/delete-expired-mcp-sessions! (config/config-int :max-session-age)
+ (request/enabled-session-timeout-seconds))
+ (record-unrecorded-endings!)
+ (session.db/delete-sessions-ended-long-ago!))
(def ^:private session-cleanup-job-key (jobs/key "metabase.task.session-cleanup.job"))
(def ^:private session-cleanup-trigger-key (triggers/key "metabase.task.session-cleanup.trigger"))
-(task/defjob ^{:doc "Job that cleans up outdated sessions."}
+(task/defjob ^{:doc "Job that records the ending of sessions that stopped being live, and deletes those ended
+ long ago."}
SessionCleanup
[_]
(cleanup-sessions!)
diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.clj
index da2c3ce639f..bde00494c8e 100644
--- a/src/metabase/users_rest/api.clj
+++ b/src/metabase/users_rest/api.clj
@@ -646,7 +646,7 @@
users-rest.db/mfa-auth-identity-id-from-hashed-key
:mfa_auth_identity_id)]
;; set-password! invalidates the user's existing sessions; a self-change gets a fresh one below
- (auth-identity/set-password! id password)
+ (auth-identity/set-password! id password {:ended-by api/*current-user-id*})
;; after a successful password update go ahead and offer the client a new session that they can use
(when (= id api/*current-user-id*)
(let [{session-key :key, :as session} (auth-identity/create-session-with-auth-tracking!
diff --git a/test/metabase/analytics/stats_test.clj b/test/metabase/analytics/stats_test.clj
index e99c833a8ab..d4ac113d0bd 100644
--- a/test/metabase/analytics/stats_test.clj
+++ b/test/metabase/analytics/stats_test.clj
@@ -560,6 +560,7 @@
:metabase-ai-managed
:metabot-v3
:cloud-custom-smtp
+ :session-management
:session-timeout-config
:sso-oidc
:admin-security-center})
diff --git a/test/metabase/auth_identity/provider_test.clj b/test/metabase/auth_identity/provider_test.clj
index f14c8bacbac..f439fe9dbcd 100644
--- a/test/metabase/auth_identity/provider_test.clj
+++ b/test/metabase/auth_identity/provider_test.clj
@@ -5,7 +5,8 @@
[metabase.auth-identity.core :as auth-identity]
[metabase.auth-identity.provider :as provider]
[metabase.test :as mt]
- [methodical.core :as methodical]))
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
;; Set up test providers for testing the hierarchy
(auth-identity/derive! :provider/test-password ::provider/provider)
@@ -107,6 +108,53 @@
:tenant_id 1}
:jwt))))))
+;;; Two providers that differ only in whether their `:after` method redirects session attribution.
+(auth-identity/derive! :provider/test-session-attribution ::provider/provider)
+(auth-identity/derive! :provider/test-plain-attribution ::provider/provider)
+
+(methodical/defmethod provider/authenticate :provider/test-session-attribution
+ [_provider {:keys [user-id]}]
+ {:success? true :user-id user-id})
+
+(methodical/defmethod provider/login! :after :provider/test-session-attribution
+ [_provider result]
+ (assoc result :session/provider :provider/password))
+
+(methodical/defmethod provider/authenticate :provider/test-plain-attribution
+ [_provider {:keys [user-id]}]
+ {:success? true :user-id user-id})
+
+(deftest login!-honours-session-provider-test
+ (testing "a login! :after method can attribute the session it triggers to another provider's AuthIdentity"
+ (mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
+ (let [password-identity-id (t2/select-one-pk :model/AuthIdentity :user_id (:id user) :provider "password")
+ result (provider/login! :provider/test-session-attribution
+ {:user-id (:id user)
+ :device-info {:device_id "test"
+ :embedded false
+ :token_exchange false
+ :device_description "Test"
+ :ip_address "127.0.0.1"}})]
+ (is (true? (:success? result)))
+ (is (= password-identity-id (get-in result [:session :auth_identity_id])))))))
+
+(deftest login!-ignores-caller-supplied-session-provider-test
+ (testing "a caller cannot choose the session's AuthIdentity by putting :session/provider in the login request"
+ (mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "test-password")
+ (let [result (provider/login! :provider/test-plain-attribution
+ {:user-id (:id user)
+ :session/provider :provider/password
+ :device-info {:device_id "test"
+ :embedded false
+ :token_exchange false
+ :device_description "Test"
+ :ip_address "127.0.0.1"}})]
+ (is (true? (:success? result)))
+ (is (nil? (get-in result [:session :auth_identity_id]))
+ "the session is attributed to the provider that actually authenticated, which has no AuthIdentity")))))
+
(deftest ^:parallel ^:parallel three-valued-success-state-test
(testing "Success states work correctly"
(testing "Success state: true"
diff --git a/test/metabase/login_history/api_test.clj b/test/metabase/login_history/api_test.clj
index 69bc4f47866..469f26f3653 100644
--- a/test/metabase/login_history/api_test.clj
+++ b/test/metabase/login_history/api_test.clj
@@ -5,7 +5,8 @@
[metabase.request.util :as req.util]
[metabase.session.core :as session]
[metabase.test :as mt]
- [metabase.util :as u]))
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -96,3 +97,35 @@
[:location [:= "Virginia, United States"]]
[:timezone [:= "ET"]]]]
(mt/client session-key :get 200 "login-history/current"))))))))
+
+(deftest login-history-active-means-live-test
+ (testing "GET /api/login-history/current: `active` is whether the login's session is still live, not whether its row
+ exists"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [session! (fn [& {:as extra}]
+ (let [id (session/generate-session-id)]
+ (t2/insert! (t2/table-name :model/Session)
+ (merge {:id id
+ :key_hashed (session/hash-session-key (session/generate-session-key))
+ :user_id user-id
+ :created_at :%now}
+ extra))
+ id))
+ login! (fn [session-id ip]
+ (t2/insert! :model/LoginHistory {:user_id user-id
+ :session_id session-id
+ :device_id (str (random-uuid))
+ :device_description windows-user-agent
+ :ip_address ip}))]
+ (login! (session! :key_hashed nil :ended_at :%now :end_reason "admin") "10.0.0.1")
+ (login! (session! :expires_at (t/minus (t/instant) (t/minutes 1))) "10.0.0.2")
+ (login! (session!) "10.0.0.3")
+ (login! nil "10.0.0.4")
+ (mt/with-dynamic-fn-redefs [req.util/geocode-ip-addresses
+ (fn [ips] (zipmap ips (repeat {:description "Somewhere" :timezone nil})))]
+ (is (= {"10.0.0.1" false ; revoked: the row is kept, but the session is not live
+ "10.0.0.2" false ; expired, whether or not the sweep has recorded it
+ "10.0.0.3" true
+ "10.0.0.4" false} ; the session row is gone
+ (into {} (map (juxt :ip_address :active))
+ (mt/user-http-request user-id :get 200 "login-history/current")))))))))
diff --git a/test/metabase/mcp/db_test.clj b/test/metabase/mcp/db_test.clj
index 8e5108eb19f..a55ca961b7d 100644
--- a/test/metabase/mcp/db_test.clj
+++ b/test/metabase/mcp/db_test.clj
@@ -2,8 +2,10 @@
(:require
[clojure.test :refer [are deftest is testing use-fixtures]]
[metabase.mcp.db :as mcp.db]
+ [metabase.session.query :as session.query]
[metabase.test :as mt]
- [metabase.test.fixtures :as fixtures]))
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -57,3 +59,28 @@
(are [ids] (= {} (mcp.db/user-id->tenant-id ids))
[]
#{})))
+
+(deftest get-or-create-core-session-stamps-the-mcp-provider-test
+ (testing "MCP-created sessions are stamped with the `mcp` provider so session management can exclude them"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [key-hashed (str "mcp-test-" (random-uuid))
+ session (mcp.db/get-or-create-core-session! key-hashed user-id)]
+ (try
+ (is (some? (:auth_identity_id session)))
+ (is (= session.query/mcp-provider
+ (t2/select-one-fn :provider :model/AuthIdentity :id (:auth_identity_id session))))
+ (testing "a second handshake reuses the same auth identity rather than tripping the unique constraint"
+ (let [again (mcp.db/get-or-create-core-session! (str "mcp-test-" (random-uuid)) user-id)]
+ (try
+ (is (= (:auth_identity_id session) (:auth_identity_id again)))
+ (finally
+ (t2/delete! :core_session :id (:id again))))))
+ (testing "the stamped session is not live, so it can never be listed or revoked by criteria"
+ (is (empty? (t2/query (merge session.query/session-from-and-joins
+ {:select [[:session.id :id]]
+ :where (into [:and [:= :session.user_id user-id]]
+ (session.query/live-session-conditions
+ (session.query/liveness-params)))})))))
+ (finally
+ (t2/delete! :core_session :id (:id session))
+ (t2/delete! :model/AuthIdentity :user_id user-id :provider session.query/mcp-provider)))))))
diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.clj
index 51e654d7670..91d8792e29e 100644
--- a/test/metabase/server/middleware/session_test.clj
+++ b/test/metabase/server/middleware/session_test.clj
@@ -437,7 +437,8 @@
:is-group-manager? false,
:user-locale nil
:is-data-analyst? false
- :auth-provider nil}
+ :auth-provider nil
+ :session-key-hash test-session-key-hashed}
(#'mw.session/current-user-info-for-session test-session-key nil)))
(finally
(t2/delete! :model/Session :id test-session-id))))))
@@ -454,7 +455,8 @@
:is-group-manager? false,
:user-locale nil
:is-data-analyst? false
- :auth-provider nil}
+ :auth-provider nil
+ :session-key-hash test-session-key-hashed}
(#'mw.session/current-user-info-for-session test-session-key nil)))
(finally
(t2/delete! :model/Session :id test-session-id))))))
@@ -507,7 +509,8 @@
:is-group-manager? false,
:user-locale nil
:is-data-analyst? false
- :auth-provider nil}
+ :auth-provider nil
+ :session-key-hash test-session-key-hashed}
(#'mw.session/current-user-info-for-session test-session-key test-anti-csrf-token)))
(finally
(t2/delete! :model/Session :id test-session-id)))
diff --git a/test/metabase/session/api_test.clj b/test/metabase/session/api_test.clj
index aed7d164247..0e3a7280251 100644
--- a/test/metabase/session/api_test.clj
+++ b/test/metabase/session/api_test.clj
@@ -85,9 +85,13 @@
[:user_id [:= (mt/user->id :rasta)]]
[:device_id ms/UUIDString]
[:device_description ms/NonBlankString]
- [:ip_address ms/NonBlankString]
- [:active [:= true]]]
- (t2/select-one :model/LoginHistory :user_id (mt/user->id :rasta), :session_id (t2/select-one-fn :id :model/Session :key_hashed (session/hash-session-key (:id response)))))))))
+ [:ip_address ms/NonBlankString]]
+ (t2/select-one :model/LoginHistory
+ :user_id (mt/user->id :rasta)
+ :session_id (t2/select-one-fn :id :model/Session
+ :key_hashed (session/hash-session-key (:id response))))))
+ (is (true? (:active (first (login-history.db/login-history-for-user (mt/user->id :rasta)))))
+ "the login just made is the newest, and its session is live"))))
(deftest login-remember-me-sets-max-age-test
(testing "POST /api/session - 'remember me' checkbox sets Max-Age attribute on session cookie"
@@ -237,25 +241,33 @@
(test.users/clear-cached-session-tokens!)
(let [session-key (client/authenticate (test.users/user->credentials :rasta))
session-key-hashed (session/hash-session-key session-key)
- login-history-id (t2/select-one-pk :model/LoginHistory :session_id (t2/select-one-pk :model/Session :key_hashed session-key-hashed))]
+ session-id (t2/select-one-pk :model/Session :key_hashed session-key-hashed)
+ login-history-id (t2/select-one-pk :model/LoginHistory :session_id session-id)]
(testing "LoginHistory should have been recorded"
(is (integer? login-history-id)))
- ;; Ok, calling the logout endpoint should delete the Session in the DB. Don't worry, `test-users` will log back
+ ;; Ok, calling the logout endpoint should end the Session in the DB. Don't worry, `test-users` will log back
;; in on the next API call
(client/client session-key :delete 204 "session")
- ;; check whether it's still there -- should be GONE
- (is (= nil
- (t2/select-one :model/Session :key_hashed session-key-hashed)))
- (testing "LoginHistory item should still exist, but session_id should be set to nil (active = false)"
+ (testing "the session is ended, attributed to the user, and its key destroyed — but the row is kept"
+ (is (nil? (t2/select-one :model/Session :key_hashed session-key-hashed)))
+ (is (=? {:end_reason "logout"
+ :ended_by_user_id (mt/user->id :rasta)
+ :ended_at some?
+ :key_hashed nil}
+ (t2/select-one :model/Session :id session-id))))
+ (testing "the old cookie no longer authenticates"
+ (is (= "Unauthenticated" (client/client session-key :get 401 "user/current"))))
+ (testing "LoginHistory item should still exist, but read as no longer active"
(is (malli= [:map
[:id ms/PositiveInt]
[:timestamp (ms/InstanceOfClass java.time.OffsetDateTime)]
[:user_id [:= (mt/user->id :rasta)]]
[:device_id ms/UUIDString]
[:device_description ms/NonBlankString]
- [:ip_address ms/NonBlankString]
- [:active [:= false]]]
- (t2/select-one :model/LoginHistory :id login-history-id))))))))
+ [:ip_address ms/NonBlankString]]
+ (t2/select-one :model/LoginHistory :id login-history-id)))
+ (is (false? (:active (first (login-history.db/login-history-for-user (mt/user->id :rasta)))))
+ "the newest login of the user is the one just logged out"))))))
(deftest login-survives-concurrent-session-delete-test
(testing (str "POST /api/session - SEC-1208: deleting the user's sessions (as a password change does) between the"
@@ -548,7 +560,7 @@
:password "whateverUP12!!"})))))))
(deftest reset-password-from-token-invalidates-sessions-test
- (testing "POST /api/session/reset_password deletes the user's existing sessions"
+ (testing "POST /api/session/reset_password ends the user's existing sessions"
(mt/with-temp [:model/User user {}]
(auth-identity/set-password! (:id user) "password")
(let [session (auth-identity/create-session-with-auth-tracking!
@@ -560,8 +572,67 @@
(is (some? (t2/select-one :model/Session :id (:id session)))
"sanity check: the session exists before the reset")
(mt/client :post 200 "session/reset_password" {:token token :password "whateverUP12!!"})
- (is (nil? (t2/select-one :model/Session :id (:id session)))
- "the pre-existing session should be deleted after resetting the password via token")))))
+ (is (=? {:end_reason "password-change", :ended_by_user_id (:id user), :ended_at some?, :key_hashed nil}
+ (t2/select-one :model/Session :id (:id session)))
+ "the pre-existing session should be ended, by the user, after resetting the password via token")))))
+
+(deftest reset-password-session-is-attributed-to-password-identity-test
+ (testing "POST /api/session/reset_password issues a session belonging to the user's password AuthIdentity"
+ (mt/with-temp [:model/User user {}
+ ;; the pre-existing session hangs off a different identity, so last_used_at on the
+ ;; password identity below is nil until the reset itself touches it
+ :model/AuthIdentity _ {:user_id (:id user) :provider "google" :metadata {:sso_source "google"}}]
+ (auth-identity/set-password! (:id user) "password")
+ (let [stale-session (auth-identity/create-session-with-auth-tracking!
+ user
+ {:device_id "reset-attribution-device" :embedded false :token_exchange false
+ :device_description "Test" :ip_address "127.0.0.1"}
+ :provider/google)
+ token (auth-identity/create-password-reset! (:id user))]
+ (mt/client :post 200 "session/reset_password" {:token token :password "whateverUP12!!"})
+ ;; read core_session directly: auth_identity_id is the column session listing joins the provider on
+ (let [password-identity-id (t2/select-one-pk :model/AuthIdentity :user_id (:id user) :provider "password")
+ sessions (t2/query {:select [:id :auth_identity_id]
+ :from [:core_session]
+ :where [:and [:= :user_id (:id user)] [:= :ended_at nil]]})]
+ (is (=? {:end_reason "password-change", :key_hashed nil}
+ (t2/select-one :model/Session :id (:id stale-session)))
+ "the session that existed before the reset is revoked")
+ (is (= 1 (count sessions))
+ "only the session the reset just created is live")
+ (is (some? (:auth_identity_id (first sessions)))
+ "the new session is attributed to an auth identity")
+ (is (= password-identity-id (:auth_identity_id (first sessions)))
+ "the new session is attributed to the password identity the reset just wrote")
+ (is (some? (t2/select-one-fn :last_used_at :model/AuthIdentity password-identity-id))
+ "completing the reset counts as a use of the password identity")
+ (is (nil? (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "emailed-secret-password-reset"))
+ "the consumed reset identity is still deleted"))))))
+
+(deftest reset-password-refused-when-password-login-disabled-test
+ (testing "POST /api/session/reset_password refuses, and changes nothing, when password login is disabled"
+ (ldap.test/with-ldap-server!
+ (mt/with-temp [:model/User user {}]
+ (auth-identity/set-password! (:id user) "password")
+ (let [session (auth-identity/create-session-with-auth-tracking!
+ user
+ {:device_id "reset-disabled-device" :embedded false :token_exchange false
+ :device_description "Test" :ip_address "127.0.0.1"}
+ :provider/password)
+ credentials (t2/select-one-fn :credentials :model/AuthIdentity
+ :user_id (:id user) :provider "password")
+ token (auth-identity/create-password-reset! (:id user))]
+ (mt/with-premium-features #{:disable-password-login}
+ (mt/with-temporary-setting-values [enable-password-login false]
+ (is (= "Password login is disabled for this instance."
+ (mt/client :post 400 "session/reset_password" {:token token :password "whateverUP12!!"})))
+ (is (= credentials
+ (t2/select-one-fn :credentials :model/AuthIdentity :user_id (:id user) :provider "password"))
+ "the password is unchanged: the stored credential is still the same hash")
+ (is (some? (t2/select-one :model/Session :id (:id session)))
+ "the user's existing sessions are not revoked")
+ (is (some? (t2/select-one :model/AuthIdentity :user_id (:id user) :provider "emailed-secret-password-reset"))
+ "the reset token is not consumed"))))))))
(deftest check-reset-token-valid-test
(testing "GET /session/password_reset_token_valid"
diff --git a/test/metabase/session/core_test.clj b/test/metabase/session/core_test.clj
new file mode 100644
index 00000000000..c0ee3ba9c49
--- /dev/null
+++ b/test/metabase/session/core_test.clj
@@ -0,0 +1,41 @@
+(ns metabase.session.core-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.session.core :as session]
+ [metabase.test :as mt]
+ [metabase.util :as u]))
+
+(set! *warn-on-reflection* true)
+
+(defn- activity-cache
+ []
+ @@#'session/session-last-update-times)
+
+(def ^:private past-throttle-window
+ "A [[metabase.util/since-ms]] stub that makes every cached entry look older than the throttle window."
+ (constantly (inc @#'session/activity-update-throttle-ms)))
+
+(deftest record-session-activity-update!-throttles-test
+ (session/clear-session-activity-cache!)
+ (let [key-hash (str (random-uuid))]
+ (testing "the first activity update for a session is allowed through"
+ (is (true? (session/record-session-activity-update! key-hash))))
+ (testing "a second update within the throttle window is throttled"
+ (is (false? (session/record-session-activity-update! key-hash))))
+ (testing "an update after the throttle window has elapsed is allowed through again"
+ (mt/with-dynamic-fn-redefs [u/since-ms past-throttle-window]
+ (is (true? (session/record-session-activity-update! key-hash)))))
+ (testing "sessions are throttled independently of one another"
+ (is (true? (session/record-session-activity-update! (str (random-uuid))))))))
+
+(deftest prune-session-activity-cache!-test
+ (session/clear-session-activity-cache!)
+ (let [key-hash (str (random-uuid))]
+ (session/record-session-activity-update! key-hash)
+ (testing "entries inside the throttle window are kept"
+ (session/prune-session-activity-cache!)
+ (is (contains? (activity-cache) key-hash)))
+ (testing "entries older than the throttle window are dropped"
+ (mt/with-dynamic-fn-redefs [u/since-ms past-throttle-window]
+ (session/prune-session-activity-cache!))
+ (is (not (contains? (activity-cache) key-hash))))))
diff --git a/test/metabase/session/db_test.clj b/test/metabase/session/db_test.clj
new file mode 100644
index 00000000000..ee3d7159880
--- /dev/null
+++ b/test/metabase/session/db_test.clj
@@ -0,0 +1,62 @@
+(ns metabase.session.db-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.session.core :as session]
+ [metabase.session.db :as session.db]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn- insert-session!
+ "Insert a session row the way a login would, returning `[session-id session-key]`."
+ [user-id]
+ (let [session-key (session/generate-session-key)
+ id (session/generate-session-id)]
+ (t2/insert! (t2/table-name :model/Session)
+ {:id id
+ :key_hashed (session/hash-session-key session-key)
+ :user_id user-id
+ :created_at :%now})
+ [id session-key]))
+
+(defn- row [session-id]
+ (select-keys (t2/select-one :model/Session :id session-id) [:end_reason :ended_by_user_id :key_hashed]))
+
+(deftest end-sessions-test
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/User {other-id :id} {}]
+ (let [[by-key session-key] (insert-session! user-id)
+ [by-user _] (insert-session! user-id)
+ [others _] (insert-session! other-id)]
+ (testing "a request presenting the session works before it is ended"
+ (is (= user-id (:id (mt/client session-key :get 200 "user/current")))))
+ (testing "ending by hashed key records the reason and destroys the key"
+ (is (= 1 (session.db/end-sessions! {:key_hashed (session/hash-session-key session-key)} "logout" :self)))
+ (is (= {:end_reason "logout", :ended_by_user_id user-id, :key_hashed nil} (row by-key))
+ "`:self` attributes the ending to the session's own user")
+ (is (some? (:ended_at (t2/select-one :model/Session :id by-key)))))
+ (testing "and the old cookie is unauthenticated from then on"
+ (is (= "Unauthenticated" (mt/client session-key :get 401 "user/current"))))
+ (testing "ending by user records the actor, and only touches that user's live sessions"
+ (is (= 1 (session.db/end-sessions! {:user_id user-id} "admin" (mt/user->id :crowberto))))
+ (is (= {:end_reason "admin", :ended_by_user_id (mt/user->id :crowberto), :key_hashed nil} (row by-user)))
+ (is (= {:end_reason "logout", :ended_by_user_id user-id, :key_hashed nil} (row by-key))
+ "an already-ended session keeps its first ending")
+ (is (= {:end_reason nil, :ended_by_user_id nil} (dissoc (row others) :key_hashed))))
+ (testing "the rows are kept"
+ (is (= 3 (t2/count :model/Session :id [:in [by-key by-user others]]))))
+ (testing "ending an already-ended session is a no-op"
+ (is (zero? (session.db/end-sessions! {:id [by-key by-user]} "admin" nil))))
+ (testing "an explicitly empty id list ends nothing"
+ (is (zero? (session.db/end-sessions! {:id []} "admin" nil)))))))
+
+(deftest end-sessions-by-ids-batches-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [ids (vec (repeatedly 5 #(first (insert-session! user-id))))]
+ ;; a real revoke batches at `default-end-batch-size`; two and a half batches of two exercises the same code,
+ ;; including the short final batch, without inserting thousands of rows
+ (is (= 5 (session.db/end-sessions-by-ids! ids "admin" nil 2))
+ "every batch is counted, including the short final one")
+ (is (every? #(nil? (:key_hashed %)) (t2/select :model/Session :id [:in ids])))
+ (is (zero? (session.db/end-sessions-by-ids! [] "admin" nil))))))
diff --git a/test/metabase/session/events/revoke_on_deactivation_test.clj b/test/metabase/session/events/revoke_on_deactivation_test.clj
index 8b3432c590c..24c4ab2dc9f 100644
--- a/test/metabase/session/events/revoke_on_deactivation_test.clj
+++ b/test/metabase/session/events/revoke_on_deactivation_test.clj
@@ -18,27 +18,33 @@
:created_at :%now})
id))
+(defn- ending [session-id]
+ (select-keys (t2/select-one :model/Session :id session-id) [:end_reason :ended_by_user_id :key_hashed]))
+
(deftest revoke-on-event-test
- (testing ":event/user-credentials-revoked deletes the user's sessions, leaving other users' untouched"
+ (testing ":event/user-credentials-revoked ends the user's sessions, leaving other users' untouched"
(mt/with-temp [:model/User {victim :id} {}
:model/User {bystander :id} {}]
(let [victim-session (insert-session! victim)
bystander-session (insert-session! bystander)]
- (events/publish-event! :event/user-credentials-revoked {:user-id victim})
- (is (not (t2/exists? :model/Session :id victim-session))
- "victim's session is deleted")
- (is (t2/exists? :model/Session :id bystander-session)
+ (mt/with-current-user (mt/user->id :crowberto)
+ (events/publish-event! :event/user-credentials-revoked {:user-id victim}))
+ (is (= {:end_reason "user-deactivated", :ended_by_user_id (mt/user->id :crowberto), :key_hashed nil}
+ (ending victim-session))
+ "victim's session is ended, attributed to the deactivating admin, and its key destroyed")
+ (is (some? (:ended_at (t2/select-one :model/Session :id victim-session))))
+ (is (= {:end_reason nil, :ended_by_user_id nil} (dissoc (ending bystander-session) :key_hashed))
"an unrelated user's session is untouched")))))
(deftest deactivation-revokes-and-reactivation-does-not-revive-test
- (testing "deactivating a user deletes their sessions; reactivating does NOT bring them back (SEC-863)"
+ (testing "deactivating a user ends their sessions; reactivating does NOT bring them back (SEC-863)"
(mt/with-temp [:model/User {user-id :id} {:is_active true}]
(let [session-id (insert-session! user-id)]
- (is (t2/exists? :model/Session :id session-id)
- "session exists while the user is active")
+ (is (nil? (:ended_at (t2/select-one :model/Session :id session-id)))
+ "session is live while the user is active")
(t2/update! :model/User user-id {:is_active false})
- (is (not (t2/exists? :model/Session :id session-id))
- "deactivation revokes the session")
+ (is (= {:end_reason "user-deactivated", :ended_by_user_id nil, :key_hashed nil} (ending session-id))
+ "deactivation outside a request ends the session with no actor")
(t2/update! :model/User user-id {:is_active true})
- (is (not (t2/exists? :model/Session :id session-id))
+ (is (= {:end_reason "user-deactivated", :ended_by_user_id nil, :key_hashed nil} (ending session-id))
"reactivation does not revive the pre-deactivation session")))))
diff --git a/test/metabase/session/models/session_test.clj b/test/metabase/session/models/session_test.clj
index e365461f021..92165df89d0 100644
--- a/test/metabase/session/models/session_test.clj
+++ b/test/metabase/session/models/session_test.clj
@@ -195,3 +195,29 @@
(is (not= (codecs/bytes->hex (buddy-hash/sha512 key-bytes))
(session/hash-session-key session-key))
"keyed hash must differ from the unsalted SHA-512 an attacker can compute"))))))
+
+(deftest before-update-only-allows-an-ending-test
+ (mt/with-temp [:model/User {user-id :id}]
+ (mt/with-model-cleanup [:model/Session]
+ (let [session-id (session/generate-session-id)]
+ (t2/insert! :model/Session {:id session-id :user_id user-id :session_key (session/generate-session-key)})
+ (testing "no column outside the four an ending writes can be updated"
+ (doseq [changes [{:expires_at (t/instant)}
+ {:user_id (mt/user->id :rasta)}
+ {:last_active_at (t/instant)}
+ {:ended_at (t/instant), :expires_at (t/instant)}]]
+ (is (thrown-with-msg? RuntimeException #"You cannot update a Session"
+ (t2/update! :model/Session session-id changes)))))
+ (testing "recording an ending is allowed"
+ (is (= 1 (t2/update! :model/Session session-id {:ended_at (t/instant)
+ :end_reason "admin"
+ :ended_by_user_id (mt/user->id :crowberto)
+ :key_hashed nil}))))
+ (testing "an ending is final: nothing an ending writes can be changed once it is recorded"
+ (doseq [changes [{:ended_at nil}
+ {:ended_at (t/instant)}
+ {:end_reason "timed-out"}
+ {:ended_by_user_id (mt/user->id :rasta)}
+ {:key_hashed (session/hash-session-key (session/generate-session-key))}]]
+ (is (thrown-with-msg? RuntimeException #"You cannot change a Session that has ended"
+ (t2/update! :model/Session session-id changes)))))))))
diff --git a/test/metabase/session/task/session_cleanup_test.clj b/test/metabase/session/task/session_cleanup_test.clj
index 2022fc67752..cec99dd3bc6 100644
--- a/test/metabase/session/task/session_cleanup_test.clj
+++ b/test/metabase/session/task/session_cleanup_test.clj
@@ -2,50 +2,124 @@
(:require
[clojure.test :refer :all]
[java-time.api :as t]
+ [metabase.session.core :as session]
+ [metabase.session.db :as session.db]
[metabase.session.task.session-cleanup :as session-cleanup]
[metabase.test :as mt]
- [toucan2.core :as t2]))
+ [metabase.util :as u]
+ [toucan2.core :as t2])
+ (:import
+ (metabase.session.task.session_cleanup SessionCleanup)
+ (org.quartz Job)))
-(deftest clean-sessions-test
+(set! *warn-on-reflection* true)
+
+(defn- insert-session!
+ "Insert a `core_session` row directly, bypassing the model hooks so the timestamps can be arbitrary. Returns the
+ session id."
+ [user-id & {:as extra-cols}]
+ (let [id (session/generate-session-id)]
+ (t2/insert! (t2/table-name :model/Session)
+ (merge {:id id
+ :key_hashed (session/hash-session-key (str (random-uuid)))
+ :user_id user-id
+ :created_at :%now}
+ extra-cols))
+ id))
+
+(defn- ending
+ "How the session with `session-id` ended, or nil if it has not: its reason, whether its key is cleared, and whether
+ `ended_at` is set. Nil if the row is gone."
+ [session-id]
+ (when-let [{:keys [ended_at end_reason key_hashed]} (t2/select-one :model/Session :id session-id)]
+ {:reason end_reason, :ended? (some? ended_at), :key-cleared? (nil? key_hashed)}))
+
+(defn- sweep! [] (#'session-cleanup/cleanup-sessions!))
+
+(deftest sweep-records-max-age-expiry-test
(mt/with-temp-env-var-value! [:max-session-age (str (* 60 24))] ;; one day
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [old (insert-session! user-id :created_at (t/minus (t/local-date-time) (t/days 2)))
+ new (insert-session! user-id :created_at (t/minus (t/local-date-time) (t/hours 5)))]
+ (testing "a session past max-session-age is recorded as expired, its key cleared, and the row kept"
+ (sweep!)
+ (is (= {:reason "expired", :ended? true, :key-cleared? true} (ending old)))
+ (is (= {:reason nil, :ended? false, :key-cleared? false} (ending new))))))))
- (mt/with-temp [:model/User {user-id :id} {}
- :model/Session old-session {:id "a"
- :key_hashed "a1"
- :user_id user-id
- :created_at (t/minus (t/local-date-time) (t/days 2))}
- :model/Session new-session {:id "b"
- :key_hashed "b1"
- :user_id user-id
- :created_at (t/minus (t/local-date-time) (t/hours 5))}]
- (testing "session-cleanup deletes old sessions and keeps new enough ones"
- (is (t2/select-one :model/Session :id (old-session :id)))
- (#'session-cleanup/cleanup-sessions!)
- (is (not (t2/exists? :model/Session :id (:id old-session))))
- (is (t2/exists? :model/Session :id (:id new-session)))))))
-
-(deftest clean-expired-sessions-test
+(deftest sweep-records-hard-expiry-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.
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [expired (insert-session! user-id :created_at recently :expires_at (t/minus (t/instant) (t/minutes 1)))
+ unexpired (insert-session! user-id :created_at recently :expires_at (t/plus (t/instant) (t/hours 1)))
+ no-expiry (insert-session! user-id :created_at recently)]
+ (testing "a session past its own expires_at is recorded as expired even inside max-session-age"
+ (sweep!)
+ (is (= {:reason "expired", :ended? true, :key-cleared? true} (ending expired)))
+ (is (false? (:ended? (ending unexpired))))
+ (is (false? (:ended? (ending no-expiry))))))))))
+
+(deftest sweep-records-user-deactivation-test
+ (mt/with-temp [:model/User {user-id :id} {:is_active true}]
+ (let [session-id (insert-session! user-id)
+ ;; also past max age, to show which reason wins
+ old-session (insert-session! user-id :created_at (t/minus (t/local-date-time) (t/days 400)))]
+ ;; the raw table: the model's before-update would end the sessions itself, which is not what this test is about
+ (t2/update! (t2/table-name :model/User) user-id {:is_active false})
+ (sweep!)
+ (testing "a deactivated user's session is recorded as user-deactivated"
+ (is (= {:reason "user-deactivated", :ended? true, :key-cleared? true} (ending session-id))))
+ (testing "deactivation wins over expiry when both apply"
+ (is (= "user-deactivated" (:reason (ending old-session))))))))
+
+(deftest sweep-leaves-recorded-endings-alone-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [session-id (insert-session! user-id :created_at (t/minus (t/local-date-time) (t/days 400)))]
+ (session.db/end-sessions! {:id [session-id]} "logout" :self)
+ (let [before (t2/select-one :model/Session :id session-id)]
+ (sweep!)
+ (testing "a session whose ending is already recorded keeps its reason and instant, however stale it is now"
+ (is (= (select-keys before [:end_reason :ended_at :ended_by_user_id])
+ (select-keys (t2/select-one :model/Session :id session-id)
+ [:end_reason :ended_at :ended_by_user_id]))))))))
+
+(deftest sweep-deletes-sessions-ended-long-ago-test
+ (mt/with-temp-env-var-value! [:max-session-age (str (* 60 24 60))] ;; sixty days
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (let [ended-at (fn [days-ago] (t/minus (t/offset-date-time) (t/days days-ago)))
+ gone (insert-session! user-id :key_hashed nil :end_reason "logout" :ended_at (ended-at 31))
+ kept (insert-session! user-id :key_hashed nil :end_reason "logout" :ended_at (ended-at 29))
+ live (insert-session! user-id :created_at (t/minus (t/local-date-time) (t/days 45)))]
+ (sweep!)
+ (testing "a session ended more than thirty days ago is deleted"
+ (is (nil? (ending gone))))
+ (testing "one ended less than thirty days ago is kept"
+ (is (= {:reason "logout", :ended? true, :key-cleared? true} (ending kept))))
+ (testing "a live session is never deleted, whatever its age below max-session-age"
+ (is (= {:reason nil, :ended? false, :key-cleared? false} (ending live))))))))
+
+(deftest sweep-deletes-expired-mcp-rows-test
+ (mt/with-temp-env-var-value! [:max-session-age (str (* 60 24))] ;; one day
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/AuthIdentity {mcp-id :id} {:user_id user-id :provider "mcp"}]
+ (let [expired-mcp (insert-session! user-id :auth_identity_id mcp-id
+ :created_at (t/minus (t/local-date-time) (t/days 2)))
+ fresh-mcp (insert-session! user-id :auth_identity_id mcp-id)]
+ (sweep!)
+ (testing "an expired MCP-backed row is deleted outright, never recorded as ended"
+ (is (nil? (ending expired-mcp))))
+ (testing "a fresh MCP-backed row is left alone"
+ (is (= {:reason nil, :ended? false, :key-cleared? false} (ending fresh-mcp))))))))
+
+(deftest session-cleanup-job-prunes-activity-cache-test
+ (testing "the cleanup job prunes the in-memory session activity throttle cache"
+ (session/clear-session-activity-cache!)
+ (let [key-hash (str (random-uuid))]
+ (session/record-session-activity-update! key-hash)
+ ;; the cache only drops entries older than the throttle window, so make every entry look stale
+ (mt/with-dynamic-fn-redefs [u/since-ms (constantly Long/MAX_VALUE)]
+ (.execute ^Job (SessionCleanup.) nil))
+ (is (true? (session/record-session-activity-update! key-hash))
+ "a pruned session is no longer throttled"))))
+
+;; the idle-timeout pass is tested in metabase-enterprise.api.session-test because it requires EE features.
diff --git a/test/metabase/users_rest/api_test.clj b/test/metabase/users_rest/api_test.clj
index 186294f7343..840643d12ea 100644
--- a/test/metabase/users_rest/api_test.clj
+++ b/test/metabase/users_rest/api_test.clj
@@ -1856,10 +1856,12 @@
(is (=? {:session_id string/valid-uuid?
:success true}
resp))
- ;; Original session should be gone
+ ;; Original session should be ended: its key destroyed, the change attributed to the user
(is (not (t2/exists?
:model/Session
:key_hashed (session/hash-session-key original-session-key))))
+ (is (=? {:end_reason "password-change", :ended_by_user_id user-id, :key_hashed nil}
+ (t2/select-one :model/Session :id (:id original-session))))
(let [new-session-key (:session_id resp)
new-session (t2/select-one
:model/Session
@@ -1886,8 +1888,9 @@
"sanity check: the session exists before the password change")
(mt/user-http-request :crowberto :put 204 (format "user/%d/password" (:id user))
{:password "abc123!!DEF", :old_password "def"})
- (is (nil? (t2/select-one :model/Session :id (:id session)))
- "the user's pre-existing session should be deleted after the password change")))))
+ (is (=? {:end_reason "password-change", :ended_by_user_id (mt/user->id :crowberto), :key_hashed nil}
+ (t2/select-one :model/Session :id (:id session)))
+ "the user's pre-existing session should be ended by the admin after the password change")))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Deleting (Deactivating) a User -- DELETE /api/user/:id |