-- ============================================================
-- Step 2: register and verify the host-specific ACL.
-- Run as ADMIN.
--
-- Important:
-- Oracle-managed heterogeneous Database Link traffic uses the
-- managed gateway. This ACL records SQL-user host permissions;
-- it does not replace the AWS RDS Security Group rule.
-- Redmine: #730
-- ============================================================

-- DNS resolution privilege must not have a port range.
BEGIN
  DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(
    host => 'database-1.czaaygccsncp.ap-northeast-2.rds.amazonaws.com',
    ace  => XS$ACE_TYPE(
      privilege_list => XS$NAME_LIST('resolve'),
      principal_name => SYS_CONTEXT('USERENV', 'SESSION_USER'),
      principal_type => XS_ACL.PTYPE_DB
    )
  );
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -24243 THEN
      RAISE;
    END IF;
END;
/

-- Permit only the PostgreSQL service port.
BEGIN
  DBMS_NETWORK_ACL_ADMIN.APPEND_HOST_ACE(
    host       => 'database-1.czaaygccsncp.ap-northeast-2.rds.amazonaws.com',
    lower_port => 5432,
    upper_port => 5432,
    ace        => XS$ACE_TYPE(
      privilege_list => XS$NAME_LIST('connect'),
      principal_name => SYS_CONTEXT('USERENV', 'SESSION_USER'),
      principal_type => XS_ACL.PTYPE_DB
    )
  );
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -24243 THEN
      RAISE;
    END IF;
END;
/

SELECT
  host,
  lower_port,
  upper_port,
  principal,
  privilege,
  grant_type
FROM dba_host_aces
WHERE host = 'database-1.czaaygccsncp.ap-northeast-2.rds.amazonaws.com'
  AND principal = USER
  AND privilege IN ('resolve', 'connect')
ORDER BY privilege, lower_port;
