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 02:52:41 UTC

(superset) 01/02: RLS

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

commit b66729ad087a4fe202a266f9be58d8f09bd2cde3
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Wed Dec 17 21:36:04 2025 -0500

    RLS
---
 .../dataAccessRules/PermissionsTree/index.tsx      | 117 ++++++++++++++++++++-
 .../dataAccessRules/PermissionsTree/types.ts       |  12 ++-
 .../dataAccessRules/PermissionsTree/utils.ts       |  64 +++++++++--
 3 files changed, 183 insertions(+), 10 deletions(-)

diff --git a/superset-frontend/src/features/dataAccessRules/PermissionsTree/index.tsx b/superset-frontend/src/features/dataAccessRules/PermissionsTree/index.tsx
index 39e1f71cf7..4853977da9 100644
--- a/superset-frontend/src/features/dataAccessRules/PermissionsTree/index.tsx
+++ b/superset-frontend/src/features/dataAccessRules/PermissionsTree/index.tsx
@@ -20,7 +20,7 @@
 import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
 import { t } from '@superset-ui/core';
 import { css, styled } from '@apache-superset/core/ui';
-import { Tree, Tooltip, Spin, Button, Select } from 'antd';
+import { Tree, Tooltip, Spin, Button, Select, Input } from 'antd';
 import {
   CheckCircleOutlined,
   CloseCircleOutlined,
@@ -36,6 +36,7 @@ import type {
   TreeState,
   PermissionsPayload,
   CLSAction,
+  RLSRule,
 } from './types';
 import {
   fetchDatabases,
@@ -136,6 +137,33 @@ const StyledContainer = styled.div`
       font-size: 11px;
       color: ${theme.colorTextSecondary};
     }
+
+    .rls-container {
+      display: flex;
+      flex-direction: column;
+      gap: ${theme.sizeUnit}px;
+      padding: ${theme.sizeUnit}px 0;
+      margin-bottom: ${theme.sizeUnit}px;
+      border-bottom: 1px dashed ${theme.colorBorder};
+    }
+
+    .rls-row {
+      display: flex;
+      align-items: center;
+      gap: ${theme.sizeUnit}px;
+    }
+
+    .rls-label {
+      font-size: 11px;
+      color: ${theme.colorTextSecondary};
+      min-width: 70px;
+    }
+
+    .rls-input {
+      flex: 1;
+      max-width: 250px;
+      font-size: 12px;
+    }
   `}
 `;
 
@@ -156,6 +184,7 @@ function PermissionsTree({
     treeData: [],
     permissionStates: {},
     clsRules: {},
+    rlsRules: {},
   });
   const [loading, setLoading] = useState(false);
   const [databases, setDatabases] = useState<DatabaseInfo[]>([]);
@@ -186,7 +215,7 @@ function PermissionsTree({
       return;
     }
     if (value && databaseMaps.nameToId.size > 0) {
-      const { states, clsRules } = loadPermissionsFromPayload(
+      const { states, clsRules, rlsRules } = loadPermissionsFromPayload(
         value,
         databaseMaps.nameToId,
       );
@@ -194,6 +223,7 @@ function PermissionsTree({
         ...prev,
         permissionStates: states,
         clsRules,
+        rlsRules,
       }));
     }
   }, [value, databaseMaps.nameToId]);
@@ -409,11 +439,50 @@ function PermissionsTree({
         newStates,
         databaseMaps.idToName,
         treeState.clsRules,
+        treeState.rlsRules,
       );
       onChange(payload);
     }
   };
 
+  const handleRlsChange = (
+    tableKey: string,
+    field: 'predicate' | 'groupKey',
+    value: string,
+  ) => {
+    // Mark as internal update to prevent circular updates
+    isInternalUpdateRef.current = true;
+
+    setTreeState(prev => {
+      const currentRls = prev.rlsRules[tableKey] || { predicate: '' };
+      const newRls: RLSRule = { ...currentRls, [field]: value };
+
+      // Remove the rule if both fields are empty
+      const newRlsRules = { ...prev.rlsRules };
+      if (!newRls.predicate && !newRls.groupKey) {
+        delete newRlsRules[tableKey];
+      } else {
+        newRlsRules[tableKey] = newRls;
+      }
+
+      // Notify parent of changes
+      if (onChange && databaseMaps.idToName.size > 0) {
+        const payload = generatePermissionsPayload(
+          prev.permissionStates,
+          databaseMaps.idToName,
+          prev.clsRules,
+          newRlsRules,
+        );
+        onChange(payload);
+      }
+
+      return {
+        ...prev,
+        rlsRules: newRlsRules,
+      };
+    });
+  };
+
   const handleClsChange = (
     tableKey: string,
     columnName: string,
@@ -438,6 +507,7 @@ function PermissionsTree({
           prev.permissionStates,
           databaseMaps.idToName,
           newClsRules,
+          prev.rlsRules,
         );
         onChange(payload);
       }
@@ -554,6 +624,48 @@ function PermissionsTree({
       );
     }
 
+    // Table nodes get RLS inputs when expanded
+    if (node.nodeType === 'table' && isExpanded) {
+      const currentRls = treeState.rlsRules[nodeKey] || {
+        predicate: '',
+        groupKey: '',
+      };
+
+      return (
+        <div>
+          <div className="node-title">
+            {getStateIcon(nodeKey)}
+            {getNodeIcon(node.nodeType)}
+            <span>{title}</span>
+          </div>
+          <div className="rls-container">
+            <div className="rls-row">
+              <span className="rls-label">{t('RLS Predicate')}</span>
+              <Input
+                className="rls-input"
+                size="small"
+                placeholder={t('e.g., org_id = {{current_user_id}}')}
+                value={currentRls.predicate}
+                onChange={e => handleRlsChange(nodeKey, 'predicate', e.target.value)}
+                onClick={e => e.stopPropagation()}
+              />
+            </div>
+            <div className="rls-row">
+              <span className="rls-label">{t('Group Key')}</span>
+              <Input
+                className="rls-input"
+                size="small"
+                placeholder={t('Optional grouping key')}
+                value={currentRls.groupKey || ''}
+                onChange={e => handleRlsChange(nodeKey, 'groupKey', e.target.value)}
+                onClick={e => e.stopPropagation()}
+              />
+            </div>
+          </div>
+        </div>
+      );
+    }
+
     // Non-column nodes: check if leaf (columns are leafs, tables are not anymore)
     const isLeaf = node.nodeType === 'column';
 
@@ -597,6 +709,7 @@ function PermissionsTree({
       ...prev,
       permissionStates: {},
       clsRules: {},
+      rlsRules: {},
     }));
     if (onChange) {
       onChange({ allowed: [], denied: [] });
diff --git a/superset-frontend/src/features/dataAccessRules/PermissionsTree/types.ts b/superset-frontend/src/features/dataAccessRules/PermissionsTree/types.ts
index b77751dfae..23d1b32802 100644
--- a/superset-frontend/src/features/dataAccessRules/PermissionsTree/types.ts
+++ b/superset-frontend/src/features/dataAccessRules/PermissionsTree/types.ts
@@ -41,12 +41,18 @@ export interface PermissionNode extends DataNode {
   totalCount?: number;
 }
 
+export interface RLSRule {
+  predicate: string;
+  groupKey?: string;
+}
+
 export interface TreeState {
   expandedKeys: string[];
   loadedKeys: string[];
   treeData: PermissionNode[];
   permissionStates: Record<string, PermissionState>;
-  clsRules: Record<string, CLSAction>; // key format: "tableKey:columnName" -> action
+  clsRules: Record<string, CLSAction>; // key format: "tableKey::columnName" -> action
+  rlsRules: Record<string, RLSRule>; // key format: tableKey -> RLSRule
 }
 
 export interface PermissionsPayload {
@@ -59,5 +65,9 @@ export interface PermissionEntry {
   catalog?: string;
   schema?: string;
   table?: string;
+  rls?: {
+    predicate: string;
+    group_key?: string;
+  };
   cls?: Record<string, string>; // column name -> action
 }
diff --git a/superset-frontend/src/features/dataAccessRules/PermissionsTree/utils.ts b/superset-frontend/src/features/dataAccessRules/PermissionsTree/utils.ts
index ab2636e733..ede38799a5 100644
--- a/superset-frontend/src/features/dataAccessRules/PermissionsTree/utils.ts
+++ b/superset-frontend/src/features/dataAccessRules/PermissionsTree/utils.ts
@@ -24,6 +24,7 @@ import type {
   PermissionEntry,
   NodeType,
   CLSAction,
+  RLSRule,
 } from './types';
 
 // Key format: db:{id}|cat:{name}|schema:{name}|table:{name}
@@ -337,6 +338,7 @@ export function generatePermissionsPayload(
   permissionStates: Record<string, PermissionState>,
   databases: Map<number, string>,
   clsRules: Record<string, CLSAction> = {},
+  rlsRules: Record<string, RLSRule> = {},
 ): PermissionsPayload {
   const allowed: PermissionEntry[] = [];
   const denied: PermissionEntry[] = [];
@@ -369,6 +371,19 @@ export function generatePermissionsPayload(
     if (parsed.schemaName) entry.schema = parsed.schemaName;
     if (parsed.tableName) entry.table = parsed.tableName;
 
+    // Add RLS rules if this is a table entry and has RLS rules
+    if (parsed.tableName && rlsRules[key]) {
+      const rls = rlsRules[key];
+      if (rls.predicate) {
+        entry.rls = {
+          predicate: rls.predicate,
+        };
+        if (rls.groupKey) {
+          entry.rls.group_key = rls.groupKey;
+        }
+      }
+    }
+
     // Add CLS rules if this is a table entry and has CLS rules
     if (parsed.tableName && clsByTable[key]) {
       entry.cls = clsByTable[key];
@@ -381,9 +396,14 @@ export function generatePermissionsPayload(
     }
   });
 
-  // Also add CLS rules for tables that don't have explicit permission states
-  // but do have CLS rules (they inherit permission from parent)
-  Object.entries(clsByTable).forEach(([tableKey, columnRules]) => {
+  // Also add RLS/CLS rules for tables that don't have explicit permission states
+  // but do have RLS or CLS rules (they inherit permission from parent)
+  const tablesWithRules = new Set([
+    ...Object.keys(clsByTable),
+    ...Object.keys(rlsRules),
+  ]);
+
+  tablesWithRules.forEach(tableKey => {
     // Check if we already added this table
     const parsed = parseKey(tableKey);
     const databaseName = databases.get(parsed.databaseId);
@@ -398,17 +418,34 @@ export function generatePermissionsPayload(
         entry.table === parsed.tableName,
     );
 
-    if (!alreadyInAllowed && Object.keys(columnRules).length > 0) {
+    const hasClsRules =
+      clsByTable[tableKey] && Object.keys(clsByTable[tableKey]).length > 0;
+    const hasRlsRules =
+      rlsRules[tableKey] && rlsRules[tableKey].predicate;
+
+    if (!alreadyInAllowed && (hasClsRules || hasRlsRules)) {
       // Check if the table has effective allow state (inherited)
       const effectiveState = getEffectiveState(tableKey, permissionStates);
       if (effectiveState === 'allow') {
         const entry: PermissionEntry = {
           database: databaseName,
           table: parsed.tableName,
-          cls: columnRules,
         };
         if (parsed.catalogName) entry.catalog = parsed.catalogName;
         if (parsed.schemaName) entry.schema = parsed.schemaName;
+
+        if (hasRlsRules) {
+          const rls = rlsRules[tableKey];
+          entry.rls = { predicate: rls.predicate };
+          if (rls.groupKey) {
+            entry.rls.group_key = rls.groupKey;
+          }
+        }
+
+        if (hasClsRules) {
+          entry.cls = clsByTable[tableKey];
+        }
+
         allowed.push(entry);
       }
     }
@@ -457,9 +494,14 @@ function cleanupStates(
 export function loadPermissionsFromPayload(
   payload: PermissionsPayload,
   databases: Map<string, number>,
-): { states: Record<string, PermissionState>; clsRules: Record<string, CLSAction> } {
+): {
+  states: Record<string, PermissionState>;
+  clsRules: Record<string, CLSAction>;
+  rlsRules: Record<string, RLSRule>;
+} {
   const states: Record<string, PermissionState> = {};
   const clsRules: Record<string, CLSAction> = {};
+  const rlsRules: Record<string, RLSRule> = {};
 
   payload.allowed.forEach(entry => {
     const databaseId = databases.get(entry.database);
@@ -473,6 +515,14 @@ export function loadPermissionsFromPayload(
     });
     states[key] = 'allow';
 
+    // Load RLS rules if present
+    if (entry.rls && entry.table) {
+      rlsRules[key] = {
+        predicate: entry.rls.predicate,
+        groupKey: entry.rls.group_key,
+      };
+    }
+
     // Load CLS rules if present
     if (entry.cls && entry.table) {
       Object.entries(entry.cls).forEach(([columnName, action]) => {
@@ -495,5 +545,5 @@ export function loadPermissionsFromPayload(
     states[key] = 'deny';
   });
 
-  return { states, clsRules };
+  return { states, clsRules, rlsRules };
 }