-- ============================================================
-- 24_agent_ords_security_inventory.sql
-- Central security inventory for Agent ORDS security.
--
-- Run as ADMIN after VPD, DDS, and ORDS handler setup.
-- ============================================================
WHENEVER SQLERROR CONTINUE
SET ECHO OFF
SET FEEDBACK ON
SET LINESIZE 260
SET PAGESIZE 200

COLUMN object_owner FORMAT A12
COLUMN object_name FORMAT A32
COLUMN policy_name FORMAT A26
COLUMN pf_owner FORMAT A12
COLUMN function FORMAT A30
COLUMN sel FORMAT A5
COLUMN ins FORMAT A5
COLUMN upd FORMAT A5
COLUMN del FORMAT A5
COLUMN enable FORMAT A8
COLUMN expression FORMAT A70 WORD_WRAPPED
COLUMN grant_name FORMAT A24
COLUMN grantee FORMAT A28
COLUMN privilege FORMAT A10
COLUMN allowed_columns FORMAT A76 WORD_WRAPPED
COLUMN excluded_columns FORMAT A22
COLUMN predicate FORMAT A28
COLUMN end_user_name FORMAT A26
COLUMN data_role FORMAT A28

PROMPT
PROMPT === Inventory 1. VPD policies attached to protected objects ===
SELECT object_owner,
       object_name,
       policy_name,
       pf_owner,
       function,
       sel,
       ins,
       upd,
       del,
       enable
FROM   dba_policies
WHERE  object_owner = 'ADMIN'
AND    object_name LIKE 'CB%'
ORDER  BY object_name, policy_name;

PROMPT
PROMPT === Inventory 2. Redaction policies attached to protected objects ===
SELECT object_owner,
       object_name,
       policy_name,
       enable,
       expression
FROM   redaction_policies
WHERE  object_owner = 'ADMIN'
AND    object_name LIKE 'CB%'
ORDER  BY object_name, policy_name;

PROMPT
PROMPT === Inventory 3. DDS grant summary, one row per DATA GRANT ===
SELECT grant_name,
       object_name,
       grantee,
       privilege,
       COALESCE(
         LISTAGG(column_name, ', ') WITHIN GROUP (ORDER BY column_name),
         'ALL COLUMNS'
       ) AS allowed_columns,
       COALESCE(MAX(granted_with_all_columns_except), '-') AS excluded_columns,
       predicate
FROM   dba_data_grants
WHERE  owner = 'ADMIN'
AND    object_name LIKE 'CB%'
GROUP  BY grant_name, object_name, grantee, privilege, predicate
ORDER  BY object_name, grant_name;

PROMPT
PROMPT === Inventory 4. DDS end user -> data role -> data grant matrix ===
SELECT rg.grantee AS end_user_name,
       rg.data_role,
       dg.grant_name,
       dg.object_name,
       dg.predicate,
       COALESCE(MAX(dg.granted_with_all_columns_except), '-') AS excluded_columns
FROM   dba_data_role_grants rg
LEFT   JOIN dba_data_grants dg
ON     dg.grantee = rg.data_role
WHERE  rg.grantee LIKE 'cb\_dds\_%' ESCAPE '\'
GROUP  BY rg.grantee,
          rg.data_role,
          dg.grant_name,
          dg.object_name,
          dg.predicate
ORDER  BY rg.grantee, dg.object_name, dg.grant_name;

EXIT;
