The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Restrict which models are accessible by each module (#71010)
Chris Trutercc74f66a1b3d
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 771f6720090..8b54e6b75d9 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -50,6 +50,29 @@;; {...;; :friends #{enterprise/search search-rest}};;+;; ## `model-exports`:+;;+;; Set of `:model/X` keywords that this module allows others to reference. Currently defaults to `:any` when+;; omitted, meaning all models defined in this module are freely usable by other modules. In the future we may+;; change to pure opt-in semantics where modules must explicitly list their exports. A set restricts external+;; access to only the listed models; an empty set `#{}` means no models are exported.+;;+;; enterprise/workspaces+;; {...+;; :model-exports #{:model/Workspace :model/WorkspaceMergeTransform}}+;;+;; ## `model-imports`:+;;+;; Set of `:model/X` keywords that this module is allowed to reference from other modules. Currently defaults to+;; `:any` when omitted, meaning this module can freely reference any model. In the future we may change to pure+;; opt-in semantics where modules must explicitly list their imports. A set restricts the module to only the listed+;; models; any other `:model/X` keyword in the module's source files will be flagged as a violation. If a model is+;; used but its definition cannot be found, that is also a violation.+;;+;; transforms-base+;; {...+;; :model-imports #{:model/Database :model/Field :model/Table :model/Transform}}+;;;; ## Tips;;;; PRO TIP: Check out the [[dev.deps-graph]] namespace for helpful tools to see where a module is used externally, and@@ -941,7 +964,9 @@util}}notification- {:team "Gadget"+ {;; TODO: re-enable when :model/NotificationDashboard is no longer a problem+ :model-imports :skip-test+ :team "Gadget":api #{metabase.notification.apimetabase.notification.coremetabase.notification.init@@ -1670,6 +1695,15 @@:api #{metabase.transforms-base.initmetabase.transforms-base.interfacemetabase.transforms-base.util}+ :model-imports #{:model/Database+ :model/DatabaseRouter+ :model/Field+ :model/Table+ ;; TODO regressions — transforms-base should not depend on+ ;; these directly. Remove once the module is agnostic to+ ;; global versus workspace transforms.+ :model/Transform+ :model/TransformRun}:uses #{drivereventslib@@ -2629,6 +2663,7 @@{:team "Metabot":api #{metabase-enterprise.workspaces.apimetabase-enterprise.workspaces.init}+ :model-exports #{:model/Workspace :model/WorkspaceMergeTransform}:friends #{enterprise/agent-api}:uses #{apiapp-dbdiff --git a/dev/notes/model-boundary-enforcement.md b/dev/notes/model-boundary-enforcement.mdnew file mode 100644index 00000000000..f5d4b6f8829--- /dev/null+++ b/dev/notes/model-boundary-enforcement.md@@ -0,0 +1,181 @@+# Toucan2 Model Boundary Enforcement++## What it does++The module system controls which *namespaces* can be imported between modules.+Model boundary enforcement extends this to `:model/X` keywords — controlling+which Toucan2 models each module can reference.++Two optional config keys per module in+`.clj-kondo/config/modules/config.edn`:++| Key | Default | Meaning |+|------------------|---------|---------|+| `:model-exports` | `:any` | Set of `:model/X` keywords this module allows **others** to use. |+| `:model-imports` | `:any` | Set of `:model/X` keywords **this module** may use from other modules. |++When omitted (or set to `:any`), no restrictions apply. `#{}` means export+nothing / import nothing.++## Why it exists++Two core ideas:++1. Some models need encapsulation.+2. Some modules should be storage-agnostic.++This makes both enforceable.++**Encapsulation.** Some domain models span multiple tables with complex+invariants. `enterprise/workspaces`, for example, involves `WorkspaceInput`,+`WorkspaceGraph`, `WorkspaceTransform`, and others whose internal relationships+should be managed exclusively by that module. `:model-exports` lets a module+declare a public surface area (e.g. only `#{:model/Workspace+:model/WorkspaceMergeTransform}`) while keeping internal models private.++**Testability and performance.** Restricting model access makes it easier to+reason about where blocking IO happens. Some models are more expensive than+others (large tables, complex hooks). Modules that receive data as arguments+rather than querying models directly are easier to test and easier to reason+about performance-wise.++**Jekyll mode.** In Jekyll mode, artifact definitions live in files on disk+rather than being mutated directly in the app-database. The less a module+depends on direct model access today, the less work needed to make it+compatible. Restricting model imports nudges modules in this direction+incrementally.++**Shared logic across storage backends.** Workspaces use parallel models+(`:model/Transform` / `:model/WorkspaceTransform`) backed by separate tables.+This design may change in future. While it exists, core algorithms like+dependency ordering and query compilation need to work identically for both.+If `transforms-base` restricts its model imports, it *must* be written in a+storage-agnostic way — accepting data as arguments rather than hardcoding model+references. Adding this validation caught a real regression where new code in+`transforms-base` had introduced direct `:model/Transform` references.++## How it works++Model ownership is derived automatically by scanning source files for+`(*/defmethod t2/table-name :model/X ...)` calls (any symbol ending in+`/defmethod`). No manual ownership configuration is needed.++At test time (`metabase.core.modules-test`), the system:++1. Builds a map of `:model/X` to owning module by scanning all source files+2. For each source file, finds all `:model/X` keyword usages+3. Checks each reference against:+ - The defining module's `:model-exports` (is this model exported?)+ - The using module's `:model-imports` (is this module allowed to use it?)+ - The model definition exists somewhere (unknown models are always a violation)++### Violation types++| Type | Meaning |+|-------------------|---------|+| `:not-exported` | The defining module restricts `:model-exports` and this model is not in the set |+| `:not-imported` | The using module restricts `:model-imports` and this model is not in the set |+| `:unknown-model` | The model definition was not found anywhere (always a violation) |++### Exemptions++- `metabase.models.resolution` is exempt (it intentionally references all+ models as a registry)+- Test namespaces are excluded by the existing `ignored-namespace-patterns`+- Same-module references are always allowed++## How to use it++### Restricting a module's exports++Add `:model-exports` to the module's config entry:++```clojure+enterprise/workspaces+{:team "Metabot"+ :model-exports #{:model/Workspace :model/WorkspaceMergeTransform}+ ...}+```++Only the listed models can be referenced from other modules. All other models+defined in this module become internal.++For example, if a module exports only `:model/Workspace`, then a use of+`:model/WorkspaceInput` from another module will fail with `:not-exported`.++### Restricting a module's imports++Add `:model-imports` to the module's config entry:++```clojure+transforms-base+{:team "Querying"+ :model-imports #{:model/Database :model/DatabaseRouter :model/Field :model/Table}+ ...}+```++The module can only reference these models from other modules. Any other+`:model/X` keyword in the module's source files will cause a test failure.+Unknown models (not defined anywhere) are also violations.++### Verifying changes++```bash+./bin/test-agent :only '[metabase.core.modules-test]'+```++Or at the REPL:++```clojure+(dev.deps-graph/model-ownership) ;; see which module owns each model+(dev.deps-graph/model-boundary-violations) ;; find any violations+```++The test also validates that configured `:model-exports` / `:model-imports`+only mention known models, and that exported models are actually owned by the+module exporting them.++## Limitations and future directions++Each limitation below has a natural extension.++**Keyword scanning isn't airtight.** Code can access the app-database without+`:model/X` keywords — via non-namespaced keywords like `:transform`, raw SQL+through `t2/query`, or table-name strings. The enforcement catches conventional+usage but not determined workarounds. A stronger approach: ban `toucan2.core`+entirely for pure modules via a `:banned-requires` config key, closing all+loopholes at once.++**Binary access control.** A module either can or cannot reference a given+model. A natural refinement: distinguish read-only vs read-write access, which+is particularly relevant for Jekyll mode where reads (from the app-database as+cache) are acceptable but authoritative writes are not.++**No transitive checking.** Only keywords appearing directly in a module's+source files are checked. If module A calls a function in module B that+internally references `:model/Transform`, this is not flagged against A. A+future extension could check transitive model access through module+dependencies, possibly with different restrictions for direct vs transitive+references.++**Static-only.** Static analysis operates at the module level and can't+distinguish code paths within a module. Runtime enforcement could provide+stronger guarantees that certain code paths are pure, complementing the+read-only/read-write distinction above.++## Design decisions++- **Test-time enforcement, not compile-time.** Keeps the implementation simple+ (source scanning with rewrite-clj) and avoids adding overhead to normal+ development. The tradeoff: violations are only caught when tests run.++- **Opt-in, not opt-out (for now).** Modules default to `:any` for both+ exports and imports, so enforcement is incremental — restrict one module at a+ time without touching anything else. Once enough modules have explicit sets,+ we might flip the default to `#{}` so that new modules are restricted by+ default and must explicitly declare their model dependencies. `:any` as the+ starting default avoids a big-bang migration.++- **Ownership is derived, not configured.** Instead of manually mapping models+ to modules, ownership is determined by scanning for `t2/table-name` defmethod+ calls. Avoids config duplication and stays in sync automatically.diff --git a/dev/src/dev/deps_graph.clj b/dev/src/dev/deps_graph.cljindex 7bf544a7805..ddbe8c9da62 100644--- a/dev/src/dev/deps_graph.clj+++ b/dev/src/dev/deps_graph.clj@@ -744,3 +744,148 @@;; should only include tests for `settings-rest`, `api-routes`, `core`, and the handful of random modules that use;; `settings-rest` (21 files as of 2025-11-26)(source-filenames->relevant-test-filenames ["src/metabase/settings_rest/api.clj"]))++;;;; Model boundary enforcement++(mu/defn find-model-keywords :- [:set :keyword]+ "Find all `:model/X` keywords referenced in a source file, ignoring comments."+ [file]+ (try+ (let [models (atom #{})]+ (loop [stack [(z/of-node (r.parser/parse-file-all file))]]+ (when-let [zloc (peek stack)]+ (let [stack' (pop stack)+ stack' (if-let [right (z/right zloc)]+ (conj stack' right)+ stack')]+ (if (comment-loc? zloc)+ (recur stack')+ (do+ (when (and (= (z/tag zloc) :token)+ (keyword? (z/sexpr zloc))+ (= "model" (namespace (z/sexpr zloc)))+ (Character/isUpperCase ^char (first (name (z/sexpr zloc)))))+ (swap! models conj (z/sexpr zloc)))+ (recur (if-let [child (z/down zloc)]+ (conj stack' child)+ stack')))))))+ @models)+ (catch Throwable e+ (throw (ex-info (format "Error scanning model keywords in %s: %s" (str file) (ex-message e))+ {:file file}+ e)))))++(mu/defn find-model-definitions :- [:set :keyword]+ "Find all models with their `t2/table-name` defined in this file."+ [file]+ (let [models (atom #{})]+ (loop [stack [(z/of-node (r.parser/parse-file-all file))]]+ (when-let [zloc (peek stack)]+ (let [stack' (pop stack)+ stack' (if-let [right (z/right zloc)]+ (conj stack' right)+ stack')]+ (if (comment-loc? zloc)+ (recur stack')+ (do+ (when (= (z/tag zloc) :list)+ (let [first-child (z/down zloc)]+ (when (and first-child+ (= (z/tag first-child) :token)+ (some-> (:string-value (z/node first-child)) (str/ends-with? "/defmethod")))+ (let [second-zloc (z/right first-child)+ third-zloc (some-> second-zloc z/right)]+ (when (and second-zloc+ (= (z/sexpr second-zloc) 't2/table-name)+ third-zloc+ (keyword? (z/sexpr third-zloc))+ (= "model" (namespace (z/sexpr third-zloc))))+ (swap! models conj (z/sexpr third-zloc)))))))+ (recur (if-let [child (z/down zloc)]+ (conj stack' child)+ stack')))))))+ @models))++(defn model-ownership+ "Scan all source files via [[find-model-definitions]], building a map of `:model/X` => module symbol.+ The module is derived from the defining namespace via [[module]]."+ []+ (into (sorted-map)+ (for [file (find-source-files)+ :let [ns-symb (-> (ns.file/read-file-ns-decl file)+ ns.parse/name-from-ns-decl)+ mod (module ns-symb)+ models (find-model-definitions file)]+ :when mod+ model models]+ [model mod])))++(def ^:private model-boundary-exempt-namespaces+ "Namespaces that are exempt from model boundary checking. These are 'glue' namespaces that intentionally reference+ all models."+ #{'metabase.models.resolution})++(defn- model-reference-violations+ "Return violation types for a single model reference. Pure function — no IO."+ [model defining-mod model-exports model-imports]+ (cond-> []+ (nil? defining-mod)+ (conj :unknown-model)++ (and defining-mod+ (not= model-exports :any)+ (not (contains? model-exports model)))+ (conj :not-exported)++ (and defining-mod+ (not= model-imports :any)+ (not (contains? model-imports model)))+ (conj :not-imported)))++(defn model-boundary-violations+ "Find all model boundary violations across the codebase.+ For each source file, checks that:+ 1. The defining module's `:model-exports` allows the model (`:any` or set containing it)+ 2. The using module's `:model-imports` allows the model (`:any` or set containing it)+ 3. The model's definition exists somewhere (`:unknown-model` is always a violation)++ Returns a sequence of violation maps with `:file`, `:module`, `:model`, `:defining-module`, `:violation-type`."+ ([]+ (model-boundary-violations (kondo-config)))+ ([kondo-config]+ (let [ownership (model-ownership)]+ (into []+ (comp+ (mapcat+ (fn [file]+ (try+ (let [ns-symb (-> (ns.file/read-file-ns-decl file)+ ns.parse/name-from-ns-decl)+ mod (module ns-symb)]+ (when (and mod+ (not (contains? model-boundary-exempt-namespaces ns-symb))+ (not= :skip-test (get-in kondo-config [mod :model-imports])))+ (let [model-imports (get-in kondo-config [mod :model-imports] :any)+ models (find-model-keywords file)+ rel-path (file->path-relative-to-project-root file)]+ (for [model models+ :let [defining-mod (get ownership model)]+ :when (not= defining-mod mod)+ :let [model-exports (when defining-mod+ (get-in kondo-config [defining-mod :model-exports] :any))]+ violation-type (model-reference-violations+ model defining-mod model-exports model-imports)]+ {:file rel-path+ :module mod+ :model model+ :defining-module defining-mod+ :violation-type violation-type}))))+ (catch Throwable e+ (throw (ex-info (format "Error checking model boundaries in %s" (str file))+ {:file file}+ e)))))))+ (find-source-files)))))++(comment+ (model-ownership)+ (model-boundary-violations (kondo-config)))diff --git a/src/metabase/notification/send.clj b/src/metabase/notification/send.cljindex 8a95d35f0f7..64f6fd9a963 100644--- a/src/metabase/notification/send.clj+++ b/src/metabase/notification/send.clj@@ -449,6 +449,11 @@:entity_type :card:entity_id card-id}):notification/dashboard (when-let [dashboard-id (or (:dashboard_id payload)+ ;; TODO (Chris 2023-03-19) -- this model oesn't appear to be+ ;; defined anywhere (no defmethod, no migration). Looks like+ ;; dashboard notifications always carry :dashboard_id inline+ ;; via :dashboard_subscription instead.+ ;; Is this dead code?(some->> payload_id(t2/select-one-fn :dashboard_id :model/NotificationDashboard :id)))]{:run_type :subscriptiondiff --git a/test/metabase/core/modules_test.clj b/test/metabase/core/modules_test.cljindex 3848da9d948..3f6f7d121c4 100644--- a/test/metabase/core/modules_test.clj+++ b/test/metabase/core/modules_test.clj@@ -183,3 +183,65 @@moduleused-module(symbol (str/replace used-module #"-rest$" ""))))))++;;;; Model boundary tests++(deftest ^:parallel model-boundaries-test+ (testing "Model boundary enforcement\n"+ (let [ownership (dev.deps-graph/model-ownership)+ known-models (set (keys ownership))+ config (modules-config)+ violations (dev.deps-graph/model-boundary-violations (dev.deps-graph/kondo-config))]+ (testing "No model boundary violations"+ (doseq [{:keys [file module model defining-module violation-type]} violations]+ (testing (format "\n%s (module %s) references %s (defined in %s) — %s violation"+ file module model (or defining-module "unknown") (name violation-type))+ (is (nil? violation-type)))))+ (testing ":model-exports and :model-imports reference valid models"+ (doseq [[module module-config] config]+ (when (set? (:model-exports module-config))+ (doseq [model (:model-exports module-config)]+ (testing (format "\n'%s' :model-exports %s should be a known model" module model)+ (is (contains? known-models model)))))+ (when (set? (:model-imports module-config))+ (doseq [model (:model-imports module-config)]+ (testing (format "\n'%s' :model-imports %s should be a known model" module model)+ (is (contains? known-models model)))))))+ (testing ":model-exports only lists models owned by the module"+ (doseq [[module module-config] config+ :when (set? (:model-exports module-config))+ model (:model-exports module-config)]+ (testing (format "\n'%s' exports %s (owned by %s)" module model (get ownership model))+ (is (= module (get ownership model)))))))))++(deftest ^:parallel model-exports-sorted-test+ (testing "Module :model-exports should be sorted"+ (do-each-module-config+ (fn [module config-zloc]+ (when-let [exports (-> config-zloc+ z/down+ (z/find (fn [zloc]+ (and (n/keyword-node? (z/node zloc))+ (= (z/sexpr zloc) :model-exports))))+ z/right+ z/child-sexprs+ not-empty)]+ (testing (format "\n'%s' module :model-exports" module)+ (is (= (sort exports)+ exports))))))))++(deftest ^:parallel model-imports-sorted-test+ (testing "Module :model-imports should be sorted"+ (do-each-module-config+ (fn [module config-zloc]+ (when-let [imports (-> config-zloc+ z/down+ (z/find (fn [zloc]+ (and (n/keyword-node? (z/node zloc))+ (= (z/sexpr zloc) :model-imports))))+ z/right+ z/child-sexprs+ not-empty)]+ (testing (format "\n'%s' module :model-imports" module)+ (is (= (sort imports)+ imports))))))))