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
fix: improve collections graph performance (#65098)
Edward Paget9aa661155710
diff --git a/e2e/test/scenarios/collections/collections.cy.spec.js b/e2e/test/scenarios/collections/collections.cy.spec.jsindex 7c4bd8c8c7e..a6272bfe202 100644--- a/e2e/test/scenarios/collections/collections.cy.spec.js+++ b/e2e/test/scenarios/collections/collections.cy.spec.js@@ -533,6 +533,7 @@ describe("scenarios > collection defaults", () => {({ body: { groups, revision } }) => {// Give `Data` group permission to "curate" Child collection only// Access to everything else is revoked by default - that's why we chose `Data` group+ groups[DATA_GROUP] = {};groups[DATA_GROUP][CHILD_COLLECTION_ID] = "write";// We're chaining these 2 requestes in order to match schema (passing it from GET to PUT)diff --git a/frontend/src/metabase/admin/permissions/selectors/collection-permissions.ts b/frontend/src/metabase/admin/permissions/selectors/collection-permissions.tsindex 8e326084204..d30dd280a53 100644--- a/frontend/src/metabase/admin/permissions/selectors/collection-permissions.ts+++ b/frontend/src/metabase/admin/permissions/selectors/collection-permissions.ts@@ -188,7 +188,7 @@ const getCollectionPermission = (permissions: CollectionPermissions,groupId: number,collectionId: CollectionId,-) => getIn(permissions, [groupId, collectionId]);+) => getIn(permissions, [groupId, collectionId]) || "none";const getNamespace = (_state: State, props: CollectionIdProps) =>props.namespace;diff --git a/src/metabase/permissions/models/collection/graph.clj b/src/metabase/permissions/models/collection/graph.cljindex 5b9f088e652..6e3cab2a155 100644--- a/src/metabase/permissions/models/collection/graph.clj+++ b/src/metabase/permissions/models/collection/graph.clj@@ -3,19 +3,14 @@for more details and for the code for generating and updating the *data* permissions graph."(:require[clojure.data :as data]- [com.climate.claypoole :as cp][metabase.api.common :as api]- [metabase.app-db.core :as app-db][metabase.audit-app.core :as audit]-[metabase.permissions.models.collection-permission-graph-revision :as c-perm-revision][metabase.permissions.models.permissions :as perms][metabase.permissions.models.permissions-group :as perms-group]- [metabase.permissions.path :as permissions.path][metabase.permissions.util :as perms.u][metabase.premium-features.core :refer [defenterprise]][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -48,76 +43,47 @@[](var-get (requiring-resolve 'metabase.collections.models.collection/root-collection)))-(defn- group-id->permissions-set []- (into {} (for [[group-id perms] (group-by :group_id (t2/select :model/Permissions))]- {group-id (set (map :object perms))})))--(mu/defn- perms-type-for-collection :- CollectionPermissions- [permissions-set collection-or-id]- (cond- (perms/set-has-full-permissions? permissions-set (permissions.path/collection-readwrite-path collection-or-id)) :write- (perms/set-has-full-permissions? permissions-set (permissions.path/collection-read-path collection-or-id)) :read- :else :none))--(mu/defn- group-permissions-graph :- GroupPermissionsGraph- "Return the permissions graph for a single group having `permissions-set`."- [collection-namespace permissions-set collection-ids]- (into- {:root (perms-type-for-collection permissions-set (assoc (root-collection) :namespace collection-namespace))}- (for [collection-id collection-ids]- {collection-id (perms-type-for-collection permissions-set collection-id)})))--(mu/defn- non-personal-collection-ids :- [:set ms/PositiveInt]- "Return a set of IDs of all Collections that are neither Personal Collections nor descendants of Personal- Collections (i.e., things that you can set Permissions for, and that should go in the graph.)"- [collection-namespace :- [:maybe ms/KeywordOrString]]- (let [personal-collection-ids (t2/select-pks-set :model/Collection :personal_owner_id [:not= nil])- honeysql-form {:select [[:id :id]]- :from [:collection]- :where (into [:and- ;; Does 'NULL != "trash"'? Postgres says the answer is undefined, aka- ;; NULL, which... is falsey. :sob:- [:or [:= :type nil] [:not= :type "trash"]]- [:not :archived]- (perms/audit-namespace-clause :namespace (u/qualified-name collection-namespace))- [:= :personal_owner_id nil]]- (for [collection-id personal-collection-ids]- [:not [:like :location (h2x/literal (format "/%d/%%" collection-id))]]))}]- (set (map :id (app-db/query honeysql-form)))))--(defn- calculate-perm-groups [collection-namespace group-id->perms collection-ids]- (into {}- (cp/with-shutdown! [pool (+ 2 (cp/ncpus))]- (doall (cp/upmap pool- (fn [group-id]- [group-id- (group-permissions-graph collection-namespace (group-id->perms group-id) collection-ids)])- (t2/select-pks-set :model/PermissionsGroup))))))-(defn- collection-permission-graph"Return the permission graph for the collections with id in `collection-ids` and the root collection."- ([collection-ids] (collection-permission-graph collection-ids nil))- ([collection-ids collection-namespace]- (let [group-id->perms (group-id->permissions-set)]- {:revision (c-perm-revision/latest-id)- :groups (calculate-perm-groups collection-namespace group-id->perms collection-ids)})))+ [group-perms]+ {:revision (c-perm-revision/latest-id)+ :groups group-perms})(defn- modify-instance-analytics-for-admins"In the graph, override the instance analytics collection within the admin group to read."[graph]- (let [admin-group-id (:id (perms-group/admin))+ (let [admin-group-id (:id (perms-group/admin))audit-collection-id (:id (audit/default-audit-collection))](if (nil? audit-collection-id)graph(assoc-in graph [:groups admin-group-id audit-collection-id] :read))))(mu/defn graph :- PermissionsGraph- "Fetch a graph representing the current permissions status for every group and all permissioned collections. This- works just like the function of the same name in `metabase.permissions.models.permissions`; see also the documentation- for that function.+ "Fetch a sparse graph representing the current permissions status for groups and collections with permissions.++ The returned graph is **sparse**: it only includes entries for groups and collections that have explicit+ permissions (`:read` or `:write`). Groups without any permissions and collections without permissions for a+ given group are omitted from the graph.++ **Exclusions:**+ - Personal collections and their descendants are never included+ - Archived collections are excluded+ - Trash collections are excluded+ - Collections from other namespaces are excluded when `collection-namespace` is specified- The graph is restricted to a given namespace by the optional `collection-namespace` param; by default, `nil`, which- restricts it to the 'default' namespace containing normal Card/Dashboard/Pulse Collections.+ **Parameters:**+ - `collection-namespace` (optional): Restricts the graph to a specific namespace. Default `nil` returns+ collections in the 'default' namespace (normal Card/Dashboard/Pulse Collections).+ - `collection-ids` (optional): When provided, restricts the graph to only the specified collection IDs+ - `group-ids` (optional): When provided, restricts the graph to only the specified permission group IDs++ **Structure:**+ The graph has the structure:+ ```+ {:revision <int>+ :groups {<group-id> {<collection-id> <:read|:write>+ :root <:read|:write>}}}+ ```Note: All Collections are returned at the same level of the 'graph', regardless of how the Collection hierarchy isstructured. Collections do not inherit permissions from ancestor Collections in the same way data permissions are@@ -128,11 +94,93 @@(graph nil))([collection-namespace :- [:maybe ms/KeywordOrString]]- (t2/with-transaction [_conn]- (-> collection-namespace- non-personal-collection-ids- (collection-permission-graph collection-namespace)- modify-instance-analytics-for-admins))))+ (graph collection-namespace nil nil))++ ([collection-namespace :- [:maybe ms/KeywordOrString]+ collection-ids :- [:maybe [:set [:or [:= :root] ms/PositiveInt]]]+ group-ids :- [:maybe [:set ms/PositiveInt]]]+ (let [include-root? (or (nil? collection-ids) (contains? collection-ids :root))+ root-object (str "/collection/"+ (when collection-namespace+ (str "namespace/" (name collection-namespace) "/"))+ "root/")]+ (->> (t2/reducible-query+ {:with [[:eligible_collections+ {:select [:id]+ :from [:collection]+ :where [:and+ [:or [:= :type nil] [:not= :type [:inline "trash"]]]+ (perms/audit-namespace-clause :namespace (u/qualified-name collection-namespace))+ [:not :archived]+ [:= :personal_owner_id nil]+ (let [ids-without-root (disj collection-ids :root)]+ (when (seq ids-without-root)+ [:in :id ids-without-root]))+ [:not [:exists {:select [1]+ :from [[:collection :pc]]+ :where [:and+ [:not= :pc.personal_owner_id nil]+ [:like :collection.location+ [:concat "/" :pc.id "/%"]]]}]]]}]+ [:relevant_permissions+ {:select [:group_id :collection_id :perm_value]+ :from [:permissions]+ :where (into [:and+ [:= :perm_type [:inline "perms/collection-access"]]+ [:not= :collection_id nil]]+ (when (seq group-ids)+ [[:in :group_id group-ids]]))}]]+ :union-all+ [;; Query 1: Root collection permissions, exclude this query if collection-ids are supplied+ ;; and :root is not present in that collection+ {:select [[:pg.id :group_id]+ [nil :collection_id]+ [[:max [:case [:= :p.object [:inline root-object]]+ [:inline 1]+ :else [:inline 0]]] :writable]+ [[:max [:case [:= :p.object [:inline (str root-object "read/")]]+ [:inline 1]+ :else [:inline 0]]] :readable]]+ :from [[:permissions_group :pg]]+ :join [[:permissions :p] [:and+ [:= :p.group_id :pg.id]+ [:or [:= :p.object [:inline root-object]]+ [:= :p.object [:inline (str root-object "read/")]]]]]+ :where (into [:and [:inline include-root?]]+ (when (seq group-ids)+ [[:in :pg.id group-ids]]))+ :group-by [:pg.id]}+ ;; Query 2: Regular collection permissions+ {:select [[:pg.id :group_id]+ [:c.id :collection_id]+ [[:max [:case [:= :p.perm_value [:inline "read-and-write"]]+ [:inline 1]+ :else [:inline 0]]] :writable]+ [[:max [:case [:or [:= :p.perm_value [:inline "read-and-write"]]+ [:= :p.perm_value [:inline "read"]]]+ [:inline 1]+ :else [:inline 0]]] :readable]]+ :from [[:permissions_group :pg]]+ :join [[:relevant_permissions :p] [:= :p.group_id :pg.id]+ [:eligible_collections :c] [:= :p.collection_id :c.id]]+ :where [:not= :c.id nil]+ :group-by [:pg.id :c.id]}+ ;; Query 3: The Administrators group has write access to all collections+ ;; but does not have any explicit permissions.+ {:select [[(u/the-id (perms-group/admin)) :group_id]+ [:c.id :collection_id]+ [[:inline 1] :writable]+ [[:inline 1] :readable]]+ :from [[:eligible_collections :c]]}]})+ (reduce (fn [accum {group-id :group_id collection-id :collection_id :keys [writable readable]}]+ (assoc-in accum [group-id (or collection-id :root)]+ (cond+ (= writable 1) :write+ (= readable 1) :read+ :else :none)))+ {(u/the-id (perms-group/admin)) {:root :write}})+ collection-permission-graph+ modify-instance-analytics-for-admins))));;; -------------------------------------------------- Update Graph --------------------------------------------------@@ -140,8 +188,8 @@"Update the permissions for group ID with `group-id` on collection with ID`collection-id` in the optional `collection-namespace` to `new-collection-perms`."[collection-namespace :- [:maybe ms/KeywordOrString]- group-id :- ms/PositiveInt- collection-id :- [:or [:= :root] ms/PositiveInt]+ group-id :- ms/PositiveInt+ collection-id :- [:or [:= :root] ms/PositiveInt]new-collection-perms :- CollectionPermissions](let [collection-id (if (= collection-id :root)(assoc (root-collection) :namespace collection-namespace)@@ -150,13 +198,13 @@(perms/revoke-collection-permissions! group-id collection-id)(case new-collection-perms:write (perms/grant-collection-readwrite-permissions! group-id collection-id)- :read (perms/grant-collection-read-permissions! group-id collection-id)- :none nil)))+ :read (perms/grant-collection-read-permissions! group-id collection-id)+ :none nil)))(mu/defn- update-group-permissions![collection-namespace :- [:maybe ms/KeywordOrString]- group-id :- ms/PositiveInt- new-group-perms :- GroupPermissionsGraph]+ group-id :- ms/PositiveInt+ new-group-perms :- GroupPermissionsGraph](doseq [[collection-id new-perms] new-group-perms](update-collection-permissions! collection-namespace group-id collection-id new-perms)))@@ -171,7 +219,7 @@[current-revision-number](when api/*current-user-id*(first (t2/insert-returning-instances! :model/CollectionPermissionGraphRevision- :id (inc current-revision-number)+ :id (inc current-revision-number):user_id api/*current-user-id*:before "":after ""))))@@ -182,30 +230,88 @@[revision-id before changes](future (t2/update! :model/CollectionPermissionGraphRevision revision-id {:before before :after changes})))+(defn- personal-collection-ids+ "Return a set of IDs from `collection-ids` that are personal Collections or descendants of personal Collections.+ These should never appear in permission graphs or be editable via the graph API."+ [collection-ids]+ (when (seq (disj collection-ids :root))+ (t2/select-pks-set :model/Collection+ {:where [:and+ [:in :id (disj collection-ids :root)]+ [:or [:not= :personal_owner_id nil]+ [:exists {:select [1]+ :from [[:collection :pc]]+ :where [:and+ [:not= :pc.personal_owner_id nil]+ [:like :collection.location+ [:concat "/" :pc.id "/%"]]]}]]]})))++(defn- remove-personal-collections-from-graph+ "Remove any personal collection IDs from the graph. Personal collections cannot be edited via the graph API."+ [graph collection-ids]+ (let [personal-ids (personal-collection-ids collection-ids)]+ (cond-> graph+ (seq personal-ids) (update :groups update-vals #(apply dissoc % personal-ids)))))++(defn- remove-collections-from-other-namespaces+ "Remove any collection IDs from the graph that belong to another namespace from the graph being updated."+ [graph collection-ids namespace]+ (let [other-ns-ids (when (seq (disj collection-ids :root))+ ;; This query selects collection IDs that don't match the target namespace:+ ;; - If target namespace is non-nil: collections with different non-nil namespaces OR nil namespaces+ ;; - If target namespace is nil: collections with any non-nil namespace+ (t2/select-pks-set :model/Collection {:where [:and [:in :id (disj collection-ids :root)]+ (cond-> [:or [:not= :namespace (some-> namespace name)]]+ (some? namespace) (into [[:= :namespace nil]]))]}))]+ (cond-> graph+ (seq other-ns-ids) (update :groups update-vals #(apply dissoc % other-ns-ids)))))+(mu/defn update-graph!"Update the Collections permissions graph for Collections of `collection-namespace` (default `nil`, the 'default'namespace). This works just like [[metabase.models.permission/update-data-perms-graph!]], but for Collections;refer to that function's extensive documentation to get a sense for how this works.- If there are no changes, returns nil.- If there are changes, returns the future that is used to call `fill-revision-details!`.- To run this syncronously deref the non-nil return value."+ **Automatic Filtering:**+ The following collection IDs are automatically filtered from `new-graph` before processing:+ - Personal collections and their descendants (cannot be edited via the graph API)+ - Collections belonging to namespaces other than `collection-namespace` (prevents cross-namespace edits)++ This filtering ensures that:+ 1. Attempts to modify personal collection permissions are silently ignored+ 2. Namespace isolation is maintained+ 3. Only valid, permissioned collections are processed++ **Permissions Values:**+ Each group/collection pair in the graph can have one of three values:+ - `:write` - Full read and write access+ - `:read` - Read-only access+ - `:none` - No access (revokes existing permissions)++ **Return Value:**+ - Returns `nil` if there are no changes to apply+ - Returns a `Future` if changes were made (used to populate revision details asynchronously)+ - To run synchronously, deref the non-nil return value: `@(update-graph! ...)`++ **Revision Tracking:**+ All changes are tracked in `CollectionPermissionGraphRevision` for auditing purposes. The revision number+ is checked to prevent concurrent modification conflicts (unless `force?` is true)."([new-graph](update-graph! nil new-graph false))([collection-namespace :- [:maybe ms/KeywordOrString]- new-graph :- PermissionsGraph- force? :- [:maybe boolean?]]- (let [old-graph (graph collection-namespace)- old-perms (:groups old-graph)- new-perms (:groups new-graph)- ;; filter out any groups not in the old graph- new-perms (select-keys new-perms (keys old-perms))- ;; filter out any collections not in the old graph- new-perms (into {} (for [[group-id collection-id->perms] new-perms]- [group-id (select-keys collection-id->perms (keys (get old-perms group-id)))]))- [diff-old changes] (data/diff old-perms new-perms)]- (when-not force? (perms.u/check-revision-numbers old-graph new-graph))+ new-graph :- PermissionsGraph+ force? :- [:maybe boolean?]]+ (let [new-group-ids (-> new-graph :groups keys set)+ new-collection-ids (->> new-graph :groups vals (mapcat keys) set)+ filtered-new-graph (-> (remove-personal-collections-from-graph new-graph new-collection-ids)+ (remove-collections-from-other-namespaces new-collection-ids collection-namespace))+ old-graph (graph collection-namespace new-collection-ids new-group-ids)+ ;; the new graph requires permissions to be included explicitly -- it's a fragment rather than a sparse graph+ ;; once we've removed illegal collections like personal collections or collections from other namespaces+ [diff-old changes] (data/diff (:groups old-graph) (->> (:groups filtered-new-graph)+ (filter (comp seq second))+ (into {})))]+ (when-not force? (perms.u/check-revision-numbers old-graph filtered-new-graph))(when (seq changes)(let [revision-id (t2/with-transaction [_conn](doseq [[group-id changes] changes]diff --git a/test/metabase/permissions/models/collection/graph_test.clj b/test/metabase/permissions/models/collection/graph_test.cljindex 1530d1cd300..c3c6ec69a07 100644--- a/test/metabase/permissions/models/collection/graph_test.clj+++ b/test/metabase/permissions/models/collection/graph_test.clj@@ -27,7 +27,7 @@(replace-collection-ids collection-or-id graph :COLLECTION))([collection-or-id graph replacement-key]- (let [id (if (map? collection-or-id) (:id collection-or-id) collection-or-id)+ (let [id (if (map? collection-or-id) (:id collection-or-id) collection-or-id);; match variations that pop up depending on whether the map was serialized to JSON. 100, :100, or "100"id-keys #{id (str id) (keyword (str id))}](update graph :groups (partial m/map-vals (partial m/map-keys (fn [collection-id]@@ -71,30 +71,27 @@(only-collections (cons :root collections))))(deftest basic-test- (testing "Check that the basic graph works"+ (testing "Check that the basic graph works (sparse - only groups with permissions)"(mt/with-non-admin-groups-no-root-collection-perms(is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}}}(graph :clear-revisions? true))))))(deftest new-collection-perms-test- (testing "Creating a new Collection shouldn't give perms to anyone but admins"+ (testing "Creating a new Collection shouldn't give perms to anyone but admins (sparse - no :none entries)"(mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection collection](is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none, :COLLECTION :none}- (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}(replace-collection-ids collection (graph :clear-revisions? true, :collections [collection]))))))))(deftest audit-collections-graph-test- (testing "Check that the audit collection has :read for admins."+ (testing "Check that the audit collection has :read for admins (sparse - no :none entries)."(mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection collection {}](with-redefs [audit/default-audit-collection (constantly collection)](is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none, :COLLECTION :none}- (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :read}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write, :COLLECTION :read}}}(replace-collection-ids collection (graph :clear-revisions? true, :collections [collection])))))))))(deftest read-perms-test@@ -103,8 +100,8 @@(mt/with-temp [:model/Collection collection](perms/grant-collection-read-permissions! (perms-group/all-users) collection)(is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none, :COLLECTION :read}- (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}+ :groups {(u/the-id (perms-group/all-users)) {:COLLECTION :read}+ (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}(replace-collection-ids collection (graph :clear-revisions? true, :collections [collection]))))))))(deftest grant-write-perms-for-new-collections-test@@ -112,30 +109,27 @@(mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection collection](perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)- (is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none, :COLLECTION :write}- (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}- (replace-collection-ids collection (graph :clear-revisions? true, :collections [collection]))))))))+ (is (= {:revision 0+ :groups {(u/the-id (perms-group/all-users)) {:COLLECTION :write}+ (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}+ (replace-collection-ids collection (graph :clear-revisions? true, :collections [collection]))))))))(deftest non-magical-groups-test- (testing "make sure a non-magical group will show up"+ (testing "sparse graph - groups without permissions don't appear"(mt/with-temp [:model/PermissionsGroup new-group](mt/with-non-admin-groups-no-root-collection-perms- (is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}- (u/the-id new-group) {:root :none}}}- (graph :clear-revisions? true, :groups [new-group])))))))+ (is (= {:revision 0+ :groups {(u/the-id (perms-group/admin)) {:root :write}}}+ (graph :clear-revisions? true, :groups [new-group])))))))(deftest root-collection-read-perms-test- (testing "How abut *read* permissions for the Root Collection?"+ (testing "How about *read* permissions for the Root Collection?"(mt/with-temp [:model/PermissionsGroup new-group](mt/with-non-admin-groups-no-root-collection-perms(perms/grant-collection-read-permissions! new-group collection/root-collection)(is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}- (u/the-id new-group) {:root :read}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}+ (u/the-id new-group) {:root :read}}}(graph :clear-revisions? true, :groups [new-group])))))))(deftest root-collection-write-perms-test@@ -144,9 +138,8 @@(mt/with-non-admin-groups-no-root-collection-perms(perms/grant-collection-readwrite-permissions! new-group collection/root-collection)(is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}- (u/the-id new-group) {:root :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}+ (u/the-id new-group) {:root :write}}}(graph :clear-revisions? true, :groups [new-group])))))))(deftest no-op-test@@ -157,8 +150,7 @@(binding [*current-user-id* (mt/user->id :crowberto)](graph/update-graph! (graph :clear-revisions? true))(is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}}}(graph))"revision should not have changed, because there was nothing to do...")))))@@ -172,8 +164,8 @@[:groups (u/the-id (perms-group/all-users)) (u/the-id collection)]:read))(is (= {:revision 1- :groups {(u/the-id (perms-group/all-users)) {:root :none, :COLLECTION :read}- (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}+ :groups {(u/the-id (perms-group/all-users)) {:COLLECTION :read}+ (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}(replace-collection-ids collection (graph :collections [collection]))))(is (= 1 (c-perm-revision/latest-id)))))))@@ -185,12 +177,12 @@[:groups (u/the-id (perms-group/all-users)) (u/the-id collection)]:write))(is (= {:revision 1- :groups {(u/the-id (perms-group/all-users)) {:root :none, :COLLECTION :write}- (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}+ :groups {(u/the-id (perms-group/all-users)) {:COLLECTION :write}+ (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}(replace-collection-ids collection (graph :collections [collection])))))))))(deftest revoke-perms-test- (testing "can we *revoke* perms?"+ (testing "can we *revoke* perms? (sparse - revoked perms don't appear)"(clear-graph-revisions!)(mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection collection]@@ -200,8 +192,7 @@[:groups (u/the-id (perms-group/all-users)) (u/the-id collection)]:none))(is (= {:revision 1- :groups {(u/the-id (perms-group/all-users)) {:root :none, :COLLECTION :none}- (u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write, :COLLECTION :write}}}(replace-collection-ids collection (graph :collections [collection])))))))))(deftest grant-root-permissions-test@@ -214,9 +205,8 @@[:groups (u/the-id new-group) :root]:read))(is (= {:revision 1- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}- (u/the-id new-group) {:root :read}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}+ (u/the-id new-group) {:root :read}}}(graph :groups [new-group])))))))(testing "How about granting *write* permissions for the Root Collection?"@@ -228,13 +218,12 @@[:groups (u/the-id new-group) :root]:write))(is (= {:revision 1- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}- (u/the-id new-group) {:root :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}+ (u/the-id new-group) {:root :write}}}(graph :groups [new-group]))))))))(deftest revoke-root-permissions-test- (testing "can we *revoke* RootCollection perms?"+ (testing "can we *revoke* RootCollection perms? (sparse - revoked perms don't appear)"(mt/with-temp [:model/PermissionsGroup new-group](clear-graph-revisions!)(mt/with-non-admin-groups-no-root-collection-perms@@ -244,17 +233,14 @@[:groups (u/the-id new-group) :root]:none))(is (= {:revision 1- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}- (u/the-id new-group) {:root :none}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}}}(graph :groups [new-group]))))))))(deftest personal-collections-should-not-appear-test(testing "Make sure that personal Collections *do not* appear in the Collections graph"(mt/with-non-admin-groups-no-root-collection-perms(is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}}}(graph :clear-revisions? true)))))(testing "Make sure descendants of Personal Collections do not come back as part of the graph either..."@@ -262,22 +248,20 @@(mt/with-non-admin-groups-no-root-collection-perms(mt/with-temp [:model/Collection _ {:location (lucky-collection-children-location)}](is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}}}(graph)))))))(deftest disallow-editing-personal-collections-test(testing "Make sure that if we try to be sneaky and edit a Personal Collection via the graph, changes are ignored"(mt/with-non-admin-groups-no-root-collection-perms(let [lucky-personal-collection-id (u/the-id (collection/user->personal-collection (mt/user->id :lucky)))- path [:groups (u/the-id (perms-group/all-users)) lucky-personal-collection-id]]+ path [:groups (u/the-id (perms-group/all-users)) lucky-personal-collection-id]](mt/throw-if-called! graph/update-group-permissions!(graph/update-graph! (assoc-in (graph :clear-revisions? true) path :read)))(testing "double-check that the graph is unchanged"(is (= {:revision 0- :groups {(u/the-id (perms-group/all-users)) {:root :none}- (u/the-id (perms-group/admin)) {:root :write}}}+ :groups {(u/the-id (perms-group/admin)) {:root :write}}}(graph))))(testing "No revision should have been saved"@@ -306,18 +290,18 @@;; Block until the entire graph has been `filled-in!`@future)))-(deftest collection-namespace-test- (testing "The permissions graph should be namespace-aware.\n"+(deftest collection-namespace-fetch-default-test+ (testing "Fetching graph with no args should only show Collections in the default namespace (sparse - no :none entries)"(mt/with-non-admin-groups-no-root-collection-perms- (mt/with-temp [:model/Collection {default-a :id} {:location "/"}- :model/Collection {default-ab :id} {:location (format "/%d/" default-a)}- :model/Collection {currency-a :id} {:namespace "currency" :location "/"}+ (mt/with-temp [:model/Collection {default-a :id} {:location "/"}+ :model/Collection {default-ab :id} {:location (format "/%d/" default-a)}+ :model/Collection {currency-a :id} {:namespace "currency" :location "/"}:model/Collection {currency-ab :id} {:namespace "currency" :location (format "/%d/" currency-a)}:model/PermissionsGroup {group-id :id} {}](letfn [(nice-graph [graph]- (let [id->alias {default-a "Default A"- default-ab "Default A -> B"- currency-a "Currency A"+ (let [id->alias {default-a "Default A"+ default-ab "Default A -> B"+ currency-a "Currency A"currency-ab "Currency A -> B"}](transduceidentity@@ -331,84 +315,221 @@id->alias)))](doseq [collection [default-a default-ab currency-a currency-ab]](perms/grant-collection-read-permissions! group-id collection))- (testing "Calling (graph) with no args should only show Collections in the default namespace"- (is (= {"Default A" :read, "Default A -> B" :read, :root :none}- (nice-graph (graph/graph))- (nice-graph (graph/graph nil)))))+ (is (= {"Default A" :read, "Default A -> B" :read}+ (nice-graph (graph/graph))+ (nice-graph (graph/graph nil)))))))))- (testing "You should be able to pass an different namespace to (graph) to see Collections in that namespace"- (is (= {"Currency A" :read, "Currency A -> B" :read, :root :none}- (nice-graph (graph/graph :currency)))))+(deftest collection-namespace-fetch-non-default-test+ (testing "Fetching graph for a specific namespace should only show Collections in that namespace (sparse - no :none)"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {default-a :id} {:location "/"}+ :model/Collection {default-ab :id} {:location (format "/%d/" default-a)}+ :model/Collection {currency-a :id} {:namespace "currency" :location "/"}+ :model/Collection {currency-ab :id} {:namespace "currency" :location (format "/%d/" currency-a)}+ :model/PermissionsGroup {group-id :id} {}]+ (letfn [(nice-graph [graph]+ (let [id->alias {default-a "Default A"+ default-ab "Default A -> B"+ currency-a "Currency A"+ currency-ab "Currency A -> B"}]+ (transduce+ identity+ (fn+ ([graph]+ (-> (get-in graph [:groups group-id])+ (select-keys (cons :root (vals id->alias)))))+ ([graph [collection-id k]]+ (replace-collection-ids collection-id graph k)))+ graph+ id->alias)))]+ (doseq [collection [default-a default-ab currency-a currency-ab]]+ (perms/grant-collection-read-permissions! group-id collection))+ (is (= {"Currency A" :read, "Currency A -> B" :read}+ (nice-graph (graph/graph :currency)))))))))- ;; bind a current user so CollectionPermissionGraphRevisions get saved.+(deftest collection-namespace-update-default-test+ (testing "Should be able to update the graph for the default namespace"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {default-a :id} {:location "/"}+ :model/Collection {default-ab :id} {:location (format "/%d/" default-a)}+ :model/Collection {currency-a :id} {:namespace "currency" :location "/"}+ :model/Collection {currency-ab :id} {:namespace "currency" :location (format "/%d/" currency-a)}+ :model/PermissionsGroup {group-id :id} {}]+ (letfn [(nice-graph [graph]+ (let [id->alias {default-a "Default A"+ default-ab "Default A -> B"+ currency-a "Currency A"+ currency-ab "Currency A -> B"}]+ (transduce+ identity+ (fn+ ([graph]+ (-> (get-in graph [:groups group-id])+ (select-keys (cons :root (vals id->alias)))))+ ([graph [collection-id k]]+ (replace-collection-ids collection-id graph k)))+ graph+ id->alias)))]+ (doseq [collection [default-a default-ab currency-a currency-ab]]+ (perms/grant-collection-read-permissions! group-id collection))(mt/with-test-user :crowberto- (testing "Should be able to update the graph for the default namespace.\n"- (let [before (graph/graph)]- (update-graph-and-wait! (assoc before :groups {group-id {default-ab :write, currency-ab :write}}))- (is (= {"Default A" :read, "Default A -> B" :write, :root :none}- (nice-graph (graph/graph))))-- (testing "Updates to Collections in other namespaces should be ignored"- (is (= {"Currency A" :read, "Currency A -> B" :read, :root :none}- (nice-graph (graph/graph :currency)))))-- (testing "A CollectionPermissionGraphRevision recording the *changes* to the perms graph should be saved."- (is (malli= [:map- [:id ms/PositiveInt]- [:before [:fn #(= % (mt/obj->json->obj (assoc before :namespace nil)))]]- [:after [:fn #(= % {(keyword (str group-id)) {(keyword (str default-ab)) "write"}})]]- [:user_id [:= (mt/user->id :crowberto)]]- [:created_at (ms/InstanceOfClass java.time.temporal.Temporal)]]- (t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]}))))))-- (testing "Should be able to update the graph for a non-default namespace.\n"- (let [before (graph/graph :currency)]- @(graph/update-graph! :currency (assoc (graph/graph) :groups {group-id {default-a :write, currency-a :write}}) false)- (is (= {"Currency A" :write, "Currency A -> B" :read, :root :none}- (nice-graph (graph/graph :currency))))-- (testing "Updates to Collections in other namespaces should be ignored"- (is (= {"Default A" :read, "Default A -> B" :write, :root :none}- (nice-graph (graph/graph)))))-- (testing "A CollectionPermissionGraphRevision recording the *changes* to the perms graph should be saved."- (is (malli= [:map- [:id ms/PositiveInt]- [:before [:fn #(= % (mt/obj->json->obj (assoc before :namespace "currency")))]]- [:after [:fn #(= % {(keyword (str group-id)) {(keyword (str currency-a)) "write"}})]]- [:user_id [:= (mt/user->id :crowberto)]]- [:created_at (ms/InstanceOfClass java.time.temporal.Temporal)]]- (t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]}))))))-- (testing "should be able to update permissions for the Root Collection in the default namespace via the graph"- (update-graph-and-wait! (assoc (graph/graph) :groups {group-id {:root :read}}))- (is (= {:root :read, "Default A" :read, "Default A -> B" :write}+ (let [before (graph/graph)]+ (update-graph-and-wait! (assoc before :groups {group-id {default-ab :write, currency-ab :write}}))+ (is (= {"Default A" :read, "Default A -> B" :write}(nice-graph (graph/graph))))- (testing "\nshouldn't affect Root Collection perms for non-default namespaces"- (is (= {:root :none, "Currency A" :write, "Currency A -> B" :read}+ (testing "Updates to Collections in other namespaces should be ignored"+ (is (= {"Currency A" :read, "Currency A -> B" :read}(nice-graph (graph/graph :currency)))))- (testing "A CollectionPermissionGraphRevision recording the *changes* to the perms graph should be saved."- (is (=? {:before {:namespace nil- :groups {(keyword (str group-id)) {:root "none"}}}- :after {(keyword (str group-id)) {:root "read"}}}- (t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]})))))-- (testing "should be able to update permissions for Root Collection in non-default namespace"- (update-graph-and-wait! :currency (assoc (graph/graph :currency) :groups {group-id {:root :write}}))- (is (= {:root :write, "Currency A" :write, "Currency A -> B" :read}- (nice-graph (graph/graph :currency))))-- (testing "\nshouldn't affect Root Collection perms for default namespace"- (is (= {:root :read, "Default A" :read, "Default A -> B" :write}- (nice-graph (graph/graph)))))+ (testing "A CollectionPermissionGraphRevision recording the *changes* should be saved (sparse before/after)"+ (is (malli= [:map+ [:id ms/PositiveInt]+ [:before [:map]]+ [:after [:fn #(= % {(keyword (str group-id)) {(keyword (str default-ab)) "write"}})]]+ [:user_id [:= (mt/user->id :crowberto)]]+ [:created_at (ms/InstanceOfClass java.time.temporal.Temporal)]]+ (t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]})))))))))))++(deftest collection-namespace-update-non-default-test+ (testing "Should be able to update the graph for a non-default namespace"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {default-a :id} {:location "/"}+ :model/Collection {default-ab :id} {:location (format "/%d/" default-a)}+ :model/Collection {currency-a :id} {:namespace "currency" :location "/"}+ :model/Collection {currency-ab :id} {:namespace "currency" :location (format "/%d/" currency-a)}+ :model/PermissionsGroup {group-id :id} {}]+ (letfn [(nice-graph [graph]+ (let [id->alias {default-a "Default A"+ default-ab "Default A -> B"+ currency-a "Currency A"+ currency-ab "Currency A -> B"}]+ (transduce+ identity+ (fn+ ([graph]+ (-> (get-in graph [:groups group-id])+ (select-keys (cons :root (vals id->alias)))))+ ([graph [collection-id k]]+ (replace-collection-ids collection-id graph k)))+ graph+ id->alias)))]+ (doseq [collection [default-a default-ab currency-a currency-ab]]+ (perms/grant-collection-read-permissions! group-id collection))+ ;; First update default namespace to set up state+ (mt/with-test-user :crowberto+ (let [before-default (graph/graph)]+ (update-graph-and-wait! (assoc before-default :groups {group-id {default-ab :write, currency-ab :write}})))+ ;; Now update currency namespace+ @(graph/update-graph! :currency (assoc (graph/graph) :groups {group-id {default-a :write, currency-a :write}}) false)+ (is (= {"Currency A" :write, "Currency A -> B" :read}+ (nice-graph (graph/graph :currency))))++ (testing "Updates to Collections in other namespaces should be ignored"+ (is (= {"Default A" :read, "Default A -> B" :write}+ (nice-graph (graph/graph)))))++ (testing "A CollectionPermissionGraphRevision recording the *changes* should be saved (sparse before/after)"+ (is (malli= [:map+ [:id ms/PositiveInt]+ [:before [:map]]+ [:after [:fn #(= % {(keyword (str group-id)) {(keyword (str currency-a)) "write"}})]]+ [:user_id [:= (mt/user->id :crowberto)]]+ [:created_at (ms/InstanceOfClass java.time.temporal.Temporal)]]+ (t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]}))))))))))++(deftest collection-namespace-update-root-default-test+ (testing "Should be able to update permissions for the Root Collection in the default namespace"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {default-a :id} {:location "/"}+ :model/Collection {default-ab :id} {:location (format "/%d/" default-a)}+ :model/Collection {currency-a :id} {:namespace "currency" :location "/"}+ :model/Collection {currency-ab :id} {:namespace "currency" :location (format "/%d/" currency-a)}+ :model/PermissionsGroup {group-id :id} {}]+ (letfn [(nice-graph [graph]+ (let [id->alias {default-a "Default A"+ default-ab "Default A -> B"+ currency-a "Currency A"+ currency-ab "Currency A -> B"}]+ (transduce+ identity+ (fn+ ([graph]+ (-> (get-in graph [:groups group-id])+ (select-keys (cons :root (vals id->alias)))))+ ([graph [collection-id k]]+ (replace-collection-ids collection-id graph k)))+ graph+ id->alias)))]+ (doseq [collection [default-a default-ab currency-a currency-ab]]+ (perms/grant-collection-read-permissions! group-id collection))+ ;; Set up state with default namespace update+ (mt/with-test-user :crowberto+ (let [before-default (graph/graph)]+ (update-graph-and-wait! (assoc before-default :groups {group-id {default-ab :write, currency-ab :write}})))+ ;; Update currency namespace+ @(graph/update-graph! :currency (assoc (graph/graph) :groups {group-id {default-a :write, currency-a :write}}) false)+ ;; Now update root collection+ (update-graph-and-wait! (assoc (graph/graph) :groups {group-id {:root :read}}))+ (is (= {:root :read, "Default A" :read, "Default A -> B" :write}+ (nice-graph (graph/graph))))++ (testing "Shouldn't affect Root Collection perms for non-default namespaces (sparse - no :root entry)"+ (is (= {"Currency A" :write, "Currency A -> B" :read}+ (nice-graph (graph/graph :currency)))))++ (testing "A CollectionPermissionGraphRevision recording the *changes* should be saved (sparse - no :root in before)"+ (is (=? {:before {:namespace nil+ :groups {}}+ :after {(keyword (str group-id)) {:root "read"}}}+ (t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]}))))))))))++(deftest collection-namespace-update-root-non-default-test+ (testing "Should be able to update permissions for Root Collection in non-default namespace"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {default-a :id} {:location "/"}+ :model/Collection {default-ab :id} {:location (format "/%d/" default-a)}+ :model/Collection {currency-a :id} {:namespace "currency" :location "/"}+ :model/Collection {currency-ab :id} {:namespace "currency" :location (format "/%d/" currency-a)}+ :model/PermissionsGroup {group-id :id} {}]+ (letfn [(nice-graph [graph]+ (let [id->alias {default-a "Default A"+ default-ab "Default A -> B"+ currency-a "Currency A"+ currency-ab "Currency A -> B"}]+ (transduce+ identity+ (fn+ ([graph]+ (-> (get-in graph [:groups group-id])+ (select-keys (cons :root (vals id->alias)))))+ ([graph [collection-id k]]+ (replace-collection-ids collection-id graph k)))+ graph+ id->alias)))]+ (doseq [collection [default-a default-ab currency-a currency-ab]]+ (perms/grant-collection-read-permissions! group-id collection))+ ;; Set up all previous state+ (mt/with-test-user :crowberto+ (let [before-default (graph/graph)]+ (update-graph-and-wait! (assoc before-default :groups {group-id {default-ab :write, currency-ab :write}})))+ (let [before-currency (graph/graph :currency)]+ @(graph/update-graph! :currency (assoc before-currency :groups {group-id {default-a :write, currency-a :write}}) false))+ (update-graph-and-wait! (assoc (graph/graph) :groups {group-id {:root :read}}))+ ;; Now update root for currency namespace+ (update-graph-and-wait! :currency (assoc (graph/graph :currency) :groups {group-id {:root :write}}))+ (is (= {:root :write, "Currency A" :write, "Currency A -> B" :read}+ (nice-graph (graph/graph :currency))))++ (testing "Shouldn't affect Root Collection perms for default namespace"+ (is (= {:root :read, "Default A" :read, "Default A -> B" :write}+ (nice-graph (graph/graph)))))- (testing "A CollectionPermissionGraphRevision recording the *changes* to the perms graph should be saved."- (is (=? {:before {:namespace "currency"- :groups {(keyword (str group-id)) {:root "none"}}}- :after {(keyword (str group-id)) {:root "write"}}}- (t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]})))))))))))+ (testing "A CollectionPermissionGraphRevision recording the *changes* should be saved (sparse - no :root in before)"+ (is (=? {:before {:namespace "currency"+ :groups {}}+ :after {(keyword (str group-id)) {:root "write"}}}+ (t2/select-one :model/CollectionPermissionGraphRevision {:order-by [[:id :desc]]}))))))))))(defn- do-with-n-temp-users-with-personal-collections! [num-users thunk](mt/with-model-cleanup [:model/User :model/Collection]@@ -420,15 +541,15 @@:id %)user-ids)](t2/query {:insert-into (t2/table-name :model/User)- :values values})+ :values values})(assert (= (count user-ids) num-users));; insert the Collections(t2/query {:insert-into (t2/table-name :model/Collection)- :values (for [user-id user-ids- :let [collection (mt/with-temp-defaults :model/Collection)]]- (assoc collection- :personal_owner_id user-id- :slug "my_collection"))}))+ :values (for [user-id user-ids+ :let [collection (mt/with-temp-defaults :model/Collection)]]+ (assoc collection+ :personal_owner_id user-id+ :slug "my_collection"))}));; now run the thunk(thunk)))