From befae8714d4472133f30bf15f9314188d2c52a46 Mon Sep 17 00:00:00 2001
From: Alexander Kukushkin <cyberdemn@gmail.com>
Date: Wed, 4 Nov 2026 10:40:25 +0100
Subject: [PATCH] Make fmgr_security_definer() setup and teardown symmetric

fmgr_hook saw FHET_START with the function's user and proconfig in
effect but FHET_END after both had been reverted, and the GUC nest level
was opened outside the user switch but closed inside it.  Switch the
user before opening the GUC nest level and call FHET_END before undoing
anything, so setup and teardown are strictly nested as in vacuum_rel()
and similar code.
---
 src/backend/utils/fmgr/fmgr.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/src/backend/utils/fmgr/fmgr.c b/src/backend/utils/fmgr/fmgr.c
index b2fd6dbb73d..6abc47e9c52 100644
--- a/src/backend/utils/fmgr/fmgr.c
+++ b/src/backend/utils/fmgr/fmgr.c
@@ -703,15 +703,15 @@ fmgr_security_definer(PG_FUNCTION_ARGS)
 
 	/* GetUserIdAndSecContext is cheap enough that no harm in a wasted call */
 	GetUserIdAndSecContext(&save_userid, &save_sec_context);
+	if (OidIsValid(fcache->userid))
+		SetUserIdAndSecContext(fcache->userid,
+							   save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
+
 	if (fcache->configNames != NIL) /* Need a new GUC nesting level */
 		save_nestlevel = NewGUCNestLevel();
 	else
 		save_nestlevel = 0;		/* keep compiler quiet */
 
-	if (OidIsValid(fcache->userid))
-		SetUserIdAndSecContext(fcache->userid,
-							   save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
-
 	forthree(lc1, fcache->configNames,
 			 lc2, fcache->configHandles,
 			 lc3, fcache->configValues)
@@ -768,12 +768,12 @@ fmgr_security_definer(PG_FUNCTION_ARGS)
 
 	fcinfo->flinfo = save_flinfo;
 
+	if (fmgr_hook)
+		(*fmgr_hook) (FHET_END, &fcache->flinfo, &fcache->arg);
 	if (fcache->configNames != NIL)
 		AtEOXact_GUC(true, save_nestlevel);
 	if (OidIsValid(fcache->userid))
 		SetUserIdAndSecContext(save_userid, save_sec_context);
-	if (fmgr_hook)
-		(*fmgr_hook) (FHET_END, &fcache->flinfo, &fcache->arg);
 
 	return result;
 }
-- 
2.34.1

