Skip to content

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

Snowflake workload identity federation (#82931)

metamben36348665e6bb
diff --git a/.github/workflows/drivers.yml b/.github/workflows/drivers.yml
index 233966e51bc..633ecc227a8 100644
--- a/.github/workflows/drivers.yml
+++ b/.github/workflows/drivers.yml
@@ -969,6 +969,10 @@ jobs:
if: ${{ needs.determine-driver-skips.outputs.snowflake-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 70
+ permissions:
+ # Required to mint a GitHub Actions OIDC token for the Snowflake WIF live test.
+ id-token: write
+ contents: read
strategy:
fail-fast: false
matrix:
@@ -1004,6 +1008,16 @@ jobs:
MB_SNOWFLAKE_TEST_RSA_ROLE_TEST_CUSTOM_USER: RSA_ROLE_TEST_CUSTOM_USER
MB_SNOWFLAKE_TEST_RSA_ROLE_TEST_ROLE: RSA_ROLE_TEST_ROLE
MB_SNOWFLAKE_TEST_RSA_ROLE_TEST_DB: RSA_ROLE_TEST_DB
+
+ # Workload Identity Federation live test. USER is picked by event/ref so the GH OIDC `sub`
+ # claim matches a WORKLOAD_IDENTITY subject on the Snowflake side. Contexts that no
+ # WORKLOAD_IDENTITY user matches (release-** pushes, dispatches from feature branches)
+ # opt out via the explicit 'skip' sentinel.
+ MB_SNOWFLAKE_TEST_WIF_ACCOUNT: ${{ secrets.MB_SNOWFLAKE_TEST_ACCOUNT }}
+ MB_SNOWFLAKE_TEST_WIF_WAREHOUSE: ${{ secrets.MB_SNOWFLAKE_TEST_WAREHOUSE }}
+ MB_SNOWFLAKE_TEST_WIF_USER: ${{ github.event_name == 'pull_request' && 'METABASE WIF' || (github.ref == 'refs/heads/master' && 'METABASE WIF MAIN' || 'skip') }}
+ MB_SNOWFLAKE_TEST_WIF_DB: SNOWFLAKE_SAMPLE_DATA
+ MB_SNOWFLAKE_TEST_WIF_ROLE: PUBLIC
name: Snowflake ${{ matrix.job.name }}
steps:
- uses: actions/checkout@v7
diff --git a/docs/databases/connections/snowflake.md b/docs/databases/connections/snowflake.md
index 870d95c34dd..c33d37b071d 100644
--- a/docs/databases/connections/snowflake.md
+++ b/docs/databases/connections/snowflake.md
@@ -53,9 +53,19 @@ The database username for the account that you want to use to connect to your da
On your app.snowflake.com account page, you can find Users and roles under Admin > Users & Roles.
+### Authentication method
+
+Pick how Metabase authenticates to Snowflake:
+
+- **RSA key pair** — key-based auth.
+- **Workload Identity Federation** — keyless auth using a token from an OIDC provider, AWS, Azure, or Google Cloud.
+- **Username & password** — Snowflake blocks password authentication for service users by October 2026.
+
+The fields that appear below depend on which method you pick.
+
### Password
-The password for the username that you use to connect to the database.
+The password for the username that you use to connect to the database. Snowflake blocks password authentication for service users by October 2026; use RSA key pair or Workload Identity Federation instead.
### RSA private key (PEM)
@@ -65,6 +75,25 @@ Not required. You have the option of using a **Local file path** or an **Uploade
Only required if your private key is encrypted.
+### Workload Identity Federation
+
+Metabase forwards a workload-identity token to Snowflake; Snowflake validates it against a service user you provision with `CREATE USER ... WORKLOAD_IDENTITY = (...)`. See Snowflake's [Workload identity federation docs](https://docs.snowflake.com/en/user-guide/workload-identity-federation) for the trust-policy syntax.
+
+#### Workload identity provider
+
+- **OpenID Connect (JWT)** — you supply the token (see next two fields).
+- **AWS**, **Azure**, or **Google Cloud** — no additional credential fields in Metabase. Attach an AWS IAM role, an Azure managed identity, or a GCP service account to the host running Metabase; the Snowflake driver picks it up.
+
+#### OIDC token
+
+A JWT you paste into Metabase. Convenient for a one-off test. Metabase does not refresh the token, so once it expires the connection will fail until you paste a new one.
+
+#### OIDC token file path
+
+Path to a file on the Metabase server that contains the JWT (for example, a Kubernetes projected service-account token at `/var/run/secrets/tokens/oidc-token`). The Snowflake driver re-reads this file per connection, so tokens rotated in place — the standard Kubernetes pattern — flow through without any change in Metabase.
+
+If both the pasted token and the file path are set, the file path wins.
+
### Warehouse
Snowflake warehouse. If the user lacks a default warehouse, you'll need to enter the warehouse to connect to.
diff --git a/frontend/src/metabase/databases/components/DatabaseConnectionUri/database-field-mapper.ts b/frontend/src/metabase/databases/components/DatabaseConnectionUri/database-field-mapper.ts
index 0ddec0df1e5..2ec1f1a4ac7 100644
--- a/frontend/src/metabase/databases/components/DatabaseConnectionUri/database-field-mapper.ts
+++ b/frontend/src/metabase/databases/components/DatabaseConnectionUri/database-field-mapper.ts
@@ -200,6 +200,7 @@ export function mapSnowflakeValues(parsedValues: RegexFields) {
]);
if (parsedValues.password) {
+ fieldsMap.set("details.auth-mode", "password");
fieldsMap.set("details.use-password", true);
fieldsMap.set("details.password", parsedValues.password);
}
diff --git a/modules/drivers/snowflake/resources/metabase/snowflake/metabase-plugin.yaml b/modules/drivers/snowflake/resources/metabase/snowflake/metabase-plugin.yaml
index 51f4c19d0f8..19db119d934 100644
--- a/modules/drivers/snowflake/resources/metabase/snowflake/metabase-plugin.yaml
+++ b/modules/drivers/snowflake/resources/metabase/snowflake/metabase-plugin.yaml
@@ -23,17 +23,46 @@ driver:
visible-if:
use-hostname: false
- user
- - name: use-password
- display-name: "Authenticate with user and password"
- description: Snowflake will soon block password authentication.
- type: boolean
- default: false
+ - name: auth-mode
+ display-name: Authentication method
+ type: select
+ default: key-pair
+ required: true
+ options:
+ - {name: "RSA key pair", value: "key-pair"}
+ - {name: "Workload Identity Federation", value: "wif"}
+ - {name: "Username & password", value: "password"}
+ - name: wif-provider
+ display-name: Workload identity provider
+ type: select
+ required: true
+ options:
+ - {name: "OpenID Connect (JWT)", value: "OIDC"}
+ - {name: "AWS", value: "AWS"}
+ - {name: "Azure", value: "AZURE"}
+ - {name: "Google Cloud", value: "GCP"}
+ visible-if:
+ auth-mode: wif
+ - name: wif-token
+ display-name: OIDC token
+ helper-text: Paste a JWT for a one-off test. Metabase does not refresh tokens.
+ type: password
+ placeholder: "eyJhbGciOi..."
+ visible-if:
+ wif-provider: OIDC
+ - name: wif-token-file-path
+ display-name: OIDC token file path
+ helper-text: A file readable by the Metabase server (e.g. a Kubernetes projected token). Preferred over a pasted JWT because the driver re-reads it per connection.
+ type: string
+ placeholder: "/var/run/secrets/tokens/oidc-token"
+ visible-if:
+ wif-provider: OIDC
- name: private-key
display-name: RSA private key (PKCS#8/.p8)
type: secret
secret-kind: pem-cert
visible-if:
- use-password: false
+ auth-mode: key-pair
required: true
- name: private-key-passphrase
display-name: Private key passphrase
@@ -41,11 +70,12 @@ driver:
type: password
placeholder: "********"
visible-if:
- use-password: false
+ auth-mode: key-pair
- merge:
- password
- visible-if:
- use-password: true
+ auth-mode: password
+ description: Snowflake blocks password authentication for service users by October 2026.
required: true
- name: warehouse
display-name: Warehouse
diff --git a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
index 14c8fd5bc43..ee42d1bd5e3 100644
--- a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
+++ b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
@@ -109,6 +109,33 @@
(any-message? #"(?s)Error finalising cipher|unable to read encrypted data")
(tru "The passphrase for this private key is incorrect.")
+ (any-message? #"No OIDC token was specified")
+ (tru "No OIDC token was provided. Paste a JWT or set the token file path.")
+
+ (any-message? #"(?s)Failed to parse JWT|Unable to extract JWT claims")
+ (tru "The OIDC token isn''t a valid JWT. Check the token you pasted or the file at the provided path.")
+
+ (any-message? #"Missing issuer claim in JWT token")
+ (tru "The OIDC token is missing the required `iss` (issuer) claim.")
+
+ (any-message? #"Missing sub claim in JWT token")
+ (tru "The OIDC token is missing the required `sub` (subject) claim.")
+
+ (any-message? #"No AWS credentials were found")
+ (tru "No AWS credentials found. Make sure Metabase''s workload has an IAM role attached (instance profile, ECS task role, IRSA, etc.).")
+
+ (any-message? #"No AWS region was found")
+ (tru "No AWS region was found. Set AWS_REGION in Metabase''s environment.")
+
+ (any-message? #"Managed identity is not enabled")
+ (tru "No Azure managed identity is configured on Metabase''s host.")
+
+ (any-message? #"(?s)Could not fetch Azure token|No access token found in Azure response")
+ (tru "Metabase couldn''t obtain a token from Azure''s identity endpoint.")
+
+ (any-message? #"No GCP token was found")
+ (tru "Metabase couldn''t obtain a GCP identity token. Check that the workload has a service account attached.")
+
(and (string? message) (re-matches #"(?s).*Object does not exist.*$" message))
:database-name-incorrect
@@ -181,6 +208,44 @@
(dissoc :private-key-passphrase))
(driver-api/clean-secret-properties-from-details details :snowflake))))
+(defn- jwt-expiry-ms
+ "Returns the JWT's `exp` claim as ms-since-epoch, or nil if the token can't be parsed or has no
+ `exp`. Decode-only — no signature verification; the token has already been trusted at this point."
+ [^String jwt]
+ (try
+ (let [[_ payload _] (str/split jwt #"\.")
+ json-str (String. (.decode (java.util.Base64/getUrlDecoder) ^String payload) "UTF-8")]
+ (some-> (json/decode+kw json-str) :exp long (* 1000)))
+ (catch Throwable _ nil)))
+
+(defn- resolve-wif-credentials
+ "Translate WIF details into Snowflake JDBC properties. For OIDC we always pass the token as a
+ plain `:token` string; the Snowflake JDBC driver only honors `token_file_path` under the special
+ `jdbc:snowflake:auto` URL, which we don't use. `:wif-token-file-path` wins over an inline
+ `:wif-token` — the file is slurped here into the pool spec. When the token carries an `exp`
+ claim we set `:password-expiry-timestamp` so the pool self-invalidates on expiry and rebuilds
+ against a rotated file or a fresh in-process mint."
+ [{:keys [wif-provider wif-token wif-token-file-path] :as details}]
+ (let [provider (some-> wif-provider u/upper-case-en)
+ token (when (= "OIDC" provider)
+ (cond
+ (not (str/blank? wif-token-file-path))
+ (str/trim (slurp wif-token-file-path))
+
+ (not (str/blank? wif-token))
+ wif-token))
+ expiry-ms (some-> token jwt-expiry-ms)
+ wif-spec (cond-> {:authenticator "WORKLOAD_IDENTITY"
+ :workloadIdentityProvider provider}
+ token (assoc :token token)
+ expiry-ms (assoc :password-expiry-timestamp expiry-ms))]
+ (-> details
+ (merge wif-spec)
+ (dissoc :wif-provider :wif-token :wif-token-file-path
+ :password :private-key :private-key-value :private-key-path
+ :private-key-id :private-key-options :private-key-passphrase
+ :private-key-source :private-key-creator-id :private-key-created-at))))
+
(defn- quote-name
[raw-name]
(when raw-name
@@ -226,49 +291,71 @@
spec))
(defmethod driver/db-details-to-test-and-migrate :snowflake
- [_ {:keys [password private-key-id private-key-value private-key-path use-password private-key-options] :as details}]
- (when-not (= 1 (count (remove nil? [password private-key-id private-key-value private-key-path])))
- (let [password-details (when password
- (-> details
- ;; Setting private-key-value to nil will delete the secret
- (assoc :use-password true :private-key-value nil)
- (dissoc :private-key-id :private-key-path :private-key-options
- :private-key-passphrase)
- ;; Add meta for testing
- (with-meta {:auth :password})))
- private-key-path-details (when private-key-path
+ [_ {:keys [password private-key-id private-key-value private-key-path
+ use-password private-key-options
+ auth-mode wif-token wif-token-file-path]
+ :as details}]
+ ;; Private-key fields are counted independently because Metabase's history has left DBs with more
+ ;; than one populated at once (legacy `-value` plus a persisted `-id`, etc.) — the migrate flow
+ ;; tries each. WIF is new, has no such legacy state, and has a deterministic within-mode
+ ;; precedence (file-path wins in resolve-wif-credentials), so it counts as one signal.
+ (let [wif-signal (or wif-token wif-token-file-path)]
+ (when-not (= 1 (count (remove nil? [password private-key-id private-key-value private-key-path wif-signal])))
+ (let [wif-details (when wif-signal
+ (-> details
+ (assoc :auth-mode "wif")
+ (dissoc :password :private-key-id :private-key-value :private-key-path
+ :private-key-options :private-key-passphrase :use-password)
+ (with-meta {:auth :wif})))
+ password-details (when password
+ (-> details
+ ;; Setting private-key-value to nil will delete the secret
+ (assoc :use-password true :private-key-value nil :auth-mode "password")
+ (dissoc :private-key-id :private-key-path :private-key-options
+ :private-key-passphrase :wif-token :wif-token-file-path :wif-provider)
+ ;; Add meta for testing
+ (with-meta {:auth :password})))
+ private-key-path-details (when private-key-path
+ (-> details
+ (assoc :use-password false :private-key-options "local" :auth-mode "key-pair")
+ (dissoc :password :private-key-value :wif-token :wif-token-file-path :wif-provider)
+ (with-meta {:auth :private-key-path})))
+ private-key-value-details (when private-key-value
+ (-> details
+ (assoc :use-password false :private-key-options "uploaded" :auth-mode "key-pair")
+ (dissoc :password :private-key-path :wif-token :wif-token-file-path :wif-provider)
+ (with-meta {:auth :private-key-value})))
+ private-key-id-details (when private-key-id
(-> details
- (assoc :use-password false :private-key-options "local")
- (dissoc :password :private-key-value)
- (with-meta {:auth :private-key-path})))
- private-key-value-details (when private-key-value
- (-> details
- (assoc :use-password false :private-key-options "uploaded")
- (dissoc :password :private-key-path)
- (with-meta {:auth :private-key-value})))
- private-key-id-details (when private-key-id
- (-> details
- (assoc :use-password false)
- (dissoc :password :private-key-value :private-key-path :private-key-options)
- (with-meta {:auth :private-key-id})))]
- (cond-> []
- (and use-password password-details)
- (conj password-details)
-
- (and (= "local" private-key-options) private-key-path-details)
- (conj private-key-path-details)
-
- private-key-value-details
- (conj private-key-value-details)
-
- (and (not= "local" private-key-options) private-key-path-details)
- (conj private-key-path-details)
-
- private-key-id-details
- (conj private-key-id-details)
-
- (and (not use-password) password-details)
- (conj password-details)))))
+ (assoc :use-password false :auth-mode "key-pair")
+ (dissoc :password :private-key-value :private-key-path :private-key-options
+ :wif-token :wif-token-file-path :wif-provider)
+ (with-meta {:auth :private-key-id})))]
+ (cond-> []
+ (and (= "wif" auth-mode) wif-details)
+ (conj wif-details)
+
+ (and use-password password-details)
+ (conj password-details)
+
+ (and (= "local" private-key-options) private-key-path-details)
+ (conj private-key-path-details)
+
+ private-key-value-details
+ (conj private-key-value-details)
+
+ (and (not= "local" private-key-options) private-key-path-details)
+ (conj private-key-path-details)
+
+ private-key-id-details
+ (conj private-key-id-details)
+
+ (and (not use-password) password-details)
+ (conj password-details)
+
+ ;; WIF as last-resort when auth-mode isn't explicitly "wif" but WIF fields are present
+ (and (not= "wif" auth-mode) wif-details)
+ (conj wif-details))))))
(defn- normalize-additional-options [additional-options]
(when-not (str/blank? additional-options)
@@ -284,8 +371,32 @@
(dissoc details :schema)
details))
+(defn- infer-auth-mode
+ "Returns \"password\" or \"key-pair\" implied by the auth-related keys in `details`,
+ or nil when none are present."
+ [{:keys [password use-password private-key-id private-key-path private-key-value]}]
+ (cond
+ (and (true? use-password) password) "password"
+ (false? use-password) "key-pair"
+ (or private-key-id private-key-path private-key-value) "key-pair"
+ password "password"))
+
+(defn- resolve-credentials
+ "Set the JDBC credential properties. WIF is explicit (:auth-mode must be `\"wif\"`), because it has
+ no field-based signal to infer from. Otherwise re-derive password vs key-pair from the current
+ details so callers that only tweak :use-password / :password / :private-key-* don't have to keep
+ :auth-mode in sync."
+ [{:keys [auth-mode] :as details}]
+ (case (or (when (= "wif" auth-mode) "wif")
+ (infer-auth-mode details)
+ auth-mode
+ "key-pair")
+ "wif" (resolve-wif-credentials details)
+ "password" (-> details (dissoc :private-key) resolve-private-key)
+ "key-pair" (-> details (dissoc :password) resolve-private-key)))
+
(defmethod sql-jdbc.conn/connection-details->spec :snowflake
- [_ {:keys [account additional-options host use-hostname password use-password], :as details}]
+ [_ {:keys [account additional-options host use-hostname], :as details}]
(when (get "week_start" (sql-jdbc.common/additional-options->map additional-options :url))
(log/warn (str "You should not set WEEK_START in Snowflake connection options; this might lead to incorrect "
"results. Set the Start of Week Setting instead.")))
@@ -325,17 +436,12 @@
(set/rename-keys dtls {:dbname :db})))
;; see https://github.com/metabase/metabase/issues/27856
(update :db quote-name)
- (cond-> use-password
- (dissoc :private-key))
- ;; password takes precedence if `use-password` is missing
- (cond-> (or (false? use-password) (not password))
- (dissoc :password))
;; see https://github.com/metabase/metabase/issues/9511
(update :warehouse upcase-not-nil)
(m/update-existing :schema upcase-not-nil)
(remove-schema-if-in-additional)
- resolve-private-key
- (dissoc :host :port :timezone)))
+ resolve-credentials
+ (dissoc :host :port :timezone :auth-mode)))
(sql-jdbc.common/handle-additional-options (update details
:additional-options normalize-additional-options))
;; Role is not respected when used as connection property if connection string is present with private key
@@ -1028,7 +1134,8 @@
true))))
(defn- normalize-details
- "Normalize a Snowflake details map: merge regionid into account, infer use-password. Given nil, returns nil."
+ "Normalize a Snowflake details map: merge regionid into account, infer use-password and auth-mode.
+ Given nil, returns nil."
[details]
(cond-> details
(not (str/blank? (:regionid details)))
@@ -1040,7 +1147,14 @@
(nil? (:private-key-id details))
(nil? (:private-key-path details))
(nil? (:private-key-value details)))
- (assoc :use-password true)))
+ (assoc :use-password true)
+
+ ;; Skip when nothing implies a mode — overlay maps (:write_data_details / :admin_details)
+ ;; that only tweak account/warehouse must not gain an :auth-mode, which would override
+ ;; :details' :auth-mode during the merge in effective-details.
+ (and (not (contains? details :auth-mode))
+ (some? (infer-auth-mode details)))
+ (as-> d (assoc d :auth-mode (infer-auth-mode d)))))
(defmethod driver/normalize-db-details :snowflake
[_ database]
diff --git a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj
index 30943230709..23edcb014b7 100644
--- a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj
+++ b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj
@@ -4,6 +4,7 @@
(:require
[buddy.core.codecs :as codecs]
[buddy.core.hash :as buddy-hash]
+ [clj-http.client :as http]
[clojure.data :as data]
[clojure.java.jdbc :as jdbc]
[clojure.set :as set]
@@ -224,6 +225,257 @@
(is (= "Metabase_Metabase"
(:application (sql-jdbc.conn/connection-details->spec :snowflake details)))))))
+(def ^:private wif-base-details
+ {:account "acct.us-east-2.aws"
+ :warehouse "COMPUTE_WH"
+ :db "TESTDB"
+ :user "SERVICE_USER"
+ :auth-mode "wif"})
+
+(deftest ^:parallel connection-details->spec-wif-oidc-inline-test
+ (testing "WIF OIDC with an inline pasted JWT sets :token"
+ (let [spec (sql-jdbc.conn/connection-details->spec
+ :snowflake
+ (assoc wif-base-details
+ :wif-provider "OIDC"
+ :wif-token "eyJhbGciOi.the-jwt.signature"))]
+ (is (= "WORKLOAD_IDENTITY" (:authenticator spec)))
+ (is (= "OIDC" (:workloadIdentityProvider spec)))
+ (is (= "eyJhbGciOi.the-jwt.signature" (:token spec)))
+ (is (not (contains? spec :token_file_path))))))
+
+(deftest ^:synchronized connection-details->spec-wif-oidc-file-path-test
+ (testing "WIF OIDC with a token file path slurps the file into :token (Snowflake JDBC ignores token_file_path outside auto mode)"
+ (mt/with-temp-file [tok-path "wif-token"]
+ (spit tok-path "eyJhbGciOi.file-jwt.signature\n")
+ (let [spec (sql-jdbc.conn/connection-details->spec
+ :snowflake
+ (assoc wif-base-details
+ :wif-provider "OIDC"
+ :wif-token-file-path tok-path))]
+ (is (= "eyJhbGciOi.file-jwt.signature" (:token spec)) "trailing newline stripped")
+ (is (not (contains? spec :token_file_path)))))))
+
+(deftest ^:synchronized connection-details->spec-wif-oidc-file-path-wins-test
+ (testing "file path wins over inline token"
+ (mt/with-temp-file [tok-path "wif-token"]
+ (spit tok-path "from-file")
+ (let [spec (sql-jdbc.conn/connection-details->spec
+ :snowflake
+ (assoc wif-base-details
+ :wif-provider "OIDC"
+ :wif-token "from-inline"
+ :wif-token-file-path tok-path))]
+ (is (= "from-file" (:token spec)))))))
+
+(defn- fake-jwt
+ "Build a JWT-shaped string with `claims` as the payload. Header and signature are placeholders —
+ the token is only parseable, not verifiable."
+ [claims]
+ (let [encoder (java.util.Base64/getUrlEncoder)
+ encode (fn [m] (String. (.encode encoder (.getBytes (json/encode m) "UTF-8")) "UTF-8"))]
+ (str (encode {:alg "none"}) "." (encode claims) ".sig")))
+
+(deftest ^:parallel jwt-expiry-ms-test
+ (testing "parses `exp` (seconds since epoch) into milliseconds"
+ (is (= 1700000000000 (#'driver.snowflake/jwt-expiry-ms (fake-jwt {:exp 1700000000 :sub "s"})))))
+ (testing "returns nil when the token has no `exp` claim"
+ (is (nil? (#'driver.snowflake/jwt-expiry-ms (fake-jwt {:sub "s"})))))
+ (testing "returns nil for malformed input (doesn't throw)"
+ (are [input] (nil? (#'driver.snowflake/jwt-expiry-ms input))
+ "not-a-jwt"
+ "onlyone.segment"
+ "a.b.c" ; middle segment isn't valid base64url JSON
+ (str "hdr." (String. (.encode (java.util.Base64/getUrlEncoder) (.getBytes "{not-json" "UTF-8")) "UTF-8") ".sig"))))
+
+(deftest ^:parallel connection-details->spec-wif-sets-expiry-from-jwt-test
+ (testing "when the OIDC token carries `exp`, spec gets :password-expiry-timestamp for pool auto-invalidation"
+ (let [spec (sql-jdbc.conn/connection-details->spec
+ :snowflake
+ (assoc wif-base-details
+ :wif-provider "OIDC"
+ :wif-token (fake-jwt {:exp 1700000000 :sub "s"})))]
+ (is (= 1700000000000 (:password-expiry-timestamp spec)))))
+ (testing "no exp claim → no :password-expiry-timestamp on the spec"
+ (let [spec (sql-jdbc.conn/connection-details->spec
+ :snowflake
+ (assoc wif-base-details
+ :wif-provider "OIDC"
+ :wif-token (fake-jwt {:sub "s"})))]
+ (is (not (contains? spec :password-expiry-timestamp))))))
+
+(deftest ^:parallel connection-details->spec-wif-cloud-providers-test
+ (testing "WIF AWS/AZURE/GCP set no client-side credential fields"
+ (doseq [provider ["AWS" "AZURE" "GCP"]]
+ (testing provider
+ (let [spec (sql-jdbc.conn/connection-details->spec
+ :snowflake
+ (assoc wif-base-details :wif-provider provider))]
+ (is (= "WORKLOAD_IDENTITY" (:authenticator spec)))
+ (is (= provider (:workloadIdentityProvider spec)))
+ (is (not (contains? spec :token)))
+ (is (not (contains? spec :token_file_path))))))))
+
+(deftest ^:parallel connection-details->spec-wif-strips-legacy-creds-test
+ (testing "under WIF, stray password and private-key fields do not leak into the JDBC spec"
+ (let [spec (sql-jdbc.conn/connection-details->spec
+ :snowflake
+ (assoc wif-base-details
+ :wif-provider "OIDC"
+ :wif-token "jwt"
+ :password "stale-password"
+ :private-key-value "stale-key"
+ :private-key-options "uploaded"))]
+ (is (not (contains? spec :password)))
+ (is (not (contains? spec :private_key_file)))
+ (is (nil? (:connection-uri spec))))))
+
+(deftest ^:parallel connection-details->spec-wif-role-as-property-test
+ (testing "under WIF, :role is in the JDBC properties map"
+ (let [spec (sql-jdbc.conn/connection-details->spec
+ :snowflake
+ (assoc wif-base-details
+ :role "MY_ROLE"
+ :wif-provider "OIDC"
+ :wif-token "jwt"))]
+ (is (= "MY_ROLE" (:role spec)))
+ (is (nil? (:connection-uri spec))))))
+
+(deftest ^:parallel normalize-details-auth-mode-backfill-test
+ (testing ":auth-mode is backfilled when auth-related keys imply a mode"
+ (are [in expected] (= expected (:auth-mode (#'driver.snowflake/normalize-details in)))
+ {:password "abc"} "password"
+ {:private-key-path "/tmp/k"} "key-pair"
+ {:private-key-value "xxx"} "key-pair"
+ {:private-key-id 1} "key-pair"
+ {:password "abc" :private-key-path "/x"} "key-pair"))
+ (testing "no auth signals leaves :auth-mode absent (matters for overlay maps)"
+ (is (not (contains? (#'driver.snowflake/normalize-details {}) :auth-mode)))
+ (is (not (contains? (#'driver.snowflake/normalize-details {:account "acct"}) :auth-mode))))
+ (testing "an explicit :auth-mode is preserved"
+ (are [in] (= (:auth-mode in) (:auth-mode (#'driver.snowflake/normalize-details in)))
+ {:auth-mode "wif" :wif-token "jwt"}
+ {:auth-mode "password" :password "abc"}
+ {:auth-mode "key-pair" :private-key-value "xxx"})))
+
+(deftest ^:parallel db-details-to-test-and-migrate-wif-test
+ (testing "WIF-only details are unambiguous — no candidates returned"
+ (is (nil? (driver/db-details-to-test-and-migrate
+ :snowflake
+ (assoc wif-base-details
+ :wif-provider "OIDC"
+ :wif-token "jwt")))))
+ (testing "when WIF and password are both set, WIF is tried first"
+ (let [candidates (driver/db-details-to-test-and-migrate
+ :snowflake
+ (assoc wif-base-details
+ :password "stale-pw"
+ :wif-provider "OIDC"
+ :wif-token "jwt"))]
+ (is (some? candidates))
+ (is (= :wif (-> candidates first meta :auth))))))
+
+(defn- mint-github-actions-oidc-token
+ "Returns a JWT for `audience` from the GitHub Actions OIDC endpoint, or nil when not running
+ under a GH Actions job with `id-token: write`."
+ [audience]
+ (let [req-token (System/getenv "ACTIONS_ID_TOKEN_REQUEST_TOKEN")
+ req-url (System/getenv "ACTIONS_ID_TOKEN_REQUEST_URL")]
+ (when (and (not (str/blank? req-token)) (not (str/blank? req-url)))
+ (let [{:keys [status body]} (http/get (str req-url "&audience=" audience)
+ {:headers {"Authorization" (str "Bearer " req-token)}
+ :throw-exceptions false})]
+ (when (= 200 status)
+ (:value (json/decode+kw body)))))))
+
+(defn- wif-user-or-skip
+ "Returns the WIF service username, or nil to signal the test should skip. Refuses to silently
+ skip: if MB_SNOWFLAKE_TEST_WIF_USER isn't set, records a test failure with instructions instead
+ of leaving the test as a no-op. Set the env var to 'skip' to opt out explicitly (REPL, contexts
+ without a matching Snowflake WORKLOAD_IDENTITY subject)."
+ []
+ (let [wif-user (tx/db-test-env-var :snowflake :wif-user)]
+ (cond
+ (= "skip" wif-user) nil
+ (str/blank? wif-user) (do (is false
+ (str "MB_SNOWFLAKE_TEST_WIF_USER isn't set. Set it to the "
+ "Snowflake WIF service user (e.g. 'METABASE WIF'), or "
+ "to 'skip' to opt out."))
+ nil)
+ :else wif-user)))
+
+(defn- wif-live-details-with-token
+ "WIF details map for the live tests, `token-source` merged in (`:wif-token` or `:wif-token-file-path`)."
+ [token-source]
+ (merge {:account (tx/db-test-env-var-or-throw :snowflake :wif-account)
+ :user (tx/db-test-env-var-or-throw :snowflake :wif-user)
+ :warehouse (tx/db-test-env-var-or-throw :snowflake :wif-warehouse)
+ :db (tx/db-test-env-var-or-throw :snowflake :wif-db)
+ :role (tx/db-test-env-var :snowflake :wif-role)
+ :auth-mode "wif"
+ :wif-provider "OIDC"}
+ token-source))
+
+(deftest ^:synchronized snowflake-wif-live-test
+ ;; End-to-end test against a real Snowflake WIF-configured service user.
+ ;;
+ ;; In CI (GH Actions Snowflake Driver Tests job) we mint a fresh OIDC token on-demand — GH's
+ ;; tokens live 15 minutes and the full snowflake suite runs > 30 minutes, so a token minted at
+ ;; job start would be expired before this test fires. Locally, if
+ ;; MB_SNOWFLAKE_TEST_WIF_TOKEN_FILE points to a JWT on disk, we use that as a fallback.
+ (mt/test-driver
+ :snowflake
+ (when-let [wif-user (wif-user-or-skip)]
+ (when-let [token (or (mint-github-actions-oidc-token "snowflakecomputing.com")
+ (some-> (tx/db-test-env-var :snowflake :wif-token-file)
+ slurp
+ str/trim))]
+ (let [details (wif-live-details-with-token {:wif-token token})]
+ (testing "can-connect? via WIF"
+ (is (true? (driver/can-connect? :snowflake details))))
+ (testing "session identifies as the WIF service user (proves auth flowed through WIF, not a fallback)"
+ (let [spec (sql-jdbc.conn/connection-details->spec :snowflake details)
+ rows (jdbc/query spec ["SELECT CURRENT_USER() AS \"user\""])]
+ (is (= [{:user wif-user}] rows)))))))))
+
+(deftest ^:synchronized snowflake-wif-live-rotation-test
+ ;; Proves the exp-driven pool rotation path works end-to-end: pool built with token A, we backdate the
+ ;; cached :password-expiry-timestamp to simulate expiry, rotate the file to token B, then a follow-up query rebuilds
+ ;; the pool with the fresh token. Requires the GH Actions OIDC env vars.
+ (mt/test-driver
+ :snowflake
+ (when-let [wif-user (wif-user-or-skip)]
+ (when-let [token-a (mint-github-actions-oidc-token "snowflakecomputing.com")]
+ (mt/with-temp-file [tok-file "wif-tok"]
+ (spit tok-file token-a)
+ (mt/with-temp [:model/Database db {:engine :snowflake
+ :details (wif-live-details-with-token {:wif-token-file-path tok-file})}]
+ (let [pool-cache @#'sql-jdbc.conn/pool-cache-key->connection-pool
+ cache-key [(:id db) :default]
+ query! (fn []
+ (jdbc/query (sql-jdbc.conn/db->pooled-connection-spec db)
+ ["SELECT CURRENT_USER() AS \"user\""]))]
+ (testing "initial query works with token-a"
+ (is (= [{:user wif-user}] (query!))))
+ (let [initial-exp (get-in @pool-cache [cache-key :password-expiry-timestamp])]
+ (is (integer? initial-exp)
+ ":password-expiry-timestamp propagated from resolve-wif-credentials to the pool spec")
+ (is (< (System/currentTimeMillis) initial-exp)
+ "initial expiry is in the future — pool wouldn't be invalidated yet")
+ (testing "after simulating expiry + rotating file, next query rebuilds the pool with the new token"
+ ;; Sleep 1.1s so the fresh mint gets a strictly-later `exp` (GH exp is second-precision).
+ (Thread/sleep 1100)
+ (let [token-b (mint-github-actions-oidc-token "snowflakecomputing.com")]
+ (is (not= token-a token-b) "second mint returns a distinct token")
+ (spit tok-file token-b)
+ ;; Backdate the cached expiry — this is what token expiry looks like to `pool-invalidation-reason`.
+ (swap! pool-cache assoc-in [cache-key :password-expiry-timestamp] 1)
+ (is (= [{:user wif-user}] (query!))
+ "query succeeds after simulated expiry — pool must have been rebuilt with token-b")
+ (let [new-exp (get-in @pool-cache [cache-key :password-expiry-timestamp])]
+ (is (> new-exp initial-exp)
+ "new pool's :password-expiry-timestamp reflects the fresher token"))))))))))))
+
(defn- pem->private-key
[pem]
(let [encoded (-> pem
@@ -1258,9 +1510,11 @@
:engine :snowflake,
:details {:use-password false
:password "abc"}}]
- (is (= {:password "abc" :use-password true} (:details db1)))
- (is (=? {:password "abc" :private-key-id int? :use-password :hawk/key-not-present} (:details db2)))
- (is (= {:password "abc" :use-password false} (:details db3)))))))
+ (is (= {:password "abc" :use-password true :auth-mode "password"} (:details db1)))
+ (is (=? {:password "abc" :private-key-id int? :use-password :hawk/key-not-present
+ :auth-mode "key-pair"}
+ (:details db2)))
+ (is (= {:password "abc" :use-password false :auth-mode "key-pair"} (:details db3)))))))
(deftest ^:parallel normalize-write-data-details-test
(mt/test-driver :snowflake
@@ -1278,7 +1532,7 @@
:engine :snowflake
:details {:account "my-instance"}
:write_data_details {:password "secret"}}]
- (is (= {:password "secret" :use-password true}
+ (is (= {:password "secret" :use-password true :auth-mode "password"}
(:write_data_details db))))))))
(deftest ^:parallel set-role-statement-test
diff --git a/src/metabase/driver/sql_jdbc/connection.clj b/src/metabase/driver/sql_jdbc/connection.clj
index 676e348c2b9..5ca8696fd68 100644
--- a/src/metabase/driver/sql_jdbc/connection.clj
+++ b/src/metabase/driver/sql_jdbc/connection.clj
@@ -291,8 +291,11 @@
;; also capture entries related to ssh tunneling for later use
(select-internal-keys-for-spec details-with-auth)
(select-internal-keys-for-spec spec)
- ;; remember when the password expires
- (select-keys details-with-auth [:password-expiry-timestamp]))))
+ ;; remember when the password/token expires — either baked into the details by an auth-provider,
+ ;; or into the spec by a driver that derives it from the credential itself (e.g. Snowflake WIF's
+ ;; JWT exp claim).
+ (select-keys details-with-auth [:password-expiry-timestamp])
+ (select-keys spec [:password-expiry-timestamp]))))
(defn- destroy-pool! [database-id pool-spec]
;; INFO (not DEBUG) so pool destruction is visible in CI test-log artifacts: destroying a pool closes its