Skip to content

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

feat: generic oidc provider using auth-identity (#65872)

Edward Paget59adba6f988c
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index dfb12f47737..14b68c8a92a 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1389,6 +1389,7 @@
permissions
premium-features
settings
+ system
util}}
startup
diff --git a/mage/resources/token_scanner/token_whitelist.txt b/mage/resources/token_scanner/token_whitelist.txt
index b4afa553120..06e22023a47 100644
--- a/mage/resources/token_scanner/token_whitelist.txt
+++ b/mage/resources/token_scanner/token_whitelist.txt
@@ -16,3 +16,5 @@ airgap_eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhDQkMtSFMyNTYifQ.rHUDSPzcF-Kth1pIXb
# a url that looks like a token
eyJkYXRhc2V0X3F1ZXJ5Ijp7ImxpYi90eXBlIjoibWJxbC9xdWVyeSIsInN0YWdlcyI6W3sic291cmNlLXRhYmxlIjozLCJsaWIvdHlwZSI6Im1icWwuc3RhZ2UvbWJxbCIsImV4cHJlc3Npb25zIjpbWyJjb25jYXQiLHsibGliL3V1aWQiOiJjZDRlNDM5Yy00OTYwLTRlOWMtOGFkMy1iODQ2Mjk1ZjVmOGYiLCJlZmZlY3RpdmUtdHlwZSI6InR5cGUvVGV4dCIsImxpYi9leHByZXNzaW9uLW5hbWUiOiJHb29nbGUgaXQifSwiaHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS9zZWFyY2g_cT1FQU4lMjAiLFsiZmllbGQiLHsibGliL3V1aWQiOiI2ODkxODJkOS0zNGMzLTQ5NGYtODk4NC1lNmUxODNmNzlmZDAiLCJlZmZlY3RpdmUtdHlwZSI6InR5cGUvVGV4dCIsImJhc2UtdHlwZSI6InR5cGUvVGV4dCJ9LDE1XV0sWyJjb25jYXQiLHsibGliL3V1aWQiOiJhNzMzZjNkNS1mZmNkLTQyMGYtOTMwNy1kMDlhOGM0MjBlMjgiLCJsaWIvZXhwcmVzc2lvbi1uYW1lIjoiQmluZyBpdCJ9LCJodHRwczovL3d3dy5iaW5nLmNvbS9zZWFyY2g_cT1FQU4lMjAiLFsiZmllbGQiLHsiZWZmZWN0aXZlLXR5cGUiOiJ0eXBlL1RleHQiLCJsaWIvdXVpZCI6ImI3ZTc2MGY3LTI3ZTktNDZiZS04NGVhLWZhMDIwOTRlMzUzMCIsImJhc2UtdHlwZSI6InR5cGUvVGV4dCJ9LDE1XV1dfV0sImRhdGFiYXNlIjoxfSwiZGlzcGxheSI6InRhYmxlIiwidmlzdWFsaXphdGlvbl9zZXR0aW5ncyI6e30sInR5cGUiOiJxdWVzdGlvbiJ9
+# invalid jwt token for tests
+eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIn0.invalid-signature
diff --git a/src/metabase/request/util.clj b/src/metabase/request/util.clj
index 9ba759d08a7..87300c3ec8b 100644
--- a/src/metabase/request/util.clj
+++ b/src/metabase/request/util.clj
@@ -46,34 +46,14 @@
;; font files are static and should be cached
(re-matches #"^/app/fonts/.+\.(woff2?|ttf|otf|eot)$" uri))))
-(defn https?
+(def https?
"True if the original request made by the frontend client (i.e., browser) was made over HTTPS.
In many production instances, a reverse proxy such as an ELB or nginx will handle SSL termination, and the actual
- request handled by Jetty will be over HTTP."
- [{{:strs [x-forwarded-proto x-forwarded-protocol x-url-scheme x-forwarded-ssl front-end-https origin]} :headers
- :keys [scheme]}]
- (cond
- ;; If `X-Forwarded-Proto` is present use that. There are several alternate headers that mean the same thing. See
- ;; https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
- (or x-forwarded-proto x-forwarded-protocol x-url-scheme)
- (= "https" (u/lower-case-en (or x-forwarded-proto x-forwarded-protocol x-url-scheme)))
-
- ;; If none of those headers are present, look for presence of `X-Forwarded-Ssl` or `Frontend-End-Https`, which
- ;; will be set to `on` if the original request was over HTTPS.
- (or x-forwarded-ssl front-end-https)
- (= "on" (u/lower-case-en (or x-forwarded-ssl front-end-https)))
-
- ;; If none of the above are present, we are most not likely being accessed over a reverse proxy. Still, there's a
- ;; good chance `Origin` will be present because it should be sent with `POST` requests, and most auth requests are
- ;; `POST`. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
- origin
- (str/starts-with? (u/lower-case-en origin) "https")
-
- ;; Last but not least, if none of the above are set (meaning there are no proxy servers such as ELBs or nginx in
- ;; front of us), we can look directly at the scheme of the request sent to Jetty.
- scheme
- (= scheme :https)))
+ request handled by Jetty will be over HTTP.
+
+ Note: Implementation is in [[metabase.util/https?]]."
+ u/https?)
(defn embedded?
"Whether this frontend client that made this request is embedded inside an `<iframe>`."
diff --git a/src/metabase/sso/core.clj b/src/metabase/sso/core.clj
index fd2e6b03d1c..4df0df08dc8 100644
--- a/src/metabase/sso/core.clj
+++ b/src/metabase/sso/core.clj
@@ -4,6 +4,7 @@
[metabase.sso.google]
[metabase.sso.ldap]
[metabase.sso.ldap.default-implementation]
+ [metabase.sso.oidc.state]
[metabase.sso.settings]
[potemkin :as p]))
@@ -13,6 +14,9 @@
[metabase.sso.ldap.default-implementation
LDAPSettings
ldap-search-result->user-info]
+ [metabase.sso.oidc.state
+ wrap-oidc-redirect
+ clear-oidc-state-cookie]
[metabase.sso.settings
google-auth-client-id
google-auth-enabled
diff --git a/src/metabase/sso/init.clj b/src/metabase/sso/init.clj
index 7e459a53f31..257e4d7475e 100644
--- a/src/metabase/sso/init.clj
+++ b/src/metabase/sso/init.clj
@@ -2,4 +2,5 @@
(:require
[metabase.sso.providers.google]
[metabase.sso.providers.ldap]
+ [metabase.sso.providers.oidc]
[metabase.sso.settings]))
diff --git a/src/metabase/sso/oidc/common.clj b/src/metabase/sso/oidc/common.clj
new file mode 100644
index 00000000000..b60bf444e82
--- /dev/null
+++ b/src/metabase/sso/oidc/common.clj
@@ -0,0 +1,118 @@
+(ns metabase.sso.oidc.common
+ "Common utilities for OIDC authentication."
+ (:require
+ [buddy.core.codecs :as codecs]
+ [buddy.core.nonce :as nonce]
+ [clojure.string :as str]
+ [ring.util.codec :as codec]))
+
+(defn generate-state
+ "Generate a cryptographically random state token for CSRF protection."
+ []
+ (-> (nonce/random-bytes 32) codecs/bytes->hex))
+
+(defn generate-nonce
+ "Generate a cryptographically random nonce for token validation."
+ []
+ (-> (nonce/random-bytes 32) codecs/bytes->hex))
+
+(defn build-query-string
+ "Build a URL query string from a map of parameters.
+ Properly encodes parameter names and values."
+ [params]
+ (str/join "&"
+ (for [[k v] params]
+ (str (codec/url-encode (name k))
+ "="
+ (codec/url-encode (str v))))))
+
+(defn generate-authorization-url
+ "Generate the authorization URL for OIDC flow.
+
+ Parameters:
+ - authorization-endpoint: The authorization endpoint URL
+ - client-id: OAuth client ID
+ - redirect-uri: Callback URI for the authorization response
+ - scopes: Vector of scope strings (e.g., [\"openid\" \"email\" \"profile\"])
+ - state: CSRF protection state token
+ - nonce: Token validation nonce
+
+ Returns the complete authorization URL."
+ [authorization-endpoint client-id redirect-uri scopes state nonce]
+ (let [params {:response_type "code"
+ :client_id client-id
+ :redirect_uri redirect-uri
+ :scope (str/join " " scopes)
+ :state state
+ :nonce nonce}
+ query-string (build-query-string params)]
+ (str authorization-endpoint "?" query-string)))
+
+(defn extract-oidc-config
+ "Extract OIDC configuration from various sources.
+
+ Tries in order:
+ 1. :oidc-config key in request
+ 2. :metadata field in :auth-identity
+ 3. Direct keys in request
+
+ Parameters:
+ - request: Ring request map
+
+ Returns the OIDC configuration map or nil."
+ [request]
+ (not-empty (or (:oidc-config request)
+ (get-in request [:auth-identity :metadata])
+ (select-keys request [:client-id :client-secret :issuer-uri :redirect-uri
+ :authorization-endpoint :token-endpoint
+ :userinfo-endpoint :jwks-uri :scopes]))))
+
+(defn parse-token-response
+ "Parse the token endpoint response.
+
+ Parameters:
+ - response-body: Token endpoint response body (map)
+
+ Returns a map with :id-token, :access-token, :refresh-token (if present)."
+ [response-body]
+ {:id-token (:id_token response-body)
+ :access-token (:access_token response-body)
+ :refresh-token (:refresh_token response-body)
+ :expires-in (:expires_in response-body)})
+
+(defn validate-callback-params
+ "Validate OIDC callback parameters.
+
+ Parameters:
+ - params: Query parameters from callback request
+
+ Returns a map with:
+ - :valid? - boolean indicating if params are valid
+ - :code - authorization code if valid
+ - :state - state token if valid
+ - :error - error information if invalid"
+ [params]
+ (cond
+ ;; Error response from provider
+ (:error params)
+ {:valid? false
+ :error {:code (:error params)
+ :description (:error_description params)}}
+
+ ;; Missing authorization code
+ (not (:code params))
+ {:valid? false
+ :error {:code :missing_code
+ :description "Authorization code not found in callback"}}
+
+ ;; Missing state
+ (not (:state params))
+ {:valid? false
+ :error {:code :missing_state
+ :description "State parameter not found in callback"}}
+
+ ;; Valid
+ :else
+ {:valid? true
+ :code (:code params)
+ :state (:state params)}))
diff --git a/src/metabase/sso/oidc/discovery.clj b/src/metabase/sso/oidc/discovery.clj
new file mode 100644
index 00000000000..97ec48a24ab
--- /dev/null
+++ b/src/metabase/sso/oidc/discovery.clj
@@ -0,0 +1,158 @@
+(ns metabase.sso.oidc.discovery
+ "OIDC discovery document fetching and caching.
+
+ Fetches and caches OpenID Connect discovery documents from provider issuers.
+ Falls back to manual configuration when discovery is unavailable."
+ (:require
+ [clj-http.client :as http]
+ [clojure.string :as str]
+ [java-time.api :as t]
+ [metabase.util.http :as u.http]
+ [metabase.util.log :as log]))
+
+(def ^:private discovery-cache
+ "Cache of discovery documents with TTL.
+ Map of issuer URL string -> {:document discovery-map :fetched-at timestamp}."
+ (atom {}))
+
+(def ^:private discovery-cache-ttl-ms
+ "Discovery document cache TTL: 24 hours. After this time, cached documents will be re-fetched.
+ This ensures endpoint changes by IdPs are picked up within a reasonable timeframe."
+ 86400000)
+
+(defn- cache-expired?
+ "Check if a cache entry has expired based on its fetched-at timestamp."
+ [cache-entry]
+ (or (nil? cache-entry)
+ (nil? (:fetched-at cache-entry))
+ (> (- (t/to-millis-from-epoch (t/instant)) (:fetched-at cache-entry))
+ discovery-cache-ttl-ms)))
+
+(defn- normalize-issuer
+ "Normalize issuer URL by removing trailing slashes."
+ [issuer]
+ (when issuer
+ (str/replace issuer #"/$" "")))
+
+(defn- discovery-url
+ "Build the OIDC discovery document URL for the given issuer."
+ [issuer]
+ (str (normalize-issuer issuer) "/.well-known/openid-configuration"))
+
+(defn- fetch-discovery-document
+ "Fetch the OIDC discovery document from the issuer.
+ Returns the parsed JSON document or nil on error."
+ [issuer]
+ (let [url (discovery-url issuer)]
+ (when-not (u.http/valid-host? :external-only url)
+ (throw (ex-info "Invalid issuer URL: internal addresses not allowed"
+ {:url url})))
+ (try
+ (log/infof "Fetching OIDC discovery document from %s" url)
+ (let [response (http/get url {:as :json
+ :accept :json
+ :throw-exceptions false
+ :conn-timeout 5000
+ :socket-timeout 5000})]
+ (if (= 200 (:status response))
+ (:body response)
+ (do
+ (log/warnf "OIDC discovery failed with status %s: %s" (:status response) (:body response))
+ nil)))
+ (catch Exception e
+ (log/warnf e "Failed to fetch OIDC discovery document from %s" url)
+ nil))))
+
+(defn clear-cache!
+ "Clear all cached discovery documents.
+ Useful for testing or when configuration changes."
+ []
+ (reset! discovery-cache {}))
+
+(defn invalidate-cache!
+ "Invalidate cached discovery document for a specific issuer.
+ Useful when an admin wants to force a refresh."
+ [issuer]
+ (when issuer
+ (let [normalized (normalize-issuer issuer)]
+ (swap! discovery-cache dissoc normalized)
+ (log/infof "Invalidated discovery cache for issuer %s" normalized)))
+ nil)
+
+(defn discover-oidc-configuration
+ "Fetch and cache the OIDC discovery document for the given issuer.
+
+ Parameters:
+ - issuer: The issuer URL (e.g., \"https://accounts.google.com\")
+
+ Returns the discovery document map or nil if discovery fails.
+ Results are cached per issuer with TTL-based expiration (see [[discovery-cache-ttl-ms]])."
+ [issuer]
+ (when issuer
+ (let [normalized-issuer (normalize-issuer issuer)
+ cached (get @discovery-cache normalized-issuer)]
+ (if (and cached (not (cache-expired? cached)))
+ (do
+ (log/debugf "Using cached discovery document for issuer %s" normalized-issuer)
+ (:document cached))
+ (do
+ (when cached
+ (log/infof "Discovery cache expired for issuer %s, re-fetching" normalized-issuer))
+ (when-let [doc (fetch-discovery-document normalized-issuer)]
+ (swap! discovery-cache assoc normalized-issuer {:document doc :fetched-at (t/to-millis-from-epoch (t/instant))})
+ doc))))))
+
+(defn- get-endpoint
+ "Extract an endpoint from the discovery document or manual configuration.
+
+ Parameters:
+ - config: Map containing either :discovery-document or manual endpoint configurations
+ - discovery-key: Key in the discovery document (e.g., :authorization_endpoint)
+ - manual-key: Key in manual configuration (e.g., :authorization-endpoint)
+
+ Returns the endpoint URL string or nil."
+ [config discovery-key manual-key]
+ (or (get-in config [:discovery-document discovery-key])
+ (get config manual-key)))
+
+(defn get-authorization-endpoint
+ "Get the authorization endpoint from discovery document or manual config.
+
+ Parameters:
+ - config: Map with either :discovery-document or :authorization-endpoint
+
+ Returns the authorization endpoint URL."
+ [config]
+ (get-endpoint config :authorization_endpoint :authorization-endpoint))
+
+(defn get-token-endpoint
+ "Get the token endpoint from discovery document or manual config.
+
+ Parameters:
+ - config: Map with either :discovery-document or :token-endpoint
+
+ Returns the token endpoint URL."
+ [config]
+ (get-endpoint config :token_endpoint :token-endpoint))
+
+(defn get-jwks-uri
+ "Get the JWKS URI from discovery document or manual config.
+
+ Parameters:
+ - config: Map with either :discovery-document or :jwks-uri
+
+ Returns the JWKS URI."
+ [config]
+ (get-endpoint config :jwks_uri :jwks-uri))
+
+(defn validate-configuration
+ "Validate that a configuration has all required endpoints.
+
+ Parameters:
+ - config: Configuration map (from discovery or manual)
+
+ Returns true if all required endpoints are present, false otherwise."
+ [config]
+ (and (get-authorization-endpoint config)
+ (get-token-endpoint config)
+ (get-jwks-uri config)))
diff --git a/src/metabase/sso/oidc/schema.clj b/src/metabase/sso/oidc/schema.clj
new file mode 100644
index 00000000000..9895a329d21
--- /dev/null
+++ b/src/metabase/sso/oidc/schema.clj
@@ -0,0 +1,119 @@
+(ns metabase.sso.oidc.schema
+ "Malli schemas for OIDC configuration and token claims."
+ (:require
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]))
+
+;;; Configuration Schemas
+
+(mr/def ::client-id
+ [:string {:min 1
+ :error/message "Client ID is required and must not be empty"}])
+
+(mr/def ::client-secret
+ [:string {:min 1
+ :error/message "Client secret is required and must not be empty"}])
+
+(mr/def ::uri
+ [:and
+ ms/NonBlankString
+ [:fn {:error/message "Must be a valid URI"}
+ (fn [s]
+ (try
+ (java.net.URI. s)
+ true
+ (catch Exception _
+ false)))]])
+
+(mr/def ::issuer-uri
+ ::uri)
+
+(mr/def ::redirect-uri
+ ::uri)
+
+(mr/def ::authorization-endpoint
+ [:maybe ::uri])
+
+(mr/def ::token-endpoint
+ [:maybe ::uri])
+
+(mr/def ::userinfo-endpoint
+ [:maybe ::uri])
+
+(mr/def ::jwks-uri
+ [:maybe ::uri])
+
+(mr/def ::scopes
+ [:vector {:min 1
+ :default ["openid" "email" "profile"]
+ :error/message "At least one scope is required"}
+ ms/NonBlankString])
+
+(mr/def ::oidc-configuration
+ [:map {:closed true}
+ [:client-id ::client-id]
+ [:client-secret ::client-secret]
+ [:issuer-uri ::issuer-uri]
+ [:redirect-uri ::redirect-uri]
+ [:authorization-endpoint {:optional true} ::authorization-endpoint]
+ [:token-endpoint {:optional true} ::token-endpoint]
+ [:userinfo-endpoint {:optional true} ::userinfo-endpoint]
+ [:jwks-uri {:optional true} ::jwks-uri]
+ [:scopes {:optional true
+ :default ["openid" "email" "profile"]} ::scopes]])
+
+;;; ID Token Claim Schemas
+
+(mr/def ::sub
+ [:string {:min 1
+ :error/message "Subject identifier (sub) is required"}])
+
+(mr/def ::iss
+ [:string {:min 1
+ :error/message "Issuer (iss) is required"}])
+
+(mr/def ::aud
+ [:or
+ [:string {:min 1}]
+ [:vector {:min 1} [:string {:min 1}]]])
+
+(mr/def ::exp
+ [:int {:min 0
+ :error/message "Expiry time (exp) must be a positive integer"}])
+
+(mr/def ::iat
+ [:int {:min 0
+ :error/message "Issued at time (iat) must be a positive integer"}])
+
+(mr/def ::email
+ [:maybe ms/Email])
+
+(mr/def ::given-name
+ [:maybe ms/NonBlankString])
+
+(mr/def ::family-name
+ [:maybe ms/NonBlankString])
+
+(mr/def ::name
+ [:maybe ms/NonBlankString])
+
+(mr/def ::id-token-claims
+ [:map
+ [:sub ::sub]
+ [:iss ::iss]
+ [:aud ::aud]
+ [:exp ::exp]
+ [:iat ::iat]
+ [:email {:optional true} ::email]
+ [:given_name {:optional true} ::given-name]
+ [:family_name {:optional true} ::family-name]
+ [:name {:optional true} ::name]])
+
+(defn discovery-based?
+ "Returns true if the configuration relies on discovery (only required fields present),
+ false if endpoints are manually specified."
+ [config]
+ (not (or (:authorization-endpoint config)
+ (:token-endpoint config)
+ (:userinfo-endpoint config)
+ (:jwks-uri config))))
diff --git a/src/metabase/sso/oidc/state.clj b/src/metabase/sso/oidc/state.clj
new file mode 100644
index 00000000000..848d2f2e6c8
--- /dev/null
+++ b/src/metabase/sso/oidc/state.clj
@@ -0,0 +1,350 @@
+(ns metabase.sso.oidc.state
+ "Encrypted cookie-based state management for OIDC authentication flows.
+
+ Provides secure storage of OIDC state (CSRF token), nonce (ID token validation),
+ redirect URL, and provider identification in a single encrypted cookie.
+
+ Security features:
+ - AES256-CBC-HMAC-SHA512 encryption using MB_ENCRYPTION_SECRET_KEY
+ - Built-in TTL validation (independent of cookie expiry)
+ - Optional browser binding for request forgery protection
+ - Tamper-evident via HMAC validation
+ - Redirect URL validation to prevent open redirect attacks"
+ (:require
+ [clojure.string :as str]
+ [java-time.api :as t]
+ [metabase.system.core :as system]
+ [metabase.util :as u]
+ [metabase.util.encryption :as encryption]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log]
+ [ring.util.response :as response])
+ (:import
+ (java.net URI URISyntaxException)))
+
+(set! *warn-on-reflection* true)
+
+;;; -------------------------------------------------- Constants --------------------------------------------------
+
+(def ^:private oidc-state-cookie-name
+ "Name of the encrypted OIDC state cookie."
+ "metabase.OIDC_STATE")
+
+(def ^:private default-ttl-ms
+ "Default time-to-live for OIDC state in milliseconds (10 minutes)."
+ 600000)
+
+;;; -------------------------------------------------- Redirect URL Validation --------------------------------------------------
+
+(defn- parse-uri
+ "Parse a string as a URI, returning nil if invalid."
+ ^URI [^String s]
+ (when (and s (not (str/blank? s)))
+ (try
+ (URI. s)
+ (catch URISyntaxException _
+ nil))))
+
+(defn- uri-origin
+ "Extract the origin (scheme://host:port) from a URI string.
+ Returns nil if the URI is invalid or has no scheme/host."
+ [^String uri-str]
+ (when-let [^URI uri (parse-uri uri-str)]
+ (let [scheme (.getScheme uri)
+ host (.getHost uri)
+ port (.getPort uri)]
+ (when (and scheme host)
+ (if (or (neg? port)
+ (and (= scheme "http") (= port 80))
+ (and (= scheme "https") (= port 443)))
+ (str scheme "://" host)
+ (str scheme "://" host ":" port))))))
+
+(defn- relative-url?
+ "Returns true if the URL is a relative path (starts with /).
+ Rejects protocol-relative URLs (//example.com) which could redirect to external sites."
+ [^String url]
+ (and (str/starts-with? url "/")
+ (not (str/starts-with? url "//"))))
+
+(defn valid-redirect-url?
+ "Validates that a redirect URL is safe for use after OIDC authentication.
+
+ A redirect URL is considered safe if it is:
+ 1. A relative URL starting with '/' (but not protocol-relative '//')
+ 2. An absolute URL with the same origin as the site-url
+
+ Parameters:
+ - redirect-url: The URL to validate
+ - site-url: The configured site URL (optional, will use system setting if not provided)
+
+ Returns true if the redirect URL is safe, false otherwise."
+ ([redirect-url]
+ (valid-redirect-url? redirect-url (system/site-url)))
+ ([redirect-url site-url]
+ (cond
+ ;; Nil or blank URLs are not valid
+ (or (nil? redirect-url) (str/blank? redirect-url))
+ false
+
+ ;; Relative URLs starting with / are safe (but not // which is protocol-relative)
+ (relative-url? redirect-url)
+ true
+
+ ;; Absolute URLs must have the same origin as site-url
+ :else
+ (let [redirect-origin (uri-origin redirect-url)
+ site-origin (uri-origin site-url)]
+ (and (some? redirect-origin)
+ (some? site-origin)
+ (= (u/lower-case-en redirect-origin)
+ (u/lower-case-en site-origin)))))))
+
+(defn- validate-redirect-url!
+ "Validates a redirect URL and throws an exception if invalid.
+ This prevents open redirect attacks by ensuring redirects stay within the application."
+ [redirect-url]
+ (when-not (valid-redirect-url? redirect-url)
+ (log/warnf "OIDC redirect URL validation failed: %s" redirect-url)
+ (throw (ex-info (tru "Invalid redirect URL. Redirect must be a relative path or same-origin URL.")
+ {:status-code 400
+ :redirect-url redirect-url}))))
+
+;;; -------------------------------------------------- State Creation --------------------------------------------------
+
+(defn create-oidc-state
+ "Create an OIDC state payload for encryption.
+
+ Required options:
+ - :state - CSRF protection token
+ - :nonce - ID token validation nonce
+ - :redirect - Post-auth redirect URL (must be relative or same-origin)
+ - :provider - Provider identifier keyword or string (e.g., :slack-connect)
+
+ Optional:
+ - :ttl-ms - Time-to-live in milliseconds (default: 600000 = 10 min)
+ - :browser-id - Browser identifier for request forgery protection
+
+ Returns a map suitable for encryption.
+
+ Throws an exception if the redirect URL is invalid (not relative or not same-origin).
+ This prevents open redirect attacks."
+ [{:keys [state nonce redirect provider ttl-ms browser-id]
+ :or {ttl-ms default-ttl-ms}}]
+ {:pre [(some? state) (some? nonce) (some? redirect) (some? provider)]}
+ ;; Validate redirect URL to prevent open redirect attacks
+ (validate-redirect-url! redirect)
+ (let [now (t/to-millis-from-epoch (t/instant))]
+ (cond-> {:state state
+ :nonce nonce
+ :redirect redirect
+ :provider (name provider)
+ :created-at now
+ :expires-at (+ now ttl-ms)}
+ browser-id (assoc :browser-id browser-id))))
+
+;;; -------------------------------------------------- Encryption --------------------------------------------------
+
+(defn- assert-encryption-enabled!
+ "Throws an exception if encryption is not enabled."
+ []
+ (when-not (encryption/default-encryption-enabled?)
+ (throw (ex-info (tru "OIDC authentication requires MB_ENCRYPTION_SECRET_KEY to be set. Please configure encryption to use OIDC authentication.")
+ {:status-code 500}))))
+
+(defn encrypt-state
+ "Encrypt OIDC state payload to a URL-safe string.
+
+ Uses Metabase's AES256-CBC-HMAC-SHA512 encryption with MB_ENCRYPTION_SECRET_KEY.
+ Throws an exception if encryption is not enabled."
+ [state-map]
+ (assert-encryption-enabled!)
+ (-> state-map
+ json/encode
+ encryption/encrypt))
+
+(defn decrypt-state
+ "Decrypt and validate OIDC state from encrypted string.
+
+ Returns the state map if valid, or nil if:
+ - Decryption fails (tampered or wrong key)
+ - State has expired (based on :expires-at)
+ - State is malformed
+
+ Options:
+ - :validate-browser-id - If provided, validates that :browser-id matches"
+ ([encrypted-state]
+ (decrypt-state encrypted-state nil))
+ ([encrypted-state {:keys [validate-browser-id]}]
+ (when encrypted-state
+ (try
+ (let [state-map (-> encrypted-state
+ encryption/decrypt
+ json/decode+kw)
+ now (t/to-millis-from-epoch (t/instant))]
+ (cond
+ ;; Not a valid map
+ (not (map? state-map))
+ (do (log/warn "OIDC state decryption produced non-map result")
+ nil)
+
+ ;; Missing required fields
+ (not (and (:state state-map)
+ (:nonce state-map)
+ (:redirect state-map)
+ (:provider state-map)
+ (:expires-at state-map)))
+ (do (log/warn "OIDC state missing required fields")
+ nil)
+
+ ;; Expired
+ (<= (:expires-at state-map) now)
+ (do (log/warn "OIDC state has expired")
+ nil)
+
+ ;; Browser-id mismatch (if validation requested)
+ (and validate-browser-id
+ (not= validate-browser-id (:browser-id state-map)))
+ (do (log/warnf "OIDC state browser-id mismatch: expected %s" validate-browser-id)
+ nil)
+
+ ;; Valid
+ :else
+ state-map))
+ (catch Exception e
+ (log/warn e "Failed to decrypt OIDC state")
+ nil)))))
+
+;;; -------------------------------------------------- Cookie Management --------------------------------------------------
+
+(defn- cookie-options
+ "Generate secure cookie options based on the request."
+ [request ttl-seconds]
+ (merge
+ {:http-only true
+ :path "/"
+ :max-age ttl-seconds}
+ ;; Use SameSite=Lax for OIDC since we need the cookie sent on redirect back from IdP
+ ;; Secure=true only when using HTTPS
+ (if (u/https? request)
+ {:same-site :lax
+ :secure true}
+ {:same-site :lax})))
+
+(defn set-oidc-state-cookie
+ "Add encrypted OIDC state cookie to response.
+
+ Parameters:
+ - response - Ring response map
+ - request - Ring request (for determining secure/https)
+ - state-data - Map with :state, :nonce, :redirect, :provider keys
+ - options - Optional map with :ttl-ms (default 600000), :browser-id
+
+ Returns updated response with cookie set."
+ ([response request state-data]
+ (set-oidc-state-cookie response request state-data {}))
+ ([response request state-data {:keys [ttl-ms browser-id] :or {ttl-ms default-ttl-ms}}]
+ (let [full-state (create-oidc-state (cond-> (assoc state-data :ttl-ms ttl-ms)
+ browser-id (assoc :browser-id browser-id)))
+ encrypted (encrypt-state full-state)
+ ttl-seconds (quot ttl-ms 1000)]
+ (response/set-cookie response
+ oidc-state-cookie-name
+ encrypted
+ (cookie-options request ttl-seconds)))))
+
+(defn get-oidc-state
+ "Retrieve and validate OIDC state from request cookies.
+
+ Parameters:
+ - request - Ring request with :cookies
+ - options - Optional map with :validate-browser-id, :expected-provider
+
+ Returns decrypted state map if valid, nil otherwise.
+ Validates expiration and optionally browser-id and provider."
+ ([request]
+ (get-oidc-state request {}))
+ ([request {:keys [validate-browser-id expected-provider]}]
+ (when-let [encrypted (get-in request [:cookies oidc-state-cookie-name :value])]
+ (when-let [state (decrypt-state encrypted {:validate-browser-id validate-browser-id})]
+ (if (and expected-provider
+ (not= (name expected-provider) (:provider state)))
+ (do (log/warnf "OIDC state provider mismatch: expected %s, got %s"
+ (name expected-provider) (:provider state))
+ nil)
+ state)))))
+
+(defn clear-oidc-state-cookie
+ "Clear the OIDC state cookie from response.
+
+ Should be called after successful authentication to prevent replay."
+ [response]
+ (response/set-cookie response
+ oidc-state-cookie-name
+ ""
+ {:max-age 0
+ :path "/"}))
+
+;;; -------------------------------------------------- High-Level Integration --------------------------------------------------
+
+(defn wrap-oidc-redirect
+ "Wrap an OIDC redirect response with state cookie.
+
+ Takes the auth-result from authenticate (with :redirect-url, :state, :nonce)
+ and returns a Ring redirect response with encrypted state cookie.
+
+ Parameters:
+ - auth-result - Map from authenticate with :redirect-url, :state, :nonce
+ - request - Ring request
+ - provider - Provider keyword (e.g., :slack-connect)
+ - redirect - Final redirect URL after auth completes
+ - options - Optional: :ttl-ms, :browser-id"
+ ([auth-result request provider redirect]
+ (wrap-oidc-redirect auth-result request provider redirect {}))
+ ([auth-result request provider redirect options]
+ (-> (response/redirect (:redirect-url auth-result))
+ (set-oidc-state-cookie request
+ {:state (:state auth-result)
+ :nonce (:nonce auth-result)
+ :redirect redirect
+ :provider provider}
+ options))))
+
+(defn validate-oidc-callback
+ "Validate OIDC callback request against stored state.
+
+ Checks:
+ 1. State cookie exists and is valid (not expired, not tampered)
+ 2. State parameter matches stored state (CSRF protection)
+ 3. Provider matches expected provider
+ 4. Optionally validates browser-id
+
+ Parameters:
+ - request - Ring request with :cookies
+ - expected-state - State parameter from callback query string
+ - expected-provider - Expected provider keyword
+ - options - Optional: :validate-browser-id
+
+ Returns map with :valid? and either :state-data/:nonce/:redirect or :error/:message"
+ ([request expected-state expected-provider]
+ (validate-oidc-callback request expected-state expected-provider {}))
+ ([request expected-state expected-provider options]
+ (let [state-data (get-oidc-state request (merge options
+ {:expected-provider expected-provider}))]
+ (cond
+ (nil? state-data)
+ {:valid? false
+ :error :invalid-or-expired-state
+ :message (tru "OIDC state cookie is invalid, expired, or missing")}
+
+ (not= expected-state (:state state-data))
+ {:valid? false
+ :error :state-mismatch
+ :message (tru "State parameter does not match - possible CSRF attack")}
+
+ :else
+ {:valid? true
+ :state-data state-data
+ :nonce (:nonce state-data)
+ :redirect (:redirect state-data)}))))
diff --git a/src/metabase/sso/oidc/tokens.clj b/src/metabase/sso/oidc/tokens.clj
new file mode 100644
index 00000000000..140c06e3d5f
--- /dev/null
+++ b/src/metabase/sso/oidc/tokens.clj
@@ -0,0 +1,217 @@
+(ns metabase.sso.oidc.tokens
+ "JWT token validation and JWKS handling for OIDC."
+ (:require
+ [buddy.core.keys :as keys]
+ [buddy.sign.jwt :as jwt]
+ [clj-http.client :as http]
+ [java-time.api :as t]
+ [metabase.util :as u]
+ [metabase.util.http :as u.http]
+ [metabase.util.log :as log]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private jwks-cache
+ "Cache of JWKS with TTL. Map of JWKS URI string -> {:jwks map :fetched-at timestamp}."
+ (atom {}))
+
+(def ^:private jwks-cache-ttl-ms
+ "JWKS cache TTL: 1 hour. After this time, cached JWKS will be re-fetched.
+ This ensures key rotations by IdPs are picked up within a reasonable timeframe."
+ 3600000)
+
+(defn- cache-expired?
+ "Check if a cache entry has expired based on its fetched-at timestamp."
+ [cache-entry]
+ (or (nil? cache-entry)
+ (nil? (:fetched-at cache-entry))
+ (> (- (t/to-millis-from-epoch (t/instant)) (:fetched-at cache-entry))
+ jwks-cache-ttl-ms)))
+
+(defn clear-jwks-cache!
+ "Clear all cached JWKS. Useful for testing."
+ []
+ (reset! jwks-cache {}))
+
+(defn invalidate-jwks-cache!
+ "Invalidate cached JWKS for a specific URI. Useful when signature verification fails
+ and keys may have been rotated by the IdP."
+ [jwks-uri]
+ (swap! jwks-cache dissoc jwks-uri)
+ nil)
+
+(defn- fetch-jwks
+ "Fetch JWKS from the given URI. Returns the parsed JWKS map or nil on error."
+ [jwks-uri]
+ (when-not (u.http/valid-host? :external-only jwks-uri)
+ (throw (ex-info "Invalid JWKS URI: internal addresses not allowed"
+ {:url jwks-uri})))
+ (try
+ (log/infof "Fetching JWKS from %s" jwks-uri)
+ (-> (http/get jwks-uri {:as :json
+ :accept :json
+ :throw-exceptions false
+ :conn-timeout 5000
+ :socket-timeout 5000})
+ :body)
+ (catch Exception e
+ (log/warnf e "Failed to fetch JWKS from %s" jwks-uri)
+ nil)))
+
+(defn get-jwks
+ "Get JWKS from URI, with TTL-based caching. Returns JWKS map or nil.
+ Cached entries expire after [[jwks-cache-ttl-ms]] milliseconds."
+ [jwks-uri]
+ (when jwks-uri
+ (let [cached (get @jwks-cache jwks-uri)]
+ (if (and cached (not (cache-expired? cached)))
+ (do
+ (log/debugf "Using cached JWKS for URI %s" jwks-uri)
+ (:jwks cached))
+ (do
+ (when cached
+ (log/infof "JWKS cache expired for URI %s, re-fetching" jwks-uri))
+ (when-let [jwks (fetch-jwks jwks-uri)]
+ (swap! jwks-cache assoc jwks-uri {:jwks jwks :fetched-at (t/to-millis-from-epoch (t/instant))})
+ jwks))))))
+
+(defn- find-signing-key
+ "Find the signing key from JWKS that matches the JWT kid (key ID).
+ Returns the public key or nil if not found."
+ [jwks kid]
+ (when-let [keys (:keys jwks)]
+ (some (fn [key-data]
+ (when (= (:kid key-data) kid)
+ key-data))
+ keys)))
+
+(def ^:private allowed-algorithms
+ "Allowlist of acceptable JWT signing algorithms.
+ Includes RSA and ECDSA families commonly used by OIDC providers."
+ #{:rs256 :rs384 :rs512 :es256 :es384 :es512})
+
+(defn- get-key-algorithm
+ "Extract and validate the signing algorithm from a JWK.
+ Returns the algorithm keyword if valid, or :rs256 as default if not specified.
+ Throws an exception if the algorithm is specified but not in the allowlist."
+ [key-data]
+ (if-let [alg (:alg key-data)]
+ (let [alg-kw (keyword (u/lower-case-en alg))]
+ (when-not (contains? allowed-algorithms alg-kw)
+ (throw (ex-info "Unsupported JWT signing algorithm"
+ {:algorithm alg :allowed allowed-algorithms})))
+ alg-kw)
+ ;; Default to RS256 for backwards compatibility with JWKs that don't specify alg
+ :rs256))
+
+(defn- verify-signature
+ "Verify JWT signature using JWKS.
+
+ Parameters:
+ - token: JWT string
+ - jwks-uri: URI to fetch JWKS from
+
+ Returns the verified claims map or nil if verification fails."
+ [token jwks-uri]
+ (try
+ (when-let [jwks (get-jwks jwks-uri)]
+ ;; Parse token header to get kid
+ (let [header-json (jwt/decode-header token)
+ kid (:kid header-json)]
+ (when-let [key-data (find-signing-key jwks kid)]
+ ;; Convert JWK to public key and verify using algorithm from JWK
+ (let [alg (get-key-algorithm key-data)
+ public-key (keys/jwk->public-key key-data)]
+ (jwt/unsign token public-key {:alg alg})))))
+ (catch Exception e
+ (log/warn e "JWT signature verification failed")
+ nil)))
+
+(defn- validate-expiry
+ "Validate that the token has not expired.
+
+ Parameters:
+ - claims: Token claims map
+
+ Returns true if token is not expired, false otherwise."
+ [claims]
+ (when-let [exp (:exp claims)]
+ (let [now (quot (t/to-millis-from-epoch (t/instant)) 1000)]
+ (> exp now))))
+
+(defn- validate-issuer
+ "Validate that the token issuer matches expected issuer.
+
+ Parameters:
+ - claims: Token claims map
+ - expected-issuer: Expected issuer URL
+
+ Returns true if issuer matches, false otherwise."
+ [claims expected-issuer]
+ (= (:iss claims) expected-issuer))
+
+(defn- validate-audience
+ "Validate that the token audience includes the expected client ID.
+
+ Parameters:
+ - claims: Token claims map
+ - expected-audience: Expected client ID
+
+ Returns true if audience matches, false otherwise."
+ [claims expected-audience]
+ (let [aud (:aud claims)]
+ (cond
+ (string? aud) (= aud expected-audience)
+ (sequential? aud) (some #(= % expected-audience) aud)
+ :else false)))
+
+(defn- validate-nonce
+ "Validate that the token nonce matches the expected nonce.
+
+ Parameters:
+ - claims: Token claims map
+ - expected-nonce: Expected nonce value
+
+ Returns true if nonce matches, false otherwise."
+ [claims expected-nonce]
+ (= (:nonce claims) expected-nonce))
+
+(defn validate-id-token
+ "Validate an OIDC ID token.
+
+ Parameters:
+ - token: JWT string
+ - config: Map with :jwks-uri, :issuer-uri, :client-id
+ - nonce: Expected nonce value (optional)
+
+ Returns a map with:
+ - :valid? - boolean indicating if token is valid
+ - :claims - the token claims if valid
+ - :error - error message if invalid"
+ [token {:keys [jwks-uri issuer-uri client-id]} nonce]
+ (try
+ ;; First verify signature
+ (if-let [claims (verify-signature token jwks-uri)]
+ (cond
+ ;; Validate expiry
+ (not (validate-expiry claims))
+ {:valid? false :error "Token has expired"}
+
+ ;; Validate issuer
+ (not (validate-issuer claims issuer-uri))
+ {:valid? false :error (str "Invalid issuer. Expected: " issuer-uri ", Got: " (:iss claims))}
+
+ ;; Validate audience
+ (not (validate-audience claims client-id))
+ {:valid? false :error (str "Invalid audience. Expected: " client-id ", Got: " (:aud claims))}
+
+ ;; Validate nonce if provided
+ (and nonce (not (validate-nonce claims nonce)))
+ {:valid? false :error "Invalid nonce"}
+
+ ;; All validations passed
+ :else
+ {:valid? true :claims claims})
+ {:valid? false :error "JWT signature verification failed"})
+ (catch Exception e
+ {:valid? false :error (str "Token validation error: " (.getMessage e))})))
diff --git a/src/metabase/sso/providers/oidc.clj b/src/metabase/sso/providers/oidc.clj
new file mode 100644
index 00000000000..fcdec1013d6
--- /dev/null
+++ b/src/metabase/sso/providers/oidc.clj
@@ -0,0 +1,208 @@
+(ns metabase.sso.providers.oidc
+ "Base OIDC authentication provider. Provides generic OIDC support that concrete
+ implementations (Auth0, Okta, etc.) can derive from."
+ (:require
+ [clj-http.client :as http]
+ [metabase.auth-identity.core :as auth-identity]
+ [metabase.sso.oidc.common :as oidc.common]
+ [metabase.sso.oidc.discovery :as oidc.discovery]
+ [metabase.sso.oidc.schema :as oidc.schema]
+ [metabase.sso.oidc.state :as oidc.state]
+ [metabase.sso.oidc.tokens :as oidc.tokens]
+ [metabase.util.log :as log]
+ [methodical.core :as methodical]))
+
+;;; -------------------------------------------------- Provider Registration --------------------------------------------------
+
+;; Register the OIDC provider in the hierarchy
+(derive :provider/oidc :metabase.auth-identity.provider/provider)
+(derive :provider/oidc :metabase.auth-identity.provider/create-user-if-not-exists)
+
+;;; -------------------------------------------------- Configuration Handling --------------------------------------------------
+
+(defn- enrich-config-with-discovery
+ "Enrich configuration with OIDC discovery endpoints if needed.
+
+ If the configuration doesn't have manual endpoints, attempts discovery
+ using the issuer URI.
+
+ Returns updated configuration map with :discovery-document."
+ [config]
+ (if (oidc.schema/discovery-based? config)
+ ;; Use discovery
+ (if-let [discovery-doc (oidc.discovery/discover-oidc-configuration (:issuer-uri config))]
+ (assoc config :discovery-document discovery-doc)
+ (do
+ (log/warnf "OIDC discovery failed for issuer %s, falling back to manual configuration" (:issuer-uri config))
+ config))
+ config))
+
+;;; -------------------------------------------------- Token Exchange --------------------------------------------------
+
+(defn- exchange-code-for-tokens
+ "Exchange authorization code for tokens at the token endpoint.
+
+ Parameters:
+ - code: Authorization code
+ - config: Enriched OIDC configuration with discovery document (if applicable),
+ token endpoint, client credentials, redirect URI
+
+ Returns token response map with :id-token, :access-token, etc."
+ [code config]
+ (let [token-endpoint (oidc.discovery/get-token-endpoint config)]
+ (try
+ (let [response (http/post token-endpoint
+ {:form-params {:grant_type "authorization_code"
+ :code code
+ :redirect_uri (:redirect-uri config)
+ :client_id (:client-id config)
+ :client_secret (:client-secret config)}
+ :as :json
+ :throw-exceptions false
+ :conn-timeout 5000
+ :socket-timeout 5000})]
+ (if (= 200 (:status response))
+ (oidc.common/parse-token-response (:body response))
+ (do
+ (log/errorf "Token exchange failed: %s" (:body response))
+ nil)))
+ (catch Exception e
+ (log/error e "Token exchange failed")
+ nil))))
+
+;;; -------------------------------------------------- User Data Extraction --------------------------------------------------
+
+(defn- extract-user-data
+ "Extract user data from ID token claims.
+
+ Parameters:
+ - claims: ID token claims map
+ - config: OIDC configuration (for custom attribute mappings)
+
+ Returns user data map with :email, :first_name, :last_name, :provider-id"
+ [claims config]
+ (let [;; Get attribute mappings from config, or use defaults
+ email-attr (get config :attribute-email "email")
+ firstname-attr (get config :attribute-firstname "given_name")
+ lastname-attr (get config :attribute-lastname "family_name")
+
+ ;; Extract values
+ email (get claims (keyword email-attr))
+ first-name (get claims (keyword firstname-attr))
+ last-name (get claims (keyword lastname-attr))
+ provider-id (:sub claims)]
+
+ (when email
+ {:email email
+ :first_name first-name
+ :last_name last-name
+ :provider-id provider-id
+ :sso_source :oidc})))
+
+;;; -------------------------------------------------- Authentication Implementation --------------------------------------------------
+
+(methodical/defmethod auth-identity/authenticate :provider/oidc
+ [_provider request]
+ (let [config (oidc.common/extract-oidc-config request)]
+ (cond
+ ;; Configuration missing
+ (not config)
+ {:success? false
+ :error :configuration-error
+ :message "OIDC configuration not found in request"}
+
+ ;; Callback handling (has authorization code or state or error)
+ (some #(contains? request %) [:code :error :state])
+ (let [;; Validate callback parameters
+ validation (oidc.common/validate-callback-params request)]
+ (if-not (:valid? validation)
+ {:success? false
+ :error :invalid-callback
+ :message (get-in validation [:error :description] "Invalid callback parameters")}
+
+ ;; Enrich config with discovery once for the entire callback flow
+ (let [enriched-config (enrich-config-with-discovery config)
+ code (:code validation)
+ tokens (exchange-code-for-tokens code enriched-config)]
+ (if-not (:id-token tokens)
+ {:success? false
+ :error :token-exchange-failed
+ :message "Failed to exchange authorization code for tokens"}
+
+ ;; Validate ID token
+ (let [jwks-uri (oidc.discovery/get-jwks-uri enriched-config)
+ validation-config {:jwks-uri jwks-uri
+ :issuer-uri (:issuer-uri config)
+ :client-id (:client-id config)}
+ nonce (:nonce request)
+ validation-result (oidc.tokens/validate-id-token (:id-token tokens)
+ validation-config
+ nonce)]
+ (if-not (:valid? validation-result)
+ {:success? false
+ :error :invalid-token
+ :message (:error validation-result)}
+
+ ;; Extract user data from claims
+ (let [claims (:claims validation-result)
+ user-data (extract-user-data claims config)]
+ (if-not user-data
+ {:success? false
+ :error :user-data-extraction-failed
+ :message "Failed to extract user email from token"}
+ {:success? true
+ :claims claims
+ :user-data user-data
+ :provider-id (:provider-id user-data)}))))))))
+
+ ;; Initiate authorization flow
+ :else
+ (let [enriched-config (enrich-config-with-discovery config)
+ authorization-endpoint (oidc.discovery/get-authorization-endpoint enriched-config)]
+ (if-not authorization-endpoint
+ {:success? false
+ :error :configuration-error
+ :message "Authorization endpoint not found. Check OIDC configuration or discovery."}
+
+ ;; Generate authorization URL
+ (let [state (oidc.common/generate-state)
+ nonce (oidc.common/generate-nonce)
+ scopes (get config :scopes ["openid" "email" "profile"])
+ auth-url (oidc.common/generate-authorization-url
+ authorization-endpoint
+ (:client-id config)
+ (:redirect-uri config)
+ scopes
+ state
+ nonce)]
+ {:success? :redirect
+ :redirect-url auth-url
+ :message "Redirecting to OIDC provider for authentication"
+ ;; Store state and nonce for validation on callback
+ :state state
+ :nonce nonce}))))))
+
+;;; -------------------------------------------------- Login Implementation --------------------------------------------------
+
+(methodical/defmethod auth-identity/login! :around :provider/oidc
+ [provider {:keys [code state] :as request}]
+ ;; Only validate state for OIDC callbacks (when we have code and state parameters)
+ (if (and code state)
+ (let [;; Get provider-specific keyword from request or derive from provider
+ provider-keyword (or (:oidc-provider request) provider)
+ validation (oidc.state/validate-oidc-callback request
+ state
+ provider-keyword
+ {:validate-browser-id (:browser-id request)})]
+ (if-not (:valid? validation)
+ {:success? false
+ :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 redirect from state cookie if not already set in request
+ (and (:redirect validation)
+ (not (:redirect-url request)))
+ (assoc :redirect-url (:redirect validation))))))
+ ;; Not a callback - pass through to next method
+ (next-method provider request)))
diff --git a/src/metabase/util.cljc b/src/metabase/util.cljc
index c57e8f04b2b..2200960d4d7 100644
--- a/src/metabase/util.cljc
+++ b/src/metabase/util.cljc
@@ -226,6 +226,36 @@
[s n]
(subs s 0 (min (count s) n)))
+#?(:clj
+ (defn https?
+ "True if the original request made by the frontend client (i.e., browser) was made over HTTPS.
+
+ In many production instances, a reverse proxy such as an ELB or nginx will handle SSL termination, and the actual
+ request handled by Jetty will be over HTTP."
+ [{{:strs [x-forwarded-proto x-forwarded-protocol x-url-scheme x-forwarded-ssl front-end-https origin]} :headers
+ :keys [scheme]}]
+ (cond
+ ;; If `X-Forwarded-Proto` is present use that. There are several alternate headers that mean the same thing. See
+ ;; https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
+ (or x-forwarded-proto x-forwarded-protocol x-url-scheme)
+ (= "https" (lower-case-en (or x-forwarded-proto x-forwarded-protocol x-url-scheme)))
+
+ ;; If none of those headers are present, look for presence of `X-Forwarded-Ssl` or `Frontend-End-Https`, which
+ ;; will be set to `on` if the original request was over HTTPS.
+ (or x-forwarded-ssl front-end-https)
+ (= "on" (lower-case-en (or x-forwarded-ssl front-end-https)))
+
+ ;; If none of the above are present, we are most not likely being accessed over a reverse proxy. Still, there's a
+ ;; good chance `Origin` will be present because it should be sent with `POST` requests, and most auth requests are
+ ;; `POST`. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
+ origin
+ (str/starts-with? (lower-case-en origin) "https")
+
+ ;; Last but not least, if none of the above are set (meaning there are no proxy servers such as ELBs or nginx in
+ ;; front of us), we can look directly at the scheme of the request sent to Jetty.
+ scheme
+ (= scheme :https))))
+
(defn regex->str
"Returns the contents of a regex as a string.
diff --git a/test/metabase/sso/oidc/common_test.clj b/test/metabase/sso/oidc/common_test.clj
new file mode 100644
index 00000000000..58eda481401
--- /dev/null
+++ b/test/metabase/sso/oidc/common_test.clj
@@ -0,0 +1,209 @@
+(ns metabase.sso.oidc.common-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase.sso.oidc.common :as oidc.common]))
+
+(deftest ^:parallel generate-state-test
+ (testing "Generates non-empty state token"
+ (let [state (oidc.common/generate-state)]
+ (is (string? state))
+ (is (pos? (count state)))))
+
+ (testing "Generates unique state tokens"
+ (let [state1 (oidc.common/generate-state)
+ state2 (oidc.common/generate-state)]
+ (is (not= state1 state2))))
+
+ (testing "State token is URL-safe (no special characters)"
+ (let [state (oidc.common/generate-state)]
+ (is (re-matches #"[A-Za-z0-9\-_]+" state)))))
+
+(deftest ^:parallel generate-nonce-test
+ (testing "Generates non-empty nonce"
+ (let [nonce (oidc.common/generate-nonce)]
+ (is (string? nonce))
+ (is (pos? (count nonce)))))
+
+ (testing "Generates unique nonces"
+ (let [nonce1 (oidc.common/generate-nonce)
+ nonce2 (oidc.common/generate-nonce)]
+ (is (not= nonce1 nonce2))))
+
+ (testing "Nonce is URL-safe (no special characters)"
+ (let [nonce (oidc.common/generate-nonce)]
+ (is (re-matches #"[A-Za-z0-9\-_]+" nonce)))))
+
+(deftest ^:parallel build-query-string-test
+ (testing "Builds query string from simple params"
+ (let [params {:foo "bar" :baz "qux"}
+ query-string (oidc.common/build-query-string params)]
+ (is (or (= query-string "foo=bar&baz=qux")
+ (= query-string "baz=qux&foo=bar")))))
+
+ (testing "URL-encodes parameter values"
+ (let [params {:redirect_uri "https://example.com/callback?foo=bar"}
+ query-string (oidc.common/build-query-string params)]
+ (is (= "redirect_uri=https%3A%2F%2Fexample.com%2Fcallback%3Ffoo%3Dbar" query-string))))
+
+ (testing "URL-encodes parameter names"
+ (let [params {:some-param "value"}
+ query-string (oidc.common/build-query-string params)]
+ (is (= "some-param=value" query-string))))
+
+ (testing "Handles spaces in values"
+ (let [params {:scope "openid profile email"}
+ query-string (oidc.common/build-query-string params)]
+ (is (= "scope=openid%20profile%20email" query-string))))
+
+ (testing "Handles empty params"
+ (let [query-string (oidc.common/build-query-string {})]
+ (is (= "" query-string)))))
+
+(deftest ^:parallel generate-authorization-url-test
+ (testing "Generates authorization URL with all parameters"
+ (let [url (oidc.common/generate-authorization-url
+ "https://provider.com/authorize"
+ "test-client-id"
+ "https://metabase.com/callback"
+ ["openid" "email" "profile"]
+ "test-state"
+ "test-nonce")]
+ (is (string? url))
+ (is (str/starts-with? url "https://provider.com/authorize?"))
+ (is (str/includes? url "response_type=code"))
+ (is (str/includes? url "client_id=test-client-id"))
+ (is (str/includes? url "redirect_uri=https%3A%2F%2Fmetabase.com%2Fcallback"))
+ (is (str/includes? url "scope=openid%20email%20profile"))
+ (is (str/includes? url "state=test-state"))
+ (is (str/includes? url "nonce=test-nonce"))))
+
+ (testing "Properly encodes redirect URI"
+ (let [url (oidc.common/generate-authorization-url
+ "https://provider.com/authorize"
+ "client-id"
+ "https://metabase.com/auth/oidc/callback?foo=bar"
+ ["openid"]
+ "state"
+ "nonce")]
+ (is (str/includes? url "redirect_uri=https%3A%2F%2Fmetabase.com%2Fauth%2Foidc%2Fcallback%3Ffoo%3Dbar"))))
+
+ (testing "Joins multiple scopes with spaces"
+ (let [url (oidc.common/generate-authorization-url
+ "https://provider.com/authorize"
+ "client-id"
+ "https://metabase.com/callback"
+ ["openid" "email" "profile" "groups"]
+ "state"
+ "nonce")]
+ (is (str/includes? url "scope=openid%20email%20profile%20groups")))))
+
+(deftest ^:parallel extract-oidc-config-test
+ (testing "Extracts config from :oidc-config key"
+ (let [config {:client-id "test"
+ :client-secret "secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.com/callback"}
+ request {:oidc-config config
+ :other-key "ignored"}
+ extracted (oidc.common/extract-oidc-config request)]
+ (is (= extracted config))))
+
+ (testing "Extracts config from :auth-identity :metadata"
+ (let [config {:client-id "test"
+ :client-secret "secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.com/callback"}
+ request {:auth-identity {:metadata config}
+ :other-key "ignored"}
+ extracted (oidc.common/extract-oidc-config request)]
+ (is (= extracted config))))
+
+ (testing "Extracts config from direct request keys"
+ (let [request {:client-id "test"
+ :client-secret "secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.com/callback"
+ :other-key "ignored"}
+ extracted (oidc.common/extract-oidc-config request)]
+ (is (= {:client-id "test"
+ :client-secret "secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.com/callback"}
+ extracted))))
+
+ (testing "Prefers :oidc-config over :auth-identity"
+ (let [oidc-config {:client-id "from-oidc-config"}
+ auth-identity-config {:client-id "from-auth-identity"}
+ request {:oidc-config oidc-config
+ :auth-identity {:metadata auth-identity-config}}
+ extracted (oidc.common/extract-oidc-config request)]
+ (is (= "from-oidc-config" (:client-id extracted)))))
+
+ (testing "Prefers :auth-identity over direct keys"
+ (let [auth-identity-config {:client-id "from-auth-identity"}
+ request {:auth-identity {:metadata auth-identity-config}
+ :client-id "from-direct-keys"}
+ extracted (oidc.common/extract-oidc-config request)]
+ (is (= "from-auth-identity" (:client-id extracted)))))
+
+ (testing "Returns nil when no config found"
+ (let [request {:other-key "value"}
+ extracted (oidc.common/extract-oidc-config request)]
+ (is (nil? extracted)))))
+
+(deftest ^:parallel parse-token-response-test
+ (testing "Parses token response with all fields"
+ (let [response-body {:id_token "eyJhbGciOiJSUzI1NiJ9..."
+ :access_token "access-token-123"
+ :refresh_token "refresh-token-456"
+ :expires_in 3600}
+ parsed (oidc.common/parse-token-response response-body)]
+ (is (= "eyJhbGciOiJSUzI1NiJ9..." (:id-token parsed)))
+ (is (= "access-token-123" (:access-token parsed)))
+ (is (= "refresh-token-456" (:refresh-token parsed)))
+ (is (= 3600 (:expires-in parsed)))))
+
+ (testing "Parses token response with missing optional fields"
+ (let [response-body {:id_token "eyJhbGciOiJSUzI1NiJ9..."
+ :access_token "access-token-123"}
+ parsed (oidc.common/parse-token-response response-body)]
+ (is (= "eyJhbGciOiJSUzI1NiJ9..." (:id-token parsed)))
+ (is (= "access-token-123" (:access-token parsed)))
+ (is (nil? (:refresh-token parsed)))
+ (is (nil? (:expires-in parsed))))))
+
+(deftest ^:parallel validate-callback-params-test
+ (testing "Valid callback with code and state"
+ (let [params {:code "auth-code-123"
+ :state "state-token-456"}
+ result (oidc.common/validate-callback-params params)]
+ (is (true? (:valid? result)))
+ (is (= "auth-code-123" (:code result)))
+ (is (= "state-token-456" (:state result)))
+ (is (nil? (:error result)))))
+
+ (testing "Error response from provider"
+ (let [params {:error "access_denied"
+ :error_description "User denied access"}
+ result (oidc.common/validate-callback-params params)]
+ (is (false? (:valid? result)))
+ (is (= "access_denied" (get-in result [:error :code])))
+ (is (= "User denied access" (get-in result [:error :description])))))
+
+ (testing "Missing authorization code"
+ (let [params {:state "state-token"}
+ result (oidc.common/validate-callback-params params)]
+ (is (false? (:valid? result)))
+ (is (= :missing_code (get-in result [:error :code])))))
+
+ (testing "Missing state parameter"
+ (let [params {:code "auth-code"}
+ result (oidc.common/validate-callback-params params)]
+ (is (false? (:valid? result)))
+ (is (= :missing_state (get-in result [:error :code])))))
+
+ (testing "Empty params map"
+ (let [params {}
+ result (oidc.common/validate-callback-params params)]
+ (is (false? (:valid? result))))))
diff --git a/test/metabase/sso/oidc/discovery_test.clj b/test/metabase/sso/oidc/discovery_test.clj
new file mode 100644
index 00000000000..171c1087d29
--- /dev/null
+++ b/test/metabase/sso/oidc/discovery_test.clj
@@ -0,0 +1,236 @@
+(ns metabase.sso.oidc.discovery-test
+ (:require
+ [clj-http.client :as http]
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase.sso.oidc.discovery :as oidc.discovery]))
+
+(deftest ^:parallel get-authorization-endpoint-test
+ (testing "Gets authorization endpoint from discovery document"
+ (let [config {:discovery-document {:authorization_endpoint "https://provider.com/authorize"}}
+ endpoint (oidc.discovery/get-authorization-endpoint config)]
+ (is (= "https://provider.com/authorize" endpoint))))
+
+ (testing "Gets authorization endpoint from manual config"
+ (let [config {:authorization-endpoint "https://provider.com/manual/authorize"}
+ endpoint (oidc.discovery/get-authorization-endpoint config)]
+ (is (= "https://provider.com/manual/authorize" endpoint))))
+
+ (testing "Prefers discovery document over manual config"
+ (let [config {:discovery-document {:authorization_endpoint "https://provider.com/discovery/authorize"}
+ :authorization-endpoint "https://provider.com/manual/authorize"}
+ endpoint (oidc.discovery/get-authorization-endpoint config)]
+ (is (= "https://provider.com/discovery/authorize" endpoint))))
+
+ (testing "Returns nil when not found"
+ (let [config {}
+ endpoint (oidc.discovery/get-authorization-endpoint config)]
+ (is (nil? endpoint)))))
+
+(deftest ^:parallel get-token-endpoint-test
+ (testing "Gets token endpoint from discovery document"
+ (let [config {:discovery-document {:token_endpoint "https://provider.com/token"}}
+ endpoint (oidc.discovery/get-token-endpoint config)]
+ (is (= "https://provider.com/token" endpoint))))
+
+ (testing "Gets token endpoint from manual config"
+ (let [config {:token-endpoint "https://provider.com/manual/token"}
+ endpoint (oidc.discovery/get-token-endpoint config)]
+ (is (= "https://provider.com/manual/token" endpoint))))
+
+ (testing "Prefers discovery document over manual config"
+ (let [config {:discovery-document {:token_endpoint "https://provider.com/discovery/token"}
+ :token-endpoint "https://provider.com/manual/token"}
+ endpoint (oidc.discovery/get-token-endpoint config)]
+ (is (= "https://provider.com/discovery/token" endpoint))))
+
+ (testing "Returns nil when not found"
+ (let [config {}
+ endpoint (oidc.discovery/get-token-endpoint config)]
+ (is (nil? endpoint)))))
+
+(deftest ^:parallel get-jwks-uri-test
+ (testing "Gets JWKS URI from discovery document"
+ (let [config {:discovery-document {:jwks_uri "https://provider.com/jwks"}}
+ uri (oidc.discovery/get-jwks-uri config)]
+ (is (= "https://provider.com/jwks" uri))))
+
+ (testing "Gets JWKS URI from manual config"
+ (let [config {:jwks-uri "https://provider.com/manual/jwks"}
+ uri (oidc.discovery/get-jwks-uri config)]
+ (is (= "https://provider.com/manual/jwks" uri))))
+
+ (testing "Prefers discovery document over manual config"
+ (let [config {:discovery-document {:jwks_uri "https://provider.com/discovery/jwks"}
+ :jwks-uri "https://provider.com/manual/jwks"}
+ uri (oidc.discovery/get-jwks-uri config)]
+ (is (= "https://provider.com/discovery/jwks" uri))))
+
+ (testing "Returns nil when not found"
+ (let [config {}
+ uri (oidc.discovery/get-jwks-uri config)]
+ (is (nil? uri)))))
+
+(deftest discover-oidc-configuration-success-test
+ (testing "Successfully discovers OIDC configuration"
+ (oidc.discovery/clear-cache!)
+ (with-redefs [http/get (fn [url _opts]
+ (is (= "https://example.com/.well-known/openid-configuration" url))
+ {:status 200
+ :body {:issuer "https://example.com"
+ :authorization_endpoint "https://example.com/authorize"
+ :token_endpoint "https://example.com/token"
+ :jwks_uri "https://example.com/jwks"
+ :userinfo_endpoint "https://example.com/userinfo"}})]
+ (let [config (oidc.discovery/discover-oidc-configuration "https://example.com")]
+ (is (some? config))
+ (is (= "https://example.com" (:issuer config)))
+ (is (= "https://example.com/authorize" (:authorization_endpoint config)))
+ (is (= "https://example.com/token" (:token_endpoint config)))
+ (is (= "https://example.com/jwks" (:jwks_uri config)))))))
+
+(deftest discover-oidc-configuration-http-error-test
+ (testing "Handles HTTP errors gracefully"
+ (oidc.discovery/clear-cache!)
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 404
+ :body "Not Found"})]
+ (let [config (oidc.discovery/discover-oidc-configuration "https://example.org")]
+ (is (nil? config))))))
+
+(deftest discover-oidc-configuration-exception-test
+ (testing "Handles exceptions gracefully"
+ (oidc.discovery/clear-cache!)
+ (with-redefs [http/get (fn [_url _opts]
+ (throw (ex-info "Connection timeout" {})))]
+ (let [config (oidc.discovery/discover-oidc-configuration "https://example.net")]
+ (is (nil? config))))))
+
+(deftest discover-oidc-configuration-trailing-slash-test
+ (testing "Strips trailing slash from issuer URI"
+ (oidc.discovery/clear-cache!)
+ (with-redefs [http/get (fn [url _opts]
+ (is (= "https://example.edu/.well-known/openid-configuration" url))
+ {:status 200
+ :body {:issuer "https://example.edu"
+ :authorization_endpoint "https://example.edu/authorize"}})]
+ (let [config (oidc.discovery/discover-oidc-configuration "https://example.edu/")]
+ (is (some? config))))))
+
+;;; ================================================== Cache Expiration Tests ==================================================
+
+(def ^:private test-discovery-doc
+ {:issuer "https://google.com"
+ :authorization_endpoint "https://google.com/authorize"
+ :token_endpoint "https://google.com/token"
+ :jwks_uri "https://google.com/jwks"})
+
+(deftest discovery-cache-uses-cached-entry-when-fresh-test
+ (testing "Uses cached discovery document when cache is fresh (not expired)"
+ (oidc.discovery/clear-cache!)
+ (let [fetch-count (atom 0)]
+ (with-redefs [http/get (fn [_url _opts]
+ (swap! fetch-count inc)
+ {:status 200
+ :body test-discovery-doc})]
+ ;; First call should fetch
+ (let [result1 (oidc.discovery/discover-oidc-configuration "https://google.com")]
+ (is (some? result1))
+ (is (= 1 @fetch-count)))
+ ;; Second call should use cache (no additional fetch)
+ (let [result2 (oidc.discovery/discover-oidc-configuration "https://google.com")]
+ (is (some? result2))
+ (is (= 1 @fetch-count)))))))
+
+(deftest discovery-cache-refetches-when-expired-test
+ (testing "Re-fetches discovery document when cache entry is expired"
+ (oidc.discovery/clear-cache!)
+ (let [fetch-count (atom 0)]
+ (with-redefs [http/get (fn [_url _opts]
+ (swap! fetch-count inc)
+ {:status 200
+ :body test-discovery-doc})]
+ ;; First call should fetch
+ (oidc.discovery/discover-oidc-configuration "https://github.com")
+ (is (= 1 @fetch-count))
+
+ ;; Manually expire the cache entry by setting fetched-at to 25 hours ago (TTL is 24h)
+ (let [twenty-five-hours-ago (t/to-millis-from-epoch (t/minus (t/instant) (t/hours 25)))]
+ (swap! @#'oidc.discovery/discovery-cache
+ assoc "https://github.com"
+ {:document test-discovery-doc :fetched-at twenty-five-hours-ago}))
+
+ ;; Next call should re-fetch because cache is expired
+ (oidc.discovery/discover-oidc-configuration "https://github.com")
+ (is (= 2 @fetch-count))))))
+
+(deftest invalidate-discovery-cache-test
+ (testing "invalidate-cache! removes cache entry for specific issuer"
+ (oidc.discovery/clear-cache!)
+ (let [fetch-count (atom 0)]
+ (with-redefs [http/get (fn [_url _opts]
+ (swap! fetch-count inc)
+ {:status 200
+ :body test-discovery-doc})]
+ ;; Populate cache
+ (oidc.discovery/discover-oidc-configuration "https://microsoft.com")
+ (is (= 1 @fetch-count))
+
+ ;; Invalidate the cache entry
+ (oidc.discovery/invalidate-cache! "https://microsoft.com")
+
+ ;; Next call should re-fetch
+ (oidc.discovery/discover-oidc-configuration "https://microsoft.com")
+ (is (= 2 @fetch-count))))))
+
+(deftest invalidate-discovery-cache-with-trailing-slash-test
+ (testing "invalidate-cache! normalizes issuer URL"
+ (oidc.discovery/clear-cache!)
+ (let [fetch-count (atom 0)]
+ (with-redefs [http/get (fn [_url _opts]
+ (swap! fetch-count inc)
+ {:status 200
+ :body test-discovery-doc})]
+ ;; Populate cache without trailing slash
+ (oidc.discovery/discover-oidc-configuration "https://apple.com")
+ (is (= 1 @fetch-count))
+
+ ;; Invalidate with trailing slash (should still work)
+ (oidc.discovery/invalidate-cache! "https://apple.com/")
+
+ ;; Next call should re-fetch
+ (oidc.discovery/discover-oidc-configuration "https://apple.com")
+ (is (= 2 @fetch-count))))))
+
+;;; ================================================== SSRF Protection Tests ==================================================
+
+(deftest discover-oidc-configuration-ssrf-protection-test
+ (testing "Rejects internal addresses (localhost)"
+ (oidc.discovery/clear-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid issuer URL: internal addresses not allowed"
+ (oidc.discovery/discover-oidc-configuration "http://localhost/oidc"))))
+
+ (testing "Rejects internal addresses (127.0.0.1)"
+ (oidc.discovery/clear-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid issuer URL: internal addresses not allowed"
+ (oidc.discovery/discover-oidc-configuration "http://127.0.0.1/oidc"))))
+
+ (testing "Rejects cloud metadata endpoint"
+ (oidc.discovery/clear-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid issuer URL: internal addresses not allowed"
+ (oidc.discovery/discover-oidc-configuration "http://169.254.169.254/metadata"))))
+
+ (testing "Rejects private network addresses (192.168.x.x)"
+ (oidc.discovery/clear-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid issuer URL: internal addresses not allowed"
+ (oidc.discovery/discover-oidc-configuration "http://192.168.1.1/oidc"))))
+
+ (testing "Rejects private network addresses (10.x.x.x)"
+ (oidc.discovery/clear-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid issuer URL: internal addresses not allowed"
+ (oidc.discovery/discover-oidc-configuration "http://10.0.0.1/oidc")))))
diff --git a/test/metabase/sso/oidc/schema_test.clj b/test/metabase/sso/oidc/schema_test.clj
new file mode 100644
index 00000000000..839c9a1c6e3
--- /dev/null
+++ b/test/metabase/sso/oidc/schema_test.clj
@@ -0,0 +1,44 @@
+(ns metabase.sso.oidc.schema-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.sso.oidc.schema :as oidc.schema]))
+
+(deftest ^:parallel discovery-based?-test
+ (testing "Configuration is discovery-based when no manual endpoints"
+ (let [config {:client-id "test-client-id"
+ :client-secret "test-client-secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.example.com/auth/oidc/callback"}]
+ (is (true? (oidc.schema/discovery-based? config)))))
+
+ (testing "Configuration is NOT discovery-based when authorization-endpoint present"
+ (let [config {:client-id "test-client-id"
+ :client-secret "test-client-secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.example.com/auth/oidc/callback"
+ :authorization-endpoint "https://example.com/authorize"}]
+ (is (false? (oidc.schema/discovery-based? config)))))
+
+ (testing "Configuration is NOT discovery-based when token-endpoint present"
+ (let [config {:client-id "test-client-id"
+ :client-secret "test-client-secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.example.com/auth/oidc/callback"
+ :token-endpoint "https://example.com/token"}]
+ (is (false? (oidc.schema/discovery-based? config)))))
+
+ (testing "Configuration is NOT discovery-based when jwks-uri present"
+ (let [config {:client-id "test-client-id"
+ :client-secret "test-client-secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.example.com/auth/oidc/callback"
+ :jwks-uri "https://example.com/jwks"}]
+ (is (false? (oidc.schema/discovery-based? config)))))
+
+ (testing "Configuration is NOT discovery-based when userinfo-endpoint present"
+ (let [config {:client-id "test-client-id"
+ :client-secret "test-client-secret"
+ :issuer-uri "https://example.com"
+ :redirect-uri "https://metabase.example.com/auth/oidc/callback"
+ :userinfo-endpoint "https://example.com/userinfo"}]
+ (is (false? (oidc.schema/discovery-based? config))))))
diff --git a/test/metabase/sso/oidc/state_test.clj b/test/metabase/sso/oidc/state_test.clj
new file mode 100644
index 00000000000..28a22a3fa74
--- /dev/null
+++ b/test/metabase/sso/oidc/state_test.clj
@@ -0,0 +1,481 @@
+(ns metabase.sso.oidc.state-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.sso.oidc.state :as oidc.state]
+ [metabase.system.settings :as system.settings]
+ [metabase.util.encryption :as encryption])
+ (:import
+ (java.time Instant)))
+
+(set! *warn-on-reflection* true)
+
+;;; -------------------------------------------------- Test Helpers --------------------------------------------------
+
+(defn- now-ms
+ "Returns the current time in milliseconds using java.time.Instant."
+ []
+ (.toEpochMilli (Instant/now)))
+
+(def ^:private test-secret-key
+ "A test encryption key for unit tests."
+ "Orw0AAyzkO/kPTLJRxiyKoBHXa/d6ZcO+p+gpZO/wSQ=")
+
+(def ^:private test-secret
+ "Hashed test encryption key."
+ (encryption/secret-key->hash test-secret-key))
+
+(defmacro with-test-encryption!
+ "Run body with encryption enabled using a test secret key."
+ [& body]
+ `(with-redefs [encryption/default-secret-key test-secret]
+ ~@body))
+
+(defmacro without-encryption!
+ "Run body with encryption disabled."
+ [& body]
+ `(with-redefs [encryption/default-secret-key nil]
+ ~@body))
+
+(defmacro with-site-url!
+ "Run body with a specific site-url configured."
+ [site-url & body]
+ `(with-redefs [system.settings/site-url (constantly ~site-url)]
+ ~@body))
+
+;;; -------------------------------------------------- Redirect URL Validation Tests --------------------------------------------------
+
+(deftest ^:parallel valid-redirect-url-test
+ (testing "relative URLs"
+ (testing "accepts valid relative URLs"
+ (is (true? (oidc.state/valid-redirect-url? "/" "https://example.com")))
+ (is (true? (oidc.state/valid-redirect-url? "/dashboard" "https://example.com")))
+ (is (true? (oidc.state/valid-redirect-url? "/dashboard/123" "https://example.com")))
+ (is (true? (oidc.state/valid-redirect-url? "/path?query=value" "https://example.com")))
+ (is (true? (oidc.state/valid-redirect-url? "/path#fragment" "https://example.com"))))
+
+ (testing "rejects protocol-relative URLs (potential open redirect)"
+ (is (false? (oidc.state/valid-redirect-url? "//evil.com" "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "//evil.com/path" "https://example.com")))))
+
+ (testing "absolute URLs"
+ (testing "accepts same-origin URLs"
+ (is (true? (oidc.state/valid-redirect-url? "https://example.com/" "https://example.com")))
+ (is (true? (oidc.state/valid-redirect-url? "https://example.com/dashboard" "https://example.com")))
+ (is (true? (oidc.state/valid-redirect-url? "https://example.com:443/path" "https://example.com")))
+ (is (true? (oidc.state/valid-redirect-url? "http://example.com:80/path" "http://example.com"))))
+
+ (testing "accepts same-origin with explicit default ports"
+ (is (true? (oidc.state/valid-redirect-url? "https://example.com:443/" "https://example.com/")))
+ (is (true? (oidc.state/valid-redirect-url? "http://example.com:80/" "http://example.com/"))))
+
+ (testing "accepts same-origin with non-default ports"
+ (is (true? (oidc.state/valid-redirect-url? "https://example.com:8443/path" "https://example.com:8443")))
+ (is (true? (oidc.state/valid-redirect-url? "http://example.com:3000/" "http://example.com:3000/"))))
+
+ (testing "rejects different origins"
+ (is (false? (oidc.state/valid-redirect-url? "https://evil.com/" "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "https://evil.com/path" "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "https://subdomain.example.com/" "https://example.com"))))
+
+ (testing "rejects different schemes"
+ (is (false? (oidc.state/valid-redirect-url? "http://example.com/" "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "https://example.com/" "http://example.com"))))
+
+ (testing "rejects different ports"
+ (is (false? (oidc.state/valid-redirect-url? "https://example.com:8443/" "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "https://example.com/" "https://example.com:8443")))))
+
+ (testing "case insensitivity"
+ (is (true? (oidc.state/valid-redirect-url? "https://EXAMPLE.COM/path" "https://example.com")))
+ (is (true? (oidc.state/valid-redirect-url? "HTTPS://example.com/path" "https://example.com"))))
+
+ (testing "invalid inputs"
+ (is (false? (oidc.state/valid-redirect-url? nil "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "" "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? " " "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "not-a-url" "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "javascript:alert(1)" "https://example.com")))
+ (is (false? (oidc.state/valid-redirect-url? "data:text/html,<script>alert(1)</script>" "https://example.com")))))
+
+(deftest valid-redirect-url-uses-site-url-test
+ (testing "uses system site-url when not provided"
+ (with-site-url! "https://metabase.example.com"
+ (is (true? (oidc.state/valid-redirect-url? "/dashboard")))
+ (is (true? (oidc.state/valid-redirect-url? "https://metabase.example.com/dashboard")))
+ (is (false? (oidc.state/valid-redirect-url? "https://evil.com/"))))))
+
+;;; -------------------------------------------------- create-oidc-state Tests --------------------------------------------------
+
+(deftest create-oidc-state-test
+ (with-site-url! "https://metabase.example.com"
+ (testing "creates state with all required fields"
+ (let [state-map (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider :slack-connect})]
+ (is (= "csrf-token" (:state state-map)))
+ (is (= "nonce-value" (:nonce state-map)))
+ (is (= "/dashboard" (:redirect state-map)))
+ (is (= "slack-connect" (:provider state-map)))
+ (is (number? (:created-at state-map)))
+ (is (number? (:expires-at state-map)))
+ (is (> (:expires-at state-map) (:created-at state-map)))))
+
+ (testing "includes browser-id when provided"
+ (let [state-map (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider :slack-connect
+ :browser-id "device-uuid"})]
+ (is (= "device-uuid" (:browser-id state-map)))))
+
+ (testing "omits browser-id when not provided"
+ (let [state-map (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider :slack-connect})]
+ (is (not (contains? state-map :browser-id)))))
+
+ (testing "uses custom ttl-ms when provided"
+ (let [before (now-ms)
+ state-map (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider :slack-connect
+ :ttl-ms 300000}) ; 5 min
+ after (now-ms)]
+ ;; expires-at should be ~5 minutes from created-at
+ (is (>= (:expires-at state-map) (+ before 300000)))
+ (is (<= (:expires-at state-map) (+ after 300000)))))
+
+ (testing "converts provider keyword to string"
+ (let [state-map (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider :my-provider})]
+ (is (= "my-provider" (:provider state-map)))))
+
+ (testing "accepts same-origin absolute redirect URL"
+ (let [state-map (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "https://metabase.example.com/dashboard"
+ :provider :slack-connect})]
+ (is (= "https://metabase.example.com/dashboard" (:redirect state-map)))))
+
+ (testing "throws on missing required fields"
+ (is (thrown? AssertionError
+ (oidc.state/create-oidc-state {:nonce "nonce"
+ :redirect "/"
+ :provider :test})))
+ (is (thrown? AssertionError
+ (oidc.state/create-oidc-state {:state "state"
+ :redirect "/"
+ :provider :test})))
+ (is (thrown? AssertionError
+ (oidc.state/create-oidc-state {:state "state"
+ :nonce "nonce"
+ :provider :test})))
+ (is (thrown? AssertionError
+ (oidc.state/create-oidc-state {:state "state"
+ :nonce "nonce"
+ :redirect "/"}))))))
+
+(deftest create-oidc-state-rejects-invalid-redirects-test
+ (with-site-url! "https://metabase.example.com"
+ (testing "throws on external redirect URL (open redirect protection)"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid redirect URL"
+ (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "https://evil.com/steal-session"
+ :provider :slack-connect}))))
+
+ (testing "throws on protocol-relative URL"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid redirect URL"
+ (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "//evil.com/path"
+ :provider :slack-connect}))))
+
+ (testing "throws on different subdomain"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid redirect URL"
+ (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "https://other.example.com/path"
+ :provider :slack-connect}))))
+
+ (testing "throws on javascript: URL"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid redirect URL"
+ (oidc.state/create-oidc-state {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "javascript:alert(document.cookie)"
+ :provider :slack-connect}))))))
+
+;;; -------------------------------------------------- Encryption Tests --------------------------------------------------
+
+(deftest encrypt-decrypt-roundtrip-test
+ (with-test-encryption!
+ (testing "encrypts and decrypts successfully"
+ (let [original {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider "slack-connect"
+ :created-at 1704412800000
+ :expires-at (+ (now-ms) 600000)}
+ encrypted (oidc.state/encrypt-state original)
+ decrypted (oidc.state/decrypt-state encrypted)]
+ (is (string? encrypted))
+ (is (not= (pr-str original) encrypted))
+ (is (= original decrypted))))
+
+ (testing "encrypted output is URL-safe base64"
+ (let [state-map {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider "slack-connect"
+ :created-at 1704412800000
+ :expires-at (+ (now-ms) 600000)}
+ encrypted (oidc.state/encrypt-state state-map)]
+ ;; Base64 characters only (with possible padding)
+ (is (re-matches #"[A-Za-z0-9+/=]+" encrypted))))))
+
+(deftest encrypt-state-requires-encryption-test
+ (without-encryption!
+ (testing "throws exception when encryption not enabled"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"MB_ENCRYPTION_SECRET_KEY"
+ (oidc.state/encrypt-state {:state "csrf"
+ :nonce "nonce"
+ :redirect "/"
+ :provider "test"
+ :created-at 1704412800000
+ :expires-at 1704413400000}))))))
+
+(deftest decrypt-state-expired-test
+ (with-test-encryption!
+ (testing "returns nil for expired state"
+ (let [state-map {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider "slack-connect"
+ :created-at 1704412800000
+ :expires-at (- (now-ms) 1000)}
+ encrypted (oidc.state/encrypt-state state-map)]
+ (is (nil? (oidc.state/decrypt-state encrypted)))))))
+
+(deftest decrypt-state-tampered-test
+ (with-test-encryption!
+ (testing "returns nil for tampered ciphertext"
+ (let [state-map {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider "slack-connect"
+ :created-at 1704412800000
+ :expires-at (+ (now-ms) 600000)}
+ encrypted (oidc.state/encrypt-state state-map)
+ ;; Tamper with the middle of the encrypted string
+ tampered (str (subs encrypted 0 10) "XXXXX" (subs encrypted 15))]
+ (is (nil? (oidc.state/decrypt-state tampered)))))))
+
+(deftest decrypt-state-nil-input-test
+ (with-test-encryption!
+ (testing "returns nil for nil input"
+ (is (nil? (oidc.state/decrypt-state nil))))))
+
+(deftest decrypt-state-browser-id-validation-test
+ (with-test-encryption!
+ (testing "validates browser-id when requested"
+ (let [state-map {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider "slack-connect"
+ :created-at 1704412800000
+ :expires-at (+ (now-ms) 600000)
+ :browser-id "correct-device"}
+ encrypted (oidc.state/encrypt-state state-map)]
+ ;; Correct browser-id passes
+ (is (some? (oidc.state/decrypt-state encrypted {:validate-browser-id "correct-device"})))
+ ;; Wrong browser-id fails
+ (is (nil? (oidc.state/decrypt-state encrypted {:validate-browser-id "wrong-device"})))
+ ;; No validation passes
+ (is (some? (oidc.state/decrypt-state encrypted)))))))
+
+;;; -------------------------------------------------- Cookie Management Tests --------------------------------------------------
+
+(deftest set-and-get-oidc-state-cookie-test
+ (with-site-url! "https://metabase.example.com"
+ (with-test-encryption!
+ (testing "sets and retrieves state via cookies"
+ (let [request {:scheme :https}
+ state-data {:state "csrf-token"
+ :nonce "nonce-value"
+ :redirect "/dashboard"
+ :provider :slack-connect}
+ response (oidc.state/set-oidc-state-cookie {} request state-data)
+ cookie-val (get-in response [:cookies "metabase.OIDC_STATE" :value])
+ ;; Simulate the request coming back with the cookie
+ callback-request {:cookies {"metabase.OIDC_STATE" {:value cookie-val}}}
+ retrieved (oidc.state/get-oidc-state callback-request)]
+ (is (string? cookie-val))
+ (is (= "csrf-token" (:state retrieved)))
+ (is (= "nonce-value" (:nonce retrieved)))
+ (is (= "/dashboard" (:redirect retrieved)))
+ (is (= "slack-connect" (:provider retrieved))))))
+
+ (with-test-encryption!
+ (testing "sets correct cookie attributes for HTTPS"
+ (let [request {:scheme :https}
+ response (oidc.state/set-oidc-state-cookie {} request {:state "s"
+ :nonce "n"
+ :redirect "/"
+ :provider :test})
+ cookie (get-in response [:cookies "metabase.OIDC_STATE"])]
+ (is (true? (:http-only cookie)))
+ (is (true? (:secure cookie)))
+ (is (= :lax (:same-site cookie)))
+ (is (= "/" (:path cookie)))
+ (is (= 600 (:max-age cookie)))))) ; Default 10 minutes
+
+ (with-test-encryption!
+ (testing "sets correct cookie attributes for HTTP"
+ (let [request {:scheme :http}
+ response (oidc.state/set-oidc-state-cookie {} request {:state "s"
+ :nonce "n"
+ :redirect "/"
+ :provider :test})
+ cookie (get-in response [:cookies "metabase.OIDC_STATE"])]
+ (is (true? (:http-only cookie)))
+ (is (nil? (:secure cookie)))
+ (is (= :lax (:same-site cookie))))))))
+
+(deftest get-oidc-state-provider-validation-test
+ (with-site-url! "https://metabase.example.com"
+ (with-test-encryption!
+ (testing "validates expected provider"
+ (let [request {:scheme :https}
+ response (oidc.state/set-oidc-state-cookie {} request {:state "csrf"
+ :nonce "nonce"
+ :redirect "/"
+ :provider :slack-connect})
+ cookie-val (get-in response [:cookies "metabase.OIDC_STATE" :value])
+ callback {:cookies {"metabase.OIDC_STATE" {:value cookie-val}}}]
+ ;; Correct provider passes
+ (is (some? (oidc.state/get-oidc-state callback {:expected-provider :slack-connect})))
+ ;; Wrong provider fails
+ (is (nil? (oidc.state/get-oidc-state callback {:expected-provider :other-provider})))
+ ;; No provider validation passes
+ (is (some? (oidc.state/get-oidc-state callback))))))))
+
+(deftest clear-oidc-state-cookie-test
+ (testing "clears the cookie"
+ (let [response (oidc.state/clear-oidc-state-cookie {})
+ cookie (get-in response [:cookies "metabase.OIDC_STATE"])]
+ (is (= "" (:value cookie)))
+ (is (= 0 (:max-age cookie))))))
+
+;;; -------------------------------------------------- High-Level Integration Tests --------------------------------------------------
+
+(deftest wrap-oidc-redirect-test
+ (with-site-url! "https://metabase.example.com"
+ (with-test-encryption!
+ (testing "creates redirect response with state cookie"
+ (let [auth-result {:redirect-url "https://slack.com/oauth/authorize?..."
+ :state "generated-state"
+ :nonce "generated-nonce"}
+ request {:scheme :https}
+ response (oidc.state/wrap-oidc-redirect auth-result
+ request
+ :slack-connect
+ "/final-redirect")]
+ ;; Should be a redirect response
+ (is (= 302 (:status response)))
+ (is (= "https://slack.com/oauth/authorize?..." (get-in response [:headers "Location"])))
+ ;; Should have state cookie
+ (is (string? (get-in response [:cookies "metabase.OIDC_STATE" :value]))))))
+
+ (with-test-encryption!
+ (testing "rejects external redirect URL (open redirect protection)"
+ (let [auth-result {:redirect-url "https://slack.com/oauth/authorize?..."
+ :state "generated-state"
+ :nonce "generated-nonce"}
+ request {:scheme :https}]
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Invalid redirect URL"
+ (oidc.state/wrap-oidc-redirect auth-result
+ request
+ :slack-connect
+ "https://evil.com/steal-session"))))))))
+
+(deftest validate-oidc-callback-test
+ (with-site-url! "https://metabase.example.com"
+ (with-test-encryption!
+ (testing "validates matching state"
+ (let [request {:scheme :https}
+ response (oidc.state/set-oidc-state-cookie {} request {:state "correct-state"
+ :nonce "test-nonce"
+ :redirect "/dashboard"
+ :provider :slack-connect})
+ cookie-val (get-in response [:cookies "metabase.OIDC_STATE" :value])
+ callback {:cookies {"metabase.OIDC_STATE" {:value cookie-val}}}
+ result (oidc.state/validate-oidc-callback callback "correct-state" :slack-connect)]
+ (is (true? (:valid? result)))
+ (is (= "test-nonce" (:nonce result)))
+ (is (= "/dashboard" (:redirect result)))))
+
+ (testing "rejects mismatched state (CSRF protection)"
+ (let [request {:scheme :https}
+ response (oidc.state/set-oidc-state-cookie {} request {:state "correct-state"
+ :nonce "test-nonce"
+ :redirect "/dashboard"
+ :provider :slack-connect})
+ cookie-val (get-in response [:cookies "metabase.OIDC_STATE" :value])
+ callback {:cookies {"metabase.OIDC_STATE" {:value cookie-val}}}
+ result (oidc.state/validate-oidc-callback callback "wrong-state" :slack-connect)]
+ (is (false? (:valid? result)))
+ (is (= :state-mismatch (:error result)))))
+
+ (testing "rejects wrong provider"
+ (let [request {:scheme :https}
+ response (oidc.state/set-oidc-state-cookie {} request {:state "state"
+ :nonce "nonce"
+ :redirect "/"
+ :provider :slack-connect})
+ cookie-val (get-in response [:cookies "metabase.OIDC_STATE" :value])
+ callback {:cookies {"metabase.OIDC_STATE" {:value cookie-val}}}
+ result (oidc.state/validate-oidc-callback callback "state" :other-provider)]
+ (is (false? (:valid? result)))
+ (is (= :invalid-or-expired-state (:error result)))))
+
+ (testing "rejects missing cookie"
+ (let [result (oidc.state/validate-oidc-callback {:cookies {}} "state" :slack-connect)]
+ (is (false? (:valid? result)))
+ (is (= :invalid-or-expired-state (:error result))))))))
+
+(deftest validate-oidc-callback-browser-id-test
+ (with-site-url! "https://metabase.example.com"
+ (with-test-encryption!
+ (testing "validates browser-id when requested"
+ (let [request {:scheme :https}
+ response (oidc.state/set-oidc-state-cookie {} request
+ {:state "state"
+ :nonce "nonce"
+ :redirect "/"
+ :provider :test}
+ {:browser-id "device-123"})
+ cookie-val (get-in response [:cookies "metabase.OIDC_STATE" :value])
+ callback {:cookies {"metabase.OIDC_STATE" {:value cookie-val}}}]
+ ;; Correct browser-id passes
+ (is (:valid? (oidc.state/validate-oidc-callback callback "state" :test
+ {:validate-browser-id "device-123"})))
+ ;; Wrong browser-id fails
+ (is (not (:valid? (oidc.state/validate-oidc-callback callback "state" :test
+ {:validate-browser-id "wrong-device"})))))))))
diff --git a/test/metabase/sso/oidc/tokens_test.clj b/test/metabase/sso/oidc/tokens_test.clj
new file mode 100644
index 00000000000..9a3a96cea93
--- /dev/null
+++ b/test/metabase/sso/oidc/tokens_test.clj
@@ -0,0 +1,461 @@
+(ns metabase.sso.oidc.tokens-test
+ (:require
+ [buddy.core.keys :as buddy.keys]
+ [buddy.sign.jwt :as jwt]
+ [clj-http.client :as http]
+ [clojure.test :refer :all]
+ [java-time.api :as t]
+ [metabase.sso.oidc.tokens :as oidc.tokens])
+ (:import
+ (java.security KeyPairGenerator)
+ (java.security.spec ECGenParameterSpec)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private test-rsa-private-key-pem
+ "Test RSA private key PEM string for signing JWTs"
+ "-----BEGIN PRIVATE KEY-----
+MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCzaoNf/pO3shyj
+M5ynvNemVGb2S/KETJi7HCrlLBEkk4qs7gelUUfDXoX4bT2COXCejtcsEwat/4cq
+rMecbrnc7F6OEqG2hobVDVHvMoyd51fBjRP9shlu0lj0LvBAkn0EKJj09rc85e7d
+kE666tQboZb9f2MzQIZjnWvk1c2L+ruRXvCteX86l7JUychszrDjfRl/FO3cCrya
+2G+9HiWr7i3eS8FwC117Xcob8G5L9Dys0wlNvz0WLH81hYDvdklXDB5qhjC+i/he
+4Mk0OAEVJAuZLO1tKWpKMQnNZmDAvAvuZCxl6g7jkOg6ilChau50ssooceG4h7An
+wdqobhTnAgMBAAECggEAEVepikUNL0jyrAh9oIMdpJDCVmq3RE2JHTEBqR741ecY
+alMkfw4xGHPnEZaG8bMEAqI+WfQe2wEjph7cY+/EsdOmkidqj+jyAzRjPUf5aqal
+h2p6dQqFmyjkUKTG3rRU4ZWGWiC3oUB9NdfQnGW9ifbf0EduJdKbYD6juBNokm/z
+PqnLyz6lXt0fYhKiLrbZaKxtADQr0ueaJ9AHIGVjewnbi7hIPz4fwpXkP4hjos+n
+PKnR33TNrn7zyVTRui68wM+oM6gMtI0yP6rUhyMBPosS7llT/fWNZJbAUxA+ujrx
+ZJrif9FrForHbmQ3OVJbSLBfddx00EV9rMhOIXqp4QKBgQD799+US2yeCR6JoCgR
+4e114oUNtQrhJJECdlbsMsZRO0DbaH4C8mlP0x5E8JORyhRJuf8xcMPvyJP7mYPg
+ok1mZcG7JRgwWfxAeeRblchFyhTnwENuu/uO/367MZzhb+TLtdy4IJ/wNMhRWIt2
+WstooHco9lJEeUses4S5iDiKxwKBgQC2SXKLoQ3iols1+sdTaZz2ukhPRyO3cgZN
+garL7xThNo7zENQ+tWmt4VmjtAyM2SNw5EAJaPW7qxGfZPECCVgMnkhEAcp5rwzr
+0m8Z8sDxe6lKaONB+4Hs2gKPn+gAwvFHEZFl3obGSMNuZ1/ZWEsNQLfLbge3nqmp
+QIoylecE4QKBgHQCViBS8bl5fWPkJ07EdK5YEuaSumWajmFR1wd9AS4ZV+0tGQeG
+UNJ942veUDNJlTm0tzguMShPc0LeFYfxci15IE9n7tEkPS36cRdxyPnI5wMk1GdB
+ibr3C4RofVCWUgMwwmTMMJdJ1gkN+XgOqaSMbRChCJOaPOnvwWYiv9W1AoGAbHCX
+Ft9xjjA9iIguSb3bZZ994sOUSM4pV7RascUBq9S0B38sdD2hp5IWrF8w1B1ciw0N
+10s8XC8xZZw8D5UVbzQ+E07pb6gmTKe79jjGdSG2nRB2mUsQiKFMwrpC3ykZNckK
+sQpHLPAearBOgdKXm0Oz0u4a4y4dChXd4KfybaECgYBGG6YQL3JYqPnJFFoxlElJ
+6qZ8YxN8UqWG/meMxA25wDyFaWH4mpQzY8s1OP9Br0ZD9snNktKb6RfoJIr6IMOL
+FoQyvsf7lfwsO1MqmDEWuTjHfLyAFqhdJOQBdhpaKVaRQI45oyQIH5krTvfrBA2f
+C4LNFx/mlSrwtFu9TAtd2A==
+-----END PRIVATE KEY-----")
+
+(def ^:private test-rsa-public-key-pem
+ "Test RSA public key PEM string corresponding to test-rsa-private-key-pem"
+ "-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs2qDX/6Tt7IcozOcp7zX
+plRm9kvyhEyYuxwq5SwRJJOKrO4HpVFHw16F+G09gjlwno7XLBMGrf+HKqzHnG65
+3OxejhKhtoaG1Q1R7zKMnedXwY0T/bIZbtJY9C7wQJJ9BCiY9Pa3POXu3ZBOuurU
+G6GW/X9jM0CGY51r5NXNi/q7kV7wrXl/OpeyVMnIbM6w430ZfxTt3Aq8mthvvR4l
+q+4t3kvBcAtde13KG/BuS/Q8rNMJTb89Fix/NYWA73ZJVwweaoYwvov4XuDJNDgB
+FSQLmSztbSlqSjEJzWZgwLwL7mQsZeoO45DoOopQoWrudLLKKHHhuIewJ8HaqG4U
+5wIDAQAB
+-----END PUBLIC KEY-----")
+
+(def ^:private test-rsa-private-key
+ "Test RSA private key for signing JWTs"
+ (buddy.keys/str->private-key test-rsa-private-key-pem))
+
+(def ^:private test-rsa-public-key
+ "Test RSA public key for verifying JWTs"
+ (buddy.keys/str->public-key test-rsa-public-key-pem))
+
+(def ^:private test-jwks
+ "Test JWKS"
+ {:keys [(merge {:kid "test-key-id" :use "sig"} (buddy.keys/public-key->jwk test-rsa-public-key))]})
+
+(defn- generate-ec-keypair
+ "Generate an ECDSA keypair for the given curve (e.g., \"secp256r1\" for ES256)."
+ [curve-name]
+ (let [kpg (KeyPairGenerator/getInstance "EC")]
+ (.initialize kpg (ECGenParameterSpec. curve-name))
+ (.generateKeyPair kpg)))
+
+(def ^:private test-ec-keypair
+ "Test ECDSA keypair for ES256 algorithm"
+ (generate-ec-keypair "secp256r1"))
+
+(def ^:private test-ec-private-key
+ "Test EC private key for signing JWTs"
+ (.getPrivate test-ec-keypair))
+
+(def ^:private test-ec-public-key
+ "Test EC public key for verifying JWTs"
+ (.getPublic test-ec-keypair))
+
+(def ^:private test-ec-jwks
+ "Test JWKS with EC key"
+ {:keys [(merge {:kid "test-ec-key-id" :use "sig" :alg "ES256"}
+ (buddy.keys/public-key->jwk test-ec-public-key))]})
+
+(defn- create-test-id-token
+ "Create a test ID token with the given claims"
+ [claims]
+ (jwt/sign claims test-rsa-private-key {:alg :rs256 :header {:kid "test-key-id"}}))
+
+(deftest validate-id-token-valid-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Successfully validates a valid ID token"
+ (let [now (t/instant)
+ exp (t/plus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 60))
+ claims {:sub "user123"
+ :iss "https://provider.com"
+ :aud "test-client-id"
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "test-nonce"
+ :email "[email protected]"}
+ token (create-test-id-token claims)
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (true? (:valid? result)))
+ (is (some? (:claims result)))
+ (is (= "user123" (get-in result [:claims :sub])))
+ (is (= "[email protected]" (get-in result [:claims :email])))
+ (is (nil? (:error result))))))))
+
+(deftest validate-id-token-invalid-signature-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Rejects token with invalid signature"
+ (let [token "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIn0.invalid-signature"
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (false? (:valid? result)))
+ (is (some? (:error result))))))))
+
+(deftest validate-id-token-expired-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Rejects expired token"
+ (let [now (t/instant)
+ exp (t/minus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 7200))
+ claims {:sub "user123"
+ :iss "https://provider.com"
+ :aud "test-client-id"
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "test-nonce"}
+ token (create-test-id-token claims)
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (false? (:valid? result)))
+ (is (some? (:error result))))))))
+
+(deftest validate-id-token-wrong-issuer-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Rejects token with wrong issuer"
+ (let [now (t/instant)
+ exp (t/plus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 60))
+ claims {:sub "user123"
+ :iss "https://wrong-provider.com"
+ :aud "test-client-id"
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "test-nonce"}
+ token (create-test-id-token claims)
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (false? (:valid? result)))
+ (is (some? (:error result))))))))
+
+(deftest validate-id-token-wrong-audience-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Rejects token with wrong audience"
+ (let [now (t/instant)
+ exp (t/plus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 60))
+ claims {:sub "user123"
+ :iss "https://provider.com"
+ :aud "wrong-client-id"
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "test-nonce"}
+ token (create-test-id-token claims)
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (false? (:valid? result)))
+ (is (some? (:error result))))))))
+
+(deftest validate-id-token-wrong-nonce-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Rejects token with wrong nonce"
+ (let [now (t/instant)
+ exp (t/plus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 60))
+ claims {:sub "user123"
+ :iss "https://provider.com"
+ :aud "test-client-id"
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "wrong-nonce"}
+ token (create-test-id-token claims)
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (false? (:valid? result)))
+ (is (some? (:error result))))))))
+
+(deftest validate-id-token-audience-array-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Accepts token with audience as array"
+ (let [now (t/instant)
+ exp (t/plus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 60))
+ claims {:sub "user123"
+ :iss "https://provider.com"
+ :aud ["test-client-id" "other-client-id"]
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "test-nonce"}
+ token (create-test-id-token claims)
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (true? (:valid? result))))))))
+
+(deftest validate-id-token-jwks-fetch-failure-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Handles JWKS fetch failure"
+ (let [token "some-token"
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ (throw (ex-info "Network error" {})))]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (false? (:valid? result)))
+ (is (some? (:error result))))))))
+
+(deftest validate-id-token-malformed-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Handles malformed token"
+ (let [token "not-a-valid-jwt"
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (false? (:valid? result)))
+ (is (some? (:error result))))))))
+
+;;; ================================================== Cache Expiration Tests ==================================================
+
+(deftest jwks-cache-uses-cached-entry-when-fresh-test
+ (testing "Uses cached JWKS when cache is fresh (not expired)"
+ (oidc.tokens/clear-jwks-cache!)
+ (let [fetch-count (atom 0)]
+ (with-redefs [http/get (fn [_url _opts]
+ (swap! fetch-count inc)
+ {:status 200
+ :body test-jwks})]
+ ;; First call should fetch
+ (let [result1 (oidc.tokens/get-jwks "https://provider.com/jwks")]
+ (is (some? result1))
+ (is (= 1 @fetch-count)))
+ ;; Second call should use cache (no additional fetch)
+ (let [result2 (oidc.tokens/get-jwks "https://provider.com/jwks")]
+ (is (some? result2))
+ (is (= 1 @fetch-count)))))))
+
+(deftest jwks-cache-refetches-when-expired-test
+ (testing "Re-fetches JWKS when cache entry is expired"
+ (oidc.tokens/clear-jwks-cache!)
+ (let [fetch-count (atom 0)]
+ (with-redefs [http/get (fn [_url _opts]
+ (swap! fetch-count inc)
+ {:status 200
+ :body test-jwks})]
+ ;; First call should fetch
+ (oidc.tokens/get-jwks "https://github.com/jwks")
+ (is (= 1 @fetch-count))
+
+ ;; Manually expire the cache entry by setting fetched-at to 2 hours ago
+ (let [two-hours-ago (t/to-millis-from-epoch (t/minus (t/instant) (t/hours 2)))]
+ (swap! @#'oidc.tokens/jwks-cache
+ assoc "https://github.com/jwks"
+ {:jwks test-jwks :fetched-at two-hours-ago}))
+
+ ;; Next call should re-fetch because cache is expired
+ (oidc.tokens/get-jwks "https://github.com/jwks")
+ (is (= 2 @fetch-count))))))
+
+(deftest invalidate-jwks-cache-test
+ (testing "invalidate-jwks-cache! removes cache entry for specific URI"
+ (oidc.tokens/clear-jwks-cache!)
+ (let [fetch-count (atom 0)]
+ (with-redefs [http/get (fn [_url _opts]
+ (swap! fetch-count inc)
+ {:status 200
+ :body test-jwks})]
+ ;; Populate cache
+ (oidc.tokens/get-jwks "https://provider.com/jwks")
+ (is (= 1 @fetch-count))
+
+ ;; Invalidate the cache entry
+ (oidc.tokens/invalidate-jwks-cache! "https://provider.com/jwks")
+
+ ;; Next call should re-fetch
+ (oidc.tokens/get-jwks "https://provider.com/jwks")
+ (is (= 2 @fetch-count))))))
+
+;;; ================================================== SSRF Protection Tests ==================================================
+
+(deftest get-jwks-ssrf-protection-test
+ (testing "Rejects internal addresses (localhost)"
+ (oidc.tokens/clear-jwks-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid JWKS URI: internal addresses not allowed"
+ (oidc.tokens/get-jwks "http://localhost/jwks"))))
+
+ (testing "Rejects internal addresses (127.0.0.1)"
+ (oidc.tokens/clear-jwks-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid JWKS URI: internal addresses not allowed"
+ (oidc.tokens/get-jwks "http://127.0.0.1/jwks"))))
+
+ (testing "Rejects cloud metadata endpoint"
+ (oidc.tokens/clear-jwks-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid JWKS URI: internal addresses not allowed"
+ (oidc.tokens/get-jwks "http://169.254.169.254/jwks"))))
+
+ (testing "Rejects private network addresses (192.168.x.x)"
+ (oidc.tokens/clear-jwks-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid JWKS URI: internal addresses not allowed"
+ (oidc.tokens/get-jwks "http://192.168.1.1/jwks"))))
+
+ (testing "Rejects private network addresses (10.x.x.x)"
+ (oidc.tokens/clear-jwks-cache!)
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"Invalid JWKS URI: internal addresses not allowed"
+ (oidc.tokens/get-jwks "http://10.0.0.1/jwks")))))
+
+;;; ================================================== Algorithm Support Tests ==================================================
+
+(defn- create-test-ec-token
+ "Create a test ID token signed with ES256 algorithm"
+ [claims]
+ (jwt/sign claims test-ec-private-key {:alg :es256 :header {:kid "test-ec-key-id"}}))
+
+(deftest validate-id-token-es256-algorithm-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Successfully validates an ID token signed with ES256 algorithm"
+ (let [now (t/instant)
+ exp (t/plus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 60))
+ claims {:sub "user123"
+ :iss "https://provider.com"
+ :aud "test-client-id"
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "test-nonce"
+ :email "[email protected]"}
+ token (create-test-ec-token claims)
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body test-ec-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (true? (:valid? result)))
+ (is (some? (:claims result)))
+ (is (= "user123" (get-in result [:claims :sub])))
+ (is (= "[email protected]" (get-in result [:claims :email])))
+ (is (nil? (:error result))))))))
+
+(deftest validate-id-token-unsupported-algorithm-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Rejects tokens from JWKs with unsupported algorithm (HS256)"
+ (let [now (t/instant)
+ exp (t/plus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 60))
+ claims {:sub "user123"
+ :iss "https://provider.com"
+ :aud "test-client-id"
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "test-nonce"}
+ token (create-test-id-token claims)
+ ;; JWK with unsupported algorithm
+ unsupported-jwks {:keys [(merge {:kid "test-key-id" :use "sig" :alg "HS256"}
+ (buddy.keys/public-key->jwk test-rsa-public-key))]}
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body unsupported-jwks})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (false? (:valid? result)))
+ (is (= "JWT signature verification failed" (:error result))))))))
+
+(deftest validate-id-token-jwk-without-alg-defaults-to-rs256-test
+ (oidc.tokens/clear-jwks-cache!)
+ (testing "Successfully validates RS256 token when JWK has no alg field (backwards compatibility)"
+ (let [now (t/instant)
+ exp (t/plus now (t/seconds 3600))
+ iat (t/minus now (t/seconds 60))
+ claims {:sub "user123"
+ :iss "https://provider.com"
+ :aud "test-client-id"
+ :exp (quot (t/to-millis-from-epoch exp) 1000)
+ :iat (quot (t/to-millis-from-epoch iat) 1000)
+ :nonce "test-nonce"
+ :email "[email protected]"}
+ token (create-test-id-token claims)
+ ;; JWK without alg field (should default to RS256)
+ jwks-without-alg {:keys [(merge {:kid "test-key-id" :use "sig"}
+ (buddy.keys/public-key->jwk test-rsa-public-key))]}
+ config {:jwks-uri "https://provider.com/jwks"
+ :issuer-uri "https://provider.com"
+ :client-id "test-client-id"}]
+ (with-redefs [http/get (fn [_url _opts]
+ {:status 200
+ :body jwks-without-alg})]
+ (let [result (oidc.tokens/validate-id-token token config "test-nonce")]
+ (is (true? (:valid? result)))
+ (is (some? (:claims result)))
+ (is (= "user123" (get-in result [:claims :sub])))
+ (is (nil? (:error result))))))))
diff --git a/test/metabase/sso/providers/oidc_test.clj b/test/metabase/sso/providers/oidc_test.clj
new file mode 100644
index 00000000000..d8f2bfbd927
--- /dev/null
+++ b/test/metabase/sso/providers/oidc_test.clj
@@ -0,0 +1,285 @@
+(ns metabase.sso.providers.oidc-test
+ (:require
+ [clj-http.client :as http]
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase.auth-identity.provider :as provider]
+ [metabase.sso.oidc.discovery :as oidc.discovery]
+ [metabase.sso.oidc.tokens :as oidc.tokens]
+ [metabase.sso.providers.oidc]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private test-config
+ {:client-id "test-client-id"
+ :client-secret "test-client-secret"
+ :issuer-uri "https://provider.example.com"
+ :redirect-uri "https://metabase.example.com/auth/oidc/callback"
+ :scopes ["openid" "email" "profile"]})
+
+(def ^:private test-discovery-doc
+ {:authorization_endpoint "https://provider.example.com/authorize"
+ :token_endpoint "https://provider.example.com/token"
+ :jwks_uri "https://provider.example.com/jwks"
+ :userinfo_endpoint "https://provider.example.com/userinfo"})
+
+(deftest ^:parallel authenticate-missing-config-test
+ (testing "Returns error when configuration is missing"
+ (let [request {}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :configuration-error (:error result)))
+ (is (some? (:message result))))))
+
+(deftest authenticate-initiate-flow-test
+ (testing "Initiates authorization flow when no code present"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-discovery-doc)]
+ (let [request {:oidc-config test-config}
+ result (provider/authenticate :provider/oidc request)]
+ (is (= :redirect (:success? result)))
+ (is (some? (:redirect-url result)))
+ (is (some? (:state result)))
+ (is (some? (:nonce result)))
+ (is (str/includes? (:redirect-url result) "https://provider.example.com/authorize"))
+ (is (str/includes? (:redirect-url result) "client_id=test-client-id"))
+ (is (str/includes? (:redirect-url result) "response_type=code")))))
+
+ (testing "Uses manual endpoints when provided"
+ (let [config (assoc test-config
+ :authorization-endpoint "https://provider.example.com/manual/authorize")
+ request {:oidc-config config}
+ result (provider/authenticate :provider/oidc request)]
+ (is (= :redirect (:success? result)))
+ (is (str/includes? (:redirect-url result) "https://provider.example.com/manual/authorize"))))
+
+ (testing "Includes custom scopes in authorization URL"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-discovery-doc)]
+ (let [config (assoc test-config :scopes ["openid" "email" "profile" "groups"])
+ request {:oidc-config config}
+ result (provider/authenticate :provider/oidc request)]
+ (is (= :redirect (:success? result)))
+ (is (str/includes? (:redirect-url result) "scope=openid%20email%20profile%20groups")))))
+
+ (testing "Returns error when authorization endpoint not found"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] nil)]
+ (let [request {:oidc-config test-config}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :configuration-error (:error result)))))))
+
+(deftest ^:parallel authenticate-callback-validation-test
+ (testing "Returns error for invalid callback params"
+ (let [request {:oidc-config test-config
+ :error "access_denied"
+ :error_description "User denied access"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :invalid-callback (:error result)))))
+
+ (testing "Returns error when code is missing"
+ (let [request {:oidc-config test-config
+ :state "some-state"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :invalid-callback (:error result)))))
+
+ (testing "Returns error when state is missing"
+ (let [request {:oidc-config test-config
+ :code "some-code"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :invalid-callback (:error result))))))
+
+(deftest authenticate-token-exchange-test
+ (testing "Returns error when token exchange fails"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-discovery-doc)
+ http/post
+ (fn [_url _opts]
+ {:status 400
+ :body {:error "invalid_grant"}})]
+ (let [request {:oidc-config test-config
+ :code "auth-code-123"
+ :state "state-token-456"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :token-exchange-failed (:error result))))))
+
+ (testing "Returns error when token response missing id_token"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-discovery-doc)
+ http/post
+ (fn [_url _opts]
+ {:status 200
+ :body {:access_token "access-token-123"}})]
+ (let [request {:oidc-config test-config
+ :code "auth-code-123"
+ :state "state-token-456"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :token-exchange-failed (:error result)))))))
+
+(deftest authenticate-token-validation-test
+ (testing "Returns error when token validation fails"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-discovery-doc)
+ http/post
+ (fn [_url _opts]
+ {:status 200
+ :body {:id_token "invalid-token"
+ :access_token "access-token-123"}})
+ oidc.tokens/validate-id-token
+ (fn [_token _config _nonce]
+ {:valid? false
+ :error "Invalid signature"})]
+ (let [request {:oidc-config test-config
+ :code "auth-code-123"
+ :state "state-token-456"
+ :nonce "test-nonce"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :invalid-token (:error result)))))))
+
+(deftest authenticate-user-data-extraction-test
+ (testing "Returns error when email not in claims"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-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 "user123"
+ :iss "https://provider.example.com"
+ :aud "test-client-id"}})]
+ (let [request {:oidc-config test-config
+ :code "auth-code-123"
+ :state "state-token-456"
+ :nonce "test-nonce"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (false? (:success? result)))
+ (is (= :user-data-extraction-failed (:error result)))))))
+
+(deftest authenticate-success-test
+ (testing "Successfully authenticates user with valid token"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-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 "user123"
+ :iss "https://provider.example.com"
+ :aud "test-client-id"
+ :given_name "John"
+ :family_name "Doe"}})]
+ (let [request {:oidc-config test-config
+ :code "auth-code-123"
+ :state "state-token-456"
+ :nonce "test-nonce"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (true? (:success? result)))
+ (is (= "[email protected]" (get-in result [:user-data :email])))
+ (is (= "John" (get-in result [:user-data :first_name])))
+ (is (= "Doe" (get-in result [:user-data :last_name])))
+ (is (= "user123" (get-in result [:user-data :provider-id])))
+ (is (= :oidc (get-in result [:user-data :sso_source])))
+ (is (= "user123" (:provider-id result))))))
+
+ (testing "Successfully authenticates with minimal claims"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-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 "user456"
+ :iss "https://provider.example.com"
+ :aud "test-client-id"
+ :email "[email protected]"}})]
+ (let [request {:oidc-config test-config
+ :code "auth-code-123"
+ :state "state-token-456"
+ :nonce "test-nonce"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (true? (:success? result)))
+ (is (= "[email protected]" (get-in result [:user-data :email])))
+ (is (nil? (get-in result [:user-data :first_name])))
+ (is (nil? (get-in result [:user-data :last_name])))
+ (is (= "user456" (get-in result [:user-data :provider-id])))))))
+
+(deftest authenticate-custom-attribute-mapping-test
+ (testing "Uses custom attribute mappings when provided"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-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 "user789"
+ :iss "https://provider.example.com"
+ :aud "test-client-id"
+ :first "Jane"
+ :last "Smith"}})]
+ (let [config (assoc test-config
+ :attribute-email "mail"
+ :attribute-firstname "first"
+ :attribute-lastname "last")
+ request {:oidc-config config
+ :code "auth-code-123"
+ :state "state-token-456"
+ :nonce "test-nonce"}
+ result (provider/authenticate :provider/oidc request)]
+ (is (true? (:success? result)))
+ (is (= "[email protected]" (get-in result [:user-data :email])))
+ (is (= "Jane" (get-in result [:user-data :first_name])))
+ (is (= "Smith" (get-in result [:user-data :last_name])))))))
+
+(deftest authenticate-config-extraction-test
+ (testing "Extracts config from :oidc-config key"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-discovery-doc)]
+ (let [request {:oidc-config test-config}
+ result (provider/authenticate :provider/oidc request)]
+ (is (= :redirect (:success? result))))))
+
+ (testing "Extracts config from :auth-identity metadata"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-discovery-doc)]
+ (let [request {:auth-identity {:metadata test-config}}
+ result (provider/authenticate :provider/oidc request)]
+ (is (= :redirect (:success? result))))))
+
+ (testing "Extracts config from direct request keys"
+ (with-redefs [oidc.discovery/discover-oidc-configuration
+ (fn [_issuer] test-discovery-doc)]
+ (let [request (merge test-config {:other-key "ignored"})
+ result (provider/authenticate :provider/oidc request)]
+ (is (= :redirect (:success? result)))))))
+
+(deftest provider-hierarchy-test
+ (testing "OIDC provider derives from base provider"
+ (is (isa? :provider/oidc ::provider/provider)))
+
+ (testing "OIDC provider derives from create-user-if-not-exists"
+ (is (isa? :provider/oidc ::provider/create-user-if-not-exists))))
diff --git a/test/metabase/test/http_client.clj b/test/metabase/test/http_client.clj
index 601a8da9888..7f57c00aeb5 100644
--- a/test/metabase/test/http_client.clj
+++ b/test/metabase/test/http_client.clj
@@ -455,8 +455,7 @@
[& args]
(let [parsed (parse-http-client-args args)]
(log/trace parsed)
- (u/with-timeout response-timeout-ms
- (-mock-client parsed))))
+ (-mock-client parsed)))
(defn client-real-response
"Identical to `real-client` except returns the full HTTP response map, not just the body of the response."