Skip to content

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

feat: add Slack Connect SSO provider (#67955)

Edward Paget3c72591b17c8
diff --git a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj b/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
index 484d36b29fa..22e05340cc1 100644
--- a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
+++ b/enterprise/backend/src/metabase_enterprise/analytics/stats.clj
@@ -20,6 +20,9 @@
{:name :sso-saml
:available (premium-features/enable-sso-saml?)
:enabled (sso-settings/saml-enabled)}
+ {:name :sso-slack
+ :available (premium-features/enable-sso-slack?)
+ :enabled (sso-settings/slack-connect-enabled)}
{:name :scim
:available (premium-features/enable-scim?)
:enabled (boolean (scim/scim-enabled))}
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj b/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
index b2fbdc8e7b3..7a1f5337d2d 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
@@ -10,21 +10,33 @@
preferred-method (case preferred-method
"jwt" :jwt
"saml" :saml
+ "slack-connect" :slack-connect
(throw (ex-info "Invalid auth method"
{:preferred-method preferred-method
- :available [:jwt :saml]})))
+ :available [:jwt :saml :slack-connect]})))
(contains? (:params req) :jwt) :jwt
:else :saml)))
(defn- sso-backend
"Function that powers the defmulti in figuring out which SSO backend to use. It might be that we need to have more
- complex logic around this, but now it's just a simple priority. If SAML is configured use that otherwise JWT"
+ complex logic around this, but now it's just a simple priority. If multiple SSO methods are enabled, uses
+ preferred_method parameter if provided."
[req]
- (cond
- (and (sso-settings/saml-enabled) (sso-settings/jwt-enabled)) (select-sso-backend req)
- (sso-settings/saml-enabled) :saml
- (sso-settings/jwt-enabled) :jwt
- :else nil))
+ (let [enabled-count (count (filter identity
+ [(sso-settings/saml-enabled)
+ (sso-settings/jwt-enabled)
+ (sso-settings/slack-connect-enabled)]))]
+ (cond
+ ;; Multiple SSO methods enabled - use preferred_method or selection logic
+ (> enabled-count 1) (select-sso-backend req)
+
+ ;; Single SSO method enabled
+ (sso-settings/saml-enabled) :saml
+ (sso-settings/jwt-enabled) :jwt
+ (sso-settings/slack-connect-enabled) :slack-connect
+
+ ;; No SSO method enabled
+ :else nil)))
(defmulti sso-get
"Multi-method for supporting the first part of an SSO signin request. An implementation of this method will usually
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
index f40c740901b..4117e6b9443 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
@@ -7,6 +7,7 @@
[metabase-enterprise.sso.api.interface :as sso.i]
[metabase-enterprise.sso.integrations.jwt :as jwt]
[metabase-enterprise.sso.integrations.saml]
+ [metabase-enterprise.sso.integrations.slack-connect]
[metabase-enterprise.sso.settings :as sso-settings]
[metabase.api.macros :as api.macros]
[metabase.request.core :as request]
diff --git a/enterprise/backend/src/metabase_enterprise/sso/init.clj b/enterprise/backend/src/metabase_enterprise/sso/init.clj
index 511439aa6e7..d527cb0b026 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/init.clj
@@ -3,4 +3,5 @@
[metabase-enterprise.sso.integrations.google] ; has a `define-multi-setting` impl
[metabase-enterprise.sso.providers.jwt]
[metabase-enterprise.sso.providers.saml]
+ [metabase-enterprise.sso.providers.slack-connect]
[metabase-enterprise.sso.settings]))
diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/slack_connect.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/slack_connect.clj
new file mode 100644
index 00000000000..7e808acbb85
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/slack_connect.clj
@@ -0,0 +1,111 @@
+(ns metabase-enterprise.sso.integrations.slack-connect
+ "Implementation of the Slack Connect backend for SSO.
+
+ Slack Connect uses OIDC (OpenID Connect) for authentication, which only uses GET requests.
+ Both the initial authorization request and the callback are handled via GET.
+
+ Flow:
+ 1. User accesses GET /auth/sso?preferred_method=slack-connect
+ 2. Metabase redirects to Slack authorization endpoint
+ 3. User authenticates with Slack
+ 4. Slack redirects back to GET /auth/sso?code=...&state=...
+ 5. Metabase exchanges code for tokens and creates session"
+ (:require
+ [java-time.api :as t]
+ [metabase-enterprise.sso.api.interface :as sso.i]
+ [metabase-enterprise.sso.integrations.sso-utils :as sso-utils]
+ [metabase-enterprise.sso.settings :as sso-settings]
+ [metabase.api.common :as api]
+ [metabase.auth-identity.core :as auth-identity]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.request.core :as request]
+ [metabase.sso.core :as sso]
+ [metabase.system.core :as system]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.log :as log]
+ [ring.util.response :as response]))
+
+(set! *warn-on-reflection* true)
+
+(defn- slack-redirect-uri
+ "Generate the redirect URI for Slack OIDC callback."
+ []
+ (str (system/site-url) "/auth/sso"))
+
+(defmethod sso.i/sso-get :slack-connect
+ [{{:keys [code state redirect]} :params
+ :as request}]
+ ;; Check premium feature is available
+ (premium-features/assert-has-feature :sso-slack (tru "Slack Connect authentication"))
+
+ (when-not (sso-settings/slack-connect-enabled)
+ (throw (ex-info (tru "Slack Connect is not enabled")
+ {:status-code 400})))
+
+ (cond
+ ;; Case 1: Initial request (no code) - start auth flow
+ (not code)
+ (let [_ (when (and (= "link-only" (sso-settings/slack-connect-authentication-mode))
+ (not api/*current-user-id*))
+ (throw (ex-info (tru "Account linking requires an authenticated session")
+ {:status-code 401})))
+ redirect-url (if redirect
+ (sso-utils/check-sso-redirect redirect)
+ "/")
+ auth-result (auth-identity/authenticate :provider/slack-connect
+ (assoc request
+ :authenticated-user api/*current-user*
+ :redirect-uri (slack-redirect-uri)
+ :final-redirect redirect-url))]
+
+ (cond
+ (= :redirect (:success? auth-result))
+ ;; Use encrypted cookie for state storage
+ (sso/wrap-oidc-redirect auth-result
+ request
+ :slack-connect
+ redirect-url
+ {:browser-id (:browser-id request)})
+ :else
+ (throw (ex-info (or (:message auth-result) (tru "Failed to initiate Slack authentication"))
+ {:status-code 500}))))
+
+ ;; Case 2: Callback with code - complete authentication
+ ;; State validation happens inside login! via the OIDC provider
+ code
+ (let [login-result (auth-identity/login! :provider/slack-connect
+ (assoc request
+ :authenticated-user api/*current-user*
+ :code code
+ :state state
+ :oidc-provider :slack-connect
+ :redirect-uri (slack-redirect-uri)
+ :device-info (request/device-info request)))]
+
+ (cond
+ (:success? login-result)
+ (let [final-redirect (or (:redirect-url login-result) "/")
+ base-response (-> (response/redirect final-redirect)
+ (sso/clear-oidc-state-cookie))]
+ (log/infof "Slack authentication successful for user %s" (get-in login-result [:user :email]))
+ ;; In link-only mode, there's no session to set - just return the redirect
+ (if-let [session (:session login-result)]
+ (request/set-session-cookies request
+ base-response
+ session
+ (t/zoned-date-time (t/zone-id "GMT")))
+ base-response))
+
+ ;; Login failed (includes state validation failures)
+ :else
+ (let [error-msg (or (:message login-result) (tru "Slack authentication failed"))]
+ (log/errorf "Slack authentication failed: %s" error-msg)
+ (throw (ex-info error-msg {:status-code 401})))))))
+
+;; OIDC only uses GET requests, so POST should not be used.
+;; Return 405 Method Not Allowed.
+(defmethod sso.i/sso-post :slack-connect
+ [_request]
+ {:status 405
+ :headers {"Allow" "GET"}
+ :body (tru "POST not supported for OIDC authentication. Use GET instead.")})
diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj
index 9a143b8a4ba..793d163f469 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_utils.clj
@@ -37,6 +37,10 @@
[_]
(maybe-throw-user-provisioning (sso-settings/jwt-user-provisioning-enabled?)))
+(defmethod check-user-provisioning :slack-connect
+ [_]
+ (maybe-throw-user-provisioning (sso-settings/slack-connect-user-provisioning-enabled)))
+
(defn relative-uri?
"Checks that given `uri` is not an absolute (so no scheme and no host)."
[uri]
diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/slack_connect.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/slack_connect.clj
new file mode 100644
index 00000000000..47c87463b6d
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/slack_connect.clj
@@ -0,0 +1,155 @@
+(ns metabase-enterprise.sso.providers.slack-connect
+ "Slack Connect OIDC authentication provider. Derives from the base OIDC provider
+ and adds Slack-specific configuration and claim extraction."
+ (:require
+ [metabase-enterprise.sso.integrations.sso-utils :as sso-utils]
+ [metabase-enterprise.sso.settings :as sso-settings]
+ [metabase.auth-identity.core :as auth-identity]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.util.i18n :refer [tru]]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;;; -------------------------------------------------- Provider Registration --------------------------------------------------
+
+(derive :provider/slack-connect :provider/oidc)
+
+;;; -------------------------------------------------- Constants --------------------------------------------------
+
+(def provider-name
+ "Provider name for Slack Connect authentication."
+ "slack-connect")
+
+(def slack-issuer-uri
+ "Slack's OIDC issuer URI."
+ "https://slack.com")
+
+(def slack-team-image-claim
+ "Claim key for Slack team image in ID token."
+ "https://slack.com/team_image_230")
+
+;;; -------------------------------------------------- Slack-Specific Utilities --------------------------------------------------
+
+(defn- extract-slack-claims
+ "Extract Slack-specific claims from ID token.
+ Returns map with Slack team and user information for storage in login_attributes.
+ Keys are strings to match the login_attributes schema [:map-of :string :string].
+
+ NOTE: team_name is NOT included in Slack ID tokens per research.
+ Use team_id only or make additional API call if team name is required."
+ [id-token-claims]
+ (let [team-id-claim (sso-settings/slack-connect-attribute-team-id)]
+ (cond-> {}
+ (get id-token-claims team-id-claim)
+ (assoc "slack-team-id" (get id-token-claims team-id-claim))
+
+ (:sub id-token-claims)
+ (assoc "slack-user-id" (:sub id-token-claims))
+
+ (get id-token-claims slack-team-image-claim)
+ (assoc "slack-team-image" (get id-token-claims slack-team-image-claim))
+
+ (:email_verified id-token-claims)
+ (assoc "slack-email-verified" (str (:email_verified id-token-claims)))
+
+ (:locale id-token-claims)
+ (assoc "slack-locale" (:locale id-token-claims)))))
+
+(defn- build-slack-oidc-config
+ "Build OIDC configuration map for parent provider.
+ Uses Slack settings and hardcoded Slack-specific values."
+ [request]
+ (when (and (sso-settings/slack-connect-client-id)
+ (sso-settings/slack-connect-client-secret))
+ {:client-id (sso-settings/slack-connect-client-id)
+ :client-secret (sso-settings/slack-connect-client-secret)
+ :issuer-uri slack-issuer-uri
+ :scopes ["openid" "profile" "email"]
+ :redirect-uri (get request :redirect-uri)}))
+
+;;; -------------------------------------------------- Authentication Implementation --------------------------------------------------
+
+(methodical/defmethod auth-identity/authenticate :provider/slack-connect
+ [_provider request]
+ (cond
+ (not (premium-features/enable-sso-slack?))
+ {:success? false
+ :error :feature-not-available
+ :message (tru "Slack Connect authentication is not available on your plan")}
+
+ (not (sso-settings/slack-connect-enabled))
+ {:success? false
+ :error :slack-connect-not-enabled
+ :message (tru "Slack Connect authentication is not enabled")}
+
+ (not (sso-settings/slack-connect-configured))
+ {:success? false
+ :error :slack-connect-not-configured
+ :message (tru "Slack Connect is not configured")}
+
+ (and (= sso-settings/slack-connect-auth-mode-link-only (sso-settings/slack-connect-authentication-mode))
+ (not (:code request))
+ (not (some-> (:authenticated-user request) deref)))
+ {:success? false
+ :error :authentication-required
+ :message (tru "Account linking requires an authenticated session")}
+
+ :else
+ (let [oidc-config (build-slack-oidc-config request)]
+ (if-not oidc-config
+ {:success? false
+ :error :configuration-error
+ :message (tru "Failed to build Slack OIDC configuration")}
+
+ (let [auth-result (next-method _provider (assoc request :oidc-config oidc-config))]
+ (if (and (:success? auth-result)
+ (:user-data auth-result))
+ (let [id-token-claims (or (get-in request [:id-token :claims])
+ (get auth-result :claims))
+ slack-attrs (when id-token-claims
+ (extract-slack-claims id-token-claims))]
+ (cond-> (assoc-in auth-result [:user-data :sso_source] :slack)
+ slack-attrs
+ (assoc-in [:user-data :login_attributes] slack-attrs)
+
+ slack-attrs
+ (assoc :slack-data slack-attrs)))
+ auth-result))))))
+
+;;; -------------------------------------------------- Login Implementation --------------------------------------------------
+
+(defn- create-auth-identity-for-link!
+ "Create an AuthIdentity record linking an authenticated user to their Slack identity.
+ Used in link-only mode where we don't create users or sessions."
+ [user-id provider-id]
+ (when (and user-id provider-id)
+ (when-not (t2/exists? :model/AuthIdentity
+ :user_id user-id
+ :provider provider-name)
+ (t2/insert! :model/AuthIdentity
+ {:user_id user-id
+ :provider provider-name
+ :provider_id provider-id}))))
+
+(methodical/defmethod auth-identity/login! :provider/slack-connect
+ [provider {:keys [user authenticated-user user-data] :as request}]
+ (condp = (sso-settings/slack-connect-authentication-mode)
+ sso-settings/slack-connect-auth-mode-sso
+ (do (when-not user
+ (sso-utils/check-user-provisioning (keyword provider-name)))
+ (next-method provider request))
+
+ sso-settings/slack-connect-auth-mode-link-only
+ ;; In link-only mode, create AuthIdentity for the authenticated user
+ ;; but don't create a session or new user
+ (do
+ (create-auth-identity-for-link! (:id @authenticated-user) (:provider-id user-data))
+ (assoc request :success? true))))
+
+(methodical/defmethod auth-identity/login! :after :provider/slack-connect
+ [_provider result]
+ (if (= sso-settings/slack-connect-auth-mode-link-only (sso-settings/slack-connect-authentication-mode))
+ (dissoc result :user)
+ result))
diff --git a/enterprise/backend/src/metabase_enterprise/sso/settings.clj b/enterprise/backend/src/metabase_enterprise/sso/settings.clj
index a9152c7b8a5..74e9f5ac6a6 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/settings.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/settings.clj
@@ -318,13 +318,6 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e
:getter (fn [] (setting/get-value-of-type :boolean :send-new-sso-user-admin-email?))
:setter (fn [send-emails] (setting/set-value-of-type! :boolean :send-new-sso-user-admin-email? send-emails)))
-(defsetting other-sso-enabled?
- "Are we using an SSO integration other than LDAP or Google Auth? These integrations use the `/auth/sso` endpoint for
- authorization rather than the normal login form or Google Auth button."
- :visibility :public
- :setter :none
- :getter (fn [] (or (saml-enabled) (jwt-enabled))))
-
(defsetting ldap-sync-user-attributes
(deferred-tru "Should we sync user attributes when someone logs in via LDAP?")
:type :boolean
@@ -344,3 +337,93 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e
:encryption :no
:default "(member={dn})"
:audit :getter)
+
+;;; ------------------------------------------------ Slack Connect ------------------------------------------------
+
+(defsetting slack-connect-client-id
+ (deferred-tru "Client ID for your Slack app. Get this from https://api.slack.com/apps")
+ :encryption :when-encryption-key-set
+ :export? false
+ :feature :sso-slack
+ :audit :getter)
+
+(defsetting slack-connect-client-secret
+ (deferred-tru "Client Secret for your Slack app")
+ :encryption :when-encryption-key-set
+ :export? false
+ :sensitive? true
+ :feature :sso-slack
+ :audit :no-value)
+
+(def slack-connect-auth-mode-sso
+ "Authentication mode for full SSO login."
+ "sso")
+
+(def slack-connect-auth-mode-link-only
+ "Authentication mode for account linking only (no session creation)."
+ "link-only")
+
+(defsetting slack-connect-authentication-mode
+ (deferred-tru "Controls whether Slack can be used for SSO login or just account linking. Valid values: \"sso\" (default) or \"link-only\"")
+ :type :string
+ :export? false
+ :default slack-connect-auth-mode-sso
+ :feature :sso-slack
+ :audit :getter
+ :encryption :no
+ :setter (fn [new-value]
+ (when (and new-value
+ (not (contains? #{slack-connect-auth-mode-sso slack-connect-auth-mode-link-only} new-value)))
+ (throw (ex-info (tru "Invalid authentication mode. Must be \"sso\" or \"link-only\"")
+ {:status-code 400})))
+ (setting/set-value-of-type! :string :slack-connect-authentication-mode new-value)))
+
+(defsetting slack-connect-user-provisioning-enabled
+ (deferred-tru "When a user logs in via Slack Connect, create a Metabase account for them automatically if they don''t have one.")
+ :type :boolean
+ :export? false
+ :default true
+ :feature :sso-slack
+ :getter (fn []
+ (if (= (slack-connect-authentication-mode) slack-connect-auth-mode-link-only)
+ false
+ (setting/get-value-of-type :boolean :slack-connect-user-provisioning-enabled)))
+ :audit :getter)
+
+(defsetting slack-connect-attribute-team-id
+ (deferred-tru "Slack OIDC claim for the team/workspace ID")
+ :default "https://slack.com/team_id"
+ :export? false
+ :feature :sso-slack
+ :encryption :when-encryption-key-set
+ :audit :getter)
+
+(defsetting slack-connect-configured
+ (deferred-tru "Are the mandatory Slack Connect settings configured?")
+ :type :boolean
+ :export? false
+ :default false
+ :feature :sso-slack
+ :setter :none
+ :getter (fn [] (boolean
+ (and (slack-connect-client-id)
+ (slack-connect-client-secret)))))
+
+(defsetting slack-connect-enabled
+ (deferred-tru "Is Slack Connect authentication configured and enabled?")
+ :type :boolean
+ :export? false
+ :default false
+ :feature :sso-slack
+ :audit :getter
+ :getter (fn []
+ (if (slack-connect-configured)
+ (setting/get-value-of-type :boolean :slack-connect-enabled)
+ false)))
+
+(defsetting other-sso-enabled?
+ "Are we using an SSO integration other than LDAP or Google Auth? These integrations use the `/auth/sso` endpoint for
+ authorization rather than the normal login form or Google Auth button."
+ :visibility :public
+ :setter :none
+ :getter (fn [] (or (saml-enabled) (jwt-enabled) (slack-connect-enabled))))
diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
index 95e8deb824f..a086ca9a68c 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
+ :sso-slack
:support-users
:transforms
:transforms-python
@@ -97,6 +98,7 @@
:sso_jwt true
:sso_ldap true
:sso_saml true
+ :sso_slack true
:support-users true
:table_data_editing false
:transforms true
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
index e8e993770a1..97dbde1d947 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
@@ -4,19 +4,16 @@
[buddy.sign.util :as buddy-util]
[clojure.string :as str]
[clojure.test :refer :all]
- [metabase-enterprise.sso.integrations.saml-test :as saml-test]
[metabase-enterprise.sso.integrations.token-utils :as token-utils]
[metabase-enterprise.sso.settings :as sso-settings]
+ [metabase-enterprise.sso.test-setup :as sso.test-setup]
[metabase-enterprise.tenants.auth-provider] ;; make sure the auth provider is actually registered
[metabase.appearance.settings :as appearance.settings]
- [metabase.config.core :as config]
- [metabase.premium-features.token-check :as token-check]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.test.http-client :as client]
[metabase.util :as u]
[metabase.util.malli.schema :as ms]
- [metabase.util.random :as u.random]
[toucan2.core :as t2]))
(use-fixtures :once (fixtures/initialize :test-users))
@@ -28,52 +25,20 @@
(use-fixtures :each disable-api-url-prefix)
-(defn- do-with-other-sso-types-disabled! [thunk]
- (mt/with-temporary-setting-values
- [ldap-enabled false
- saml-enabled
- false]
- (thunk)))
-
-(def ^:private default-idp-uri "http://test.idp.metabase.com")
(def ^:private default-redirect-uri "/")
-(def ^:private default-jwt-secret (u.random/secure-hex 32))
-
-(defn- call-with-default-jwt-config! [f]
- (let [current-features (token-check/*token-features*)]
- (mt/with-additional-premium-features #{:sso-jwt}
- (mt/with-temporary-setting-values
- [jwt-enabled
- true
- jwt-identity-provider-uri
- default-idp-uri
- jwt-shared-secret
- default-jwt-secret
- site-url
- (format "http://localhost:%s" (config/config-str :mb-jetty-port))]
- (mt/with-premium-features current-features
- (f))))))
-(defmacro with-default-jwt-config! [& body]
- `(call-with-default-jwt-config!
- (fn []
- ~@body)))
+;; Reference test-helper values for use in token creation
+(def ^:private default-idp-uri sso.test-setup/default-jwt-idp-uri)
+(def ^:private default-jwt-secret sso.test-setup/default-jwt-secret)
-(defmacro ^:private with-jwt-default-setup! [& body]
- `(mt/test-helpers-set-global-values!
- (mt/with-model-cleanup [:model/User :model/Collection :model/Tenant]
- (mt/with-premium-features #{:audit-app}
- (do-with-other-sso-types-disabled!
- (fn []
- (mt/with-additional-premium-features #{:sso-jwt}
- (saml-test/call-with-login-attributes-cleared!
- (fn []
- (call-with-default-jwt-config!
- (fn []
- ~@body)))))))))))
+(defmacro ^:private with-jwt-default-setup!
+ "Set up default JWT configuration for tests.
+ Delegates to [[sso.test-setup/with-jwt-default-setup!]]."
+ [& body]
+ `(sso.test-setup/with-jwt-default-setup! ~@body))
(deftest sso-prereqs-test
- (do-with-other-sso-types-disabled!
+ (sso.test-setup/do-with-other-sso-types-disabled!
(fn []
(mt/with-additional-premium-features #{:sso-jwt}
(testing "SSO requests fail if JWT hasn't been configured or enabled"
@@ -93,15 +58,16 @@
(client/client :get 400 "/auth/sso")))
(testing "SSO requests fail if they don't have a valid premium-features token"
- (with-default-jwt-config!
- (mt/with-premium-features #{}
- (is
- (partial=
- {:cause "SSO has not been enabled and/or configured",
- :data {:status "error-sso-disabled", :status-code 400},
- :message "SSO has not been enabled and/or configured",
- :status "error-sso-disabled"}
- (client/client :get 400 "/auth/sso"))))))))
+ (sso.test-setup/call-with-default-jwt-config!
+ (fn []
+ (mt/with-premium-features #{}
+ (is
+ (partial=
+ {:cause "SSO has not been enabled and/or configured",
+ :data {:status "error-sso-disabled", :status-code 400},
+ :message "SSO has not been enabled and/or configured",
+ :status "error-sso-disabled"}
+ (client/client :get 400 "/auth/sso")))))))))
(testing "SSO requests fail if JWT is enabled but hasn't been configured"
(mt/with-temporary-setting-values
@@ -181,7 +147,7 @@
(deftest jwt-saml-both-enabled-test
(with-jwt-default-setup!
- (saml-test/with-saml-default-setup!
+ (sso.test-setup/with-saml-default-setup!
(mt/with-temporary-setting-values [jwt-enabled true]
(testing "with SAML and JWT configured, a GET request with JWT params should sign in correctly"
(let [response (client/client-real-response :get 302 "/auth/sso"
@@ -195,7 +161,7 @@
:extra "keypairs"
:are "also present"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "redirect URI"
(is
(= default-redirect-uri
@@ -209,7 +175,7 @@
(let [response (client/client-full-response :get 302 "/auth/sso"
{:request-options {:redirect-strategy :none}}
:return_to default-redirect-uri)]
- (is (not (saml-test/successful-login? response)))))
+ (is (not (sso.test-setup/successful-login? response)))))
(testing "with SAML and JWT configured, a GET request with preferred_method=jwt should sign in via JWT"
(let [response (client/client-real-response :get 302 "/auth/sso"
@@ -224,7 +190,7 @@
:extra "keypairs"
:are "also present"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "redirect URI (preferred_method=jwt)"
(is
(= default-redirect-uri
@@ -239,7 +205,7 @@
{:request-options {:redirect-strategy :none}}
:return_to default-redirect-uri
:preferred_method "saml")]
- (is (not (saml-test/successful-login? response)))))))))
+ (is (not (sso.test-setup/successful-login? response)))))))))
(deftest happy-path-test
(testing
@@ -260,7 +226,7 @@
:exp (+ (buddy-util/now) 3600)
:iat (buddy-util/now)}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "redirect URI"
(is
(= default-redirect-uri
@@ -326,7 +292,7 @@
:more "stuff"
:for "the new user"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(let [new-user (t2/select-one :model/User :email "[email protected]")]
(testing "new user"
(is
@@ -371,7 +337,7 @@
:jwt
(jwt/sign {:email "[email protected]"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "new user with no first or last name"
(is
(=?
@@ -396,7 +362,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "update user first and last name"
(is
(=?
@@ -442,7 +408,7 @@
:GrOuPs ["my_group"]
:for "the new user"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is
(=
#{"All Users"
@@ -471,7 +437,7 @@
:last_name "User"
:groups ["developers" "analysts"]}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "user is assigned to groups matching the names from JWT claims"
(is (= #{"All Users" "developers" "analysts"}
(group-memberships
@@ -496,7 +462,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response)))
+ (is (sso.test-setup/successful-login? response)))
;; then log in again
(let [response (client/client-real-response :get 302 "/auth/sso"
@@ -508,7 +474,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))))))
+ (is (sso.test-setup/successful-login? response))))))
(testing "Existing user login attributes are not changed on subsequent logins"
(with-jwt-default-setup!
@@ -525,7 +491,7 @@
:department "Engineering"
:role "Developer"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "initial login attributes are stored"
(is (= nil
(t2/select-one-fn :login_attributes :model/User :email "[email protected]")))))
@@ -543,7 +509,7 @@
:role "Manager"
:location "Remote"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "login attributes remain unchanged from initial login"
(is (= nil
(t2/select-one-fn :login_attributes :model/User :email "[email protected]"))))))))))
@@ -562,7 +528,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response)))
+ (is (sso.test-setup/successful-login? response)))
;; deactivate the user
(t2/update! :model/User :email "[email protected]" {:is_active false})
@@ -577,7 +543,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is (t2/select-one-fn :is_active :model/User :email "[email protected]")))
;; deactivate the user again
@@ -613,7 +579,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is (some? (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))
(is (t2/exists? :model/Tenant :slug "tenant-mctenantson")))
(testing "they should be able to log in again"
@@ -627,7 +593,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response)))))))))))
+ (is (sso.test-setup/successful-login? response)))))))))))
(deftest new-users-should-be-set-to-the-correct-tenant
(with-jwt-default-setup!
@@ -647,7 +613,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is
(= tenant-id (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))
(testing "they should be able to log in again"
@@ -661,7 +627,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is
(= tenant-id (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))))))))))
@@ -683,7 +649,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (not (saml-test/successful-login? response)))
+ (is (not (sso.test-setup/successful-login? response)))
(is
(nil? (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))))
(testing "they should be able to log in without the tenant bit, of course"
@@ -696,7 +662,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is
(nil? (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))))))))
@@ -722,7 +688,7 @@
{:email email
"@tenant" "tenant-mctenantson"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "their name is unchanged"
(is (= [first-name last-name] (t2/select-one-fn (juxt :first_name :last_name) :model/User :email email))))))))))))
@@ -748,7 +714,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is (t2/select-one-fn :is_active :model/Tenant :id tenant-id)))))
(testing "an existing user also fails to log in with correct error message"
(let [response (client/client-real-response :get 302 "/auth/sso"
@@ -761,7 +727,7 @@
:first_name "Existing"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is (t2/select-one-fn :is_active :model/Tenant :id tenant-id))))))))))
(deftest users-cannot-log-into-deactivated-tenant-with-provisioning-disabled
@@ -787,7 +753,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (not (saml-test/successful-login? response)))
+ (is (not (sso.test-setup/successful-login? response)))
(is (not (t2/select-one-fn :is_active :model/Tenant :id tenant-id))))))
(testing "an existing user cannot log into a deactivated tenant"
(let [response (client/client-real-response :get 403 "/auth/sso"
@@ -800,7 +766,7 @@
:first_name "Existing"
:last_name "User"}
default-jwt-secret))]
- (is (not (saml-test/successful-login? response)))
+ (is (not (sso.test-setup/successful-login? response)))
(is (str/includes? (:body response) "Tenant is not active"))
(is (not (t2/select-one-fn :is_active :model/Tenant :id tenant-id))))))))))))
@@ -821,7 +787,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is (nil? (t2/select-one-fn :tenant_id :model/User :email "[email protected]")))))
(testing "now log in WITH a tenant"
(let [response (client/client-real-response :get 302 "/auth/sso"
@@ -834,7 +800,7 @@
:first_name "New"
:last_name "User"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is
(= tenant-id (t2/select-one-fn :tenant_id :model/User :email "[email protected]"))))))))))
@@ -854,7 +820,7 @@
:jwt
(jwt/sign {:email email-with-tenant "@tenant" "other"}
default-jwt-secret))]
- (is (not (saml-test/successful-login? response)))
+ (is (not (sso.test-setup/successful-login? response)))
(is (str/includes? (:body response) "Tenant ID mismatch with existing user")))))))))
(deftest external-user-requires-tenant-claim
@@ -872,7 +838,7 @@
(jwt/sign
{:email email-with-tenant}
default-jwt-secret))]
- (is (not (saml-test/successful-login? response)))
+ (is (not (sso.test-setup/successful-login? response)))
(is (str/includes? (:body response) "Tenant claim required for external user")))))))))
(deftest internal-user-cannot-have-tenant-claim
@@ -891,7 +857,7 @@
{:email email-without-tenant
"@tenant" "tenant-mctenantson"}
default-jwt-secret))]
- (is (not (saml-test/successful-login? response)))
+ (is (not (sso.test-setup/successful-login? response)))
(is (str/includes? (:body response) "Cannot add tenant claim to internal user")))))))))
(deftest internal-user-cannot-login-with-tenant-claim-if-tenants-disabled
@@ -911,7 +877,7 @@
"@tenant" "tenant-mctenantson"
:foo "bar"}
default-jwt-secret))]
- (is (not (saml-test/successful-login? response)))
+ (is (not (sso.test-setup/successful-login? response)))
;; the `@tenant` key is special, does not become a user attribute
(is (nil? (t2/select-one-fn :jwt_attributes :model/User :email email-without-tenant))))))))))
@@ -951,7 +917,7 @@
:null_attr nil
"@attribute" "foo"}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(testing "only string attributes are saved to jwt_attributes"
(is (= {"string_attr" "valid-string"
@@ -1099,7 +1065,7 @@
"@tenant" "test-tenant"
:groups ["engineers"]}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(let [user (t2/select-one :model/User :email "[email protected]")]
(testing "user is assigned to the correct tenant"
(is (= tenant-id (:tenant_id user))))
@@ -1137,7 +1103,7 @@
"@tenant" "test-tenant"
:groups ["tenant-developers" "tenant-analysts"]}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(let [user (t2/select-one :model/User :email "[email protected]")]
(testing "user is assigned to the correct tenant"
(is (= tenant-id (:tenant_id user))))
@@ -1163,7 +1129,7 @@
:last_name "User"
"@tenant" 123}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(is (t2/exists? :model/Tenant :slug "123"))))
(testing "Other non-string values are rejected"
(let [response (client/client-real-response :get 401 "/auth/sso"
@@ -1177,7 +1143,7 @@
"@tenant" false}
default-jwt-secret))]
(is (= "Value of `@tenant` must be a string" (:body response)))
- (is (not (saml-test/successful-login? response)))))
+ (is (not (sso.test-setup/successful-login? response)))))
(testing "Other non-string values are rejected"
(let [response (client/client-real-response :get 401 "/auth/sso"
{:request-options {:redirect-strategy :none}}
@@ -1190,7 +1156,7 @@
"@tenant" {"foo" "bar"}}
default-jwt-secret))]
(is (= "Value of `@tenant` must be a string" (:body response)))
- (is (not (saml-test/successful-login? response))))))))))
+ (is (not (sso.test-setup/successful-login? response))))))))))
(deftest tenant-user-group-sync-on-subsequent-login-test
(testing "JWT tenant user group memberships are synced correctly on subsequent logins"
@@ -1219,7 +1185,7 @@
"@tenant" "test-tenant"
:groups ["Group A"]}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(let [user (t2/select-one :model/User :email "[email protected]")]
(is (= tenant-id (:tenant_id user)))
(is (= #{"All tenant users" "Group A"}
@@ -1235,7 +1201,7 @@
"@tenant" "test-tenant"
:groups ["Group B"]}
default-jwt-secret))]
- (is (saml-test/successful-login? response))
+ (is (sso.test-setup/successful-login? response))
(let [user (t2/select-one :model/User :email "[email protected]")]
(testing "user remains assigned to the same tenant"
(is (= tenant-id (:tenant_id user))))
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
index b1fbbb26c1f..9d39073c0f9 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/saml_test.clj
@@ -6,6 +6,7 @@
[metabase-enterprise.sso.integrations.token-utils :as token-utils]
[metabase-enterprise.sso.providers.saml :as saml.p]
[metabase-enterprise.sso.settings :as sso-settings]
+ [metabase-enterprise.sso.test-setup :as sso.test-setup]
[metabase-enterprise.tenants.auth-provider] ;; make sure the auth provider is actually registered
[metabase.appearance.settings :as appearance.settings]
[metabase.premium-features.token-check :as token-check]
@@ -61,21 +62,13 @@
(def ^:private default-idp-cert (slurp "test_resources/sso/auth0-public-idp.cert"))
(def ^:private slo-idp-cert (slurp "test_resources/sso/idp.cert"))
-(defn call-with-default-saml-config! [f]
- (let [current-features (token-check/*token-features*)]
- (mt/with-premium-features #{:sso-saml}
- (mt/with-temporary-setting-values [saml-enabled true
- saml-identity-provider-uri default-idp-uri
- saml-identity-provider-certificate default-idp-cert
- saml-keystore-path nil
- saml-keystore-password nil
- saml-keystore-alias nil
- site-url "http://localhost:3000"]
- (mt/with-premium-features current-features
- (f))))))
+(def call-with-default-saml-config!
+ "Execute a function with default SAML configuration set up.
+ Delegates to [[sso.test-setup/call-with-default-saml-config!]]."
+ sso.test-setup/call-with-default-saml-config!)
(defmacro with-default-saml-config! [& body]
- `(call-with-default-saml-config!
+ `(sso.test-setup/call-with-default-saml-config!
(fn []
~@body)))
@@ -89,33 +82,22 @@
(when some-bytes
(String. some-bytes "UTF-8")))
-(defn call-with-login-attributes-cleared!
+(def call-with-login-attributes-cleared!
"If login_attributes remain after these tests run, depending on the order that the tests run, lots of tests will
- fail as the login_attributes data from this tests is unexpected in those other tests"
- [thunk]
- (try
- (thunk)
- (finally
- (u/ignore-exceptions
- (t2/update! :model/User {} {:login_attributes nil})
- (t2/update! :model/User {:email "[email protected]"} {:first_name "Rasta" :last_name "Toucan" :sso_source nil})))))
-
-(defmacro with-saml-default-setup! [& body]
- ;; most saml tests make actual http calls, so ensuring any nested with-temp doesn't create transaction
- `(mt/test-helpers-set-global-values!
- (mt/with-additional-premium-features #{:sso-saml}
- (call-with-login-attributes-cleared!
- (fn []
- (call-with-default-saml-config!
- (fn []
- ~@body)))))))
-
-(defn successful-login?
- "Return true if the response indicates a successful user login"
- [resp]
- (or
- (string? (get-in resp [:cookies request/metabase-session-cookie :value]))
- (some #(str/starts-with? % request/metabase-session-cookie) (get-in resp [:headers "Set-Cookie"]))))
+ fail as the login_attributes data from this tests is unexpected in those other tests.
+ Delegates to [[sso.test-setup/call-with-login-attributes-cleared!]]."
+ sso.test-setup/call-with-login-attributes-cleared!)
+
+(defmacro with-saml-default-setup!
+ "Set up default SAML configuration for tests.
+ Delegates to [[sso.test-setup/with-saml-default-setup!]]."
+ [& body]
+ `(sso.test-setup/with-saml-default-setup! ~@body))
+
+(def successful-login?
+ "Return true if the response indicates a successful user login.
+ Delegates to [[sso.test-setup/successful-login?]]."
+ sso.test-setup/successful-login?)
(defn- do-with-some-validators-disabled!
"The sample responses all have `InResponseTo=\"_1\"` and invalid assertion signatures (they were edited by hand) so
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/slack_connect_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/slack_connect_test.clj
new file mode 100644
index 00000000000..16bec564cba
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/slack_connect_test.clj
@@ -0,0 +1,403 @@
+(ns metabase-enterprise.sso.integrations.slack-connect-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.sso.settings :as sso-settings]
+ [metabase-enterprise.sso.test-setup :as sso.test-setup]
+ [metabase.auth-identity.core :as auth-identity]
+ [metabase.sso.oidc.state :as oidc.state]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.test.http-client :as client]
+ [metabase.util.encryption :as encryption]
+ [methodical.core :as methodical]
+ [ring.util.codec :as codec]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(def ^:private test-encryption-key
+ "Test encryption key for OIDC state encryption."
+ "Orw0AAyzkO/kPTLJRxiyKoBHXa/d6ZcO+p+gpZO/wSQ=")
+
+(def ^:private test-secret
+ "Hashed test encryption key."
+ (encryption/secret-key->hash test-encryption-key))
+
+(defmacro ^:private with-test-encryption!
+ "Wraps body with test encryption key enabled. Use for tests that involve OIDC state cookies."
+ [& body]
+ `(with-redefs [encryption/default-secret-key test-secret]
+ ~@body))
+
+(defn- do-with-url-prefix-disabled
+ "Test fixture that disables API URL prefix."
+ [thunk]
+ (binding [client/*url-prefix* ""]
+ (thunk)))
+
+(use-fixtures :each do-with-url-prefix-disabled)
+
+(def ^:private default-redirect-uri "/")
+
+(methodical/defmethod auth-identity/authenticate :provider/test-successful-oidc
+ [_provider request]
+ (if (some #(contains? request %) [:code :error :state])
+ {:success? true
+ :claims {}
+ :user-data {:email "[email protected]"}
+ :provider-id "test-provider-id"}
+ {:success? :redirect
+ :redirect-url "http://example.com/slack"
+ :state "test-state"
+ :nonce "test-nonce"}))
+
+(methodical/prefer-method! #'auth-identity/authenticate :provider/test-successful-oidc :provider/oidc)
+
+(defmacro ^:private with-successful-oidc! [& body]
+ `(do
+ (derive :provider/slack-connect :provider/test-successful-oidc)
+ ~@body
+ (underive :provider/slack-connect :provider/test-successful-oidc)))
+
+;;; -------------------------------------------------- Prerequisites Tests --------------------------------------------------
+
+(deftest sso-prereqs-test
+ (sso.test-setup/do-with-other-sso-types-disabled!
+ (fn []
+ (mt/with-additional-premium-features #{:sso-slack}
+ (testing "SSO requests fail if Slack Connect hasn't been configured or enabled"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled false
+ slack-connect-client-id nil
+ slack-connect-client-secret nil]
+ (is
+ (partial=
+ {:cause "SSO has not been enabled and/or configured",
+ :data {:status "error-sso-disabled", :status-code 400},
+ :message "SSO has not been enabled and/or configured",
+ :status "error-sso-disabled"}
+ (mt/client :get 400 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"))))
+
+ (testing "SSO requests fail if they don't have a valid premium-features token"
+ (sso.test-setup/call-with-default-slack-config!
+ (fn []
+ (mt/with-premium-features #{}
+ (is
+ (partial=
+ {:cause "SSO has not been enabled and/or configured",
+ :data {:status "error-sso-disabled", :status-code 400},
+ :message "SSO has not been enabled and/or configured",
+ :status "error-sso-disabled"}
+ (mt/client :get 400 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"))))))))
+
+ (testing "SSO requests fail if Slack Connect is enabled but hasn't been configured"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id nil]
+ (is
+ (partial=
+ {:cause "SSO has not been enabled and/or configured",
+ :data {:status "error-sso-disabled", :status-code 400},
+ :message "SSO has not been enabled and/or configured",
+ :status "error-sso-disabled"}
+ (mt/client :get 400 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect")))))
+
+ (testing "SSO requests fail if Slack Connect is configured but hasn't been enabled"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled false
+ slack-connect-client-id "test-slack-client-id"
+ slack-connect-client-secret "test-slack-client-secret"]
+ (is
+ (partial=
+ {:cause "SSO has not been enabled and/or configured",
+ :data {:status "error-sso-disabled", :status-code 400},
+ :message "SSO has not been enabled and/or configured",
+ :status "error-sso-disabled"}
+ (mt/client :get 400 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect")))))
+
+ (testing "The client secret must also be included for SSO to be configured"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-slack-client-id"
+ slack-connect-client-secret nil]
+ (is
+ (partial=
+ {:cause "SSO has not been enabled and/or configured",
+ :data {:status "error-sso-disabled", :status-code 400},
+ :message "SSO has not been enabled and/or configured",
+ :status "error-sso-disabled"}
+ (mt/client :get 400 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect")))))))))
+
+;;; -------------------------------------------------- Redirect Tests --------------------------------------------------
+
+(deftest redirect-test
+ (testing "with Slack Connect configured, a GET request should result in a redirect to Slack"
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (with-successful-oidc!
+ (let [result (mt/client-full-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect default-redirect-uri)
+ redirect-url (get-in result [:headers "Location"])
+ oidc-state-cookie (->> (get-in result [:headers "Set-Cookie"])
+ (filter #(str/includes? % "metabase.OIDC_STATE"))
+ first)]
+ (is (str/starts-with? redirect-url "http://example.com/slack"))
+ (testing "OIDC state is stored in encrypted cookie"
+ (is (some? oidc-state-cookie))
+ ;; Verify the cookie contains encrypted data (base64-like)
+ (let [cookie-value (second (re-find #"metabase\.OIDC_STATE=([^;]+)" oidc-state-cookie))]
+ (is (some? cookie-value))
+ ;; Decrypt and verify contents (URL-decode since base64 chars +/= are encoded in cookies)
+ (let [state-data (oidc.state/decrypt-state (codec/url-decode cookie-value))]
+ (is (= "test-state" (:state state-data)))
+ (is (= "test-nonce" (:nonce state-data)))
+ (is (= "/" (:redirect state-data)))
+ (is (= "slack-connect" (:provider state-data))))))))))))
+
+(deftest multiple-sso-methods-test
+ (testing "with SAML and Slack Connect configured, a GET request with preferred_method=slack-connect should redirect to Slack"
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (mt/with-temporary-setting-values
+ [saml-enabled true
+ saml-identity-provider-uri "http://test.idp.metabase.com"
+ saml-identity-provider-certificate (slurp "test_resources/sso/auth0-public-idp.cert")]
+ (with-successful-oidc!
+ (let [result (mt/client-full-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect default-redirect-uri)
+ redirect-url (get-in result [:headers "Location"])]
+ (is (str/starts-with? redirect-url "http://example.com/slack")))))))))
+
+;;; -------------------------------------------------- POST Not Allowed Tests --------------------------------------------------
+
+(deftest post-not-allowed-test
+ (testing "POST requests should return 405 Method Not Allowed for OIDC"
+ (sso.test-setup/with-slack-default-setup!
+ (let [response (mt/client-full-response :post 405 "/auth/sso"
+ {:request-options {:content-type :x-www-form-urlencoded
+ :form-params {:preferred_method "slack-connect"}}})]
+ (is (= "GET" (get-in response [:headers "Allow"])))))))
+
+;;; -------------------------------------------------- Callback Tests --------------------------------------------------
+
+(deftest callback-state-validation-test
+ (testing "callback should fail if state cookie is missing"
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (let [response (mt/client-full-response :get 401 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :code "test-code"
+ :state "some-state")]
+ ;; Without a state cookie, the callback fails with invalid/expired state error
+ (is (str/includes? (:body response) "OIDC state cookie is invalid, expired, or missing")))))))
+
+(deftest callback-state-validation-csrf-test
+ (testing "callback with mismatched state should indicate possible CSRF attack"
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (with-successful-oidc!
+ ;; First, initiate auth to set state cookie
+ (let [init-response (mt/client-full-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect default-redirect-uri)
+ ;; Convert Set-Cookie headers to Cookie header format (extract name=value parts)
+ set-cookies (get-in init-response [:headers "Set-Cookie"])
+ cookie-header (->> set-cookies
+ (map #(first (str/split % #";"))) ; Extract name=value before first ;
+ (str/join "; "))
+ response (mt/client-real-response :get 401 "/auth/sso"
+ {:request-options {:redirect-strategy :none
+ :headers {"Cookie" cookie-header}}}
+ :code "test-code"
+ :state "wrong-state")]
+ ;; State mismatch should indicate possible CSRF attack
+ (is (str/includes? (str (:body response)) "CSRF"))))))))
+
+(deftest happy-path-callback-test
+ (testing "successful callback with valid code and state"
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (with-successful-oidc!
+ ;; First, initiate auth to set state cookie
+ (let [init-response (mt/client-full-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect default-redirect-uri)
+ ;; Convert Set-Cookie headers to Cookie header format
+ set-cookies (get-in init-response [:headers "Set-Cookie"])
+ cookie-header (->> set-cookies
+ (map #(first (str/split % #";")))
+ (str/join "; "))
+ response (mt/client-real-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none
+ :headers {"Cookie" cookie-header}}}
+ :code "test-code"
+ :state "test-state")]
+ (is (sso.test-setup/successful-login? response))
+ (is (= default-redirect-uri (get-in response [:headers "Location"])))))))))
+
+;;; -------------------------------------------------- Link-Only Mode Tests --------------------------------------------------
+
+(deftest link-only-mode-requires-session-test
+ (testing "link-only mode should require authenticated session for initial request"
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (mt/with-temporary-setting-values
+ [slack-connect-authentication-mode "link-only"]
+ (let [response (mt/client-full-response :get 401 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect default-redirect-uri)]
+ (is (str/includes? (str (get response :body)) "authenticated session"))))))))
+
+(deftest link-only-mode-with-session-test
+ (testing "link-only mode should work with authenticated session"
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (mt/with-temporary-setting-values
+ [slack-connect-authentication-mode "link-only"]
+ (with-successful-oidc!
+ (let [response (mt/user-http-request-full-response
+ :rasta :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect default-redirect-uri)]
+ (is (str/starts-with? (get-in response [:headers "Location"]) "http://example.com/slack")))))))))
+
+;;; -------------------------------------------------- Open Redirect Protection Tests --------------------------------------------------
+
+(deftest no-open-redirect-test
+ (testing "Check that we prevent open redirects to untrusted sites"
+ (sso.test-setup/with-slack-default-setup!
+ (doseq [redirect-uri ["https://badsite.com"
+ "//badsite.com"
+ "https:///badsite.com"]]
+ (is
+ (= "Invalid redirect URL"
+ (->
+ (mt/client
+ :get 400 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect redirect-uri)
+ :message)))))))
+
+;;; -------------------------------------------------- User Provisioning Tests --------------------------------------------------
+
+(deftest create-new-account-test
+ (testing "A new account will be created for a Slack user we haven't seen before"
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (mt/with-model-cleanup [:model/User]
+ (with-successful-oidc!
+ (t2/delete! :model/User :email "[email protected]")
+ (letfn [(new-user-exists? []
+ (boolean (seq (t2/select :model/User :%lower.email "[email protected]"))))]
+ (is (false? (new-user-exists?)))
+ ;; Initiate auth
+ (let [init-response (mt/client-full-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect default-redirect-uri)
+ ;; Convert Set-Cookie headers to Cookie header format
+ set-cookies (get-in init-response [:headers "Set-Cookie"])
+ cookie-header (->> set-cookies
+ (map #(first (str/split % #";")))
+ (str/join "; "))
+ response (mt/client-real-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none
+ :headers {"Cookie" cookie-header}}}
+ :code "test-code"
+ :state "test-state")]
+ ;; Complete callback
+ (is (sso.test-setup/successful-login? response))
+ (let [new-user (t2/select-one :model/User :email "[email protected]")]
+ (testing "new user"
+ (is
+ (=
+ {:email "[email protected]"
+ :first_name nil
+ :is_qbnewb true
+ :is_superuser false
+ :id true
+ :last_name nil
+ :date_joined true
+ :common_name "[email protected]"
+ :tenant_id false
+ :is_data_analyst false}
+ (-> (mt/boolean-ids-and-timestamps [new-user])
+ first
+ (dissoc :last_login)))))
+ (testing "User Invite Event is logged."
+ (is
+ (get-in (mt/latest-audit-log-entry :user-invited (:id new-user))
+ [:details :email])))))))))))))
+
+(deftest create-new-slack-user-no-user-provisioning-test
+ (testing "When user provisioning is disabled, throw an error if we attempt to create a new user."
+ (with-test-encryption!
+ (sso.test-setup/with-slack-default-setup!
+ (mt/with-temporary-setting-values [slack-connect-user-provisioning-enabled false
+ site-name "test"]
+ (with-successful-oidc!
+ (with-redefs [auth-identity/login!
+ (fn [_provider _request]
+ {:success? false
+ :error :user-provisioning-disabled
+ :message "Sorry, but you'll need a test account to view this page. Please contact your administrator."})]
+ ;; Initiate auth
+ (let [init-response (mt/client-full-response :get 302 "/auth/sso"
+ {:request-options {:redirect-strategy :none}}
+ :preferred_method "slack-connect"
+ :redirect default-redirect-uri)
+ set-cookies (get-in init-response [:headers "Set-Cookie"])
+ cookie-header (->> set-cookies
+ (map #(first (str/split % #";")))
+ (str/join "; "))]
+ ;; Try callback - should fail
+ (mt/client-real-response :get 401 "/auth/sso"
+ {:request-options {:redirect-strategy :none
+ :headers {"Cookie" cookie-header}}}
+ :code "test-code"
+ :state "test-state")))))))))
+
+;;; -------------------------------------------------- Authentication Mode Validation Tests --------------------------------------------------
+
+(deftest authentication-mode-validation-test
+ (testing "authentication mode setting only accepts valid values"
+ ;; Don't use sso.test-setup/with-slack-default-setup! here because it sets env vars
+ ;; which take precedence over DB values when reading settings.
+ ;; This test only needs to verify the setter validates input correctly.
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-authentication-mode nil]
+ (testing "valid values are accepted"
+ (sso-settings/slack-connect-authentication-mode! "sso")
+ (is (= "sso" (sso-settings/slack-connect-authentication-mode)))
+ (sso-settings/slack-connect-authentication-mode! "link-only")
+ (is (= "link-only" (sso-settings/slack-connect-authentication-mode))))
+
+ (testing "invalid values are rejected"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid authentication mode"
+ (sso-settings/slack-connect-authentication-mode! "invalid"))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/sso/providers/slack_connect_test.clj b/enterprise/backend/test/metabase_enterprise/sso/providers/slack_connect_test.clj
new file mode 100644
index 00000000000..4d6262cf3e6
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/sso/providers/slack_connect_test.clj
@@ -0,0 +1,478 @@
+(ns metabase-enterprise.sso.providers.slack-connect-test
+ (:require
+ [clj-http.client :as http]
+ [clojure.test :refer :all]
+ [metabase-enterprise.sso.providers.slack-connect]
+ [metabase-enterprise.sso.settings :as sso-settings]
+ [metabase.auth-identity.core :as auth-identity]
+ [metabase.auth-identity.provider :as provider]
+ [metabase.sso.oidc.discovery :as oidc.discovery]
+ [metabase.sso.oidc.state :as oidc.state]
+ [metabase.sso.oidc.tokens :as oidc.tokens]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :db :test-users))
+(use-fixtures :each (fn [f] (mt/with-premium-features #{:sso-slack} (f))))
+
+(def ^:private slack-discovery-doc
+ {:authorization_endpoint "https://slack.com/oauth/v2/authorize"
+ :token_endpoint "https://slack.com/api/openid.connect.token"
+ :jwks_uri "https://slack.com/openid/connect/keys"
+ :userinfo_endpoint "https://slack.com/api/openid.connect.userInfo"})
+
+;;; -------------------------------------------------- Provider Hierarchy Tests --------------------------------------------------
+
+(deftest ^:parallel provider-hierarchy-test
+ (testing "Slack Connect provider derives from OIDC provider"
+ (is (isa? :provider/slack-connect :provider/oidc)))
+
+ (testing "Slack Connect provider derives from create-user-if-not-exists"
+ (is (isa? :provider/slack-connect ::provider/create-user-if-not-exists))))
+
+;;; -------------------------------------------------- Configuration Tests --------------------------------------------------
+
+(deftest build-slack-oidc-config-test
+ (testing "Builds OIDC configuration from Slack settings"
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"]
+ (let [request {:redirect-uri "https://metabase.example.com/auth/sso"}
+ config (#'metabase-enterprise.sso.providers.slack-connect/build-slack-oidc-config request)]
+ (is (= "test-client-id" (:client-id config)))
+ (is (= "test-secret" (:client-secret config)))
+ (is (= "https://slack.com" (:issuer-uri config)))
+ (is (= ["openid" "profile" "email"] (:scopes config)))
+ (is (= "https://metabase.example.com/auth/sso" (:redirect-uri config))))))
+
+ (testing "Returns nil when client ID is missing"
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id nil
+ slack-connect-client-secret "test-secret"]
+ (let [request {:redirect-uri "https://metabase.example.com/auth/sso"}
+ config (#'metabase-enterprise.sso.providers.slack-connect/build-slack-oidc-config request)]
+ (is (nil? config)))))
+
+ (testing "Returns nil when client secret is missing"
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id "test-client-id"
+ slack-connect-client-secret nil]
+ (let [request {:redirect-uri "https://metabase.example.com/auth/sso"}
+ config (#'metabase-enterprise.sso.providers.slack-connect/build-slack-oidc-config request)]
+ (is (nil? config))))))
+
+;;; -------------------------------------------------- Claim Extraction Tests --------------------------------------------------
+
+(deftest extract-slack-claims-test
+ (testing "Extracts Slack-specific claims from ID token"
+ (mt/with-temporary-setting-values
+ [slack-connect-attribute-team-id "https://slack.com/team_id"]
+ (let [id-token-claims {:sub "U12345678"
+ "https://slack.com/team_id" "T12345678"
+ "https://slack.com/team_image_230" "https://example.com/team.png"
+ :email_verified true
+ :locale "en-US"}
+ slack-attrs (#'metabase-enterprise.sso.providers.slack-connect/extract-slack-claims id-token-claims)]
+ (is (= "U12345678" (get slack-attrs "slack-user-id")))
+ (is (= "T12345678" (get slack-attrs "slack-team-id")))
+ (is (= "https://example.com/team.png" (get slack-attrs "slack-team-image")))
+ (is (= "true" (get slack-attrs "slack-email-verified")))
+ (is (= "en-US" (get slack-attrs "slack-locale"))))))
+
+ (testing "Handles missing optional claims gracefully"
+ (mt/with-temporary-setting-values
+ [slack-connect-attribute-team-id "https://slack.com/team_id"]
+ (let [id-token-claims {:sub "U12345678"}
+ slack-attrs (#'metabase-enterprise.sso.providers.slack-connect/extract-slack-claims id-token-claims)]
+ (is (= "U12345678" (get slack-attrs "slack-user-id")))
+ (is (nil? (get slack-attrs "slack-team-id")))
+ (is (nil? (get slack-attrs "slack-team-image")))
+ (is (nil? (get slack-attrs "slack-email-verified")))
+ (is (nil? (get slack-attrs "slack-locale")))))))
+
+;;; -------------------------------------------------- Authentication Tests --------------------------------------------------
+
+(deftest authenticate-missing-premium-feature-test
+ (testing "Returns error when premium feature is not available"
+ (mt/with-premium-features #{}
+ (let [request {}
+ result (auth-identity/authenticate :provider/slack-connect request)]
+ (is (false? (:success? result)))
+ (is (= :feature-not-available (:error result)))
+ (is (some? (:message result)))))))
+
+(deftest authenticate-not-enabled-test
+ (testing "Returns error when Slack Connect is not enabled"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled false]
+ (let [request {}
+ result (auth-identity/authenticate :provider/slack-connect request)]
+ (is (false? (:success? result)))
+ (is (= :slack-connect-not-enabled (:error result)))
+ (is (some? (:message result))))))))
+
+(deftest authenticate-not-configured-test
+ (testing "Returns error when Slack Connect is not configured"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id nil
+ slack-connect-client-secret nil]
+ (let [request {}
+ result (auth-identity/authenticate :provider/slack-connect request)]
+ (is (false? (:success? result)))
+ (is (= :slack-connect-not-enabled (:error result)))
+ (is (some? (:message result))))))))
+
+(deftest authenticate-link-only-requires-session-test
+ (testing "Returns error in link-only mode when no authenticated session"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-authentication-mode "link-only"]
+ (let [request {:authenticated-user (delay nil)}
+ result (auth-identity/authenticate :provider/slack-connect request)]
+ (is (false? (:success? result)))
+ (is (= :authentication-required (:error result)))
+ (is (some? (:message result))))))))
+
+(deftest authenticate-link-only-allows-callback-test
+ (testing "Does not require session for callback in link-only mode"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-authentication-mode "link-only"]
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] slack-discovery-doc)
+ http/post
+ (fn [_url _opts]
+ {:status 200
+ :body {:id_token "valid-token"
+ :access_token "access-token-123"}})
+ oidc.tokens/validate-id-token
+ (fn [_token _config _nonce]
+ {:valid? true
+ :claims {:sub "U12345678"
+ :iss "https://slack.com"
+ :aud "test-client-id"
+ :email "[email protected]"}})]
+ (let [request {:code "test-code"
+ :state "test-state"
+ :oidc-nonce "test-nonce"
+ :redirect-uri "https://metabase.example.com/auth/sso"
+ :authenticated-user (delay nil)}
+ result (auth-identity/authenticate :provider/slack-connect request)]
+ ;; The presence of :code indicates callback, so should not error even without authenticated-user
+ (is (true? (:success? result)))
+ (is (= "[email protected]" (get-in result [:user-data :email]))))))))
+
+(deftest authenticate-enhances-with-slack-data-test
+ (testing "Enhances successful auth result with Slack-specific data"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-attribute-team-id "https://slack.com/team_id"]
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] slack-discovery-doc)
+ http/post
+ (fn [_url _opts]
+ {:status 200
+ :body {:id_token "valid-token"
+ :access_token "access-token-123"}})
+ oidc.tokens/validate-id-token
+ (fn [_token _config _nonce]
+ {:valid? true
+ :claims {:sub "U12345678"
+ :iss "https://slack.com"
+ :aud "test-client-id"
+ "https://slack.com/team_id" "T12345678"
+ :email_verified true}})]
+ (let [request {:code "test-code"
+ :state "test-state"
+ :oidc-nonce "test-nonce"
+ :redirect-uri "https://metabase.example.com/auth/sso"}
+ result (auth-identity/authenticate :provider/slack-connect request)]
+ (is (= :slack (get-in result [:user-data :sso_source])))
+ (is (= "U12345678" (get-in result [:user-data :login_attributes "slack-user-id"])))
+ (is (= "T12345678" (get-in result [:user-data :login_attributes "slack-team-id"])))
+ (is (= "true" (get-in result [:user-data :login_attributes "slack-email-verified"])))
+ (is (some? (:slack-data result)))))))))
+
+;;; -------------------------------------------------- Login Tests --------------------------------------------------
+
+(deftest link-only-mode-no-session-creation-test
+ (testing "No session is created when authentication mode is link-only"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-authentication-mode "link-only"
+ slack-connect-user-provisioning-enabled false]
+ (mt/with-temp [:model/User user {:email "[email protected]"}]
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] slack-discovery-doc)
+ oidc.state/validate-oidc-callback
+ (fn [_request _state _provider & _opts]
+ {:valid? true
+ :nonce "test-nonce"
+ :redirect "/"})
+ http/post
+ (fn [_url _opts]
+ {:status 200
+ :body {:id_token "valid-token"
+ :access_token "access-token-123"}})
+ oidc.tokens/validate-id-token
+ (fn [_token _config _nonce]
+ {:valid? true
+ :claims {:sub "U12345678"
+ :iss "https://slack.com"
+ :aud "test-client-id"
+ :email "[email protected]"}})]
+ (let [initial-session-count (t2/count :model/Session :user_id (:id user))
+ request {:code "test-code"
+ :state "test-state"
+ :redirect-uri "https://metabase.example.com/auth/sso"
+ :authenticated-user (delay user)
+ :device-info {:device_id "test-device" :device_description "Test Device" :ip_address "127.0.0.1" :embedded false}}
+ result (auth-identity/login! :provider/slack-connect request)]
+ (is (true? (:success? result)) "Login should succeed")
+ (is (nil? (:session result)) "Result should not contain a session")
+ (is (nil? (:user result)) "Result should not contain a user (dissoc'd by :after method)")
+ (is (= initial-session-count (t2/count :model/Session :user_id (:id user)))
+ "No new session should be created in the database"))))))))
+
+;;; -------------------------------------------------- AuthIdentity Creation Tests --------------------------------------------------
+
+(deftest sso-mode-creates-auth-identity-for-new-user-test
+ (testing "SSO mode creates AuthIdentity when a new user logs in via Slack"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-authentication-mode "sso"
+ slack-connect-user-provisioning-enabled true]
+ (let [test-email "[email protected]"
+ slack-user-id "U_NEW_12345"]
+ ;; Ensure user doesn't exist
+ (t2/delete! :model/User :email test-email)
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] slack-discovery-doc)
+ oidc.state/validate-oidc-callback
+ (fn [_request _state _provider & _opts]
+ {:valid? true
+ :nonce "test-nonce"
+ :redirect "/"})
+ http/post
+ (fn [_url _opts]
+ {:status 200
+ :body {:id_token "valid-token"
+ :access_token "access-token-123"}})
+ oidc.tokens/validate-id-token
+ (fn [_token _config _nonce]
+ {:valid? true
+ :claims {:sub slack-user-id
+ :iss "https://slack.com"
+ :aud "test-client-id"
+ :email test-email
+ :given_name "New"
+ :family_name "User"}})]
+ (try
+ (let [request {:code "test-code"
+ :state "test-state"
+ :redirect-uri "https://metabase.example.com/auth/sso"
+ :device-info {:device_id "test-device" :device_description "Test Device" :ip_address "127.0.0.1" :embedded false}}
+ result (auth-identity/login! :provider/slack-connect request)]
+ (is (true? (:success? result)) "Login should succeed")
+ (is (some? (:user result)) "Result should contain a user")
+ ;; Verify AuthIdentity was created
+ (let [user (t2/select-one :model/User :email test-email)
+ auth-identity (t2/select-one :model/AuthIdentity
+ :user_id (:id user)
+ :provider "slack-connect")]
+ (is (some? user) "User should be created")
+ (is (some? auth-identity) "AuthIdentity should be created")
+ (is (= slack-user-id (:provider_id auth-identity))
+ "AuthIdentity should have correct provider_id")))
+ (finally
+ (t2/delete! :model/User :email test-email)))))))))
+
+(deftest sso-mode-creates-auth-identity-for-existing-user-test
+ (testing "SSO mode creates AuthIdentity when an existing user logs in via Slack"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-authentication-mode "sso"]
+ (let [slack-user-id "U_EXISTING_789"]
+ (mt/with-temp [:model/User user {:email "[email protected]"
+ :first_name "Existing"
+ :last_name "User"}]
+ ;; Ensure no AuthIdentity exists for this user
+ (t2/delete! :model/AuthIdentity :user_id (:id user) :provider "slack-connect")
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] slack-discovery-doc)
+ oidc.state/validate-oidc-callback
+ (fn [_request _state _provider & _opts]
+ {:valid? true
+ :nonce "test-nonce"
+ :redirect "/"})
+ http/post
+ (fn [_url _opts]
+ {:status 200
+ :body {:id_token "valid-token"
+ :access_token "access-token-123"}})
+ oidc.tokens/validate-id-token
+ (fn [_token _config _nonce]
+ {:valid? true
+ :claims {:sub slack-user-id
+ :iss "https://slack.com"
+ :aud "test-client-id"
+ :email "[email protected]"}})]
+ (let [request {:code "test-code"
+ :state "test-state"
+ :redirect-uri "https://metabase.example.com/auth/sso"
+ :device-info {:device_id "test-device" :device_description "Test Device" :ip_address "127.0.0.1" :embedded false}}
+ result (auth-identity/login! :provider/slack-connect request)]
+ (is (true? (:success? result)) "Login should succeed")
+ ;; Verify AuthIdentity was created
+ (let [auth-identity (t2/select-one :model/AuthIdentity
+ :user_id (:id user)
+ :provider "slack-connect")]
+ (is (some? auth-identity) "AuthIdentity should be created for existing user")
+ (is (= slack-user-id (:provider_id auth-identity))
+ "AuthIdentity should have correct provider_id"))))))))))
+
+(deftest link-only-mode-creates-auth-identity-test
+ (testing "Link-only mode creates AuthIdentity for the authenticated user"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-authentication-mode "link-only"]
+ (let [slack-user-id "U_LINK_456"]
+ (mt/with-temp [:model/User user {:email "[email protected]"
+ :first_name "Link"
+ :last_name "User"}]
+ ;; Ensure no AuthIdentity exists for this user
+ (t2/delete! :model/AuthIdentity :user_id (:id user) :provider "slack-connect")
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] slack-discovery-doc)
+ oidc.state/validate-oidc-callback
+ (fn [_request _state _provider & _opts]
+ {:valid? true
+ :nonce "test-nonce"
+ :redirect "/"})
+ http/post
+ (fn [_url _opts]
+ {:status 200
+ :body {:id_token "valid-token"
+ :access_token "access-token-123"}})
+ oidc.tokens/validate-id-token
+ (fn [_token _config _nonce]
+ {:valid? true
+ :claims {:sub slack-user-id
+ :iss "https://slack.com"
+ :aud "test-client-id"
+ :email "[email protected]"}})]
+ (let [initial-session-count (t2/count :model/Session :user_id (:id user))
+ request {:code "test-code"
+ :state "test-state"
+ :redirect-uri "https://metabase.example.com/auth/sso"
+ :authenticated-user (delay user)
+ :device-info {:device_id "test-device" :device_description "Test Device" :ip_address "127.0.0.1" :embedded false}}
+ result (auth-identity/login! :provider/slack-connect request)]
+ (is (true? (:success? result)) "Login should succeed")
+ (is (nil? (:session result)) "No session should be created in link-only mode")
+ ;; Verify AuthIdentity was created
+ (let [auth-identity (t2/select-one :model/AuthIdentity
+ :user_id (:id user)
+ :provider "slack-connect")]
+ (is (some? auth-identity) "AuthIdentity should be created in link-only mode")
+ (is (= slack-user-id (:provider_id auth-identity))
+ "AuthIdentity should have correct provider_id"))
+ ;; Verify no new session was created
+ (is (= initial-session-count (t2/count :model/Session :user_id (:id user)))
+ "No new session should be created")))))))))
+
+;;; -------------------------------------------------- Settings Validation Tests --------------------------------------------------
+
+(deftest slack-connect-configured-test
+ (testing "Returns true when client ID and secret are configured"
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"]
+ (is (true? (sso-settings/slack-connect-configured)))))
+
+ (testing "Returns false when client ID is missing"
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id nil
+ slack-connect-client-secret "test-secret"]
+ (is (false? (sso-settings/slack-connect-configured)))))
+
+ (testing "Returns false when client secret is missing"
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id "test-client-id"
+ slack-connect-client-secret nil]
+ (is (false? (sso-settings/slack-connect-configured))))))
+
+(deftest slack-connect-enabled-test
+ (testing "Returns true when configured and enabled"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-enabled true]
+ (is (true? (sso-settings/slack-connect-enabled))))))
+
+ (testing "Returns false when configured but not enabled"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id "test-client-id"
+ slack-connect-client-secret "test-secret"
+ slack-connect-enabled false]
+ (is (false? (sso-settings/slack-connect-enabled))))))
+
+ (testing "Returns false when not configured even if enabled is true"
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-client-id nil
+ slack-connect-client-secret nil
+ slack-connect-enabled true]
+ (is (false? (sso-settings/slack-connect-enabled)))))))
+
+(deftest slack-connect-authentication-mode-validation-test
+ (testing "Accepts valid authentication modes"
+ (mt/with-temporary-setting-values
+ [slack-connect-authentication-mode nil]
+ (sso-settings/slack-connect-authentication-mode! "sso")
+ (is (= "sso" (sso-settings/slack-connect-authentication-mode)))
+ (sso-settings/slack-connect-authentication-mode! "link-only")
+ (is (= "link-only" (sso-settings/slack-connect-authentication-mode)))))
+
+ (testing "Rejects invalid authentication modes"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid authentication mode"
+ (sso-settings/slack-connect-authentication-mode! "invalid")))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid authentication mode"
+ (sso-settings/slack-connect-authentication-mode! "SSO")))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid authentication mode"
+ (sso-settings/slack-connect-authentication-mode! "")))))
diff --git a/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj b/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj
new file mode 100644
index 00000000000..50610022cbc
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj
@@ -0,0 +1,156 @@
+(ns metabase-enterprise.sso.test-setup
+ "Shared test helpers for SSO tests.
+
+ These utilities are used across multiple SSO integration tests (SAML, JWT, Slack Connect, etc.)
+ to avoid circular dependencies between test namespaces."
+ (:require
+ [clojure.string :as str]
+ [metabase.config.core :as config]
+ [metabase.premium-features.token-check :as token-check]
+ [metabase.request.core :as request]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [metabase.util.random :as u.random]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;;; -------------------------------------------------- Generic Helpers --------------------------------------------------
+
+(defn successful-login?
+ "Return true if the response indicates a successful user login.
+ Checks for the presence of a session cookie in the response."
+ [resp]
+ (or
+ (string? (get-in resp [:cookies request/metabase-session-cookie :value]))
+ (some #(str/starts-with? % request/metabase-session-cookie) (get-in resp [:headers "Set-Cookie"]))))
+
+(defn call-with-login-attributes-cleared!
+ "Execute `thunk` and ensure login_attributes are cleared afterward.
+
+ If login_attributes remain after tests run, depending on the order that the tests run,
+ lots of tests will fail as the login_attributes data from this test is unexpected in
+ those other tests."
+ [thunk]
+ (try
+ (thunk)
+ (finally
+ (u/ignore-exceptions
+ (t2/update! :model/User {} {:login_attributes nil})
+ (t2/update! :model/User {:email "[email protected]"} {:first_name "Rasta" :last_name "Toucan" :sso_source nil})))))
+
+(defn do-with-other-sso-types-disabled!
+ "Execute `thunk` with LDAP, SAML, and JWT SSO types disabled.
+ Useful when testing a specific SSO provider in isolation."
+ [thunk]
+ (mt/with-temporary-setting-values
+ [ldap-enabled false
+ saml-enabled false
+ jwt-enabled false]
+ (thunk)))
+
+;;; -------------------------------------------------- SAML Setup --------------------------------------------------
+
+(def ^:private default-saml-idp-uri "http://test.idp.metabase.com")
+(def ^:private default-saml-idp-cert (delay (slurp "test_resources/sso/auth0-public-idp.cert")))
+
+(defn call-with-default-saml-config!
+ "Execute `f` with default SAML configuration set up."
+ [f]
+ (let [current-features (token-check/*token-features*)]
+ (mt/with-premium-features #{:sso-saml}
+ (mt/with-temporary-setting-values [saml-enabled true
+ saml-identity-provider-uri default-saml-idp-uri
+ saml-identity-provider-certificate @default-saml-idp-cert
+ saml-keystore-path nil
+ saml-keystore-password nil
+ saml-keystore-alias nil
+ site-url "http://localhost:3000"]
+ (mt/with-premium-features current-features
+ (f))))))
+
+(defmacro with-saml-default-setup!
+ "Set up default SAML configuration for tests.
+ Includes premium features, login attributes cleanup, and default SAML config."
+ [& body]
+ `(mt/test-helpers-set-global-values!
+ (mt/with-additional-premium-features #{:sso-saml}
+ (call-with-login-attributes-cleared!
+ (fn []
+ (call-with-default-saml-config!
+ (fn []
+ ~@body)))))))
+
+;;; -------------------------------------------------- JWT Setup --------------------------------------------------
+
+(def default-jwt-idp-uri
+ "Default JWT IDP URI for tests."
+ "http://test.idp.metabase.com")
+
+(def default-jwt-secret
+ "Default JWT secret for tests. Note: this is regenerated on each test run."
+ (u.random/secure-hex 32))
+
+(defn call-with-default-jwt-config!
+ "Execute `f` with default JWT configuration set up."
+ [f]
+ (let [current-features (token-check/*token-features*)]
+ (mt/with-additional-premium-features #{:sso-jwt}
+ (mt/with-temporary-setting-values
+ [jwt-enabled true
+ jwt-identity-provider-uri default-jwt-idp-uri
+ jwt-shared-secret default-jwt-secret
+ site-url (format "http://localhost:%s" (config/config-str :mb-jetty-port))]
+ (mt/with-premium-features current-features
+ (f))))))
+
+(defmacro with-jwt-default-setup!
+ "Set up default JWT configuration for tests.
+ Includes premium features, model cleanup, other SSO types disabled, login attributes cleanup, and default JWT config."
+ [& body]
+ `(mt/test-helpers-set-global-values!
+ (mt/with-model-cleanup [:model/User :model/Collection :model/Tenant]
+ (mt/with-premium-features #{:audit-app}
+ (do-with-other-sso-types-disabled!
+ (fn []
+ (mt/with-additional-premium-features #{:sso-jwt}
+ (call-with-login-attributes-cleared!
+ (fn []
+ (call-with-default-jwt-config!
+ (fn []
+ ~@body)))))))))))
+
+;;; -------------------------------------------------- Slack Connect Setup --------------------------------------------------
+
+(def ^:private default-slack-client-id "test-slack-client-id")
+(def ^:private default-slack-client-secret "test-slack-client-secret")
+
+(defn call-with-default-slack-config!
+ "Execute `f` with default Slack Connect configuration set up."
+ [f]
+ (let [current-features (token-check/*token-features*)]
+ (mt/with-additional-premium-features #{:sso-slack}
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id default-slack-client-id
+ slack-connect-client-secret default-slack-client-secret
+ slack-connect-authentication-mode "sso"
+ slack-connect-user-provisioning-enabled true
+ site-url (format "http://localhost:%s" (config/config-str :mb-jetty-port))]
+ (mt/with-premium-features current-features
+ (f))))))
+
+(defmacro with-slack-default-setup!
+ "Set up default Slack Connect configuration for tests.
+ Includes premium features, other SSO types disabled, login attributes cleanup, and default Slack config."
+ [& body]
+ `(mt/test-helpers-set-global-values!
+ (mt/with-premium-features #{:audit-app}
+ (do-with-other-sso-types-disabled!
+ (fn []
+ (mt/with-additional-premium-features #{:sso-slack}
+ (call-with-login-attributes-cleared!
+ (fn []
+ (call-with-default-slack-config!
+ (fn []
+ ~@body))))))))))
diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.clj
index fb4482cf1f4..1092c519c54 100644
--- a/src/metabase/analytics/stats.clj
+++ b/src/metabase/analytics/stats.clj
@@ -799,7 +799,7 @@
(defn- ee-snowplow-features-data'
[]
- (let [features [:sso-jwt :sso-saml :scim :sandboxes :email-allow-list :semantic-search]]
+ (let [features [:sso-jwt :sso-saml :sso-slack :scim :sandboxes :email-allow-list :semantic-search]]
(map
(fn [feature]
{:name feature
diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.clj
index 9dda27515bc..14cb73222bb 100644
--- a/src/metabase/premium_features/core.clj
+++ b/src/metabase/premium_features/core.clj
@@ -77,6 +77,7 @@
enable-sso-ldap?
enable-sso-saml?
enable-support-users?
+ enable-sso-slack?
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 9a455a66b11..55b302a8cd7 100644
--- a/src/metabase/premium_features/settings.clj
+++ b/src/metabase/premium_features/settings.clj
@@ -146,6 +146,10 @@
"Should we enable SAML-based authentication?"
:sso-saml)
+(define-premium-feature ^{:added "0.59.0"} enable-sso-slack?
+ "Should we enable Slack Connect (OIDC) authentication?"
+ :sso-slack)
+
(define-premium-feature enable-sso-ldap?
"Should we enable advanced configuration for LDAP authentication?"
:sso-ldap)
@@ -163,6 +167,7 @@
[]
(or (enable-sso-jwt?)
(enable-sso-saml?)
+ (enable-sso-slack?)
(enable-sso-ldap?)
(enable-sso-google?)))
@@ -365,6 +370,7 @@
:sso_jwt (enable-sso-jwt?)
:sso_ldap (enable-sso-ldap?)
:sso_saml (enable-sso-saml?)
+ :sso_slack (enable-sso-slack?)
:support-users (enable-support-users?)
:table_data_editing (table-data-editing?)
:tenants (enable-tenants?)
diff --git a/src/metabase/sso/providers/oidc.clj b/src/metabase/sso/providers/oidc.clj
index fcdec1013d6..5b5645a4ec0 100644
--- a/src/metabase/sso/providers/oidc.clj
+++ b/src/metabase/sso/providers/oidc.clj
@@ -134,7 +134,8 @@
validation-config {:jwks-uri jwks-uri
:issuer-uri (:issuer-uri config)
:client-id (:client-id config)}
- nonce (:nonce request)
+ ;; Use :oidc-nonce to avoid collision with CSP :nonce from security middleware
+ nonce (:oidc-nonce request)
validation-result (oidc.tokens/validate-id-token (:id-token tokens)
validation-config
nonce)]
@@ -199,7 +200,8 @@
:error (:error validation)
:message (:message validation)}
;; Add nonce and redirect from validated state to request
- (next-method provider (cond-> (assoc request :nonce (:nonce validation))
+ ;; Use :oidc-nonce to avoid collision with CSP :nonce from security middleware
+ (next-method provider (cond-> (assoc request :oidc-nonce (:nonce validation))
;; Use redirect from state cookie if not already set in request
(and (:redirect validation)
(not (:redirect-url request)))