Skip to content

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

11.1 KB
Raw Blame
(ns metabase-enterprise.sso.api.sso-test
  (:require
   [buddy.sign.jwt :as jwt]
   [clojure.string :as str]
   [clojure.test :refer :all]
   [metabase.channel.email.messages :as messages]
   [metabase.request.core :as request]
   [metabase.server.instance :as server.instance]
   [metabase.session.core :as session]
   [metabase.test :as mt]
   [metabase.test.fixtures :as fixtures]
   [metabase.test.http-client :as client]
   [metabase.util :as u]
   [metabase.util.random :as u.random]
   [ring.util.codec :as codec]))

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

(use-fixtures :once (fixtures/initialize :test-users))

(deftest saml-logout
  (testing "with slo enabled and configured"
    (mt/with-premium-features #{:sso-saml}
      (mt/with-clock #t "2020-09-30T17:53:32Z"
        (mt/with-temporary-setting-values [saml-enabled                       true
                                           saml-identity-provider-uri         "http://idp.example.com/login"
                                           saml-identity-provider-certificate (slurp "test_resources/sso/auth0-public-idp.cert")
                                           saml-keystore-path                 "test_resources/keystore.jks"
                                           saml-keystore-password             "123456"
                                           saml-keystore-alias                "sp"
                                           site-url                           "http://localhost:3000"
                                           saml-slo-enabled                   true
                                           saml-identity-provider-slo-uri     "http://idp.example.com/logout"]
          (mt/with-dynamic-fn-redefs [random-uuid (constantly "66d96ab4-9834-40db-a3cd-42b361503ab9")]
            (binding [client/*url-prefix* ""]
              (let [session-key (session/generate-session-key)]
                (mt/with-temp [:model/User user {:email "[email protected]" :sso_source "saml"}
                               :model/Session _ {:user_id (:id user) :id (session/generate-session-id) :key_hashed (session/hash-session-key session-key)}]
                  (testing "logout is redirected to idp"
                    (let [req-options (assoc-in {} [:request-options :cookies request/metabase-session-cookie :value] session-key)
                          response    (client/client :post "/auth/sso/logout" req-options)]
                      (is (= (str
                              "http://idp.example.com/logout?SAMLRequest=nZFBa4Qw"
                              "EIXv%2FRWSezQa165B3RakIOz20G576KVEDduASawTy%2F78Rl"
                              "1h2UMPvQQC87733ky2O6vO%2BxEDSKNzFPoEeUI3ppX6lKO34x"
                              "Peol1xlwFXXdSzvTmZ0b6I71GA9Ur3SM3tLP2ytmdBINveF2eu"
                              "%2Bk74jVFBNyuQV5U5km2StGnC6xinWxrjmLQ15rRpcRzVNAk3"
                              "hPI6dbMAo6g0WK5tjiISEUxSTMkxvGcbymjkE0I%2BkPe%2Bxo"
                              "6m2K6IBrYEzdE4aGY4SGCaKwHMNuz18bBnbpT1g7GmMR0qll5s"
                              "NhyuCX8DOIAYptqoOAjLaw4iC65RK%2FjZSavyX%2BBp%2BtO6"
                              "DT%2Boi8W0z9VmAReX781hil8%3D&RelayState=aHR0cDovL2"
                              "xvY2FsaG9zdDozMDAwL2F1dGgvc3NvL2hhbmRsZV9zbG8%3D&S"
                              "igAlg=http%3A%2F%2Fwww.w3.org%2F2000%2F09%2Fxmldsi"
                              "g%23rsa-sha1&Signature=sZakr0C7r%2F%2FGnN7NmdmnnKj"
                              "kKR1pLB1aC%2Bj0dyQwtbr9C%2FE2VMeBCV%2FQDNoTGP7UMVI"
                              "g%2BIRZXaZ4h0mLwG7MQwyv9KCL9tH0GZ%2F3K3mqYhg3d8zDO"
                              "W6HSXlA%2FP2W1xFSMV7isYbynM%2BTPZ1vp88zQCpb0xVzDWt"
                              "%2FYw11yAqadb8%3D")
                             (:saml-logout-url response))))))))))))))

(deftest saml-logout-session-index
  (testing "the SessionIndex recorded at login is sent in the LogoutRequest"
    ;; Auth0 maps several sessions to one email and rejects a LogoutRequest that does not name
    ;; which session to end (#77837).
    (mt/with-premium-features #{:sso-saml}
      (mt/with-temporary-setting-values [saml-enabled                       true
                                         saml-identity-provider-uri         "http://idp.example.com/login"
                                         saml-identity-provider-certificate (slurp "test_resources/sso/auth0-public-idp.cert")
                                         saml-keystore-path                 "test_resources/keystore.jks"
                                         saml-keystore-password             "123456"
                                         saml-keystore-alias                "sp"
                                         site-url                           "http://localhost:3000"
                                         saml-slo-enabled                   true
                                         saml-identity-provider-slo-uri     "http://idp.example.com/logout"]
        (binding [client/*url-prefix* ""]
          (letfn [(logout-url [session-index]
                    (let [session-key (session/generate-session-key)]
                      (mt/with-temp [:model/User user {:email "[email protected]" :sso_source "saml"}
                                     :model/Session _ {:user_id            (:id user)
                                                       :id                 (session/generate-session-id)
                                                       :key_hashed         (session/hash-session-key session-key)
                                                       :saml_session_index session-index}]
                        (-> (client/client :post "/auth/sso/logout"
                                           (assoc-in {} [:request-options :cookies
                                                         request/metabase-session-cookie :value]
                                                     session-key))
                            :saml-logout-url))))
                  (saml-request [url]
                    ;; The LogoutRequest is deflated + base64'd into the SAMLRequest query param.
                    (let [param (second (re-find #"SAMLRequest=([^&]+)" url))
                          bytes (-> param codec/url-decode u/decode-base64-to-bytes)]
                      (with-open [in (java.util.zip.InflaterInputStream.
                                      (java.io.ByteArrayInputStream. bytes)
                                      (java.util.zip.Inflater. true))]
                        (slurp in))))]
            (testing "a session with a SessionIndex names it in the request"
              (let [xml (saml-request (logout-url "_session-index-from-idp"))]
                (is (str/includes? xml "<saml2p:SessionIndex>_session-index-from-idp</saml2p:SessionIndex>"))))
            (testing "a session without one omits the element entirely"
              ;; A fabricated or fixed SessionIndex broke Azure AD before (#41600), so IdPs that
              ;; never send one must keep seeing exactly the request they saw before.
              (let [xml (saml-request (logout-url nil))]
                (is (not (str/includes? xml "SessionIndex")))))))))))

(def ^:private default-jwt-secret (u.random/secure-hex 32))

(defn- with-jwt-settings! [f]
  (mt/with-additional-premium-features #{:sso-jwt}
    (mt/with-temporary-setting-values
      [jwt-enabled true
       jwt-identity-provider-uri "http://test.idp.metabase.com"
       jwt-shared-secret default-jwt-secret
       site-url (format "http://localhost:%s" (server.instance/server-port))]
      (f))))

(defn- create-valid-jwt-token
  ([]
   (create-valid-jwt-token {}))
  ([claims]
   (let [now (int (/ (System/currentTimeMillis) 1000))
         default-claims {:email "[email protected]"
                         :first_name "Test"
                         :last_name "User"
                         :iat now
                         :exp (+ now 3600)}]
     (jwt/sign (merge default-claims claims) default-jwt-secret))))

(deftest jwt-to-session-test
  (testing "POST /auth/sso/to_session"
    (binding [client/*url-prefix* ""]
      (with-jwt-settings!
        (fn []
          (testing "successful JWT to session conversion"
            (let [jwt-token (create-valid-jwt-token)
                  response (mt/client :post 200 "/auth/sso/to_session" {:jwt jwt-token})]
              (is (string? (:session_token response)))))
          (testing "missing JWT token"
            (is (=? {:errors {:jwt "value must be a non-blank string."}}
                    (mt/client :post 400 "/auth/sso/to_session" {}))))
          (testing "JWT disabled"
            (mt/with-temporary-setting-values [jwt-enabled false]
              (let [jwt-token (create-valid-jwt-token)]
                (is (= "JWT authentication is not enabled"
                       (mt/client :post 400 "/auth/sso/to_session" {:jwt jwt-token}))))))
          (testing "invalid JWT token"
            (is (= "Message seems corrupt or manipulated"
                   (mt/client :post 401 "/auth/sso/to_session" {:jwt "invalid-token"}))))
          (testing "expired JWT token"
            (let [expired-token (create-valid-jwt-token {:exp (- (int (/ (System/currentTimeMillis) 1000)) 3600)})]
              (is (str/starts-with? (mt/client :post 401 "/auth/sso/to_session" {:jwt expired-token})
                                    "Token is expired"))))
          (testing "JWT with different secret"
            (let [wrong-secret-token (jwt/sign {:email "[email protected]"
                                                :first_name "Test"
                                                :last_name "User"
                                                :iat (int (/ (System/currentTimeMillis) 1000))
                                                :exp (+ (int (/ (System/currentTimeMillis) 1000)) 3600)}
                                               "wrong-secret")]
              (is (= "Message seems corrupt or manipulated"
                     (mt/client :post 401 "/auth/sso/to_session" {:jwt wrong-secret-token})))))
          (testing "does not send new device login email"
            (let [email-addr  "[email protected]"
                  emails-sent (atom [])]
              (mt/with-temp [:model/User {user-id :id} {:email      email-addr
                                                        :first_name "Test"
                                                        :last_name  "NoEmail"}
                             ;; existing login history so it's not the user's first login ever
                             :model/LoginHistory _ {:user_id   user-id
                                                    :device_id "existing-device"}]
                (mt/with-dynamic-fn-redefs [messages/send-login-from-new-device-email! (fn [info]
                                                                                         (swap! emails-sent conj info))]
                  (let [jwt-token (create-valid-jwt-token {:email email-addr})
                        response  (mt/client :post 200 "/auth/sso/to_session" {:jwt jwt-token})]
                    (is (string? (:session_token response)))
                    (is (= [] @emails-sent)
                        "to_session endpoint should not send new device login emails")))))))))))