-- ============================================================
-- 42_agent_ords_fga_execution_audit.sql
-- Durable, request-correlated execution evidence for VPD probes.
--
-- Run as the protected-object owner (ADMIN in this PoC), after the
-- VPD policies and CB_PROTECTED_OBJECT entries have been applied.
--
-- Each enabled protected object gets an FGA SELECT policy. Autonomous Oracle
-- writes SQL_TEXT and RLS_INFO to UNIFIED_AUDIT_TRAIL (traditional databases
-- can expose the same information through DBA_FGA_AUDIT_TRAIL). The ORDS handler puts the
-- backoffice-generated X-VPD-Probe-Id into CLIENT_ID, so the UI can read
-- exactly this request's audit row rather than guess from V$SQL.
-- ============================================================
WHENEVER SQLERROR EXIT SQL.SQLCODE
SET ECHO ON
SET FEEDBACK ON

PROMPT === Applying FGA execution-audit policies ===
DECLARE
  v_policy_name VARCHAR2(128);
BEGIN
  FOR r IN (
    SELECT object_id, owner, object_name
    FROM   cb_protected_object
    WHERE  enabled_yn = 'Y'
    ORDER  BY object_id
  ) LOOP
    IF UPPER(r.owner) <> USER THEN
      RAISE_APPLICATION_ERROR(
        -20842,
        'Run this script as protected object owner ' || r.owner
          || ' (current user: ' || USER || ')'
      );
    END IF;

    v_policy_name := 'CB_VPD_EXEC_AUDIT_' || r.object_id;
    BEGIN
      DBMS_FGA.DROP_POLICY(
        object_schema => r.owner,
        object_name   => r.object_name,
        policy_name   => v_policy_name
      );
    EXCEPTION
      WHEN OTHERS THEN
        -- ORA-28102: policy does not exist. Other errors must stop setup.
        IF SQLCODE <> -28102 THEN
          RAISE;
        END IF;
    END;

    DBMS_FGA.ADD_POLICY(
      object_schema   => r.owner,
      object_name     => r.object_name,
      policy_name     => v_policy_name,
      audit_condition => NULL,
      audit_column    => NULL,
      statement_types => 'SELECT',
      audit_trail     => DBMS_FGA.DB + DBMS_FGA.EXTENDED,
      enable          => TRUE
    );
  END LOOP;
END;
/

COMMIT;

PROMPT === FGA policies are ready ===
PROMPT Run 22, 29 and 43 as CB_ORDS, then run a new permission-result probe.
PROMPT The resulting row is read from UNIFIED_AUDIT_TRAIL by CLIENT_IDENTIFIER.
EXIT;
