From 88ea675233f3078c77740ca3ef2493d11381c3d9 Mon Sep 17 00:00:00 2001
From: Soumya <soumyamurali.work@gmail.com>
Date: Wed, 8 Apr 2026 12:47:45 +0530
Subject: [PATCH] prevent access to other sessions' temporary tables

Signed-off-by: Soumya <soumyamurali.work@gmail.com>
---
 src/backend/storage/buffer/bufmgr.c | 32 +++++++++++++++++++++--------
 1 file changed, 24 insertions(+), 8 deletions(-)

diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 3cc0b0bdd92..ec72fa97ea6 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -791,11 +791,16 @@ PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
 
 	if (RelationUsesLocalBuffers(reln))
 	{
-		/* see comments in ReadBufferExtended */
-		if (RELATION_IS_OTHER_TEMP(reln))
-			ereport(ERROR,
-					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
-					 errmsg("cannot access temporary tables of other sessions")));
+		/* ACCESS DENIED CHECK */
+		if (reln != NULL &&
+    		reln->rd_rel != NULL &&
+    		reln->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
+    		!RelationUsesLocalBuffers(reln))
+		{
+    		ereport(ERROR,
+            		(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+             		errmsg("cannot access temporary tables of other sessions")));
+		}
 
 		/* pass it off to localbuf.c */
 		return PrefetchLocalBuffer(RelationGetSmgr(reln), forkNum, blockNum);
@@ -933,7 +938,8 @@ ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
 	 * likely to get wrong data since we have no visibility into the owning
 	 * session's local buffers.
 	 */
-	if (RELATION_IS_OTHER_TEMP(reln))
+	if (reln->rd_rel->relpersistence == RELPERSISTENCE_TEMP &&
+    !RelationUsesLocalBuffers(reln))
 		ereport(ERROR,
 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
 				 errmsg("cannot access temporary tables of other sessions")));
@@ -1313,9 +1319,19 @@ ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
 	}
 
 	if (rel)
-		persistence = rel->rd_rel->relpersistence;
+    	persistence = rel->rd_rel->relpersistence;
 	else
-		persistence = smgr_persistence;
+    	persistence = smgr_persistence;
+
+	/* ACCESS DENIED */
+	if (rel != NULL &&
+    	persistence == RELPERSISTENCE_TEMP &&
+    !	RelationUsesLocalBuffers(rel))
+	{
+    	ereport(ERROR,
+            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+            errmsg("cannot access temporary tables of other sessions")));
+	}	
 
 	if (unlikely(mode == RBM_ZERO_AND_CLEANUP_LOCK ||
 				 mode == RBM_ZERO_AND_LOCK))
-- 
2.34.1

