Skip to content

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

Collect customer consent to grant instance access to Metabase success engineers (#65701)

Anderson28b5fb79f18e
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index b025fbdf6c2..22dfca0373e 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -208,8 +208,8 @@
auth-identity
{:team "UX West"
- :api #{metabase.auth-identity.core
- metabase.auth-identity.init}
+ :api #{metabase.auth-identity.core
+ metabase.auth-identity.init}
:uses #{channel
events
login-history
@@ -989,7 +989,7 @@
metabase.queries.core
metabase.queries.init
metabase.queries.models.query ; TODO FIXME
- metabase.queries.schema} ; TODO FIXME
+ metabase.queries.schema} ; TODO FIXME
:uses #{analytics
analyze
api
@@ -1118,7 +1118,7 @@
:uses #{api
config
embedding
- permissions ; FIXME
+ permissions ; FIXME
session
settings
users
@@ -1757,7 +1757,7 @@
enterprise/auth-identity
{:team "UX West"
- :api #{}
+ :api #{}
:uses #{premium-features}}
enterprise/auth-provider
@@ -2201,6 +2201,19 @@
settings
util}}
+ enterprise/support-access-grants
+ {:team "UX West"
+ :api #{metabase-enterprise.support-access-grants.api
+ metabase-enterprise.support-access-grants.init}
+ :uses #{api
+ auth-identity
+ events
+ models
+ request
+ settings
+ system
+ util}}
+
enterprise/transforms
{:team "Querying"
:api #{metabase-enterprise.transforms.api
diff --git a/e2e/test/scenarios/admin/tools/help.cy.spec.ts b/e2e/test/scenarios/admin/tools/help.cy.spec.ts
new file mode 100644
index 00000000000..043826a030d
--- /dev/null
+++ b/e2e/test/scenarios/admin/tools/help.cy.spec.ts
@@ -0,0 +1,170 @@
+import dayjs from "dayjs";
+
+const { H } = cy;
+
+describe("scenarios > admin > tools > help", { tags: "@OSS" }, () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ it("should link `Get help` to help", () => {
+ cy.visit("/admin/tools/help");
+
+ // eslint-disable-next-line no-unscoped-text-selectors -- deprecated usage
+ cy.findByText("Metabase Admin");
+ // eslint-disable-next-line no-unscoped-text-selectors -- deprecated usage
+ cy.findByText("Get help")
+ .parents("a")
+ .should("have.prop", "href")
+ .and(
+ "match",
+ /^https:\/\/www\.metabase\.com\/help\?utm_source=in-product&utm_medium=troubleshooting&utm_campaign=help&instance_version=v(?:(?!diag=).)+$/,
+ );
+ });
+});
+
+describe("scenarios > admin > tools > help (EE)", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("pro-self-hosted");
+ });
+
+ it("should link `Get Help` to help-premium", () => {
+ cy.visit("/admin/tools/help");
+
+ cy.findByTestId("admin-layout-content")
+ .findByText("Get help")
+ .parents("a")
+ .should("have.prop", "href")
+ .and(
+ "match",
+ /^https:\/\/www\.metabase\.com\/help-premium\?utm_source=in-product&utm_medium=troubleshooting&utm_campaign=help&instance_version=v.+&diag=%7B.+%7D$/,
+ );
+ });
+});
+
+describe("scenarios > admin > tools > help > helping hand", () => {
+ const executeCreateGrantAccessFlow = (
+ durationOption?: "96 hours" | "48 hours" | "24 hours",
+ ticket?: string,
+ notes?: string,
+ ) => {
+ cy.findByTestId("access-grant-list-table").should("not.exist");
+ cy.button("Request a helping hand").should("be.enabled");
+ cy.button("Request a helping hand").click();
+
+ // Clicking the button should open the modal
+ cy.findByTestId("grant-access-modal").should("be.visible");
+ cy.findByTestId("grant-access-modal").within(() => {
+ cy.findByRole("heading", { name: "Grant Access?" }).should("be.visible");
+
+ if (durationOption) {
+ cy.findByLabelText(/Access duration/).click();
+ cy.document()
+ .findByRole("listbox")
+ .findByText(new RegExp(durationOption, "g"))
+ .click();
+ }
+
+ ticket && cy.findByLabelText("Ticket").type(ticket);
+ notes && cy.findByLabelText("Notes").type(notes);
+
+ cy.button("Grant access").click();
+ });
+
+ H.undoToast()
+ .findByText("Access grant created successfully")
+ .should("be.visible");
+ };
+
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.mockSessionPropertiesTokenFeatures({ "support-users": true });
+ });
+
+ it("should only display the `Helping hand` section for cloud customers", () => {
+ cy.visit("/admin/tools/help");
+ cy.findByRole("heading", { name: "Helping hand" }).should("not.exist");
+
+ H.activateToken("pro-self-hosted");
+ cy.reload();
+ cy.findByRole("heading", { name: "Helping hand" }).should("not.exist");
+
+ H.activateToken("starter");
+ cy.reload();
+ cy.findByRole("heading", { name: "Helping hand" }).should("be.visible");
+
+ H.activateToken("pro-cloud");
+ cy.reload();
+ cy.findByRole("heading", { name: "Helping hand" }).should("be.visible");
+ });
+
+ it("should allow creating a new access grant", () => {
+ H.activateToken("pro-cloud");
+ cy.visit("/admin/tools/help");
+
+ cy.findByTestId("access-grant-list-table").should("not.exist");
+
+ executeCreateGrantAccessFlow();
+
+ cy.findByTestId("access-grant-list-table").should("be.visible");
+ cy.findByTestId("access-grant-list-table").within(() => {
+ cy.get("tbody").findAllByRole("row").should("have.length", 1);
+ });
+ });
+
+ it("allow creating an access grant with a ticket number and custom notes", () => {
+ H.activateToken("pro-cloud");
+ cy.visit("/admin/tools/help");
+
+ executeCreateGrantAccessFlow("48 hours", "TICKET-999", "Custom notes");
+
+ cy.findByTestId("access-grant-list-table").within(() => {
+ cy.findByRole("cell", {
+ name: new RegExp(dayjs().format("MMM D, YYYY"), "g"),
+ }).should("be.visible");
+ cy.findByRole("cell", { name: /TICKET-999/ }).should("be.visible");
+ cy.findByRole("cell", { name: /Custom notes/ }).should("be.visible");
+ cy.findByText(/48 hours left/).should("be.visible");
+ });
+ });
+
+ it("should disallow more than one active access grant", () => {
+ H.activateToken("pro-cloud");
+ cy.visit("/admin/tools/help");
+
+ executeCreateGrantAccessFlow();
+
+ cy.button("Request a helping hand").should("be.disabled");
+ cy.button("Request a helping hand")
+ .siblings()
+ .findByText("You can only have one active request at a time")
+ .should("be.visible");
+ });
+
+ it("can revoke an access grant", () => {
+ H.activateToken("pro-cloud");
+ cy.visit("/admin/tools/help");
+
+ executeCreateGrantAccessFlow();
+ cy.button("Request a helping hand").should("be.disabled");
+
+ H.undoToast().icon("close").click();
+
+ cy.findByTestId("access-grant-list-table")
+ .button("Revoke access grant")
+ .click();
+ H.modal()
+ .findByRole("heading", { name: "Revoke access grant?" })
+ .should("be.visible");
+ H.modal().button("Revoke").click();
+ H.undoToast()
+ .findByText("Access grant revoked successfully")
+ .should("be.visible");
+
+ cy.button("Request a helping hand").should("be.enabled");
+ });
+});
diff --git a/e2e/test/scenarios/admin/troubleshooting.cy.spec.js b/e2e/test/scenarios/admin/tools/tools.cy.spec.ts
similarity index 90%
rename from e2e/test/scenarios/admin/troubleshooting.cy.spec.js
rename to e2e/test/scenarios/admin/tools/tools.cy.spec.ts
index 4643fe673e2..a7dec55f94f 100644
--- a/e2e/test/scenarios/admin/troubleshooting.cy.spec.js
+++ b/e2e/test/scenarios/admin/tools/tools.cy.spec.ts
@@ -1,52 +1,10 @@
import dayjs from "dayjs";
+import type { NativeQuestionDetails } from "e2e/support/helpers";
import { createMockTask } from "metabase-types/api/mocks";
const { H } = cy;
-describe("scenarios > admin > tools > help", { tags: "@OSS" }, () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should link `Get help` to help", () => {
- cy.visit("/admin/tools/help");
-
- // eslint-disable-next-line no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Metabase Admin");
- // eslint-disable-next-line no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Get help")
- .parents("a")
- .should("have.prop", "href")
- .and(
- "match",
- /^https:\/\/www\.metabase\.com\/help\?utm_source=in-product&utm_medium=troubleshooting&utm_campaign=help&instance_version=v(?:(?!diag=).)+$/,
- );
- });
-});
-
-describe("scenarios > admin > tools > help (EE)", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- H.activateToken("pro-self-hosted");
- });
-
- it("should link `Get Help` to help-premium", () => {
- cy.visit("/admin/tools/help");
-
- cy.findByTestId("admin-layout-content")
- .findByText("Get help")
- .parents("a")
- .should("have.prop", "href")
- .and(
- "match",
- /^https:\/\/www\.metabase\.com\/help-premium\?utm_source=in-product&utm_medium=troubleshooting&utm_campaign=help&instance_version=v.+&diag=%7B.+%7D$/,
- );
- });
-});
-
describe("issue 14636", () => {
const total = 57;
const limit = 50;
@@ -56,7 +14,7 @@ describe("issue 14636", () => {
* @param {(0|1)} payload.page
* @param {("first"|"second")} payload.alias
*/
- function stubPageResponses({ page, alias }) {
+ function stubPageResponses({ page, alias }: { page: number; alias: string }) {
const offset = page * limit;
cy.intercept(
@@ -80,7 +38,7 @@ describe("issue 14636", () => {
* @param {(0|1)} page
* @returns Row[]
*/
- function stubPageRows(page) {
+ function stubPageRows(page: number) {
// There rows details don't really matter.
// We're generating two types of rows. One for each page.
const tasks = ["field values scanning", "analyze"];
@@ -103,11 +61,10 @@ describe("issue 14636", () => {
const pageRows = [limit, total - limit];
const length = pageRows[page];
- const stubbedRows = Array.from({ length }, (_, index) => ({
+ return Array.from({ length }, (_, index) => ({
...row,
id: index + 1,
}));
- return stubbedRows;
}
beforeEach(() => {
@@ -356,7 +313,7 @@ describe("scenarios > admin > tools > logs", () => {
* The formatted timestamp may vary depending on the timezone in which the test is run.
* This function makes test assertions timezone-agnostic.
*/
- function formatTimestamp(timestamp) {
+ function formatTimestamp(timestamp: string) {
return dayjs(timestamp).format();
}
});
@@ -381,7 +338,7 @@ describe("admin > tools > erroring questions ", () => {
display: "scalar",
};
- function fixQuestion(name) {
+ function fixQuestion(name: string) {
cy.findByTestId("visualization-root").findByText(name).click();
cy.findByText("Open Editor").click();
@@ -396,7 +353,7 @@ describe("admin > tools > erroring questions ", () => {
});
}
- function selectQuestion(name) {
+ function selectQuestion(name: string) {
cy.findByText(name)
.closest("tr")
.within(() => {
@@ -435,7 +392,7 @@ describe("admin > tools > erroring questions ", () => {
describe("with the existing broken questions", () => {
beforeEach(() => {
- H.createNativeQuestion(brokenQuestionDetails, {
+ H.createNativeQuestion(brokenQuestionDetails as NativeQuestionDetails, {
loadMetadata: true,
});
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index 5cfafb93c38..d5c57da6909 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -36,6 +36,7 @@
[metabase-enterprise.semantic-search.api]
[metabase-enterprise.serialization.api]
[metabase-enterprise.stale.api]
+ [metabase-enterprise.support-access-grants.api]
[metabase-enterprise.transforms-python.api]
[metabase-enterprise.transforms.api]
[metabase-enterprise.upload-management.api]
@@ -72,6 +73,7 @@
:upload-management (deferred-tru "Upload Management")
:database-routing (deferred-tru "Database Routing")
:cloud-custom-smtp (deferred-tru "Custom SMTP")
+ :support-users (deferred-tru "Support Users")
:transforms-python (deferred-tru "Transforms Python")})
(defn- premium-handler [handler required-feature]
@@ -128,6 +130,7 @@
"/semantic-search" (premium-handler metabase-enterprise.semantic-search.api/routes :semantic-search)
"/serialization" (premium-handler metabase-enterprise.serialization.api/routes :serialization)
"/stale" (premium-handler metabase-enterprise.stale.api/routes :collection-cleanup)
+ "/support-access-grant" (premium-handler metabase-enterprise.support-access-grants.api/routes :support-users)
"/transform" (premium-handler metabase-enterprise.transforms.api/routes :transforms)
"/transform-job" (premium-handler metabase-enterprise.transforms.api/transform-job-routes :transforms)
"/transform-tag" (premium-handler metabase-enterprise.transforms.api/transform-tag-routes :transforms)
diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.clj
index 7b426d5ea44..394902e55ec 100644
--- a/enterprise/backend/src/metabase_enterprise/core/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj
@@ -22,5 +22,6 @@
[metabase-enterprise.semantic-search.init]
[metabase-enterprise.sso.init]
[metabase-enterprise.stale.init]
+ [metabase-enterprise.support-access-grants.init]
[metabase-enterprise.transforms-python.init]
[metabase-enterprise.transforms.init]))
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index 702638b48f5..133d748ace5 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -106,6 +106,7 @@
"Secret"
"SemanticSearchTokenTracking"
"Session"
+ "SupportAccessGrantLog"
"TaskHistory"
"TransformJobRun"
"TransformRun"
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/api.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/api.clj
new file mode 100644
index 00000000000..37d3688dad8
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/api.clj
@@ -0,0 +1,72 @@
+(ns metabase-enterprise.support-access-grants.api
+ "API endpoints for managing support access grants."
+ (:require
+ [metabase-enterprise.support-access-grants.core :as grants]
+ [metabase-enterprise.support-access-grants.schema :as grants.schema]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.request.core :as request]
+ [metabase.util.malli.schema :as ms]))
+
+(api.macros/defendpoint :post "/"
+ :- ::grants.schema/grant-response
+ "Create a new support access grant.
+
+ Requires superuser permissions. Only one active grant can exist at a time."
+ [_route-params
+ _query-params
+ body :- ::grants.schema/create-grant-request]
+ (api/check-superuser)
+ (api/create-check :model/SupportAccessGrantLog body)
+ (grants/create-grant! api/*current-user-id*
+ (:grant_duration_minutes body)
+ (:ticket_number body)
+ (:notes body)))
+
+(api.macros/defendpoint :put "/:id/revoke"
+ :- ::grants.schema/grant-response
+ "Revoke an existing support access grant.
+
+ Requires superuser permissions. Any admin can revoke any grant."
+ [{id :id} :- [:map [:id ms/PositiveInt]]]
+ (api/check-superuser)
+ (api/write-check :model/SupportAccessGrantLog id)
+ (grants/revoke-grant! api/*current-user-id* id))
+
+(api.macros/defendpoint :get "/"
+ :- ::grants.schema/list-grants-response
+ "List support access grants with optional filtering and pagination.
+
+ Requires superuser permissions.
+
+ Query parameters:
+ - ticket-number: Filter by ticket number
+ - user-id: Filter by user who created the grant
+ - include-revoked: Include revoked grants (default false)"
+ [_route-params
+ {:keys [ticket-number
+ user-id
+ include-revoked]} :- [:map
+ [:ticket-number {:optional true} [:maybe :string]]
+ [:user-id {:optional true} [:maybe ms/PositiveInt]]
+ [:include-revoked {:optional true} [:maybe :boolean]]]]
+ (api/check-superuser)
+ (grants/list-grants {:limit (request/limit)
+ :offset (request/offset)
+ :ticket-number ticket-number
+ :user-id user-id
+ :include-revoked include-revoked}))
+
+(api.macros/defendpoint :get "/current"
+ :- ::grants.schema/current-grant-response
+ "Get the currently active support access grant, if one exists.
+
+ Requires superuser permissions."
+ []
+ (api/check-superuser)
+ (grants/get-current-grant))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/support-access-grant` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj
new file mode 100644
index 00000000000..e4b8d078441
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj
@@ -0,0 +1,157 @@
+(ns metabase-enterprise.support-access-grants.core
+ "Core business logic for support access grant management."
+ (:require
+ [java-time.api :as t]
+ [metabase-enterprise.support-access-grants.models.support-access-grant-log :as sag.model]
+ [metabase-enterprise.support-access-grants.provider :as sag.provider]
+ [metabase-enterprise.support-access-grants.settings :as sag.settings]
+ [metabase.events.core :as events]
+ [metabase.system.core :as system]
+ [metabase.util.i18n :refer [tru]]
+ [toucan2.core :as t2]))
+
+(defn- active-grant-exists?
+ "Check if there is an active (non-revoked, non-expired) grant."
+ []
+ (let [now (t/instant)]
+ (t2/exists? :model/SupportAccessGrantLog
+ :revoked_at nil
+ :grant_end_timestamp [:> now])))
+
+(defn create-grant!
+ "Create a new support access grant.
+
+ Parameters:
+ - user-id: ID of the user creating the grant
+ - grant-duration-minutes: Duration in minutes (max 10080 = 7 days)
+ - ticket-number: The support ticket number (string)
+ - notes: Additional information (string)
+
+ Returns the created grant record with an optional :token field if a support user was found or created.
+
+ Throws if an active grant already exists."
+ [user-id grant-duration-minutes ticket-number notes]
+ (when (active-grant-exists?)
+ (throw (ex-info (tru "Cannot create grant: an active grant already exists")
+ {:status-code 409})))
+ (t2/with-transaction [_]
+ (let [now (t/instant)
+ grant-end (t/plus now (t/minutes grant-duration-minutes))
+ grant-record {:user_id user-id
+ :ticket_number ticket-number
+ :notes notes
+ :grant_start_timestamp now
+ :grant_end_timestamp grant-end}
+ grant (-> (t2/insert-returning-instance! :model/SupportAccessGrantLog grant-record)
+ (t2/hydrate :user_info))
+ support-email (sag.settings/support-access-grant-email)
+ support-user (sag.model/fetch-or-create-support-user!)
+ token (sag.provider/create-support-access-reset! (:id support-user) grant)
+ password-reset-url (when token
+ (str (system/site-url) "/auth/reset_password/" token))]
+
+ ;; Publish event - the notification system handles email sending automatically
+ (when (and token password-reset-url)
+ (events/publish-event! :event/support-access-grant-created
+ {:support_email support-email
+ :ticket_number ticket-number
+ :duration_minutes grant-duration-minutes
+ :grant_end_time grant-end
+ :password_reset_url password-reset-url
+ :notes notes}))
+
+ ;; Return grant with token
+ (cond-> grant
+ token (assoc :token token)))))
+
+(defn revoke-grant!
+ "Revoke an existing support access grant.
+
+ Parameters:
+ - user-id: ID of the user revoking the grant
+ - grant-id: The ID of the grant to revoke
+
+ Returns the updated grant record.
+
+ Throws if:
+ - Grant doesn't exist
+ - Grant is already revoked"
+ [user-id grant-id]
+ (let [grant (t2/select-one :model/SupportAccessGrantLog :id grant-id)]
+ (when-not grant
+ (throw (ex-info (tru "Grant not found")
+ {:status-code 404})))
+ (when (:revoked_at grant)
+ (throw (ex-info (tru "Grant is already revoked")
+ {:status-code 400})))
+ (let [now (t/instant)]
+ (t2/update! :model/SupportAccessGrantLog grant-id
+ {:revoked_at now
+ :revoked_by_user_id user-id})
+ (-> (t2/select-one :model/SupportAccessGrantLog :id grant-id)
+ (t2/hydrate :user_info)))))
+
+(defn list-grants
+ "List support access grants with optional filtering and pagination.
+
+ Parameters:
+ - opts: Map with optional keys:
+ - :limit (default 50, max 100)
+ - :offset (default 0)
+ - :ticket-number (optional filter)
+ - :user-id (optional filter)
+ - :include-revoked (default false)
+
+ Returns a map with:
+ - :data - Vector of grant records
+ - :total - Total count of matching grants
+ - :limit - Applied limit
+ - :offset - Applied offset"
+ [{:keys [limit offset ticket-number user-id include-revoked]
+ :or {limit 50 offset 0 include-revoked false}}]
+
+ (let [limit (min (or limit 50) 100)
+ offset (or offset 0)
+ where-conditions (cond-> []
+ (not include-revoked)
+ (conj [:= :revoked_at nil])
+
+ ticket-number
+ (conj [:= :ticket_number ticket-number])
+
+ user-id
+ (conj [:= :user_id user-id]))
+ where-clause (when (seq where-conditions)
+ (if (= 1 (count where-conditions))
+ (first where-conditions)
+ (into [:and] where-conditions)))
+ grants (if where-clause
+ (t2/select :model/SupportAccessGrantLog
+ {:where where-clause
+ :limit limit
+ :offset offset
+ :order-by [[:created_at :desc]]})
+ (t2/select :model/SupportAccessGrantLog
+ {:limit limit
+ :offset offset
+ :order-by [[:created_at :desc]]}))
+ grants-with-user-name (t2/hydrate grants :user_info)
+ total (if where-clause
+ (t2/count :model/SupportAccessGrantLog {:where where-clause})
+ (t2/count :model/SupportAccessGrantLog))]
+ {:data grants-with-user-name
+ :total total
+ :limit limit
+ :offset offset}))
+
+(defn get-current-grant
+ "Get the currently active support access grant, if one exists.
+
+ Returns the active grant record or nil if no active grant exists."
+ []
+ (some-> (t2/select-one :model/SupportAccessGrantLog
+ {:where [:and [:= :revoked_at nil]
+ [:> :grant_end_timestamp :%now]]
+ :order-by [[:created_at :desc]
+ [:id :desc]]})
+ (t2/hydrate :user_info)))
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/events.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/events.clj
new file mode 100644
index 00000000000..e999d6264c3
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/events.clj
@@ -0,0 +1,4 @@
+(ns metabase-enterprise.support-access-grants.events)
+
+(derive ::event :metabase/event)
+(derive :event/support-access-grant-created ::event)
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/init.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/init.clj
new file mode 100644
index 00000000000..475c7f602b8
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/init.clj
@@ -0,0 +1,5 @@
+(ns metabase-enterprise.support-access-grants.init
+ (:require
+ [metabase-enterprise.support-access-grants.events]
+ [metabase-enterprise.support-access-grants.provider]
+ [metabase-enterprise.support-access-grants.settings]))
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
new file mode 100644
index 00000000000..0bac5ef98c1
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj
@@ -0,0 +1,51 @@
+(ns metabase-enterprise.support-access-grants.models.support-access-grant-log
+ "Model for support access grant log entries. Tracks temporary access grants for customer support."
+ (:require
+ [metabase-enterprise.support-access-grants.settings :as sag.settings]
+ [metabase.models.interface :as mi]
+ [metabase.util :as u]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/SupportAccessGrantLog
+ [_model]
+ :support_access_grant_log)
+
+(doto :model/SupportAccessGrantLog
+ (derive :metabase/model)
+ (derive ::mi/read-policy.superuser)
+ (derive ::mi/write-policy.superuser)
+ (derive ::mi/create-policy.superuser)
+ (derive :hook/timestamped?))
+
+(defn fetch-or-create-support-user!
+ "Fetch or Create the support user account from settings."
+ []
+ (or (t2/select-one :model/User :email (sag.settings/support-access-grant-email))
+ (t2/insert-returning-instance! :model/User
+ {:email (sag.settings/support-access-grant-email)
+ :first_name (sag.settings/support-access-grant-first-name)
+ :last_name (sag.settings/support-access-grant-last-name)
+ :password (str (random-uuid))})))
+
+(methodical/defmethod t2/batched-hydrate [:model/SupportAccessGrantLog :user_info]
+ [_model _k grants]
+ (let [user-ids (keep :user_id grants)
+ user-info (when (seq user-ids)
+ (t2/select-pk->fn #(select-keys % [:first_name :email])
+ [:model/User :id :first_name :email]
+ :id [:in user-ids]))]
+ (for [grant grants]
+ (let [user-info (get user-info (:user_id grant))]
+ (assoc grant
+ :user_name (:first_name user-info)
+ :user_email (:email user-info))))))
+
+(t2/define-after-update :model/SupportAccessGrantLog
+ [{revoked-at :revoked_at :as grant}]
+ (u/prog1 grant
+ (when revoked-at
+ (let [support-user-id (:id (fetch-or-create-support-user!))
+ auth-identity-ids (t2/select-pks-vec :model/AuthIdentity :user_id support-user-id)]
+ (t2/update! :model/AuthIdentity :id [:in auth-identity-ids] {:expires_at revoked-at})
+ (t2/delete! :model/Session :user_id support-user-id)))))
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj
new file mode 100644
index 00000000000..6d0effc2296
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj
@@ -0,0 +1,111 @@
+(ns metabase-enterprise.support-access-grants.provider
+ "Auth provider for support access grants with time-limited passwords.
+
+ This provider extends the emailed-secret provider to support time-limited passwords for customer support access.
+ When a support access grant is active, password reset tokens created for support access will track the grant's
+ end time and automatically set the user's password to expire when the grant expires."
+ (:require
+ [java-time.api :as t]
+ [metabase-enterprise.support-access-grants.schema :as schema]
+ [metabase.auth-identity.core :as auth-identity]
+ [metabase.util :as u]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.schema :as ms]
+ [metabase.util.password :as u.password]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(mu/defn create-support-access-reset-token-credentials
+ "Creates a credentials map for a support access password reset token with grant end time tracking.
+
+ Similar to [[emailed-secret/create-reset-token-credentials]], but adds a `:grant_ends_at` timestamp that
+ tracks when the support access grant expires. The token itself expires in 48 hours (or as specified), but
+ the grant end time is used to set the password expiration when the user logs in.
+
+ Parameters:
+ - `token`: The plaintext reset token that will be hashed using bcrypt
+ - `grant-ends-at`: The instant when the support access grant expires
+ - `expires-in-ms`: Optional token TTL in milliseconds (defaults to 48 hours)
+
+ Returns a map containing:
+ - `:token_hash` - The bcrypt hash of the token
+ - `:expires_at` - When the token itself expires
+ - `:grant_ends_at` - When the support access grant expires
+ - `:consumed_at` - Initially nil, set when token is used"
+ [token :- :string
+ grant-ends-at :- ::schema/timestamp
+ & {:keys [expires-in-ms]
+ :or {expires-in-ms (* 48 60 60 1000)}}]
+ {:token_hash (u.password/hash-bcrypt token)
+ :expires_at (t/plus (t/instant) (t/millis expires-in-ms))
+ :grant_ends_at grant-ends-at
+ :consumed_at nil})
+
+(mu/defn create-support-access-reset!
+ "Creates or updates a support access password reset token for a user and returns the plaintext token.
+
+ Generates a new reset token for the user identified by `user-id` and stores it in an [[AuthIdentity]] record with
+ provider `support-access-grant`. The token includes the support access grant's end time, which will be used to set
+ the user's password expiration when they log in.
+
+ Parameters:
+ - `user-id`: The ID of the user to create a password reset token for
+ - `grant`: The support access grant map containing at minimum `:grant_end_timestamp`
+
+ Throws an exception if:
+ - The grant is nil
+ - The grant has expired
+
+ Returns the plaintext token string that should be sent to the user via email."
+ [user-id :- ms/PositiveInt
+ grant :- [:maybe [:map [:grant_end_timestamp ::schema/timestamp]]]]
+ (when-not grant
+ (throw (ex-info "Cannot create support access reset token: no grant provided"
+ {:status-code 400})))
+ (let [grant-ends-at (:grant_end_timestamp grant)]
+ (when (t/before? grant-ends-at (t/offset-date-time))
+ (throw (ex-info "Cannot create support access reset token: grant has expired"
+ {:status-code 400})))
+ (u/prog1 (auth-identity/generate-reset-token user-id)
+ (t2/with-transaction [_]
+ (let [user (t2/select-one :model/User user-id)
+ auth-identity {:user_id user-id
+ :provider "support-access-grant"
+ :provider_id (:email user)
+ :expires_at grant-ends-at
+ :credentials (create-support-access-reset-token-credentials <> grant-ends-at)
+ :metadata (auth-identity/create-reset-token-metadata (:email user))}]
+ (if-let [auth-identity-id (t2/select-one-pk :model/AuthIdentity :user_id user-id :provider "support-access-grant")]
+ (t2/update! :model/AuthIdentity auth-identity-id auth-identity)
+ (t2/insert! :model/AuthIdentity auth-identity)))))))
+
+;;; -------------------------------------------------- Provider Registration --------------------------------------------------
+
+;; Register support-access-grant provider in the hierarchy, deriving from emailed-secret
+(derive :provider/support-access-grant :provider/emailed-secret)
+
+;;; -------------------------------------------------- Multimethod Implementations --------------------------------------------------
+
+(methodical/defmethod auth-identity/login! :after :provider/support-access-grant
+ "Completes the support access password reset process after successful authentication.
+
+ After a successful support access authentication, this method:
+ - Marks the reset token as consumed in the [[AuthIdentity]]
+ - Updates the user's password
+ - Sets the user's expires_at based on the grant's end time
+
+ All operations are performed within a transaction to ensure consistency."
+ [_provider {:keys [user password auth-identity] :as result}]
+ (when (:success? result)
+ (let [grant-ends-at (get-in auth-identity [:credentials :grant_ends_at])]
+ (log/infof "Setting password expiration for user %s to %s based on support access grant"
+ (:id user) grant-ends-at)
+ (t2/with-transaction [_]
+ (t2/update! :model/AuthIdentity (:id auth-identity) (auth-identity/mark-token-consumed auth-identity))
+ (t2/update! :model/AuthIdentity :user_id (:id user) :provider "password"
+ {:expires_at grant-ends-at
+ :credentials {:plaintext_password password}}))))
+ result)
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/schema.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/schema.clj
new file mode 100644
index 00000000000..ebe2dbd560c
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/schema.clj
@@ -0,0 +1,55 @@
+(ns metabase-enterprise.support-access-grants.schema
+ "Malli schemas for support access grant API request and response bodies."
+ (:require
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]))
+
+;;; Maximum grant duration in minutes (7 days = 168 hours = 10080 minutes)
+(def max-grant-duration-minutes
+ "The maximum duration of an access grant in minutes"
+ 10080)
+
+(mr/def ::timestamp
+ [:or
+ (ms/InstanceOfClass java.time.OffsetDateTime)
+ (ms/InstanceOfClass java.time.ZonedDateTime)])
+
+;;; ------------------------------------------- Request Schemas -------------------------------------------
+
+(mr/def ::create-grant-request
+ "Schema for POST /api/ee/support-access-grants request body."
+ [:map
+ [:grant_duration_minutes [:int {:min 1 :max max-grant-duration-minutes}]]
+ [:ticket_number {:optional true} [:maybe [:string {:min 1 :max 100}]]]
+ [:notes {:optional true} [:maybe [:string {:min 1 :max 255}]]]])
+
+;;; ------------------------------------------- Response Schemas -------------------------------------------
+
+(mr/def ::grant-response
+ "Schema for a support access grant object in API responses."
+ [:map
+ [:id ms/PositiveInt]
+ [:user_id ms/PositiveInt]
+ [:user_name [:maybe :string]]
+ [:user_email [:maybe :string]]
+ [:ticket_number [:maybe :string]]
+ [:notes [:maybe :string]]
+ [:grant_start_timestamp ::timestamp]
+ [:grant_end_timestamp ::timestamp]
+ [:revoked_at [:maybe ::timestamp]]
+ [:revoked_by_user_id [:maybe ms/PositiveInt]]
+ [:created_at ::timestamp]
+ [:updated_at ::timestamp]
+ [:token {:optional true} [:maybe :string]]])
+
+(mr/def ::list-grants-response
+ "Schema for GET /api/ee/support-access-grants response (paginated list)."
+ [:map
+ [:data [:sequential ::grant-response]]
+ [:total nat-int?]
+ [:limit ms/PositiveInt]
+ [:offset nat-int?]])
+
+(mr/def ::current-grant-response
+ "Schema for GET /api/ee/support-access-grants/current response."
+ [:maybe ::grant-response])
diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/settings.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/settings.clj
new file mode 100644
index 00000000000..f29b171cf7d
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/settings.clj
@@ -0,0 +1,34 @@
+(ns metabase-enterprise.support-access-grants.settings
+ (:require
+ [metabase.settings.core :refer [defsetting]]
+ [metabase.util.i18n :refer [deferred-tru]]))
+
+(defsetting support-access-grant-email
+ (deferred-tru "Email to grant temporary access to for support")
+ :type :string
+ :visibility :internal
+ :export? false
+ :setter :none
+ :audit :never
+ :doc false
+ :default "[email protected]")
+
+(defsetting support-access-grant-first-name
+ (deferred-tru "First name of the support user")
+ :type :string
+ :visibility :internal
+ :export? false
+ :setter :none
+ :audit :never
+ :doc false
+ :default "Support")
+
+(defsetting support-access-grant-last-name
+ (deferred-tru "Last name of the support user")
+ :type :string
+ :visibility :internal
+ :export? false
+ :setter :none
+ :audit :never
+ :doc false
+ :default "User")
diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
index 74d4650f666..032b0a101fa 100644
--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
@@ -49,6 +49,7 @@
:sso-jwt
:sso-ldap
:sso-saml
+ :support-users
:transforms
:transforms-python
:upload-management
@@ -95,6 +96,7 @@
:sso_jwt true
:sso_ldap true
:sso_saml true
+ :support-users true
:table_data_editing false
:transforms true
:transforms-python true
diff --git a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
index d14652d4825..2f19d99cf9c 100644
--- a/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/models/entity_id_test.clj
@@ -87,6 +87,7 @@
:model/SearchIndexMetadata
:model/Secret
:model/Session
+ :model/SupportAccessGrantLog
:model/TaskHistory
:model/TimelineEvent
;; TODO we should remove these models from here once serialization is supported
diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/api_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/api_test.clj
new file mode 100644
index 00000000000..04aa78b1702
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/api_test.clj
@@ -0,0 +1,205 @@
+(ns metabase-enterprise.support-access-grants.api-test
+ "Tests for /api/ee/support-access-grant endpoints."
+ (:require
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(use-fixtures :each (fn [f] (mt/with-premium-features #{:support-users}
+ (f))))
+
+(deftest api-requires-support-users-feature-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (mt/with-premium-features #{}
+ (is (=? {:message "Support Users is a paid feature not currently available to your instance. Please upgrade to use it. Learn more at metabase.com/upgrade/"}
+ (mt/user-http-request :crowberto :post 402 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-12345"
+ :grant_duration_minutes 240}))))))
+
+(deftest create-grant-returns-grant-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [response (mt/user-http-request :crowberto :post 200 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-12345"
+ :grant_duration_minutes 240})]
+ (is (some? response))
+ (is (= (mt/user->id :crowberto) (:user_id response)))
+ (is (= "SUPPORT-12345" (:ticket_number response)))
+ (is (some? (:grant_start_timestamp response)))
+ (is (some? (:grant_end_timestamp response)))
+ (is (nil? (:revoked_at response)))
+ (is (nil? (:revoked_by_user_id response))))))
+
+(deftest create-grant-fails-for-non-admin-test
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-12346"
+ :grant_duration_minutes 240}))))
+
+(deftest create-grant-fails-when-active-grant-exists-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (mt/user-http-request :crowberto :post 200 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-12347"
+ :grant_duration_minutes 240})
+ (is (= "Cannot create grant: an active grant already exists"
+ (mt/user-http-request :crowberto :post 409 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-12348"
+ :grant_duration_minutes 240})))))
+
+(deftest create-grant-validates-max-duration-test
+ (mt/user-http-request :crowberto :post 400 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-12349"
+ :grant_duration_minutes 10081}))
+
+(deftest create-grant-requires-duration-test
+ (mt/user-http-request :crowberto :post 400 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-12350"}))
+
+(deftest revoke-grant-sets-revoked-fields-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [grant (mt/user-http-request :crowberto :post 200 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-22345"
+ :grant_duration_minutes 240})
+ grant-id (:id grant)
+ revoked (mt/user-http-request :crowberto :put 200 (format "ee/support-access-grant/%d/revoke" grant-id))]
+ (is (some? revoked))
+ (is (some? (:revoked_at revoked)))
+ (is (= (mt/user->id :crowberto) (:revoked_by_user_id revoked))))))
+
+(deftest revoke-grant-fails-for-non-admin-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [grant (mt/user-http-request :crowberto :post 200 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-22347"
+ :grant_duration_minutes 240})
+ grant-id (:id grant)]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :lucky :put 403 (format "ee/support-access-grant/%d/revoke" grant-id)))))))
+
+(deftest revoke-grant-fails-for-nonexistent-grant-test
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :put 404 "ee/support-access-grant/999999/revoke"))))
+
+(deftest revoke-grant-fails-for-already-revoked-grant-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [grant (mt/user-http-request :crowberto :post 200 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-22348"
+ :grant_duration_minutes 240})
+ grant-id (:id grant)]
+ (mt/user-http-request :crowberto :put 200 (format "ee/support-access-grant/%d/revoke" grant-id))
+ (is (= "Grant is already revoked"
+ (mt/user-http-request :crowberto :put 400 (format "ee/support-access-grant/%d/revoke" grant-id)))))))
+
+(deftest list-grants-returns-paginated-results-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (dotimes [i 3]
+ (t2/insert! :model/SupportAccessGrantLog
+ {:user_id (mt/user->id :crowberto)
+ :ticket_number (str "SUPPORT-3" i)
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/minutes 240))}))
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/support-access-grant")]
+ (is (map? response))
+ (is (contains? response :data))
+ (is (contains? response :total))
+ (is (contains? response :limit))
+ (is (contains? response :offset))
+ (is (= 50 (:limit response)))
+ (is (= 0 (:offset response)))
+ (is (>= (count (:data response)) 3)))))
+
+(deftest list-grants-fails-for-non-admin-test
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/support-access-grant"))))
+
+(deftest list-grants-respects-pagination-parameters-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/support-access-grant"
+ :limit 2
+ :offset 1)]
+ (is (= 2 (:limit response)))
+ (is (= 1 (:offset response))))))
+
+(deftest list-grants-filters-by-ticket-number-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket "SUPPORT-FILTER-TEST"]
+ (t2/insert! :model/SupportAccessGrantLog
+ {:user_id user-id
+ :ticket_number ticket
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/minutes 240))})
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/support-access-grant"
+ :ticket-number ticket)]
+ (is (= 1 (count (:data response))))
+ (is (= ticket (:ticket_number (first (:data response))))))))))
+
+(deftest list-grants-filters-by-user-id-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (t2/insert! :model/SupportAccessGrantLog
+ {:user_id user-id
+ :ticket_number "SUPPORT-USER-FILTER"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/minutes 240))})
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/support-access-grant"
+ :user-id user-id)]
+ (is (>= (count (:data response)) 1))
+ (is (every? #(= user-id (:user_id %)) (:data response)))))))
+
+(deftest list-grants-excludes-revoked-by-default-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [now (t/instant)]
+ (t2/insert! :model/SupportAccessGrantLog
+ {:user_id user-id
+ :ticket_number "SUPPORT-REVOKED"
+ :grant_start_timestamp now
+ :grant_end_timestamp (t/plus now (t/minutes 240))
+ :revoked_at now
+ :revoked_by_user_id user-id})
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/support-access-grant"
+ :ticket-number "SUPPORT-REVOKED")]
+ (is (= 0 (count (:data response)))))))))
+
+(deftest list-grants-includes-revoked-when-requested-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [now (t/instant)]
+ (t2/insert! :model/SupportAccessGrantLog
+ {:user_id user-id
+ :ticket_number "SUPPORT-REVOKED-2"
+ :grant_start_timestamp now
+ :grant_end_timestamp (t/plus now (t/minutes 240))
+ :revoked_at now
+ :revoked_by_user_id user-id})
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/support-access-grant"
+ :ticket-number "SUPPORT-REVOKED-2"
+ :include-revoked true)]
+ (is (= 1 (count (:data response)))))))))
+
+(deftest get-current-grant-returns-nil-when-no-grant-exists-test
+ (let [response (mt/user-http-request :crowberto :get 204 "ee/support-access-grant/current")]
+ (is (nil? response))))
+
+(deftest get-current-grant-returns-active-grant-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [grant (mt/user-http-request :crowberto :post 200 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-CURRENT"
+ :grant_duration_minutes 240})
+ current (mt/user-http-request :crowberto :get 200 "ee/support-access-grant/current")]
+ (is (some? current))
+ (is (= (:id grant) (:id current))))))
+
+(deftest get-current-grant-returns-nil-when-grant-revoked-test
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [grant (mt/user-http-request :crowberto :post 200 "ee/support-access-grant"
+ {:ticket_number "SUPPORT-CURRENT-2"
+ :grant_duration_minutes 240})
+ grant-id (:id grant)]
+ (mt/user-http-request :crowberto :put 200 (format "ee/support-access-grant/%d/revoke" grant-id))
+ (let [current (mt/user-http-request :crowberto :get 204 "ee/support-access-grant/current")]
+ (is (nil? current))))))
+
+(deftest get-current-grant-fails-for-non-admin-test
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/support-access-grant/current"))))
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
new file mode 100644
index 00000000000..efe90a065fa
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/core_test.clj
@@ -0,0 +1,359 @@
+(ns metabase-enterprise.support-access-grants.core-test
+ "Tests for support access grant core business logic."
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase-enterprise.support-access-grants.core :as grants]
+ [metabase-enterprise.support-access-grants.provider :as sag.provider]
+ [metabase-enterprise.support-access-grants.settings :as sag.settings]
+ [metabase.events.core :as events]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(deftest create-grant-returns-grant-test
+ (mt/with-temp [:model/User {user-id :id} {:first_name "Bobby" :email "[email protected]"}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket-number "SUPPORT-12345"
+ duration 240
+ notes "Some notes"
+ grant (grants/create-grant! user-id duration ticket-number notes)]
+ (is (some? grant))
+ (is (= user-id (:user_id grant)))
+ (is (= ticket-number (:ticket_number grant)))
+ (is (= notes (:notes grant)))
+ (is (= "Bobby" (:user_name grant)))
+ (is (= "[email protected]" (:user_email grant)))
+ (is (some? (:grant_start_timestamp grant)))
+ (is (some? (:grant_end_timestamp grant)))
+ (is (nil? (:revoked_at grant)))
+ (is (nil? (:revoked_by_user_id grant)))))))
+
+(deftest create-grant-with-nil-fields-test
+ (mt/with-temp [:model/User {user-id :id} {:first_name nil :email "[email protected]"}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [grant (grants/create-grant! user-id 240 nil nil)]
+ (is (some? grant))
+ (is (= user-id (:user_id grant)))
+ (is (nil? (:ticket_number grant)))
+ (is (nil? (:notes grant)))
+ (is (nil? (:user_name grant)))
+ (is (= "[email protected]" (:user_email grant)))
+ (is (some? (:grant_start_timestamp grant)))
+ (is (some? (:grant_end_timestamp grant)))
+ (is (nil? (:revoked_at grant)))
+ (is (nil? (:revoked_by_user_id grant)))))))
+
+(deftest create-grant-duration-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket-number "SUPPORT-12346"
+ duration 60
+ grant (grants/create-grant! user-id duration ticket-number nil)
+ start-time (:grant_start_timestamp grant)
+ end-time (:grant_end_timestamp grant)
+ duration-mins (t/as (t/duration start-time end-time) :minutes)]
+ (is (= duration duration-mins))))))
+
+(deftest create-grant-fails-when-active-grant-exists-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket-number "SUPPORT-12347"]
+ (grants/create-grant! user-id 240 ticket-number nil)
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Cannot create grant: an active grant already exists"
+ (grants/create-grant! user-id 120 "SUPPORT-12348" "Some notes")))))))
+
+(deftest create-grant-succeeds-after-revoked-grant-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket-number1 "SUPPORT-12351"
+ ticket-number2 "SUPPORT-12352"
+ grant1 (grants/create-grant! user-id 240 ticket-number1 nil)]
+ (grants/revoke-grant! user-id (:id grant1))
+ (let [grant2 (grants/create-grant! user-id 240 ticket-number2 nil)]
+ (is (some? grant2))
+ (is (not= (:id grant1) (:id grant2))))))))
+
+(deftest revoke-grant-sets-revoked-fields-test
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/User {revoker-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket-number "SUPPORT-22345"
+ grant (grants/create-grant! user-id 240 ticket-number nil)
+ revoked-grant (grants/revoke-grant! revoker-id (:id grant))]
+ (is (some? revoked-grant))
+ (is (some? (:revoked_at revoked-grant)))
+ (is (= revoker-id (:revoked_by_user_id revoked-grant)))))))
+
+(deftest revoke-grant-fails-for-nonexistent-grant-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Grant not found"
+ (grants/revoke-grant! user-id 999999)))))
+
+(deftest revoke-grant-fails-for-already-revoked-grant-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket-number "SUPPORT-22346"
+ grant (grants/create-grant! user-id 240 ticket-number nil)]
+ (grants/revoke-grant! user-id (:id grant))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Grant is already revoked"
+ (grants/revoke-grant! user-id (:id grant))))))))
+
+(deftest list-grants-default-pagination-test
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-30"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}
+ :model/SupportAccessGrantLog {grant-id :id} {:user_id user-id
+ :ticket_number "SUPPORT-31"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-32"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}]
+ (grants/revoke-grant! user-id grant-id)
+ (let [result (grants/list-grants {})]
+ (is (= 2 (count (:data result))) "Only non-revoked grants by default")
+ (is (= 2 (:total result)))
+ (is (= 50 (:limit result)))
+ (is (= 0 (:offset result))))))
+
+(deftest list-grants-includes-revoked-test
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-33345"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))
+ :revoked_at (t/instant)
+ :revoked_by_user_id user-id}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-33346"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}]
+ (let [result (grants/list-grants {:include-revoked true})]
+ (is (= 2 (count (:data result))))
+ (is (= 2 (:total result))))))
+
+(deftest list-grants-filters-by-ticket-number-test
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-44345"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-44346"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}]
+ (let [result (grants/list-grants {:ticket-number "SUPPORT-44345"})]
+ (is (= 1 (count (:data result))))
+ (is (= "SUPPORT-44345" (:ticket_number (first (:data result))))))))
+
+(deftest list-grants-filters-by-user-id-test
+ (mt/with-temp [:model/User {user1-id :id} {}
+ :model/User {user2-id :id} {}
+ :model/SupportAccessGrantLog _ {:user_id user1-id
+ :ticket_number "SUPPORT-55345"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}
+ :model/SupportAccessGrantLog _ {:user_id user2-id
+ :ticket_number "SUPPORT-55346"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}]
+ (let [result (grants/list-grants {:user-id user1-id})]
+ (is (= 1 (count (:data result))))
+ (is (= user1-id (:user_id (first (:data result))))))))
+
+(deftest list-grants-respects-limit-and-offset-test
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-60000"
+ :grant_start_timestamp (t/instant)
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-61000"
+ :grant_start_timestamp (t/plus (t/instant) (t/millis 10))
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-62000"
+ :grant_start_timestamp (t/plus (t/instant) (t/millis 20))
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-63000"
+ :grant_start_timestamp (t/plus (t/instant) (t/millis 30))
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}
+ :model/SupportAccessGrantLog _ {:user_id user-id
+ :ticket_number "SUPPORT-64000"
+ :grant_start_timestamp (t/plus (t/instant) (t/millis 40))
+ :grant_end_timestamp (t/plus (t/instant) (t/hours 240))}]
+ (let [result1 (grants/list-grants {:limit 2 :offset 0})
+ result2 (grants/list-grants {:limit 2 :offset 2})]
+ (is (= 2 (count (:data result1))))
+ (is (= 2 (count (:data result2))))
+ (is (not= (map :id (:data result1))
+ (map :id (:data result2)))
+ "Different pages should return different grants"))))
+
+(deftest list-grants-enforces-maximum-limit-test
+ (let [result (grants/list-grants {:limit 150})]
+ (is (= 100 (:limit result)))))
+
+(deftest get-current-grant-returns-nil-when-no-grant-exists-test
+ (is (nil? (grants/get-current-grant))))
+
+(deftest get-current-grant-returns-active-grant-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket-number "SUPPORT-77345"
+ notes "here some notes"
+ grant (grants/create-grant! user-id 240 ticket-number notes)
+ current (grants/get-current-grant)]
+ (is (some? current))
+ (is (= (:id grant) (:id current)))))))
+
+(deftest get-current-grant-returns-nil-when-grant-revoked-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (let [ticket-number "SUPPORT-77346"
+ notes "here some notes"
+ grant (grants/create-grant! user-id 240 ticket-number notes)]
+ (grants/revoke-grant! user-id (:id grant))
+ (is (nil? (grants/get-current-grant)))))))
+
+(deftest get-current-grant-returns-most-recent-test
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog]
+ (grants/create-grant! user-id 240 "SUPPORT-77348" nil)
+ (let [now (t/instant)
+ grant-end (t/plus now (t/minutes 240))]
+ (t2/insert! :model/SupportAccessGrantLog
+ {:user_id user-id
+ :ticket_number "SUPPORT-77349"
+ :grant_start_timestamp (t/minus now (t/minutes 5))
+ :grant_end_timestamp grant-end}))
+ (let [current (grants/get-current-grant)]
+ (is (some? current))
+ (is (= "SUPPORT-77349" (:ticket_number current))
+ "Returns most recent grant when multiple active grants exist")))))
+
+(deftest create-grant-creates-token-for-support-user-test
+ (testing "create-grant! creates a token when support user exists"
+ (let [support-email "[email protected]"]
+ (mt/with-temp [:model/User {creator-id :id} {}
+ :model/User {support-user-id :id} {:email support-email}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity]
+ (mt/with-temp-env-var-value! [mb-support-access-grant-email support-email]
+ (with-redefs [sag.settings/support-access-grant-email (constantly support-email)]
+ (let [grant (grants/create-grant! creator-id 240 "SUPPORT-TOKEN-1" "test notes")]
+ (is (some? (:token grant)) "Token should be created")
+ (is (string? (:token grant)) "Token should be a string")
+ (is (re-matches (re-pattern (str support-user-id "_.+")) (:token grant))
+ "Token should start with support user ID")
+ (let [auth-identity (t2/select-one :model/AuthIdentity
+ :user_id support-user-id
+ :provider "support-access-grant")]
+ (is (some? auth-identity) "AuthIdentity should be created for support user")
+ (is (= "support-access-grant" (:provider auth-identity))))))))))))
+
+(deftest create-grant-creates-support-user-if-not-exists-test
+ (testing "create-grant! creates a support user if one doesn't exist"
+ (let [support-email "[email protected]"
+ support-first-name "Support"
+ support-last-name "User"]
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
+ (with-redefs [sag.settings/support-access-grant-email (constantly support-email)
+ sag.settings/support-access-grant-first-name (constantly support-first-name)
+ sag.settings/support-access-grant-last-name (constantly support-last-name)]
+ (let [grant (grants/create-grant! creator-id 240 "SUPPORT-CREATE-USER" "test notes")
+ created-user (t2/select-one :model/User :email support-email)]
+ (is (some? created-user) "Support user should be created")
+ (is (= support-email (:email created-user)))
+ (is (= support-first-name (:first_name created-user)))
+ (is (= support-last-name (:last_name created-user)))
+ (is (some? (:token grant)) "Token should be created for the new support user")
+ (is (string? (:token grant)))
+ (let [auth-identity (t2/select-one :model/AuthIdentity
+ :user_id (:id created-user)
+ :provider "support-access-grant")]
+ (is (some? auth-identity) "AuthIdentity should be created for new support user")))))))))
+
+(deftest create-grant-publishes-event-test
+ (testing "Creating a grant publishes :event/support-access-grant-created event"
+ (let [support-email "[email protected]"
+ published-events (atom [])]
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
+ (with-redefs [sag.settings/support-access-grant-email (constantly support-email)
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")
+ events/publish-event! (fn [topic payload]
+ (swap! published-events conj [topic payload]))]
+ (let [grant (grants/create-grant! creator-id 60 "TICKET-123" "Test notes")
+ our-events (filter (fn [[topic _]] (= topic :event/support-access-grant-created)) @published-events)]
+ (is (some? (:token grant)) "Token should be created")
+ (testing "Event was published"
+ (is (= 1 (count our-events)) "Exactly one support-access-grant-created event should be published")
+ (let [[topic payload] (first our-events)]
+ (is (= :event/support-access-grant-created topic) "Event topic should be correct")
+ (is (= support-email (:support_email payload)) "Payload should contain support email")
+ (is (= "TICKET-123" (:ticket_number payload)) "Payload should contain ticket number")
+ (is (= "Test notes" (:notes payload)) "Payload should contain notes")
+ (is (= 60 (:duration_minutes payload)) "Payload should contain duration")
+ (is (some? (:grant_end_time payload)) "Payload should contain grant end time")
+ (is (some? (:password_reset_url payload)) "Payload should contain password reset URL")
+ (is (str/includes? (:password_reset_url payload) "reset_password")
+ "Password reset URL should have correct path"))))))))))
+
+(deftest create-grant-does-not-publish-event-when-no-token-test
+ (testing "No event is published when token creation fails"
+ (let [support-email "[email protected]"
+ published-events (atom [])]
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
+ (with-redefs [sag.settings/support-access-grant-email (constantly support-email)
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")
+ sag.provider/create-support-access-reset! (constantly nil)
+ events/publish-event! (fn [topic payload]
+ (swap! published-events conj [topic payload]))]
+ (let [grant (grants/create-grant! creator-id 60 "TICKET-456" "Test notes")
+ our-events (filter (fn [[topic _]] (= topic :event/support-access-grant-created)) @published-events)]
+ (is (nil? (:token grant)) "Token should not be created")
+ (is (zero? (count our-events)) "No support-access-grant-created event should be published when token is nil"))))))))
+
+(deftest create-grant-event-payload-has-correct-data-test
+ (testing "Event payload contains all required fields with correct values"
+ (let [support-email "[email protected]"
+ ticket-number "TICKET-789"
+ duration-minutes 120
+ published-events (atom [])]
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
+ (with-redefs [sag.settings/support-access-grant-email (constantly support-email)
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")
+ events/publish-event! (fn [topic payload]
+ (swap! published-events conj [topic payload]))]
+ (let [grant-before (t/instant)
+ _ (grants/create-grant! creator-id duration-minutes ticket-number "Test notes")
+ grant-after (t/instant)
+ our-events (filter (fn [[topic _]] (= topic :event/support-access-grant-created)) @published-events)
+ [_topic payload] (first our-events)
+ grant-end-time (:grant_end_time payload)]
+ (is (some? grant-end-time) "Grant end time should be present")
+ (is (t/after? grant-end-time grant-before) "Grant end time should be after creation started")
+ (is (t/after? grant-end-time grant-after) "Grant end time should be in the future")
+ (let [expected-end (t/plus grant-before (t/minutes duration-minutes))
+ diff-seconds (t/as (t/duration expected-end grant-end-time) :seconds)]
+ (is (< (Math/abs ^long diff-seconds) 2)
+ "Grant end time should be approximately duration_minutes in the future")))))))))
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
new file mode 100644
index 00000000000..36dfcc11e4b
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/models/support_access_grant_log_test.clj
@@ -0,0 +1,71 @@
+(ns metabase-enterprise.support-access-grants.models.support-access-grant-log-test
+ "Tests for SupportAccessGrantLog model, particularly revocation behavior."
+ (:require
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase-enterprise.support-access-grants.models.support-access-grant-log :as sag-log]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(deftest no-revoke-when-revoked-at-nil-test
+ (testing "Auth identities and sessions are NOT affected when revoked_at remains nil"
+ (mt/with-model-cleanup [:model/User]
+ (mt/with-temp-env-var-value! [:mb-support-access-grant-email "[email protected]"]
+ (let [support-user (sag-log/fetch-or-create-support-user!)
+ support-user-id (:id support-user)]
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/SupportAccessGrantLog {grant-id :id}
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Test grant"
+ :grant_start_timestamp (t/offset-date-time)
+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}
+ :model/Session {session-id :id}
+ {:id "test-id-0"
+ :user_id support-user-id
+ :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? (:expires_at (t2/select-one :model/AuthIdentity :id support-user-id)))
+ "Auth identity expires_at should remain unchanged")))))))
+
+(deftest revoke-grant-only-affects-support-user-test
+ (testing "Revoking a grant only affects the support user, not other users"
+ (mt/with-temp-env-var-value! [:mb-support-access-grant-email "[email protected]"]
+ (mt/with-model-cleanup [:model/User]
+ (let [support-user (sag-log/fetch-or-create-support-user!)
+ support-user-id (:id support-user)]
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/User {other-user-id :id} {}
+ :model/SupportAccessGrantLog {grant-id :id}
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Test grant"
+ :grant_start_timestamp (t/offset-date-time)
+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}
+ :model/Session {support-session-id :id}
+ {:id "test-id-0"
+ :user_id support-user-id
+ :session_key "test1"
+ :auth_identity_id (t2/select-one-pk :model/AuthIdentity :user_id support-user-id)}
+ :model/Session {other-session-id :id}
+ {:id "test-id-1"
+ :user_id other-user-id
+ :session_key "test2"
+ :auth_identity_id (t2/select-one-pk :model/AuthIdentity :user_id other-user-id)}]
+ (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")
+ (is (some? (:expires_at (t2/select-one :model/AuthIdentity :user_id support-user-id)))
+ "Support user auth identity should have expires_at set")
+ (is (nil? (:expires_at (t2/select-one :model/AuthIdentity :user_id other-user-id)))
+ "Other user auth identity should remain unchanged"))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/support_access_grants/provider_test.clj b/enterprise/backend/test/metabase_enterprise/support_access_grants/provider_test.clj
new file mode 100644
index 00000000000..2bc3f0a9b77
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/provider_test.clj
@@ -0,0 +1,170 @@
+(ns metabase-enterprise.support-access-grants.provider-test
+ "Tests for support access grant provider functionality."
+ (:require
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase-enterprise.support-access-grants.provider :as sag.provider]
+ [metabase.auth-identity.provider :as provider]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(deftest create-support-access-reset-with-active-grant-test
+ (testing "create-support-access-reset! creates AuthIdentity when active grant exists"
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/User {user-id :id email :email} {}
+ :model/SupportAccessGrantLog {grant-end :grant_end_timestamp :as grant}
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Test grant"
+ :grant_start_timestamp (t/offset-date-time)
+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}]
+ (let [token (sag.provider/create-support-access-reset! user-id grant)]
+ (is (string? token))
+ (is (re-matches (re-pattern (str user-id "_.+")) token))
+ (let [auth-identity (t2/select-one :model/AuthIdentity
+ :user_id user-id
+ :provider "support-access-grant")]
+ (is (some? auth-identity))
+ (is (= "support-access-grant" (:provider auth-identity)))
+ (is (= user-id (:user_id auth-identity)))
+ (is (= email (:provider_id auth-identity)))
+ (is (contains? (:credentials auth-identity) :token_hash))
+ (is (contains? (:credentials auth-identity) :expires_at))
+ (is (contains? (:credentials auth-identity) :grant_ends_at))
+ (is (nil? (get-in auth-identity [:credentials :consumed_at])))
+ (is (= email (get-in auth-identity [:metadata :email])))
+ (is (= (str grant-end) (str (get-in auth-identity [:credentials :grant_ends_at])))))))))
+
+(deftest create-support-access-reset-without-active-grant-test
+ (testing "create-support-access-reset! throws when no grant provided"
+ (mt/with-temp [:model/User {user-id :id} {}]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"no grant provided"
+ (sag.provider/create-support-access-reset! user-id nil))))))
+
+(deftest create-support-access-reset-with-expired-grant-test
+ (testing "create-support-access-reset! throws when grant has expired"
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/User {user-id :id} {}
+ :model/SupportAccessGrantLog grant
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Expired grant"
+ :grant_start_timestamp (t/minus (t/offset-date-time) (t/hours 2))
+ :grant_end_timestamp (t/minus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"grant has expired"
+ (sag.provider/create-support-access-reset! user-id grant))))))
+
+(deftest create-support-access-reset-updates-existing-auth-identity-test
+ (testing "create-support-access-reset! updates existing AuthIdentity instead of creating duplicate"
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/User {user-id :id} {}
+ :model/SupportAccessGrantLog grant
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Test grant"
+ :grant_start_timestamp (t/offset-date-time)
+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}]
+ (let [first-token (sag.provider/create-support-access-reset! user-id grant)
+ first-auth-identity (t2/select-one :model/AuthIdentity
+ :user_id user-id
+ :provider "support-access-grant")
+ second-token (sag.provider/create-support-access-reset! user-id grant)
+ auth-identities (t2/select :model/AuthIdentity
+ :user_id user-id
+ :provider "support-access-grant")]
+ (is (= 1 (count auth-identities)))
+ (is (not= first-token second-token))
+ (is (= (:id first-auth-identity) (:id (first auth-identities))))))))
+
+(deftest support-access-login-sets-expires-at-test
+ (testing "login! :after sets expires_at on password auth-identity based on grant_ends_at"
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/User {user-id :id} {}
+ :model/SupportAccessGrantLog {grant-end :grant_end_timestamp :as grant}
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Test grant"
+ :grant_start_timestamp (t/offset-date-time)
+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}]
+
+ (let [token (sag.provider/create-support-access-reset! user-id grant)
+ auth-identity (t2/select-one :model/AuthIdentity
+ :user_id user-id
+ :provider "support-access-grant")
+ new-password "new-secure-password-123"]
+ (provider/login! :provider/support-access-grant {:token token
+ :password new-password})
+ (let [updated-user (t2/select-one [:model/User :password] :id user-id)
+ updated-pw-auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")
+ updated-auth-identity (t2/select-one :model/AuthIdentity :id (:id auth-identity) :provider "support-access-grant")
+ session (t2/select-one :model/Session :auth_identity_id (:id updated-auth-identity))]
+ (is (some? (:expires_at session)))
+ (is (= grant-end (:expires_at updated-pw-auth-identity)))
+ (is (= (get-in updated-pw-auth-identity [:credentials :password_hash]) (:password updated-user)))
+ (is (some? (get-in updated-auth-identity [:credentials :consumed_at]))))))))
+
+(deftest support-access-authenticate-inherits-from-emailed-secret-test
+ (testing "support-access-grant provider inherits authenticate from emailed-secret"
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/User {user-id :id} {}
+ :model/SupportAccessGrantLog grant
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Test grant"
+ :grant_start_timestamp (t/offset-date-time)
+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}]
+ (let [token (sag.provider/create-support-access-reset! user-id grant)
+ result (provider/authenticate :provider/support-access-grant {:token token})]
+ (is (true? (:success? result)))
+ (is (= user-id (:user-id result)))
+ (is (some? (:auth-identity result)))
+ (is (= "support-access-grant" (get-in result [:auth-identity :provider])))))))
+
+(deftest support-access-authenticate-rejects-invalid-token-test
+ (testing "authenticate rejects invalid token"
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/User {user-id :id} {}
+ :model/SupportAccessGrantLog grant
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Test grant"
+ :grant_start_timestamp (t/offset-date-time)
+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}]
+ (sag.provider/create-support-access-reset! user-id grant)
+ (let [result (provider/authenticate :provider/support-access-grant {:token (str user-id "_invalid-token")})]
+ (is (false? (:success? result)))
+ (is (= :invalid-token (:error result)))))))
+
+(deftest support-access-authenticate-rejects-expired-token-test
+ (testing "authenticate rejects expired token"
+ (mt/with-temp [:model/User {grant-creator-id :id} {}
+ :model/User {user-id :id} {}
+ :model/SupportAccessGrantLog grant
+ {:user_id grant-creator-id
+ :ticket_number "TEST-123"
+ :notes "Test grant"
+ :grant_start_timestamp (t/offset-date-time)
+ :grant_end_timestamp (t/plus (t/offset-date-time) (t/hours 1))
+ :revoked_at nil}]
+ (let [token (sag.provider/create-support-access-reset! user-id grant)
+ auth-identity (t2/select-one :model/AuthIdentity
+ :user_id user-id
+ :provider "support-access-grant")]
+ (t2/update! :model/AuthIdentity (:id auth-identity)
+ {:credentials (assoc (:credentials auth-identity)
+ :expires_at (t/minus (t/offset-date-time) (t/hours 1)))})
+ (let [result (provider/authenticate :provider/support-access-grant {:token token})]
+ (is (false? (:success? result)))
+ (is (= :expired-token (:error result))))))))
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
new file mode 100644
index 00000000000..314a0d8436b
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/support_access_grants/session_integration_test.clj
@@ -0,0 +1,168 @@
+(ns metabase-enterprise.support-access-grants.session-integration-test
+ "Tests for session API integration with support access grants.
+ Tests the fallback mechanism in /api/session/reset_password and /api/session/password_reset_token_valid
+ that tries support-access-grant provider first, then falls back to emailed-secret-password-reset."
+ (:require
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase-enterprise.support-access-grants.core :as grants]
+ [metabase-enterprise.support-access-grants.settings :as sag.settings]
+ [metabase.auth-identity.core :as auth-identity]
+ [metabase.session.api :as api.session]
+ [metabase.session.core :as session]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(use-fixtures :each (fn [f] (mt/with-premium-features #{:support-access-grants}
+ (with-redefs [api.session/throttling-disabled? true]
+ (f)))))
+
+(deftest reset-password-with-support-access-grant-token-test
+ (testing "POST /api/session/reset_password works with support access grant token"
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
+ (with-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
+ (let [grant (grants/create-grant! creator-id 60 "TICKET-123" "Test notes")
+ token (:token grant)
+ new-password "NewSecurePassword123!"]
+ (is (some? token) "Token should be created")
+ (testing "Can reset password with support access grant token"
+ (let [response (mt/client :post 200 "session/reset_password"
+ {:token token
+ :password new-password})]
+ (is (true? (:success response)) "Reset should succeed")
+ (is (some? (:session_id response)) "Should return session ID")
+ (testing "Support user can login with new password"
+ (let [login-result (auth-identity/login! :provider/password
+ {:email "[email protected]"
+ :password new-password
+ :device-info {:device_id "test-device"
+ :device_description "Test"
+ :embedded true
+ :ip_address "127.0.0.1"}})]
+ (is (:success? login-result) "Should be able to login with new password")))))))))))
+
+(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]"}]
+ (let [regular-token (auth-identity/create-password-reset! (:id user))
+ new-password "NewPassword123!"]
+ (testing "Regular password reset token still works with fallback"
+ (let [response (mt/client :post 200 "session/reset_password"
+ {:token regular-token
+ :password new-password})]
+ (is (true? (:success response)) "Reset should succeed with regular token")
+ (is (some? (:session_id response)) "Should return session ID")
+ (testing "User can login with new password"
+ (let [login-result (auth-identity/login! :provider/password
+ {:email "[email protected]"
+ :password new-password
+ :device-info {:device_id "test-device"
+ :device_description "Test"
+ :ip_address "127.0.0.1"
+ :embedded true}})]
+ (is (:success? login-result) "Should be able to login with new password")))))))))
+
+(deftest reset-password-with-expired-support-grant-test
+ (testing "POST /api/session/reset_password rejects expired support access grant token"
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
+ (with-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
+ (let [grant (t/with-clock (t/mock-clock (t/minus (t/instant) (t/weeks 5)))
+ (grants/create-grant! creator-id 60 "TICKET-123" "Test notes"))
+ token (:token grant)]
+ (is (some? token) "Token should be created")
+ (testing "Expired support access grant token is rejected"
+ (let [response (mt/client :post 400 "session/reset_password"
+ {:token token
+ :password "NewPassword123!"})]
+ (is (some? (:errors response)) "Should return error for expired token")))))))))
+
+(deftest password-reset-token-valid-with-support-grant-test
+ (testing "GET /api/session/password_reset_token_valid works with support access grant token"
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
+ (with-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
+ (let [grant (grants/create-grant! creator-id 60 "TICKET-456" "Test notes")
+ token (:token grant)]
+ (is (some? token) "Token should be created")
+ (testing "Support access grant token is valid"
+ (let [response (mt/client :get 200 "session/password_reset_token_valid"
+ :token token)]
+ (is (true? (:valid response)) "Token should be valid")))))))))
+
+(deftest password-reset-token-valid-fallback-test
+ (testing "GET /api/session/password_reset_token_valid falls back to regular password reset token"
+ (mt/with-temp [:model/User user {:email "[email protected]"}]
+ (let [regular-token (auth-identity/create-password-reset! (:id user))]
+ (testing "Regular password reset token is valid with fallback"
+ (let [response (mt/client :get 200 "session/password_reset_token_valid"
+ :token regular-token)]
+ (is (true? (:valid response)) "Regular token should be valid")))))))
+
+(deftest password-reset-token-valid-with-invalid-token-test
+ (testing "GET /api/session/password_reset_token_valid returns false for completely invalid token"
+ (let [response (mt/client :get 200 "session/password_reset_token_valid"
+ :token "totally-invalid-token-12345")]
+ (is (false? (:valid response)) "Invalid token should return valid=false"))))
+
+(deftest password-reset-token-valid-with-expired-support-grant-test
+ (testing "GET /api/session/password_reset_token_valid returns false for expired support grant"
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User]
+ (with-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
+ (let [grant (t/with-clock (t/mock-clock (t/minus (t/instant) (t/weeks 5)))
+ (grants/create-grant! creator-id 60 "TICKET-123" "Test notes"))
+ token (:token grant)]
+ (is (some? token) "Token should be created")
+ (testing "Expired support grant token is invalid"
+ (let [response (mt/client :get 200 "session/password_reset_token_valid"
+ :token token)]
+ (is (false? (:valid response)) "Expired token should be invalid")))))))))
+
+(deftest reset-password-creates-session-test
+ (testing "POST /api/session/reset_password creates a session after successful password reset"
+ (mt/with-temp [:model/User {creator-id :id} {}]
+ (mt/with-model-cleanup [:model/SupportAccessGrantLog :model/AuthIdentity :model/User :model/Session]
+ (with-redefs [sag.settings/support-access-grant-email (constantly "[email protected]")
+ sag.settings/support-access-grant-first-name (constantly "Support")
+ sag.settings/support-access-grant-last-name (constantly "User")]
+ (let [grant (grants/create-grant! creator-id 60 "TICKET-999" "Test notes")
+ token (:token grant)
+ new-password "SecurePassword123!"]
+ (testing "Session is created after password reset"
+ (let [response (mt/client :post 200 "session/reset_password"
+ {:token token
+ :password new-password})
+ session-id (:session_id response)]
+ (is (some? session-id) "Should return session ID")
+ (testing "Session exists in database"
+ (let [session (t2/select-one :model/Session :key_hashed (session/hash-session-key session-id))]
+ (is (some? session) "Session should exist in database")
+ (is (= "[email protected]" (:email (t2/select-one :model/User :id (:user_id session))))
+ "Session should be for support user")))))))))))
+
+(deftest forgot-password-support-user-disabled-test
+ (testing "POST /api/session/forgot_password - Support Users cannot reset passwords"
+ (with-redefs [api.session/forgot-password-impl
+ (let [orig @#'api.session/forgot-password-impl]
+ (fn [& args] (u/deref-with-timeout (apply orig args) 1000)))]
+ (mt/with-temp [:model/User user {:first_name "support"
+ :last_name "user"
+ :email "[email protected]"}
+ :model/AuthIdentity _ {:user_id (:id user)
+ :provider "support-access-grant"}]
+ (let [my-url "abcdefghij"]
+ (mt/with-temporary-setting-values [site-url my-url]
+ (mt/with-fake-inbox
+ (mt/user-http-request user :post 204 "session/forgot_password" {:email (:email user)})
+ (is (not (t2/exists? :model/AuthIdentity :user_id (:id user) :provider "emailed-secret-password-reset"))))))))))
diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.ts
index 99f4b031eca..a7dab8f8f6a 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts
@@ -13,6 +13,7 @@ export * from "./remote-sync";
export * from "./metabot";
export * from "./saml";
export * from "./scim";
+export * from "./support-access-grants";
export * from "./tags";
export * from "./transform";
export * from "./transform-job";
diff --git a/enterprise/frontend/src/metabase-enterprise/api/support-access-grants.ts b/enterprise/frontend/src/metabase-enterprise/api/support-access-grants.ts
new file mode 100644
index 00000000000..679b2834b2f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/api/support-access-grants.ts
@@ -0,0 +1,80 @@
+import type {
+ CreateSupportAccessGrantRequest,
+ CurrentSupportAccessGrantResponse,
+ ListSupportAccessGrantsRequest,
+ ListSupportAccessGrantsResponse,
+ SupportAccessGrant,
+} from "metabase-types/api";
+
+import { EnterpriseApi } from "./api";
+import {
+ idTag,
+ invalidateTags,
+ listTag,
+ provideSupportAccessGrantListTags,
+ tag,
+} from "./tags";
+
+export const supportAccessGrantsApi = EnterpriseApi.injectEndpoints({
+ endpoints: (builder) => ({
+ listSupportAccessGrants: builder.query<
+ ListSupportAccessGrantsResponse,
+ ListSupportAccessGrantsRequest | void
+ >({
+ query: (params) => ({
+ method: "GET",
+ url: "/api/ee/support-access-grant",
+ params,
+ }),
+ providesTags: (response) =>
+ response ? provideSupportAccessGrantListTags(response.data) : [],
+ }),
+
+ getCurrentSupportAccessGrant: builder.query<
+ CurrentSupportAccessGrantResponse,
+ void
+ >({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/support-access-grant/current",
+ }),
+ providesTags: () => [tag("support-access-grant-current")],
+ }),
+
+ createSupportAccessGrant: builder.mutation<
+ SupportAccessGrant,
+ CreateSupportAccessGrantRequest
+ >({
+ query: (body) => ({
+ method: "POST",
+ url: "/api/ee/support-access-grant",
+ body,
+ }),
+ invalidatesTags: (_, error) =>
+ invalidateTags(error, [
+ tag("support-access-grant-current"),
+ listTag("support-access-grant"),
+ ]),
+ }),
+
+ revokeSupportAccessGrant: builder.mutation<SupportAccessGrant, number>({
+ query: (id) => ({
+ method: "PUT",
+ url: `/api/ee/support-access-grant/${id}/revoke`,
+ }),
+ invalidatesTags: (_, error, id) =>
+ invalidateTags(error, [
+ tag("support-access-grant-current"),
+ idTag("support-access-grant", id),
+ listTag("support-access-grant"),
+ ]),
+ }),
+ }),
+});
+
+export const {
+ useListSupportAccessGrantsQuery,
+ useGetCurrentSupportAccessGrantQuery,
+ useCreateSupportAccessGrantMutation,
+ useRevokeSupportAccessGrantMutation,
+} = supportAccessGrantsApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
index 77b012e22c6..cdb13fe922b 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts
@@ -18,6 +18,7 @@ import type {
PythonLibrary,
SandboxDependencyNode,
SnippetDependencyNode,
+ SupportAccessGrant,
TableDependencyNode,
Transform,
TransformDependencyNode,
@@ -48,6 +49,8 @@ export const ENTERPRISE_TAG_TYPES = [
"remote-sync-branches",
"remote-sync-current-task",
"python-transform-library",
+ "support-access-grant",
+ "support-access-grant-current",
] as const;
export type EnterpriseTagType = (typeof ENTERPRISE_TAG_TYPES)[number];
@@ -273,3 +276,18 @@ export function provideDependencyGraphTags(
): TagDescription<EnterpriseTagType>[] {
return provideDependencyNodeListTags(graph.nodes);
}
+
+export function provideSupportAccessGrantTags(
+ grant: SupportAccessGrant,
+): TagDescription<EnterpriseTagType>[] {
+ return [idTag("support-access-grant", grant.id)];
+}
+
+export function provideSupportAccessGrantListTags(
+ grants: SupportAccessGrant[],
+): TagDescription<EnterpriseTagType>[] {
+ return [
+ listTag("support-access-grant"),
+ ...grants.flatMap(provideSupportAccessGrantTags),
+ ];
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.js b/enterprise/frontend/src/metabase-enterprise/plugins.js
index 9a9c17b686f..585339a8ce8 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.js
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.js
@@ -40,6 +40,7 @@ import { initializePlugin as initializeSemanticSearch } from "./semantic_search"
import { initializePlugin as initializeSharing } from "./sharing";
import { initializePlugin as initializeSmtpOverride } from "./smtp-override";
import { initializePlugin as initializeSnippets } from "./snippets";
+import { initializePlugin as initializeSupport } from "./support";
import { initializePlugin as initializeTableEditing } from "./table-editing";
import { initializePlugin as initializeTools } from "./tools";
import { initializePlugin as initializeTransforms } from "./transforms";
@@ -91,4 +92,5 @@ export function initializePlugins() {
initializeTransforms?.();
initializeTransformsPython?.();
initializePublicSharing?.();
+ initializeSupport?.();
}
diff --git a/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/AccessGrantList.tsx b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/AccessGrantList.tsx
new file mode 100644
index 00000000000..c767a0f7cc7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/AccessGrantList.tsx
@@ -0,0 +1,115 @@
+import cx from "classnames";
+import dayjs, { type Dayjs } from "dayjs";
+import { c, t } from "ttag";
+
+import { useConfirmation } from "metabase/common/hooks";
+import AdminS from "metabase/css/admin.module.css";
+import CS from "metabase/css/core/index.css";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { ActionIcon, Badge, Group, Icon } from "metabase/ui";
+import { useRevokeSupportAccessGrantMutation } from "metabase-enterprise/api";
+import type { SupportAccessGrant } from "metabase-types/api";
+
+interface AccessGrantListProps {
+ accessGrants: SupportAccessGrant[];
+}
+
+export const AccessGrantList = (props: AccessGrantListProps) => {
+ const { accessGrants } = props;
+ const [revokeSupportAccessGrant, { isLoading: isRevoking }] =
+ useRevokeSupportAccessGrantMutation();
+ const { sendErrorToast, sendSuccessToast } = useMetadataToasts();
+ const { modalContent, show } = useConfirmation();
+
+ const handleRevokeAccessGrant = async (grantId: number) => {
+ show({
+ title: t`Revoke access grant?`,
+ message: t`This will immediately revoke the support agent's access to your instance.`,
+ confirmButtonText: t`Revoke`,
+ confirmButtonProps: { color: "danger" },
+ size: "sm",
+ onConfirm: async () => {
+ try {
+ await revokeSupportAccessGrant(grantId).unwrap();
+ sendSuccessToast(t`Access grant revoked successfully`);
+ } catch {
+ sendErrorToast(t`Sorry, something went wrong. Please try again.`);
+ }
+ },
+ });
+ };
+ const now = dayjs();
+
+ return (
+ <>
+ <table
+ data-testid="access-grant-list-table"
+ className={cx(AdminS.ContentTable, CS.borderBottom)}
+ >
+ <thead>
+ <tr>
+ <th style={{ paddingLeft: 0 }}>{t`Date`}</th>
+ <th>{t`Ticket`}</th>
+ <th>{t`Notes`}</th>
+ <th>{t`Request creator`}</th>
+ <th>{t`Expired`}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {accessGrants.map((grant) => {
+ const startDate = dayjs(grant.grant_start_timestamp);
+ const effectiveEndDate = dayjs(
+ grant.revoked_at || grant.grant_end_timestamp,
+ );
+
+ return (
+ <tr key={grant.id}>
+ <td style={{ paddingLeft: 0 }}>{startDate.format("lll")}</td>
+ <td>{grant.ticket_number || "-"}</td>
+ <td>{grant.notes || "-"}</td>
+ <td>{grant.user_name || grant.user_email || grant.user_id}</td>
+ <td>
+ {effectiveEndDate.isBefore(now) ? (
+ effectiveEndDate.format("lll")
+ ) : (
+ <Group gap="sm">
+ <Badge
+ m={0}
+ variant="outline"
+ title={effectiveEndDate.format("lll")}
+ >
+ {c("{0} is the time until expiration")
+ .t`${getTimeLeft(effectiveEndDate)} left`}
+ </Badge>
+ <ActionIcon
+ aria-label={t`Revoke access grant`}
+ loading={isRevoking}
+ onClick={() => handleRevokeAccessGrant(grant.id)}
+ size="sm"
+ title={t`Revoke access grant`}
+ variant="viewHeader"
+ >
+ <Icon name="close" />
+ </ActionIcon>
+ </Group>
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ {modalContent}
+ </>
+ );
+};
+
+const getTimeLeft = (date: Dayjs) => {
+ const hourDiff = date.diff(dayjs(), "hours", true);
+
+ if (hourDiff > 1 && hourDiff <= 48) {
+ return c("{0} is the number of hours").t`${Math.round(hourDiff)} hours`;
+ }
+
+ return date.toNow(true);
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/AccessGrantList.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/AccessGrantList.unit.spec.tsx
new file mode 100644
index 00000000000..d9fe4d197a7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/AccessGrantList.unit.spec.tsx
@@ -0,0 +1,167 @@
+import dayjs from "dayjs";
+import fetchMock from "fetch-mock";
+
+import {
+ setupRevokeAccessGrantEndpoint,
+ setupRevokeAccessGrantEndpointWithError,
+} from "__support__/server-mocks";
+import {
+ fireEvent,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
+import type { SupportAccessGrant } from "metabase-types/api";
+import { createMockAccessGrant } from "metabase-types/api/mocks";
+
+import { AccessGrantList } from "./AccessGrantList";
+
+const setup = (accessGrants: SupportAccessGrant[]) => {
+ renderWithProviders(
+ <>
+ <AccessGrantList accessGrants={accessGrants} />
+ <UndoListing />
+ </>,
+ );
+};
+
+describe("AccessGrantList", () => {
+ beforeEach(() => {
+ jest.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ jest.spyOn(console, "error").mockRestore();
+ fetchMock.clearHistory();
+ });
+
+ const testActiveGrant = createMockAccessGrant({
+ id: 1,
+ ticket_number: "TICKET-1234",
+ notes: "This is a test note",
+ grant_start_timestamp: dayjs().subtract(1, "hour").toISOString(),
+ grant_end_timestamp: dayjs().add(23, "hours").toISOString(),
+ revoked_at: null,
+ user_name: "John Doe",
+ user_email: "[email protected]",
+ });
+
+ const testRevokedGrant = createMockAccessGrant({
+ id: 2,
+ ticket_number: null,
+ notes: null,
+ grant_start_timestamp: dayjs().subtract(3, "days").toISOString(),
+ grant_end_timestamp: dayjs().add(1, "day").toISOString(),
+ revoked_at: dayjs().subtract(2, "days").toISOString(),
+ user_name: "Jane Smith",
+ user_email: "[email protected]",
+ });
+
+ it("should render a list of access grants", () => {
+ setup([testActiveGrant, testRevokedGrant]);
+
+ const table = screen.getByTestId("access-grant-list-table");
+ expect(table).toBeInTheDocument();
+
+ expect(within(table).getByText("TICKET-1234")).toBeInTheDocument();
+ expect(within(table).getByText("This is a test note")).toBeInTheDocument();
+ expect(within(table).getByText("John Doe")).toBeInTheDocument();
+
+ const cells = within(table).getAllByText("-");
+ expect(cells.length).toBeGreaterThanOrEqual(2);
+ expect(within(table).getByText("Jane Smith")).toBeInTheDocument();
+
+ const revokeButtons = screen.getAllByLabelText("Revoke access grant");
+ expect(revokeButtons).toHaveLength(1);
+
+ expect(within(table).getByText(/23 hours left/)).toBeInTheDocument();
+ });
+
+ it("should use email and user id as fallback if name is not set", () => {
+ setup([
+ { ...testActiveGrant, user_id: 1001, user_name: null },
+ { ...testActiveGrant, user_id: 1002, user_name: null, user_email: null },
+ ]);
+
+ const table = screen.getByTestId("access-grant-list-table");
+ expect(table).toBeInTheDocument();
+
+ expect(within(table).getAllByText("[email protected]")).toHaveLength(1);
+ expect(within(table).queryByText("1001")).not.toBeInTheDocument();
+ expect(within(table).getAllByText("1002")).toHaveLength(1);
+ });
+
+ describe("revoking", () => {
+ const executeAccessRevokeFlow = async (grantId: number) => {
+ const revokeButton = screen.getByLabelText("Revoke access grant");
+ fireEvent.click(revokeButton);
+
+ await waitFor(() => {
+ expect(screen.getByText("Revoke access grant?")).toBeInTheDocument();
+ });
+
+ const confirmButton = screen.getByRole("button", { name: "Revoke" });
+ fireEvent.click(confirmButton);
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls(
+ `path:/api/ee/support-access-grant/${grantId}/revoke`,
+ ),
+ ).toHaveLength(1);
+ });
+ };
+
+ it("can revoke an active grant access", async () => {
+ const activeGrant = createMockAccessGrant({
+ id: 1,
+ grant_start_timestamp: dayjs().subtract(1, "hour").toISOString(),
+ grant_end_timestamp: dayjs().add(23, "hours").toISOString(),
+ revoked_at: null,
+ });
+
+ const revokedGrant = createMockAccessGrant({
+ ...activeGrant,
+ revoked_at: dayjs().toISOString(),
+ });
+
+ setupRevokeAccessGrantEndpoint(activeGrant.id, revokedGrant);
+ setup([activeGrant]);
+
+ await executeAccessRevokeFlow(activeGrant.id);
+
+ await waitFor(() => {
+ const toast = screen.getByTestId("toast-undo");
+ expect(
+ within(toast).getByText(/Access grant revoked successfully/),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("should display error toast when revoking fails", async () => {
+ const activeGrant = createMockAccessGrant({
+ id: 1,
+ grant_start_timestamp: dayjs().subtract(1, "hour").toISOString(),
+ grant_end_timestamp: dayjs().add(23, "hours").toISOString(),
+ revoked_at: null,
+ });
+
+ setupRevokeAccessGrantEndpointWithError(activeGrant.id);
+
+ setup([activeGrant]);
+
+ await executeAccessRevokeFlow(activeGrant.id);
+
+ await waitFor(() => {
+ const toast = screen.getByTestId("toast-undo");
+ expect(
+ within(toast).getByText(
+ /Sorry, something went wrong. Please try again/,
+ ),
+ ).toBeInTheDocument();
+ });
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/GrantAccessModal.tsx b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/GrantAccessModal.tsx
new file mode 100644
index 00000000000..da0b73a025c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/GrantAccessModal.tsx
@@ -0,0 +1,124 @@
+import { useMount } from "react-use";
+import { t } from "ttag";
+
+import {
+ Form,
+ FormErrorMessage,
+ FormProvider,
+ FormSelect,
+ FormSubmitButton,
+ FormTextInput,
+ FormTextarea,
+} from "metabase/forms";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { PLUGIN_SUPPORT } from "metabase/plugins";
+import { Box, Flex, Modal, Stack, Text } from "metabase/ui";
+import { useCreateSupportAccessGrantMutation } from "metabase-enterprise/api";
+
+interface GrantAccessModalProps {
+ onClose: VoidFunction;
+}
+
+type AccessGrantFormValues = {
+ grant_duration_minutes?: string;
+ ticket_number?: string;
+ notes?: string;
+};
+
+export const GrantAccessModal = ({ onClose }: GrantAccessModalProps) => {
+ const [createSupportAccessGrant] = useCreateSupportAccessGrantMutation();
+ const { sendErrorToast, sendSuccessToast } = useMetadataToasts();
+
+ useMount(() => {
+ if (!PLUGIN_SUPPORT.isEnabled) {
+ onClose();
+ }
+ });
+
+ const handleSubmit = async (values: AccessGrantFormValues) => {
+ if (!values.grant_duration_minutes) {
+ sendErrorToast(t`Please select a duration and provide a ticket number.`);
+ return Promise.reject();
+ }
+
+ try {
+ await createSupportAccessGrant({
+ grant_duration_minutes: Number(values.grant_duration_minutes),
+ notes: values.notes || null,
+ ticket_number: values.ticket_number || null,
+ }).unwrap();
+ sendSuccessToast(t`Access grant created successfully`);
+ onClose();
+ } catch (error) {
+ sendErrorToast(t`Sorry, something went wrong. Please try again`);
+ throw error;
+ }
+ };
+
+ return (
+ <Modal
+ data-testid="grant-access-modal"
+ onClose={onClose}
+ opened
+ title={t`Grant Access?`}
+ padding="xl"
+ >
+ <Stack>
+ <Box mt="sm">
+ <Text display="inline">
+ {/* eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins. */}
+ {t`You are about to allow a Metabase team member to access your instance.`}{" "}
+ </Text>
+ <Text fw="bold" display="inline">
+ {t`The support agent will have full admin access until the grant expires or is revoked.`}
+ </Text>
+ </Box>
+ <FormProvider initialValues={initialValues} onSubmit={handleSubmit}>
+ {({ values }) => (
+ <Form>
+ <Stack mt="md">
+ <FormSelect
+ name="grant_duration_minutes"
+ label={t`Access duration`}
+ data={[
+ { value: String(24 * 60), label: t`24 hours` },
+ { value: String(48 * 60), label: t`48 hours` },
+ { value: String(96 * 60), label: t`96 hours` },
+ ]}
+ placeholder={t`Choose...`}
+ required
+ />
+ <FormTextInput
+ label={t`Ticket`}
+ name="ticket_number"
+ placeholder={t`TICKET-1234`}
+ />
+ <FormTextarea
+ label={t`Notes`}
+ minRows={3}
+ name="notes"
+ placeholder={t`Add any important information we should know to help you better.`}
+ />
+ <Flex justify="end" mt="md" gap="md">
+ <FormErrorMessage />
+ <FormSubmitButton
+ disabled={!values.grant_duration_minutes}
+ label={t`Grant access`}
+ style={{ flexShrink: 0 }}
+ variant="filled"
+ />
+ </Flex>
+ </Stack>
+ </Form>
+ )}
+ </FormProvider>
+ </Stack>
+ </Modal>
+ );
+};
+
+const initialValues: AccessGrantFormValues = {
+ grant_duration_minutes: String(96 * 60),
+ ticket_number: "",
+ notes: "",
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/GrantAccessModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/GrantAccessModal.unit.spec.tsx
new file mode 100644
index 00000000000..f5f53cff92f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/GrantAccessModal.unit.spec.tsx
@@ -0,0 +1,98 @@
+import fetchMock from "fetch-mock";
+
+import {
+ setupCreateAccessGrantEndpoint,
+ setupCreateAccessGrantEndpointWithError,
+} from "__support__/server-mocks";
+import {
+ fireEvent,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
+import { PLUGIN_SUPPORT } from "metabase/plugins";
+import { createMockAccessGrant } from "metabase-types/api/mocks";
+
+import { GrantAccessModal } from "./GrantAccessModal";
+
+const onClose = jest.fn();
+
+const setup = () => {
+ renderWithProviders(
+ <>
+ <GrantAccessModal onClose={onClose} />
+ <UndoListing />
+ </>,
+ );
+};
+
+describe("GrantAccessModal", () => {
+ beforeEach(() => {
+ jest.spyOn(console, "error").mockImplementation(() => {});
+ PLUGIN_SUPPORT.isEnabled = true;
+ });
+
+ afterEach(() => {
+ jest.spyOn(console, "error").mockRestore();
+ onClose.mockClear();
+ fetchMock.clearHistory();
+ });
+
+ it("should close if PLUGIN_SUPPORT plugin is disabled", () => {
+ PLUGIN_SUPPORT.isEnabled = false;
+ setup();
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("should create an access grant with default values", async () => {
+ setupCreateAccessGrantEndpoint(createMockAccessGrant());
+ setup();
+ const durationField = screen.getByLabelText(/Access duration/);
+ expect(durationField).toHaveValue("96 hours");
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ await waitFor(async () => {
+ expect(
+ fetchMock.callHistory.calls(`path:/api/ee/support-access-grant`, {
+ body: {
+ grant_duration_minutes: 96 * 60,
+ notes: null,
+ ticket_number: null,
+ },
+ }),
+ ).toHaveLength(1);
+ });
+ expect(onClose).toHaveBeenCalledTimes(1);
+
+ await waitFor(() => {
+ const undo = screen.getByTestId("toast-undo");
+ expect(
+ within(undo).getByText(/Access grant created successfully/),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("should handle response error", async () => {
+ const errorMessage = "An error occurred and this is the error message";
+ setupCreateAccessGrantEndpointWithError(errorMessage);
+ setup();
+ fireEvent.click(screen.getByRole("button", { name: "Grant access" }));
+ await waitFor(async () => {
+ expect(
+ fetchMock.callHistory.calls(`path:/api/ee/support-access-grant`),
+ ).toHaveLength(1);
+ });
+ expect(onClose).not.toHaveBeenCalled();
+
+ await waitFor(() => {
+ const undo = screen.getByTestId("toast-undo");
+ expect(
+ within(undo).getByText(/Sorry, something went wrong. Please try again/),
+ ).toBeInTheDocument();
+ });
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ new RegExp(errorMessage),
+ );
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/SupportSettingsSection.tsx b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/SupportSettingsSection.tsx
new file mode 100644
index 00000000000..5c6053daf1d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/SupportSettingsSection.tsx
@@ -0,0 +1,97 @@
+import { push } from "react-router-redux";
+import { t } from "ttag";
+
+import { SettingsSection } from "metabase/admin/components/SettingsSection";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { PaginationControls } from "metabase/common/components/PaginationControls";
+import { useDispatch } from "metabase/lib/redux";
+import { adminToolsGrantAccess } from "metabase/lib/urls";
+import { Box, Button, Flex, LoadingOverlay, Text, Title } from "metabase/ui";
+
+import { useAccessGrantsQuery } from "../../hooks/useAccessGrantsQuery";
+
+import { AccessGrantList } from "./AccessGrantList";
+
+export function SupportSettingsSection() {
+ const dispatch = useDispatch();
+ const {
+ accessGrants,
+ accessGrantsError,
+ currentAccessGrant,
+ handleNextPage,
+ handlePreviousPage,
+ isFetchingAccessGrants,
+ isLoadingAccessGrants,
+ page,
+ pageSize,
+ total,
+ } = useAccessGrantsQuery();
+
+ return (
+ <SettingsSection
+ title={t`Helping hand`}
+ description={
+ <>
+ <Text c="text-medium" mt="sm">
+ {/* eslint-disable-next-line no-literal-metabase-strings -- This string only shows for admins. */}
+ {t`Let a Metabase support agent log in to your instance with a troubleshooting account to help resolve problems for you.`}
+ </Text>
+ <Text c="text-medium">
+ {t`Access always auto expires after the period you select.`}
+ </Text>
+ </>
+ }
+ stackProps={{ gap: 0 }}
+ >
+ <LoadingAndErrorWrapper
+ error={accessGrantsError}
+ loading={isLoadingAccessGrants}
+ >
+ <Box pb="lg">
+ <Button
+ disabled={!!currentAccessGrant}
+ onClick={() => dispatch(push(adminToolsGrantAccess()))}
+ variant="filled"
+ title={
+ currentAccessGrant
+ ? t`You already have an active access grant`
+ : undefined
+ }
+ mt="md"
+ mb="sm"
+ >
+ {t`Request a helping hand`}
+ </Button>
+ <Text size="sm" c="text-secondary">
+ {t`You can only have one active request at a time`}
+ </Text>
+
+ {accessGrants.length > 0 && (
+ <Box pos="relative">
+ <LoadingOverlay
+ visible={isFetchingAccessGrants}
+ zIndex={1000}
+ overlayProps={{ radius: "sm", blur: 0.25 }}
+ />
+ <Title lh="2.5rem" order={4} pt="lg">
+ {t`History`}
+ </Title>
+ <AccessGrantList accessGrants={accessGrants} />
+ <Flex justify="flex-end" mt="sm">
+ <PaginationControls
+ itemsLength={accessGrants.length}
+ onNextPage={handleNextPage}
+ onPreviousPage={handlePreviousPage}
+ page={page}
+ pageSize={pageSize}
+ total={total}
+ showTotal
+ />
+ </Flex>
+ </Box>
+ )}
+ </Box>
+ </LoadingAndErrorWrapper>
+ </SettingsSection>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/SupportSettingsSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/SupportSettingsSection.unit.spec.tsx
new file mode 100644
index 00000000000..3de353cab6f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/SupportSettingsSection.unit.spec.tsx
@@ -0,0 +1,110 @@
+import dayjs from "dayjs";
+import fetchMock from "fetch-mock";
+import { Route } from "react-router";
+
+import {
+ setupCurrentAccessGrantEndpoint,
+ setupListAccessGrantsEndpoint,
+ setupListAccessGrantsEndpointWithError,
+} from "__support__/server-mocks";
+import { fireEvent, renderWithProviders, screen, within } from "__support__/ui";
+import { createMockAccessGrant } from "metabase-types/api/mocks";
+
+import { GrantAccessModal } from "./GrantAccessModal";
+import { SupportSettingsSection } from "./SupportSettingsSection";
+
+const setup = () => {
+ return renderWithProviders(
+ <>
+ <Route
+ path="/admin/tools/help"
+ component={() => <SupportSettingsSection />}
+ />
+ <Route
+ path="/admin/tools/help/grant-access"
+ component={() => <GrantAccessModal onClose={jest.fn()} />}
+ />
+ </>,
+ { withRouter: true, initialRoute: "/admin/tools/help" },
+ );
+};
+
+describe("SupportSettingsSection", () => {
+ beforeEach(() => {
+ jest.spyOn(console, "error").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ jest.spyOn(console, "error").mockRestore();
+ fetchMock.clearHistory();
+ });
+
+ describe("'Request a helping hand' button", () => {
+ it("should be enabled when there is no current access grant", async () => {
+ setupCurrentAccessGrantEndpoint(null);
+ setupListAccessGrantsEndpoint([]);
+
+ setup();
+
+ const button = await screen.findByRole("button", {
+ name: "Request a helping hand",
+ });
+ expect(button).toBeEnabled();
+ });
+
+ it("should be disabled when there is a current access grant", async () => {
+ const currentGrant = createMockAccessGrant({
+ id: 1,
+ grant_start_timestamp: dayjs().subtract(1, "hour").toISOString(),
+ grant_end_timestamp: dayjs().add(23, "hours").toISOString(),
+ revoked_at: null,
+ });
+
+ setupCurrentAccessGrantEndpoint(currentGrant);
+ setupListAccessGrantsEndpoint([currentGrant]);
+
+ setup();
+
+ const button = await screen.findByRole("button", {
+ name: "Request a helping hand",
+ });
+ expect(button).toBeDisabled();
+ expect(button).toHaveAttribute(
+ "title",
+ "You already have an active access grant",
+ );
+ });
+ });
+
+ it("should display error message when access grant list endpoint fails", async () => {
+ const errorMessage = "Failed to load access grants";
+ setupCurrentAccessGrantEndpoint(null);
+ setupListAccessGrantsEndpointWithError(errorMessage);
+
+ setup();
+
+ expect(
+ await screen.findByRole("heading", { name: errorMessage }),
+ ).toBeInTheDocument();
+ });
+
+ it("can click the 'Request a helping hand' button to show the grant access modal", async () => {
+ setupCurrentAccessGrantEndpoint(null);
+ setupListAccessGrantsEndpoint([]);
+
+ setup();
+
+ const button = await screen.findByRole("button", {
+ name: "Request a helping hand",
+ });
+
+ fireEvent.click(button);
+
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(
+ within(screen.getByRole("dialog")).getByRole("heading", {
+ name: "Grant Access?",
+ }),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/index.ts b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/index.ts
new file mode 100644
index 00000000000..22d1d5b2ad8
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/components/SupportSettingsSection/index.ts
@@ -0,0 +1,2 @@
+export { SupportSettingsSection } from "./SupportSettingsSection";
+export { GrantAccessModal } from "./GrantAccessModal";
diff --git a/enterprise/frontend/src/metabase-enterprise/support/hooks/useAccessGrantsQuery.ts b/enterprise/frontend/src/metabase-enterprise/support/hooks/useAccessGrantsQuery.ts
new file mode 100644
index 00000000000..c319d2ec8b7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/hooks/useAccessGrantsQuery.ts
@@ -0,0 +1,38 @@
+import { usePagination } from "metabase/common/hooks/use-pagination";
+import {
+ useGetCurrentSupportAccessGrantQuery,
+ useListSupportAccessGrantsQuery,
+} from "metabase-enterprise/api";
+
+const PAGE_SIZE = 10;
+
+export const useAccessGrantsQuery = () => {
+ const { page, handlePreviousPage, handleNextPage } = usePagination();
+ const offset = PAGE_SIZE * page;
+
+ const {
+ data: listResponse,
+ error,
+ isFetching,
+ isLoading,
+ } = useListSupportAccessGrantsQuery({
+ "include-revoked": true,
+ offset,
+ limit: PAGE_SIZE,
+ });
+ const { data: currentAccessGrant } = useGetCurrentSupportAccessGrantQuery();
+ const { data: accessGrants = [], total } = listResponse || {};
+
+ return {
+ accessGrants,
+ accessGrantsError: error,
+ currentAccessGrant,
+ isLoadingAccessGrants: isLoading,
+ isFetchingAccessGrants: isFetching,
+ total,
+ pageSize: PAGE_SIZE,
+ handlePreviousPage,
+ handleNextPage,
+ page,
+ };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/support/index.ts b/enterprise/frontend/src/metabase-enterprise/support/index.ts
new file mode 100644
index 00000000000..da3c4dd5f67
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/support/index.ts
@@ -0,0 +1,16 @@
+import { isEEBuild } from "metabase/lib/utils";
+import { PLUGIN_SUPPORT } from "metabase/plugins";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
+
+import {
+ GrantAccessModal,
+ SupportSettingsSection,
+} from "./components/SupportSettingsSection";
+
+export function initializePlugin() {
+ if (hasPremiumFeature("support-users") && isEEBuild()) {
+ PLUGIN_SUPPORT.isEnabled = true;
+ PLUGIN_SUPPORT.SupportSettings = SupportSettingsSection;
+ PLUGIN_SUPPORT.GrantAccessModal = GrantAccessModal;
+ }
+}
diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.ts
index 70fee7f1d9f..c6e1014893c 100644
--- a/frontend/src/metabase-types/api/index.ts
+++ b/frontend/src/metabase-types/api/index.ts
@@ -50,6 +50,7 @@ export * from "./slack";
export * from "./snippets";
export * from "./store";
export * from "./subscription";
+export * from "./support-access-grants";
export * from "./table";
export * from "./task";
export * from "./timeline";
diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.ts
index bc7a6338910..e613615518c 100644
--- a/frontend/src/metabase-types/api/mocks/index.ts
+++ b/frontend/src/metabase-types/api/mocks/index.ts
@@ -32,6 +32,7 @@ export * from "./session";
export * from "./settings";
export * from "./snippets";
export * from "./store";
+export * from "./support-access-grants";
export * from "./table";
export * from "./task";
export * from "./timeline";
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index 815eef1dce3..d4acccea663 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -143,6 +143,7 @@ export const createMockTokenFeatures = (
transforms: false,
remote_sync: false,
"transforms-python": false,
+ "support-users": false,
...opts,
});
diff --git a/frontend/src/metabase-types/api/mocks/support-access-grants.ts b/frontend/src/metabase-types/api/mocks/support-access-grants.ts
new file mode 100644
index 00000000000..7adde6c4835
--- /dev/null
+++ b/frontend/src/metabase-types/api/mocks/support-access-grants.ts
@@ -0,0 +1,21 @@
+import type { SupportAccessGrant } from "metabase-types/api";
+
+export const createMockAccessGrant = (
+ opts: Partial<SupportAccessGrant> = {},
+): SupportAccessGrant => {
+ return {
+ id: 1,
+ created_at: "2025-03-01T00:00:00.000Z",
+ grant_end_timestamp: "2025-11-04T00:00:00.000Z",
+ grant_start_timestamp: "2025-11-01T00:00:00.000Z",
+ notes: "notes",
+ revoked_at: null,
+ revoked_by_user_id: null,
+ ticket_number: null,
+ updated_at: "2025-03-01T00:00:00.000Z",
+ user_id: 123,
+ user_name: "Bobby",
+ user_email: "[email protected]",
+ ...opts,
+ };
+};
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index eb1207020cc..9f85a7c3204 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -330,6 +330,7 @@ export const tokenFeatures = [
"semantic_search",
"transforms",
"transforms-python",
+ "support-users",
] as const;
export type TokenFeature = (typeof tokenFeatures)[number];
diff --git a/frontend/src/metabase-types/api/support-access-grants.ts b/frontend/src/metabase-types/api/support-access-grants.ts
new file mode 100644
index 00000000000..c8bb72ef4d2
--- /dev/null
+++ b/frontend/src/metabase-types/api/support-access-grants.ts
@@ -0,0 +1,37 @@
+export interface SupportAccessGrant {
+ id: number;
+ user_id: number;
+ user_name: string | null;
+ user_email: string | null;
+ ticket_number: string | null;
+ notes: string | null;
+ grant_start_timestamp: string;
+ grant_end_timestamp: string;
+ revoked_at?: string | null;
+ revoked_by_user_id: number | null;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface CreateSupportAccessGrantRequest {
+ grant_duration_minutes: number;
+ notes: string | null;
+ ticket_number: string | null;
+}
+
+export interface ListSupportAccessGrantsRequest {
+ "ticket-number"?: string;
+ "user-id"?: number;
+ "include-revoked"?: boolean;
+ limit?: number;
+ offset?: number;
+}
+
+export interface ListSupportAccessGrantsResponse {
+ data: SupportAccessGrant[];
+ total: number;
+ limit: number;
+ offset: number;
+}
+
+export type CurrentSupportAccessGrantResponse = SupportAccessGrant | null;
diff --git a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
index 0d76db374a8..1330b2450dd 100644
--- a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
+++ b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
@@ -15,16 +15,18 @@ export function SettingsSection({
title,
description,
children,
+ stackProps,
...boxProps
}: {
title?: React.ReactNode;
description?: React.ReactNode;
children?: React.ReactNode;
+ stackProps?: StackProps;
} & BoxProps) {
return (
<Box {...boxProps}>
{children && (
- <Stack gap="lg" className={S.SettingsSection}>
+ <Stack gap="lg" className={S.SettingsSection} {...stackProps}>
{(title || description) && (
<Box mb="sm">
{title && <Title order={2}>{title}</Title>}
diff --git a/frontend/src/metabase/admin/routes.jsx b/frontend/src/metabase/admin/routes.jsx
index dcf0da01946..947b06dafcc 100644
--- a/frontend/src/metabase/admin/routes.jsx
+++ b/frontend/src/metabase/admin/routes.jsx
@@ -50,6 +50,7 @@ import {
PLUGIN_DB_ROUTING,
PLUGIN_DEPENDENCIES,
PLUGIN_METABOT,
+ PLUGIN_SUPPORT,
PLUGIN_TRANSFORMS,
} from "metabase/plugins";
@@ -252,7 +253,14 @@ const getRoutes = (store, CanAccessSettings, IsAdmin) => (
>
<ModalRoute path=":jobId" modal={ModelCacheRefreshJobModal} />
</Route>
- <Route path="help" component={Help} />
+ <Route path="help" component={Help}>
+ {PLUGIN_SUPPORT.isEnabled && (
+ <ModalRoute
+ modal={PLUGIN_SUPPORT.GrantAccessModal}
+ path="grant-access"
+ />
+ )}
+ </Route>
<Route path="tasks" component={TasksApp}>
<ModalRoute
path=":taskId"
diff --git a/frontend/src/metabase/admin/tools/components/Help/Help.tsx b/frontend/src/metabase/admin/tools/components/Help/Help.tsx
index 1d51d03335c..e17beceefb4 100644
--- a/frontend/src/metabase/admin/tools/components/Help/Help.tsx
+++ b/frontend/src/metabase/admin/tools/components/Help/Help.tsx
@@ -1,5 +1,5 @@
import cx from "classnames";
-import { useState } from "react";
+import { type PropsWithChildren, useState } from "react";
import { useMount } from "react-use";
import { t } from "ttag";
import _ from "underscore";
@@ -15,6 +15,7 @@ import ExternalLink from "metabase/common/components/ExternalLink";
import { useSetting } from "metabase/common/hooks";
import CS from "metabase/css/core/index.css";
import { useSelector } from "metabase/lib/redux";
+import { PLUGIN_SUPPORT } from "metabase/plugins";
import { getIsPaidPlan } from "metabase/selectors/settings";
import { UtilApi } from "metabase/services";
import { Box, Group } from "metabase/ui";
@@ -89,7 +90,7 @@ const InfoBlock = ({ children }: InfoBlockProps) => (
</Box>
);
-export const Help = () => {
+export const Help = ({ children }: PropsWithChildren) => {
const [details, setDetails] = useState({ "browser-info": navigatorInfo() });
const { tag } = useSetting("version");
const isPaidPlan = useSelector(getIsPaidPlan);
@@ -123,6 +124,8 @@ export const Help = () => {
<UpsellBetterSupport location="settings-troubleshooting" />
+ {PLUGIN_SUPPORT.isEnabled && <PLUGIN_SUPPORT.SupportSettings />}
+
<SettingsSection
title={t`Diagnostic info`}
description={t`Please include these details in support requests. Thank you!`}
@@ -139,6 +142,8 @@ export const Help = () => {
link={UtilApi.get_connection_pool_details_url()}
/>
</SettingsSection>
+ {/* render 'children' so that the child modal routes can show up */}
+ {children}
</SettingsPageWrapper>
);
};
diff --git a/frontend/src/metabase/common/components/ConfirmModal/ConfirmModal.tsx b/frontend/src/metabase/common/components/ConfirmModal/ConfirmModal.tsx
index 938ba4b184c..f8a198e13c5 100644
--- a/frontend/src/metabase/common/components/ConfirmModal/ConfirmModal.tsx
+++ b/frontend/src/metabase/common/components/ConfirmModal/ConfirmModal.tsx
@@ -48,7 +48,7 @@ export const ConfirmModal = ({
return (
<Modal title={title} onClose={onClose} size="lg" {...props}>
- <Flex direction="column" gap="lg" mt="lg">
+ <Flex direction="column" gap="lg" mt="md">
{content ? <Text>{content}</Text> : null}
<Text>{message}</Text>
<Flex align="center" justify="space-between" gap="md">
diff --git a/frontend/src/metabase/lib/urls/admin.ts b/frontend/src/metabase/lib/urls/admin.ts
index df46fcad4aa..3bef5f0648d 100644
--- a/frontend/src/metabase/lib/urls/admin.ts
+++ b/frontend/src/metabase/lib/urls/admin.ts
@@ -95,3 +95,7 @@ export function adminToolsErrors() {
export function adminToolsModelCaching() {
return "/admin/tools/model-caching";
}
+
+export function adminToolsGrantAccess() {
+ return "/admin/tools/help/grant-access";
+}
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 470a6cafdc1..f8de67d4367 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -943,6 +943,16 @@ export const PLUGIN_REMOTE_SYNC: {
}),
};
+export const PLUGIN_SUPPORT: {
+ isEnabled: boolean;
+ SupportSettings: ComponentType;
+ GrantAccessModal: ComponentType<{ onClose: VoidFunction }>;
+} = {
+ isEnabled: false,
+ SupportSettings: NotFoundPlaceholder,
+ GrantAccessModal: NotFoundPlaceholder,
+};
+
export type PythonTransformEditorProps = {
name?: string;
source: PythonTransformSourceDraft;
diff --git a/frontend/src/metabase/ui/components/overlays/Overlay/index.tsx b/frontend/src/metabase/ui/components/overlays/Overlay/index.tsx
index 02a3277e0aa..8881cdba7ed 100644
--- a/frontend/src/metabase/ui/components/overlays/Overlay/index.tsx
+++ b/frontend/src/metabase/ui/components/overlays/Overlay/index.tsx
@@ -7,6 +7,7 @@ import {
import { PreventEagerPortal } from "metabase/ui";
export { type OverlayProps } from "@mantine/core";
+export { LoadingOverlay } from "@mantine/core";
export { overlayOverrides } from "./Overlay.config";
/**
diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.ts
index 97415c4f609..0c662dcad1c 100644
--- a/frontend/test/__support__/server-mocks/index.ts
+++ b/frontend/test/__support__/server-mocks/index.ts
@@ -40,6 +40,7 @@ export * from "./settings";
export * from "./setup";
export * from "./slack";
export * from "./store";
+export * from "./support-access-grants";
export * from "./table";
export * from "./task";
export * from "./timeline";
diff --git a/frontend/test/__support__/server-mocks/support-access-grants.ts b/frontend/test/__support__/server-mocks/support-access-grants.ts
new file mode 100644
index 00000000000..1e570e36069
--- /dev/null
+++ b/frontend/test/__support__/server-mocks/support-access-grants.ts
@@ -0,0 +1,60 @@
+import fetchMock from "fetch-mock";
+
+import type { SupportAccessGrant } from "metabase-types/api";
+
+export function setupCreateAccessGrantEndpoint(
+ createdAccessGrant: SupportAccessGrant,
+) {
+ fetchMock.post("path:/api/ee/support-access-grant", createdAccessGrant);
+}
+
+export function setupCreateAccessGrantEndpointWithError(error: string) {
+ fetchMock.post("path:/api/ee/support-access-grant", {
+ status: 500,
+ body: error,
+ });
+}
+
+export function setupRevokeAccessGrantEndpoint(
+ grantId: number,
+ revokedGrant: SupportAccessGrant,
+) {
+ fetchMock.put(
+ `path:/api/ee/support-access-grant/${grantId}/revoke`,
+ revokedGrant,
+ );
+}
+
+export function setupRevokeAccessGrantEndpointWithError(grantId: number) {
+ fetchMock.put(`path:/api/ee/support-access-grant/${grantId}/revoke`, {
+ status: 500,
+ });
+}
+
+export function setupListAccessGrantsEndpoint(
+ accessGrants: SupportAccessGrant[],
+ total?: number,
+) {
+ fetchMock.get("path:/api/ee/support-access-grant", {
+ data: accessGrants,
+ total: total ?? accessGrants.length,
+ limit: 10,
+ offset: 0,
+ });
+}
+
+export function setupListAccessGrantsEndpointWithError(error: string) {
+ fetchMock.get("path:/api/ee/support-access-grant", {
+ status: 500,
+ body: error,
+ });
+}
+
+export function setupCurrentAccessGrantEndpoint(
+ currentGrant: SupportAccessGrant | null,
+) {
+ fetchMock.get("path:/api/ee/support-access-grant/current", {
+ status: currentGrant ? 200 : 204,
+ body: currentGrant || "",
+ });
+}
diff --git a/resources/migrations/058_update_migrations.yaml b/resources/migrations/058_update_migrations.yaml
index a0c1cdafe6c..a2b6107b8dc 100644
--- a/resources/migrations/058_update_migrations.yaml
+++ b/resources/migrations/058_update_migrations.yaml
@@ -159,6 +159,156 @@ databaseChangeLog:
tableName: auth_identity
constraintName: unique_auth_identity_user_provider
+ - changeSet:
+ id: v58.2025-11-06T15:00:43
+ author: edpaget
+ comment: Create support_access_grant_log table for tracking support access grants
+ changes:
+ - createTable:
+ tableName: support_access_grant_log
+ remarks: Store support access grant requests and their lifecycle for audit purposes
+ columns:
+ - column:
+ name: id
+ type: int
+ autoIncrement: true
+ remarks: Unique identifier for the grant
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: user_id
+ type: int
+ remarks: ID of the admin user who created this grant
+ constraints:
+ nullable: true
+ - column:
+ name: ticket_number
+ type: varchar(100)
+ remarks: Support ticket number associated with this grant
+ constraints:
+ nullable: true
+ - column:
+ name: notes
+ type: varchar(255)
+ remarks: Additional notes associated with this grant
+ constraints:
+ nullable: true
+ - column:
+ name: grant_start_timestamp
+ type: ${timestamp_type}
+ remarks: When the grant becomes active (UTC)
+ constraints:
+ nullable: false
+ - column:
+ name: grant_end_timestamp
+ type: ${timestamp_type}
+ remarks: When the grant expires (UTC)
+ constraints:
+ nullable: false
+ - column:
+ name: revoked_at
+ type: ${timestamp_type}
+ remarks: When the grant was manually revoked (UTC), null if not revoked
+ constraints:
+ nullable: true
+ - column:
+ name: revoked_by_user_id
+ type: int
+ remarks: ID of the admin user who revoked this grant
+ constraints:
+ nullable: true
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ defaultValueComputed: current_timestamp
+ remarks: When this record was created (UTC)
+ constraints:
+ nullable: false
+ - column:
+ name: updated_at
+ type: ${timestamp_type}
+ defaultValueComputed: current_timestamp
+ remarks: When this record was last updated (UTC)
+ constraints:
+ nullable: false
+ rollback:
+ - dropTable:
+ tableName: support_access_grant_log
+
+ - changeSet:
+ id: v58.2025-11-06T15:01:00
+ author: edpaget
+ comment: Add index for finding support access grants by user
+ changes:
+ - createIndex:
+ indexName: idx_support_access_grant_log_user_id
+ tableName: support_access_grant_log
+ columns:
+ - column:
+ name: user_id
+
+ - changeSet:
+ id: v58.2025-11-06T15:01:01
+ author: edpaget
+ comment: Add index for finding support access grants by revoked_by_user_id
+ changes:
+ - createIndex:
+ indexName: idx_support_access_grant_log_revoked_by_user_id
+ tableName: support_access_grant_log
+ columns:
+ - column:
+ name: revoked_by_user_id
+
+ - changeSet:
+ id: v58.2025-11-06T15:01:02
+ author: edpaget
+ comment: Add foreign key constraint from support_access_grant_log.user_id to core_user with SET NULL on delete
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: support_access_grant_log
+ baseColumnNames: user_id
+ constraintName: fk_support_access_grant_log_user_id
+ referencedTableName: core_user
+ referencedColumnNames: id
+ onDelete: SET NULL
+ rollback:
+ - dropForeignKeyConstraint:
+ baseTableName: support_access_grant_log
+ constraintName: fk_support_access_grant_log_user_id
+
+ - changeSet:
+ id: v58.2025-11-06T15:01:03
+ author: edpaget
+ comment: Add foreign key constraint from support_access_grant_log.revoked_by_user_id to core_user with SET NULL on delete
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: support_access_grant_log
+ baseColumnNames: revoked_by_user_id
+ constraintName: fk_support_access_grant_log_revoked_by_user_id
+ referencedTableName: core_user
+ referencedColumnNames: id
+ onDelete: SET NULL
+ rollback:
+ - dropForeignKeyConstraint:
+ baseTableName: support_access_grant_log
+ constraintName: fk_support_access_grant_log_revoked_by_user_id
+
+ - changeSet:
+ id: v58.2025-11-06T15:01:04
+ author: edpaget
+ comment: Add index for finding active support access grants
+ changes:
+ - createIndex:
+ indexName: idx_support_access_grant_log_active
+ tableName: support_access_grant_log
+ columns:
+ - column:
+ name: grant_end_timestamp
+ - column:
+ name: revoked_at
+ where: revoked_at IS NULL
+
- changeSet:
id: v58.2025-11-12T00:00:00
author: edpaget
diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.clj
index af32f5c8d91..b98fed53e81 100644
--- a/src/metabase/analytics/stats.clj
+++ b/src/metabase/analytics/stats.clj
@@ -893,7 +893,10 @@
:enabled (premium-features/enable-python-transforms?)}
{:name :dependencies
:available (premium-features/enable-dependencies?)
- :enabled (premium-features/enable-dependencies?)}])
+ :enabled (premium-features/enable-dependencies?)}
+ {:name :support-users
+ :available (premium-features/enable-support-users?)
+ :enabled (premium-features/enable-support-users?)}])
(defn- snowplow-features
[]
diff --git a/src/metabase/auth_identity/core.clj b/src/metabase/auth_identity/core.clj
index db9a5166e32..8a6c7f8e32a 100644
--- a/src/metabase/auth_identity/core.clj
+++ b/src/metabase/auth_identity/core.clj
@@ -59,4 +59,17 @@
;; Import emailed-secret provider functions
(p/import-vars
[emailed-secret
- create-password-reset!])
+ create-password-reset!
+ create-reset-token-metadata
+ generate-reset-token
+ mark-token-consumed])
+
+(defn with-fallback
+ "Try multiple providers until one works. Always returns the result of the last provider run."
+ [method [provider & rst-providers] request]
+ (let [{:keys [success?] :as response} (try (method provider request)
+ (catch Throwable _
+ {:success? false}))]
+ (if (or success? (empty? rst-providers))
+ response
+ (recur method rst-providers request))))
diff --git a/src/metabase/auth_identity/models/auth_identity.clj b/src/metabase/auth_identity/models/auth_identity.clj
index 4b8297e72c6..607a2b35473 100644
--- a/src/metabase/auth_identity/models/auth_identity.clj
+++ b/src/metabase/auth_identity/models/auth_identity.clj
@@ -27,17 +27,13 @@
(defn- parse-credentials-timestamps-out
"Parse timestamp strings in credentials to java.time.Instant when reading from database."
[credentials]
- (when credentials
- (cond-> credentials
- ;; Parse expires_at for emailed_secret providers
- (and (string? (:expires_at credentials))
- (:expires_at credentials))
- (update :expires_at t/instant)
-
- ;; Parse consumed_at for emailed_secret providers
- (and (string? (:consumed_at credentials))
- (:consumed_at credentials))
- (update :consumed_at t/instant))))
+ (into {}
+ (map (fn [[key value]]
+ (cond-> [key value]
+ (and (contains? #{:expires_at :consumed_at :grant_ends_at} key)
+ (string? value))
+ (update 1 t/instant))))
+ credentials))
(t2/deftransforms :model/AuthIdentity
{:credentials {:in mi/json-in
@@ -58,23 +54,24 @@
- Both :password_hash and :password_salt already present (already hashed)
Returns credentials map with :password_hash and :password_salt."
- [{:keys [plaintext_password password_hash password_salt]}]
- (cond
- ;; Already hashed - return as is
- (and password_hash password_salt)
- {:password_hash password_hash
- :password_salt password_salt}
-
- ;; Has plaintext password - hash it
- plaintext_password
- (let [salt (str (random-uuid))
- hash (u.password/hash-bcrypt (str salt plaintext_password))]
- {:password_hash hash
- :password_salt salt})
-
- ;; No password data - return empty map
- :else
- {}))
+ [{:keys [plaintext_password password_hash password_salt] :as credentials}]
+ (-> (merge credentials (cond
+ ;; Already hashed - return as is
+ (and password_hash password_salt)
+ {:password_hash password_hash
+ :password_salt password_salt}
+
+ ;; Has plaintext password - hash it
+ plaintext_password
+ (let [salt (str (random-uuid))
+ hash (u.password/hash-bcrypt (str salt plaintext_password))]
+ {:password_hash hash
+ :password_salt salt})
+
+ ;; No password data - return empty map
+ :else
+ credentials))
+ (dissoc :plaintext_password)))
(t2/define-before-insert :model/AuthIdentity
[{:keys [provider] :as auth-identity}]
diff --git a/src/metabase/auth_identity/providers/emailed_secret.clj b/src/metabase/auth_identity/providers/emailed_secret.clj
index a35d31aa3dd..b42dbfc4104 100644
--- a/src/metabase/auth_identity/providers/emailed_secret.clj
+++ b/src/metabase/auth_identity/providers/emailed_secret.clj
@@ -28,7 +28,7 @@
:expires_at (t/plus (t/instant) (t/millis expires-in-ms))
:consumed_at nil})
-(mu/defn- create-reset-token-metadata
+(mu/defn create-reset-token-metadata
"Creates a metadata map for a password reset token containing the user's email and optional request context.
The `email` parameter is the user's email address. Optional keyword arguments `ip-address` and `user-agent` capture
@@ -64,7 +64,7 @@
:else
:invalid))
-(mu/defn- mark-token-consumed :- [:map [:credentials :map]]
+(mu/defn mark-token-consumed :- [:map [:credentials :map]]
"Marks a token as consumed by setting the `:consumed_at` timestamp in the auth-identity's credentials.
Takes an `auth-identity` map and returns an updated version with the current instant set as the `:consumed_at`
@@ -84,7 +84,7 @@
(catch NumberFormatException _
nil))))
-(mu/defn- generate-reset-token :- :string
+(mu/defn generate-reset-token :- :string
"Generates a password reset token for a user.
The token format is `USER-ID_RANDOM-UUID`, which allows efficient user lookup while maintaining uniqueness and
@@ -144,8 +144,7 @@
(if-let [user-id (parse-token-user-id token)]
(if-let [auth-identity (t2/select-one :model/AuthIdentity
:user_id user-id
- :provider (case provider
- :provider/emailed-secret-password-reset "emailed-secret-password-reset"))]
+ :provider (name provider))]
(let [verification-result (verify-reset-token token (:credentials auth-identity))]
(case verification-result
:valid
diff --git a/src/metabase/channel/email/support_access_grant.hbs b/src/metabase/channel/email/support_access_grant.hbs
new file mode 100644
index 00000000000..7292e445421
--- /dev/null
+++ b/src/metabase/channel/email/support_access_grant.hbs
@@ -0,0 +1,85 @@
+{{> metabase/channel/email/_dashsub_alert_header.hbs }}
+ <body style="padding: 0px; margin: 0px">
+ <table class="background" width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #F9F9F9; padding: 48px; table-layout: fixed;">
+ <tr>
+ <td>
+ <div class="container" style="background-color: white; max-width: 555px; border-radius: 24px; margin: 0 auto; padding: 40px; border: 1px solid rgba(7, 23, 34, 0.14)">
+ <div style="text-align: center; height: 45px; margin-bottom: 32px;">
+ <img width="35.55" height="45" src="{{context.application_logo_url}}" alt="Metabase logo"/>
+ </div>
+
+ <h1 style="text-align: center; font-size: 27px; line-height: 36px; font-weight: 400; margin: 0 0 8px 0; color: #2F3C45;">
+ Support Access Grant Created
+ </h1>
+
+ <p style="text-align: center; font-size: 15px; line-height: 165%; color: #656F76; margin: 0 0 32px 0;">
+ A support access grant has been created for a Metabase instance.
+ </p>
+
+ {{!-- Grant details --}}
+ <div style="background-color: #FAFAFB; border-radius: 12px; padding: 24px; margin: 0 auto 32px auto;">
+ <table style="width: 100%; font-size: 14px; color: #2F3C45; border-collapse: collapse;">
+ <tr>
+ <td style="padding: 8px 0; font-weight: 700; width: 40%;">Duration:</td>
+ <td style="padding: 8px 0;">{{payload.event_info.duration_minutes}} minutes</td>
+ </tr>
+ <tr>
+ <td style="padding: 8px 0; font-weight: 700;">Expires:</td>
+ <td style="padding: 8px 0;">{{format-date payload.event_info.grant_end_time "MMM d, yyyy 'at' h:mm a"}} UTC</td>
+ </tr>
+ </table>
+
+ {{#if payload.event_info.notes}}
+ <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid rgba(7, 23, 34, 0.08);">
+ <div style="font-weight: 700; font-size: 14px; color: #2F3C45; margin-bottom: 8px;">Notes:</div>
+ <div style="font-size: 14px; color: #656F76; line-height: 20px; white-space: pre-wrap;">{{payload.event_info.notes}}</div>
+ </div>
+ {{/if}}
+
+ {{#if payload.event_info.ticket_number}}
+ <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid rgba(7, 23, 34, 0.08);">
+ <div style="font-size: 12px; color: #92999E;">
+ Reference: {{payload.event_info.ticket_number}}
+ </div>
+ </div>
+ {{/if}}
+ </div>
+
+ {{!-- CTA button --}}
+ <div style="text-align: center; margin: 12px 0 32px 0;">
+ <a href="{{payload.event_info.password_reset_url}}"
+ style="display: inline-block; background-color: {{context.application_color}}; color: #ffffff !important; font-weight: 700; font-size: 14px; border-radius: 8px; padding: 12px 16px; text-decoration: none;">
+ Set Password & Access Instance
+ </a>
+ </div>
+
+ <p style="font-size: 13px; line-height: 20px; color: #656F76; text-align: center; margin: 0;">
+ This link will expire when the grant period ends.
+ </p>
+
+ <hr style="margin-top: 32px; margin-bottom: 32px;">
+ <div style="font-size: 12px; line-height: 16px; width: max-content; margin: 0 auto; color: #656F76; text-align: center;">
+ Sent from <a href="{{context.site_url}}" style="color: {{context.application_color}}">{{context.site_url}}</a>.
+ </div>
+ </div>
+
+ <div style="margin-top: 40px;">
+ <div style="text-align: center; color: #92999E; font-size: 13px;">
+ Metabase, Inc.
+ </div>
+
+ <div style="text-align: center; color: #92999E; font-size: 13px;">
+ 9740 Campo Rd., Suite 1029, Spring Valley, CA 91977
+ </div>
+
+ <div style="text-align: center; margin-top: 8px;">
+ <a href="https://www.metabase.com" style="color: #656F76 !important; font-size: 13px;">
+ www.metabase.com
+ </a>
+ </div>
+ </div>
+ </td>
+ </tr>
+ </table>
+ </body>
+</html>
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 795539461ea..7e504a238c9 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -91,6 +91,7 @@
:model/SemanticSearchTokenTracking metabase-enterprise.semantic-search.models.token-tracking
:model/Session metabase.session.models.session
:model/Setting metabase.settings.models.setting
+ :model/SupportAccessGrantLog metabase-enterprise.support-access-grants.models.support-access-grant-log
:model/Table metabase.warehouse-schema.models.table
:model/TaskHistory metabase.task-history.models.task-history
:model/Timeline metabase.timeline.models.timeline
diff --git a/src/metabase/notification/events/notification.clj b/src/metabase/notification/events/notification.clj
index b48cd1b299a..3af3dd3405a 100644
--- a/src/metabase/notification/events/notification.clj
+++ b/src/metabase/notification/events/notification.clj
@@ -15,7 +15,8 @@
(def ^:private supported-topics #{:event/user-invited
:event/notification-create
:event/slack-token-invalid
- :event/comment-created})
+ :event/comment-created
+ :event/support-access-grant-created})
(def ^:private hydrate-transformer
(mtx/transformer
diff --git a/src/metabase/notification/seed.clj b/src/metabase/notification/seed.clj
index 25734e1520b..aee96407fee 100644
--- a/src/metabase/notification/seed.clj
+++ b/src/metabase/notification/seed.clj
@@ -119,7 +119,25 @@
:path "metabase/channel/email/comment_created.hbs"
:recipient-type "cc"}}
:recipients [{:type :notification-recipient/template
- :details {:pattern "{{payload.event_info.email}}"}}]}]}]))
+ :details {:pattern "{{payload.event_info.email}}"}}]}]}
+
+ ;; support access grant created
+ {:internal_id "system-event/support-access-grant-created"
+ :active true
+ :payload_type :notification/system-event
+ :subscriptions [{:type :notification-subscription/system-event
+ :event_name :event/support-access-grant-created}]
+ :handlers [{:active true
+ :channel_type :channel/email
+ :channel_id nil
+ :template {:name "Support Access Grant Created Email"
+ :channel_type :channel/email
+ :details {:type "email/handlebars-resource"
+ :subject "Support Access Grant Created"
+ :path "metabase/channel/email/support_access_grant.hbs"
+ :recipient-type "cc"}}
+ :recipients [{:type :notification-recipient/template
+ :details {:pattern "{{payload.event_info.support_email}}"}}]}]}]))
(defn- cleanup-notification!
[internal-id existing-row]
diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.clj
index 6a67ff2a02a..113d948df86 100644
--- a/src/metabase/premium_features/core.clj
+++ b/src/metabase/premium_features/core.clj
@@ -74,6 +74,7 @@
enable-sso-jwt?
enable-sso-ldap?
enable-sso-saml?
+ enable-support-users?
enable-transforms?
enable-python-transforms?
enable-upload-management?
diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.clj
index 57871a0ebe3..1aa5a9f5758 100644
--- a/src/metabase/premium_features/settings.clj
+++ b/src/metabase/premium_features/settings.clj
@@ -311,6 +311,10 @@
"Should we allow users to use dependency tracking?"
:dependencies)
+(define-premium-feature ^{:added "0.57.1"} enable-support-users?
+ "Should users be allowed to enable support users in-app?"
+ :support-users)
+
(defn- -token-features []
{:advanced_permissions (enable-advanced-permissions?)
:ai_sql_fixer (enable-ai-sql-fixer?)
@@ -357,6 +361,7 @@
:sso_jwt (enable-sso-jwt?)
:sso_ldap (enable-sso-ldap?)
:sso_saml (enable-sso-saml?)
+ :support-users (enable-support-users?)
:table_data_editing (table-data-editing?)
:transforms (enable-transforms?)
:transforms-python (enable-python-transforms?)
diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.clj
index 36144f4e072..edf00ae576e 100644
--- a/src/metabase/session/api.clj
+++ b/src/metabase/session/api.clj
@@ -71,7 +71,7 @@
:password password
:device-info device-info})]
(cond
- (contains? {:invalid-credentials :server-error} (:error result)) nil
+ (contains? #{:invalid-credentials :server-error :authentication-expired} (:error result)) nil
(:success? result) (:session result)
:else (throw (ex-info (str (:message result)) {:errors {:_error (:error result)}
:status-code 401})))))
@@ -158,11 +158,14 @@
(defn- password-reset-disabled?
"Disable password reset for all users created with SSO logins, unless those Users were created with Google SSO
- in which case disable reset for them as long as the Google SSO feature is enabled."
- [sso-source]
- (if (and (= sso-source :google) (not (sso/sso-enabled?)))
- (sso/google-auth-enabled)
- (some? sso-source)))
+ in which case disable reset for them as long as the Google SSO feature is enabled.
+
+ Disable password reset for any support users -- users with a auth-identity of type `support-access-request`."
+ [user-id sso-source]
+ (cond
+ (t2/exists? :model/AuthIdentity :user_id user-id :provider "support-access-grant") true
+ (and (= sso-source :google) (not (sso/sso-enabled?))) (sso/google-auth-enabled)
+ :else (some? sso-source)))
(defn- forgot-password-impl
[email]
@@ -173,7 +176,7 @@
(t2/select-one [:model/User :id :sso_source :is_active]
:%lower.email
(u/lower-case-en email))]
- (if (password-reset-disabled? sso-source)
+ (if (password-reset-disabled? user-id sso-source)
;; If user uses any SSO method to log in, no need to generate a reset token. Some cases for Google SSO
;; are exempted see `password-reset-allowed?`
(messages/send-password-reset-email! email sso-source nil is-active?)
@@ -216,7 +219,10 @@
request]
(let [request-source (request/ip-address request)]
(throttle-check reset-password-throttler request-source))
- (let [auth-result (auth-identity/login! :provider/emailed-secret-password-reset request-body)]
+ (let [auth-result (auth-identity/with-fallback auth-identity/login!
+ [:provider/support-access-grant
+ :provider/emailed-secret-password-reset]
+ request-body)]
(if (:success? auth-result)
(request/set-session-cookies request
{:success true :session_id (get-in auth-result [:session :key])}
@@ -231,7 +237,10 @@
[_route-params
{:keys [token]} :- [:map
[:token ms/NonBlankString]]]
- (let [auth-result (auth-identity/authenticate :provider/emailed-secret-password-reset {:token token})]
+ (let [auth-result (auth-identity/with-fallback auth-identity/authenticate
+ [:provider/support-access-grant
+ :provider/emailed-secret-password-reset]
+ {:token token})]
{:valid (:success? auth-result)}))
(api.macros/defendpoint :get "/properties"
diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.clj
index 27668506a3e..665f45e231e 100644
--- a/test/metabase/cmd/copy_test.clj
+++ b/test/metabase/cmd/copy_test.clj
@@ -43,6 +43,7 @@
:model/RemoteSyncTask
:model/SearchIndexMetadata
:model/SemanticSearchTokenTracking
+ :model/SupportAccessGrantLog
:model/TaskHistory
;; TODO we should remove these models from here once serialization is supported
:model/Transform