Skip to content

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

21.5 KB
Raw Blame
(ns metabase-enterprise.custom-viz-plugin.api
  "/api/ee/custom-viz-plugin endpoints."
  (:require
   [clj-http.client :as http]
   [clojure.core.async :as a]
   [metabase-enterprise.custom-viz-plugin.cache :as cache]
   [metabase-enterprise.custom-viz-plugin.db :as custom-viz-plugin.db]
   [metabase-enterprise.custom-viz-plugin.manifest :as manifest]
   [metabase-enterprise.custom-viz-plugin.settings :as custom-viz.settings]
   [metabase.api-scope.data-app :as api-scope]
   [metabase.api.common :as api]
   [metabase.api.macros :as api.macros]
   [metabase.api.routes.common :refer [+auth]]
   [metabase.events.core :as events]
   [metabase.server.streaming-response :as sr]
   [metabase.util.http :as u.http]
   [metabase.util.log :as log]
   [metabase.util.malli.schema :as ms])
  (:import
   (java.io BufferedReader File InputStream InputStreamReader OutputStream)
   (java.nio.file Files)))

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

;;; ------------------------------------------------ Dev-mode guard ------------------------------------------------

(defn- check-dev-mode-enabled!
  "Throws a 403 if dev mode is not enabled via MB_CUSTOM_VIZ_PLUGIN_DEV_MODE_ENABLED."
  []
  (api/check (custom-viz.settings/custom-viz-plugin-dev-mode-enabled)
             [403 "Custom visualization plugin dev mode is not enabled."]))

;;; ------------------------------------------------ Upload guard ------------------------------------------------

(defn- check-upload!
  "Validate an incoming multipart `file` part before we spend any IO reading it.
   Rejects oversized uploads with 413 using `:size` (populated by Ring from the
   bytes it actually buffered, not a client header) and rejects missing files with
   400. Returns the `java.io.File` tempfile."
  ^File [file]
  (let [tempfile (:tempfile file)]
    (when-not (instance? File tempfile)
      (throw (ex-info "No file provided" {:status-code 400})))
    (when (> (:size file) cache/max-bundle-bytes)
      (throw (ex-info (format "Bundle must be less than %dMB." cache/max-bundle-mib)
                      {:status-code 413})))
    tempfile))

;;; ------------------------------------------------ Schemas ------------------------------------------------

(def ^:private BundleUploadParts
  "The multipart parts carrying a tar.gz bundle. `:size` is what [[check-upload!]] enforces the size limit with, so it
  has to be declared here for it to survive param decoding."
  [:map {:closed true}
   [:file [:map {:closed true}
           [:filename :string]
           [:size     ms/IntGreaterThanOrEqualToZero]
           [:tempfile (ms/InstanceOfClass File)]]]])

(def ^:private CustomVizPluginResponse
  [:map
   [:id              ms/PositiveInt]
   [:display_name    ms/NonBlankString]
   [:identifier      ms/NonBlankString]
   [:status          [:enum :active :error]]
   [:enabled         :boolean]
   [:icon            {:optional true} [:maybe :string]]
   [:error_message   {:optional true} [:maybe :string]]
   [:bundle_hash     {:optional true} [:maybe :string]]
   [:dev_bundle_url  {:optional true} [:maybe :string]]
   [:dev_only        :boolean]
   [:manifest        {:optional true} [:maybe :any]]
   [:metabase_version {:optional true} [:maybe :string]]
   [:warnings        [:sequential [:map [:type :string]]]]
   [:created_at      :any]
   [:updated_at      :any]])

(def ^:private CustomVizPluginRuntimeResponse
  [:map
   [:id              ms/PositiveInt]
   [:identifier      ms/NonBlankString]
   [:display_name    ms/NonBlankString]
   [:icon            {:optional true} [:maybe :string]]
   [:bundle_url      ms/NonBlankString]
   [:bundle_hash     {:optional true} [:maybe :string]]
   [:dev_bundle_url  {:optional true} [:maybe :string]]
   [:manifest        {:optional true} [:maybe :any]]
   [:warnings        [:sequential [:map [:type :string]]]]])

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

(defn- dev-only-plugin?
  "Returns true if the plugin has no uploaded bundle and is served from a dev URL."
  [plugin]
  (nil? (:bundle_hash plugin)))

(defn- plugin-warnings
  "Warnings for a plugin. Dev-only plugins get no version warnings."
  [plugin]
  (cond-> (if (dev-only-plugin? plugin)
            []
            (manifest/warnings plugin))
    ;; a legacy pre-validation identifier; /list skips such plugins entirely
    (manifest/identifier-error (:identifier plugin))
    (conj {:type "invalid-identifier" :identifier (:identifier plugin)})))

(defn- plugin->response
  "Convert a plugin record to API response format."
  [plugin]
  (-> plugin
      (assoc :dev_only (dev-only-plugin? plugin)
             :warnings (plugin-warnings plugin))
      ;; never expose the raw bundle bytes
      (dissoc :bundle)))

(defn- plugin->runtime-response
  "Convert a plugin record to the safe runtime response shape.
   `bundle_url` is suffixed with `?v=<bundle_hash>` so that a re-uploaded bundle is fetched
   instead of served from the browser's `immutable` cache."
  [{:keys [id identifier display_name icon bundle_hash manifest dev_bundle_url]
    :as   plugin}]
  (cond-> {:id           id
           :identifier   identifier
           :display_name display_name
           :icon         icon
           :bundle_url   (cond-> (format "/api/ee/custom-viz-plugin/%d/bundle" id)
                           bundle_hash (str "?v=" bundle_hash))
           :bundle_hash  bundle_hash
           :manifest     manifest
           :warnings     (plugin-warnings plugin)}
    dev_bundle_url (assoc :dev_bundle_url dev_bundle_url)))

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

(api.macros/defendpoint :post "/" :- CustomVizPluginResponse
  "Register a new custom visualization plugin from an uploaded tar.gz bundle.

  The archive must contain `metabase-plugin.json` at the root and
  `dist/index.js` for the JS bundle. The only static asset served from the bundle
  is the manifest `icon` (under `dist/assets/`); plugins do not ship arbitrary
  assets. The plugin's `identifier` is taken from the manifest's `name` field."
  {:multipart {:max-file-size  cache/max-bundle-bytes
               :max-file-count 1}}
  [_route-params
   _query-params
   {:keys [file]} :- BundleUploadParts]
  (api/check-superuser)
  (let [tempfile (check-upload! file)]
    (try
      (let [bundle-bytes (Files/readAllBytes (.toPath tempfile))
            validated    (cache/validate-bundle! bundle-bytes)
            identifier   (get-in validated [:manifest :name])
            _            (api/check-400
                          (not (custom-viz-plugin.db/plugin-identifier-exists? identifier))
                          (format "A custom visualization with identifier \"%s\" already exists." identifier))
            plugin       (cache/insert-bundle! identifier validated)]
        (events/publish-event! :event/custom-viz-plugin-create {:object  plugin
                                                                :user-id api/*current-user-id*})
        (plugin->response (dissoc plugin :bundle)))
      (finally
        (try (.delete tempfile) (catch Exception _))))))

(api.macros/defendpoint :post "/dev" :- CustomVizPluginResponse
  "Register a dev-only custom visualization plugin from a local dev server.
   No bundle upload is required — files are served from the dev server URL.
   Requires custom viz plugin dev mode to be enabled."
  [_route-params
   _query-params
   {:keys [identifier dev_bundle_url]} :- [:map {:closed true}
                                           [:identifier     {:optional true} [:maybe ms/NonBlankString]]
                                           [:dev_bundle_url ms/NonBlankString]]]
  (api/check-superuser)
  (check-dev-mode-enabled!)
  (let [manifest     (cache/fetch-dev-manifest dev_bundle_url)
        identifier   (or identifier
                         (:name manifest)
                         (throw (ex-info (if manifest
                                           "metabase-plugin.json is missing a \"name\" field."
                                           "Could not fetch metabase-plugin.json from the dev server.")
                                         {:status-code 400})))
        _            (when-let [error (manifest/identifier-error identifier)]
                       (throw (ex-info error {:status-code 400})))
        _            (api/check-400
                      (not (custom-viz-plugin.db/plugin-identifier-exists? identifier))
                      (format "A custom visualization with identifier \"%s\" already exists." identifier))
        display-name (or (:name manifest) identifier)
        icon         (:icon manifest)
        version-str  (get-in manifest [:metabase :version])
        plugin       (custom-viz-plugin.db/insert-plugin! {:display_name     display-name
                                                           :identifier       identifier
                                                           :status           :active
                                                           :enabled          true
                                                           :dev_bundle_url   dev_bundle_url
                                                           :icon             icon
                                                           :manifest         manifest
                                                           :metabase_version version-str})]
    (cache/set-or-clear-dev-bundle! (:id plugin) dev_bundle_url)
    (events/publish-event! :event/custom-viz-plugin-create {:object  plugin
                                                            :user-id api/*current-user-id*})
    (plugin->response plugin)))

(api.macros/defendpoint :get "/" :- [:sequential CustomVizPluginResponse]
  "List all registered custom visualization plugins."
  []
  (api/check-superuser)
  (->> (custom-viz-plugin.db/non-blob-plugins)
       (mapv (comp plugin->response api/read-check))))

(api.macros/defendpoint :get "/list" :- [:sequential CustomVizPluginRuntimeResponse]
  "List active and enabled custom visualization plugins. Available to any authenticated user.
   Plugins with version mismatches are included, with soft `warnings` attached.
   Dev-only plugins are excluded when dev mode is disabled."
  {:scope api-scope/data-app}
  []
  (let [dev-mode? (custom-viz.settings/custom-viz-plugin-dev-mode-enabled)
        plugins   (custom-viz-plugin.db/active-enabled-non-blob-plugins)]
    (->> plugins
         (remove #(and (not dev-mode?) (dev-only-plugin? %)))
         ;; An identifier containing ":" would collide with another plugin's `custom:<id>:`
         ;; settings prefix on the frontend. Colons are rejected at registration now; skip any
         ;; legacy row that predates that check instead of serving it.
         (remove #(manifest/identifier-error (:identifier %)))
         (mapv (comp plugin->runtime-response api/read-check)))))

(api.macros/defendpoint :delete "/:id" :- :nil
  "Remove a custom visualization plugin and evict its on-disk cache."
  [{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]]
  (let [plugin (api/write-check (custom-viz-plugin.db/non-blob-plugin id))]
    (custom-viz-plugin.db/delete-plugin! id)
    (cache/purge-plugin-cache! plugin)
    (events/publish-event! :event/custom-viz-plugin-delete {:object  plugin
                                                            :user-id api/*current-user-id*})
    nil))

(api.macros/defendpoint :put "/:id" :- CustomVizPluginResponse
  "Update a custom visualization plugin. Currently only `enabled` may be toggled."
  [{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]
   _query-params
   body :- [:map {:closed true}
            [:enabled {:optional true} [:maybe :boolean]]]]
  (let [existing (api/write-check (custom-viz-plugin.db/non-blob-plugin id))
        updates  (select-keys body [:enabled])]
    (when (seq updates)
      (custom-viz-plugin.db/update-plugin! id updates))
    (let [result (custom-viz-plugin.db/non-blob-plugin id)]
      (events/publish-event! :event/custom-viz-plugin-update {:object          result
                                                              :previous-object existing
                                                              :user-id         api/*current-user-id*})
      (plugin->response result))))

(api.macros/defendpoint :put "/:id/bundle" :- CustomVizPluginResponse
  "Replace the bundle for an existing plugin. Accepts a multipart tar.gz upload in
   the same format as the `POST /` endpoint. The manifest's `name` field must
   match the plugin's existing `identifier`."
  {:multipart {:max-file-size  cache/max-bundle-bytes
               :max-file-count 1}}
  [{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]
   _query-params
   {:keys [file]} :- BundleUploadParts]
  (let [existing (api/write-check (custom-viz-plugin.db/non-blob-plugin id))
        _        (api/check-400 (nil? (manifest/identifier-error (:identifier existing)))
                                (format (str "This plugin's identifier (\"%s\") contains \":\", which is no longer allowed. "
                                             "Delete the plugin and upload the bundle under a name without \":\".")
                                        (:identifier existing)))
        tempfile (check-upload! file)]
    (try
      (let [bundle-bytes (Files/readAllBytes (.toPath tempfile))
            validated    (->> (cache/validate-bundle! bundle-bytes)
                              (cache/check-bundle-identifier! (:identifier existing)))
            result       (cache/save-bundle! existing validated)]
        (events/publish-event! :event/custom-viz-plugin-update
                               {:object          result
                                :previous-object existing
                                :user-id         api/*current-user-id*})
        (plugin->response (dissoc result :bundle)))
      (finally
        (try (.delete tempfile) (catch Exception _))))))

(api.macros/defendpoint :get "/:id/bundle" :- :any
  "Serve the JS bundle for a plugin from the on-disk cache.
   Returns application/javascript with ETag and Cache-Control headers.
   In dev mode, proxies from `dev_bundle_url` if set."
  {:scope api-scope/data-app}
  [{:keys [id], :as _route-params} :- [:map {:closed true} [:id ms/PositiveInt]]
   _query-params
   _body
   _request
   respond
   raise]
  (try
    (let [plugin  (api/read-check (custom-viz-plugin.db/non-blob-plugin id))
          dev-url (cache/resolve-dev-bundle id)
          entry   (cache/resolve-bundle plugin)]
      (if entry
        (respond {:status  200
                  :headers (cond-> {"Content-Type"                 "application/javascript"
                                    "X-Content-Type-Options"       "nosniff"
                                    "Cross-Origin-Resource-Policy" "same-origin"
                                    "Referrer-Policy"              "no-referrer"
                                    "ETag"                         (:hash entry)}
                             dev-url       (assoc "Cache-Control" "no-store")
                             (not dev-url) (assoc "Cache-Control" "public, max-age=31536000, immutable"))
                  :body    (:content entry)})
        (respond {:status  503
                  :headers {"Content-Type" "application/json"}
                  :body    "{\"error\": \"Bundle not available\"}"})))
    (catch Throwable e
      (raise e))))

(api.macros/defendpoint :get "/:id/asset" :- :any
  "Serve the plugin's icon image from its bundle.
   The asset path is passed as a `path` query parameter (e.g. `?path=icon.svg`)
   and must match the manifest `icon`. Only the icon is served — plugins do not
   ship arbitrary assets.
   In dev mode, proxies from the dev base URL if set."
  {:scope api-scope/data-app}
  [{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]
   {:keys [path]} :- [:map {:closed true} [:path ms/NonBlankString]]
   _body
   _request
   respond
   raise]
  (try
    (let [plugin       (api/read-check (custom-viz-plugin.db/non-blob-plugin id))
          content-type (or (manifest/asset-content-type path)
                           (throw (ex-info "Unsupported asset type" {:status-code 404})))
          dev?         (cache/resolve-dev-bundle id)
          bytes        (cache/resolve-asset plugin path)]
      (if bytes
        (respond {:status  200
                  :headers (cond-> {"Content-Type"                 content-type
                                    "X-Content-Type-Options"       "nosniff"
                                    "Cross-Origin-Resource-Policy" "same-origin"
                                    "Referrer-Policy"              "no-referrer"}
                             dev?       (assoc "Cache-Control" "no-store")
                             (not dev?) (assoc "Cache-Control" "public, max-age=31536000, immutable"))
                  :body    (java.io.ByteArrayInputStream. bytes)})
        (respond {:status  404
                  :headers {"Content-Type" "application/json"}
                  :body    "{\"error\": \"Asset not found\"}"})))
    (catch Throwable e
      (raise e))))

(api.macros/defendpoint :put "/:id/dev-url" :- [:map {:closed true} [:dev_bundle_url [:maybe :string]]]
  "Set or clear the dev base URL for a plugin (e.g. `http://localhost:5174`).
   The bundle is fetched from `{base}/index.js` and assets from `{base}/assets/{name}`.
   Persisted to the database so it survives server restarts.
   Requires custom viz plugin dev mode to be enabled."
  [{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]
   _query-params
   {:keys [dev_bundle_url]} :- [:map {:closed true} [:dev_bundle_url [:maybe :string]]]]
  (api/write-check (custom-viz-plugin.db/non-blob-plugin id))
  (check-dev-mode-enabled!)
  (cache/set-or-clear-dev-bundle! id dev_bundle_url)
  {:dev_bundle_url (cache/resolve-dev-bundle id)})

(api.macros/defendpoint :get "/:id/dev-sse" :- :any
  "Proxy Server-Sent Events from the plugin's dev server.
   Connects to `{dev_bundle_url}/__sse` and forwards events to the browser.
   This avoids the need for a CSP exception for the dev server origin.
   Requires custom viz plugin dev mode to be enabled."
  [{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]]
  (check-dev-mode-enabled!)
  (let [dev-url (cache/resolve-dev-bundle id)]
    (when-not dev-url
      (throw (ex-info "No dev server URL configured" {:status-code 404})))
    (let [sse-url (str (cache/dev-base-url dev-url) "__sse")]
      (sr/streaming-response {:content-type "text/event-stream"
                              :status       200
                              :headers      {"Cache-Control"      "no-cache"
                                             "Connection"         "keep-alive"
                                             "X-Accel-Buffering"  "no"}}
                             [^OutputStream os canceled-chan]
        (try
          ;; the SSE stream is long-lived and idle between events, so override the 5s read timeout
          ;; from dev-http-opts (0 = no read timeout)
          (let [resp (http/get sse-url (merge cache/dev-http-opts
                                              {:as             :stream
                                               :socket-timeout 0
                                               :headers        {"Accept" "text/event-stream"}}))]
            (with-open [^InputStream is (:body resp)
                        rdr (BufferedReader. (InputStreamReader. is "UTF-8"))]
              (if-not (= "text/event-stream" (u.http/response-content-type resp))
                (sr/write-error! os {:message "Dev server did not return an event stream"} nil 400)
                (loop []
                  (when-not (a/poll! canceled-chan)
                    (when-let [line (.readLine rdr)]
                      (.write os (.getBytes (str line "\n") "UTF-8"))
                      (.flush os)
                      (recur)))))))
          (catch Exception e
            (log/debugf "SSE proxy for plugin %d ended: %s" id (ex-message e))
            (sr/write-error! os e nil)))))))

(api.macros/defendpoint :post "/:id/refresh" :- CustomVizPluginResponse
  "Re-fetch the manifest from the dev server for a dev-only plugin. For uploaded
   plugins this is a no-op — to update an upload-backed plugin, PUT a new bundle
   to `/:id/bundle`."
  [{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]]
  (let [plugin (api/write-check (custom-viz-plugin.db/non-blob-plugin id))]
    (api/check-400 (dev-only-plugin? plugin)
                   "Refresh is only supported for dev-only plugins; upload a new bundle to update an upload-backed plugin.")
    (let [dev-url      (or (cache/resolve-dev-bundle id)
                           (throw (ex-info "No dev server URL configured" {:status-code 404})))
          manifest     (or (cache/fetch-dev-manifest dev-url)
                           (throw (ex-info "Failed to fetch manifest from dev server" {:status-code 502})))
          version-str  (get-in manifest [:metabase :version])]
      (custom-viz-plugin.db/update-plugin! id
                                           {:display_name     (or (:name manifest) (:identifier plugin))
                                            :icon             (:icon manifest)
                                            :manifest         manifest
                                            :metabase_version version-str})
      (let [result (custom-viz-plugin.db/non-blob-plugin id)]
        (events/publish-event! :event/custom-viz-plugin-update {:object          result
                                                                :previous-object plugin
                                                                :user-id         api/*current-user-id*})
        (plugin->response result)))))

(def routes
  "`/api/ee/custom-viz-plugin` routes."
  (api.macros/ns-handler *ns* +auth))