You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by be...@apache.org on 2025/12/18 00:35:00 UTC

(superset) branch new-dar updated: UI progress

This is an automated email from the ASF dual-hosted git repository.

beto pushed a commit to branch new-dar
in repository https://gitbox.apache.org/repos/asf/superset.git


The following commit(s) were added to refs/heads/new-dar by this push:
     new ca7635dfc2 UI progress
ca7635dfc2 is described below

commit ca7635dfc27d5826001f7380f07152b11e2f336e
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Wed Dec 17 19:34:52 2025 -0500

    UI progress
---
 .../dataAccessRules/PermissionsTree/index.tsx      | 34 ++++--------
 .../dataAccessRules/PermissionsTree/types.ts       |  1 -
 .../dataAccessRules/PermissionsTree/utils.ts       |  4 +-
 superset/data_access_rules/utils.py                | 61 ++++++++++++++++++++++
 superset/utils/filters.py                          | 56 ++++++++++++++------
 5 files changed, 111 insertions(+), 45 deletions(-)

diff --git a/superset-frontend/src/features/dataAccessRules/PermissionsTree/index.tsx b/superset-frontend/src/features/dataAccessRules/PermissionsTree/index.tsx
index 2218c0eef9..892895a67d 100644
--- a/superset-frontend/src/features/dataAccessRules/PermissionsTree/index.tsx
+++ b/superset-frontend/src/features/dataAccessRules/PermissionsTree/index.tsx
@@ -17,10 +17,10 @@
  * under the License.
  */
 
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
 import { t } from '@superset-ui/core';
 import { css, styled } from '@apache-superset/core/ui';
-import { Tree, Input, Tooltip, Spin, Button } from 'antd';
+import { Tree, Tooltip, Spin, Button } from 'antd';
 import {
   CheckCircleOutlined,
   CloseCircleOutlined,
@@ -32,7 +32,6 @@ import {
 import type { TreeProps } from 'antd';
 import type {
   PermissionNode,
-  PermissionState,
   TreeState,
   PermissionsPayload,
 } from './types';
@@ -45,7 +44,6 @@ import {
 } from './api';
 import {
   makeKey,
-  parseKey,
   getEffectiveState,
   getExplicitState,
   cyclePermissionState,
@@ -129,7 +127,6 @@ function PermissionsTree({
     loadedKeys: [],
     treeData: [],
     permissionStates: {},
-    searchValue: '',
   });
   const [loading, setLoading] = useState(false);
   const [databases, setDatabases] = useState<DatabaseInfo[]>([]);
@@ -146,7 +143,7 @@ function PermissionsTree({
   }, [databases]);
 
   // Track if we're in the middle of an internal update to avoid circular updates
-  const [isInternalUpdate, setIsInternalUpdate] = useState(false);
+  const isInternalUpdateRef = useRef(false);
 
   // Load initial databases
   useEffect(() => {
@@ -155,8 +152,8 @@ function PermissionsTree({
 
   // Load initial value (only on mount or when value changes externally)
   useEffect(() => {
-    if (isInternalUpdate) {
-      setIsInternalUpdate(false);
+    if (isInternalUpdateRef.current) {
+      isInternalUpdateRef.current = false;
       return;
     }
     if (value && databaseMaps.nameToId.size > 0) {
@@ -342,7 +339,7 @@ function PermissionsTree({
     const newStates = cyclePermissionState(nodeKey, treeState.permissionStates);
 
     // Mark as internal update to prevent circular updates
-    setIsInternalUpdate(true);
+    isInternalUpdateRef.current = true;
 
     setTreeState(prev => ({
       ...prev,
@@ -419,6 +416,7 @@ function PermissionsTree({
     const nodeKey = node.key as string;
     const isExpanded = treeState.expandedKeys.includes(nodeKey);
     const isLeaf = node.isLeaf || node.nodeType === 'table';
+    const title = node.title as string;
 
     // Count descendants with custom permissions when collapsed
     const counts =
@@ -431,7 +429,7 @@ function PermissionsTree({
       <div className="node-title">
         {getStateIcon(nodeKey)}
         {getNodeIcon(node.nodeType)}
-        <span>{node.title as string}</span>
+        <span>{title}</span>
         {hasCustomRules && (
           <span className="node-count">
             (
@@ -454,15 +452,8 @@ function PermissionsTree({
     );
   };
 
-  const onSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
-    setTreeState(prev => ({
-      ...prev,
-      searchValue: e.target.value,
-    }));
-  };
-
   const clearAll = () => {
-    setIsInternalUpdate(true);
+    isInternalUpdateRef.current = true;
     setTreeState(prev => ({
       ...prev,
       permissionStates: {},
@@ -474,13 +465,6 @@ function PermissionsTree({
 
   return (
     <StyledContainer>
-      <Input.Search
-        className="search-input"
-        placeholder={t('Search databases, schemas, tables...')}
-        onChange={onSearch}
-        value={treeState.searchValue}
-        allowClear
-      />
       <div style={{ marginBottom: 8 }}>
         <Button size="small" onClick={clearAll}>
           {t('Reset All')}
diff --git a/superset-frontend/src/features/dataAccessRules/PermissionsTree/types.ts b/superset-frontend/src/features/dataAccessRules/PermissionsTree/types.ts
index 86071dd2cc..5a91f254d3 100644
--- a/superset-frontend/src/features/dataAccessRules/PermissionsTree/types.ts
+++ b/superset-frontend/src/features/dataAccessRules/PermissionsTree/types.ts
@@ -43,7 +43,6 @@ export interface TreeState {
   loadedKeys: string[];
   treeData: PermissionNode[];
   permissionStates: Record<string, PermissionState>;
-  searchValue: string;
 }
 
 export interface PermissionsPayload {
diff --git a/superset-frontend/src/features/dataAccessRules/PermissionsTree/utils.ts b/superset-frontend/src/features/dataAccessRules/PermissionsTree/utils.ts
index 78f14df347..b18a775eb1 100644
--- a/superset-frontend/src/features/dataAccessRules/PermissionsTree/utils.ts
+++ b/superset-frontend/src/features/dataAccessRules/PermissionsTree/utils.ts
@@ -190,7 +190,7 @@ function clearDescendantStates(
  */
 function isDescendantOf(childKey: string, ancestorKey: string): boolean {
   // A key is a descendant if it starts with the ancestor key + '|'
-  return childKey.startsWith(ancestorKey + '|');
+  return childKey.startsWith(`${ancestorKey}|`);
 }
 
 /**
@@ -245,7 +245,7 @@ export function countDescendantPermissions(
  * Check if a key is a direct child of another key.
  */
 function isDirectChildOf(childKey: string, parentKey: string): boolean {
-  if (!childKey.startsWith(parentKey + '|')) {
+  if (!childKey.startsWith(`${parentKey}|`)) {
     return false;
   }
   // Count the number of '|' segments after the parent
diff --git a/superset/data_access_rules/utils.py b/superset/data_access_rules/utils.py
index c56d9268f2..b36c82fe6b 100644
--- a/superset/data_access_rules/utils.py
+++ b/superset/data_access_rules/utils.py
@@ -742,6 +742,67 @@ class AllowedTable:
     catalog: str | None = None
 
 
+@dataclass
+class AllowedEntry:
+    """
+    An allowed entry from DAR at any level of the hierarchy.
+
+    Fields may be None to indicate "all" at that level:
+    - database only: all catalogs/schemas/tables in that database
+    - database + catalog: all schemas/tables in that catalog
+    - database + schema: all tables in that schema (for DBs without catalogs)
+    - database + catalog + schema: all tables in that schema
+    - database + schema + table: specific table (for DBs without catalogs)
+    - database + catalog + schema + table: specific table
+    """
+
+    database: str
+    catalog: str | None = None
+    schema: str | None = None
+    table: str | None = None
+
+
+def get_all_allowed_entries() -> list[AllowedEntry]:
+    """
+    Get all access entries that the current user has via Data Access Rules
+    across all databases.
+
+    This function returns entries at all hierarchy levels (database, schema, table),
+    allowing callers to build appropriate filters for their use case.
+
+    Returns:
+        List of AllowedEntry objects representing allowed access.
+    """
+    if not is_feature_enabled("DATA_ACCESS_RULES"):
+        return []
+
+    rules = get_user_rules()
+    if not rules:
+        return []
+
+    allowed_entries: list[AllowedEntry] = []
+
+    for rule in rules:
+        rule_dict = rule.rule_dict
+
+        # Collect all allowed entries
+        for entry in rule_dict.get("allowed", []):
+            database = entry.get("database")
+            if not database:
+                continue
+
+            allowed_entries.append(
+                AllowedEntry(
+                    database=database,
+                    catalog=entry.get("catalog"),
+                    schema=entry.get("schema"),
+                    table=entry.get("table"),
+                )
+            )
+
+    return allowed_entries
+
+
 def get_all_allowed_tables() -> list[AllowedTable]:
     """
     Get all tables that the current user has access to via Data Access Rules
diff --git a/superset/utils/filters.py b/superset/utils/filters.py
index fb90dc7c7d..1058d4b71f 100644
--- a/superset/utils/filters.py
+++ b/superset/utils/filters.py
@@ -22,7 +22,15 @@ from sqlalchemy.sql.elements import BooleanClauseList
 
 
 def get_dar_dataset_filters(base_model: type[Model]) -> list[Any]:
-    """Get SQLAlchemy filters for DAR-allowed tables."""
+    """
+    Get SQLAlchemy filters for DAR-allowed datasets.
+
+    Handles hierarchical permissions:
+    - Database-level: allows all tables in the database
+    - Catalog-level: allows all tables in the catalog
+    - Schema-level: allows all tables in the schema
+    - Table-level: allows only the specific table
+    """
     # pylint: disable=import-outside-toplevel
     import logging
 
@@ -33,28 +41,42 @@ def get_dar_dataset_filters(base_model: type[Model]) -> list[Any]:
         return []
 
     try:
-        from superset.data_access_rules.utils import get_all_allowed_tables
+        from superset.data_access_rules.utils import get_all_allowed_entries
 
-        allowed_tables = get_all_allowed_tables()
-        if not allowed_tables:
+        allowed_entries = get_all_allowed_entries()
+        if not allowed_entries:
             return []
 
-        # Build OR filters for each allowed table
-        table_filters = []
-        for table in allowed_tables:
-            table_filter = and_(
-                Database.database_name == table.database,
-                base_model.table_name == table.table,
-            )
+        # Build OR filters for each allowed entry at its hierarchy level
+        filters = []
+        for entry in allowed_entries:
+            # Start with database filter (always required)
+            entry_filter = Database.database_name == entry.database
+
+            # Add catalog filter if specified
+            if entry.catalog is not None:
+                entry_filter = and_(
+                    entry_filter,
+                    base_model.catalog == entry.catalog,
+                )
+
             # Add schema filter if specified
-            if table.schema:
-                table_filter = and_(
-                    table_filter,
-                    base_model.schema == table.schema,
+            if entry.schema is not None:
+                entry_filter = and_(
+                    entry_filter,
+                    base_model.schema == entry.schema,
                 )
-            table_filters.append(table_filter)
 
-        return table_filters
+            # Add table filter if specified
+            if entry.table is not None:
+                entry_filter = and_(
+                    entry_filter,
+                    base_model.table_name == entry.table,
+                )
+
+            filters.append(entry_filter)
+
+        return filters
     except Exception as ex:
         logging.getLogger(__name__).warning(
             "Error getting DAR dataset filters: %s", ex