From c9272847c466d4cd9d4c7d13437e3b99137cf4aa Mon Sep 17 00:00:00 2001 From: Amit Langote Date: Thu, 16 Jul 2026 18:17:09 +0900 Subject: [PATCH v1 5/6] Begin RI fast-path index scan under the switched user id ri_FastPathCheck() called index_beginscan() before switching to the referenced relation's owner for the permission check and probe. For btree this has no consequence, but starting the scan before the user id switch sets a poor example for code dealing with out-of-tree access methods, whose beginscan could observe the wrong user id. Move index_beginscan() after the SetUserIdAndSecContext() call. Reported-by: Noah Misch Discussion: https://postgr.es/m/20260705210533.ee.noahmisch@microsoft.com Backpatch-through: 19 --- src/backend/utils/adt/ri_triggers.c | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c index 8805b283995..53b834a42de 100644 --- a/src/backend/utils/adt/ri_triggers.c +++ b/src/backend/utils/adt/ri_triggers.c @@ -2841,10 +2841,6 @@ ri_FastPathCheck(RI_ConstraintInfo *riinfo, idx_rel = index_open(riinfo->conindid, AccessShareLock); slot = table_slot_create(pk_rel, NULL); - scandesc = index_beginscan(pk_rel, idx_rel, - snapshot, NULL, - riinfo->nkeys, 0, - SO_NONE); GetUserIdAndSecContext(&saved_userid, &saved_sec_context); SetUserIdAndSecContext(RelationGetForm(pk_rel)->relowner, @@ -2853,6 +2849,17 @@ ri_FastPathCheck(RI_ConstraintInfo *riinfo, SECURITY_NOFORCE_RLS); ri_CheckPermissions(pk_rel); + /* + * Begin the scan under the switched user id, so that any access method + * code invoked by index_beginscan() runs as the PK relation's owner. For + * btree this has no functional consequence, but it keeps the ordering + * correct for out-of-tree access methods. + */ + scandesc = index_beginscan(pk_rel, idx_rel, + snapshot, NULL, + riinfo->nkeys, 0, + SO_NONE); + if (riinfo->fpmeta == NULL) { /* Reload to ensure it's valid. */ -- 2.47.3