Skip to content

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

8.8 KB
Raw Blame
(ns metabase-enterprise.sso.api.oidc
  "Admin-only CRUD endpoints for managing OIDC providers at `/api/ee/sso/oidc`."
  (:require
   [clojure.string :as str]
   [clojure.walk :as walk]
   [metabase-enterprise.sso.settings :as sso-settings]
   [metabase.api.common :as api]
   [metabase.api.macros :as api.macros]
   [metabase.premium-features.core :as premium-features]
   [metabase.settings.core :as setting]
   [metabase.sso.core :as sso]
   [metabase.util :as u]
   [metabase.util.i18n :refer [tru]]))

(set! *warn-on-reflection* true)

;;; -------------------------------------------------- Schema --------------------------------------------------

(def ^:private oidc-provider-create-schema
  [:map {:closed true}
   [:key :string]
   [:login-prompt :string]
   [:issuer-uri :string]
   [:client-id :string]
   [:client-secret :string]
   [:scopes {:optional true} [:sequential :string]]
   [:enabled {:optional true} :boolean]
   [:attribute-map {:optional true} [:map-of :string :string]]
   [:group-sync {:optional true} [:map {:closed true}
                                  [:enabled {:optional true} :boolean]
                                  [:group-attribute {:optional true} :string]
                                  [:group-mappings {:optional true} [:map-of :string [:sequential :int]]]]]])

(def ^:private oidc-provider-update-schema
  [:map {:closed true}
   [:login-prompt {:optional true} :string]
   [:issuer-uri {:optional true} :string]
   [:client-id {:optional true} :string]
   [:client-secret {:optional true} :string]
   [:scopes {:optional true} [:sequential :string]]
   [:enabled {:optional true} :boolean]
   [:attribute-map {:optional true} [:map-of :string :string]]
   [:group-sync {:optional true} [:map {:closed true}
                                  [:enabled {:optional true} :boolean]
                                  [:group-attribute {:optional true} :string]
                                  [:group-mappings {:optional true} [:map-of :string [:sequential :int]]]]]])

(def ^:private oidc-provider-response-schema
  [:map {:closed true}
   [:key :string]
   [:login-prompt :string]
   [:issuer-uri :string]
   [:client-id :string]
   [:client-secret :string]
   [:scopes {:optional true} [:sequential :string]]
   [:enabled {:optional true} :boolean]
   [:attribute-map {:optional true} [:map-of :string :string]]
   [:group-sync {:optional true} [:map {:closed true}
                                  [:enabled {:optional true} :boolean]
                                  [:group-attribute {:optional true} :string]
                                  [:group-mappings {:optional true} [:map-of :string [:sequential :int]]]]]])

;;; -------------------------------------------------- Helpers --------------------------------------------------

(defn- sanitize-response
  "Ensures the API response is safe to return to the client.
  Obfuscates the client-secret and ensures keys are strings."
  [provider]
  (cond-> provider
    (:client-secret provider)            (update :client-secret setting/obfuscate-value)
    (:attribute-map provider)            (update :attribute-map walk/stringify-keys)
    (get-in provider [:group-sync :group-mappings])
    (update-in [:group-sync :group-mappings] walk/stringify-keys)))

(defn- check-oidc-connection!
  "Run OIDC configuration check and throw a 400 if it fails. Returns the check result on success."
  [issuer-uri client-id client-secret scopes]
  (let [result (sso/check-oidc-configuration issuer-uri client-id client-secret scopes)]
    (api/check-400 (:ok result)
                   (or (get-in result [:credentials :error])
                       (get-in result [:discovery :error])
                       "OIDC configuration check failed"))
    result))

;;; -------------------------------------------------- Endpoints --------------------------------------------------

;; GET /api/ee/sso/oidc
(api.macros/defendpoint :get "/" :- [:sequential oidc-provider-response-schema]
  "List all OIDC providers (with client secrets masked)."
  []
  (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))
  (mapv sanitize-response (sso-settings/oidc-providers)))

;; GET /api/ee/sso/oidc/:key
(api.macros/defendpoint :get "/:key" :- oidc-provider-response-schema
  "Get a single OIDC provider by key (with client secret masked)."
  [{provider-key :key} :- [:map {:closed true} [:key :string]]]
  (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))
  (let [provider (sso-settings/get-oidc-provider provider-key)]
    (api/check-404 provider)
    (sanitize-response provider)))

;; POST /api/ee/sso/oidc
(api.macros/defendpoint :post "/" :- oidc-provider-response-schema
  "Create a new OIDC provider."
  [_route-params
   _query-params
   body :- oidc-provider-create-schema]
  (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))
  (let [provider-key (:key body)]
    (api/check-400 (u/valid-slug? provider-key) "Provider key must be a URL-safe slug (lowercase letters, numbers, hyphens, must start with letter or number)")
    (api/check-400 (nil? (sso-settings/get-oidc-provider provider-key)) (format "An OIDC provider with key '%s' already exists" provider-key))
    (let [providers    (sso-settings/oidc-providers)
          new-provider (merge {:enabled false
                               :scopes  ["openid" "email" "profile"]}
                              body)]
      (check-oidc-connection! (:issuer-uri new-provider) (:client-id new-provider) (:client-secret new-provider) (:scopes new-provider))
      (sso-settings/oidc-providers! (conj (vec providers) new-provider))
      (sanitize-response new-provider))))

;; PUT /api/ee/sso/oidc/:key
(api.macros/defendpoint :put "/:key" :- oidc-provider-response-schema
  "Update an existing OIDC provider."
  [{provider-key :key} :- [:map {:closed true} [:key :string]]
   _query-params
   body :- oidc-provider-update-schema]
  (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))
  (let [providers (sso-settings/oidc-providers)
        idx       (some (fn [[i p]] (when (= (:key p) provider-key) i))
                        (map-indexed vector providers))]
    (api/check-404 idx)
    (let [existing  (nth providers idx)
          ;; If client-secret is the mask or not provided, keep the existing one
          body      (if (or (not (:client-secret body))
                            (= (:client-secret body) (setting/obfuscate-value (:client-secret body))))
                      (dissoc body :client-secret)
                      body)
          updated   (merge existing body)]
      (check-oidc-connection! (:issuer-uri updated) (:client-id updated) (:client-secret updated) (:scopes updated))
      (let [providers (assoc (vec providers) idx updated)]
        (sso-settings/oidc-providers! providers)
        (sanitize-response updated)))))

;; POST /api/ee/sso/oidc/check
(def ^:private oidc-check-request-schema
  [:map {:closed true}
   [:issuer-uri :string]
   [:client-id :string]
   [:client-secret {:optional true} [:maybe :string]]
   [:key {:optional true} [:maybe :string]]
   [:scopes {:optional true} [:maybe [:sequential :string]]]])

(def ^:private oidc-check-step-schema
  [:map
   [:step :keyword]
   [:success :boolean]
   [:verified {:optional true} :boolean]
   [:error {:optional true} :string]
   [:token-endpoint {:optional true} :string]])

(def ^:private oidc-check-response-schema
  [:map
   [:ok :boolean]
   [:discovery oidc-check-step-schema]
   [:credentials {:optional true} oidc-check-step-schema]])

(api.macros/defendpoint :post "/check" :- oidc-check-response-schema
  "Check an OIDC provider configuration by probing its discovery document and testing client credentials."
  [_route-params
   _query-params
   body :- oidc-check-request-schema]
  (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))
  (let [issuer-uri    (:issuer-uri body)
        client-id     (:client-id body)
        stored        (some-> body :key sso-settings/get-oidc-provider)
        client-secret (let [s (:client-secret body)]
                        (if (str/blank? s)
                          (:client-secret stored)
                          s))
        scopes        (or (:scopes body) (:scopes stored) ["openid"])]
    (check-oidc-connection! issuer-uri client-id client-secret scopes)))

;; DELETE /api/ee/sso/oidc/:key
(api.macros/defendpoint :delete "/:key"  :- :nil
  "Delete an OIDC provider."
  [{provider-key :key} :- [:map {:closed true} [:key :string]]]
  (premium-features/assert-has-feature :sso-oidc (tru "OIDC authentication"))
  (let [providers (sso-settings/oidc-providers)
        filtered  (vec (remove #(= (:key %) provider-key) providers))]
    (when (= (count providers) (count filtered))
      (api/check-404 nil))
    (sso-settings/oidc-providers! filtered)
    nil))

(def ^{:arglists '([request respond raise])} routes
  "`/api/ee/sso/oidc` routes."
  (api.macros/ns-handler *ns* api/+check-superuser))