Skip to content

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

Restrict notification schema and allowed template values (#70261)

Nicola Mometto88f48ce99697
diff --git a/src/metabase/channel/models/channel.clj b/src/metabase/channel/models/channel.clj
index 6af32a35752..de7d5817ca2 100644
--- a/src/metabase/channel/models/channel.clj
+++ b/src/metabase/channel/models/channel.clj
@@ -3,6 +3,7 @@
[malli.core :as mc]
[metabase.analytics.prometheus :as prometheus]
[metabase.api.common :as api]
+ [metabase.channel.template.handlebars :as handlebars]
[metabase.models.interface :as mi]
[metabase.models.serialization :as serdes]
[metabase.permissions.core :as perms]
@@ -96,7 +97,10 @@
[:multi {:dispatch (comp keyword :type)}
[:email/handlebars-resource
[:map
- [:path string?]]]
+ [:path [:and
+ string?
+ [:fn {:error/message "invalid template path"}
+ handlebars/valid-template-path?]]]]]
[:email/handlebars-text
[:map
[:body string?]]]]])
@@ -112,6 +116,26 @@
[:details ::ChannelTemplateEmailDetails]]]
[::mc/default :any]]])
+(mr/def ::ChannelTemplateEmailDetailsUserProvided
+ "Email template details schema for API-provided templates. Only handlebars-text is allowed;
+ handlebars-resource is restricted to internal use only."
+ [:map
+ [:type (ms/enum-keywords-and-strings :email/handlebars-text)]
+ [:subject string?]
+ [:recipient-type {:optional true} (ms/enum-keywords-and-strings :cc :bcc)]
+ [:body string?]])
+
+(mr/def ::ChannelTemplateUserProvided
+ "Channel Template schema for API-provided templates. Does not allow handlebars-resource."
+ [:merge
+ [:map
+ [:channel_type [:fn #(= "channel" (-> % keyword namespace))]]]
+ [:multi {:dispatch :channel_type}
+ [:channel/email
+ [:map
+ [:details ::ChannelTemplateEmailDetailsUserProvided]]]
+ [::mc/default :any]]])
+
(defn- check-valid-channel-template
[channel-template]
(mu/validate-throw ::ChannelTemplate channel-template))
diff --git a/src/metabase/channel/template/handlebars.clj b/src/metabase/channel/template/handlebars.clj
index 19a9baf4e04..07517f7e9fe 100644
--- a/src/metabase/channel/template/handlebars.clj
+++ b/src/metabase/channel/template/handlebars.clj
@@ -1,5 +1,6 @@
(ns metabase.channel.template.handlebars
(:require
+ [clojure.string :as str]
[clojure.walk :as walk]
[metabase.channel.template.handlebars-helper :as handlebars-helper]
[metabase.config.core :as config]
@@ -56,11 +57,32 @@
(catch Exception e
(log/warn e "Error reloading default helpers"))))))
+(def ^:private allowed-template-prefixes
+ "Set of allowed directory prefixes for template paths."
+ #{"metabase/channel/email/"
+ "notification/channel_template/"})
+
+(defn valid-template-path?
+ "Returns true if the template path is safe: ends with .hbs, does not contain ..,
+ and starts with one of the allowed prefixes."
+ [^String path]
+ (boolean
+ (and (str/ends-with? path ".hbs")
+ (not (str/includes? path ".."))
+ (some #(str/starts-with? path %) allowed-template-prefixes))))
+
+(defn- validate-template-path!
+ "Validate that a template path is safe, throw if not."
+ [^String path]
+ (when-not (valid-template-path? path)
+ (throw (ex-info "invalid template path" {:path path}))))
+
(defn render
"Render a template with a context."
([template-name context]
(render @default-hbs template-name context))
([^Handlebars req ^String template-name ctx]
+ (validate-template-path! template-name)
(let [template ^Template (.compile req template-name)]
(.apply template (build-context ctx)))))
@@ -78,4 +100,4 @@
(render-string "{{format-date \"2000-01-02\" \"YYYY-dd-MM\" }}" {})
(render-string "Hello {{name}}" {:name "Ngoc"})
(render-string "Hello {{#unless hide_name}}{{name}}{{/unless}}" {:name "Ngoc" :hide_name false})
- (render "/metabase/channel/email/_header.hbs" {}))
+ (render "metabase/channel/email/_header.hbs" {}))
diff --git a/src/metabase/notification/api/notification.clj b/src/metabase/notification/api/notification.clj
index c43a6609e22..8afa6bbcb13 100644
--- a/src/metabase/notification/api/notification.clj
+++ b/src/metabase/notification/api/notification.clj
@@ -7,6 +7,7 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.channel.email.messages :as messages]
+ [metabase.channel.models.channel :as models.channel]
[metabase.channel.settings :as channel.settings]
[metabase.embedding.util :as embed.util]
[metabase.events.core :as events]
@@ -14,12 +15,37 @@
[metabase.notification.core :as notification]
[metabase.notification.models :as models.notification]
[metabase.util :as u]
+ [metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]
[toucan2.realize :as t2.realize]))
(set! *warn-on-reflection* true)
+(mr/def ::NotificationApiInput
+ "Notification schema for API input. Like FullyHydratedNotification but restricts templates
+ to user-provided types only (no handlebars-resource)."
+ [:merge
+ ::models.notification/FullyHydratedNotification
+ [:map
+ [:handlers {:optional true}
+ [:sequential
+ [:merge
+ ::models.notification/NotificationHandler
+ [:map
+ [:template {:optional true} [:maybe ::models.channel/ChannelTemplateUserProvided]]
+ [:channel {:optional true} [:maybe ::models.channel/Channel]]
+ [:recipients {:optional true} [:sequential ::models.notification/NotificationRecipient]]]]]]]])
+
+(defn- check-no-resource-templates!
+ "Validate that no handler uses handlebars-resource templates. That type is internal only."
+ [handlers]
+ (doseq [{:keys [template]} handlers
+ :when template
+ :let [template-type (some-> template :details :type keyword)]]
+ (when (= :email/handlebars-resource template-type)
+ (throw (ex-info "invalid template" {:status-code 400})))))
+
(defn get-notification
"Get a notification by id."
[id]
@@ -153,7 +179,8 @@
#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
(api.macros/defendpoint :post "/"
"Create a new notification, return the created notification."
- [_route _query body :- ::models.notification/FullyHydratedNotification request]
+ [_route _query body :- ::NotificationApiInput request]
+ (check-no-resource-templates! (:handlers body))
(api/create-check :model/Notification body)
(let [notification (models.notification/hydrate-notification
(models.notification/create-notification!
@@ -205,7 +232,8 @@
Return the updated notification."
[{:keys [id]} :- [:map [:id ms/PositiveInt]]
_query
- body :- ::models.notification/FullyHydratedNotification]
+ body :- ::NotificationApiInput]
+ (check-no-resource-templates! (:handlers body))
(let [existing-notification (get-notification id)]
(api/update-check existing-notification body)
(models.notification/update-notification! existing-notification body)
@@ -248,7 +276,8 @@
#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
(api.macros/defendpoint :post "/send"
"Send an unsaved notification."
- [_route _query body :- ::models.notification/FullyHydratedNotification request]
+ [_route _query body :- ::NotificationApiInput request]
+ (check-no-resource-templates! (:handlers body))
(api/create-check :model/Notification body)
(models.notification/validate-email-handlers! (:handlers body))
(let [notification (-> body
diff --git a/test/metabase/channel/models/channel_test.clj b/test/metabase/channel/models/channel_test.clj
index c7fc8ee5b14..aefbf6ab596 100644
--- a/test/metabase/channel/models/channel_test.clj
+++ b/test/metabase/channel/models/channel_test.clj
@@ -58,7 +58,12 @@
(testing "success"
(is (some? (insert! {:details {:type "email/handlebars-resource"
:subject "Hello {{name}}"
- :path "/path/to/resource"}}))))
+ :path "metabase/channel/email/password_reset.hbs"}}))))
+ (testing "invalid path"
+ (is (thrown? Exception
+ (insert! {:details {:type "email/handlebars-resource"
+ :subject "Hello {{name}}"
+ :path "/path/to/resource"}}))))
(testing "invalid template"
(is (thrown? Exception
(insert! {:details {:type "email/handlebars-resource"
diff --git a/test/metabase/channel/template/handlebars_test.clj b/test/metabase/channel/template/handlebars_test.clj
index 771ed3d00c2..bc165888c91 100644
--- a/test/metabase/channel/template/handlebars_test.clj
+++ b/test/metabase/channel/template/handlebars_test.clj
@@ -21,13 +21,13 @@
(defn do-with-temp-template!
[filename content thunk]
- ;; create the channel_template folder if not exists
(let [temp-file (format "test_resources/%s" filename)]
- (try
- (spit temp-file content)
- (thunk filename)
- (finally
- (io/delete-file temp-file)))))
+ (with-redefs [handlebars/allowed-template-prefixes #{""}]
+ (try
+ (spit temp-file content)
+ (thunk filename)
+ (finally
+ (io/delete-file temp-file))))))
(defmacro with-temp-template!
[[filename-binding filename content] & body]
@@ -50,14 +50,27 @@
(deftest render-test
(testing "Render a template with a context."
(with-temp-template! [tmpl-name "tmpl.hbs" "Hello {{name}}"]
- (is (= "Hello Ngoc" (handlebars/render tmpl-name {:name "Ngoc"}))))
- (with-temp-template! [tmpl-name "tmpl.handlebars" "Hello {{name}}"]
(is (= "Hello Ngoc" (handlebars/render tmpl-name {:name "Ngoc"})))))
(testing "with custom req"
(with-temp-template! [tmpl-name "tmpl.hbs" "Hello {{uppercase name}}"]
(is (= "Hello NGOC" (handlebars/render custom-hbs tmpl-name {:name "Ngoc"}))))))
+(deftest validate-template-path-test
+ (testing "valid paths are accepted"
+ (is (true? (handlebars/valid-template-path? "metabase/channel/email/password_reset.hbs")))
+ (is (true? (handlebars/valid-template-path? "metabase/channel/email/notification_card.hbs")))
+ (is (true? (handlebars/valid-template-path? "notification/channel_template/hello_world.hbs"))))
+
+ (is (false? (handlebars/valid-template-path? "foo/bar/baz.hbs")))
+ (is (false? (handlebars/valid-template-path? "/metabase/channel/email/foo.hbs")))
+
+ (testing "render rejects invalid paths"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"invalid template path"
+ (handlebars/render "foo/bar.hbs" {})))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"invalid template path"
+ (handlebars/render "metabase/channel/email/logo.clj" {})))))
+
(deftest dotted-path-resolution-works-on-maps-test
(are [template context]
(= "" (handlebars/render-string template context))
diff --git a/test/metabase/notification/api/notification_test.clj b/test/metabase/notification/api/notification_test.clj
index e7b5a5f7bdc..d01757e612e 100644
--- a/test/metabase/notification/api/notification_test.clj
+++ b/test/metabase/notification/api/notification_test.clj
@@ -256,6 +256,47 @@
recreated-template (-> notification :handlers first :template)]
(is (=? template recreated-template))))))))
+(deftest api-rejects-handlebars-resource-templates-test
+ (let [resource-template {:name "test"
+ :channel_type "channel/email"
+ :details {:type "email/handlebars-resource"
+ :subject "test"
+ :path "metabase/channel/email/password_reset.hbs"}}]
+ (testing "POST /api/notification rejects handlebars-resource templates"
+ (mt/with-model-cleanup [:model/Notification]
+ (mt/with-temp [:model/Card {card-id :id} {}]
+ (is (=? "invalid template"
+ (mt/user-http-request :crowberto :post 400 "notification"
+ {:payload_type "notification/card"
+ :payload {:card_id card-id}
+ :handlers [{:channel_type "channel/email"
+ :template resource-template
+ :recipients [{:type "notification-recipient/user"
+ :user_id (mt/user->id :crowberto)}]}]}))))))
+
+ (testing "POST /api/notification/send rejects handlebars-resource templates"
+ (mt/with-temp [:model/Card {card-id :id} {}]
+ (is (=? "invalid template"
+ (mt/user-http-request :crowberto :post 400 "notification/send"
+ {:payload_type "notification/card"
+ :payload {:card_id card-id
+ :send_condition "has_result"}
+ :handlers [{:channel_type "channel/email"
+ :template resource-template
+ :recipients [{:type "notification-recipient/user"
+ :user_id (mt/user->id :crowberto)}]}]})))))
+
+ (testing "PUT /api/notification/:id rejects handlebars-resource templates"
+ (notification.tu/with-card-notification
+ [notification {:handlers [{:channel_type "channel/email"
+ :recipients [{:type :notification-recipient/user
+ :user_id (mt/user->id :crowberto)}]}]}]
+ (is (=? "invalid template"
+ (mt/user-http-request :crowberto :put 400 (format "notification/%d" (:id notification))
+ (update notification :handlers
+ (fn [[handler]]
+ [(assoc handler :template resource-template)])))))))))
+
(defn- update-cron-subscription
[{:keys [subscriptions] :as notification} new-schedule ui-display-type]
(assert (= 1 (count subscriptions)))