From a142adc318d9ca423b4c8f98502c1aa0a60cb8f7 Mon Sep 17 00:00:00 2001
From: Japin Li <japinli@hotmail.com>
Date: Thu, 31 Jul 2025 16:09:13 +0800
Subject: [PATCH] Restore security context for add_reindex_index_hook

---
 contrib/vci/expected/bugs.out | 7 +++++++
 contrib/vci/sql/bugs.sql      | 9 +++++++++
 src/backend/catalog/index.c   | 6 ++++++
 3 files changed, 22 insertions(+)

diff --git a/contrib/vci/expected/bugs.out b/contrib/vci/expected/bugs.out
index a32ea0ef983..4ebbde8a80f 100644
--- a/contrib/vci/expected/bugs.out
+++ b/contrib/vci/expected/bugs.out
@@ -66,3 +66,10 @@ SELECT relname FROM pg_class WHERE relname ~ '^vci_*';
 ---------
 (0 rows)
 
+-- Bug reported by Japin Li that forgot to restore security context
+-- See https://www.postgresql.org/message-id/ME0P300MB0445827B6E9CC04E0FAEE446B624A%40ME0P300MB0445.AUSP300.PROD.OUTLOOK.COM
+CREATE TABLE t5 (id int, info text);
+CREATE INDEX t5_idx ON t5 USING vci (id);
+REINDEX TABLE t5;
+REINDEX TABLE t5;
+DROP TABLE t5;
diff --git a/contrib/vci/sql/bugs.sql b/contrib/vci/sql/bugs.sql
index 2675f514c21..54d9c321cac 100644
--- a/contrib/vci/sql/bugs.sql
+++ b/contrib/vci/sql/bugs.sql
@@ -36,3 +36,12 @@ CREATE INDEX t4_idx ON t4 USING vci (id);
 SELECT relname FROM pg_class WHERE relname ~ '^vci_*' ORDER BY relname;
 DROP TABLE t4;
 SELECT relname FROM pg_class WHERE relname ~ '^vci_*';
+
+-- Bug reported by Japin Li that forgot to restore security context
+-- See https://www.postgresql.org/message-id/ME0P300MB0445827B6E9CC04E0FAEE446B624A%40ME0P300MB0445.AUSP300.PROD.OUTLOOK.COM
+
+CREATE TABLE t5 (id int, info text);
+CREATE INDEX t5_idx ON t5 USING vci (id);
+REINDEX TABLE t5;
+REINDEX TABLE t5;
+DROP TABLE t5;
diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
index dd67530fdf5..fedbece872a 100644
--- a/src/backend/catalog/index.c
+++ b/src/backend/catalog/index.c
@@ -3704,6 +3704,12 @@ reindex_index(const ReindexStmt *stmt, Oid indexId,
 		{
 			RemoveReindexPending(RelationGetRelid(iRel));
 
+			/* Roll back any GUC changes */
+			AtEOXact_GUC(false, save_nestlevel);
+
+			/* Restore userid and security context */
+			SetUserIdAndSecContext(save_userid, save_sec_context);
+
 			/* Close rels, but keep locks */
 			index_close(iRel, NoLock);
 			table_close(heapRelation, NoLock);
-- 
2.43.0

